Cleaned up the loop that receives network spool. NOT THE FIX
[citadel.git] / citadel / modules / network / serv_network.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2010 by the citadel.org team
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
22  * This is a fairly high-level type of critical section.  It ensures that no
23  * two threads work on the netconfigs files at the same time.  Since we do
24  * so many things inside these, here are the rules:
25  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26  *  2. Do *not* perform any I/O with the client during these sections.
27  *
28  */
29
30 /*
31  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32  * requests that have not been confirmed will be deleted.
33  */
34 #define EXP     259200  /* three days */
35
36 #include "sysdep.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <stdio.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <signal.h>
43 #include <pwd.h>
44 #include <errno.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <dirent.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58 #ifdef HAVE_SYSCALL_H
59 # include <syscall.h>
60 #else 
61 # if HAVE_SYS_SYSCALL_H
62 #  include <sys/syscall.h>
63 # endif
64 #endif
65
66 #include <sys/wait.h>
67 #include <string.h>
68 #include <limits.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "user_ops.h"
76 #include "database.h"
77 #include "msgbase.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
81 #include "file_ops.h"
82 #include "citadel_dirs.h"
83 #include "threads.h"
84
85 #ifndef HAVE_SNPRINTF
86 #include "snprintf.h"
87 #endif
88
89 #include "context.h"
90
91 #include "ctdl_module.h"
92
93
94
95 /* Nonzero while we are doing network processing */
96 static int doing_queue = 0;
97
98 /*
99  * When we do network processing, it's accomplished in two passes; one to
100  * gather a list of rooms and one to actually do them.  It's ok that rplist
101  * is global; we have a mutex that keeps it safe.
102  */
103 struct RoomProcList *rplist = NULL;
104
105 /*
106  * We build a map of network nodes during processing.
107  */
108 NetMap *the_netmap = NULL;
109 int netmap_changed = 0;
110 char *working_ignetcfg = NULL;
111
112 /*
113  * Load or refresh the Citadel network (IGnet) configuration for this node.
114  */
115 void load_working_ignetcfg(void) {
116         char *cfg;
117         char *oldcfg;
118
119         cfg = CtdlGetSysConfig(IGNETCFG);
120         if (cfg == NULL) {
121                 cfg = strdup("");
122         }
123
124         oldcfg = working_ignetcfg;
125         working_ignetcfg = cfg;
126         if (oldcfg != NULL) {
127                 free(oldcfg);
128         }
129 }
130
131
132
133
134
135 /*
136  * Keep track of what messages to reject
137  */
138 FilterList *load_filter_list(void) {
139         char *serialized_list = NULL;
140         int i;
141         char buf[SIZ];
142         FilterList *newlist = NULL;
143         FilterList *nptr;
144
145         serialized_list = CtdlGetSysConfig(FILTERLIST);
146         if (serialized_list == NULL) return(NULL); /* if null, no entries */
147
148         /* Use the string tokenizer to grab one line at a time */
149         for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
150                 extract_token(buf, serialized_list, i, '\n', sizeof buf);
151                 nptr = (FilterList *) malloc(sizeof(FilterList));
152                 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
153                 striplt(nptr->fl_user);
154                 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
155                 striplt(nptr->fl_room);
156                 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
157                 striplt(nptr->fl_node);
158
159                 /* Cowardly refuse to add an any/any/any entry that would
160                  * end up filtering every single message.
161                  */
162                 if (IsEmptyStr(nptr->fl_user) && 
163                     IsEmptyStr(nptr->fl_room) &&
164                     IsEmptyStr(nptr->fl_node)) {
165                         free(nptr);
166                 }
167                 else {
168                         nptr->next = newlist;
169                         newlist = nptr;
170                 }
171         }
172
173         free(serialized_list);
174         return newlist;
175 }
176
177
178 void free_filter_list(FilterList *fl) {
179         if (fl == NULL) return;
180         free_filter_list(fl->next);
181         free(fl);
182 }
183
184
185
186 /*
187  * Check the use table.  This is a list of messages which have recently
188  * arrived on the system.  It is maintained and queried to prevent the same
189  * message from being entered into the database multiple times if it happens
190  * to arrive multiple times by accident.
191  */
192 int network_usetable(struct CtdlMessage *msg) {
193
194         char msgid[SIZ];
195         struct cdbdata *cdbut;
196         struct UseTable ut;
197
198         /* Bail out if we can't generate a message ID */
199         if (msg == NULL) {
200                 return(0);
201         }
202         if (msg->cm_fields['I'] == NULL) {
203                 return(0);
204         }
205         if (IsEmptyStr(msg->cm_fields['I'])) {
206                 return(0);
207         }
208
209         /* Generate the message ID */
210         strcpy(msgid, msg->cm_fields['I']);
211         if (haschar(msgid, '@') == 0) {
212                 strcat(msgid, "@");
213                 if (msg->cm_fields['N'] != NULL) {
214                         strcat(msgid, msg->cm_fields['N']);
215                 }
216                 else {
217                         return(0);
218                 }
219         }
220
221         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
222         if (cdbut != NULL) {
223                 cdb_free(cdbut);
224                 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
225                 return(1);
226         }
227
228         /* If we got to this point, it's unique: add it. */
229         strcpy(ut.ut_msgid, msgid);
230         ut.ut_timestamp = time(NULL);
231         cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
232         return(0);
233 }
234
235
236 /* 
237  * Read the network map from its configuration file into memory.
238  */
239 void read_network_map(void) {
240         char *serialized_map = NULL;
241         int i;
242         char buf[SIZ];
243         NetMap *nmptr;
244
245         serialized_map = CtdlGetSysConfig(IGNETMAP);
246         if (serialized_map == NULL) return;     /* if null, no entries */
247
248         /* Use the string tokenizer to grab one line at a time */
249         for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
250                 extract_token(buf, serialized_map, i, '\n', sizeof buf);
251                 nmptr = (NetMap *) malloc(sizeof(NetMap));
252                 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
253                 nmptr->lastcontact = extract_long(buf, 1);
254                 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
255                 nmptr->next = the_netmap;
256                 the_netmap = nmptr;
257         }
258
259         free(serialized_map);
260         netmap_changed = 0;
261 }
262
263
264 /*
265  * Write the network map from memory back to the configuration file.
266  */
267 void write_network_map(void) {
268         char *serialized_map = NULL;
269         NetMap *nmptr;
270
271
272         if (netmap_changed) {
273                 serialized_map = strdup("");
274         
275                 if (the_netmap != NULL) {
276                         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
277                                 serialized_map = realloc(serialized_map,
278                                                         (strlen(serialized_map)+SIZ) );
279                                 if (!IsEmptyStr(nmptr->nodename)) {
280                                         snprintf(&serialized_map[strlen(serialized_map)],
281                                                 SIZ,
282                                                 "%s|%ld|%s\n",
283                                                 nmptr->nodename,
284                                                 (long)nmptr->lastcontact,
285                                                 nmptr->nexthop);
286                                 }
287                         }
288                 }
289
290                 CtdlPutSysConfig(IGNETMAP, serialized_map);
291                 free(serialized_map);
292         }
293
294         /* Now free the list */
295         while (the_netmap != NULL) {
296                 nmptr = the_netmap->next;
297                 free(the_netmap);
298                 the_netmap = nmptr;
299         }
300         netmap_changed = 0;
301 }
302
303
304
305 /* 
306  * Check the network map and determine whether the supplied node name is
307  * valid.  If it is not a neighbor node, supply the name of a neighbor node
308  * which is the next hop.  If it *is* a neighbor node, we also fill in the
309  * shared secret.
310  */
311 int is_valid_node(char *nexthop, char *secret, char *node) {
312         int i;
313         char linebuf[SIZ];
314         char buf[SIZ];
315         int retval;
316         NetMap *nmptr;
317
318         if (node == NULL) {
319                 return(-1);
320         }
321
322         /*
323          * First try the neighbor nodes
324          */
325         if (working_ignetcfg == NULL) {
326                 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
327                 if (nexthop != NULL) {
328                         strcpy(nexthop, "");
329                 }
330                 return(-1);
331         }
332
333         retval = (-1);
334         if (nexthop != NULL) {
335                 strcpy(nexthop, "");
336         }
337
338         /* Use the string tokenizer to grab one line at a time */
339         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
340                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
341                 extract_token(buf, linebuf, 0, '|', sizeof buf);
342                 if (!strcasecmp(buf, node)) {
343                         if (nexthop != NULL) {
344                                 strcpy(nexthop, "");
345                         }
346                         if (secret != NULL) {
347                                 extract_token(secret, linebuf, 1, '|', 256);
348                         }
349                         retval = 0;
350                 }
351         }
352
353         if (retval == 0) {
354                 return(retval);         /* yup, it's a direct neighbor */
355         }
356
357         /*      
358          * If we get to this point we have to see if we know the next hop
359          */
360         if (the_netmap != NULL) {
361                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
362                         if (!strcasecmp(nmptr->nodename, node)) {
363                                 if (nexthop != NULL) {
364                                         strcpy(nexthop, nmptr->nexthop);
365                                 }
366                                 return(0);
367                         }
368                 }
369         }
370
371         /*
372          * If we get to this point, the supplied node name is bogus.
373          */
374         CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
375         return(-1);
376 }
377
378
379
380
381
382 void cmd_gnet(char *argbuf) {
383         char filename[PATH_MAX];
384         char buf[SIZ];
385         FILE *fp;
386
387         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
388                 /* users can edit the netconfigs for their own mailbox rooms */
389         }
390         else if (CtdlAccessCheck(ac_room_aide)) return;
391
392         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
393         cprintf("%d Network settings for room #%ld <%s>\n",
394                 LISTING_FOLLOWS,
395                 CC->room.QRnumber, CC->room.QRname);
396
397         fp = fopen(filename, "r");
398         if (fp != NULL) {
399                 while (fgets(buf, sizeof buf, fp) != NULL) {
400                         buf[strlen(buf)-1] = 0;
401                         cprintf("%s\n", buf);
402                 }
403                 fclose(fp);
404         }
405
406         cprintf("000\n");
407 }
408
409
410 void cmd_snet(char *argbuf) {
411         char tempfilename[PATH_MAX];
412         char filename[PATH_MAX];
413         int TmpFD;
414         StrBuf *Line;
415         struct stat StatBuf;
416         long len;
417         int rc;
418
419         unbuffer_output();
420
421         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
422                 /* users can edit the netconfigs for their own mailbox rooms */
423         }
424         else if (CtdlAccessCheck(ac_room_aide)) return;
425
426         len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
427         memcpy(tempfilename, filename, len + 1);
428
429         memset(&StatBuf, 0, sizeof(struct stat));
430         if ((stat(filename, &StatBuf)  == -1) || (StatBuf.st_size == 0))
431                 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
432
433         sprintf(tempfilename + len, ".%d", CC->cs_pid);
434         errno = 0;
435         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
436
437         if ((TmpFD > 0) && (errno == 0))
438         {
439                 char *tmp = malloc(StatBuf.st_size * 2);
440                 memset(tmp, ' ', StatBuf.st_size * 2);
441                 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
442                 free(tmp);
443                 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
444                 {
445                         close(TmpFD);
446                         cprintf("%d Unable to allocate the space required for %s: %s\n",
447                                 ERROR + INTERNAL_ERROR,
448                                 tempfilename,
449                                 strerror(errno));
450                         unlink(tempfilename);
451                         return;
452                 }       
453                 lseek(TmpFD, SEEK_SET, 0);
454         }
455         else {
456                 cprintf("%d Unable to allocate the space required for %s: %s\n",
457                         ERROR + INTERNAL_ERROR,
458                         tempfilename,
459                         strerror(errno));
460                 unlink(tempfilename);
461                 return;
462         }
463         Line = NewStrBuf();
464
465         cprintf("%d %s\n", SEND_LISTING, tempfilename);
466
467         len = 0;
468         while (rc = CtdlClientGetLine(Line), 
469                (rc >= 0))
470         {
471                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
472                         break;
473                 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
474                 write(TmpFD, ChrPtr(Line), StrLength(Line));
475                 len += StrLength(Line);
476         }
477         FreeStrBuf(&Line);
478         ftruncate(TmpFD, len);
479         close(TmpFD);
480
481         /* Now copy the temp file to its permanent location.
482          * (We copy instead of link because they may be on different filesystems)
483          */
484         begin_critical_section(S_NETCONFIGS);
485         rename(tempfilename, filename);
486         end_critical_section(S_NETCONFIGS);
487 }
488
489
490 /*
491  * Deliver digest messages
492  */
493 void network_deliver_digest(SpoolControl *sc) {
494         char buf[SIZ];
495         int i;
496         struct CtdlMessage *msg = NULL;
497         long msglen;
498         char *recps = NULL;
499         size_t recps_len = SIZ;
500         size_t siz;
501         struct recptypes *valid;
502         namelist *nptr;
503         char bounce_to[256];
504
505         if (sc->num_msgs_spooled < 1) {
506                 fclose(sc->digestfp);
507                 sc->digestfp = NULL;
508                 return;
509         }
510
511         msg = malloc(sizeof(struct CtdlMessage));
512         memset(msg, 0, sizeof(struct CtdlMessage));
513         msg->cm_magic = CTDLMESSAGE_MAGIC;
514         msg->cm_format_type = FMT_RFC822;
515         msg->cm_anon_type = MES_NORMAL;
516
517         sprintf(buf, "%ld", time(NULL));
518         msg->cm_fields['T'] = strdup(buf);
519         msg->cm_fields['A'] = strdup(CC->room.QRname);
520         snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
521         msg->cm_fields['U'] = strdup(buf);
522         sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
523         for (i=0; buf[i]; ++i) {
524                 if (isspace(buf[i])) buf[i]='_';
525                 buf[i] = tolower(buf[i]);
526         }
527         msg->cm_fields['F'] = strdup(buf);
528         msg->cm_fields['R'] = strdup(buf);
529
530         /* Set the 'List-ID' header */
531         msg->cm_fields['L'] = malloc(1024);
532         snprintf(msg->cm_fields['L'], 1024,
533                 "%s <%ld.list-id.%s>",
534                 CC->room.QRname,
535                 CC->room.QRnumber,
536                 config.c_fqdn
537         );
538
539         /*
540          * Go fetch the contents of the digest
541          */
542         fseek(sc->digestfp, 0L, SEEK_END);
543         msglen = ftell(sc->digestfp);
544
545         msg->cm_fields['M'] = malloc(msglen + 1);
546         fseek(sc->digestfp, 0L, SEEK_SET);
547         siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
548         msg->cm_fields['M'][msglen] = '\0';
549
550         fclose(sc->digestfp);
551         sc->digestfp = NULL;
552
553         /* Now generate the delivery instructions */
554
555         /* 
556          * Figure out how big a buffer we need to allocate
557          */
558         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
559                 recps_len = recps_len + strlen(nptr->name) + 2;
560         }
561         
562         recps = malloc(recps_len);
563
564         if (recps == NULL) {
565                 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
566                 abort();
567         }
568
569         strcpy(recps, "");
570
571         /* Each recipient */
572         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
573                 if (nptr != sc->digestrecps) {
574                         strcat(recps, ",");
575                 }
576                 strcat(recps, nptr->name);
577         }
578
579         /* Where do we want bounces and other noise to be heard?  Surely not the list members! */
580         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
581
582         /* Now submit the message */
583         valid = validate_recipients(recps, NULL, 0);
584         free(recps);
585         if (valid != NULL) {
586                 valid->bounce_to = strdup(bounce_to);
587                 valid->envelope_from = strdup(bounce_to);
588                 CtdlSubmitMsg(msg, valid, NULL, 0);
589         }
590         CtdlFreeMessage(msg);
591         free_recipients(valid);
592 }
593
594
595 /*
596  * Deliver list messages to everyone on the list ... efficiently
597  */
598 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
599         char *recps = NULL;
600         size_t recps_len = SIZ;
601         struct recptypes *valid;
602         namelist *nptr;
603         char bounce_to[256];
604
605         /* Don't do this if there were no recipients! */
606         if (sc->listrecps == NULL) return;
607
608         /* Now generate the delivery instructions */
609
610         /* 
611          * Figure out how big a buffer we need to allocate
612          */
613         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
614                 recps_len = recps_len + strlen(nptr->name) + 2;
615         }
616         
617         recps = malloc(recps_len);
618
619         if (recps == NULL) {
620                 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
621                 abort();
622         }
623
624         strcpy(recps, "");
625
626         /* Each recipient */
627         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
628                 if (nptr != sc->listrecps) {
629                         strcat(recps, ",");
630                 }
631                 strcat(recps, nptr->name);
632         }
633
634         /* Where do we want bounces and other noise to be heard?  Surely not the list members! */
635         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
636
637         /* Now submit the message */
638         valid = validate_recipients(recps, NULL, 0);
639         free(recps);
640         if (valid != NULL) {
641                 valid->bounce_to = strdup(bounce_to);
642                 valid->envelope_from = strdup(bounce_to);
643                 CtdlSubmitMsg(msg, valid, NULL, 0);
644                 free_recipients(valid);
645         }
646         /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
647 }
648
649
650
651
652 /*
653  * Spools out one message from the list.
654  */
655 void network_spool_msg(long msgnum, void *userdata) {
656         SpoolControl *sc;
657         int i;
658         char *newpath = NULL;
659         size_t instr_len = SIZ;
660         struct CtdlMessage *msg = NULL;
661         namelist *nptr;
662         maplist *mptr;
663         struct ser_ret sermsg;
664         FILE *fp;
665         char filename[PATH_MAX];
666         char buf[SIZ];
667         int bang = 0;
668         int send = 1;
669         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
670         int ok_to_participate = 0;
671         struct recptypes *valid;
672
673         sc = (SpoolControl *)userdata;
674
675         /*
676          * Process mailing list recipients
677          */
678         instr_len = SIZ;
679         if (sc->listrecps != NULL) {
680                 /* Fetch the message.  We're going to need to modify it
681                  * in order to insert the [list name] in it, etc.
682                  */
683                 msg = CtdlFetchMessage(msgnum, 1);
684                 if (msg != NULL) {
685                         if (msg->cm_fields['V'] == NULL){
686                                 /* local message, no enVelope */
687                                 StrBuf *Buf;
688                                 Buf = NewStrBuf();
689                                 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
690                                 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
691                                 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
692                                 
693                                 msg->cm_fields['K'] = SmashStrBuf(&Buf);
694                         }
695                         else {
696                                 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
697                         }
698                         /* Set the 'List-ID' header */
699                         if (msg->cm_fields['L'] != NULL) {
700                                 free(msg->cm_fields['L']);
701                         }
702                         msg->cm_fields['L'] = malloc(1024);
703                         snprintf(msg->cm_fields['L'], 1024,
704                                 "%s <%ld.list-id.%s>",
705                                 CC->room.QRname,
706                                 CC->room.QRnumber,
707                                 config.c_fqdn
708                         );
709
710                         /* Prepend "[List name]" to the subject */
711                         if (msg->cm_fields['U'] == NULL) {
712                                 msg->cm_fields['U'] = strdup("(no subject)");
713                         }
714                         snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
715                         free(msg->cm_fields['U']);
716                         msg->cm_fields['U'] = strdup(buf);
717
718                         /* Set the recipient of the list message to the
719                          * email address of the room itself.
720                          * FIXME ... I want to be able to pick any address
721                          */
722                         if (msg->cm_fields['R'] != NULL) {
723                                 free(msg->cm_fields['R']);
724                         }
725                         msg->cm_fields['R'] = malloc(256);
726                         snprintf(msg->cm_fields['R'], 256,
727                                 "room_%s@%s", CC->room.QRname,
728                                 config.c_fqdn);
729                         for (i=0; msg->cm_fields['R'][i]; ++i) {
730                                 if (isspace(msg->cm_fields['R'][i])) {
731                                         msg->cm_fields['R'][i] = '_';
732                                 }
733                         }
734
735                         /* Handle delivery */
736                         network_deliver_list(msg, sc);
737                         CtdlFreeMessage(msg);
738                 }
739         }
740
741         /*
742          * Process digest recipients
743          */
744         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
745                 msg = CtdlFetchMessage(msgnum, 1);
746                 if (msg != NULL) {
747                         fprintf(sc->digestfp,   " -----------------------------------"
748                                                 "------------------------------------"
749                                                 "-------\n");
750                         fprintf(sc->digestfp, "From: ");
751                         if (msg->cm_fields['A'] != NULL) {
752                                 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
753                         }
754                         if (msg->cm_fields['F'] != NULL) {
755                                 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
756                         }
757                         else if (msg->cm_fields['N'] != NULL) {
758                                 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
759                         }
760                         fprintf(sc->digestfp, "\n");
761                         if (msg->cm_fields['U'] != NULL) {
762                                 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
763                         }
764
765                         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
766                         
767                         safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
768                         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
769
770                         StrBufTrim(CC->redirect_buffer);
771                         fwrite(HKEY("\n"), 1, sc->digestfp);
772                         fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
773                         fwrite(HKEY("\n"), 1, sc->digestfp);
774
775                         FreeStrBuf(&CC->redirect_buffer);
776
777                         sc->num_msgs_spooled += 1;
778                         free(msg);
779                 }
780         }
781
782         /*
783          * Process client-side list participations for this room
784          */
785         instr_len = SIZ;
786         if (sc->participates != NULL) {
787                 msg = CtdlFetchMessage(msgnum, 1);
788                 if (msg != NULL) {
789
790                         /* Only send messages which originated on our own Citadel
791                          * network, otherwise we'll end up sending the remote
792                          * mailing list's messages back to it, which is rude...
793                          */
794                         ok_to_participate = 0;
795                         if (msg->cm_fields['N'] != NULL) {
796                                 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
797                                         ok_to_participate = 1;
798                                 }
799                                 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
800                                         ok_to_participate = 1;
801                                 }
802                         }
803                         if (ok_to_participate) {
804                                 if (msg->cm_fields['F'] != NULL) {
805                                         free(msg->cm_fields['F']);
806                                 }
807                                 msg->cm_fields['F'] = malloc(SIZ);
808                                 /* Replace the Internet email address of the actual
809                                 * author with the email address of the room itself,
810                                 * so the remote listserv doesn't reject us.
811                                 * FIXME ... I want to be able to pick any address
812                                 */
813                                 snprintf(msg->cm_fields['F'], SIZ,
814                                         "room_%s@%s", CC->room.QRname,
815                                         config.c_fqdn);
816                                 for (i=0; msg->cm_fields['F'][i]; ++i) {
817                                         if (isspace(msg->cm_fields['F'][i])) {
818                                                 msg->cm_fields['F'][i] = '_';
819                                         }
820                                 }
821
822                                 /* 
823                                  * Figure out how big a buffer we need to allocate
824                                  */
825                                 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
826
827                                         if (msg->cm_fields['R'] == NULL) {
828                                                 free(msg->cm_fields['R']);
829                                         }
830                                         msg->cm_fields['R'] = strdup(nptr->name);
831         
832                                         valid = validate_recipients(nptr->name, NULL, 0);
833                                         CtdlSubmitMsg(msg, valid, "", 0);
834                                         free_recipients(valid);
835                                 }
836                         
837                         }
838                         CtdlFreeMessage(msg);
839                 }
840         }
841         
842         /*
843          * Process IGnet push shares
844          */
845         msg = CtdlFetchMessage(msgnum, 1);
846         if (msg != NULL) {
847                 size_t newpath_len;
848
849                 /* Prepend our node name to the Path field whenever
850                  * sending a message to another IGnet node
851                  */
852                 if (msg->cm_fields['P'] == NULL) {
853                         msg->cm_fields['P'] = strdup("username");
854                 }
855                 newpath_len = strlen(msg->cm_fields['P']) +
856                          strlen(config.c_nodename) + 2;
857                 newpath = malloc(newpath_len);
858                 snprintf(newpath, newpath_len, "%s!%s",
859                          config.c_nodename, msg->cm_fields['P']);
860                 free(msg->cm_fields['P']);
861                 msg->cm_fields['P'] = newpath;
862
863                 /*
864                  * Determine if this message is set to be deleted
865                  * after sending out on the network
866                  */
867                 if (msg->cm_fields['S'] != NULL) {
868                         if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
869                                 delete_after_send = 1;
870                         }
871                 }
872
873                 /* Now send it to every node */
874                 if (sc->ignet_push_shares != NULL)
875                   for (mptr = sc->ignet_push_shares; mptr != NULL;
876                     mptr = mptr->next) {
877
878                         send = 1;
879
880                         /* Check for valid node name */
881                         if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
882                                 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
883                                 send = 0;
884                         }
885
886                         /* Check for split horizon */
887                         CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
888                         bang = num_tokens(msg->cm_fields['P'], '!');
889                         if (bang > 1) for (i=0; i<(bang-1); ++i) {
890                                 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
891                                 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
892                                         buf, mptr->remote_nodename) ;
893                                 if (!strcasecmp(buf, mptr->remote_nodename)) {
894                                         send = 0;
895                                         CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
896                                                 mptr->remote_nodename);
897                                 }
898                                 else {
899                                         CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
900                                 }
901                         }
902
903                         /* Send the message */
904                         if (send == 1) {
905
906                                 /*
907                                  * Force the message to appear in the correct room
908                                  * on the far end by setting the C field correctly
909                                  */
910                                 if (msg->cm_fields['C'] != NULL) {
911                                         free(msg->cm_fields['C']);
912                                 }
913                                 if (!IsEmptyStr(mptr->remote_roomname)) {
914                                         msg->cm_fields['C'] = strdup(mptr->remote_roomname);
915                                 }
916                                 else {
917                                         msg->cm_fields['C'] = strdup(CC->room.QRname);
918                                 }
919
920                                 /* serialize it for transmission */
921                                 serialize_message(&sermsg, msg);
922                                 if (sermsg.len > 0) {
923
924                                         /* write it to a spool file */
925                                         snprintf(filename, sizeof filename,"%s/%s@%lx%x",
926                                                 ctdl_netout_dir,
927                                                 mptr->remote_nodename,
928                                                 time(NULL),
929                                                 rand()
930                                         );
931                                         CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
932                                         fp = fopen(filename, "ab");
933                                         if (fp != NULL) {
934                                                 fwrite(sermsg.ser,
935                                                         sermsg.len, 1, fp);
936                                                 fclose(fp);
937                                         }
938                                         else {
939                                                 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
940                                         }
941         
942                                         /* free the serialized version */
943                                         free(sermsg.ser);
944                                 }
945
946                         }
947                 }
948                 CtdlFreeMessage(msg);
949         }
950
951         /* update lastsent */
952         sc->lastsent = msgnum;
953
954         /* Delete this message if delete-after-send is set */
955         if (delete_after_send) {
956                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
957         }
958
959 }
960         
961
962 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
963 {
964         FILE *fp;
965         char instr[SIZ];
966         char buf[SIZ];
967         char nodename[256];
968         char roomname[ROOMNAMELEN];
969         size_t miscsize = 0;
970         size_t linesize = 0;
971         int skipthisline = 0;
972         namelist *nptr = NULL;
973         maplist *mptr = NULL;
974         SpoolControl *sc;
975
976         fp = fopen(filename, "r");
977         if (fp == NULL) {
978                 return 0;
979         }
980         sc = malloc(sizeof(SpoolControl));
981         memset(sc, 0, sizeof(SpoolControl));
982         *scc = sc;
983
984         while (fgets(buf, sizeof buf, fp) != NULL) {
985                 buf[strlen(buf)-1] = 0;
986
987                 extract_token(instr, buf, 0, '|', sizeof instr);
988                 if (!strcasecmp(instr, strof(lastsent))) {
989                         sc->lastsent = extract_long(buf, 1);
990                 }
991                 else if (!strcasecmp(instr, strof(listrecp))) {
992                         nptr = (namelist *)
993                                 malloc(sizeof(namelist));
994                         nptr->next = sc->listrecps;
995                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
996                         sc->listrecps = nptr;
997                 }
998                 else if (!strcasecmp(instr, strof(participate))) {
999                         nptr = (namelist *)
1000                                 malloc(sizeof(namelist));
1001                         nptr->next = sc->participates;
1002                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1003                         sc->participates = nptr;
1004                 }
1005                 else if (!strcasecmp(instr, strof(digestrecp))) {
1006                         nptr = (namelist *)
1007                                 malloc(sizeof(namelist));
1008                         nptr->next = sc->digestrecps;
1009                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1010                         sc->digestrecps = nptr;
1011                 }
1012                 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1013                         extract_token(nodename, buf, 1, '|', sizeof nodename);
1014                         extract_token(roomname, buf, 2, '|', sizeof roomname);
1015                         mptr = (maplist *) malloc(sizeof(maplist));
1016                         mptr->next = sc->ignet_push_shares;
1017                         strcpy(mptr->remote_nodename, nodename);
1018                         strcpy(mptr->remote_roomname, roomname);
1019                         sc->ignet_push_shares = mptr;
1020                 }
1021                 else {
1022                         /* Preserve 'other' lines ... *unless* they happen to
1023                          * be subscribe/unsubscribe pendings with expired
1024                          * timestamps.
1025                          */
1026                         skipthisline = 0;
1027                         if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1028                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
1029                                         skipthisline = 1;
1030                                 }
1031                         }
1032                         if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1033                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
1034                                         skipthisline = 1;
1035                                 }
1036                         }
1037
1038                         if (skipthisline == 0) {
1039                                 linesize = strlen(buf);
1040                                 sc->misc = realloc(sc->misc,
1041                                         (miscsize + linesize + 2) );
1042                                 sprintf(&sc->misc[miscsize], "%s\n", buf);
1043                                 miscsize = miscsize + linesize + 1;
1044                         }
1045                 }
1046
1047
1048         }
1049         fclose(fp);
1050         return 1;
1051 }
1052
1053 void free_spoolcontrol_struct(SpoolControl **scc)
1054 {
1055         SpoolControl *sc;
1056         namelist *nptr = NULL;
1057         maplist *mptr = NULL;
1058
1059         sc = *scc;
1060         while (sc->listrecps != NULL) {
1061                 nptr = sc->listrecps->next;
1062                 free(sc->listrecps);
1063                 sc->listrecps = nptr;
1064         }
1065         /* Do the same for digestrecps */
1066         while (sc->digestrecps != NULL) {
1067                 nptr = sc->digestrecps->next;
1068                 free(sc->digestrecps);
1069                 sc->digestrecps = nptr;
1070         }
1071         /* Do the same for participates */
1072         while (sc->participates != NULL) {
1073                 nptr = sc->participates->next;
1074                 free(sc->participates);
1075                 sc->participates = nptr;
1076         }
1077         while (sc->ignet_push_shares != NULL) {
1078                 mptr = sc->ignet_push_shares->next;
1079                 free(sc->ignet_push_shares);
1080                 sc->ignet_push_shares = mptr;
1081         }
1082         free(sc->misc);
1083         free(sc);
1084         *scc=NULL;
1085 }
1086
1087 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1088 {
1089         char tempfilename[PATH_MAX];
1090         int TmpFD;
1091         SpoolControl *sc;
1092         namelist *nptr = NULL;
1093         maplist *mptr = NULL;
1094         long len;
1095         time_t unixtime;
1096         struct timeval tv;
1097         long reltid; /* if we don't have SYS_gettid, use "random" value */
1098         StrBuf *Cfg;
1099         int rc;
1100
1101         len = strlen(filename);
1102         memcpy(tempfilename, filename, len + 1);
1103
1104
1105 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1106         reltid = syscall(SYS_gettid);
1107 #endif
1108         gettimeofday(&tv, NULL);
1109         /* Promote to time_t; types differ on some OSes (like darwin) */
1110         unixtime = tv.tv_sec;
1111
1112         sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1113         sc = *scc;
1114         errno = 0;
1115         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1116         Cfg = NewStrBuf();
1117         if ((TmpFD < 0) || (errno != 0)) {
1118                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1119                         filename, strerror(errno));
1120                 free_spoolcontrol_struct(scc);
1121                 unlink(tempfilename);
1122         }
1123         else {
1124                 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1125
1126                 /* Write out the listrecps while freeing from memory at the
1127                  * same time.  Am I clever or what?  :)
1128                  */
1129                 while (sc->listrecps != NULL) {
1130                         StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1131                         nptr = sc->listrecps->next;
1132                         free(sc->listrecps);
1133                         sc->listrecps = nptr;
1134                 }
1135                 /* Do the same for digestrecps */
1136                 while (sc->digestrecps != NULL) {
1137                         StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1138                         nptr = sc->digestrecps->next;
1139                         free(sc->digestrecps);
1140                         sc->digestrecps = nptr;
1141                 }
1142                 /* Do the same for participates */
1143                 while (sc->participates != NULL) {
1144                         StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1145                         nptr = sc->participates->next;
1146                         free(sc->participates);
1147                         sc->participates = nptr;
1148                 }
1149                 while (sc->ignet_push_shares != NULL) {
1150                         StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1151                         if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1152                                 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1153                         }
1154                         StrBufAppendPrintf(Cfg, "\n");
1155                         mptr = sc->ignet_push_shares->next;
1156                         free(sc->ignet_push_shares);
1157                         sc->ignet_push_shares = mptr;
1158                 }
1159                 if (sc->misc != NULL) {
1160                         StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1161                 }
1162                 free(sc->misc);
1163
1164                 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1165                 if ((rc >=0 ) && (rc == StrLength(Cfg))) 
1166                 {
1167                         close(TmpFD);
1168                         rename(tempfilename, filename);
1169                 }
1170                 else {
1171                         CtdlLogPrintf(CTDL_EMERG, 
1172                                       "unable to write %s; [%s]; not enough space on the disk?\n", 
1173                                       tempfilename, 
1174                                       strerror(errno));
1175                         close(TmpFD);
1176                         unlink(tempfilename);
1177                 }
1178                 FreeStrBuf(&Cfg);
1179                 free(sc);
1180                 *scc=NULL;
1181         }
1182         return 1;
1183 }
1184 int is_recipient(SpoolControl *sc, const char *Name)
1185 {
1186         namelist *nptr;
1187         size_t len;
1188
1189         len = strlen(Name);
1190         nptr = sc->listrecps;
1191         while (nptr != NULL) {
1192                 if (strncmp(Name, nptr->name, len)==0)
1193                         return 1;
1194                 nptr = nptr->next;
1195         }
1196         /* Do the same for digestrecps */
1197         nptr = sc->digestrecps;
1198         while (nptr != NULL) {
1199                 if (strncmp(Name, nptr->name, len)==0)
1200                         return 1;
1201                 nptr = nptr->next;
1202         }
1203         /* Do the same for participates */
1204         nptr = sc->participates;
1205         while (nptr != NULL) {
1206                 if (strncmp(Name, nptr->name, len)==0)
1207                         return 1;
1208                 nptr = nptr->next;
1209         }
1210         return 0;
1211 }
1212
1213
1214 /*
1215  * Batch up and send all outbound traffic from the current room
1216  */
1217 void network_spoolout_room(char *room_to_spool) {
1218         char buf[SIZ];
1219         char filename[PATH_MAX];
1220         SpoolControl *sc;
1221         int i;
1222
1223         /*
1224          * If the room doesn't exist, don't try to perform its networking tasks.
1225          * Normally this should never happen, but once in a while maybe a room gets
1226          * queued for networking and then deleted before it can happen.
1227          */
1228         if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1229                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1230                 return;
1231         }
1232
1233         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1234         begin_critical_section(S_NETCONFIGS);
1235
1236         /* Only do net processing for rooms that have netconfigs */
1237         if (!read_spoolcontrol_file(&sc, filename))
1238         {
1239                 end_critical_section(S_NETCONFIGS);
1240                 return;
1241         }
1242         CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1243
1244         /* If there are digest recipients, we have to build a digest */
1245         if (sc->digestrecps != NULL) {
1246                 sc->digestfp = tmpfile();
1247                 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1248         }
1249
1250         /* Do something useful */
1251         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1252                 network_spool_msg, sc);
1253
1254         /* If we wrote a digest, deliver it and then close it */
1255         snprintf(buf, sizeof buf, "room_%s@%s",
1256                 CC->room.QRname, config.c_fqdn);
1257         for (i=0; buf[i]; ++i) {
1258                 buf[i] = tolower(buf[i]);
1259                 if (isspace(buf[i])) buf[i] = '_';
1260         }
1261         if (sc->digestfp != NULL) {
1262                 fprintf(sc->digestfp,   " -----------------------------------"
1263                                         "------------------------------------"
1264                                         "-------\n"
1265                                         "You are subscribed to the '%s' "
1266                                         "list.\n"
1267                                         "To post to the list: %s\n",
1268                                         CC->room.QRname, buf
1269                 );
1270                 network_deliver_digest(sc);     /* deliver and close */
1271         }
1272
1273         /* Now rewrite the config file */
1274         writenfree_spoolcontrol_file (&sc, filename);
1275         end_critical_section(S_NETCONFIGS);
1276 }
1277
1278
1279
1280 /*
1281  * Send the *entire* contents of the current room to one specific network node,
1282  * ignoring anything we know about which messages have already undergone
1283  * network processing.  This can be used to bring a new node into sync.
1284  */
1285 int network_sync_to(char *target_node) {
1286         SpoolControl sc;
1287         int num_spooled = 0;
1288         int found_node = 0;
1289         char buf[256];
1290         char sc_type[256];
1291         char sc_node[256];
1292         char sc_room[256];
1293         char filename[PATH_MAX];
1294         FILE *fp;
1295
1296         /* Grab the configuration line we're looking for */
1297         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1298         begin_critical_section(S_NETCONFIGS);
1299         fp = fopen(filename, "r");
1300         if (fp == NULL) {
1301                 end_critical_section(S_NETCONFIGS);
1302                 return(-1);
1303         }
1304         while (fgets(buf, sizeof buf, fp) != NULL) {
1305                 buf[strlen(buf)-1] = 0;
1306                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1307                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1308                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1309                 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1310                    && (!strcasecmp(sc_node, target_node)) ) {
1311                         found_node = 1;
1312                         
1313                         /* Concise syntax because we don't need a full linked-list */
1314                         memset(&sc, 0, sizeof(SpoolControl));
1315                         sc.ignet_push_shares = (maplist *)
1316                                 malloc(sizeof(maplist));
1317                         sc.ignet_push_shares->next = NULL;
1318                         safestrncpy(sc.ignet_push_shares->remote_nodename,
1319                                 sc_node,
1320                                 sizeof sc.ignet_push_shares->remote_nodename);
1321                         safestrncpy(sc.ignet_push_shares->remote_roomname,
1322                                 sc_room,
1323                                 sizeof sc.ignet_push_shares->remote_roomname);
1324                 }
1325         }
1326         fclose(fp);
1327         end_critical_section(S_NETCONFIGS);
1328
1329         if (!found_node) return(-1);
1330
1331         /* Send ALL messages */
1332         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1333                 network_spool_msg, &sc);
1334
1335         /* Concise cleanup because we know there's only one node in the sc */
1336         free(sc.ignet_push_shares);
1337
1338         CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1339                 num_spooled, target_node);
1340         return(num_spooled);
1341 }
1342
1343
1344 /*
1345  * Implements the NSYN command
1346  */
1347 void cmd_nsyn(char *argbuf) {
1348         int num_spooled;
1349         char target_node[256];
1350
1351         if (CtdlAccessCheck(ac_aide)) return;
1352
1353         extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1354         num_spooled = network_sync_to(target_node);
1355         if (num_spooled >= 0) {
1356                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1357         }
1358         else {
1359                 cprintf("%d No such room/node share exists.\n",
1360                         ERROR + ROOM_NOT_FOUND);
1361         }
1362 }
1363
1364
1365
1366 /*
1367  * Batch up and send all outbound traffic from the current room
1368  */
1369 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1370         struct RoomProcList *ptr;
1371
1372         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1373         if (ptr == NULL) return;
1374
1375         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1376         begin_critical_section(S_RPLIST);
1377         ptr->next = rplist;
1378         rplist = ptr;
1379         end_critical_section(S_RPLIST);
1380 }
1381
1382 void destroy_network_queue_room(void)
1383 {
1384         struct RoomProcList *cur, *p;
1385         NetMap *nmcur, *nmp;
1386
1387         cur = rplist;
1388         begin_critical_section(S_RPLIST);
1389         while (cur != NULL)
1390         {
1391                 p = cur->next;
1392                 free (cur);
1393                 cur = p;                
1394         }
1395         rplist = NULL;
1396         end_critical_section(S_RPLIST);
1397
1398         nmcur = the_netmap;
1399         while (nmcur != NULL)
1400         {
1401                 nmp = nmcur->next;
1402                 free (nmcur);
1403                 nmcur = nmp;            
1404         }
1405         the_netmap = NULL;
1406         if (working_ignetcfg != NULL)
1407                 free (working_ignetcfg);
1408         working_ignetcfg = NULL;
1409 }
1410
1411
1412 /*
1413  * Learn topology from path fields
1414  */
1415 void network_learn_topology(char *node, char *path) {
1416         char nexthop[256];
1417         NetMap *nmptr;
1418
1419         strcpy(nexthop, "");
1420
1421         if (num_tokens(path, '!') < 3) return;
1422         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1423                 if (!strcasecmp(nmptr->nodename, node)) {
1424                         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1425                         nmptr->lastcontact = time(NULL);
1426                         ++netmap_changed;
1427                         return;
1428                 }
1429         }
1430
1431         /* If we got here then it's not in the map, so add it. */
1432         nmptr = (NetMap *) malloc(sizeof (NetMap));
1433         strcpy(nmptr->nodename, node);
1434         nmptr->lastcontact = time(NULL);
1435         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1436         nmptr->next = the_netmap;
1437         the_netmap = nmptr;
1438         ++netmap_changed;
1439 }
1440
1441
1442
1443
1444 /*
1445  * Bounce a message back to the sender
1446  */
1447 void network_bounce(struct CtdlMessage *msg, char *reason) {
1448         char *oldpath = NULL;
1449         char buf[SIZ];
1450         char bouncesource[SIZ];
1451         char recipient[SIZ];
1452         struct recptypes *valid = NULL;
1453         char force_room[ROOMNAMELEN];
1454         static int serialnum = 0;
1455         size_t size;
1456
1457         CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1458
1459         if (msg == NULL) return;
1460
1461         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1462
1463         /* 
1464          * Give it a fresh message ID
1465          */
1466         if (msg->cm_fields['I'] != NULL) {
1467                 free(msg->cm_fields['I']);
1468         }
1469         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1470                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1471         msg->cm_fields['I'] = strdup(buf);
1472
1473         /*
1474          * FIXME ... right now we're just sending a bounce; we really want to
1475          * include the text of the bounced message.
1476          */
1477         if (msg->cm_fields['M'] != NULL) {
1478                 free(msg->cm_fields['M']);
1479         }
1480         msg->cm_fields['M'] = strdup(reason);
1481         msg->cm_format_type = 0;
1482
1483         /*
1484          * Turn the message around
1485          */
1486         if (msg->cm_fields['R'] == NULL) {
1487                 free(msg->cm_fields['R']);
1488         }
1489
1490         if (msg->cm_fields['D'] == NULL) {
1491                 free(msg->cm_fields['D']);
1492         }
1493
1494         snprintf(recipient, sizeof recipient, "%s@%s",
1495                 msg->cm_fields['A'], msg->cm_fields['N']);
1496
1497         if (msg->cm_fields['A'] == NULL) {
1498                 free(msg->cm_fields['A']);
1499         }
1500
1501         if (msg->cm_fields['N'] == NULL) {
1502                 free(msg->cm_fields['N']);
1503         }
1504
1505         if (msg->cm_fields['U'] == NULL) {
1506                 free(msg->cm_fields['U']);
1507         }
1508
1509         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1510         msg->cm_fields['N'] = strdup(config.c_nodename);
1511         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1512
1513         /* prepend our node to the path */
1514         if (msg->cm_fields['P'] != NULL) {
1515                 oldpath = msg->cm_fields['P'];
1516                 msg->cm_fields['P'] = NULL;
1517         }
1518         else {
1519                 oldpath = strdup("unknown_user");
1520         }
1521         size = strlen(oldpath) + SIZ;
1522         msg->cm_fields['P'] = malloc(size);
1523         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1524         free(oldpath);
1525
1526         /* Now submit the message */
1527         valid = validate_recipients(recipient, NULL, 0);
1528         if (valid != NULL) if (valid->num_error != 0) {
1529                 free_recipients(valid);
1530                 valid = NULL;
1531         }
1532         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1533                 strcpy(force_room, config.c_aideroom);
1534         }
1535         else {
1536                 strcpy(force_room, "");
1537         }
1538         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1539                 strcpy(force_room, config.c_aideroom);
1540         }
1541         CtdlSubmitMsg(msg, valid, force_room, 0);
1542
1543         /* Clean up */
1544         if (valid != NULL) free_recipients(valid);
1545         CtdlFreeMessage(msg);
1546         CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1547 }
1548
1549
1550
1551
1552 /*
1553  * Process a buffer containing a single message from a single file
1554  * from the inbound queue 
1555  */
1556 void network_process_buffer(char *buffer, long size) {
1557         struct CtdlMessage *msg = NULL;
1558         long pos;
1559         int field;
1560         struct recptypes *recp = NULL;
1561         char target_room[ROOMNAMELEN];
1562         struct ser_ret sermsg;
1563         char *oldpath = NULL;
1564         char filename[PATH_MAX];
1565         FILE *fp;
1566         char nexthop[SIZ];
1567         unsigned char firstbyte;
1568         unsigned char lastbyte;
1569
1570         CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1571
1572         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
1573         firstbyte = buffer[0];
1574         lastbyte = buffer[size-1];
1575         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1576                 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
1577                         size, firstbyte, lastbyte);
1578                 return;
1579         }
1580
1581         /* Set default target room to trash */
1582         strcpy(target_room, TWITROOM);
1583
1584         /* Load the message into memory */
1585         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1586         memset(msg, 0, sizeof(struct CtdlMessage));
1587         msg->cm_magic = CTDLMESSAGE_MAGIC;
1588         msg->cm_anon_type = buffer[1];
1589         msg->cm_format_type = buffer[2];
1590
1591         for (pos = 3; pos < size; ++pos) {
1592                 field = buffer[pos];
1593                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1594                 pos = pos + strlen(&buffer[(int)pos]);
1595         }
1596
1597         /* Check for message routing */
1598         if (msg->cm_fields['D'] != NULL) {
1599                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1600
1601                         /* route the message */
1602                         strcpy(nexthop, "");
1603                         if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1604                                 /* prepend our node to the path */
1605                                 if (msg->cm_fields['P'] != NULL) {
1606                                         oldpath = msg->cm_fields['P'];
1607                                         msg->cm_fields['P'] = NULL;
1608                                 }
1609                                 else {
1610                                         oldpath = strdup("unknown_user");
1611                                 }
1612                                 size = strlen(oldpath) + SIZ;
1613                                 msg->cm_fields['P'] = malloc(size);
1614                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1615                                         config.c_nodename, oldpath);
1616                                 free(oldpath);
1617
1618                                 /* serialize the message */
1619                                 serialize_message(&sermsg, msg);
1620
1621                                 /* now send it */
1622                                 if (IsEmptyStr(nexthop)) {
1623                                         strcpy(nexthop, msg->cm_fields['D']);
1624                                 }
1625                                 snprintf(filename, 
1626                                         sizeof filename,
1627                                         "%s/%s@%lx%x",
1628                                         ctdl_netout_dir,
1629                                         nexthop,
1630                                         time(NULL),
1631                                         rand()
1632                                 );
1633                                 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1634                                 fp = fopen(filename, "ab");
1635                                 if (fp != NULL) {
1636                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
1637                                         fclose(fp);
1638                                 }
1639                                 else {
1640                                         CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1641                                 }
1642                                 free(sermsg.ser);
1643                                 CtdlFreeMessage(msg);
1644                                 return;
1645                         }
1646                         
1647                         else {  /* invalid destination node name */
1648
1649                                 network_bounce(msg,
1650 "A message you sent could not be delivered due to an invalid destination node"
1651 " name.  Please check the address and try sending the message again.\n");
1652                                 msg = NULL;
1653                                 return;
1654
1655                         }
1656                 }
1657         }
1658
1659         /*
1660          * Check to see if we already have a copy of this message, and
1661          * abort its processing if so.  (We used to post a warning to Aide>
1662          * every time this happened, but the network is now so densely
1663          * connected that it's inevitable.)
1664          */
1665         if (network_usetable(msg) != 0) {
1666                 CtdlFreeMessage(msg);
1667                 return;
1668         }
1669
1670         /* Learn network topology from the path */
1671         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1672                 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1673         }
1674
1675         /* Is the sending node giving us a very persuasive suggestion about
1676          * which room this message should be saved in?  If so, go with that.
1677          */
1678         if (msg->cm_fields['C'] != NULL) {
1679                 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1680         }
1681
1682         /* Otherwise, does it have a recipient?  If so, validate it... */
1683         else if (msg->cm_fields['R'] != NULL) {
1684                 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1685                 if (recp != NULL) if (recp->num_error != 0) {
1686                         network_bounce(msg,
1687                                 "A message you sent could not be delivered due to an invalid address.\n"
1688                                 "Please check the address and try sending the message again.\n");
1689                         msg = NULL;
1690                         free_recipients(recp);
1691                         CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1692                         return;
1693                 }
1694                 strcpy(target_room, "");        /* no target room if mail */
1695         }
1696
1697         /* Our last shot at finding a home for this message is to see if
1698          * it has the O field (Originating room) set.
1699          */
1700         else if (msg->cm_fields['O'] != NULL) {
1701                 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1702         }
1703
1704         /* Strip out fields that are only relevant during transit */
1705         if (msg->cm_fields['D'] != NULL) {
1706                 free(msg->cm_fields['D']);
1707                 msg->cm_fields['D'] = NULL;
1708         }
1709         if (msg->cm_fields['C'] != NULL) {
1710                 free(msg->cm_fields['C']);
1711                 msg->cm_fields['C'] = NULL;
1712         }
1713
1714         /* save the message into a room */
1715         if (PerformNetprocHooks(msg, target_room) == 0) {
1716                 msg->cm_flags = CM_SKIP_HOOKS;
1717                 CtdlSubmitMsg(msg, recp, target_room, 0);
1718         }
1719         CtdlFreeMessage(msg);
1720         free_recipients(recp);
1721 }
1722
1723
1724 /*
1725  * Process a single message from a single file from the inbound queue 
1726  */
1727 void network_process_message(FILE *fp, long msgstart, long msgend) {
1728         long hold_pos;
1729         long size;
1730         char *buffer;
1731
1732         hold_pos = ftell(fp);
1733         size = msgend - msgstart + 1;
1734         buffer = malloc(size);
1735         if (buffer != NULL) {
1736                 fseek(fp, msgstart, SEEK_SET);
1737                 if (fread(buffer, size, 1, fp) > 0) {
1738                         network_process_buffer(buffer, size);
1739                 }
1740                 free(buffer);
1741         }
1742
1743         fseek(fp, hold_pos, SEEK_SET);
1744 }
1745
1746
1747 /*
1748  * Process a single file from the inbound queue 
1749  */
1750 void network_process_file(char *filename) {
1751         FILE *fp;
1752         long msgstart = (-1L);
1753         long msgend = (-1L);
1754         long msgcur = 0L;
1755         int ch;
1756
1757
1758         fp = fopen(filename, "rb");
1759         if (fp == NULL) {
1760                 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1761                 return;
1762         }
1763
1764         fseek(fp, 0L, SEEK_END);
1765         CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1766         rewind(fp);
1767
1768         /* Look for messages in the data stream and break them out */
1769         while (ch = getc(fp), ch >= 0) {
1770         
1771                 if (ch == 255) {
1772                         if (msgstart >= 0L) {
1773                                 msgend = msgcur - 1;
1774                                 network_process_message(fp, msgstart, msgend);
1775                         }
1776                         msgstart = msgcur;
1777                 }
1778
1779                 ++msgcur;
1780         }
1781
1782         msgend = msgcur - 1;
1783         if (msgstart >= 0L) {
1784                 network_process_message(fp, msgstart, msgend);
1785         }
1786
1787         fclose(fp);
1788         unlink(filename);
1789 }
1790
1791
1792 /*
1793  * Process anything in the inbound queue
1794  */
1795 void network_do_spoolin(void) {
1796         DIR *dp;
1797         struct dirent *d;
1798         struct stat statbuf;
1799         char filename[PATH_MAX];
1800         static time_t last_spoolin_mtime = 0L;
1801
1802         /*
1803          * Check the spoolin directory's modification time.  If it hasn't
1804          * been touched, we don't need to scan it.
1805          */
1806         if (stat(ctdl_netin_dir, &statbuf)) return;
1807         if (statbuf.st_mtime == last_spoolin_mtime) {
1808                 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1809                 return;
1810         }
1811         last_spoolin_mtime = statbuf.st_mtime;
1812         CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1813
1814         /*
1815          * Ok, there's something interesting in there, so scan it.
1816          */
1817         dp = opendir(ctdl_netin_dir);
1818         if (dp == NULL) return;
1819
1820         while (d = readdir(dp), d != NULL) {
1821                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1822                         snprintf(filename, 
1823                                 sizeof filename,
1824                                 "%s/%s",
1825                                 ctdl_netin_dir,
1826                                 d->d_name
1827                         );
1828                         network_process_file(filename);
1829                 }
1830         }
1831
1832         closedir(dp);
1833 }
1834
1835 /*
1836  * Step 1: consolidate files in the outbound queue into one file per neighbor node
1837  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1838  */
1839 void network_consolidate_spoolout(void) {
1840         DIR *dp;
1841         struct dirent *d;
1842         char filename[PATH_MAX];
1843         char cmd[PATH_MAX];
1844         char nexthop[256];
1845         int i;
1846         char *ptr;
1847
1848         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1849         dp = opendir(ctdl_netout_dir);
1850         if (dp == NULL) return;
1851         while (d = readdir(dp), d != NULL) {
1852                 if (
1853                         (strcmp(d->d_name, "."))
1854                         && (strcmp(d->d_name, ".."))
1855                         && (strchr(d->d_name, '@') != NULL)
1856                 ) {
1857                         safestrncpy(nexthop, d->d_name, sizeof nexthop);
1858                         ptr = strchr(nexthop, '@');
1859                         if (ptr) *ptr = 0;
1860         
1861                         snprintf(filename, 
1862                                 sizeof filename,
1863                                 "%s/%s",
1864                                 ctdl_netout_dir,
1865                                 d->d_name
1866                         );
1867         
1868                         CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1869                         if (network_talking_to(nexthop, NTT_CHECK)) {
1870                                 CtdlLogPrintf(CTDL_DEBUG,
1871                                         "Currently online with %s - skipping for now\n",
1872                                         nexthop
1873                                 );
1874                         }
1875                         else {
1876                                 network_talking_to(nexthop, NTT_ADD);
1877                                 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1878                                         filename,
1879                                         ctdl_netout_dir, nexthop,
1880                                         filename
1881                                 );
1882                                 system(cmd);
1883                                 network_talking_to(nexthop, NTT_REMOVE);
1884                         }
1885                 }
1886         }
1887         closedir(dp);
1888
1889         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1890
1891         dp = opendir(ctdl_netout_dir);
1892         if (dp == NULL) return;
1893
1894         while (d = readdir(dp), d != NULL) {
1895                 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1896                         continue;
1897                 ptr = strchr(d->d_name, '@');
1898                 if (d != NULL)
1899                         continue;
1900                 snprintf(filename, 
1901                         sizeof filename,
1902                         "%s/%s",
1903                         ctdl_netout_dir,
1904                         d->d_name
1905                 );
1906
1907                 strcpy(nexthop, "");
1908                 i = is_valid_node(nexthop, NULL, d->d_name);
1909         
1910                 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1911                         unlink(filename);
1912                 }
1913         }
1914
1915
1916         closedir(dp);
1917 }
1918
1919
1920 /*
1921  * receive network spool from the remote system
1922  */
1923 void receive_spool(int *sock, char *remote_nodename) {
1924         int download_len = 0L;
1925         int bytes_received = 0L;
1926         char buf[SIZ];
1927         static char pbuf[IGNET_PACKET_SIZE];
1928         char tempfilename[PATH_MAX];
1929         char permfilename[PATH_MAX];
1930         int plen;
1931         FILE *fp;
1932
1933         snprintf(tempfilename, 
1934                 sizeof tempfilename, 
1935                 "%s/%s.%lx%x",
1936                 ctdl_nettmp_dir,
1937                 remote_nodename, 
1938                 time(NULL),
1939                 rand()
1940         );
1941
1942         snprintf(permfilename, 
1943                 sizeof permfilename, 
1944                 "%s/%s.%lx%x",
1945                 ctdl_netin_dir,
1946                 remote_nodename, 
1947                 time(NULL),
1948                 rand()
1949         );
1950
1951         if (sock_puts(sock, "NDOP") < 0) return;
1952         if (sock_getln(sock, buf, sizeof buf) < 0) return;
1953         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1954         if (buf[0] != '2') {
1955                 return;
1956         }
1957
1958         download_len = extract_long(&buf[4], 0);
1959         if (download_len <= 0) {
1960                 return;
1961         }
1962
1963         bytes_received = 0L;
1964         fp = fopen(tempfilename, "w");
1965         if (fp == NULL) {
1966                 CtdlLogPrintf(CTDL_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1967                 return;
1968         }
1969
1970         CtdlLogPrintf(CTDL_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1971         while (bytes_received < download_len) {
1972                 /*
1973                  * If shutting down we can exit here and unlink the temp file.
1974                  * this shouldn't loose us any messages.
1975                  */
1976                 if (CtdlThreadCheckStop())
1977                 {
1978                         fclose(fp);
1979                         unlink(tempfilename);
1980                         return;
1981                 }
1982                 snprintf(buf, sizeof buf, "READ %d|%d",
1983                          bytes_received,
1984                          ((download_len - bytes_received > IGNET_PACKET_SIZE)
1985                           ? IGNET_PACKET_SIZE : (download_len - bytes_received))
1986                 );
1987                 
1988                 if (sock_puts(sock, buf) < 0) {
1989                         fclose(fp);
1990                         unlink(tempfilename);
1991                         return;
1992                 }
1993                 if (sock_getln(sock, buf, sizeof buf) < 0) {
1994                         fclose(fp);
1995                         unlink(tempfilename);
1996                         return;
1997                 }
1998                 
1999                 if (buf[0] == '6') {
2000                         plen = extract_int(&buf[4], 0);
2001                         if (sock_read(sock, pbuf, plen, 1) < 0) {
2002                                 fclose(fp);
2003                                 unlink(tempfilename);
2004                                 return;
2005                         }
2006                         fwrite((char *) pbuf, plen, 1, fp);
2007                         bytes_received += plen;
2008                 }
2009         }
2010
2011         fclose(fp);
2012
2013         /* Last chance for shutdown exit */
2014         if (CtdlThreadCheckStop())
2015         {
2016                 unlink(tempfilename);
2017                 return;
2018         }
2019
2020         if (sock_puts(sock, "CLOS") < 0) {
2021                 unlink(tempfilename);
2022                 return;
2023         }
2024
2025         /*
2026          * From here on we must complete or messages will get lost
2027          */
2028         if (sock_getln(sock, buf, sizeof buf) < 0) {
2029                 unlink(tempfilename);
2030                 return;
2031         }
2032
2033         CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2034         CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
2035
2036         /*
2037          * Now move the temp file to its permanent location.
2038          */
2039         if (link(tempfilename, permfilename) != 0) {
2040                 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2041                         tempfilename, permfilename, strerror(errno)
2042                 );
2043         }
2044         
2045         unlink(tempfilename);
2046 }
2047
2048
2049
2050 /*
2051  * transmit network spool to the remote system
2052  */
2053 void transmit_spool(int *sock, char *remote_nodename)
2054 {
2055         char buf[SIZ];
2056         char pbuf[4096];
2057         long plen;
2058         long bytes_to_write, thisblock, bytes_written;
2059         int fd;
2060         char sfname[128];
2061
2062         if (sock_puts(sock, "NUOP") < 0) return;
2063         if (sock_getln(sock, buf, sizeof buf) < 0) return;
2064         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2065         if (buf[0] != '2') {
2066                 return;
2067         }
2068
2069         snprintf(sfname, sizeof sfname, 
2070                 "%s/%s",
2071                 ctdl_netout_dir,
2072                 remote_nodename
2073         );
2074         fd = open(sfname, O_RDONLY);
2075         if (fd < 0) {
2076                 if (errno != ENOENT) {
2077                         CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2078                 }
2079                 return;
2080         }
2081         bytes_written = 0;
2082         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2083                 bytes_to_write = plen;
2084                 while (bytes_to_write > 0L) {
2085                         /* Exit if shutting down */
2086                         if (CtdlThreadCheckStop())
2087                         {
2088                                 close(fd);
2089                                 return;
2090                         }
2091                         
2092                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2093                         if (sock_puts(sock, buf) < 0) {
2094                                 close(fd);
2095                                 return;
2096                         }
2097                         if (sock_getln(sock, buf, sizeof buf) < 0) {
2098                                 close(fd);
2099                                 return;
2100                         }
2101                         thisblock = atol(&buf[4]);
2102                         if (buf[0] == '7') {
2103                                 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2104                                         close(fd);
2105                                         return;
2106                                 }
2107                                 bytes_to_write -= thisblock;
2108                                 bytes_written += thisblock;
2109                         } else {
2110                                 goto ABORTUPL;
2111                         }
2112                 }
2113         }
2114
2115 ABORTUPL:
2116         close(fd);
2117
2118         /* Last chance for shutdown exit */
2119         if(CtdlThreadCheckStop())
2120                 return;
2121                 
2122         if (sock_puts(sock, "UCLS 1") < 0) return;
2123
2124         /*
2125          * From here on we must complete or messages will get lost
2126          */
2127         if (sock_getln(sock, buf, sizeof buf) < 0) return;
2128         CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2129         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2130         if (buf[0] == '2') {
2131                 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2132                 unlink(sfname);
2133         }
2134 }
2135
2136
2137
2138 /*
2139  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2140  */
2141 void network_poll_node(char *node, char *secret, char *host, char *port) {
2142         int sock;
2143         char buf[SIZ];
2144         char err_buf[SIZ];
2145         char connected_to[SIZ];
2146         CitContext *CCC=CC;
2147
2148         if (network_talking_to(node, NTT_CHECK)) return;
2149         network_talking_to(node, NTT_ADD);
2150         CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2151         CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2152
2153         sock = sock_connect(host, port);
2154         if (sock < 0) {
2155                 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2156                 network_talking_to(node, NTT_REMOVE);
2157                 return;
2158         }
2159         
2160         CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2161         CCC->sReadBuf = NewStrBuf();
2162         CCC->sMigrateBuf = NewStrBuf();
2163         CCC->sPos = NULL;
2164
2165         /* Read the server greeting */
2166         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2167         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2168
2169         /* Check that the remote is who we think it is and warn the Aide if not */
2170         extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2171         if (strcmp(connected_to, node))
2172         {
2173                 snprintf(err_buf, sizeof(err_buf),
2174                         "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2175                         connected_to, node
2176                 );
2177                 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2178                 CtdlAideMessage(err_buf, "Network error");
2179         }
2180         else {
2181                 /* We're talking to the correct node.  Now identify ourselves. */
2182                 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2183                 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2184                 if (sock_puts(&sock, buf) <0) goto bail;
2185                 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2186                 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2187                 if (buf[0] != '2') {
2188                         goto bail;
2189                 }
2190         
2191                 /* At this point we are authenticated. */
2192                 if (!CtdlThreadCheckStop())
2193                         receive_spool(&sock, node);
2194                 if (!CtdlThreadCheckStop())
2195                         transmit_spool(&sock, node);
2196         }
2197
2198         sock_puts(&sock, "QUIT");
2199 bail:   
2200         FreeStrBuf(&CCC->sReadBuf);
2201         FreeStrBuf(&CCC->sMigrateBuf);
2202         if (sock != -1)
2203                 sock_close(sock);
2204         network_talking_to(node, NTT_REMOVE);
2205 }
2206
2207
2208
2209 /*
2210  * Poll other Citadel nodes and transfer inbound/outbound network data.
2211  * Set "full" to nonzero to force a poll of every node, or to zero to poll
2212  * only nodes to which we have data to send.
2213  */
2214 void network_poll_other_citadel_nodes(int full_poll) {
2215         int i;
2216         char linebuf[256];
2217         char node[SIZ];
2218         char host[256];
2219         char port[256];
2220         char secret[256];
2221         int poll = 0;
2222         char spoolfile[256];
2223
2224         if (working_ignetcfg == NULL) {
2225                 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2226                 return;
2227         }
2228
2229         /* Use the string tokenizer to grab one line at a time */
2230         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2231                 if(CtdlThreadCheckStop())
2232                         return;
2233                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2234                 extract_token(node, linebuf, 0, '|', sizeof node);
2235                 extract_token(secret, linebuf, 1, '|', sizeof secret);
2236                 extract_token(host, linebuf, 2, '|', sizeof host);
2237                 extract_token(port, linebuf, 3, '|', sizeof port);
2238                 if ( !IsEmptyStr(node) && !IsEmptyStr(secret) 
2239                    && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2240                         poll = full_poll;
2241                         if (poll == 0) {
2242                                 snprintf(spoolfile, 
2243                                          sizeof spoolfile,
2244                                          "%s/%s",
2245                                          ctdl_netout_dir, 
2246                                          node
2247                                 );
2248                                 if (access(spoolfile, R_OK) == 0) {
2249                                         poll = 1;
2250                                 }
2251                         }
2252                         if (poll) {
2253                                 network_poll_node(node, secret, host, port);
2254                         }
2255                 }
2256         }
2257
2258 }
2259
2260
2261
2262
2263 /*
2264  * It's ok if these directories already exist.  Just fail silently.
2265  */
2266 void create_spool_dirs(void) {
2267         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2268                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2269         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2270                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2271         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2272                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2273         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2274                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2275         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2276                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2277         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2278                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2279         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2280                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2281         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2282                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2283 }
2284
2285
2286
2287
2288
2289 /*
2290  * network_do_queue()
2291  * 
2292  * Run through the rooms doing various types of network stuff.
2293  */
2294 void network_do_queue(void) {
2295         static time_t last_run = 0L;
2296         struct RoomProcList *ptr;
2297         int full_processing = 1;
2298
2299         /*
2300          * Run the full set of processing tasks no more frequently
2301          * than once every n seconds
2302          */
2303         if ( (time(NULL) - last_run) < config.c_net_freq ) {
2304                 full_processing = 0;
2305                 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2306                         config.c_net_freq - (time(NULL)- last_run)
2307                 );
2308         }
2309
2310         /*
2311          * This is a simple concurrency check to make sure only one queue run
2312          * is done at a time.  We could do this with a mutex, but since we
2313          * don't really require extremely fine granularity here, we'll do it
2314          * with a static variable instead.
2315          */
2316         if (doing_queue) {
2317                 return;
2318         }
2319         doing_queue = 1;
2320
2321         /* Load the IGnet Configuration into memory */
2322         load_working_ignetcfg();
2323
2324         /*
2325          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
2326          * then we poll everyone.  Otherwise we only poll nodes we have stuff
2327          * to send to.
2328          */
2329         network_poll_other_citadel_nodes(full_processing);
2330
2331         /*
2332          * Load the network map and filter list into memory.
2333          */
2334         read_network_map();
2335         filterlist = load_filter_list();
2336
2337         /* 
2338          * Go ahead and run the queue
2339          */
2340         if (full_processing && !CtdlThreadCheckStop()) {
2341                 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2342                 CtdlForEachRoom(network_queue_room, NULL);
2343         }
2344
2345         if (rplist != NULL) {
2346                 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2347                 while (rplist != NULL && !CtdlThreadCheckStop()) {
2348                         char spoolroomname[ROOMNAMELEN];
2349                         safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2350                         begin_critical_section(S_RPLIST);
2351
2352                         /* pop this record off the list */
2353                         ptr = rplist;
2354                         rplist = rplist->next;
2355                         free(ptr);
2356
2357                         /* invalidate any duplicate entries to prevent double processing */
2358                         for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2359                                 if (!strcasecmp(ptr->name, spoolroomname)) {
2360                                         ptr->name[0] = 0;
2361                                 }
2362                         }
2363
2364                         end_critical_section(S_RPLIST);
2365                         if (spoolroomname[0] != 0) {
2366                                 network_spoolout_room(spoolroomname);
2367                         }
2368                 }
2369         }
2370
2371         /* If there is anything in the inbound queue, process it */
2372         if (!CtdlThreadCheckStop()) {
2373                 network_do_spoolin();
2374         }
2375
2376         /* Save the network map back to disk */
2377         write_network_map();
2378
2379         /* Free the filter list in memory */
2380         free_filter_list(filterlist);
2381         filterlist = NULL;
2382
2383         network_consolidate_spoolout();
2384
2385         CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2386
2387         if (full_processing) {
2388                 last_run = time(NULL);
2389         }
2390
2391         doing_queue = 0;
2392 }
2393
2394
2395 /*
2396  * cmd_netp() - authenticate to the server as another Citadel node polling
2397  *            for network traffic
2398  */
2399 void cmd_netp(char *cmdbuf)
2400 {
2401         char node[256];
2402         char pass[256];
2403         int v;
2404
2405         char secret[256];
2406         char nexthop[256];
2407         char err_buf[SIZ];
2408
2409         /* Authenticate */
2410         extract_token(node, cmdbuf, 0, '|', sizeof node);
2411         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2412
2413         /* load the IGnet Configuration to check node validity */
2414         load_working_ignetcfg();
2415         v = is_valid_node(nexthop, secret, node);
2416
2417         if (v != 0) {
2418                 snprintf(err_buf, sizeof err_buf,
2419                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2420                         node, CC->cs_host, CC->cs_addr
2421                 );
2422                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2423                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2424                 CtdlAideMessage(err_buf, "IGNet Networking.");
2425                 return;
2426         }
2427
2428         if (strcasecmp(pass, secret)) {
2429                 snprintf(err_buf, sizeof err_buf,
2430                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2431                         CC->cs_host, CC->cs_addr, node
2432                 );
2433                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2434                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2435                 CtdlAideMessage(err_buf, "IGNet Networking.");
2436                 return;
2437         }
2438
2439         if (network_talking_to(node, NTT_CHECK)) {
2440                 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2441                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2442                 return;
2443         }
2444
2445         safestrncpy(CC->net_node, node, sizeof CC->net_node);
2446         network_talking_to(node, NTT_ADD);
2447         CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2448                 CC->net_node, CC->cs_host, CC->cs_addr
2449         );
2450         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2451 }
2452
2453
2454 int network_room_handler (struct ctdlroom *room)
2455 {
2456         network_queue_room(room, NULL);
2457         return 0;
2458 }
2459
2460 void *ignet_thread(void *arg) {
2461         struct CitContext ignet_thread_CC;
2462
2463         CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2464         CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2465         citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2466
2467         while (!CtdlThreadCheckStop()) {
2468                 network_do_queue();
2469                 CtdlThreadSleep(60);
2470         }
2471
2472         CtdlClearSystemContext();
2473         return(NULL);
2474 }
2475
2476
2477
2478
2479 /*
2480  * Module entry point
2481  */
2482 CTDL_MODULE_INIT(network)
2483 {
2484         if (!threading)
2485         {
2486                 create_spool_dirs();
2487                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2488                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2489                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2490                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2491                 CtdlRegisterRoomHook(network_room_handler);
2492                 CtdlRegisterCleanupHook(destroy_network_queue_room);
2493                 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);
2494         }
2495         return "network";
2496 }