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