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