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