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