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