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