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