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