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