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