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