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