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