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