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