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