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