* move policy.c into modules/expire/expire_policy.c, since it just controls this.
[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 the spool file */
878                                         snprintf(filename, sizeof filename,"%s/%s",
879                                                         ctdl_netout_dir,
880                                                         mptr->remote_nodename);
881                                         CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
882                                         fp = fopen(filename, "ab");
883                                         if (fp != NULL) {
884                                                 fwrite(sermsg.ser,
885                                                         sermsg.len, 1, fp);
886                                                 fclose(fp);
887                                         }
888                                         else {
889                                                 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
890                                         }
891         
892                                         /* free the serialized version */
893                                         free(sermsg.ser);
894                                 }
895
896                         }
897                 }
898                 CtdlFreeMessage(msg);
899         }
900
901         /* update lastsent */
902         sc->lastsent = msgnum;
903
904         /* Delete this message if delete-after-send is set */
905         if (delete_after_send) {
906                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
907         }
908
909 }
910         
911
912 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
913 {
914         FILE *fp;
915         char instr[SIZ];
916         char buf[SIZ];
917         char nodename[256];
918         char roomname[ROOMNAMELEN];
919         size_t miscsize = 0;
920         size_t linesize = 0;
921         int skipthisline = 0;
922         namelist *nptr = NULL;
923         maplist *mptr = NULL;
924         SpoolControl *sc;
925
926         fp = fopen(filename, "r");
927         if (fp == NULL) {
928                 return 0;
929         }
930         sc = malloc(sizeof(SpoolControl));
931         memset(sc, 0, sizeof(SpoolControl));
932         *scc = sc;
933
934         while (fgets(buf, sizeof buf, fp) != NULL) {
935                 buf[strlen(buf)-1] = 0;
936
937                 extract_token(instr, buf, 0, '|', sizeof instr);
938                 if (!strcasecmp(instr, strof(lastsent))) {
939                         sc->lastsent = extract_long(buf, 1);
940                 }
941                 else if (!strcasecmp(instr, strof(listrecp))) {
942                         nptr = (namelist *)
943                                 malloc(sizeof(namelist));
944                         nptr->next = sc->listrecps;
945                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
946                         sc->listrecps = nptr;
947                 }
948                 else if (!strcasecmp(instr, strof(participate))) {
949                         nptr = (namelist *)
950                                 malloc(sizeof(namelist));
951                         nptr->next = sc->participates;
952                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
953                         sc->participates = nptr;
954                 }
955                 else if (!strcasecmp(instr, strof(digestrecp))) {
956                         nptr = (namelist *)
957                                 malloc(sizeof(namelist));
958                         nptr->next = sc->digestrecps;
959                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
960                         sc->digestrecps = nptr;
961                 }
962                 else if (!strcasecmp(instr, strof(ignet_push_share))) {
963                         extract_token(nodename, buf, 1, '|', sizeof nodename);
964                         extract_token(roomname, buf, 2, '|', sizeof roomname);
965                         mptr = (maplist *) malloc(sizeof(maplist));
966                         mptr->next = sc->ignet_push_shares;
967                         strcpy(mptr->remote_nodename, nodename);
968                         strcpy(mptr->remote_roomname, roomname);
969                         sc->ignet_push_shares = mptr;
970                 }
971                 else {
972                         /* Preserve 'other' lines ... *unless* they happen to
973                          * be subscribe/unsubscribe pendings with expired
974                          * timestamps.
975                          */
976                         skipthisline = 0;
977                         if (!strncasecmp(buf, strof(subpending)"|", 11)) {
978                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
979                                         skipthisline = 1;
980                                 }
981                         }
982                         if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
983                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
984                                         skipthisline = 1;
985                                 }
986                         }
987
988                         if (skipthisline == 0) {
989                                 linesize = strlen(buf);
990                                 sc->misc = realloc(sc->misc,
991                                         (miscsize + linesize + 2) );
992                                 sprintf(&sc->misc[miscsize], "%s\n", buf);
993                                 miscsize = miscsize + linesize + 1;
994                         }
995                 }
996
997
998         }
999         fclose(fp);
1000         return 1;
1001 }
1002
1003 void free_spoolcontrol_struct(SpoolControl **scc)
1004 {
1005         SpoolControl *sc;
1006         namelist *nptr = NULL;
1007         maplist *mptr = NULL;
1008
1009         sc = *scc;
1010         while (sc->listrecps != NULL) {
1011                 nptr = sc->listrecps->next;
1012                 free(sc->listrecps);
1013                 sc->listrecps = nptr;
1014         }
1015         /* Do the same for digestrecps */
1016         while (sc->digestrecps != NULL) {
1017                 nptr = sc->digestrecps->next;
1018                 free(sc->digestrecps);
1019                 sc->digestrecps = nptr;
1020         }
1021         /* Do the same for participates */
1022         while (sc->participates != NULL) {
1023                 nptr = sc->participates->next;
1024                 free(sc->participates);
1025                 sc->participates = nptr;
1026         }
1027         while (sc->ignet_push_shares != NULL) {
1028                 mptr = sc->ignet_push_shares->next;
1029                 free(sc->ignet_push_shares);
1030                 sc->ignet_push_shares = mptr;
1031         }
1032         free(sc->misc);
1033         free(sc);
1034         *scc=NULL;
1035 }
1036
1037 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1038 {
1039         FILE *fp;
1040         SpoolControl *sc;
1041         namelist *nptr = NULL;
1042         maplist *mptr = NULL;
1043
1044         sc = *scc;
1045         fp = fopen(filename, "w");
1046         if (fp == NULL) {
1047                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1048                         filename, strerror(errno));
1049                 free_spoolcontrol_struct(scc);
1050         }
1051         else {
1052                 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1053
1054                 /* Write out the listrecps while freeing from memory at the
1055                  * same time.  Am I clever or what?  :)
1056                  */
1057                 while (sc->listrecps != NULL) {
1058                         fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1059                         nptr = sc->listrecps->next;
1060                         free(sc->listrecps);
1061                         sc->listrecps = nptr;
1062                 }
1063                 /* Do the same for digestrecps */
1064                 while (sc->digestrecps != NULL) {
1065                         fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1066                         nptr = sc->digestrecps->next;
1067                         free(sc->digestrecps);
1068                         sc->digestrecps = nptr;
1069                 }
1070                 /* Do the same for participates */
1071                 while (sc->participates != NULL) {
1072                         fprintf(fp, "participate|%s\n", sc->participates->name);
1073                         nptr = sc->participates->next;
1074                         free(sc->participates);
1075                         sc->participates = nptr;
1076                 }
1077                 while (sc->ignet_push_shares != NULL) {
1078                         fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1079                         if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1080                                 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1081                         }
1082                         fprintf(fp, "\n");
1083                         mptr = sc->ignet_push_shares->next;
1084                         free(sc->ignet_push_shares);
1085                         sc->ignet_push_shares = mptr;
1086                 }
1087                 if (sc->misc != NULL) {
1088                         fwrite(sc->misc, strlen(sc->misc), 1, fp);
1089                 }
1090                 free(sc->misc);
1091
1092                 fclose(fp);
1093                 free(sc);
1094                 *scc=NULL;
1095         }
1096         return 1;
1097 }
1098 int is_recipient(SpoolControl *sc, const char *Name)
1099 {
1100         namelist *nptr;
1101         size_t len;
1102
1103         len = strlen(Name);
1104         nptr = sc->listrecps;
1105         while (nptr != NULL) {
1106                 if (strncmp(Name, nptr->name, len)==0)
1107                         return 1;
1108                 nptr = nptr->next;
1109         }
1110         /* Do the same for digestrecps */
1111         nptr = sc->digestrecps;
1112         while (nptr != NULL) {
1113                 if (strncmp(Name, nptr->name, len)==0)
1114                         return 1;
1115                 nptr = nptr->next;
1116         }
1117         /* Do the same for participates */
1118         nptr = sc->participates;
1119         while (nptr != NULL) {
1120                 if (strncmp(Name, nptr->name, len)==0)
1121                         return 1;
1122                 nptr = nptr->next;
1123         }
1124         return 0;
1125 }
1126
1127
1128 /*
1129  * Batch up and send all outbound traffic from the current room
1130  */
1131 void network_spoolout_room(char *room_to_spool) {
1132         char buf[SIZ];
1133         char filename[PATH_MAX];
1134         SpoolControl *sc;
1135         int i;
1136
1137         /*
1138          * If the room doesn't exist, don't try to perform its networking tasks.
1139          * Normally this should never happen, but once in a while maybe a room gets
1140          * queued for networking and then deleted before it can happen.
1141          */
1142         if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1143                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1144                 return;
1145         }
1146
1147         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1148         begin_critical_section(S_NETCONFIGS);
1149
1150         /* Only do net processing for rooms that have netconfigs */
1151         if (!read_spoolcontrol_file(&sc, filename))
1152         {
1153                 end_critical_section(S_NETCONFIGS);
1154                 return;
1155         }
1156         CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1157
1158         /* If there are digest recipients, we have to build a digest */
1159         if (sc->digestrecps != NULL) {
1160                 sc->digestfp = tmpfile();
1161                 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1162         }
1163
1164         /* Do something useful */
1165         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1166                 network_spool_msg, sc);
1167
1168         /* If we wrote a digest, deliver it and then close it */
1169         snprintf(buf, sizeof buf, "room_%s@%s",
1170                 CC->room.QRname, config.c_fqdn);
1171         for (i=0; buf[i]; ++i) {
1172                 buf[i] = tolower(buf[i]);
1173                 if (isspace(buf[i])) buf[i] = '_';
1174         }
1175         if (sc->digestfp != NULL) {
1176                 fprintf(sc->digestfp,   " -----------------------------------"
1177                                         "------------------------------------"
1178                                         "-------\n"
1179                                         "You are subscribed to the '%s' "
1180                                         "list.\n"
1181                                         "To post to the list: %s\n",
1182                                         CC->room.QRname, buf
1183                 );
1184                 network_deliver_digest(sc);     /* deliver and close */
1185         }
1186
1187         /* Now rewrite the config file */
1188         writenfree_spoolcontrol_file (&sc, filename);
1189         end_critical_section(S_NETCONFIGS);
1190 }
1191
1192
1193
1194 /*
1195  * Send the *entire* contents of the current room to one specific network node,
1196  * ignoring anything we know about which messages have already undergone
1197  * network processing.  This can be used to bring a new node into sync.
1198  */
1199 int network_sync_to(char *target_node) {
1200         SpoolControl sc;
1201         int num_spooled = 0;
1202         int found_node = 0;
1203         char buf[256];
1204         char sc_type[256];
1205         char sc_node[256];
1206         char sc_room[256];
1207         char filename[PATH_MAX];
1208         FILE *fp;
1209
1210         /* Grab the configuration line we're looking for */
1211         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1212         begin_critical_section(S_NETCONFIGS);
1213         fp = fopen(filename, "r");
1214         if (fp == NULL) {
1215                 end_critical_section(S_NETCONFIGS);
1216                 return(-1);
1217         }
1218         while (fgets(buf, sizeof buf, fp) != NULL) {
1219                 buf[strlen(buf)-1] = 0;
1220                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1221                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1222                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1223                 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1224                    && (!strcasecmp(sc_node, target_node)) ) {
1225                         found_node = 1;
1226                         
1227                         /* Concise syntax because we don't need a full linked-list */
1228                         memset(&sc, 0, sizeof(SpoolControl));
1229                         sc.ignet_push_shares = (maplist *)
1230                                 malloc(sizeof(maplist));
1231                         sc.ignet_push_shares->next = NULL;
1232                         safestrncpy(sc.ignet_push_shares->remote_nodename,
1233                                 sc_node,
1234                                 sizeof sc.ignet_push_shares->remote_nodename);
1235                         safestrncpy(sc.ignet_push_shares->remote_roomname,
1236                                 sc_room,
1237                                 sizeof sc.ignet_push_shares->remote_roomname);
1238                 }
1239         }
1240         fclose(fp);
1241         end_critical_section(S_NETCONFIGS);
1242
1243         if (!found_node) return(-1);
1244
1245         /* Send ALL messages */
1246         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1247                 network_spool_msg, &sc);
1248
1249         /* Concise cleanup because we know there's only one node in the sc */
1250         free(sc.ignet_push_shares);
1251
1252         CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1253                 num_spooled, target_node);
1254         return(num_spooled);
1255 }
1256
1257
1258 /*
1259  * Implements the NSYN command
1260  */
1261 void cmd_nsyn(char *argbuf) {
1262         int num_spooled;
1263         char target_node[256];
1264
1265         if (CtdlAccessCheck(ac_aide)) return;
1266
1267         extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1268         num_spooled = network_sync_to(target_node);
1269         if (num_spooled >= 0) {
1270                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1271         }
1272         else {
1273                 cprintf("%d No such room/node share exists.\n",
1274                         ERROR + ROOM_NOT_FOUND);
1275         }
1276 }
1277
1278
1279
1280 /*
1281  * Batch up and send all outbound traffic from the current room
1282  */
1283 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1284         struct RoomProcList *ptr;
1285
1286         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1287         if (ptr == NULL) return;
1288
1289         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1290         begin_critical_section(S_RPLIST);
1291         ptr->next = rplist;
1292         rplist = ptr;
1293         end_critical_section(S_RPLIST);
1294 }
1295
1296 void destroy_network_queue_room(void)
1297 {
1298         struct RoomProcList *cur, *p;
1299         NetMap *nmcur, *nmp;
1300
1301         cur = rplist;
1302         begin_critical_section(S_RPLIST);
1303         while (cur != NULL)
1304         {
1305                 p = cur->next;
1306                 free (cur);
1307                 cur = p;                
1308         }
1309         rplist = NULL;
1310         end_critical_section(S_RPLIST);
1311
1312         nmcur = the_netmap;
1313         while (nmcur != NULL)
1314         {
1315                 nmp = nmcur->next;
1316                 free (nmcur);
1317                 nmcur = nmp;            
1318         }
1319         the_netmap = NULL;
1320         if (working_ignetcfg != NULL)
1321                 free (working_ignetcfg);
1322         working_ignetcfg = NULL;
1323 }
1324
1325
1326 /*
1327  * Learn topology from path fields
1328  */
1329 void network_learn_topology(char *node, char *path) {
1330         char nexthop[256];
1331         NetMap *nmptr;
1332
1333         strcpy(nexthop, "");
1334
1335         if (num_tokens(path, '!') < 3) return;
1336         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1337                 if (!strcasecmp(nmptr->nodename, node)) {
1338                         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1339                         nmptr->lastcontact = time(NULL);
1340                         ++netmap_changed;
1341                         return;
1342                 }
1343         }
1344
1345         /* If we got here then it's not in the map, so add it. */
1346         nmptr = (NetMap *) malloc(sizeof (NetMap));
1347         strcpy(nmptr->nodename, node);
1348         nmptr->lastcontact = time(NULL);
1349         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1350         nmptr->next = the_netmap;
1351         the_netmap = nmptr;
1352         ++netmap_changed;
1353 }
1354
1355
1356
1357
1358 /*
1359  * Bounce a message back to the sender
1360  */
1361 void network_bounce(struct CtdlMessage *msg, char *reason) {
1362         char *oldpath = NULL;
1363         char buf[SIZ];
1364         char bouncesource[SIZ];
1365         char recipient[SIZ];
1366         struct recptypes *valid = NULL;
1367         char force_room[ROOMNAMELEN];
1368         static int serialnum = 0;
1369         size_t size;
1370
1371         CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1372
1373         if (msg == NULL) return;
1374
1375         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1376
1377         /* 
1378          * Give it a fresh message ID
1379          */
1380         if (msg->cm_fields['I'] != NULL) {
1381                 free(msg->cm_fields['I']);
1382         }
1383         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1384                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1385         msg->cm_fields['I'] = strdup(buf);
1386
1387         /*
1388          * FIXME ... right now we're just sending a bounce; we really want to
1389          * include the text of the bounced message.
1390          */
1391         if (msg->cm_fields['M'] != NULL) {
1392                 free(msg->cm_fields['M']);
1393         }
1394         msg->cm_fields['M'] = strdup(reason);
1395         msg->cm_format_type = 0;
1396
1397         /*
1398          * Turn the message around
1399          */
1400         if (msg->cm_fields['R'] == NULL) {
1401                 free(msg->cm_fields['R']);
1402         }
1403
1404         if (msg->cm_fields['D'] == NULL) {
1405                 free(msg->cm_fields['D']);
1406         }
1407
1408         snprintf(recipient, sizeof recipient, "%s@%s",
1409                 msg->cm_fields['A'], msg->cm_fields['N']);
1410
1411         if (msg->cm_fields['A'] == NULL) {
1412                 free(msg->cm_fields['A']);
1413         }
1414
1415         if (msg->cm_fields['N'] == NULL) {
1416                 free(msg->cm_fields['N']);
1417         }
1418
1419         if (msg->cm_fields['U'] == NULL) {
1420                 free(msg->cm_fields['U']);
1421         }
1422
1423         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1424         msg->cm_fields['N'] = strdup(config.c_nodename);
1425         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1426
1427         /* prepend our node to the path */
1428         if (msg->cm_fields['P'] != NULL) {
1429                 oldpath = msg->cm_fields['P'];
1430                 msg->cm_fields['P'] = NULL;
1431         }
1432         else {
1433                 oldpath = strdup("unknown_user");
1434         }
1435         size = strlen(oldpath) + SIZ;
1436         msg->cm_fields['P'] = malloc(size);
1437         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1438         free(oldpath);
1439
1440         /* Now submit the message */
1441         valid = validate_recipients(recipient, NULL, 0);
1442         if (valid != NULL) if (valid->num_error != 0) {
1443                 free_recipients(valid);
1444                 valid = NULL;
1445         }
1446         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1447                 strcpy(force_room, config.c_aideroom);
1448         }
1449         else {
1450                 strcpy(force_room, "");
1451         }
1452         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1453                 strcpy(force_room, config.c_aideroom);
1454         }
1455         CtdlSubmitMsg(msg, valid, force_room, 0);
1456
1457         /* Clean up */
1458         if (valid != NULL) free_recipients(valid);
1459         CtdlFreeMessage(msg);
1460         CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1461 }
1462
1463
1464
1465
1466 /*
1467  * Process a buffer containing a single message from a single file
1468  * from the inbound queue 
1469  */
1470 void network_process_buffer(char *buffer, long size) {
1471         struct CtdlMessage *msg = NULL;
1472         long pos;
1473         int field;
1474         struct recptypes *recp = NULL;
1475         char target_room[ROOMNAMELEN];
1476         struct ser_ret sermsg;
1477         char *oldpath = NULL;
1478         char filename[PATH_MAX];
1479         FILE *fp;
1480         char nexthop[SIZ];
1481         unsigned char firstbyte;
1482         unsigned char lastbyte;
1483
1484         CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1485
1486         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
1487         firstbyte = buffer[0];
1488         lastbyte = buffer[size-1];
1489         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1490                 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
1491                         size, firstbyte, lastbyte);
1492                 return;
1493         }
1494
1495         /* Set default target room to trash */
1496         strcpy(target_room, TWITROOM);
1497
1498         /* Load the message into memory */
1499         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1500         memset(msg, 0, sizeof(struct CtdlMessage));
1501         msg->cm_magic = CTDLMESSAGE_MAGIC;
1502         msg->cm_anon_type = buffer[1];
1503         msg->cm_format_type = buffer[2];
1504
1505         for (pos = 3; pos < size; ++pos) {
1506                 field = buffer[pos];
1507                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1508                 pos = pos + strlen(&buffer[(int)pos]);
1509         }
1510
1511         /* Check for message routing */
1512         if (msg->cm_fields['D'] != NULL) {
1513                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1514
1515                         /* route the message */
1516                         strcpy(nexthop, "");
1517                         if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1518                                 /* prepend our node to the path */
1519                                 if (msg->cm_fields['P'] != NULL) {
1520                                         oldpath = msg->cm_fields['P'];
1521                                         msg->cm_fields['P'] = NULL;
1522                                 }
1523                                 else {
1524                                         oldpath = strdup("unknown_user");
1525                                 }
1526                                 size = strlen(oldpath) + SIZ;
1527                                 msg->cm_fields['P'] = malloc(size);
1528                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1529                                         config.c_nodename, oldpath);
1530                                 free(oldpath);
1531
1532                                 /* serialize the message */
1533                                 serialize_message(&sermsg, msg);
1534
1535                                 /* now send it */
1536                                 if (IsEmptyStr(nexthop)) {
1537                                         strcpy(nexthop, msg->cm_fields['D']);
1538                                 }
1539                                 snprintf(filename, 
1540                                                  sizeof filename,
1541                                                  "%s/%s",
1542                                                  ctdl_netout_dir,
1543                                                  nexthop);
1544                                 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1545                                 fp = fopen(filename, "ab");
1546                                 if (fp != NULL) {
1547                                         fwrite(sermsg.ser,
1548                                                 sermsg.len, 1, fp);
1549                                         fclose(fp);
1550                                 }
1551                                 else {
1552                                         CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1553                                 }
1554                                 free(sermsg.ser);
1555                                 CtdlFreeMessage(msg);
1556                                 return;
1557                         }
1558                         
1559                         else {  /* invalid destination node name */
1560
1561                                 network_bounce(msg,
1562 "A message you sent could not be delivered due to an invalid destination node"
1563 " name.  Please check the address and try sending the message again.\n");
1564                                 msg = NULL;
1565                                 return;
1566
1567                         }
1568                 }
1569         }
1570
1571         /*
1572          * Check to see if we already have a copy of this message, and
1573          * abort its processing if so.  (We used to post a warning to Aide>
1574          * every time this happened, but the network is now so densely
1575          * connected that it's inevitable.)
1576          */
1577         if (network_usetable(msg) != 0) {
1578                 CtdlFreeMessage(msg);
1579                 return;
1580         }
1581
1582         /* Learn network topology from the path */
1583         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1584                 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1585         }
1586
1587         /* Is the sending node giving us a very persuasive suggestion about
1588          * which room this message should be saved in?  If so, go with that.
1589          */
1590         if (msg->cm_fields['C'] != NULL) {
1591                 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1592         }
1593
1594         /* Otherwise, does it have a recipient?  If so, validate it... */
1595         else if (msg->cm_fields['R'] != NULL) {
1596                 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1597                 if (recp != NULL) if (recp->num_error != 0) {
1598                         network_bounce(msg,
1599                                 "A message you sent could not be delivered due to an invalid address.\n"
1600                                 "Please check the address and try sending the message again.\n");
1601                         msg = NULL;
1602                         free_recipients(recp);
1603                         CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1604                         return;
1605                 }
1606                 strcpy(target_room, "");        /* no target room if mail */
1607         }
1608
1609         /* Our last shot at finding a home for this message is to see if
1610          * it has the O field (Originating room) set.
1611          */
1612         else if (msg->cm_fields['O'] != NULL) {
1613                 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1614         }
1615
1616         /* Strip out fields that are only relevant during transit */
1617         if (msg->cm_fields['D'] != NULL) {
1618                 free(msg->cm_fields['D']);
1619                 msg->cm_fields['D'] = NULL;
1620         }
1621         if (msg->cm_fields['C'] != NULL) {
1622                 free(msg->cm_fields['C']);
1623                 msg->cm_fields['C'] = NULL;
1624         }
1625
1626         /* save the message into a room */
1627         if (PerformNetprocHooks(msg, target_room) == 0) {
1628                 msg->cm_flags = CM_SKIP_HOOKS;
1629                 CtdlSubmitMsg(msg, recp, target_room, 0);
1630         }
1631         CtdlFreeMessage(msg);
1632         free_recipients(recp);
1633 }
1634
1635
1636 /*
1637  * Process a single message from a single file from the inbound queue 
1638  */
1639 void network_process_message(FILE *fp, long msgstart, long msgend) {
1640         long hold_pos;
1641         long size;
1642         char *buffer;
1643
1644         hold_pos = ftell(fp);
1645         size = msgend - msgstart + 1;
1646         buffer = malloc(size);
1647         if (buffer != NULL) {
1648                 fseek(fp, msgstart, SEEK_SET);
1649                 if (fread(buffer, size, 1, fp) > 0) {
1650                         network_process_buffer(buffer, size);
1651                 }
1652                 free(buffer);
1653         }
1654
1655         fseek(fp, hold_pos, SEEK_SET);
1656 }
1657
1658
1659 /*
1660  * Process a single file from the inbound queue 
1661  */
1662 void network_process_file(char *filename) {
1663         FILE *fp;
1664         long msgstart = (-1L);
1665         long msgend = (-1L);
1666         long msgcur = 0L;
1667         int ch;
1668
1669
1670         fp = fopen(filename, "rb");
1671         if (fp == NULL) {
1672                 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1673                 return;
1674         }
1675
1676         fseek(fp, 0L, SEEK_END);
1677         CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1678         rewind(fp);
1679
1680         /* Look for messages in the data stream and break them out */
1681         while (ch = getc(fp), ch >= 0) {
1682         
1683                 if (ch == 255) {
1684                         if (msgstart >= 0L) {
1685                                 msgend = msgcur - 1;
1686                                 network_process_message(fp, msgstart, msgend);
1687                         }
1688                         msgstart = msgcur;
1689                 }
1690
1691                 ++msgcur;
1692         }
1693
1694         msgend = msgcur - 1;
1695         if (msgstart >= 0L) {
1696                 network_process_message(fp, msgstart, msgend);
1697         }
1698
1699         fclose(fp);
1700         unlink(filename);
1701 }
1702
1703
1704 /*
1705  * Process anything in the inbound queue
1706  */
1707 void network_do_spoolin(void) {
1708         DIR *dp;
1709         struct dirent *d;
1710         struct stat statbuf;
1711         char filename[PATH_MAX];
1712         static time_t last_spoolin_mtime = 0L;
1713
1714         /*
1715          * Check the spoolin directory's modification time.  If it hasn't
1716          * been touched, we don't need to scan it.
1717          */
1718         if (stat(ctdl_netin_dir, &statbuf)) return;
1719         if (statbuf.st_mtime == last_spoolin_mtime) {
1720                 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1721                 return;
1722         }
1723         last_spoolin_mtime = statbuf.st_mtime;
1724         CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1725
1726         /*
1727          * Ok, there's something interesting in there, so scan it.
1728          */
1729         dp = opendir(ctdl_netin_dir);
1730         if (dp == NULL) return;
1731
1732         while (d = readdir(dp), d != NULL) {
1733                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1734                         snprintf(filename, 
1735                                          sizeof filename,
1736                                          "%s/%s",
1737                                          ctdl_netin_dir,
1738                                          d->d_name);
1739                         network_process_file(filename);
1740                 }
1741         }
1742
1743         closedir(dp);
1744 }
1745
1746 /*
1747  * Delete any files in the outbound queue that were intended
1748  * to be sent to nodes which no longer exist.
1749  */
1750 void network_purge_spoolout(void) {
1751         DIR *dp;
1752         struct dirent *d;
1753         char filename[PATH_MAX];
1754         char nexthop[256];
1755         int i;
1756
1757         dp = opendir(ctdl_netout_dir);
1758         if (dp == NULL) return;
1759
1760         while (d = readdir(dp), d != NULL) {
1761                 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1762                         continue;
1763                 snprintf(filename, 
1764                                  sizeof filename,
1765                                  "%s/%s",
1766                                  ctdl_netout_dir,
1767                                  d->d_name);
1768
1769                 strcpy(nexthop, "");
1770                 i = is_valid_node(nexthop, NULL, d->d_name);
1771         
1772                 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1773                         unlink(filename);
1774                 }
1775         }
1776
1777
1778         closedir(dp);
1779 }
1780
1781
1782 /*
1783  * receive network spool from the remote system
1784  */
1785 void receive_spool(int *sock, char *remote_nodename) {
1786         size_t siz;
1787         long download_len = 0L;
1788         long bytes_received = 0L;
1789         long bytes_copied = 0L;
1790         char buf[SIZ];
1791         static char pbuf[IGNET_PACKET_SIZE];
1792         char tempfilename[PATH_MAX];
1793         char filename[PATH_MAX];
1794         long plen;
1795         FILE *fp, *newfp;
1796
1797         CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
1798         if (sock_puts(sock, "NDOP") < 0) return;
1799         if (sock_getln(sock, buf, sizeof buf) < 0) return;
1800         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1801         if (buf[0] != '2') {
1802                 return;
1803         }
1804         download_len = extract_long(&buf[4], 0);
1805
1806         bytes_received = 0L;
1807         fp = fopen(tempfilename, "w");
1808         if (fp == NULL) {
1809                 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1810                         strerror(errno));
1811                 return;
1812         }
1813
1814         while (bytes_received < download_len) {
1815                 /**
1816                  * If shutting down we can exit here and unlink the temp file.
1817                  * this shouldn't loose us any messages.
1818                  */
1819                 if (CtdlThreadCheckStop())
1820                 {
1821                         fclose(fp);
1822                         unlink(tempfilename);
1823                         return;
1824                 }
1825                 snprintf(buf, sizeof buf, "READ %ld|%ld",
1826                         bytes_received,
1827                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1828                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1829                 if (sock_puts(sock, buf) < 0) {
1830                         fclose(fp);
1831                         unlink(tempfilename);
1832                         return;
1833                 }
1834                 if (sock_getln(sock, buf, sizeof buf) < 0) {
1835                         fclose(fp);
1836                         unlink(tempfilename);
1837                         return;
1838                 }
1839                 if (buf[0] == '6') {
1840                         plen = extract_long(&buf[4], 0);
1841                         if (sock_read(sock, pbuf, plen, 1) < 0) {
1842                                 fclose(fp);
1843                                 unlink(tempfilename);
1844                                 return;
1845                         }
1846                         fwrite((char *) pbuf, plen, 1, fp);
1847                         bytes_received = bytes_received + plen;
1848                 }
1849         }
1850
1851         fclose(fp);
1852         /** Last chance for shutdown exit */
1853         if (CtdlThreadCheckStop())
1854         {
1855                 unlink(tempfilename);
1856                 return;
1857         }
1858         if (sock_puts(sock, "CLOS") < 0) {
1859                 unlink(tempfilename);
1860                 return;
1861         }
1862         /**
1863          * From here on we must complete or messages will get lost
1864          */
1865         if (sock_getln(sock, buf, sizeof buf) < 0) {
1866                 unlink(tempfilename);
1867                 return;
1868         }
1869         if (download_len > 0) {
1870                 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1871         }
1872         CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1873         
1874         /* Now copy the temp file to its permanent location.
1875          * (We copy instead of link because they may be on different filesystems)
1876          */
1877         begin_critical_section(S_NETSPOOL);
1878         snprintf(filename, 
1879                          sizeof filename, 
1880                          "%s/%s.%ld",
1881                          ctdl_netin_dir,
1882                          remote_nodename, 
1883                          (long) getpid()
1884         );
1885         fp = fopen(tempfilename, "r");
1886         if (fp != NULL) {
1887                 newfp = fopen(filename, "w");
1888                 if (newfp != NULL) {
1889                         bytes_copied = 0L;
1890                         while (bytes_copied < download_len) {
1891                                 plen = download_len - bytes_copied;
1892                                 if (plen > sizeof buf) {
1893                                         plen = sizeof buf;
1894                                 }
1895                                 siz = fread(buf, plen, 1, fp);
1896                                 fwrite(buf, plen, 1, newfp);
1897                                 bytes_copied += plen;
1898                         }
1899                         fclose(newfp);
1900                 }
1901                 fclose(fp);
1902         }
1903         end_critical_section(S_NETSPOOL);
1904         unlink(tempfilename);
1905 }
1906
1907
1908
1909 /*
1910  * transmit network spool to the remote system
1911  */
1912 void transmit_spool(int *sock, char *remote_nodename)
1913 {
1914         char buf[SIZ];
1915         char pbuf[4096];
1916         long plen;
1917         long bytes_to_write, thisblock, bytes_written;
1918         int fd;
1919         char sfname[128];
1920
1921         if (sock_puts(sock, "NUOP") < 0) return;
1922         if (sock_getln(sock, buf, sizeof buf) < 0) return;
1923         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1924         if (buf[0] != '2') {
1925                 return;
1926         }
1927
1928         snprintf(sfname, sizeof sfname, 
1929                          "%s/%s",
1930                          ctdl_netout_dir,
1931                          remote_nodename);
1932         fd = open(sfname, O_RDONLY);
1933         if (fd < 0) {
1934                 if (errno != ENOENT) {
1935                         CtdlLogPrintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1936                                 strerror(errno));
1937                 }
1938                 return;
1939         }
1940         bytes_written = 0;
1941         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1942                 bytes_to_write = plen;
1943                 while (bytes_to_write > 0L) {
1944                         /** Exit if shutting down */
1945                         if (CtdlThreadCheckStop())
1946                         {
1947                                 close(fd);
1948                                 return;
1949                         }
1950                         
1951                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1952                         if (sock_puts(sock, buf) < 0) {
1953                                 close(fd);
1954                                 return;
1955                         }
1956                         if (sock_getln(sock, buf, sizeof buf) < 0) {
1957                                 close(fd);
1958                                 return;
1959                         }
1960                         thisblock = atol(&buf[4]);
1961                         if (buf[0] == '7') {
1962                                 if (sock_write(sock, pbuf,
1963                                    (int) thisblock) < 0) {
1964                                         close(fd);
1965                                         return;
1966                                 }
1967                                 bytes_to_write -= thisblock;
1968                                 bytes_written += thisblock;
1969                         } else {
1970                                 goto ABORTUPL;
1971                         }
1972                 }
1973         }
1974
1975 ABORTUPL:
1976         close(fd);
1977         /** Last chance for shutdown exit */
1978         if(CtdlThreadCheckStop())
1979                 return;
1980                 
1981         if (sock_puts(sock, "UCLS 1") < 0) return;
1982         /**
1983          * From here on we must complete or messages will get lost
1984          */
1985         if (sock_getln(sock, buf, sizeof buf) < 0) return;
1986         CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n",
1987                         bytes_written, remote_nodename);
1988         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1989         if (buf[0] == '2') {
1990                 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
1991                 unlink(sfname);
1992         }
1993 }
1994
1995
1996
1997 /*
1998  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1999  */
2000 void network_poll_node(char *node, char *secret, char *host, char *port) {
2001         int sock;
2002         char buf[SIZ];
2003         char err_buf[SIZ];
2004         char connected_to[SIZ];
2005         CitContext *CCC=CC;
2006
2007         if (network_talking_to(node, NTT_CHECK)) return;
2008         network_talking_to(node, NTT_ADD);
2009         CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2010
2011         sock = sock_connect(host, port, "tcp");
2012         if (sock < 0) {
2013                 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2014                 network_talking_to(node, NTT_REMOVE);
2015                 return;
2016         }
2017         
2018         CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2019         CCC->sReadBuf = NewStrBuf();
2020         CCC->sMigrateBuf = NewStrBuf();
2021         CCC->sPos = NULL;
2022         /* Read the server greeting */
2023         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2024         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2025
2026         /* Check that the remote is who we think it is and warn the Aide if not */
2027         extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2028         if (strcmp(connected_to, node))
2029         {
2030                 snprintf (err_buf, sizeof(err_buf), "Connected to node \"%s\" but I was expecting to connect to node \"%s\".", connected_to, node);
2031                 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2032                 CtdlAideMessage(err_buf, "Network error");
2033         }
2034         else {
2035                 /* We're talking to the correct node.  Now identify ourselves. */
2036                 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2037                 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2038                 if (sock_puts(&sock, buf) <0) goto bail;
2039                 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2040                 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2041                 if (buf[0] != '2') goto bail;
2042         
2043                 /* At this point we are authenticated. */
2044                 if (!CtdlThreadCheckStop())
2045                         receive_spool(&sock, node);
2046                 if (!CtdlThreadCheckStop())
2047                         transmit_spool(&sock, node);
2048         }
2049
2050         sock_puts(&sock, "QUIT");
2051 bail:   
2052         FreeStrBuf(&CCC->sReadBuf);
2053         FreeStrBuf(&CCC->sMigrateBuf);
2054         if (sock != -1)
2055                 sock_close(sock);
2056         network_talking_to(node, NTT_REMOVE);
2057 }
2058
2059
2060
2061 /*
2062  * Poll other Citadel nodes and transfer inbound/outbound network data.
2063  * Set "full" to nonzero to force a poll of every node, or to zero to poll
2064  * only nodes to which we have data to send.
2065  */
2066 void network_poll_other_citadel_nodes(int full_poll) {
2067         int i;
2068         char linebuf[256];
2069         char node[SIZ];
2070         char host[256];
2071         char port[256];
2072         char secret[256];
2073         int poll = 0;
2074         char spoolfile[256];
2075
2076         if (working_ignetcfg == NULL) {
2077                 CtdlLogPrintf(CTDL_DEBUG, "No nodes defined - not polling\n");
2078                 return;
2079         }
2080
2081         /* Use the string tokenizer to grab one line at a time */
2082         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2083                 if(CtdlThreadCheckStop())
2084                         return;
2085                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2086                 extract_token(node, linebuf, 0, '|', sizeof node);
2087                 extract_token(secret, linebuf, 1, '|', sizeof secret);
2088                 extract_token(host, linebuf, 2, '|', sizeof host);
2089                 extract_token(port, linebuf, 3, '|', sizeof port);
2090                 if ( !IsEmptyStr(node) && !IsEmptyStr(secret) 
2091                    && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2092                         poll = full_poll;
2093                         if (poll == 0) {
2094                                 snprintf(spoolfile, 
2095                                                  sizeof spoolfile,
2096                                                  "%s/%s",
2097                                                  ctdl_netout_dir, 
2098                                                  node);
2099                                 if (access(spoolfile, R_OK) == 0) {
2100                                         poll = 1;
2101                                 }
2102                         }
2103                         if (poll) {
2104                                 network_poll_node(node, secret, host, port);
2105                         }
2106                 }
2107         }
2108
2109 }
2110
2111
2112
2113
2114 /*
2115  * It's ok if these directories already exist.  Just fail silently.
2116  */
2117 void create_spool_dirs(void) {
2118         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2119                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2120         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2121                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2122         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2123                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2124         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2125                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2126         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2127                 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2128         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2129                 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2130 }
2131
2132
2133
2134
2135
2136 /*
2137  * network_do_queue()
2138  * 
2139  * Run through the rooms doing various types of network stuff.
2140  */
2141 void *network_do_queue(void *args) {
2142         static time_t last_run = 0L;
2143         struct RoomProcList *ptr;
2144         int full_processing = 1;
2145         struct CitContext networkerCC;
2146
2147         /* Give the networker its own private CitContext */
2148         CtdlFillSystemContext(&networkerCC, "network");
2149         citthread_setspecific(MyConKey, (void *)&networkerCC );
2150
2151         /*
2152          * Run the full set of processing tasks no more frequently
2153          * than once every n seconds
2154          */
2155         if ( (time(NULL) - last_run) < config.c_net_freq ) {
2156                 full_processing = 0;
2157                 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n", config.c_net_freq - (time(NULL)- last_run));
2158         }
2159
2160         /*
2161          * This is a simple concurrency check to make sure only one queue run
2162          * is done at a time.  We could do this with a mutex, but since we
2163          * don't really require extremely fine granularity here, we'll do it
2164          * with a static variable instead.
2165          */
2166         if (doing_queue) return NULL;
2167         doing_queue = 1;
2168
2169         /* Load the IGnet Configuration into memory */
2170         load_working_ignetcfg();
2171
2172         /*
2173          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
2174          * then we poll everyone.  Otherwise we only poll nodes we have stuff
2175          * to send to.
2176          */
2177         network_poll_other_citadel_nodes(full_processing);
2178
2179         /*
2180          * Load the network map and filter list into memory.
2181          */
2182         read_network_map();
2183         filterlist = load_filter_list();
2184
2185         /* 
2186          * Go ahead and run the queue
2187          */
2188         if (full_processing && !CtdlThreadCheckStop()) {
2189                 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2190                 CtdlForEachRoom(network_queue_room, NULL);
2191         }
2192
2193         if (rplist != NULL) {
2194                 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2195                 while (rplist != NULL && !CtdlThreadCheckStop()) {
2196                         char spoolroomname[ROOMNAMELEN];
2197                         safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2198                         begin_critical_section(S_RPLIST);
2199
2200                         /* pop this record off the list */
2201                         ptr = rplist;
2202                         rplist = rplist->next;
2203                         free(ptr);
2204
2205                         /* invalidate any duplicate entries to prevent double processing */
2206                         for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2207                                 if (!strcasecmp(ptr->name, spoolroomname)) {
2208                                         ptr->name[0] = 0;
2209                                 }
2210                         }
2211
2212                         end_critical_section(S_RPLIST);
2213                         if (spoolroomname[0] != 0) {
2214                                 network_spoolout_room(spoolroomname);
2215                         }
2216                 }
2217         }
2218
2219         /* If there is anything in the inbound queue, process it */
2220         if (!CtdlThreadCheckStop())
2221                 network_do_spoolin();
2222
2223         /* Save the network map back to disk */
2224         write_network_map();
2225
2226         /* Free the filter list in memory */
2227         free_filter_list(filterlist);
2228         filterlist = NULL;
2229
2230         network_purge_spoolout();
2231
2232         CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2233
2234         if (full_processing) {
2235                 last_run = time(NULL);
2236         }
2237
2238         doing_queue = 0;
2239         if (!CtdlThreadCheckStop()) // Only reschedule if system is not stopping
2240                 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, time(NULL) + 60);
2241         else
2242                 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2243         return NULL;
2244 }
2245
2246
2247 /*
2248  * cmd_netp() - authenticate to the server as another Citadel node polling
2249  *            for network traffic
2250  */
2251 void cmd_netp(char *cmdbuf)
2252 {
2253         char node[256];
2254         char pass[256];
2255         int v;
2256
2257         char secret[256];
2258         char nexthop[256];
2259         char err_buf[SIZ];
2260
2261         /* Authenticate */
2262         extract_token(node, cmdbuf, 0, '|', sizeof node);
2263         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2264
2265         if (doing_queue) {
2266                 CtdlLogPrintf(CTDL_WARNING, "Network node <%s> refused - spooling\n", node);
2267                 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
2268                 return;
2269         }
2270
2271         /* load the IGnet Configuration to check node validity */
2272         load_working_ignetcfg();
2273         v = is_valid_node(nexthop, secret, node);
2274
2275         if (v != 0) {
2276                 snprintf(err_buf, sizeof err_buf,
2277                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2278                         node, CC->cs_host, CC->cs_addr
2279                 );
2280                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2281                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2282                 CtdlAideMessage(err_buf, "IGNet Networking.");
2283                 return;
2284         }
2285
2286         if (strcasecmp(pass, secret)) {
2287                 snprintf(err_buf, sizeof err_buf,
2288                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2289                         CC->cs_host, CC->cs_addr, node
2290                 );
2291                 CtdlLogPrintf(CTDL_WARNING, err_buf);
2292                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2293                 CtdlAideMessage(err_buf, "IGNet Networking.");
2294                 return;
2295         }
2296
2297         if (network_talking_to(node, NTT_CHECK)) {
2298                 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2299                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2300                 return;
2301         }
2302
2303         safestrncpy(CC->net_node, node, sizeof CC->net_node);
2304         network_talking_to(node, NTT_ADD);
2305         CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2306                 CC->net_node, CC->cs_host, CC->cs_addr
2307         );
2308         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2309 }
2310
2311
2312 int network_room_handler (struct ctdlroom *room)
2313 {
2314         network_queue_room(room, NULL);
2315         return 0;
2316 }
2317
2318
2319 /*
2320  * Module entry point
2321  */
2322 CTDL_MODULE_INIT(network)
2323 {
2324         if (!threading)
2325         {
2326                 create_spool_dirs();
2327                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2328                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2329                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2330                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2331                 CtdlRegisterRoomHook(network_room_handler);
2332                 CtdlRegisterCleanupHook(destroy_network_queue_room);
2333         }
2334         else
2335                 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2336         /* return our Subversion id for the Log */
2337         return "$Id$";
2338 }