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