* Renamed "struct user" to "struct ctdluser"
[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         lprintf(7, "Spooling <%s>\n", room_to_spool);
697         if (getroom(&CC->room, room_to_spool) != 0) {
698                 lprintf(1, "ERROR: cannot load <%s>\n", room_to_spool);
699                 return;
700         }
701
702         memset(&sc, 0, sizeof(struct SpoolControl));
703         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
704
705         begin_critical_section(S_NETCONFIGS);
706         end_critical_section(S_NETCONFIGS);
707
708         fp = fopen(filename, "r");
709         if (fp == NULL) {
710                 lprintf(7, "Outbound batch processing skipped for <%s>\n",
711                         CC->room.QRname);
712                 end_critical_section(S_NETCONFIGS);
713                 return;
714         }
715
716         lprintf(5, "Outbound batch processing started for <%s>\n",
717                 CC->room.QRname);
718
719         while (fgets(buf, sizeof buf, fp) != NULL) {
720                 buf[strlen(buf)-1] = 0;
721
722                 extract(instr, buf, 0);
723                 if (!strcasecmp(instr, "lastsent")) {
724                         sc.lastsent = extract_long(buf, 1);
725                 }
726                 else if (!strcasecmp(instr, "listrecp")) {
727                         nptr = (struct namelist *)
728                                 mallok(sizeof(struct namelist));
729                         nptr->next = sc.listrecps;
730                         extract(nptr->name, buf, 1);
731                         sc.listrecps = nptr;
732                 }
733                 else if (!strcasecmp(instr, "digestrecp")) {
734                         nptr = (struct namelist *)
735                                 mallok(sizeof(struct namelist));
736                         nptr->next = sc.digestrecps;
737                         extract(nptr->name, buf, 1);
738                         sc.digestrecps = nptr;
739                 }
740                 else if (!strcasecmp(instr, "ignet_push_share")) {
741                         nptr = (struct namelist *)
742                                 mallok(sizeof(struct namelist));
743                         nptr->next = sc.ignet_push_shares;
744                         extract(nptr->name, buf, 1);
745                         sc.ignet_push_shares = nptr;
746                 }
747                 else {
748                         /* Preserve 'other' lines ... *unless* they happen to
749                          * be subscribe/unsubscribe pendings with expired
750                          * timestamps.
751                          */
752                         skipthisline = 0;
753                         if (!strncasecmp(buf, "subpending|", 11)) {
754                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
755                                         skipthisline = 1;
756                                 }
757                         }
758                         if (!strncasecmp(buf, "unsubpending|", 13)) {
759                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
760                                         skipthisline = 1;
761                                 }
762                         }
763
764                         if (skipthisline == 0) {
765                                 linesize = strlen(buf);
766                                 sc.misc = realloc(sc.misc,
767                                         (miscsize + linesize + 2) );
768                                 sprintf(&sc.misc[miscsize], "%s\n", buf);
769                                 miscsize = miscsize + linesize + 1;
770                         }
771                 }
772
773
774         }
775         fclose(fp);
776
777         /* If there are digest recipients, we have to build a digest */
778         if (sc.digestrecps != NULL) {
779                 sc.digestfp = tmpfile();
780                 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
781         }
782
783         /* Do something useful */
784         CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
785                 network_spool_msg, &sc);
786
787         /* If we wrote a digest, deliver it and then close it */
788         snprintf(buf, sizeof buf, "room_%s@%s",
789                 CC->room.QRname, config.c_fqdn);
790         for (i=0; i<strlen(buf); ++i) {
791                 buf[i] = tolower(buf[i]);
792                 if (isspace(buf[i])) buf[i] = '_';
793         }
794         if (sc.digestfp != NULL) {
795                 fprintf(sc.digestfp,    " -----------------------------------"
796                                         "------------------------------------"
797                                         "-------\n"
798                                         "You are subscribed to the '%s' "
799                                         "list.\n"
800                                         "To post to the list: %s\n",
801                                         CC->room.QRname, buf
802                 );
803                 network_deliver_digest(&sc);    /* deliver and close */
804         }
805
806         /* Now rewrite the config file */
807         fp = fopen(filename, "w");
808         if (fp == NULL) {
809                 lprintf(1, "ERROR: cannot open %s: %s\n",
810                         filename, strerror(errno));
811         }
812         else {
813                 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
814
815                 /* Write out the listrecps while freeing from memory at the
816                  * same time.  Am I clever or what?  :)
817                  */
818                 while (sc.listrecps != NULL) {
819                         fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
820                         nptr = sc.listrecps->next;
821                         phree(sc.listrecps);
822                         sc.listrecps = nptr;
823                 }
824                 /* Do the same for digestrecps */
825                 while (sc.digestrecps != NULL) {
826                         fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
827                         nptr = sc.digestrecps->next;
828                         phree(sc.digestrecps);
829                         sc.digestrecps = nptr;
830                 }
831                 while (sc.ignet_push_shares != NULL) {
832                         fprintf(fp, "ignet_push_share|%s\n",
833                                 sc.ignet_push_shares->name);
834                         nptr = sc.ignet_push_shares->next;
835                         phree(sc.ignet_push_shares);
836                         sc.ignet_push_shares = nptr;
837                 }
838                 if (sc.misc != NULL) {
839                         fwrite(sc.misc, strlen(sc.misc), 1, fp);
840                 }
841                 phree(sc.misc);
842
843                 fclose(fp);
844         }
845         end_critical_section(S_NETCONFIGS);
846
847         lprintf(5, "Outbound batch processing finished for <%s>\n",
848                 CC->room.QRname);
849 }
850
851
852 /*
853  * Batch up and send all outbound traffic from the current room
854  */
855 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
856         struct RoomProcList *ptr;
857
858         ptr = (struct RoomProcList *) mallok(sizeof (struct RoomProcList));
859         if (ptr == NULL) return;
860
861         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
862         ptr->next = rplist;
863         rplist = ptr;
864 }
865
866
867 /*
868  * Learn topology from path fields
869  */
870 void network_learn_topology(char *node, char *path) {
871         char nexthop[SIZ];
872         struct NetMap *nmptr;
873
874         strcpy(nexthop, "");
875
876         if (num_tokens(path, '!') < 3) return;
877         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
878                 if (!strcasecmp(nmptr->nodename, node)) {
879                         extract_token(nmptr->nexthop, path, 0, '!');
880                         nmptr->lastcontact = time(NULL);
881                         return;
882                 }
883         }
884
885         /* If we got here then it's not in the map, so add it. */
886         nmptr = (struct NetMap *) mallok(sizeof (struct NetMap));
887         strcpy(nmptr->nodename, node);
888         nmptr->lastcontact = time(NULL);
889         extract_token(nmptr->nexthop, path, 0, '!');
890         nmptr->next = the_netmap;
891         the_netmap = nmptr;
892 }
893
894
895
896
897 /*
898  * Bounce a message back to the sender
899  */
900 void network_bounce(struct CtdlMessage *msg, char *reason) {
901         char *oldpath = NULL;
902         char buf[SIZ];
903         char bouncesource[SIZ];
904         char recipient[SIZ];
905         struct recptypes *valid = NULL;
906         char force_room[ROOMNAMELEN];
907         static int serialnum = 0;
908         size_t size;
909
910         lprintf(9, "entering network_bounce()\n");
911
912         if (msg == NULL) return;
913
914         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
915
916         /* 
917          * Give it a fresh message ID
918          */
919         if (msg->cm_fields['I'] != NULL) {
920                 phree(msg->cm_fields['I']);
921         }
922         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
923                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
924         msg->cm_fields['I'] = strdoop(buf);
925
926         /*
927          * FIXME ... right now we're just sending a bounce; we really want to
928          * include the text of the bounced message.
929          */
930         if (msg->cm_fields['M'] != NULL) {
931                 phree(msg->cm_fields['M']);
932         }
933         msg->cm_fields['M'] = strdoop(reason);
934         msg->cm_format_type = 0;
935
936         /*
937          * Turn the message around
938          */
939         if (msg->cm_fields['R'] == NULL) {
940                 phree(msg->cm_fields['R']);
941         }
942
943         if (msg->cm_fields['D'] == NULL) {
944                 phree(msg->cm_fields['D']);
945         }
946
947         snprintf(recipient, sizeof recipient, "%s@%s",
948                 msg->cm_fields['A'], msg->cm_fields['N']);
949
950         if (msg->cm_fields['A'] == NULL) {
951                 phree(msg->cm_fields['A']);
952         }
953
954         if (msg->cm_fields['N'] == NULL) {
955                 phree(msg->cm_fields['N']);
956         }
957
958         msg->cm_fields['A'] = strdoop(BOUNCESOURCE);
959         msg->cm_fields['N'] = strdoop(config.c_nodename);
960         
961
962         /* prepend our node to the path */
963         if (msg->cm_fields['P'] != NULL) {
964                 oldpath = msg->cm_fields['P'];
965                 msg->cm_fields['P'] = NULL;
966         }
967         else {
968                 oldpath = strdoop("unknown_user");
969         }
970         size = strlen(oldpath) + SIZ;
971         msg->cm_fields['P'] = mallok(size);
972         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
973         phree(oldpath);
974
975         /* Now submit the message */
976         valid = validate_recipients(recipient);
977         if (valid != NULL) if (valid->num_error > 0) {
978                 phree(valid);
979                 valid = NULL;
980         }
981         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
982                 strcpy(force_room, config.c_aideroom);
983         }
984         else {
985                 strcpy(force_room, "");
986         }
987         if ( (valid == NULL) && (strlen(force_room) == 0) ) {
988                 strcpy(force_room, config.c_aideroom);
989         }
990         CtdlSubmitMsg(msg, valid, force_room);
991
992         /* Clean up */
993         if (valid != NULL) phree(valid);
994         CtdlFreeMessage(msg);
995         lprintf(9, "leaving network_bounce()\n");
996 }
997
998
999
1000
1001 /*
1002  * Process a buffer containing a single message from a single file
1003  * from the inbound queue 
1004  */
1005 void network_process_buffer(char *buffer, long size) {
1006         struct CtdlMessage *msg;
1007         long pos;
1008         int field;
1009         struct recptypes *recp = NULL;
1010         char target_room[ROOMNAMELEN];
1011         struct ser_ret sermsg;
1012         char *oldpath = NULL;
1013         char filename[SIZ];
1014         FILE *fp;
1015         char buf[SIZ];
1016
1017         /* Set default target room to trash */
1018         strcpy(target_room, TWITROOM);
1019
1020         /* Load the message into memory */
1021         msg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
1022         memset(msg, 0, sizeof(struct CtdlMessage));
1023         msg->cm_magic = CTDLMESSAGE_MAGIC;
1024         msg->cm_anon_type = buffer[1];
1025         msg->cm_format_type = buffer[2];
1026
1027         for (pos = 3; pos < size; ++pos) {
1028                 field = buffer[pos];
1029                 msg->cm_fields[field] = strdoop(&buffer[pos+1]);
1030                 pos = pos + strlen(&buffer[(int)pos]);
1031         }
1032
1033         /* Check for message routing */
1034         if (msg->cm_fields['D'] != NULL) {
1035                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1036
1037                         /* route the message */
1038                         if (is_valid_node(NULL, NULL,
1039                            msg->cm_fields['D']) == 0) {
1040
1041                                 /* prepend our node to the path */
1042                                 if (msg->cm_fields['P'] != NULL) {
1043                                         oldpath = msg->cm_fields['P'];
1044                                         msg->cm_fields['P'] = NULL;
1045                                 }
1046                                 else {
1047                                         oldpath = strdoop("unknown_user");
1048                                 }
1049                                 size = strlen(oldpath) + SIZ;
1050                                 msg->cm_fields['P'] = mallok(size);
1051                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1052                                         config.c_nodename, oldpath);
1053                                 phree(oldpath);
1054
1055                                 /* serialize the message */
1056                                 serialize_message(&sermsg, msg);
1057
1058                                 /* now send it */
1059                                 snprintf(filename, sizeof filename,
1060                                         "./network/spoolout/%s",
1061                                         msg->cm_fields['D']);
1062                                 fp = fopen(filename, "ab");
1063                                 if (fp != NULL) {
1064                                         fwrite(sermsg.ser,
1065                                                 sermsg.len, 1, fp);
1066                                         fclose(fp);
1067                                 }
1068                                 phree(sermsg.ser);
1069                                 CtdlFreeMessage(msg);
1070                                 return;
1071                         }
1072                         
1073                         else {  /* invalid destination node name */
1074
1075                                 network_bounce(msg,
1076 "A message you sent could not be delivered due to an invalid destination node"
1077 " name.  Please check the address and try sending the message again.\n");
1078                                 msg = NULL;
1079                                 return;
1080
1081                         }
1082                 }
1083         }
1084
1085         /*
1086          * Check to see if we already have a copy of this message
1087          */
1088         if (network_usetable(msg) != 0) {
1089                 snprintf(buf, sizeof buf,
1090                         "Loopzapper rejected message <%s> "
1091                         "from <%s> in <%s> @ <%s>\n",
1092                         ((msg->cm_fields['I']!=NULL)?(msg->cm_fields['I']):""),
1093                         ((msg->cm_fields['A']!=NULL)?(msg->cm_fields['A']):""),
1094                         ((msg->cm_fields['O']!=NULL)?(msg->cm_fields['O']):""),
1095                         ((msg->cm_fields['N']!=NULL)?(msg->cm_fields['N']):"")
1096                 );
1097                 aide_message(buf);
1098                 CtdlFreeMessage(msg);
1099                 msg = NULL;
1100                 return;
1101         }
1102
1103         /* Learn network topology from the path */
1104         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1105                 network_learn_topology(msg->cm_fields['N'], 
1106                                         msg->cm_fields['P']);
1107         }
1108
1109         /* Does it have a recipient?  If so, validate it... */
1110         if (msg->cm_fields['R'] != NULL) {
1111                 recp = validate_recipients(msg->cm_fields['R']);
1112                 if (recp != NULL) if (recp->num_error > 0) {
1113                         network_bounce(msg,
1114 "A message you sent could not be delivered due to an invalid address.\n"
1115 "Please check the address and try sending the message again.\n");
1116                         msg = NULL;
1117                         phree(recp);
1118                         return;
1119                 }
1120                 strcpy(target_room, "");        /* no target room if mail */
1121         }
1122
1123         else if (msg->cm_fields['C'] != NULL) {
1124                 safestrncpy(target_room,
1125                         msg->cm_fields['C'],
1126                         sizeof target_room);
1127         }
1128
1129         else if (msg->cm_fields['O'] != NULL) {
1130                 safestrncpy(target_room,
1131                         msg->cm_fields['O'],
1132                         sizeof target_room);
1133         }
1134
1135         /* Strip out fields that are only relevant during transit */
1136         if (msg->cm_fields['D'] != NULL) {
1137                 phree(msg->cm_fields['D']);
1138                 msg->cm_fields['D'] = NULL;
1139         }
1140         if (msg->cm_fields['C'] != NULL) {
1141                 phree(msg->cm_fields['C']);
1142                 msg->cm_fields['C'] = NULL;
1143         }
1144
1145         /* save the message into a room */
1146         if (PerformNetprocHooks(msg, target_room) == 0) {
1147                 msg->cm_flags = CM_SKIP_HOOKS;
1148                 CtdlSubmitMsg(msg, recp, target_room);
1149         }
1150         CtdlFreeMessage(msg);
1151         phree(recp);
1152 }
1153
1154
1155 /*
1156  * Process a single message from a single file from the inbound queue 
1157  */
1158 void network_process_message(FILE *fp, long msgstart, long msgend) {
1159         long hold_pos;
1160         long size;
1161         char *buffer;
1162
1163         hold_pos = ftell(fp);
1164         size = msgend - msgstart + 1;
1165         buffer = mallok(size);
1166         if (buffer != NULL) {
1167                 fseek(fp, msgstart, SEEK_SET);
1168                 fread(buffer, size, 1, fp);
1169                 network_process_buffer(buffer, size);
1170                 phree(buffer);
1171         }
1172
1173         fseek(fp, hold_pos, SEEK_SET);
1174 }
1175
1176
1177 /*
1178  * Process a single file from the inbound queue 
1179  */
1180 void network_process_file(char *filename) {
1181         FILE *fp;
1182         long msgstart = (-1L);
1183         long msgend = (-1L);
1184         long msgcur = 0L;
1185         int ch;
1186
1187         lprintf(7, "network: processing <%s>\n", filename);
1188
1189         fp = fopen(filename, "rb");
1190         if (fp == NULL) {
1191                 lprintf(5, "Error opening %s: %s\n",
1192                         filename, strerror(errno));
1193                 return;
1194         }
1195
1196         /* Look for messages in the data stream and break them out */
1197         while (ch = getc(fp), ch >= 0) {
1198         
1199                 if (ch == 255) {
1200                         if (msgstart >= 0L) {
1201                                 msgend = msgcur - 1;
1202                                 network_process_message(fp, msgstart, msgend);
1203                         }
1204                         msgstart = msgcur;
1205                 }
1206
1207                 ++msgcur;
1208         }
1209
1210         msgend = msgcur - 1;
1211         if (msgstart >= 0L) {
1212                 network_process_message(fp, msgstart, msgend);
1213         }
1214
1215         fclose(fp);
1216         unlink(filename);
1217 }
1218
1219
1220 /*
1221  * Process anything in the inbound queue
1222  */
1223 void network_do_spoolin(void) {
1224         DIR *dp;
1225         struct dirent *d;
1226         char filename[SIZ];
1227
1228         dp = opendir("./network/spoolin");
1229         if (dp == NULL) return;
1230
1231         while (d = readdir(dp), d != NULL) {
1232                 snprintf(filename, sizeof filename, "./network/spoolin/%s", d->d_name);
1233                 network_process_file(filename);
1234         }
1235
1236
1237         closedir(dp);
1238 }
1239
1240
1241
1242
1243
1244 /*
1245  * receive network spool from the remote system
1246  */
1247 void receive_spool(int sock, char *remote_nodename) {
1248         long download_len;
1249         long bytes_received;
1250         char buf[SIZ];
1251         static char pbuf[IGNET_PACKET_SIZE];
1252         char tempfilename[PATH_MAX];
1253         long plen;
1254         FILE *fp;
1255
1256         strcpy(tempfilename, tmpnam(NULL));
1257         if (sock_puts(sock, "NDOP") < 0) return;
1258         if (sock_gets(sock, buf) < 0) return;
1259         lprintf(9, "<%s\n", buf);
1260         if (buf[0] != '2') {
1261                 return;
1262         }
1263         download_len = extract_long(&buf[4], 0);
1264
1265         bytes_received = 0L;
1266         fp = fopen(tempfilename, "w");
1267         if (fp == NULL) {
1268                 lprintf(9, "cannot open download file locally: %s\n",
1269                         strerror(errno));
1270                 return;
1271         }
1272
1273         while (bytes_received < download_len) {
1274                 snprintf(buf, sizeof buf, "READ %ld|%ld",
1275                         bytes_received,
1276                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1277                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1278                 if (sock_puts(sock, buf) < 0) {
1279                         fclose(fp);
1280                         unlink(tempfilename);
1281                         return;
1282                 }
1283                 if (sock_gets(sock, buf) < 0) {
1284                         fclose(fp);
1285                         unlink(tempfilename);
1286                         return;
1287                 }
1288                 if (buf[0] == '6') {
1289                         plen = extract_long(&buf[4], 0);
1290                         if (sock_read(sock, pbuf, plen) < 0) {
1291                                 fclose(fp);
1292                                 unlink(tempfilename);
1293                                 return;
1294                         }
1295                         fwrite((char *) pbuf, plen, 1, fp);
1296                         bytes_received = bytes_received + plen;
1297                 }
1298         }
1299
1300         fclose(fp);
1301         if (sock_puts(sock, "CLOS") < 0) {
1302                 unlink(tempfilename);
1303                 return;
1304         }
1305         if (sock_gets(sock, buf) < 0) {
1306                 unlink(tempfilename);
1307                 return;
1308         }
1309         lprintf(9, "%s\n", buf);
1310         snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1311                 tempfilename, remote_nodename, (long) getpid());
1312         system(buf);
1313 }
1314
1315
1316
1317 /*
1318  * transmit network spool to the remote system
1319  */
1320 void transmit_spool(int sock, char *remote_nodename)
1321 {
1322         char buf[SIZ];
1323         char pbuf[4096];
1324         long plen;
1325         long bytes_to_write, thisblock;
1326         int fd;
1327         char sfname[128];
1328
1329         if (sock_puts(sock, "NUOP") < 0) return;
1330         if (sock_gets(sock, buf) < 0) return;
1331         lprintf(9, "<%s\n", buf);
1332         if (buf[0] != '2') {
1333                 return;
1334         }
1335
1336         snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1337         fd = open(sfname, O_RDONLY);
1338         if (fd < 0) {
1339                 if (errno == ENOENT) {
1340                         lprintf(9, "Nothing to send.\n");
1341                 } else {
1342                         lprintf(5, "cannot open upload file locally: %s\n",
1343                                 strerror(errno));
1344                 }
1345                 return;
1346         }
1347         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1348                 bytes_to_write = plen;
1349                 while (bytes_to_write > 0L) {
1350                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1351                         if (sock_puts(sock, buf) < 0) {
1352                                 close(fd);
1353                                 return;
1354                         }
1355                         if (sock_gets(sock, buf) < 0) {
1356                                 close(fd);
1357                                 return;
1358                         }
1359                         thisblock = atol(&buf[4]);
1360                         if (buf[0] == '7') {
1361                                 if (sock_write(sock, pbuf,
1362                                    (int) thisblock) < 0) {
1363                                         close(fd);
1364                                         return;
1365                                 }
1366                                 bytes_to_write = bytes_to_write - thisblock;
1367                         } else {
1368                                 goto ABORTUPL;
1369                         }
1370                 }
1371         }
1372
1373 ABORTUPL:
1374         close(fd);
1375         if (sock_puts(sock, "UCLS 1") < 0) return;
1376         if (sock_gets(sock, buf) < 0) return;
1377         lprintf(9, "<%s\n", buf);
1378         if (buf[0] == '2') {
1379                 unlink(sfname);
1380         }
1381 }
1382
1383
1384
1385 /*
1386  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1387  */
1388 void network_poll_node(char *node, char *secret, char *host, char *port) {
1389         int sock;
1390         char buf[SIZ];
1391
1392         if (network_talking_to(node, NTT_CHECK)) return;
1393         network_talking_to(node, NTT_ADD);
1394         lprintf(5, "Polling node <%s> at %s:%s\n", node, host, port);
1395
1396         sock = sock_connect(host, port, "tcp");
1397         if (sock < 0) {
1398                 lprintf(7, "Could not connect: %s\n", strerror(errno));
1399                 network_talking_to(node, NTT_REMOVE);
1400                 return;
1401         }
1402         
1403         lprintf(9, "Connected!\n");
1404
1405         /* Read the server greeting */
1406         if (sock_gets(sock, buf) < 0) goto bail;
1407         lprintf(9, ">%s\n", buf);
1408
1409         /* Identify ourselves */
1410         snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1411         lprintf(9, "<%s\n", buf);
1412         if (sock_puts(sock, buf) <0) goto bail;
1413         if (sock_gets(sock, buf) < 0) goto bail;
1414         lprintf(9, ">%s\n", buf);
1415         if (buf[0] != '2') goto bail;
1416
1417         /* At this point we are authenticated. */
1418         receive_spool(sock, node);
1419         transmit_spool(sock, node);
1420
1421         sock_puts(sock, "QUIT");
1422 bail:   sock_close(sock);
1423         network_talking_to(node, NTT_REMOVE);
1424 }
1425
1426
1427
1428 /*
1429  * Poll other Citadel nodes and transfer inbound/outbound network data.
1430  */
1431 void network_poll_other_citadel_nodes(void) {
1432         char *ignetcfg = NULL;
1433         int i;
1434         char linebuf[SIZ];
1435         char node[SIZ];
1436         char host[SIZ];
1437         char port[SIZ];
1438         char secret[SIZ];
1439
1440         ignetcfg = CtdlGetSysConfig(IGNETCFG);
1441         if (ignetcfg == NULL) return;   /* no nodes defined */
1442
1443         /* Use the string tokenizer to grab one line at a time */
1444         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
1445                 extract_token(linebuf, ignetcfg, i, '\n');
1446                 extract(node, linebuf, 0);
1447                 extract(secret, linebuf, 1);
1448                 extract(host, linebuf, 2);
1449                 extract(port, linebuf, 3);
1450                 if ( (strlen(node) > 0) && (strlen(secret) > 0) 
1451                    && (strlen(host) > 0) && strlen(port) > 0) {
1452                         network_poll_node(node, secret, host, port);
1453                 }
1454         }
1455
1456         phree(ignetcfg);
1457 }
1458
1459
1460
1461
1462
1463
1464
1465 /*
1466  * network_do_queue()
1467  * 
1468  * Run through the rooms doing various types of network stuff.
1469  */
1470 void network_do_queue(void) {
1471         static time_t last_run = 0L;
1472         struct RoomProcList *ptr;
1473
1474         /*
1475          * Run no more frequently than once every n seconds
1476          */
1477         if ( (time(NULL) - last_run) < config.c_net_freq ) return;
1478
1479         /*
1480          * This is a simple concurrency check to make sure only one queue run
1481          * is done at a time.  We could do this with a mutex, but since we
1482          * don't really require extremely fine granularity here, we'll do it
1483          * with a static variable instead.
1484          */
1485         if (doing_queue) return;
1486         doing_queue = 1;
1487         last_run = time(NULL);
1488
1489         /*
1490          * Poll other Citadel nodes.
1491          */
1492         network_poll_other_citadel_nodes();
1493
1494         /*
1495          * Load the network map and filter list into memory.
1496          */
1497         read_network_map();
1498         filterlist = load_filter_list();
1499
1500         /* 
1501          * Go ahead and run the queue
1502          */
1503         lprintf(7, "network: loading outbound queue\n");
1504         ForEachRoom(network_queue_room, NULL);
1505
1506         lprintf(7, "network: running outbound queue\n");
1507         while (rplist != NULL) {
1508                 network_spoolout_room(rplist->name);
1509                 ptr = rplist;
1510                 rplist = rplist->next;
1511                 phree(ptr);
1512         }
1513
1514         lprintf(7, "network: processing inbound queue\n");
1515         network_do_spoolin();
1516
1517         /* Save the network map back to disk */
1518         write_network_map();
1519
1520         /* Free the filter list in memory */
1521         free_filter_list(filterlist);
1522         filterlist = NULL;
1523
1524         lprintf(7, "network: queue run completed\n");
1525         doing_queue = 0;
1526 }
1527
1528
1529 /*
1530  * cmd_netp() - authenticate to the server as another Citadel node polling
1531  *              for network traffic
1532  */
1533 void cmd_netp(char *cmdbuf)
1534 {
1535         char node[SIZ];
1536         char pass[SIZ];
1537
1538         char secret[SIZ];
1539         char nexthop[SIZ];
1540
1541         if (doing_queue) {
1542                 cprintf("%d spooling - try again in a few minutes\n", ERROR);
1543                 return;
1544         }
1545
1546         extract(node, cmdbuf, 0);
1547         extract(pass, cmdbuf, 1);
1548
1549         if (is_valid_node(nexthop, secret, node) != 0) {
1550                 cprintf("%d authentication failed\n", ERROR);
1551                 return;
1552         }
1553
1554         if (strcasecmp(pass, secret)) {
1555                 cprintf("%d authentication failed\n", ERROR);
1556                 return;
1557         }
1558
1559         if (network_talking_to(node, NTT_CHECK)) {
1560                 cprintf("%d Already talking to %s right now\n", ERROR, node);
1561                 return;
1562         }
1563
1564         safestrncpy(CC->net_node, node, sizeof CC->net_node);
1565         network_talking_to(node, NTT_ADD);
1566         cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1567                 CC->net_node);
1568 }
1569
1570
1571
1572
1573
1574 /*
1575  * Module entry point
1576  */
1577 char *serv_network_init(void)
1578 {
1579         CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1580         CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1581         CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1582         CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1583         return "$Id$";
1584 }