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