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