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