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