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