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