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