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