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