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