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