]> code.citadel.org Git - citadel.git/blob - citadel/serv_network.c
* The IGnet map is now rewritten to disk only when it changes.
[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         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1252         msg->cm_fields['N'] = strdup(config.c_nodename);
1253         
1254
1255         /* prepend our node to the path */
1256         if (msg->cm_fields['P'] != NULL) {
1257                 oldpath = msg->cm_fields['P'];
1258                 msg->cm_fields['P'] = NULL;
1259         }
1260         else {
1261                 oldpath = strdup("unknown_user");
1262         }
1263         size = strlen(oldpath) + SIZ;
1264         msg->cm_fields['P'] = malloc(size);
1265         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1266         free(oldpath);
1267
1268         /* Now submit the message */
1269         valid = validate_recipients(recipient);
1270         if (valid != NULL) if (valid->num_error > 0) {
1271                 free(valid);
1272                 valid = NULL;
1273         }
1274         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1275                 strcpy(force_room, config.c_aideroom);
1276         }
1277         else {
1278                 strcpy(force_room, "");
1279         }
1280         if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1281                 strcpy(force_room, config.c_aideroom);
1282         }
1283         CtdlSubmitMsg(msg, valid, force_room);
1284
1285         /* Clean up */
1286         if (valid != NULL) free(valid);
1287         CtdlFreeMessage(msg);
1288         lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1289 }
1290
1291
1292
1293
1294 /*
1295  * Process a buffer containing a single message from a single file
1296  * from the inbound queue 
1297  */
1298 void network_process_buffer(char *buffer, long size) {
1299         struct CtdlMessage *msg;
1300         long pos;
1301         int field;
1302         struct recptypes *recp = NULL;
1303         char target_room[ROOMNAMELEN];
1304         struct ser_ret sermsg;
1305         char *oldpath = NULL;
1306         char filename[SIZ];
1307         FILE *fp;
1308         char nexthop[SIZ];
1309         unsigned char firstbyte;
1310         unsigned char lastbyte;
1311
1312         /* Validate just a little bit.  First byte should be FF and
1313          * last byte should be 00.
1314          */
1315         memcpy(&firstbyte, &buffer[0], 1);
1316         memcpy(&lastbyte, &buffer[size-1], 1);
1317         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1318                 lprintf(CTDL_ERR, "Corrupt message!  Ignoring.\n");
1319                 return;
1320         }
1321
1322         /* Set default target room to trash */
1323         strcpy(target_room, TWITROOM);
1324
1325         /* Load the message into memory */
1326         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1327         memset(msg, 0, sizeof(struct CtdlMessage));
1328         msg->cm_magic = CTDLMESSAGE_MAGIC;
1329         msg->cm_anon_type = buffer[1];
1330         msg->cm_format_type = buffer[2];
1331
1332         for (pos = 3; pos < size; ++pos) {
1333                 field = buffer[pos];
1334                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1335                 pos = pos + strlen(&buffer[(int)pos]);
1336         }
1337
1338         /* Check for message routing */
1339         if (msg->cm_fields['D'] != NULL) {
1340                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1341
1342                         /* route the message */
1343                         strcpy(nexthop, "");
1344                         if (is_valid_node(nexthop, NULL,
1345                            msg->cm_fields['D']) == 0) {
1346
1347                                 /* prepend our node to the path */
1348                                 if (msg->cm_fields['P'] != NULL) {
1349                                         oldpath = msg->cm_fields['P'];
1350                                         msg->cm_fields['P'] = NULL;
1351                                 }
1352                                 else {
1353                                         oldpath = strdup("unknown_user");
1354                                 }
1355                                 size = strlen(oldpath) + SIZ;
1356                                 msg->cm_fields['P'] = malloc(size);
1357                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1358                                         config.c_nodename, oldpath);
1359                                 free(oldpath);
1360
1361                                 /* serialize the message */
1362                                 serialize_message(&sermsg, msg);
1363
1364                                 /* now send it */
1365                                 if (strlen(nexthop) == 0) {
1366                                         strcpy(nexthop, msg->cm_fields['D']);
1367                                 }
1368                                 snprintf(filename, sizeof filename,
1369                                         "./network/spoolout/%s", nexthop);
1370                                 fp = fopen(filename, "ab");
1371                                 if (fp != NULL) {
1372                                         fwrite(sermsg.ser,
1373                                                 sermsg.len, 1, fp);
1374                                         fclose(fp);
1375                                 }
1376                                 free(sermsg.ser);
1377                                 CtdlFreeMessage(msg);
1378                                 return;
1379                         }
1380                         
1381                         else {  /* invalid destination node name */
1382
1383                                 network_bounce(msg,
1384 "A message you sent could not be delivered due to an invalid destination node"
1385 " name.  Please check the address and try sending the message again.\n");
1386                                 msg = NULL;
1387                                 return;
1388
1389                         }
1390                 }
1391         }
1392
1393         /*
1394          * Check to see if we already have a copy of this message, and
1395          * abort its processing if so.  (We used to post a warning to Aide>
1396          * every time this happened, but the network is now so densely
1397          * connected that it's inevitable.)
1398          */
1399         if (network_usetable(msg) != 0) {
1400                 return;
1401         }
1402
1403         /* Learn network topology from the path */
1404         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1405                 network_learn_topology(msg->cm_fields['N'], 
1406                                         msg->cm_fields['P']);
1407         }
1408
1409         /* Is the sending node giving us a very persuasive suggestion about
1410          * which room this message should be saved in?  If so, go with that.
1411          */
1412         if (msg->cm_fields['C'] != NULL) {
1413                 safestrncpy(target_room,
1414                         msg->cm_fields['C'],
1415                         sizeof target_room);
1416         }
1417
1418         /* Otherwise, does it have a recipient?  If so, validate it... */
1419         else if (msg->cm_fields['R'] != NULL) {
1420                 recp = validate_recipients(msg->cm_fields['R']);
1421                 if (recp != NULL) if (recp->num_error > 0) {
1422                         network_bounce(msg,
1423 "A message you sent could not be delivered due to an invalid address.\n"
1424 "Please check the address and try sending the message again.\n");
1425                         msg = NULL;
1426                         free(recp);
1427                         return;
1428                 }
1429                 strcpy(target_room, "");        /* no target room if mail */
1430         }
1431
1432         /* Our last shot at finding a home for this message is to see if
1433          * it has the O field (Originating room) set.
1434          */
1435         else if (msg->cm_fields['O'] != NULL) {
1436                 safestrncpy(target_room,
1437                         msg->cm_fields['O'],
1438                         sizeof target_room);
1439         }
1440
1441         /* Strip out fields that are only relevant during transit */
1442         if (msg->cm_fields['D'] != NULL) {
1443                 free(msg->cm_fields['D']);
1444                 msg->cm_fields['D'] = NULL;
1445         }
1446         if (msg->cm_fields['C'] != NULL) {
1447                 free(msg->cm_fields['C']);
1448                 msg->cm_fields['C'] = NULL;
1449         }
1450
1451         /* save the message into a room */
1452         if (PerformNetprocHooks(msg, target_room) == 0) {
1453                 msg->cm_flags = CM_SKIP_HOOKS;
1454                 CtdlSubmitMsg(msg, recp, target_room);
1455         }
1456         CtdlFreeMessage(msg);
1457         free(recp);
1458 }
1459
1460
1461 /*
1462  * Process a single message from a single file from the inbound queue 
1463  */
1464 void network_process_message(FILE *fp, long msgstart, long msgend) {
1465         long hold_pos;
1466         long size;
1467         char *buffer;
1468
1469         hold_pos = ftell(fp);
1470         size = msgend - msgstart + 1;
1471         buffer = malloc(size);
1472         if (buffer != NULL) {
1473                 fseek(fp, msgstart, SEEK_SET);
1474                 fread(buffer, size, 1, fp);
1475                 network_process_buffer(buffer, size);
1476                 free(buffer);
1477         }
1478
1479         fseek(fp, hold_pos, SEEK_SET);
1480 }
1481
1482
1483 /*
1484  * Process a single file from the inbound queue 
1485  */
1486 void network_process_file(char *filename) {
1487         FILE *fp;
1488         long msgstart = (-1L);
1489         long msgend = (-1L);
1490         long msgcur = 0L;
1491         int ch;
1492
1493
1494         fp = fopen(filename, "rb");
1495         if (fp == NULL) {
1496                 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1497                         filename, strerror(errno));
1498                 return;
1499         }
1500
1501         lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1502
1503         /* Look for messages in the data stream and break them out */
1504         while (ch = getc(fp), ch >= 0) {
1505         
1506                 if (ch == 255) {
1507                         if (msgstart >= 0L) {
1508                                 msgend = msgcur - 1;
1509                                 network_process_message(fp, msgstart, msgend);
1510                         }
1511                         msgstart = msgcur;
1512                 }
1513
1514                 ++msgcur;
1515         }
1516
1517         msgend = msgcur - 1;
1518         if (msgstart >= 0L) {
1519                 network_process_message(fp, msgstart, msgend);
1520         }
1521
1522         fclose(fp);
1523         unlink(filename);
1524 }
1525
1526
1527 /*
1528  * Process anything in the inbound queue
1529  */
1530 void network_do_spoolin(void) {
1531         DIR *dp;
1532         struct dirent *d;
1533         char filename[256];
1534
1535         dp = opendir("./network/spoolin");
1536         if (dp == NULL) return;
1537
1538         while (d = readdir(dp), d != NULL) {
1539                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1540                         snprintf(filename, sizeof filename,
1541                                 "./network/spoolin/%s", d->d_name);
1542                         network_process_file(filename);
1543                 }
1544         }
1545
1546         closedir(dp);
1547 }
1548
1549
1550 /*
1551  * Delete any files in the outbound queue that were intended
1552  * to be sent to nodes which no longer exist.
1553  */
1554 void network_purge_spoolout(void) {
1555         DIR *dp;
1556         struct dirent *d;
1557         char filename[256];
1558         char nexthop[256];
1559         int i;
1560
1561         dp = opendir("./network/spoolout");
1562         if (dp == NULL) return;
1563
1564         while (d = readdir(dp), d != NULL) {
1565                 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1566                         continue;
1567                 snprintf(filename, sizeof filename,
1568                         "./network/spoolout/%s", d->d_name);
1569
1570                 strcpy(nexthop, "");
1571                 i = is_valid_node(nexthop, NULL, d->d_name);
1572         
1573                 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1574                         unlink(filename);
1575                 }
1576         }
1577
1578
1579         closedir(dp);
1580 }
1581
1582
1583
1584 /*
1585  * receive network spool from the remote system
1586  */
1587 void receive_spool(int sock, char *remote_nodename) {
1588         long download_len;
1589         long bytes_received;
1590         char buf[SIZ];
1591         static char pbuf[IGNET_PACKET_SIZE];
1592         char tempfilename[PATH_MAX];
1593         long plen;
1594         FILE *fp;
1595
1596         strcpy(tempfilename, tmpnam(NULL));
1597         if (sock_puts(sock, "NDOP") < 0) return;
1598         if (sock_gets(sock, buf) < 0) return;
1599         lprintf(CTDL_DEBUG, "<%s\n", buf);
1600         if (buf[0] != '2') {
1601                 return;
1602         }
1603         download_len = extract_long(&buf[4], 0);
1604
1605         bytes_received = 0L;
1606         fp = fopen(tempfilename, "w");
1607         if (fp == NULL) {
1608                 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1609                         strerror(errno));
1610                 return;
1611         }
1612
1613         while (bytes_received < download_len) {
1614                 snprintf(buf, sizeof buf, "READ %ld|%ld",
1615                         bytes_received,
1616                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1617                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1618                 if (sock_puts(sock, buf) < 0) {
1619                         fclose(fp);
1620                         unlink(tempfilename);
1621                         return;
1622                 }
1623                 if (sock_gets(sock, buf) < 0) {
1624                         fclose(fp);
1625                         unlink(tempfilename);
1626                         return;
1627                 }
1628                 if (buf[0] == '6') {
1629                         plen = extract_long(&buf[4], 0);
1630                         if (sock_read(sock, pbuf, plen) < 0) {
1631                                 fclose(fp);
1632                                 unlink(tempfilename);
1633                                 return;
1634                         }
1635                         fwrite((char *) pbuf, plen, 1, fp);
1636                         bytes_received = bytes_received + plen;
1637                 }
1638         }
1639
1640         fclose(fp);
1641         if (sock_puts(sock, "CLOS") < 0) {
1642                 unlink(tempfilename);
1643                 return;
1644         }
1645         if (sock_gets(sock, buf) < 0) {
1646                 unlink(tempfilename);
1647                 return;
1648         }
1649         if (download_len > 0)
1650                 lprintf(CTDL_NOTICE, "Received %ld octets from <%s>",
1651                                 download_len, remote_nodename);
1652         lprintf(CTDL_DEBUG, "%s", buf);
1653         snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1654                 tempfilename, remote_nodename, (long) getpid());
1655         system(buf);
1656 }
1657
1658
1659
1660 /*
1661  * transmit network spool to the remote system
1662  */
1663 void transmit_spool(int sock, char *remote_nodename)
1664 {
1665         char buf[SIZ];
1666         char pbuf[4096];
1667         long plen;
1668         long bytes_to_write, thisblock, bytes_written;
1669         int fd;
1670         char sfname[128];
1671
1672         if (sock_puts(sock, "NUOP") < 0) return;
1673         if (sock_gets(sock, buf) < 0) return;
1674         lprintf(CTDL_DEBUG, "<%s\n", buf);
1675         if (buf[0] != '2') {
1676                 return;
1677         }
1678
1679         snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1680         fd = open(sfname, O_RDONLY);
1681         if (fd < 0) {
1682                 if (errno != ENOENT) {
1683                         lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1684                                 strerror(errno));
1685                 }
1686                 return;
1687         }
1688         bytes_written = 0;
1689         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1690                 bytes_to_write = plen;
1691                 while (bytes_to_write > 0L) {
1692                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1693                         if (sock_puts(sock, buf) < 0) {
1694                                 close(fd);
1695                                 return;
1696                         }
1697                         if (sock_gets(sock, buf) < 0) {
1698                                 close(fd);
1699                                 return;
1700                         }
1701                         thisblock = atol(&buf[4]);
1702                         if (buf[0] == '7') {
1703                                 if (sock_write(sock, pbuf,
1704                                    (int) thisblock) < 0) {
1705                                         close(fd);
1706                                         return;
1707                                 }
1708                                 bytes_to_write -= thisblock;
1709                                 bytes_written += thisblock;
1710                         } else {
1711                                 goto ABORTUPL;
1712                         }
1713                 }
1714         }
1715
1716 ABORTUPL:
1717         close(fd);
1718         if (sock_puts(sock, "UCLS 1") < 0) return;
1719         if (sock_gets(sock, buf) < 0) return;
1720         lprintf(CTDL_NOTICE, "Sent %ld octets to <%s>",
1721                         bytes_written, remote_nodename);
1722         lprintf(CTDL_DEBUG, "<%s\n", buf);
1723         if (buf[0] == '2') {
1724                 unlink(sfname);
1725         }
1726 }
1727
1728
1729
1730 /*
1731  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1732  */
1733 void network_poll_node(char *node, char *secret, char *host, char *port) {
1734         int sock;
1735         char buf[SIZ];
1736
1737         if (network_talking_to(node, NTT_CHECK)) return;
1738         network_talking_to(node, NTT_ADD);
1739         lprintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
1740
1741         sock = sock_connect(host, port, "tcp");
1742         if (sock < 0) {
1743                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1744                 network_talking_to(node, NTT_REMOVE);
1745                 return;
1746         }
1747         
1748         lprintf(CTDL_DEBUG, "Connected!\n");
1749
1750         /* Read the server greeting */
1751         if (sock_gets(sock, buf) < 0) goto bail;
1752         lprintf(CTDL_DEBUG, ">%s\n", buf);
1753
1754         /* Identify ourselves */
1755         snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1756         lprintf(CTDL_DEBUG, "<%s\n", buf);
1757         if (sock_puts(sock, buf) <0) goto bail;
1758         if (sock_gets(sock, buf) < 0) goto bail;
1759         lprintf(CTDL_DEBUG, ">%s\n", buf);
1760         if (buf[0] != '2') goto bail;
1761
1762         /* At this point we are authenticated. */
1763         receive_spool(sock, node);
1764         transmit_spool(sock, node);
1765
1766         sock_puts(sock, "QUIT");
1767 bail:   sock_close(sock);
1768         network_talking_to(node, NTT_REMOVE);
1769 }
1770
1771
1772
1773 /*
1774  * Poll other Citadel nodes and transfer inbound/outbound network data.
1775  * Set "full" to nonzero to force a poll of every node, or to zero to poll
1776  * only nodes to which we have data to send.
1777  */
1778 void network_poll_other_citadel_nodes(int full_poll) {
1779         int i;
1780         char linebuf[256];
1781         char node[SIZ];
1782         char host[256];
1783         char port[256];
1784         char secret[256];
1785         int poll = 0;
1786         char spoolfile[256];
1787
1788         if (working_ignetcfg == NULL) {
1789                 lprintf(CTDL_DEBUG, "No nodes defined - not polling\n");
1790                 return;
1791         }
1792
1793         /* Use the string tokenizer to grab one line at a time */
1794         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1795                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
1796                 extract_token(node, linebuf, 0, '|', sizeof node);
1797                 extract_token(secret, linebuf, 1, '|', sizeof secret);
1798                 extract_token(host, linebuf, 2, '|', sizeof host);
1799                 extract_token(port, linebuf, 3, '|', sizeof port);
1800                 if ( (strlen(node) > 0) && (strlen(secret) > 0) 
1801                    && (strlen(host) > 0) && strlen(port) > 0) {
1802                         poll = full_poll;
1803                         if (poll == 0) {
1804                                 snprintf(spoolfile, sizeof spoolfile,
1805                                         "./network/spoolout/%s", node);
1806                                 if (access(spoolfile, R_OK) == 0) {
1807                                         poll = 1;
1808                                 }
1809                         }
1810                         if (poll) {
1811                                 network_poll_node(node, secret, host, port);
1812                         }
1813                 }
1814         }
1815
1816 }
1817
1818
1819
1820
1821
1822
1823
1824 /*
1825  * network_do_queue()
1826  * 
1827  * Run through the rooms doing various types of network stuff.
1828  */
1829 void network_do_queue(void) {
1830         static time_t last_run = 0L;
1831         struct RoomProcList *ptr;
1832         int full_processing = 1;
1833
1834         /*
1835          * Run the full set of processing tasks no more frequently
1836          * than once every n seconds
1837          */
1838         if ( (time(NULL) - last_run) < config.c_net_freq ) {
1839                 full_processing = 0;
1840         }
1841
1842         /*
1843          * This is a simple concurrency check to make sure only one queue run
1844          * is done at a time.  We could do this with a mutex, but since we
1845          * don't really require extremely fine granularity here, we'll do it
1846          * with a static variable instead.
1847          */
1848         if (doing_queue) return;
1849         doing_queue = 1;
1850
1851         /* Load the IGnet Configuration into memory */
1852         load_working_ignetcfg();
1853
1854         /*
1855          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
1856          * then we poll everyone.  Otherwise we only poll nodes we have stuff
1857          * to send to.
1858          */
1859         network_poll_other_citadel_nodes(full_processing);
1860
1861         /*
1862          * Load the network map and filter list into memory.
1863          */
1864         read_network_map();
1865         filterlist = load_filter_list();
1866
1867         /* 
1868          * Go ahead and run the queue
1869          */
1870         if (full_processing) {
1871                 lprintf(CTDL_DEBUG, "network: loading outbound queue\n");
1872                 ForEachRoom(network_queue_room, NULL);
1873
1874                 lprintf(CTDL_DEBUG, "network: running outbound queue\n");
1875                 while (rplist != NULL) {
1876                         network_spoolout_room(rplist->name);
1877                         ptr = rplist;
1878                         rplist = rplist->next;
1879                         free(ptr);
1880                 }
1881         }
1882
1883         lprintf(CTDL_DEBUG, "network: processing inbound queue\n");
1884         network_do_spoolin();
1885
1886         /* Save the network map back to disk */
1887         write_network_map();
1888
1889         /* Free the filter list in memory */
1890         free_filter_list(filterlist);
1891         filterlist = NULL;
1892
1893         network_purge_spoolout();
1894
1895         lprintf(CTDL_DEBUG, "network: queue run completed\n");
1896
1897         if (full_processing) {
1898                 last_run = time(NULL);
1899         }
1900
1901         doing_queue = 0;
1902 }
1903
1904
1905 /*
1906  * cmd_netp() - authenticate to the server as another Citadel node polling
1907  *            for network traffic
1908  */
1909 void cmd_netp(char *cmdbuf)
1910 {
1911         char node[256];
1912         char pass[256];
1913         int v;
1914
1915         char secret[256];
1916         char nexthop[256];
1917
1918         /* Authenticate */
1919         extract_token(node, cmdbuf, 0, '|', sizeof node);
1920         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
1921
1922         if (doing_queue) {
1923                 lprintf(CTDL_WARNING, "Network node <%s> refused - spooling", node);
1924                 cprintf("%d spooling - try again in a few minutes\n",
1925                         ERROR + RESOURCE_BUSY);
1926                 return;
1927         }
1928
1929         /* load the IGnet Configuration to check node validity */
1930         load_working_ignetcfg();
1931         v = is_valid_node(nexthop, secret, node);
1932
1933         if (v != 0) {
1934                 lprintf(CTDL_WARNING, "Unknown node <%s>\n", node);
1935                 cprintf("%d authentication failed\n",
1936                         ERROR + PASSWORD_REQUIRED);
1937                 return;
1938         }
1939
1940         if (strcasecmp(pass, secret)) {
1941                 lprintf(CTDL_WARNING, "Bad password for network node <%s>", node);
1942                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1943                 return;
1944         }
1945
1946         if (network_talking_to(node, NTT_CHECK)) {
1947                 lprintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
1948                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1949                 return;
1950         }
1951
1952         safestrncpy(CC->net_node, node, sizeof CC->net_node);
1953         network_talking_to(node, NTT_ADD);
1954         lprintf(CTDL_NOTICE, "Network node <%s> logged in\n", CC->net_node);
1955         cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1956                 CC->net_node);
1957 }
1958
1959
1960
1961 /*
1962  * Module entry point
1963  */
1964 char *serv_network_init(void)
1965 {
1966         CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1967         CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1968         CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1969         CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1970         CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1971         return "$Id$";
1972 }