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