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