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