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