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