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