1df6dfd6f47d7a0f91aec88787330637a4e60fc5
[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                         int len, rlen;
686                         char *pCh;
687
688                         if (msg->cm_fields['V'] == NULL){
689                                 /* local message, no enVelope */
690                                 StrBuf *Buf;
691                                 Buf = NewStrBuf();
692                                 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
693                                 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
694                                 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
695                                 
696                                 msg->cm_fields['K'] = SmashStrBuf(&Buf);
697                         }
698                         else {
699                                 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
700                         }
701                         /* Set the 'List-ID' header */
702                         if (msg->cm_fields['L'] != NULL) {
703                                 free(msg->cm_fields['L']);
704                         }
705                         msg->cm_fields['L'] = malloc(1024);
706                         snprintf(msg->cm_fields['L'], 1024,
707                                 "%s <%ld.list-id.%s>",
708                                 CC->room.QRname,
709                                 CC->room.QRnumber,
710                                 config.c_fqdn
711                         );
712
713                         /* Prepend "[List name]" to the subject */
714                         if (msg->cm_fields['U'] == NULL) {
715                                 msg->cm_fields['U'] = strdup("(no subject)");
716                         }
717                         
718                         len  = strlen(msg->cm_fields['U']);
719                         rlen = strlen(CC->room.QRname);
720                         pCh  = strstr(msg->cm_fields['U'], CC->room.QRname);
721                         if ((pCh == NULL) ||
722                             (*(pCh + rlen) != ']') ||
723                             (pCh == msg->cm_fields['U']) ||
724                             (*(pCh - 1) != '[')
725                                 )
726                         {
727                                 char *pBuff;
728
729                                 rlen += len + 4;
730                                 pBuff = malloc (rlen * sizeof(char));
731
732                                 snprintf(pBuff, rlen, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
733                                 free(msg->cm_fields['U']);
734                                 msg->cm_fields['U'] = pBuff;
735                         }
736                         /* else we won't modify the buffer, since the roomname is already here. */
737
738                         /* Set the recipient of the list message to the
739                          * email address of the room itself.
740                          * FIXME ... I want to be able to pick any address
741                          */
742                         if (msg->cm_fields['R'] != NULL) {
743                                 free(msg->cm_fields['R']);
744                         }
745                         msg->cm_fields['R'] = malloc(256);
746                         snprintf(msg->cm_fields['R'], 256,
747                                 "room_%s@%s", CC->room.QRname,
748                                 config.c_fqdn);
749                         for (i=0; msg->cm_fields['R'][i]; ++i) {
750                                 if (isspace(msg->cm_fields['R'][i])) {
751                                         msg->cm_fields['R'][i] = '_';
752                                 }
753                         }
754
755                         /* Handle delivery */
756                         network_deliver_list(msg, sc);
757                         CtdlFreeMessage(msg);
758                 }
759         }
760
761         /*
762          * Process digest recipients
763          */
764         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
765                 msg = CtdlFetchMessage(msgnum, 1);
766                 if (msg != NULL) {
767                         fprintf(sc->digestfp,   " -----------------------------------"
768                                                 "------------------------------------"
769                                                 "-------\n");
770                         fprintf(sc->digestfp, "From: ");
771                         if (msg->cm_fields['A'] != NULL) {
772                                 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
773                         }
774                         if (msg->cm_fields['F'] != NULL) {
775                                 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
776                         }
777                         else if (msg->cm_fields['N'] != NULL) {
778                                 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
779                         }
780                         fprintf(sc->digestfp, "\n");
781                         if (msg->cm_fields['U'] != NULL) {
782                                 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
783                         }
784
785                         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
786                         
787                         safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
788                         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
789
790                         StrBufTrim(CC->redirect_buffer);
791                         fwrite(HKEY("\n"), 1, sc->digestfp);
792                         fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
793                         fwrite(HKEY("\n"), 1, sc->digestfp);
794
795                         FreeStrBuf(&CC->redirect_buffer);
796
797                         sc->num_msgs_spooled += 1;
798                         free(msg);
799                 }
800         }
801
802         /*
803          * Process client-side list participations for this room
804          */
805         instr_len = SIZ;
806         if (sc->participates != NULL) {
807                 msg = CtdlFetchMessage(msgnum, 1);
808                 if (msg != NULL) {
809
810                         /* Only send messages which originated on our own Citadel
811                          * network, otherwise we'll end up sending the remote
812                          * mailing list's messages back to it, which is rude...
813                          */
814                         ok_to_participate = 0;
815                         if (msg->cm_fields['N'] != NULL) {
816                                 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
817                                         ok_to_participate = 1;
818                                 }
819                                 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
820                                         ok_to_participate = 1;
821                                 }
822                         }
823                         if (ok_to_participate) {
824                                 if (msg->cm_fields['F'] != NULL) {
825                                         free(msg->cm_fields['F']);
826                                 }
827                                 msg->cm_fields['F'] = malloc(SIZ);
828                                 /* Replace the Internet email address of the actual
829                                 * author with the email address of the room itself,
830                                 * so the remote listserv doesn't reject us.
831                                 * FIXME ... I want to be able to pick any address
832                                 */
833                                 snprintf(msg->cm_fields['F'], SIZ,
834                                         "room_%s@%s", CC->room.QRname,
835                                         config.c_fqdn);
836                                 for (i=0; msg->cm_fields['F'][i]; ++i) {
837                                         if (isspace(msg->cm_fields['F'][i])) {
838                                                 msg->cm_fields['F'][i] = '_';
839                                         }
840                                 }
841
842                                 /* 
843                                  * Figure out how big a buffer we need to allocate
844                                  */
845                                 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
846
847                                         if (msg->cm_fields['R'] == NULL) {
848                                                 free(msg->cm_fields['R']);
849                                         }
850                                         msg->cm_fields['R'] = strdup(nptr->name);
851         
852                                         valid = validate_recipients(nptr->name, NULL, 0);
853                                         CtdlSubmitMsg(msg, valid, "", 0);
854                                         free_recipients(valid);
855                                 }
856                         
857                         }
858                         CtdlFreeMessage(msg);
859                 }
860         }
861         
862         /*
863          * Process IGnet push shares
864          */
865         msg = CtdlFetchMessage(msgnum, 1);
866         if (msg != NULL) {
867                 size_t newpath_len;
868
869                 /* Prepend our node name to the Path field whenever
870                  * sending a message to another IGnet node
871                  */
872                 if (msg->cm_fields['P'] == NULL) {
873                         msg->cm_fields['P'] = strdup("username");
874                 }
875                 newpath_len = strlen(msg->cm_fields['P']) +
876                          strlen(config.c_nodename) + 2;
877                 newpath = malloc(newpath_len);
878                 snprintf(newpath, newpath_len, "%s!%s",
879                          config.c_nodename, msg->cm_fields['P']);
880                 free(msg->cm_fields['P']);
881                 msg->cm_fields['P'] = newpath;
882
883                 /*
884                  * Determine if this message is set to be deleted
885                  * after sending out on the network
886                  */
887                 if (msg->cm_fields['S'] != NULL) {
888                         if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
889                                 delete_after_send = 1;
890                         }
891                 }
892
893                 /* Now send it to every node */
894                 if (sc->ignet_push_shares != NULL)
895                   for (mptr = sc->ignet_push_shares; mptr != NULL;
896                     mptr = mptr->next) {
897
898                         send = 1;
899
900                         /* Check for valid node name */
901                         if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
902                                 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
903                                 send = 0;
904                         }
905
906                         /* Check for split horizon */
907                         CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
908                         bang = num_tokens(msg->cm_fields['P'], '!');
909                         if (bang > 1) for (i=0; i<(bang-1); ++i) {
910                                 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
911                                 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
912                                         buf, mptr->remote_nodename) ;
913                                 if (!strcasecmp(buf, mptr->remote_nodename)) {
914                                         send = 0;
915                                         CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
916                                                 mptr->remote_nodename);
917                                 }
918                                 else {
919                                         CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
920                                 }
921                         }
922
923                         /* Send the message */
924                         if (send == 1) {
925
926                                 /*
927                                  * Force the message to appear in the correct room
928                                  * on the far end by setting the C field correctly
929                                  */
930                                 if (msg->cm_fields['C'] != NULL) {
931                                         free(msg->cm_fields['C']);
932                                 }
933                                 if (!IsEmptyStr(mptr->remote_roomname)) {
934                                         msg->cm_fields['C'] = strdup(mptr->remote_roomname);
935                                 }
936                                 else {
937                                         msg->cm_fields['C'] = strdup(CC->room.QRname);
938                                 }
939
940                                 /* serialize it for transmission */
941                                 serialize_message(&sermsg, msg);
942                                 if (sermsg.len > 0) {
943
944                                         /* write it to a spool file */
945                                         snprintf(filename, sizeof filename,"%s/%s@%lx%x",
946                                                 ctdl_netout_dir,
947                                                 mptr->remote_nodename,
948                                                 time(NULL),
949                                                 rand()
950                                         );
951                                         CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
952                                         fp = fopen(filename, "ab");
953                                         if (fp != NULL) {
954                                                 fwrite(sermsg.ser,
955                                                         sermsg.len, 1, fp);
956                                                 fclose(fp);
957                                         }
958                                         else {
959                                                 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
960                                         }
961         
962                                         /* free the serialized version */
963                                         free(sermsg.ser);
964                                 }
965
966                         }
967                 }
968                 CtdlFreeMessage(msg);
969         }
970
971         /* update lastsent */
972         sc->lastsent = msgnum;
973
974         /* Delete this message if delete-after-send is set */
975         if (delete_after_send) {
976                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
977         }
978
979 }
980         
981
982 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
983 {
984         FILE *fp;
985         char instr[SIZ];
986         char buf[SIZ];
987         char nodename[256];
988         char roomname[ROOMNAMELEN];
989         size_t miscsize = 0;
990         size_t linesize = 0;
991         int skipthisline = 0;
992         namelist *nptr = NULL;
993         maplist *mptr = NULL;
994         SpoolControl *sc;
995
996         fp = fopen(filename, "r");
997         if (fp == NULL) {
998                 return 0;
999         }
1000         sc = malloc(sizeof(SpoolControl));
1001         memset(sc, 0, sizeof(SpoolControl));
1002         *scc = sc;
1003
1004         while (fgets(buf, sizeof buf, fp) != NULL) {
1005                 buf[strlen(buf)-1] = 0;
1006
1007                 extract_token(instr, buf, 0, '|', sizeof instr);
1008                 if (!strcasecmp(instr, strof(lastsent))) {
1009                         sc->lastsent = extract_long(buf, 1);
1010                 }
1011                 else if (!strcasecmp(instr, strof(listrecp))) {
1012                         nptr = (namelist *)
1013                                 malloc(sizeof(namelist));
1014                         nptr->next = sc->listrecps;
1015                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1016                         sc->listrecps = nptr;
1017                 }
1018                 else if (!strcasecmp(instr, strof(participate))) {
1019                         nptr = (namelist *)
1020                                 malloc(sizeof(namelist));
1021                         nptr->next = sc->participates;
1022                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1023                         sc->participates = nptr;
1024                 }
1025                 else if (!strcasecmp(instr, strof(digestrecp))) {
1026                         nptr = (namelist *)
1027                                 malloc(sizeof(namelist));
1028                         nptr->next = sc->digestrecps;
1029                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1030                         sc->digestrecps = nptr;
1031                 }
1032                 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1033                         extract_token(nodename, buf, 1, '|', sizeof nodename);
1034                         extract_token(roomname, buf, 2, '|', sizeof roomname);
1035                         mptr = (maplist *) malloc(sizeof(maplist));
1036                         mptr->next = sc->ignet_push_shares;
1037                         strcpy(mptr->remote_nodename, nodename);
1038                         strcpy(mptr->remote_roomname, roomname);
1039                         sc->ignet_push_shares = mptr;
1040                 }
1041                 else {
1042                         /* Preserve 'other' lines ... *unless* they happen to
1043                          * be subscribe/unsubscribe pendings with expired
1044                          * timestamps.
1045                          */
1046                         skipthisline = 0;
1047                         if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1048                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
1049                                         skipthisline = 1;
1050                                 }
1051                         }
1052                         if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1053                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
1054                                         skipthisline = 1;
1055                                 }
1056                         }
1057
1058                         if (skipthisline == 0) {
1059                                 linesize = strlen(buf);
1060                                 sc->misc = realloc(sc->misc,
1061                                         (miscsize + linesize + 2) );
1062                                 sprintf(&sc->misc[miscsize], "%s\n", buf);
1063                                 miscsize = miscsize + linesize + 1;
1064                         }
1065                 }
1066
1067
1068         }
1069         fclose(fp);
1070         return 1;
1071 }
1072
1073 void free_spoolcontrol_struct(SpoolControl **scc)
1074 {
1075         SpoolControl *sc;
1076         namelist *nptr = NULL;
1077         maplist *mptr = NULL;
1078
1079         sc = *scc;
1080         while (sc->listrecps != NULL) {
1081                 nptr = sc->listrecps->next;
1082                 free(sc->listrecps);
1083                 sc->listrecps = nptr;
1084         }
1085         /* Do the same for digestrecps */
1086         while (sc->digestrecps != NULL) {
1087                 nptr = sc->digestrecps->next;
1088                 free(sc->digestrecps);
1089                 sc->digestrecps = nptr;
1090         }
1091         /* Do the same for participates */
1092         while (sc->participates != NULL) {
1093                 nptr = sc->participates->next;
1094                 free(sc->participates);
1095                 sc->participates = nptr;
1096         }
1097         while (sc->ignet_push_shares != NULL) {
1098                 mptr = sc->ignet_push_shares->next;
1099                 free(sc->ignet_push_shares);
1100                 sc->ignet_push_shares = mptr;
1101         }
1102         free(sc->misc);
1103         free(sc);
1104         *scc=NULL;
1105 }
1106
1107 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1108 {
1109         char tempfilename[PATH_MAX];
1110         int TmpFD;
1111         SpoolControl *sc;
1112         namelist *nptr = NULL;
1113         maplist *mptr = NULL;
1114         long len;
1115         time_t unixtime;
1116         struct timeval tv;
1117         long reltid; /* if we don't have SYS_gettid, use "random" value */
1118         StrBuf *Cfg;
1119         int rc;
1120
1121         len = strlen(filename);
1122         memcpy(tempfilename, filename, len + 1);
1123
1124
1125 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1126         reltid = syscall(SYS_gettid);
1127 #endif
1128         gettimeofday(&tv, NULL);
1129         /* Promote to time_t; types differ on some OSes (like darwin) */
1130         unixtime = tv.tv_sec;
1131
1132         sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1133         sc = *scc;
1134         errno = 0;
1135         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1136         Cfg = NewStrBuf();
1137         if ((TmpFD < 0) || (errno != 0)) {
1138                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1139                         filename, strerror(errno));
1140                 free_spoolcontrol_struct(scc);
1141                 unlink(tempfilename);
1142         }
1143         else {
1144                 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1145
1146                 /* Write out the listrecps while freeing from memory at the
1147                  * same time.  Am I clever or what?  :)
1148                  */
1149                 while (sc->listrecps != NULL) {
1150                         StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1151                         nptr = sc->listrecps->next;
1152                         free(sc->listrecps);
1153                         sc->listrecps = nptr;
1154                 }
1155                 /* Do the same for digestrecps */
1156                 while (sc->digestrecps != NULL) {
1157                         StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1158                         nptr = sc->digestrecps->next;
1159                         free(sc->digestrecps);
1160                         sc->digestrecps = nptr;
1161                 }
1162                 /* Do the same for participates */
1163                 while (sc->participates != NULL) {
1164                         StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1165                         nptr = sc->participates->next;
1166                         free(sc->participates);
1167                         sc->participates = nptr;
1168                 }
1169                 while (sc->ignet_push_shares != NULL) {
1170                         StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1171                         if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1172                                 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1173                         }
1174                         StrBufAppendPrintf(Cfg, "\n");
1175                         mptr = sc->ignet_push_shares->next;
1176                         free(sc->ignet_push_shares);
1177                         sc->ignet_push_shares = mptr;
1178                 }
1179                 if (sc->misc != NULL) {
1180                         StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1181                 }
1182                 free(sc->misc);
1183
1184                 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1185                 if ((rc >=0 ) && (rc == StrLength(Cfg))) 
1186                 {
1187                         close(TmpFD);
1188                         rename(tempfilename, filename);
1189                 }
1190                 else {
1191                         CtdlLogPrintf(CTDL_EMERG, 
1192                                       "unable to write %s; [%s]; not enough space on the disk?\n", 
1193                                       tempfilename, 
1194                                       strerror(errno));
1195                         close(TmpFD);
1196                         unlink(tempfilename);
1197                 }
1198                 FreeStrBuf(&Cfg);
1199                 free(sc);
1200                 *scc=NULL;
1201         }
1202         return 1;
1203 }
1204 int is_recipient(SpoolControl *sc, const char *Name)
1205 {
1206         namelist *nptr;
1207         size_t len;
1208
1209         len = strlen(Name);
1210         nptr = sc->listrecps;
1211         while (nptr != NULL) {
1212                 if (strncmp(Name, nptr->name, len)==0)
1213                         return 1;
1214                 nptr = nptr->next;
1215         }
1216         /* Do the same for digestrecps */
1217         nptr = sc->digestrecps;
1218         while (nptr != NULL) {
1219                 if (strncmp(Name, nptr->name, len)==0)
1220                         return 1;
1221                 nptr = nptr->next;
1222         }
1223         /* Do the same for participates */
1224         nptr = sc->participates;
1225         while (nptr != NULL) {
1226                 if (strncmp(Name, nptr->name, len)==0)
1227                         return 1;
1228                 nptr = nptr->next;
1229         }
1230         return 0;
1231 }
1232
1233
1234 /*
1235  * Batch up and send all outbound traffic from the current room
1236  */
1237 void network_spoolout_room(char *room_to_spool) {
1238         char buf[SIZ];
1239         char filename[PATH_MAX];
1240         SpoolControl *sc;
1241         int i;
1242
1243         /*
1244          * If the room doesn't exist, don't try to perform its networking tasks.
1245          * Normally this should never happen, but once in a while maybe a room gets
1246          * queued for networking and then deleted before it can happen.
1247          */
1248         if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1249                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1250                 return;
1251         }
1252
1253         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1254         begin_critical_section(S_NETCONFIGS);
1255
1256         /* Only do net processing for rooms that have netconfigs */
1257         if (!read_spoolcontrol_file(&sc, filename))
1258         {
1259                 end_critical_section(S_NETCONFIGS);
1260                 return;
1261         }
1262         CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1263
1264         /* If there are digest recipients, we have to build a digest */
1265         if (sc->digestrecps != NULL) {
1266                 sc->digestfp = tmpfile();
1267                 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1268         }
1269
1270         /* Do something useful */
1271         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1272                 network_spool_msg, sc);
1273
1274         /* If we wrote a digest, deliver it and then close it */
1275         snprintf(buf, sizeof buf, "room_%s@%s",
1276                 CC->room.QRname, config.c_fqdn);
1277         for (i=0; buf[i]; ++i) {
1278                 buf[i] = tolower(buf[i]);
1279                 if (isspace(buf[i])) buf[i] = '_';
1280         }
1281         if (sc->digestfp != NULL) {
1282                 fprintf(sc->digestfp,   " -----------------------------------"
1283                                         "------------------------------------"
1284                                         "-------\n"
1285                                         "You are subscribed to the '%s' "
1286                                         "list.\n"
1287                                         "To post to the list: %s\n",
1288                                         CC->room.QRname, buf
1289                 );
1290                 network_deliver_digest(sc);     /* deliver and close */
1291         }
1292
1293         /* Now rewrite the config file */
1294         writenfree_spoolcontrol_file (&sc, filename);
1295         end_critical_section(S_NETCONFIGS);
1296 }
1297
1298
1299
1300 /*
1301  * Send the *entire* contents of the current room to one specific network node,
1302  * ignoring anything we know about which messages have already undergone
1303  * network processing.  This can be used to bring a new node into sync.
1304  */
1305 int network_sync_to(char *target_node) {
1306         SpoolControl sc;
1307         int num_spooled = 0;
1308         int found_node = 0;
1309         char buf[256];
1310         char sc_type[256];
1311         char sc_node[256];
1312         char sc_room[256];
1313         char filename[PATH_MAX];
1314         FILE *fp;
1315
1316         /* Grab the configuration line we're looking for */
1317         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1318         begin_critical_section(S_NETCONFIGS);
1319         fp = fopen(filename, "r");
1320         if (fp == NULL) {
1321                 end_critical_section(S_NETCONFIGS);
1322                 return(-1);
1323         }
1324         while (fgets(buf, sizeof buf, fp) != NULL) {
1325                 buf[strlen(buf)-1] = 0;
1326                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1327                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1328                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1329                 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1330                    && (!strcasecmp(sc_node, target_node)) ) {
1331                         found_node = 1;
1332                         
1333                         /* Concise syntax because we don't need a full linked-list */
1334                         memset(&sc, 0, sizeof(SpoolControl));
1335                         sc.ignet_push_shares = (maplist *)
1336                                 malloc(sizeof(maplist));
1337                         sc.ignet_push_shares->next = NULL;
1338                         safestrncpy(sc.ignet_push_shares->remote_nodename,
1339                                 sc_node,
1340                                 sizeof sc.ignet_push_shares->remote_nodename);
1341                         safestrncpy(sc.ignet_push_shares->remote_roomname,
1342                                 sc_room,
1343                                 sizeof sc.ignet_push_shares->remote_roomname);
1344                 }
1345         }
1346         fclose(fp);
1347         end_critical_section(S_NETCONFIGS);
1348
1349         if (!found_node) return(-1);
1350
1351         /* Send ALL messages */
1352         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1353                 network_spool_msg, &sc);
1354
1355         /* Concise cleanup because we know there's only one node in the sc */
1356         free(sc.ignet_push_shares);
1357
1358         CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1359                 num_spooled, target_node);
1360         return(num_spooled);
1361 }
1362
1363
1364 /*
1365  * Implements the NSYN command
1366  */
1367 void cmd_nsyn(char *argbuf) {
1368         int num_spooled;
1369         char target_node[256];
1370
1371         if (CtdlAccessCheck(ac_aide)) return;
1372
1373         extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1374         num_spooled = network_sync_to(target_node);
1375         if (num_spooled >= 0) {
1376                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1377         }
1378         else {
1379                 cprintf("%d No such room/node share exists.\n",
1380                         ERROR + ROOM_NOT_FOUND);
1381         }
1382 }
1383
1384
1385
1386 /*
1387  * Batch up and send all outbound traffic from the current room
1388  */
1389 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1390         struct RoomProcList *ptr;
1391
1392         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1393         if (ptr == NULL) return;
1394
1395         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1396         begin_critical_section(S_RPLIST);
1397         ptr->next = rplist;
1398         rplist = ptr;
1399         end_critical_section(S_RPLIST);
1400 }
1401
1402 void destroy_network_queue_room(void)
1403 {
1404         struct RoomProcList *cur, *p;
1405         NetMap *nmcur, *nmp;
1406
1407         cur = rplist;
1408         begin_critical_section(S_RPLIST);
1409         while (cur != NULL)
1410         {
1411                 p = cur->next;
1412                 free (cur);
1413                 cur = p;                
1414         }
1415         rplist = NULL;
1416         end_critical_section(S_RPLIST);
1417
1418         nmcur = the_netmap;
1419         while (nmcur != NULL)
1420         {
1421                 nmp = nmcur->next;
1422                 free (nmcur);
1423                 nmcur = nmp;            
1424         }
1425         the_netmap = NULL;
1426         if (working_ignetcfg != NULL)
1427                 free (working_ignetcfg);
1428         working_ignetcfg = NULL;
1429 }
1430
1431
1432 /*
1433  * Learn topology from path fields
1434  */
1435 void network_learn_topology(char *node, char *path) {
1436         char nexthop[256];
1437         NetMap *nmptr;
1438
1439         strcpy(nexthop, "");
1440
1441         if (num_tokens(path, '!') < 3) return;
1442         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1443                 if (!strcasecmp(nmptr->nodename, node)) {
1444                         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1445                         nmptr->lastcontact = time(NULL);
1446                         ++netmap_changed;
1447                         return;
1448                 }
1449         }
1450
1451         /* If we got here then it's not in the map, so add it. */
1452         nmptr = (NetMap *) malloc(sizeof (NetMap));
1453         strcpy(nmptr->nodename, node);
1454         nmptr->lastcontact = time(NULL);
1455         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1456         nmptr->next = the_netmap;
1457         the_netmap = nmptr;
1458         ++netmap_changed;
1459 }
1460
1461
1462
1463
1464 /*
1465  * Bounce a message back to the sender
1466  */
1467 void network_bounce(struct CtdlMessage *msg, char *reason) {
1468         char *oldpath = NULL;
1469         char buf[SIZ];
1470         char bouncesource[SIZ];
1471         char recipient[SIZ];
1472         struct recptypes *valid = NULL;
1473         char force_room[ROOMNAMELEN];
1474         static int serialnum = 0;
1475         size_t size;
1476
1477         CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1478
1479         if (msg == NULL) return;
1480
1481         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1482
1483         /* 
1484          * Give it a fresh message ID
1485          */
1486         if (msg->cm_fields['I'] != NULL) {
1487                 free(msg->cm_fields['I']);
1488         }
1489         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1490                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1491         msg->cm_fields['I'] = strdup(buf);
1492
1493         /*
1494          * FIXME ... right now we're just sending a bounce; we really want to
1495          * include the text of the bounced message.
1496          */
1497         if (msg->cm_fields['M'] != NULL) {
1498                 free(msg->cm_fields['M']);
1499         }
1500         msg->cm_fields['M'] = strdup(reason);
1501         msg->cm_format_type = 0;
1502
1503         /*
1504          * Turn the message around
1505          */
1506         if (msg->cm_fields['R'] == NULL) {
1507                 free(msg->cm_fields['R']);
1508         }
1509
1510         if (msg->cm_fields['D'] == NULL) {
1511                 free(msg->cm_fields['D']);
1512         }
1513
1514         snprintf(recipient, sizeof recipient, "%s@%s",
1515                 msg->cm_fields['A'], msg->cm_fields['N']);
1516
1517         if (msg->cm_fields['A'] == NULL) {
1518                 free(msg->cm_fields['A']);
1519         }
1520
1521         if (msg->cm_fields['N'] == NULL) {
1522                 free(msg->cm_fields['N']);
1523         }
1524
1525         if (msg->cm_fields['U'] == NULL) {
1526                 free(msg->cm_fields['U']);
1527         }
1528
1529         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1530         msg->cm_fields['N'] = strdup(config.c_nodename);
1531         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1532
1533         /* prepend our node to the path */
1534         if (msg->cm_fields['P'] != NULL) {
1535                 oldpath = msg->cm_fields['P'];
1536                 msg->cm_fields['P'] = NULL;
1537         }
1538         else {
1539                 oldpath = strdup("unknown_user");
1540         }
1541         size = strlen(oldpath) + SIZ;
1542         msg->cm_fields['P'] = malloc(size);
1543         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1544         free(oldpath);
1545
1546         /* Now submit the message */
1547         valid = validate_recipients(recipient, NULL, 0);
1548         if (valid != NULL) if (valid->num_error != 0) {
1549                 free_recipients(valid);
1550                 valid = NULL;
1551         }
1552         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1553                 strcpy(force_room, config.c_aideroom);
1554         }
1555         else {
1556                 strcpy(force_room, "");
1557         }
1558         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1559                 strcpy(force_room, config.c_aideroom);
1560         }
1561         CtdlSubmitMsg(msg, valid, force_room, 0);
1562
1563         /* Clean up */
1564         if (valid != NULL) free_recipients(valid);
1565         CtdlFreeMessage(msg);
1566         CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1567 }
1568
1569
1570
1571
1572 /*
1573  * Process a buffer containing a single message from a single file
1574  * from the inbound queue 
1575  */
1576 void network_process_buffer(char *buffer, long size) {
1577         struct CtdlMessage *msg = NULL;
1578         long pos;
1579         int field;
1580         struct recptypes *recp = NULL;
1581         char target_room[ROOMNAMELEN];
1582         struct ser_ret sermsg;
1583         char *oldpath = NULL;
1584         char filename[PATH_MAX];
1585         FILE *fp;
1586         char nexthop[SIZ];
1587         unsigned char firstbyte;
1588         unsigned char lastbyte;
1589
1590         CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1591
1592         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
1593         firstbyte = buffer[0];
1594         lastbyte = buffer[size-1];
1595         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1596                 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
1597                         size, firstbyte, lastbyte);
1598                 return;
1599         }
1600
1601         /* Set default target room to trash */
1602         strcpy(target_room, TWITROOM);
1603
1604         /* Load the message into memory */
1605         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1606         memset(msg, 0, sizeof(struct CtdlMessage));
1607         msg->cm_magic = CTDLMESSAGE_MAGIC;
1608         msg->cm_anon_type = buffer[1];
1609         msg->cm_format_type = buffer[2];
1610
1611         for (pos = 3; pos < size; ++pos) {
1612                 field = buffer[pos];
1613                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1614                 pos = pos + strlen(&buffer[(int)pos]);
1615         }
1616
1617         /* Check for message routing */
1618         if (msg->cm_fields['D'] != NULL) {
1619                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1620
1621                         /* route the message */
1622                         strcpy(nexthop, "");
1623                         if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1624                                 /* prepend our node to the path */
1625                                 if (msg->cm_fields['P'] != NULL) {
1626                                         oldpath = msg->cm_fields['P'];
1627                                         msg->cm_fields['P'] = NULL;
1628                                 }
1629                                 else {
1630                                         oldpath = strdup("unknown_user");
1631                                 }
1632                                 size = strlen(oldpath) + SIZ;
1633                                 msg->cm_fields['P'] = malloc(size);
1634                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1635                                         config.c_nodename, oldpath);
1636                                 free(oldpath);
1637
1638                                 /* serialize the message */
1639                                 serialize_message(&sermsg, msg);
1640
1641                                 /* now send it */
1642                                 if (IsEmptyStr(nexthop)) {
1643                                         strcpy(nexthop, msg->cm_fields['D']);
1644                                 }
1645                                 snprintf(filename, 
1646                                         sizeof filename,
1647                                         "%s/%s@%lx%x",
1648                                         ctdl_netout_dir,
1649                                         nexthop,
1650                                         time(NULL),
1651                                         rand()
1652                                 );
1653                                 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1654                                 fp = fopen(filename, "ab");
1655                                 if (fp != NULL) {
1656                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
1657                                         fclose(fp);
1658                                 }
1659                                 else {
1660                                         CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1661                                 }
1662                                 free(sermsg.ser);
1663                                 CtdlFreeMessage(msg);
1664                                 return;
1665                         }
1666                         
1667                         else {  /* invalid destination node name */
1668
1669                                 network_bounce(msg,
1670 "A message you sent could not be delivered due to an invalid destination node"
1671 " name.  Please check the address and try sending the message again.\n");
1672                                 msg = NULL;
1673                                 return;
1674
1675                         }
1676                 }
1677         }
1678
1679         /*
1680          * Check to see if we already have a copy of this message, and
1681          * abort its processing if so.  (We used to post a warning to Aide>
1682          * every time this happened, but the network is now so densely
1683          * connected that it's inevitable.)
1684          */
1685         if (network_usetable(msg) != 0) {
1686                 CtdlFreeMessage(msg);
1687                 return;
1688         }
1689
1690         /* Learn network topology from the path */
1691         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1692                 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1693         }
1694
1695         /* Is the sending node giving us a very persuasive suggestion about
1696          * which room this message should be saved in?  If so, go with that.
1697          */
1698         if (msg->cm_fields['C'] != NULL) {
1699                 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1700         }
1701
1702         /* Otherwise, does it have a recipient?  If so, validate it... */
1703         else if (msg->cm_fields['R'] != NULL) {
1704                 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1705                 if (recp != NULL) if (recp->num_error != 0) {
1706                         network_bounce(msg,
1707                                 "A message you sent could not be delivered due to an invalid address.\n"
1708                                 "Please check the address and try sending the message again.\n");
1709                         msg = NULL;
1710                         free_recipients(recp);
1711                         CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1712                         return;
1713                 }
1714                 strcpy(target_room, "");        /* no target room if mail */
1715         }
1716
1717         /* Our last shot at finding a home for this message is to see if
1718          * it has the O field (Originating room) set.
1719          */
1720         else if (msg->cm_fields['O'] != NULL) {
1721                 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1722         }
1723
1724         /* Strip out fields that are only relevant during transit */
1725         if (msg->cm_fields['D'] != NULL) {
1726                 free(msg->cm_fields['D']);
1727                 msg->cm_fields['D'] = NULL;
1728         }
1729         if (msg->cm_fields['C'] != NULL) {
1730                 free(msg->cm_fields['C']);
1731                 msg->cm_fields['C'] = NULL;
1732         }
1733
1734         /* save the message into a room */
1735         if (PerformNetprocHooks(msg, target_room) == 0) {
1736                 msg->cm_flags = CM_SKIP_HOOKS;
1737                 CtdlSubmitMsg(msg, recp, target_room, 0);
1738         }
1739         CtdlFreeMessage(msg);
1740         free_recipients(recp);
1741 }
1742
1743
1744 /*
1745  * Process a single message from a single file from the inbound queue 
1746  */
1747 void network_process_message(FILE *fp, long msgstart, long msgend) {
1748         long hold_pos;
1749         long size;
1750         char *buffer;
1751
1752         hold_pos = ftell(fp);
1753         size = msgend - msgstart + 1;
1754         buffer = malloc(size);
1755         if (buffer != NULL) {
1756                 fseek(fp, msgstart, SEEK_SET);
1757                 if (fread(buffer, size, 1, fp) > 0) {
1758                         network_process_buffer(buffer, size);
1759                 }
1760                 free(buffer);
1761         }
1762
1763         fseek(fp, hold_pos, SEEK_SET);
1764 }
1765
1766
1767 /*
1768  * Process a single file from the inbound queue 
1769  */
1770 void network_process_file(char *filename) {
1771         FILE *fp;
1772         long msgstart = (-1L);
1773         long msgend = (-1L);
1774         long msgcur = 0L;
1775         int ch;
1776
1777
1778         fp = fopen(filename, "rb");
1779         if (fp == NULL) {
1780                 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1781                 return;
1782         }
1783
1784         fseek(fp, 0L, SEEK_END);
1785         CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1786         rewind(fp);
1787
1788         /* Look for messages in the data stream and break them out */
1789         while (ch = getc(fp), ch >= 0) {
1790         
1791                 if (ch == 255) {
1792                         if (msgstart >= 0L) {
1793                                 msgend = msgcur - 1;
1794                                 network_process_message(fp, msgstart, msgend);
1795                         }
1796                         msgstart = msgcur;
1797                 }
1798
1799                 ++msgcur;
1800         }
1801
1802         msgend = msgcur - 1;
1803         if (msgstart >= 0L) {
1804                 network_process_message(fp, msgstart, msgend);
1805         }
1806
1807         fclose(fp);
1808         unlink(filename);
1809 }
1810
1811
1812 /*
1813  * Process anything in the inbound queue
1814  */
1815 void network_do_spoolin(void) {
1816         DIR *dp;
1817         struct dirent *d;
1818         struct stat statbuf;
1819         char filename[PATH_MAX];
1820         static time_t last_spoolin_mtime = 0L;
1821
1822         /*
1823          * Check the spoolin directory's modification time.  If it hasn't
1824          * been touched, we don't need to scan it.
1825          */
1826         if (stat(ctdl_netin_dir, &statbuf)) return;
1827         if (statbuf.st_mtime == last_spoolin_mtime) {
1828                 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1829                 return;
1830         }
1831         last_spoolin_mtime = statbuf.st_mtime;
1832         CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1833
1834         /*
1835          * Ok, there's something interesting in there, so scan it.
1836          */
1837         dp = opendir(ctdl_netin_dir);
1838         if (dp == NULL) return;
1839
1840         while (d = readdir(dp), d != NULL) {
1841                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1842                         snprintf(filename, 
1843                                 sizeof filename,
1844                                 "%s/%s",
1845                                 ctdl_netin_dir,
1846                                 d->d_name
1847                         );
1848                         network_process_file(filename);
1849                 }
1850         }
1851
1852         closedir(dp);
1853 }
1854
1855 /*
1856  * Step 1: consolidate files in the outbound queue into one file per neighbor node
1857  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1858  */
1859 void network_consolidate_spoolout(void) {
1860         DIR *dp;
1861         struct dirent *d;
1862         char filename[PATH_MAX];
1863         char cmd[PATH_MAX];
1864         char nexthop[256];
1865         int i;
1866         char *ptr;
1867
1868         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1869         dp = opendir(ctdl_netout_dir);
1870         if (dp == NULL) return;
1871         while (d = readdir(dp), d != NULL) {
1872                 if (
1873                         (strcmp(d->d_name, "."))
1874                         && (strcmp(d->d_name, ".."))
1875                         && (strchr(d->d_name, '@') != NULL)
1876                 ) {
1877                         safestrncpy(nexthop, d->d_name, sizeof nexthop);
1878                         ptr = strchr(nexthop, '@');
1879                         if (ptr) *ptr = 0;
1880         
1881                         snprintf(filename, 
1882                                 sizeof filename,
1883                                 "%s/%s",
1884                                 ctdl_netout_dir,
1885                                 d->d_name
1886                         );
1887         
1888                         CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1889                         if (network_talking_to(nexthop, NTT_CHECK)) {
1890                                 CtdlLogPrintf(CTDL_DEBUG,
1891                                         "Currently online with %s - skipping for now\n",
1892                                         nexthop
1893                                 );
1894                         }
1895                         else {
1896                                 network_talking_to(nexthop, NTT_ADD);
1897                                 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1898                                         filename,
1899                                         ctdl_netout_dir, nexthop,
1900                                         filename
1901                                 );
1902                                 system(cmd);
1903                                 network_talking_to(nexthop, NTT_REMOVE);
1904                         }
1905                 }
1906         }
1907         closedir(dp);
1908
1909         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1910
1911         dp = opendir(ctdl_netout_dir);
1912         if (dp == NULL) return;
1913
1914         while (d = readdir(dp), d != NULL) {
1915                 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1916                         continue;
1917                 ptr = strchr(d->d_name, '@');
1918                 if (d != NULL)
1919                         continue;
1920                 snprintf(filename, 
1921                         sizeof filename,
1922                         "%s/%s",
1923                         ctdl_netout_dir,
1924                         d->d_name
1925                 );
1926
1927                 strcpy(nexthop, "");
1928                 i = is_valid_node(nexthop, NULL, d->d_name);
1929         
1930                 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1931                         unlink(filename);
1932                 }
1933         }
1934
1935
1936         closedir(dp);
1937 }
1938
1939
1940 /*
1941  * receive network spool from the remote system
1942  */
1943 void receive_spool(int *sock, char *remote_nodename) {
1944         int download_len = 0L;
1945         int bytes_received = 0L;
1946         char buf[SIZ];
1947         char tempfilename[PATH_MAX];
1948         char permfilename[PATH_MAX];
1949         int plen;
1950         FILE *fp;
1951
1952         snprintf(tempfilename, 
1953                 sizeof tempfilename, 
1954                 "%s/%s.%lx%x",
1955                 ctdl_nettmp_dir,
1956                 remote_nodename, 
1957                 time(NULL),
1958                 rand()
1959         );
1960
1961         snprintf(permfilename, 
1962                 sizeof permfilename, 
1963                 "%s/%s.%lx%x",
1964                 ctdl_netin_dir,
1965                 remote_nodename, 
1966                 time(NULL),
1967                 rand()
1968         );
1969
1970         if (sock_puts(sock, "NDOP") < 0) return;
1971         if (sock_getln(sock, buf, sizeof buf) < 0) return;
1972         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1973         if (buf[0] != '2') {
1974                 return;
1975         }
1976
1977         download_len = extract_long(&buf[4], 0);
1978         if (download_len <= 0) {
1979                 return;
1980         }
1981
1982         bytes_received = 0L;
1983         fp = fopen(tempfilename, "w");
1984         if (fp == NULL) {
1985                 CtdlLogPrintf(CTDL_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1986                 return;
1987         }
1988
1989         CtdlLogPrintf(CTDL_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1990         while (bytes_received < download_len) {
1991                 /*
1992                  * If shutting down we can exit here and unlink the temp file.
1993                  * this shouldn't loose us any messages.
1994                  */
1995                 if (CtdlThreadCheckStop())
1996                 {
1997                         fclose(fp);
1998                         unlink(tempfilename);
1999                         return;
2000                 }
2001                 snprintf(buf, sizeof buf, "READ %d|%d",
2002                          bytes_received,
2003                          ((download_len - bytes_received > IGNET_PACKET_SIZE)
2004                           ? IGNET_PACKET_SIZE : (download_len - bytes_received))
2005                 );
2006                 
2007                 if (sock_puts(sock, buf) < 0) {
2008                         fclose(fp);
2009                         unlink(tempfilename);
2010                         return;
2011                 }
2012                 if (sock_getln(sock, buf, sizeof buf) < 0) {
2013                         fclose(fp);
2014                         unlink(tempfilename);
2015                         return;
2016                 }
2017                 
2018                 if (buf[0] == '6') {
2019                         plen = extract_int(&buf[4], 0);
2020                         StrBuf *pbuf = NewStrBuf();
2021                         if (socket_read_blob(sock, pbuf, plen, CLIENT_TIMEOUT) != plen) {
2022                                 CtdlLogPrintf(CTDL_INFO, "Short read from peer; aborting.\n");
2023                                 fclose(fp);
2024                                 unlink(tempfilename);
2025                                 FreeStrBuf(&pbuf);
2026                                 return;
2027                         }
2028                         fwrite(ChrPtr(pbuf), plen, 1, fp);
2029                         bytes_received += plen;
2030                         FreeStrBuf(&pbuf);
2031                 }
2032         }
2033
2034         fclose(fp);
2035
2036         /* Last chance for shutdown exit */
2037         if (CtdlThreadCheckStop())
2038         {
2039                 unlink(tempfilename);
2040                 return;
2041         }
2042
2043         if (sock_puts(sock, "CLOS") < 0) {
2044                 unlink(tempfilename);
2045                 return;
2046         }
2047
2048         /*
2049          * From here on we must complete or messages will get lost
2050          */
2051         if (sock_getln(sock, buf, sizeof buf) < 0) {
2052                 unlink(tempfilename);
2053                 return;
2054         }
2055
2056         CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2057
2058         /*
2059          * Now move the temp file to its permanent location.
2060          */
2061         if (link(tempfilename, permfilename) != 0) {
2062                 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2063                         tempfilename, permfilename, strerror(errno)
2064                 );
2065         }
2066         
2067         unlink(tempfilename);
2068 }
2069
2070
2071
2072 /*
2073  * transmit network spool to the remote system
2074  */
2075 void transmit_spool(int *sock, char *remote_nodename)
2076 {
2077         char buf[SIZ];
2078         char pbuf[4096];
2079         long plen;
2080         long bytes_to_write, thisblock, bytes_written;
2081         int fd;
2082         char sfname[128];
2083
2084         if (sock_puts(sock, "NUOP") < 0) return;
2085         if (sock_getln(sock, buf, sizeof buf) < 0) return;
2086         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2087         if (buf[0] != '2') {
2088                 return;
2089         }
2090
2091         snprintf(sfname, sizeof sfname, 
2092                 "%s/%s",
2093                 ctdl_netout_dir,
2094                 remote_nodename
2095         );
2096         fd = open(sfname, O_RDONLY);
2097         if (fd < 0) {
2098                 if (errno != ENOENT) {
2099                         CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2100                 }
2101                 return;
2102         }
2103         bytes_written = 0;
2104         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2105                 bytes_to_write = plen;
2106                 while (bytes_to_write > 0L) {
2107                         /* Exit if shutting down */
2108                         if (CtdlThreadCheckStop())
2109                         {
2110                                 close(fd);
2111                                 return;
2112                         }
2113                         
2114                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2115                         if (sock_puts(sock, buf) < 0) {
2116                                 close(fd);
2117                                 return;
2118                         }
2119                         if (sock_getln(sock, buf, sizeof buf) < 0) {
2120                                 close(fd);
2121                                 return;
2122                         }
2123                         thisblock = atol(&buf[4]);
2124                         if (buf[0] == '7') {
2125                                 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2126                                         close(fd);
2127                                         return;
2128                                 }
2129                                 bytes_to_write -= thisblock;
2130                                 bytes_written += thisblock;
2131                         } else {
2132                                 goto ABORTUPL;
2133                         }
2134                 }
2135         }
2136
2137 ABORTUPL:
2138         close(fd);
2139
2140         /* Last chance for shutdown exit */
2141         if(CtdlThreadCheckStop())
2142                 return;
2143                 
2144         if (sock_puts(sock, "UCLS 1") < 0) return;
2145
2146         /*
2147          * From here on we must complete or messages will get lost
2148          */
2149         if (sock_getln(sock, buf, sizeof buf) < 0) return;
2150         CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2151         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2152         if (buf[0] == '2') {
2153                 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2154                 unlink(sfname);
2155         }
2156 }
2157
2158
2159
2160 /*
2161  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2162  */
2163 void network_poll_node(char *node, char *secret, char *host, char *port) {
2164         int sock;
2165         char buf[SIZ];
2166         char err_buf[SIZ];
2167         char connected_to[SIZ];
2168         CitContext *CCC=CC;
2169
2170         if (network_talking_to(node, NTT_CHECK)) return;
2171         network_talking_to(node, NTT_ADD);
2172         CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2173         CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2174
2175         sock = sock_connect(host, port);
2176         if (sock < 0) {
2177                 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2178                 network_talking_to(node, NTT_REMOVE);
2179                 return;
2180         }
2181         
2182         CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2183         CCC->sReadBuf = NewStrBuf();
2184         CCC->sMigrateBuf = NewStrBuf();
2185         CCC->sPos = NULL;
2186
2187         /* Read the server greeting */
2188         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2189         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2190
2191         /* Check that the remote is who we think it is and warn the Aide if not */
2192         extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2193         if (strcmp(connected_to, node))
2194         {
2195                 snprintf(err_buf, sizeof(err_buf),
2196                         "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2197                         connected_to, node
2198                 );
2199                 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2200                 CtdlAideMessage(err_buf, "Network error");
2201         }
2202         else {
2203                 /* We're talking to the correct node.  Now identify ourselves. */
2204                 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2205                 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2206                 if (sock_puts(&sock, buf) <0) goto bail;
2207                 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2208                 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2209                 if (buf[0] != '2') {
2210                         goto bail;
2211                 }
2212         
2213                 /* At this point we are authenticated. */
2214                 if (!CtdlThreadCheckStop())
2215                         receive_spool(&sock, node);
2216                 if (!CtdlThreadCheckStop())
2217                         transmit_spool(&sock, node);
2218         }
2219
2220         sock_puts(&sock, "QUIT");
2221 bail:   
2222         FreeStrBuf(&CCC->sReadBuf);
2223         FreeStrBuf(&CCC->sMigrateBuf);
2224         if (sock != -1)
2225                 sock_close(sock);
2226         network_talking_to(node, NTT_REMOVE);
2227 }
2228
2229
2230
2231 /*
2232  * Poll other Citadel nodes and transfer inbound/outbound network data.
2233  * Set "full" to nonzero to force a poll of every node, or to zero to poll
2234  * only nodes to which we have data to send.
2235  */
2236 void network_poll_other_citadel_nodes(int full_poll) {
2237         int i;
2238         char linebuf[256];
2239         char node[SIZ];
2240         char host[256];
2241         char port[256];
2242         char secret[256];
2243         int poll = 0;
2244         char spoolfile[256];
2245
2246         if (working_ignetcfg == NULL) {
2247                 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2248                 return;
2249         }
2250
2251         /* Use the string tokenizer to grab one line at a time */
2252         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2253                 if(CtdlThreadCheckStop())
2254                         return;
2255                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2256                 extract_token(node, linebuf, 0, '|', sizeof node);
2257                 extract_token(secret, linebuf, 1, '|', sizeof secret);
2258                 extract_token(host, linebuf, 2, '|', sizeof host);
2259                 extract_token(port, linebuf, 3, '|', sizeof port);
2260                 if ( !IsEmptyStr(node) && !IsEmptyStr(secret) 
2261                    && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2262                         poll = full_poll;
2263                         if (poll == 0) {
2264                                 snprintf(spoolfile, 
2265                                          sizeof spoolfile,
2266                                          "%s/%s",
2267                                          ctdl_netout_dir, 
2268                                          node
2269                                 );
2270                                 if (access(spoolfile, R_OK) == 0) {
2271                                         poll = 1;
2272                                 }
2273                         }
2274                         if (poll) {
2275                                 network_poll_node(node, secret, host, port);
2276                         }
2277                 }
2278         }
2279
2280 }
2281
2282
2283
2284
2285 /*
2286  * It's ok if these directories already exist.  Just fail silently.
2287  */
2288 void create_spool_dirs(void) {
2289         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2290                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2291         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2292                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2293         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2294                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2295         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2296                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2297         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2298                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2299         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2300                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2301         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2302                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2303         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2304                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2305 }
2306
2307
2308
2309
2310
2311 /*
2312  * network_do_queue()
2313  * 
2314  * Run through the rooms doing various types of network stuff.
2315  */
2316 void network_do_queue(void) {
2317         static time_t last_run = 0L;
2318         struct RoomProcList *ptr;
2319         int full_processing = 1;
2320
2321         /*
2322          * Run the full set of processing tasks no more frequently
2323          * than once every n seconds
2324          */
2325         if ( (time(NULL) - last_run) < config.c_net_freq ) {
2326                 full_processing = 0;
2327                 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2328                         config.c_net_freq - (time(NULL)- last_run)
2329                 );
2330         }
2331
2332         /*
2333          * This is a simple concurrency check to make sure only one queue run
2334          * is done at a time.  We could do this with a mutex, but since we
2335          * don't really require extremely fine granularity here, we'll do it
2336          * with a static variable instead.
2337          */
2338         if (doing_queue) {
2339                 return;
2340         }
2341         doing_queue = 1;
2342
2343         /* Load the IGnet Configuration into memory */
2344         load_working_ignetcfg();
2345
2346         /*
2347          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
2348          * then we poll everyone.  Otherwise we only poll nodes we have stuff
2349          * to send to.
2350          */
2351         network_poll_other_citadel_nodes(full_processing);
2352
2353         /*
2354          * Load the network map and filter list into memory.
2355          */
2356         read_network_map();
2357         filterlist = load_filter_list();
2358
2359         /* 
2360          * Go ahead and run the queue
2361          */
2362         if (full_processing && !CtdlThreadCheckStop()) {
2363                 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2364                 CtdlForEachRoom(network_queue_room, NULL);
2365         }
2366
2367         if (rplist != NULL) {
2368                 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2369                 while (rplist != NULL && !CtdlThreadCheckStop()) {
2370                         char spoolroomname[ROOMNAMELEN];
2371                         safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2372                         begin_critical_section(S_RPLIST);
2373
2374                         /* pop this record off the list */
2375                         ptr = rplist;
2376                         rplist = rplist->next;
2377                         free(ptr);
2378
2379                         /* invalidate any duplicate entries to prevent double processing */
2380                         for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2381                                 if (!strcasecmp(ptr->name, spoolroomname)) {
2382                                         ptr->name[0] = 0;
2383                                 }
2384                         }
2385
2386                         end_critical_section(S_RPLIST);
2387                         if (spoolroomname[0] != 0) {
2388                                 network_spoolout_room(spoolroomname);
2389                         }
2390                 }
2391         }
2392
2393         /* If there is anything in the inbound queue, process it */
2394         if (!CtdlThreadCheckStop()) {
2395                 network_do_spoolin();
2396         }
2397
2398         /* Save the network map back to disk */
2399         write_network_map();
2400
2401         /* Free the filter list in memory */
2402         free_filter_list(filterlist);
2403         filterlist = NULL;
2404
2405         network_consolidate_spoolout();
2406
2407         CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2408
2409         if (full_processing) {
2410                 last_run = time(NULL);
2411         }
2412
2413         doing_queue = 0;
2414 }
2415
2416
2417 /*
2418  * cmd_netp() - authenticate to the server as another Citadel node polling
2419  *            for network traffic
2420  */
2421 void cmd_netp(char *cmdbuf)
2422 {
2423         char node[256];
2424         char pass[256];
2425         int v;
2426
2427         char secret[256];
2428         char nexthop[256];
2429         char err_buf[SIZ];
2430
2431         /* Authenticate */
2432         extract_token(node, cmdbuf, 0, '|', sizeof node);
2433         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2434
2435         /* load the IGnet Configuration to check node validity */
2436         load_working_ignetcfg();
2437         v = is_valid_node(nexthop, secret, node);
2438
2439         if (v != 0) {
2440                 snprintf(err_buf, sizeof err_buf,
2441                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2442                         node, CC->cs_host, CC->cs_addr
2443                 );
2444                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2445                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2446                 CtdlAideMessage(err_buf, "IGNet Networking.");
2447                 return;
2448         }
2449
2450         if (strcasecmp(pass, secret)) {
2451                 snprintf(err_buf, sizeof err_buf,
2452                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2453                         CC->cs_host, CC->cs_addr, node
2454                 );
2455                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2456                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2457                 CtdlAideMessage(err_buf, "IGNet Networking.");
2458                 return;
2459         }
2460
2461         if (network_talking_to(node, NTT_CHECK)) {
2462                 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2463                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2464                 return;
2465         }
2466
2467         safestrncpy(CC->net_node, node, sizeof CC->net_node);
2468         network_talking_to(node, NTT_ADD);
2469         CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2470                 CC->net_node, CC->cs_host, CC->cs_addr
2471         );
2472         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2473 }
2474
2475
2476 int network_room_handler (struct ctdlroom *room)
2477 {
2478         network_queue_room(room, NULL);
2479         return 0;
2480 }
2481
2482 void *ignet_thread(void *arg) {
2483         struct CitContext ignet_thread_CC;
2484
2485         CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2486         CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2487         citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2488
2489         while (!CtdlThreadCheckStop()) {
2490                 network_do_queue();
2491                 CtdlThreadSleep(60);
2492         }
2493
2494         CtdlClearSystemContext();
2495         return(NULL);
2496 }
2497
2498
2499
2500
2501 /*
2502  * Module entry point
2503  */
2504 CTDL_MODULE_INIT(network)
2505 {
2506         if (!threading)
2507         {
2508                 create_spool_dirs();
2509                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2510                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2511                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2512                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2513                 CtdlRegisterRoomHook(network_room_handler);
2514                 CtdlRegisterCleanupHook(destroy_network_queue_room);
2515                 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);
2516         }
2517         return "network";
2518 }