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