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