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