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