]> code.citadel.org Git - citadel.git/blob - citadel/serv_network.c
*** empty log message ***
[citadel.git] / citadel / serv_network.c
1 /*
2  * $Id$ 
3  *
4  * This module handles shared rooms, inter-Citadel mail, and outbound
5  * mailing list processing.
6  *
7  * Copyright (C) 2000-2002 by Art Cancro and others.
8  * This code is released under the terms of the GNU General Public License.
9  *
10  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
11  * This is a fairly high-level type of critical section.  It ensures that no
12  * two threads work on the netconfigs files at the same time.  Since we do
13  * so many things inside these, here are the rules:
14  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
15  *  2. Do *not* perform any I/O with the client during these sections.
16  *
17  */
18
19 /*
20  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
21  * requests that have not been confirmed will be deleted.
22  */
23 #define EXP     259200  /* three days */
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <dirent.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
38 # include <time.h>
39 #else
40 # if HAVE_SYS_TIME_H
41 #  include <sys/time.h>
42 # else
43 #  include <time.h>
44 # endif
45 #endif
46
47 #include <sys/wait.h>
48 #include <string.h>
49 #include <limits.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "serv_extensions.h"
57 #include "room_ops.h"
58 #include "user_ops.h"
59 #include "policy.h"
60 #include "database.h"
61 #include "msgbase.h"
62 #include "tools.h"
63 #include "internet_addressing.h"
64 #include "serv_network.h"
65 #include "clientsocket.h"
66 #include "file_ops.h"
67
68 #ifndef HAVE_SNPRINTF
69 #include "snprintf.h"
70 #endif
71
72 /* Nonzero while we are doing outbound network processing */
73 static int doing_queue = 0;
74
75 /*
76  * When we do network processing, it's accomplished in two passes; one to
77  * gather a list of rooms and one to actually do them.  It's ok that rplist
78  * is global; this process *only* runs as part of the housekeeping loop and
79  * therefore only one will run at a time.
80  */
81 struct RoomProcList *rplist = NULL;
82
83 /*
84  * We build a map of network nodes during processing.
85  */
86 struct NetMap *the_netmap = NULL;
87
88 char *ignetcfg = NULL;
89
90 char *working_ignetcfg = NULL;
91
92 /*
93  * Keep track of what messages to reject
94  */
95 struct FilterList *load_filter_list(void) {
96         char *serialized_list = NULL;
97         int i;
98         char buf[SIZ];
99         struct FilterList *newlist = NULL;
100         struct FilterList *nptr;
101
102         serialized_list = CtdlGetSysConfig(FILTERLIST);
103         if (serialized_list == NULL) return(NULL); /* if null, no entries */
104
105         /* Use the string tokenizer to grab one line at a time */
106         for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
107                 extract_token(buf, serialized_list, i, '\n');
108                 nptr = (struct FilterList *) malloc(sizeof(struct FilterList));
109                 extract(nptr->fl_user, buf, 0);
110                 striplt(nptr->fl_user);
111                 extract(nptr->fl_room, buf, 1);
112                 striplt(nptr->fl_room);
113                 extract(nptr->fl_node, buf, 2);
114                 striplt(nptr->fl_node);
115
116                 /* Cowardly refuse to add an any/any/any entry that would
117                  * end up filtering every single message.
118                  */
119                 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
120                    + strlen(nptr->fl_node) == 0) {
121                         free(nptr);
122                 }
123                 else {
124                         nptr->next = newlist;
125                         newlist = nptr;
126                 }
127         }
128
129         free(serialized_list);
130         return newlist;
131 }
132
133
134 void free_filter_list(struct FilterList *fl) {
135         if (fl == NULL) return;
136         free_filter_list(fl->next);
137         free(fl);
138 }
139
140
141
142 /*
143  * Check the use table.  This is a list of messages which have recently
144  * arrived on the system.  It is maintained and queried to prevent the same
145  * message from being entered into the database multiple times if it happens
146  * to arrive multiple times by accident.
147  */
148 int network_usetable(struct CtdlMessage *msg) {
149
150         char msgid[SIZ];
151         struct cdbdata *cdbut;
152         struct UseTable ut;
153
154         /* Bail out if we can't generate a message ID */
155         if (msg == NULL) {
156                 return(0);
157         }
158         if (msg->cm_fields['I'] == NULL) {
159                 return(0);
160         }
161         if (strlen(msg->cm_fields['I']) == 0) {
162                 return(0);
163         }
164
165         /* Generate the message ID */
166         strcpy(msgid, msg->cm_fields['I']);
167         if (haschar(msgid, '@') == 0) {
168                 strcat(msgid, "@");
169                 if (msg->cm_fields['N'] != NULL) {
170                         strcat(msgid, msg->cm_fields['N']);
171                 }
172                 else {
173                         return(0);
174                 }
175         }
176
177         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
178         if (cdbut != NULL) {
179                 cdb_free(cdbut);
180                 return(1);
181         }
182
183         /* If we got to this point, it's unique: add it. */
184         strcpy(ut.ut_msgid, msgid);
185         ut.ut_timestamp = time(NULL);
186         cdb_store(CDB_USETABLE, msgid, strlen(msgid),
187                 &ut, sizeof(struct UseTable) );
188         return(0);
189 }
190
191
192 /* 
193  * Read the network map from its configuration file into memory.
194  */
195 void read_network_map(void) {
196         char *serialized_map = NULL;
197         int i;
198         char buf[SIZ];
199         struct NetMap *nmptr;
200
201         serialized_map = CtdlGetSysConfig(IGNETMAP);
202         if (serialized_map == NULL) return;     /* if null, no entries */
203
204         /* Use the string tokenizer to grab one line at a time */
205         for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
206                 extract_token(buf, serialized_map, i, '\n');
207                 nmptr = (struct NetMap *) malloc(sizeof(struct NetMap));
208                 extract(nmptr->nodename, buf, 0);
209                 nmptr->lastcontact = extract_long(buf, 1);
210                 extract(nmptr->nexthop, buf, 2);
211                 nmptr->next = the_netmap;
212                 the_netmap = nmptr;
213         }
214
215         free(serialized_map);
216 }
217
218
219 /*
220  * Write the network map from memory back to the configuration file.
221  */
222 void write_network_map(void) {
223         char *serialized_map = NULL;
224         struct NetMap *nmptr;
225
226         serialized_map = strdup("");
227
228         if (the_netmap != NULL) {
229                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
230                         serialized_map = realloc(serialized_map,
231                                                 (strlen(serialized_map)+SIZ) );
232                         if (strlen(nmptr->nodename) > 0) {
233                                 snprintf(&serialized_map[strlen(serialized_map)],
234                                         SIZ,
235                                         "%s|%ld|%s\n",
236                                         nmptr->nodename,
237                                         (long)nmptr->lastcontact,
238                                         nmptr->nexthop);
239                         }
240                 }
241         }
242
243         CtdlPutSysConfig(IGNETMAP, serialized_map);
244         free(serialized_map);
245
246         /* Now free the list */
247         while (the_netmap != NULL) {
248                 nmptr = the_netmap->next;
249                 free(the_netmap);
250                 the_netmap = nmptr;
251         }
252 }
253
254
255
256 /* 
257  * Check the network map and determine whether the supplied node name is
258  * valid.  If it is not a neighbor node, supply the name of a neighbor node
259  * which is the next hop.  If it *is* a neighbor node, we also fill in the
260  * shared secret.
261  */
262 int is_valid_node(char *nexthop, char *secret, char *node) {
263         int i;
264         char linebuf[SIZ];
265         char buf[SIZ];
266         int retval;
267         struct NetMap *nmptr;
268
269         if (node == NULL) {
270                 return(-1);
271         }
272
273         /*
274          * First try the neighbor nodes
275          */
276         if (working_ignetcfg == NULL) {
277                 if (nexthop != NULL) {
278                         strcpy(nexthop, "");
279                 }
280                 return(-1);
281         }
282
283         retval = (-1);
284         if (nexthop != NULL) {
285                 strcpy(nexthop, "");
286         }
287
288         /* Use the string tokenizer to grab one line at a time */
289         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
290                 extract_token(linebuf, working_ignetcfg, i, '\n');
291                 extract(buf, linebuf, 0);
292                 if (!strcasecmp(buf, node)) {
293                         if (nexthop != NULL) {
294                                 strcpy(nexthop, "");
295                         }
296                         if (secret != NULL) {
297                                 extract(secret, linebuf, 1);
298                         }
299                         retval = 0;
300                 }
301         }
302
303         if (retval == 0) {
304                 return(retval);         /* yup, it's a direct neighbor */
305         }
306
307         /*      
308          * If we get to this point we have to see if we know the next hop
309          */
310         if (the_netmap != NULL) {
311                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
312                         if (!strcasecmp(nmptr->nodename, node)) {
313                                 if (nexthop != NULL) {
314                                         strcpy(nexthop, nmptr->nexthop);
315                                 }
316                                 return(0);
317                         }
318                 }
319         }
320
321         /*
322          * If we get to this point, the supplied node name is bogus.
323          */
324         lprintf(CTDL_ERR, "Invalid node name <%s>\n", node);
325         return(-1);
326 }
327
328
329
330
331
332 void cmd_gnet(char *argbuf) {
333         char filename[SIZ];
334         char buf[SIZ];
335         FILE *fp;
336
337         if (CtdlAccessCheck(ac_room_aide)) return;
338         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
339         cprintf("%d Network settings for room #%ld <%s>\n",
340                 LISTING_FOLLOWS,
341                 CC->room.QRnumber, CC->room.QRname);
342
343         fp = fopen(filename, "r");
344         if (fp != NULL) {
345                 while (fgets(buf, sizeof buf, fp) != NULL) {
346                         buf[strlen(buf)-1] = 0;
347                         cprintf("%s\n", buf);
348                 }
349                 fclose(fp);
350         }
351
352         cprintf("000\n");
353 }
354
355
356 void cmd_snet(char *argbuf) {
357         char tempfilename[SIZ];
358         char filename[SIZ];
359         char buf[SIZ];
360         FILE *fp;
361
362         if (CtdlAccessCheck(ac_room_aide)) return;
363         safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
364         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
365
366         fp = fopen(tempfilename, "w");
367         if (fp == NULL) {
368                 cprintf("%d Cannot open %s: %s\n",
369                         ERROR + INTERNAL_ERROR,
370                         tempfilename,
371                         strerror(errno));
372         }
373
374         cprintf("%d %s\n", SEND_LISTING, tempfilename);
375         while (client_gets(buf), strcmp(buf, "000")) {
376                 fprintf(fp, "%s\n", buf);
377         }
378         fclose(fp);
379
380         /* Now copy the temp file to its permanent location
381          * (We use /bin/mv instead of link() because they may be on
382          * different filesystems)
383          */
384         unlink(filename);
385         snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
386         begin_critical_section(S_NETCONFIGS);
387         system(buf);
388         end_critical_section(S_NETCONFIGS);
389 }
390
391
392 /*
393  * Spools out one message from the list.
394  */
395 void network_spool_msg(long msgnum, void *userdata) {
396         struct SpoolControl *sc;
397         int err;
398         int i;
399         char *newpath = NULL;
400         char *instr = NULL;
401         size_t instr_len = SIZ;
402         struct CtdlMessage *msg = NULL;
403         struct CtdlMessage *imsg;
404         struct namelist *nptr;
405         struct ser_ret sermsg;
406         FILE *fp;
407         char filename[SIZ];
408         char buf[SIZ];
409         int bang = 0;
410         int send = 1;
411         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
412
413         sc = (struct SpoolControl *)userdata;
414
415         /*
416          * Process mailing list recipients
417          */
418         if (sc->listrecps != NULL) {
419         
420                 /* First, copy it to the spoolout room */
421                 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
422                 if (err != 0) return;
423
424                 /* 
425                  * Figure out how big a buffer we need to allocate
426                  */
427                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
428                         instr_len = instr_len + strlen(nptr->name);
429                 }
430         
431                 /*
432                  * allocate...
433                  */
434                 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
435                 instr = malloc(instr_len);
436                 if (instr == NULL) {
437                         lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
438                                 (long)instr_len);
439                         abort();
440                 }
441                 snprintf(instr, instr_len,
442                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
443                         "bounceto|postmaster@%s\n" ,
444                         SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
445         
446                 /* Generate delivery instructions for each recipient */
447                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
448                         size_t tmp = strlen(instr);
449                         snprintf(&instr[tmp], instr_len - tmp,
450                                  "remote|%s|0||\n", nptr->name);
451                 }
452         
453                 /*
454                  * Generate a message from the instructions
455                  */
456                 imsg = malloc(sizeof(struct CtdlMessage));
457                 memset(imsg, 0, sizeof(struct CtdlMessage));
458                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
459                 imsg->cm_anon_type = MES_NORMAL;
460                 imsg->cm_format_type = FMT_RFC822;
461                 imsg->cm_fields['A'] = strdup("Citadel");
462                 imsg->cm_fields['M'] = instr;
463         
464                 /* Save delivery instructions in spoolout room */
465                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
466                 CtdlFreeMessage(imsg);
467         }
468
469         /*
470          * Process digest recipients
471          */
472         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
473                 fprintf(sc->digestfp,   " -----------------------------------"
474                                         "------------------------------------"
475                                         "-------\n");
476                 CtdlRedirectOutput(sc->digestfp, -1);
477                 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
478                 CtdlRedirectOutput(NULL, -1);
479                 sc->num_msgs_spooled += 1;
480         }
481         
482         /*
483          * Process IGnet push shares
484          */
485         if (sc->ignet_push_shares != NULL) {
486         
487                 msg = CtdlFetchMessage(msgnum, 1);
488                 if (msg != NULL) {
489                         size_t newpath_len;
490
491                         /* Prepend our node name to the Path field whenever
492                          * sending a message to another IGnet node
493                          */
494                         if (msg->cm_fields['P'] == NULL) {
495                                 msg->cm_fields['P'] = strdup("username");
496                         }
497                         newpath_len = strlen(msg->cm_fields['P']) +
498                                  strlen(config.c_nodename) + 2;
499                         newpath = malloc(newpath_len);
500                         snprintf(newpath, newpath_len, "%s!%s",
501                                  config.c_nodename, msg->cm_fields['P']);
502                         free(msg->cm_fields['P']);
503                         msg->cm_fields['P'] = newpath;
504
505                         /*
506                          * Force the message to appear in the correct room
507                          * on the far end by setting the C field correctly
508                          */
509                         if (msg->cm_fields['C'] != NULL) {
510                                 free(msg->cm_fields['C']);
511                         }
512                         msg->cm_fields['C'] = strdup(CC->room.QRname);
513
514                         /*
515                          * Determine if this message is set to be deleted
516                          * after sending out on the network
517                          */
518                         if (msg->cm_fields['S'] != NULL) {
519                                 if (!strcasecmp(msg->cm_fields['S'],
520                                    "CANCEL")) {
521                                         delete_after_send = 1;
522                                 }
523                         }
524
525                         /* 
526                          * Now serialize it for transmission
527                          */
528                         serialize_message(&sermsg, msg);
529
530                         /* Now send it to every node */
531                         for (nptr = sc->ignet_push_shares; nptr != NULL;
532                             nptr = nptr->next) {
533
534                                 send = 1;
535
536                                 /* Check for valid node name */
537                                 if (is_valid_node(NULL, NULL, nptr->name) != 0) {
538                                         lprintf(CTDL_ERR, "Invalid node <%s>\n",
539                                                 nptr->name);
540                                         send = 0;
541                                 }
542
543                                 /* Check for split horizon */
544                                 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
545                                 bang = num_tokens(msg->cm_fields['P'], '!');
546                                 if (bang > 1) for (i=0; i<(bang-1); ++i) {
547                                         extract_token(buf, msg->cm_fields['P'],
548                                                 i, '!');
549                                         if (!strcasecmp(buf, nptr->name)) {
550                                                 send = 0;
551                                         }
552                                 }
553
554                                 /* Send the message */
555                                 if (send == 1) {
556                                         snprintf(filename, sizeof filename,
557                                                 "./network/spoolout/%s",
558                                                 nptr->name);
559                                         fp = fopen(filename, "ab");
560                                         if (fp != NULL) {
561                                                 fwrite(sermsg.ser,
562                                                         sermsg.len, 1, fp);
563                                                 fclose(fp);
564                                         }
565                                 }
566                         }
567                         free(sermsg.ser);
568                         CtdlFreeMessage(msg);
569                 }
570         }
571
572         /* update lastsent */
573         sc->lastsent = msgnum;
574
575         /* Delete this message if delete-after-send is set */
576         if (delete_after_send) {
577                 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
578         }
579
580 }
581         
582
583 /*
584  * Deliver digest messages
585  */
586 void network_deliver_digest(struct SpoolControl *sc) {
587         char buf[SIZ];
588         int i;
589         struct CtdlMessage *msg;
590         long msglen;
591         long msgnum;
592         char *instr = NULL;
593         size_t instr_len = SIZ;
594         struct CtdlMessage *imsg;
595         struct namelist *nptr;
596
597         if (sc->num_msgs_spooled < 1) {
598                 fclose(sc->digestfp);
599                 sc->digestfp = NULL;
600                 return;
601         }
602
603         msg = malloc(sizeof(struct CtdlMessage));
604         memset(msg, 0, sizeof(struct CtdlMessage));
605         msg->cm_magic = CTDLMESSAGE_MAGIC;
606         msg->cm_format_type = FMT_RFC822;
607         msg->cm_anon_type = MES_NORMAL;
608
609         sprintf(buf, "%ld", time(NULL));
610         msg->cm_fields['T'] = strdup(buf);
611         msg->cm_fields['A'] = strdup(CC->room.QRname);
612         msg->cm_fields['U'] = strdup(CC->room.QRname);
613         sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
614         for (i=0; i<strlen(buf); ++i) {
615                 if (isspace(buf[i])) buf[i]='_';
616                 buf[i] = tolower(buf[i]);
617         }
618         msg->cm_fields['F'] = strdup(buf);
619
620         fseek(sc->digestfp, 0L, SEEK_END);
621         msglen = ftell(sc->digestfp);
622
623         msg->cm_fields['M'] = malloc(msglen + 1);
624         fseek(sc->digestfp, 0L, SEEK_SET);
625         fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
626         msg->cm_fields['M'][msglen] = 0;
627
628         fclose(sc->digestfp);
629         sc->digestfp = NULL;
630
631         msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
632         CtdlFreeMessage(msg);
633
634         /* Now generate the delivery instructions */
635
636         /* 
637          * Figure out how big a buffer we need to allocate
638          */
639         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
640                 instr_len = instr_len + strlen(nptr->name);
641         }
642         
643         /*
644          * allocate...
645          */
646         lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
647         instr = malloc(instr_len);
648         if (instr == NULL) {
649                 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
650                         (long)instr_len);
651                 abort();
652         }
653         snprintf(instr, instr_len,
654                 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
655                 "bounceto|postmaster@%s\n" ,
656                 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
657
658         /* Generate delivery instructions for each recipient */
659         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
660                 size_t tmp = strlen(instr);
661                 snprintf(&instr[tmp], instr_len - tmp,
662                          "remote|%s|0||\n", nptr->name);
663         }
664
665         /*
666          * Generate a message from the instructions
667          */
668         imsg = malloc(sizeof(struct CtdlMessage));
669         memset(imsg, 0, sizeof(struct CtdlMessage));
670         imsg->cm_magic = CTDLMESSAGE_MAGIC;
671         imsg->cm_anon_type = MES_NORMAL;
672         imsg->cm_format_type = FMT_RFC822;
673         imsg->cm_fields['A'] = strdup("Citadel");
674         imsg->cm_fields['M'] = instr;
675
676         /* Save delivery instructions in spoolout room */
677         CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
678         CtdlFreeMessage(imsg);
679 }
680
681
682 /*
683  * Batch up and send all outbound traffic from the current room
684  */
685 void network_spoolout_room(char *room_to_spool) {
686         char filename[SIZ];
687         char buf[SIZ];
688         char instr[SIZ];
689         char nodename[SIZ];
690         char nexthop[SIZ];
691         FILE *fp;
692         struct SpoolControl sc;
693         struct namelist *nptr = NULL;
694         size_t miscsize = 0;
695         size_t linesize = 0;
696         int skipthisline = 0;
697         int i;
698
699         if (getroom(&CC->room, room_to_spool) != 0) {
700                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
701                 return;
702         }
703
704         memset(&sc, 0, sizeof(struct SpoolControl));
705         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
706
707         begin_critical_section(S_NETCONFIGS);
708
709         fp = fopen(filename, "r");
710         if (fp == NULL) {
711                 end_critical_section(S_NETCONFIGS);
712                 return;
713         }
714
715         lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
716
717         while (fgets(buf, sizeof buf, fp) != NULL) {
718                 buf[strlen(buf)-1] = 0;
719
720                 extract(instr, buf, 0);
721                 if (!strcasecmp(instr, "lastsent")) {
722                         sc.lastsent = extract_long(buf, 1);
723                 }
724                 else if (!strcasecmp(instr, "listrecp")) {
725                         nptr = (struct namelist *)
726                                 malloc(sizeof(struct namelist));
727                         nptr->next = sc.listrecps;
728                         extract(nptr->name, buf, 1);
729                         sc.listrecps = nptr;
730                 }
731                 else if (!strcasecmp(instr, "digestrecp")) {
732                         nptr = (struct namelist *)
733                                 malloc(sizeof(struct namelist));
734                         nptr->next = sc.digestrecps;
735                         extract(nptr->name, buf, 1);
736                         sc.digestrecps = nptr;
737                 }
738                 else if (!strcasecmp(instr, "ignet_push_share")) {
739                         /* by checking each node's validity, we automatically
740                          * purge nodes which do not exist from room network
741                          * configurations at this time.
742                          */
743                         extract(nodename, buf, 1);
744                         strcpy(nexthop, "xxx");
745                         if (is_valid_node(nexthop, NULL, nodename) == 0) {
746                                 if (strlen(nexthop) == 0) {
747                                         nptr = (struct namelist *)
748                                                 malloc(sizeof(struct namelist));
749                                         nptr->next = sc.ignet_push_shares;
750                                         strcpy(nptr->name, nodename);
751                                         sc.ignet_push_shares = nptr;
752                                 }
753                         }
754                 }
755                 else {
756                         /* Preserve 'other' lines ... *unless* they happen to
757                          * be subscribe/unsubscribe pendings with expired
758                          * timestamps.
759                          */
760                         skipthisline = 0;
761                         if (!strncasecmp(buf, "subpending|", 11)) {
762                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
763                                         skipthisline = 1;
764                                 }
765                         }
766                         if (!strncasecmp(buf, "unsubpending|", 13)) {
767                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
768                                         skipthisline = 1;
769                                 }
770                         }
771
772                         if (skipthisline == 0) {
773                                 linesize = strlen(buf);
774                                 sc.misc = realloc(sc.misc,
775                                         (miscsize + linesize + 2) );
776                                 sprintf(&sc.misc[miscsize], "%s\n", buf);
777                                 miscsize = miscsize + linesize + 1;
778                         }
779                 }
780
781
782         }
783         fclose(fp);
784
785         /* If there are digest recipients, we have to build a digest */
786         if (sc.digestrecps != NULL) {
787                 sc.digestfp = tmpfile();
788                 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
789         }
790
791         /* Do something useful */
792         CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
793                 network_spool_msg, &sc);
794
795         /* If we wrote a digest, deliver it and then close it */
796         snprintf(buf, sizeof buf, "room_%s@%s",
797                 CC->room.QRname, config.c_fqdn);
798         for (i=0; i<strlen(buf); ++i) {
799                 buf[i] = tolower(buf[i]);
800                 if (isspace(buf[i])) buf[i] = '_';
801         }
802         if (sc.digestfp != NULL) {
803                 fprintf(sc.digestfp,    " -----------------------------------"
804                                         "------------------------------------"
805                                         "-------\n"
806                                         "You are subscribed to the '%s' "
807                                         "list.\n"
808                                         "To post to the list: %s\n",
809                                         CC->room.QRname, buf
810                 );
811                 network_deliver_digest(&sc);    /* deliver and close */
812         }
813
814         /* Now rewrite the config file */
815         fp = fopen(filename, "w");
816         if (fp == NULL) {
817                 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
818                         filename, strerror(errno));
819         }
820         else {
821                 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
822
823                 /* Write out the listrecps while freeing from memory at the
824                  * same time.  Am I clever or what?  :)
825                  */
826                 while (sc.listrecps != NULL) {
827                         fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
828                         nptr = sc.listrecps->next;
829                         free(sc.listrecps);
830                         sc.listrecps = nptr;
831                 }
832                 /* Do the same for digestrecps */
833                 while (sc.digestrecps != NULL) {
834                         fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
835                         nptr = sc.digestrecps->next;
836                         free(sc.digestrecps);
837                         sc.digestrecps = nptr;
838                 }
839                 while (sc.ignet_push_shares != NULL) {
840                         /* by checking each node's validity, we automatically
841                          * purge nodes which do not exist from room network
842                          * configurations at this time.
843                          */
844                         if (is_valid_node(NULL, NULL, sc.ignet_push_shares->name) == 0) {
845                         }
846                         fprintf(fp, "ignet_push_share|%s\n",
847                                 sc.ignet_push_shares->name);
848                         nptr = sc.ignet_push_shares->next;
849                         free(sc.ignet_push_shares);
850                         sc.ignet_push_shares = nptr;
851                 }
852                 if (sc.misc != NULL) {
853                         fwrite(sc.misc, strlen(sc.misc), 1, fp);
854                 }
855                 free(sc.misc);
856
857                 fclose(fp);
858         }
859         end_critical_section(S_NETCONFIGS);
860 }
861
862
863
864 /*
865  * Send the *entire* contents of the current room to one specific network node,
866  * ignoring anything we know about which messages have already undergone
867  * network processing.  This can be used to bring a new node into sync.
868  */
869 int network_sync_to(char *target_node) {
870         struct SpoolControl sc;
871         int num_spooled = 0;
872
873         /* Concise syntax because we don't need a full linked-list */
874         memset(&sc, 0, sizeof(struct SpoolControl));
875         sc.ignet_push_shares = (struct namelist *)
876                 malloc(sizeof(struct namelist));
877         sc.ignet_push_shares->next = NULL;
878         safestrncpy(sc.ignet_push_shares->name,
879                 target_node,
880                 sizeof sc.ignet_push_shares->name);
881
882         /* Send ALL messages */
883         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
884                 network_spool_msg, &sc);
885
886         /* Concise cleanup because we know there's only one node in the sc */
887         free(sc.ignet_push_shares);
888
889         lprintf(CTDL_INFO, "Synchronized %d messages to <%s>\n",
890                 num_spooled, target_node);
891         return(num_spooled);
892 }
893
894
895 /*
896  * Implements the NSYN command
897  */
898 void cmd_nsyn(char *argbuf) {
899         int num_spooled;
900         char target_node[SIZ];
901
902         if (CtdlAccessCheck(ac_aide)) return;
903
904         extract(target_node, argbuf, 0);
905         num_spooled = network_sync_to(target_node);
906         cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
907 }
908
909
910
911 /*
912  * Batch up and send all outbound traffic from the current room
913  */
914 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
915         struct RoomProcList *ptr;
916
917         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
918         if (ptr == NULL) return;
919
920         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
921         ptr->next = rplist;
922         rplist = ptr;
923 }
924
925
926 /*
927  * Learn topology from path fields
928  */
929 void network_learn_topology(char *node, char *path) {
930         char nexthop[SIZ];
931         struct NetMap *nmptr;
932
933         strcpy(nexthop, "");
934
935         if (num_tokens(path, '!') < 3) return;
936         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
937                 if (!strcasecmp(nmptr->nodename, node)) {
938                         extract_token(nmptr->nexthop, path, 0, '!');
939                         nmptr->lastcontact = time(NULL);
940                         return;
941                 }
942         }
943
944         /* If we got here then it's not in the map, so add it. */
945         nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
946         strcpy(nmptr->nodename, node);
947         nmptr->lastcontact = time(NULL);
948         extract_token(nmptr->nexthop, path, 0, '!');
949         nmptr->next = the_netmap;
950         the_netmap = nmptr;
951 }
952
953
954
955
956 /*
957  * Bounce a message back to the sender
958  */
959 void network_bounce(struct CtdlMessage *msg, char *reason) {
960         char *oldpath = NULL;
961         char buf[SIZ];
962         char bouncesource[SIZ];
963         char recipient[SIZ];
964         struct recptypes *valid = NULL;
965         char force_room[ROOMNAMELEN];
966         static int serialnum = 0;
967         size_t size;
968
969         lprintf(CTDL_DEBUG, "entering network_bounce()\n");
970
971         if (msg == NULL) return;
972
973         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
974
975         /* 
976          * Give it a fresh message ID
977          */
978         if (msg->cm_fields['I'] != NULL) {
979                 free(msg->cm_fields['I']);
980         }
981         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
982                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
983         msg->cm_fields['I'] = strdup(buf);
984
985         /*
986          * FIXME ... right now we're just sending a bounce; we really want to
987          * include the text of the bounced message.
988          */
989         if (msg->cm_fields['M'] != NULL) {
990                 free(msg->cm_fields['M']);
991         }
992         msg->cm_fields['M'] = strdup(reason);
993         msg->cm_format_type = 0;
994
995         /*
996          * Turn the message around
997          */
998         if (msg->cm_fields['R'] == NULL) {
999                 free(msg->cm_fields['R']);
1000         }
1001
1002         if (msg->cm_fields['D'] == NULL) {
1003                 free(msg->cm_fields['D']);
1004         }
1005
1006         snprintf(recipient, sizeof recipient, "%s@%s",
1007                 msg->cm_fields['A'], msg->cm_fields['N']);
1008
1009         if (msg->cm_fields['A'] == NULL) {
1010                 free(msg->cm_fields['A']);
1011         }
1012
1013         if (msg->cm_fields['N'] == NULL) {
1014                 free(msg->cm_fields['N']);
1015         }
1016
1017         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1018         msg->cm_fields['N'] = strdup(config.c_nodename);
1019         
1020
1021         /* prepend our node to the path */
1022         if (msg->cm_fields['P'] != NULL) {
1023                 oldpath = msg->cm_fields['P'];
1024                 msg->cm_fields['P'] = NULL;
1025         }
1026         else {
1027                 oldpath = strdup("unknown_user");
1028         }
1029         size = strlen(oldpath) + SIZ;
1030         msg->cm_fields['P'] = malloc(size);
1031         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1032         free(oldpath);
1033
1034         /* Now submit the message */
1035         valid = validate_recipients(recipient);
1036         if (valid != NULL) if (valid->num_error > 0) {
1037                 free(valid);
1038                 valid = NULL;
1039         }
1040         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1041                 strcpy(force_room, config.c_aideroom);
1042         }
1043         else {
1044                 strcpy(force_room, "");
1045         }
1046         if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1047                 strcpy(force_room, config.c_aideroom);
1048         }
1049         CtdlSubmitMsg(msg, valid, force_room);
1050
1051         /* Clean up */
1052         if (valid != NULL) free(valid);
1053         CtdlFreeMessage(msg);
1054         lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1055 }
1056
1057
1058
1059
1060 /*
1061  * Process a buffer containing a single message from a single file
1062  * from the inbound queue 
1063  */
1064 void network_process_buffer(char *buffer, long size) {
1065         struct CtdlMessage *msg;
1066         long pos;
1067         int field;
1068         struct recptypes *recp = NULL;
1069         char target_room[ROOMNAMELEN];
1070         struct ser_ret sermsg;
1071         char *oldpath = NULL;
1072         char filename[SIZ];
1073         FILE *fp;
1074         char nexthop[SIZ];
1075         unsigned char firstbyte;
1076         unsigned char lastbyte;
1077
1078         /* Validate just a little bit.  First byte should be FF and
1079          * last byte should be 00.
1080          */
1081         memcpy(&firstbyte, &buffer[0], 1);
1082         memcpy(&lastbyte, &buffer[size-1], 1);
1083         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1084                 lprintf(CTDL_ERR, "Corrupt message!  Ignoring.\n");
1085                 return;
1086         }
1087
1088         /* Set default target room to trash */
1089         strcpy(target_room, TWITROOM);
1090
1091         /* Load the message into memory */
1092         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1093         memset(msg, 0, sizeof(struct CtdlMessage));
1094         msg->cm_magic = CTDLMESSAGE_MAGIC;
1095         msg->cm_anon_type = buffer[1];
1096         msg->cm_format_type = buffer[2];
1097
1098         for (pos = 3; pos < size; ++pos) {
1099                 field = buffer[pos];
1100                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1101                 pos = pos + strlen(&buffer[(int)pos]);
1102         }
1103
1104         /* Check for message routing */
1105         if (msg->cm_fields['D'] != NULL) {
1106                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1107
1108                         /* route the message */
1109                         strcpy(nexthop, "");
1110                         if (is_valid_node(nexthop, NULL,
1111                            msg->cm_fields['D']) == 0) {
1112
1113                                 /* prepend our node to the path */
1114                                 if (msg->cm_fields['P'] != NULL) {
1115                                         oldpath = msg->cm_fields['P'];
1116                                         msg->cm_fields['P'] = NULL;
1117                                 }
1118                                 else {
1119                                         oldpath = strdup("unknown_user");
1120                                 }
1121                                 size = strlen(oldpath) + SIZ;
1122                                 msg->cm_fields['P'] = malloc(size);
1123                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1124                                         config.c_nodename, oldpath);
1125                                 free(oldpath);
1126
1127                                 /* serialize the message */
1128                                 serialize_message(&sermsg, msg);
1129
1130                                 /* now send it */
1131                                 if (strlen(nexthop) == 0) {
1132                                         strcpy(nexthop, msg->cm_fields['D']);
1133                                 }
1134                                 snprintf(filename, sizeof filename,
1135                                         "./network/spoolout/%s", nexthop);
1136                                 fp = fopen(filename, "ab");
1137                                 if (fp != NULL) {
1138                                         fwrite(sermsg.ser,
1139                                                 sermsg.len, 1, fp);
1140                                         fclose(fp);
1141                                 }
1142                                 free(sermsg.ser);
1143                                 CtdlFreeMessage(msg);
1144                                 return;
1145                         }
1146                         
1147                         else {  /* invalid destination node name */
1148
1149                                 network_bounce(msg,
1150 "A message you sent could not be delivered due to an invalid destination node"
1151 " name.  Please check the address and try sending the message again.\n");
1152                                 msg = NULL;
1153                                 return;
1154
1155                         }
1156                 }
1157         }
1158
1159         /*
1160          * Check to see if we already have a copy of this message, and
1161          * abort its processing if so.  (We used to post a warning to Aide>
1162          * every time this happened, but the network is now so densely
1163          * connected that it's inevitable.)
1164          */
1165         if (network_usetable(msg) != 0) {
1166                 return;
1167         }
1168
1169         /* Learn network topology from the path */
1170         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1171                 network_learn_topology(msg->cm_fields['N'], 
1172                                         msg->cm_fields['P']);
1173         }
1174
1175         /* Is the sending node giving us a very persuasive suggestion about
1176          * which room this message should be saved in?  If so, go with that.
1177          */
1178         if (msg->cm_fields['C'] != NULL) {
1179                 safestrncpy(target_room,
1180                         msg->cm_fields['C'],
1181                         sizeof target_room);
1182         }
1183
1184         /* Otherwise, does it have a recipient?  If so, validate it... */
1185         else if (msg->cm_fields['R'] != NULL) {
1186                 recp = validate_recipients(msg->cm_fields['R']);
1187                 if (recp != NULL) if (recp->num_error > 0) {
1188                         network_bounce(msg,
1189 "A message you sent could not be delivered due to an invalid address.\n"
1190 "Please check the address and try sending the message again.\n");
1191                         msg = NULL;
1192                         free(recp);
1193                         return;
1194                 }
1195                 strcpy(target_room, "");        /* no target room if mail */
1196         }
1197
1198         /* Our last shot at finding a home for this message is to see if
1199          * it has the O field (Originating room) set.
1200          */
1201         else if (msg->cm_fields['O'] != NULL) {
1202                 safestrncpy(target_room,
1203                         msg->cm_fields['O'],
1204                         sizeof target_room);
1205         }
1206
1207         /* Strip out fields that are only relevant during transit */
1208         if (msg->cm_fields['D'] != NULL) {
1209                 free(msg->cm_fields['D']);
1210                 msg->cm_fields['D'] = NULL;
1211         }
1212         if (msg->cm_fields['C'] != NULL) {
1213                 free(msg->cm_fields['C']);
1214                 msg->cm_fields['C'] = NULL;
1215         }
1216
1217         /* save the message into a room */
1218         if (PerformNetprocHooks(msg, target_room) == 0) {
1219                 msg->cm_flags = CM_SKIP_HOOKS;
1220                 CtdlSubmitMsg(msg, recp, target_room);
1221         }
1222         CtdlFreeMessage(msg);
1223         free(recp);
1224 }
1225
1226
1227 /*
1228  * Process a single message from a single file from the inbound queue 
1229  */
1230 void network_process_message(FILE *fp, long msgstart, long msgend) {
1231         long hold_pos;
1232         long size;
1233         char *buffer;
1234
1235         hold_pos = ftell(fp);
1236         size = msgend - msgstart + 1;
1237         buffer = malloc(size);
1238         if (buffer != NULL) {
1239                 fseek(fp, msgstart, SEEK_SET);
1240                 fread(buffer, size, 1, fp);
1241                 network_process_buffer(buffer, size);
1242                 free(buffer);
1243         }
1244
1245         fseek(fp, hold_pos, SEEK_SET);
1246 }
1247
1248
1249 /*
1250  * Process a single file from the inbound queue 
1251  */
1252 void network_process_file(char *filename) {
1253         FILE *fp;
1254         long msgstart = (-1L);
1255         long msgend = (-1L);
1256         long msgcur = 0L;
1257         int ch;
1258
1259
1260         fp = fopen(filename, "rb");
1261         if (fp == NULL) {
1262                 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1263                         filename, strerror(errno));
1264                 return;
1265         }
1266
1267         lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1268
1269         /* Look for messages in the data stream and break them out */
1270         while (ch = getc(fp), ch >= 0) {
1271         
1272                 if (ch == 255) {
1273                         if (msgstart >= 0L) {
1274                                 msgend = msgcur - 1;
1275                                 network_process_message(fp, msgstart, msgend);
1276                         }
1277                         msgstart = msgcur;
1278                 }
1279
1280                 ++msgcur;
1281         }
1282
1283         msgend = msgcur - 1;
1284         if (msgstart >= 0L) {
1285                 network_process_message(fp, msgstart, msgend);
1286         }
1287
1288         fclose(fp);
1289         unlink(filename);
1290 }
1291
1292
1293 /*
1294  * Process anything in the inbound queue
1295  */
1296 void network_do_spoolin(void) {
1297         DIR *dp;
1298         struct dirent *d;
1299         char filename[SIZ];
1300
1301         dp = opendir("./network/spoolin");
1302         if (dp == NULL) return;
1303
1304         while (d = readdir(dp), d != NULL) {
1305                 snprintf(filename, sizeof filename,
1306                         "./network/spoolin/%s", d->d_name);
1307                 network_process_file(filename);
1308         }
1309
1310
1311         closedir(dp);
1312 }
1313
1314
1315 /*
1316  * Delete any files in the outbound queue that were intended
1317  * to be sent to nodes which no longer exist.
1318  */
1319 void network_purge_spoolout(void) {
1320         DIR *dp;
1321         struct dirent *d;
1322         char filename[SIZ];
1323         char nexthop[SIZ];
1324         int i;
1325
1326         dp = opendir("./network/spoolout");
1327         if (dp == NULL) return;
1328
1329         while (d = readdir(dp), d != NULL) {
1330                 snprintf(filename, sizeof filename,
1331                         "./network/spoolout/%s", d->d_name);
1332
1333                 strcpy(nexthop, "");
1334                 i = is_valid_node(nexthop, NULL, d->d_name);
1335         
1336                 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1337                         unlink(filename);
1338                 }
1339         }
1340
1341
1342         closedir(dp);
1343 }
1344
1345
1346
1347 /*
1348  * receive network spool from the remote system
1349  */
1350 void receive_spool(int sock, char *remote_nodename) {
1351         long download_len;
1352         long bytes_received;
1353         char buf[SIZ];
1354         static char pbuf[IGNET_PACKET_SIZE];
1355         char tempfilename[PATH_MAX];
1356         long plen;
1357         FILE *fp;
1358
1359         strcpy(tempfilename, tmpnam(NULL));
1360         if (sock_puts(sock, "NDOP") < 0) return;
1361         if (sock_gets(sock, buf) < 0) return;
1362         lprintf(CTDL_DEBUG, "<%s\n", buf);
1363         if (buf[0] != '2') {
1364                 return;
1365         }
1366         download_len = extract_long(&buf[4], 0);
1367
1368         bytes_received = 0L;
1369         fp = fopen(tempfilename, "w");
1370         if (fp == NULL) {
1371                 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1372                         strerror(errno));
1373                 return;
1374         }
1375
1376         while (bytes_received < download_len) {
1377                 snprintf(buf, sizeof buf, "READ %ld|%ld",
1378                         bytes_received,
1379                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1380                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1381                 if (sock_puts(sock, buf) < 0) {
1382                         fclose(fp);
1383                         unlink(tempfilename);
1384                         return;
1385                 }
1386                 if (sock_gets(sock, buf) < 0) {
1387                         fclose(fp);
1388                         unlink(tempfilename);
1389                         return;
1390                 }
1391                 if (buf[0] == '6') {
1392                         plen = extract_long(&buf[4], 0);
1393                         if (sock_read(sock, pbuf, plen) < 0) {
1394                                 fclose(fp);
1395                                 unlink(tempfilename);
1396                                 return;
1397                         }
1398                         fwrite((char *) pbuf, plen, 1, fp);
1399                         bytes_received = bytes_received + plen;
1400                 }
1401         }
1402
1403         fclose(fp);
1404         if (sock_puts(sock, "CLOS") < 0) {
1405                 unlink(tempfilename);
1406                 return;
1407         }
1408         if (sock_gets(sock, buf) < 0) {
1409                 unlink(tempfilename);
1410                 return;
1411         }
1412         lprintf(CTDL_DEBUG, "%s\n", buf);
1413         snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1414                 tempfilename, remote_nodename, (long) getpid());
1415         system(buf);
1416 }
1417
1418
1419
1420 /*
1421  * transmit network spool to the remote system
1422  */
1423 void transmit_spool(int sock, char *remote_nodename)
1424 {
1425         char buf[SIZ];
1426         char pbuf[4096];
1427         long plen;
1428         long bytes_to_write, thisblock;
1429         int fd;
1430         char sfname[128];
1431
1432         if (sock_puts(sock, "NUOP") < 0) return;
1433         if (sock_gets(sock, buf) < 0) return;
1434         lprintf(CTDL_DEBUG, "<%s\n", buf);
1435         if (buf[0] != '2') {
1436                 return;
1437         }
1438
1439         snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1440         fd = open(sfname, O_RDONLY);
1441         if (fd < 0) {
1442                 if (errno == ENOENT) {
1443                         lprintf(CTDL_INFO, "Nothing to send.\n");
1444                 } else {
1445                         lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1446                                 strerror(errno));
1447                 }
1448                 return;
1449         }
1450         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1451                 bytes_to_write = plen;
1452                 while (bytes_to_write > 0L) {
1453                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1454                         if (sock_puts(sock, buf) < 0) {
1455                                 close(fd);
1456                                 return;
1457                         }
1458                         if (sock_gets(sock, buf) < 0) {
1459                                 close(fd);
1460                                 return;
1461                         }
1462                         thisblock = atol(&buf[4]);
1463                         if (buf[0] == '7') {
1464                                 if (sock_write(sock, pbuf,
1465                                    (int) thisblock) < 0) {
1466                                         close(fd);
1467                                         return;
1468                                 }
1469                                 bytes_to_write = bytes_to_write - thisblock;
1470                         } else {
1471                                 goto ABORTUPL;
1472                         }
1473                 }
1474         }
1475
1476 ABORTUPL:
1477         close(fd);
1478         if (sock_puts(sock, "UCLS 1") < 0) return;
1479         if (sock_gets(sock, buf) < 0) return;
1480         lprintf(CTDL_DEBUG, "<%s\n", buf);
1481         if (buf[0] == '2') {
1482                 unlink(sfname);
1483         }
1484 }
1485
1486
1487
1488 /*
1489  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1490  */
1491 void network_poll_node(char *node, char *secret, char *host, char *port) {
1492         int sock;
1493         char buf[SIZ];
1494
1495         if (network_talking_to(node, NTT_CHECK)) return;
1496         network_talking_to(node, NTT_ADD);
1497         lprintf(CTDL_INFO, "Polling node <%s> at %s:%s\n", node, host, port);
1498
1499         sock = sock_connect(host, port, "tcp");
1500         if (sock < 0) {
1501                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1502                 network_talking_to(node, NTT_REMOVE);
1503                 return;
1504         }
1505         
1506         lprintf(CTDL_DEBUG, "Connected!\n");
1507
1508         /* Read the server greeting */
1509         if (sock_gets(sock, buf) < 0) goto bail;
1510         lprintf(CTDL_DEBUG, ">%s\n", buf);
1511
1512         /* Identify ourselves */
1513         snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1514         lprintf(CTDL_DEBUG, "<%s\n", buf);
1515         if (sock_puts(sock, buf) <0) goto bail;
1516         if (sock_gets(sock, buf) < 0) goto bail;
1517         lprintf(CTDL_DEBUG, ">%s\n", buf);
1518         if (buf[0] != '2') goto bail;
1519
1520         /* At this point we are authenticated. */
1521         receive_spool(sock, node);
1522         transmit_spool(sock, node);
1523
1524         sock_puts(sock, "QUIT");
1525 bail:   sock_close(sock);
1526         network_talking_to(node, NTT_REMOVE);
1527 }
1528
1529
1530
1531 /*
1532  * Poll other Citadel nodes and transfer inbound/outbound network data.
1533  * Set "full" to nonzero to force a poll of every node, or to zero to poll
1534  * only nodes to which we have data to send.
1535  */
1536 void network_poll_other_citadel_nodes(int full_poll) {
1537         int i;
1538         char linebuf[SIZ];
1539         char node[SIZ];
1540         char host[SIZ];
1541         char port[SIZ];
1542         char secret[SIZ];
1543         int poll = 0;
1544         char spoolfile[SIZ];
1545
1546         if (working_ignetcfg == NULL) return;   /* no nodes defined */
1547
1548         /* Use the string tokenizer to grab one line at a time */
1549         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1550                 extract_token(linebuf, working_ignetcfg, i, '\n');
1551                 extract(node, linebuf, 0);
1552                 extract(secret, linebuf, 1);
1553                 extract(host, linebuf, 2);
1554                 extract(port, linebuf, 3);
1555                 if ( (strlen(node) > 0) && (strlen(secret) > 0) 
1556                    && (strlen(host) > 0) && strlen(port) > 0) {
1557                         poll = full_poll;
1558                         if (poll == 0) {
1559                                 sprintf(spoolfile, "./network/spoolout/%s",
1560                                         node);
1561                                 if (access(spoolfile, R_OK) == 0) {
1562                                         poll = 1;
1563                                 }
1564                         }
1565                         if (poll) {
1566                                 network_poll_node(node, secret, host, port);
1567                         }
1568                 }
1569         }
1570
1571 }
1572
1573
1574
1575
1576
1577
1578
1579 /*
1580  * network_do_queue()
1581  * 
1582  * Run through the rooms doing various types of network stuff.
1583  */
1584 void network_do_queue(void) {
1585         static time_t last_run = 0L;
1586         struct RoomProcList *ptr;
1587         int full_processing = 1;
1588
1589         /*
1590          * Run the full set of processing tasks no more frequently
1591          * than once every n seconds
1592          */
1593         if ( (time(NULL) - last_run) < config.c_net_freq ) {
1594                 full_processing = 0;
1595         }
1596
1597         /*
1598          * This is a simple concurrency check to make sure only one queue run
1599          * is done at a time.  We could do this with a mutex, but since we
1600          * don't really require extremely fine granularity here, we'll do it
1601          * with a static variable instead.
1602          */
1603         if (doing_queue) return;
1604         doing_queue = 1;
1605
1606         /* Load the IGnet Configuration into memory */
1607         working_ignetcfg = CtdlGetSysConfig(IGNETCFG);
1608
1609         /*
1610          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
1611          * then we poll everyone.  Otherwise we only poll nodes we have stuff
1612          * to send to.
1613          */
1614         network_poll_other_citadel_nodes(full_processing);
1615
1616         /*
1617          * Load the network map and filter list into memory.
1618          */
1619         read_network_map();
1620         filterlist = load_filter_list();
1621
1622         /* 
1623          * Go ahead and run the queue
1624          */
1625         if (full_processing) {
1626                 lprintf(CTDL_INFO, "network: loading outbound queue\n");
1627                 ForEachRoom(network_queue_room, NULL);
1628
1629                 lprintf(CTDL_INFO, "network: running outbound queue\n");
1630                 while (rplist != NULL) {
1631                         network_spoolout_room(rplist->name);
1632                         ptr = rplist;
1633                         rplist = rplist->next;
1634                         free(ptr);
1635                 }
1636         }
1637
1638         lprintf(CTDL_INFO, "network: processing inbound queue\n");
1639         network_do_spoolin();
1640
1641         /* Save the network map back to disk */
1642         write_network_map();
1643
1644         /* Free the filter list in memory */
1645         free_filter_list(filterlist);
1646         filterlist = NULL;
1647
1648         network_purge_spoolout();
1649
1650         lprintf(CTDL_INFO, "network: queue run completed\n");
1651
1652         if (full_processing) {
1653                 last_run = time(NULL);
1654         }
1655
1656         doing_queue = 0;
1657         free(working_ignetcfg);
1658 }
1659
1660
1661 /*
1662  * cmd_netp() - authenticate to the server as another Citadel node polling
1663  *              for network traffic
1664  */
1665 void cmd_netp(char *cmdbuf)
1666 {
1667         char node[SIZ];
1668         char pass[SIZ];
1669
1670         char secret[SIZ];
1671         char nexthop[SIZ];
1672
1673         if (doing_queue) {
1674                 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
1675                 return;
1676         }
1677
1678         extract(node, cmdbuf, 0);
1679         extract(pass, cmdbuf, 1);
1680
1681         if (is_valid_node(nexthop, secret, node) != 0) {
1682                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1683                 return;
1684         }
1685
1686         if (strcasecmp(pass, secret)) {
1687                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1688                 return;
1689         }
1690
1691         if (network_talking_to(node, NTT_CHECK)) {
1692                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1693                 return;
1694         }
1695
1696         safestrncpy(CC->net_node, node, sizeof CC->net_node);
1697         network_talking_to(node, NTT_ADD);
1698         cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1699                 CC->net_node);
1700 }
1701
1702
1703 /*
1704  * This handler detects changes being made to the system's IGnet
1705  * configuration.
1706  */
1707 int netconfig_aftersave(struct CtdlMessage *msg) {
1708         char *ptr;
1709         int linelen;
1710
1711         /* If this isn't the configuration room, or if this isn't a MIME
1712          * message, don't bother.
1713          */
1714         if (strcasecmp(msg->cm_fields['O'], SYSCONFIGROOM)) return(0);
1715         if (msg->cm_format_type != 4) return(0);
1716
1717         ptr = msg->cm_fields['M'];
1718         while (ptr != NULL) {
1719         
1720                 linelen = strcspn(ptr, "\n");
1721                 if (linelen == 0) return(0);    /* end of headers */    
1722                 
1723                 if (!strncasecmp(ptr, "Content-type: ", 14)) {
1724                         if (!strncasecmp(&ptr[14], IGNETCFG,
1725                            strlen(IGNETCFG))) {
1726                                 if (ignetcfg != NULL) free(ignetcfg);
1727                                 ignetcfg = NULL;
1728                         }
1729                 }
1730
1731                 ptr = strchr((char *)ptr, '\n');
1732                 if (ptr != NULL) ++ptr;
1733         }
1734
1735         return(0);
1736 }
1737
1738
1739
1740
1741 /*
1742  * Module entry point
1743  */
1744 char *serv_network_init(void)
1745 {
1746         CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1747         CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1748         CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1749         CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1750         CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1751         CtdlRegisterMessageHook(netconfig_aftersave, EVT_AFTERSAVE);
1752         return "$Id$";
1753 }