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