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