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