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