a92789124361ccc7cf0ce93b21f960e3988c6255
[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-2001 by Art Cancro and others.
8  * This code is released under the terms of the GNU General Public License.
9  *
10  */
11
12 /*
13  * FIXME do something about concurrency issues:
14  * 1. Don't allow the two nodes to poll each other at the same time
15  * 2. Don't allow polls during network processing
16  * 3. Kill Bill Gates using either a chainsaw or a wood chipper
17  */
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <signal.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <dirent.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <sys/wait.h>
41 #include <string.h>
42 #include <limits.h>
43 #include "citadel.h"
44 #include "server.h"
45 #include "sysdep_decls.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "dynloader.h"
50 #include "room_ops.h"
51 #include "user_ops.h"
52 #include "policy.h"
53 #include "database.h"
54 #include "msgbase.h"
55 #include "tools.h"
56 #include "internet_addressing.h"
57 #include "serv_network.h"
58 #include "clientsocket.h"
59
60
61 /*
62  * When we do network processing, it's accomplished in two passes; one to
63  * gather a list of rooms and one to actually do them.  It's ok that rplist
64  * is global; this process *only* runs as part of the housekeeping loop and
65  * therefore only one will run at a time.
66  */
67 struct RoomProcList {
68         struct RoomProcList *next;
69         char name[ROOMNAMELEN];
70 };
71
72 struct RoomProcList *rplist = NULL;
73
74
75 /*
76  * We build a map of the Citadel network during network runs.
77  */
78 struct NetMap {
79         struct NetMap *next;
80         char nodename[SIZ];
81         time_t lastcontact;
82         char nexthop[SIZ];
83 };
84
85 struct NetMap *the_netmap = NULL;
86
87
88
89 /*
90  * network_talking_to()  --  concurrency checker
91  */
92 int network_talking_to(char *nodename, int operation) {
93
94         static char *nttlist = NULL;
95         char *ptr = NULL;
96         int i;
97         char buf[SIZ];
98         int retval = 0;
99
100         begin_critical_section(S_NTTLIST);
101
102         switch(operation) {
103
104                 case NTT_ADD:
105                         if (nttlist == NULL) nttlist = strdoop("");
106                         if (nttlist == NULL) break;
107                         nttlist = (char *)reallok(nttlist,
108                                 (strlen(nttlist) + strlen(nodename) + 3) );
109                         strcat(nttlist, "|");
110                         strcat(nttlist, nodename);
111                         break;
112
113                 case NTT_REMOVE:
114                         if (nttlist == NULL) break;
115                         if (strlen(nttlist) == 0) break;
116                         ptr = mallok(strlen(nttlist));
117                         if (ptr == NULL) break;
118                         strcpy(ptr, "");
119                         for (i = 0; i < num_tokens(nttlist, '|'); ++i) {
120                                 extract(buf, nttlist, i);
121                                 if ( (strlen(buf) > 0)
122                                      && (strcasecmp(buf, nodename)) ) {
123                                                 strcat(ptr, buf);
124                                                 strcat(ptr, "|");
125                                 }
126                         }
127                         phree(nttlist);
128                         nttlist = ptr;
129                         break;
130
131                 case NTT_CHECK:
132                         if (nttlist == NULL) break;
133                         if (strlen(nttlist) == 0) break;
134                         for (i = 0; i < num_tokens(nttlist, '|'); ++i) {
135                                 extract(buf, nttlist, i);
136                                 if (!strcasecmp(buf, nodename)) ++retval;
137                         }
138                         break;
139         }
140
141         if (nttlist != NULL) lprintf(9, "nttlist=<%s>\n", nttlist);
142         end_critical_section(S_NTTLIST);
143         return(retval);
144 }
145
146
147
148
149
150
151
152 /* 
153  * Read the network map from its configuration file into memory.
154  */
155 void read_network_map(void) {
156         char *serialized_map = NULL;
157         int i;
158         char buf[SIZ];
159         struct NetMap *nmptr;
160
161         serialized_map = CtdlGetSysConfig(IGNETMAP);
162         if (serialized_map == NULL) return;     /* if null, no entries */
163
164         /* Use the string tokenizer to grab one line at a time */
165         for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
166                 extract_token(buf, serialized_map, i, '\n');
167                 nmptr = (struct NetMap *) mallok(sizeof(struct NetMap));
168                 extract(nmptr->nodename, buf, 0);
169                 nmptr->lastcontact = extract_long(buf, 1);
170                 extract(nmptr->nexthop, buf, 2);
171                 nmptr->next = the_netmap;
172                 the_netmap = nmptr;
173         }
174
175         phree(serialized_map);
176 }
177
178
179 /*
180  * Write the network map from memory back to the configuration file.
181  */
182 void write_network_map(void) {
183         char *serialized_map = NULL;
184         struct NetMap *nmptr;
185
186         serialized_map = strdoop("");
187
188         if (the_netmap != NULL) {
189                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
190                         serialized_map = reallok(serialized_map,
191                                                 (strlen(serialized_map)+SIZ) );
192                         if (strlen(nmptr->nodename) > 0) {
193                                 sprintf(&serialized_map[strlen(serialized_map)],
194                                         "%s|%ld|%s\n",
195                                         nmptr->nodename,
196                                         nmptr->lastcontact,
197                                         nmptr->nexthop);
198                         }
199                 }
200         }
201
202         CtdlPutSysConfig(IGNETMAP, serialized_map);
203         phree(serialized_map);
204
205         /* Now free the list */
206         while (the_netmap != NULL) {
207                 nmptr = the_netmap->next;
208                 phree(the_netmap);
209                 the_netmap = nmptr;
210         }
211 }
212
213
214
215 /* 
216  * Check the network map and determine whether the supplied node name is
217  * valid.  If it is not a neighbor node, supply the name of a neighbor node
218  * which is the next hop.  If it *is* a neighbor node, we also fill in the
219  * shared secret.
220  */
221 int is_valid_node(char *nexthop, char *secret, char *node) {
222         char *ignetcfg = NULL;
223         int i;
224         char linebuf[SIZ];
225         char buf[SIZ];
226         int retval;
227         struct NetMap *nmptr;
228
229         if (node == NULL) {
230                 return(-1);
231         }
232
233         /*
234          * First try the neighbor nodes
235          */
236         ignetcfg = CtdlGetSysConfig(IGNETCFG);
237         if (ignetcfg == NULL) {
238                 if (nexthop != NULL) {
239                         strcpy(nexthop, "");
240                 }
241                 return(-1);
242         }
243
244         retval = (-1);
245         if (nexthop != NULL) {
246                 strcpy(nexthop, "");
247         }
248
249         /* Use the string tokenizer to grab one line at a time */
250         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
251                 extract_token(linebuf, ignetcfg, i, '\n');
252                 extract(buf, linebuf, 0);
253                 if (!strcasecmp(buf, node)) {
254                         if (nexthop != NULL) {
255                                 strcpy(nexthop, "");
256                         }
257                         if (secret != NULL) {
258                                 extract(secret, linebuf, 1);
259                         }
260                         retval = 0;
261                 }
262         }
263
264         phree(ignetcfg);
265         if (retval == 0) {
266                 return(retval);         /* yup, it's a direct neighbor */
267         }
268
269         /*      
270          * If we get to this point we have to see if we know the next hop
271          */
272         if (the_netmap != NULL) {
273                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
274                         if (!strcasecmp(nmptr->nodename, node)) {
275                                 if (nexthop != NULL) {
276                                         strcpy(nexthop, nmptr->nexthop);
277                                 }
278                                 return(0);
279                         }
280                 }
281         }
282
283         /*
284          * If we get to this point, the supplied node name is bogus.
285          */
286         lprintf(5, "Invalid node name <%s>\n", node);
287         return(-1);
288 }
289
290
291
292
293
294 void cmd_gnet(char *argbuf) {
295         char filename[SIZ];
296         char buf[SIZ];
297         FILE *fp;
298
299         if (CtdlAccessCheck(ac_room_aide)) return;
300         assoc_file_name(filename, &CC->quickroom, "netconfigs");
301         cprintf("%d Network settings for room #%ld <%s>\n",
302                 LISTING_FOLLOWS,
303                 CC->quickroom.QRnumber, CC->quickroom.QRname);
304
305         fp = fopen(filename, "r");
306         if (fp != NULL) {
307                 while (fgets(buf, sizeof buf, fp) != NULL) {
308                         buf[strlen(buf)-1] = 0;
309                         cprintf("%s\n", buf);
310                 }
311                 fclose(fp);
312         }
313
314         cprintf("000\n");
315 }
316
317
318 void cmd_snet(char *argbuf) {
319         char tempfilename[SIZ];
320         char filename[SIZ];
321         char buf[SIZ];
322         FILE *fp;
323
324         if (CtdlAccessCheck(ac_room_aide)) return;
325         safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
326         assoc_file_name(filename, &CC->quickroom, "netconfigs");
327
328         fp = fopen(tempfilename, "w");
329         if (fp == NULL) {
330                 cprintf("%d Cannot open %s: %s\n",
331                         ERROR+INTERNAL_ERROR,
332                         tempfilename,
333                         strerror(errno));
334         }
335
336         cprintf("%d %s\n", SEND_LISTING, tempfilename);
337         while (client_gets(buf), strcmp(buf, "000")) {
338                 fprintf(fp, "%s\n", buf);
339         }
340         fclose(fp);
341
342         /* Now copy the temp file to its permanent location
343          * (We use /bin/mv instead of link() because they may be on
344          * different filesystems)
345          */
346         unlink(filename);
347         snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
348         system(buf);
349 }
350
351
352
353 /*
354  * Spools out one message from the list.
355  */
356 void network_spool_msg(long msgnum, void *userdata) {
357         struct SpoolControl *sc;
358         struct namelist *nptr;
359         int err;
360         int i;
361         char *instr = NULL;
362         char *newpath = NULL;
363         size_t instr_len = SIZ;
364         struct CtdlMessage *msg = NULL;
365         struct CtdlMessage *imsg;
366         struct ser_ret sermsg;
367         FILE *fp;
368         char filename[SIZ];
369         char buf[SIZ];
370         int bang = 0;
371         int send = 1;
372         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
373
374         sc = (struct SpoolControl *)userdata;
375
376         /*
377          * Process mailing list recipients
378          */
379         if (sc->listrecps != NULL) {
380         
381                 /* First, copy it to the spoolout room */
382                 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
383                 if (err != 0) return;
384
385                 /* 
386                  * Figure out how big a buffer we need to allocate
387                  */
388                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
389                         instr_len = instr_len + strlen(nptr->name);
390                 }
391         
392                 /*
393                  * allocate...
394                  */
395                 lprintf(9, "Generating delivery instructions\n");
396                 instr = mallok(instr_len);
397                 if (instr == NULL) {
398                         lprintf(1, "Cannot allocate %d bytes for instr...\n",
399                                 instr_len);
400                         abort();
401                 }
402                 sprintf(instr,
403                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
404                         "bounceto|postmaster@%s\n" ,
405                         SPOOLMIME, msgnum, time(NULL), config.c_fqdn );
406         
407                 /* Generate delivery instructions for each recipient */
408                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
409                         sprintf(&instr[strlen(instr)], "remote|%s|0||\n",
410                                 nptr->name);
411                 }
412         
413                 /*
414                  * Generate a message from the instructions
415                  */
416                 imsg = mallok(sizeof(struct CtdlMessage));
417                 memset(imsg, 0, sizeof(struct CtdlMessage));
418                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
419                 imsg->cm_anon_type = MES_NORMAL;
420                 imsg->cm_format_type = FMT_RFC822;
421                 imsg->cm_fields['A'] = strdoop("Citadel");
422                 imsg->cm_fields['M'] = instr;
423         
424                 /* Save delivery instructions in spoolout room */
425                 CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL);
426                 CtdlFreeMessage(imsg);
427         }
428         
429         /*
430          * Process IGnet push shares
431          */
432         if (sc->ignet_push_shares != NULL) {
433         
434                 msg = CtdlFetchMessage(msgnum);
435                 if (msg != NULL) {
436
437                         /* Prepend our node name to the Path field whenever
438                          * sending a message to another IGnet node
439                          */
440                         if (msg->cm_fields['P'] == NULL) {
441                                 msg->cm_fields['P'] = strdoop("username");
442                         }
443                         newpath = mallok(strlen(msg->cm_fields['P']) + 
444                                         strlen(config.c_nodename) + 2);
445                         sprintf(newpath, "%s!%s", config.c_nodename,
446                                         msg->cm_fields['P']);
447                         phree(msg->cm_fields['P']);
448                         msg->cm_fields['P'] = newpath;
449
450                         /*
451                          * Force the message to appear in the correct room
452                          * on the far end by setting the C field correctly
453                          */
454                         if (msg->cm_fields['C'] != NULL) {
455                                 phree(msg->cm_fields['C']);
456                         }
457                         msg->cm_fields['C'] = strdoop(CC->quickroom.QRname);
458
459                         /*
460                          * Determine if this message is set to be deleted
461                          * after sending out on the network
462                          */
463                         if (msg->cm_fields['S'] != NULL) {
464                                 if (!strcasecmp(msg->cm_fields['S'],
465                                    "CANCEL")) {
466                                         delete_after_send = 1;
467                                 }
468                         }
469
470                         /* 
471                          * Now serialize it for transmission
472                          */
473                         serialize_message(&sermsg, msg);
474
475                         /* Now send it to every node */
476                         for (nptr = sc->ignet_push_shares; nptr != NULL;
477                             nptr = nptr->next) {
478
479                                 send = 1;
480
481                                 /* Check for valid node name */
482                                 if (is_valid_node(NULL,NULL,nptr->name) != 0) {
483                                         lprintf(3, "Invalid node <%s>\n",
484                                                 nptr->name);
485                                         send = 0;
486                                 }
487
488                                 /* Check for split horizon */
489                                 lprintf(9, "Path is %s\n", msg->cm_fields['P']);
490                                 bang = num_tokens(msg->cm_fields['P'], '!');
491                                 if (bang > 1) for (i=0; i<(bang-1); ++i) {
492                                         extract_token(buf, msg->cm_fields['P'],
493                                                 i, '!');
494                                         if (!strcasecmp(buf, nptr->name)) {
495                                                 send = 0;
496                                         }
497                                 }
498
499                                 /* Send the message */
500                                 if (send == 1) {
501                                         sprintf(filename,
502                                                 "./network/spoolout/%s",
503                                                 nptr->name);
504                                         fp = fopen(filename, "ab");
505                                         if (fp != NULL) {
506                                                 fwrite(sermsg.ser,
507                                                         sermsg.len, 1, fp);
508                                                 fclose(fp);
509                                         }
510                                 }
511                         }
512                         phree(sermsg.ser);
513                         CtdlFreeMessage(msg);
514                 }
515         }
516
517         /* update lastsent */
518         sc->lastsent = msgnum;
519
520         /* Delete this message if delete-after-send is set */
521         if (delete_after_send) {
522                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
523         }
524
525 }
526         
527
528
529
530 /*
531  * Batch up and send all outbound traffic from the current room
532  */
533 void network_spoolout_room(char *room_to_spool) {
534         char filename[SIZ];
535         char buf[SIZ];
536         char instr[SIZ];
537         FILE *fp;
538         struct SpoolControl sc;
539         /* struct namelist *digestrecps = NULL; */
540         struct namelist *nptr;
541
542         lprintf(7, "Spooling <%s>\n", room_to_spool);
543         if (getroom(&CC->quickroom, room_to_spool) != 0) {
544                 lprintf(1, "ERROR: cannot load <%s>\n", room_to_spool);
545                 return;
546         }
547
548         memset(&sc, 0, sizeof(struct SpoolControl));
549         assoc_file_name(filename, &CC->quickroom, "netconfigs");
550
551         fp = fopen(filename, "r");
552         if (fp == NULL) {
553                 lprintf(7, "Outbound batch processing skipped for <%s>\n",
554                         CC->quickroom.QRname);
555                 return;
556         }
557
558         lprintf(5, "Outbound batch processing started for <%s>\n",
559                 CC->quickroom.QRname);
560
561         while (fgets(buf, sizeof buf, fp) != NULL) {
562                 buf[strlen(buf)-1] = 0;
563
564                 extract(instr, buf, 0);
565                 if (!strcasecmp(instr, "lastsent")) {
566                         sc.lastsent = extract_long(buf, 1);
567                 }
568                 else if (!strcasecmp(instr, "listrecp")) {
569                         nptr = (struct namelist *)
570                                 mallok(sizeof(struct namelist));
571                         nptr->next = sc.listrecps;
572                         extract(nptr->name, buf, 1);
573                         sc.listrecps = nptr;
574                 }
575                 else if (!strcasecmp(instr, "ignet_push_share")) {
576                         nptr = (struct namelist *)
577                                 mallok(sizeof(struct namelist));
578                         nptr->next = sc.ignet_push_shares;
579                         extract(nptr->name, buf, 1);
580                         sc.ignet_push_shares = nptr;
581                 }
582
583
584         }
585         fclose(fp);
586
587
588         /* Do something useful */
589         CtdlForEachMessage(MSGS_GT, sc.lastsent, (-63), NULL, NULL,
590                 network_spool_msg, &sc);
591
592
593         /* Now rewrite the config file */
594         fp = fopen(filename, "w");
595         if (fp == NULL) {
596                 lprintf(1, "ERROR: cannot open %s: %s\n",
597                         filename, strerror(errno));
598         }
599         else {
600                 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
601
602                 /* Write out the listrecps while freeing from memory at the
603                  * same time.  Am I clever or what?  :)
604                  */
605                 while (sc.listrecps != NULL) {
606                         fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
607                         nptr = sc.listrecps->next;
608                         phree(sc.listrecps);
609                         sc.listrecps = nptr;
610                 }
611                 while (sc.ignet_push_shares != NULL) {
612                         fprintf(fp, "ignet_push_share|%s\n",
613                                 sc.ignet_push_shares->name);
614                         nptr = sc.ignet_push_shares->next;
615                         phree(sc.ignet_push_shares);
616                         sc.ignet_push_shares = nptr;
617                 }
618
619                 fclose(fp);
620         }
621
622         lprintf(5, "Outbound batch processing finished for <%s>\n",
623                 CC->quickroom.QRname);
624 }
625
626
627 /*
628  * Batch up and send all outbound traffic from the current room
629  */
630 void network_queue_room(struct quickroom *qrbuf, void *data) {
631         struct RoomProcList *ptr;
632
633         ptr = (struct RoomProcList *) mallok(sizeof (struct RoomProcList));
634         if (ptr == NULL) return;
635
636         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
637         ptr->next = rplist;
638         rplist = ptr;
639 }
640
641
642 /*
643  * Learn topology from path fields
644  */
645 void network_learn_topology(char *node, char *path) {
646         char nexthop[SIZ];
647         struct NetMap *nmptr;
648
649         strcpy(nexthop, "");
650
651         if (num_tokens(path, '!') < 3) return;
652         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
653                 if (!strcasecmp(nmptr->nodename, node)) {
654                         extract_token(nmptr->nexthop, path, 0, '!');
655                         nmptr->lastcontact = time(NULL);
656                         return;
657                 }
658         }
659
660         /* If we got here then it's not in the map, so add it. */
661         nmptr = (struct NetMap *) mallok(sizeof (struct NetMap));
662         strcpy(nmptr->nodename, node);
663         nmptr->lastcontact = time(NULL);
664         extract_token(nmptr->nexthop, path, 0, '!');
665         nmptr->next = the_netmap;
666         the_netmap = nmptr;
667 }
668
669
670
671
672 /*
673  * Bounce a message back to the sender
674  */
675 void network_bounce(struct CtdlMessage *msg, char *reason) {
676         static int serialnum = 0;
677         FILE *fp;
678         char filename[SIZ];
679         struct ser_ret sermsg;
680         char *oldpath = NULL;
681         char buf[SIZ];
682
683         lprintf(9, "entering network_bounce()\n");
684
685         if (msg == NULL) return;
686
687         /* 
688          * Give it a fresh message ID
689          */
690         if (msg->cm_fields['I'] != NULL) {
691                 phree(msg->cm_fields['I']);
692         }
693         sprintf(buf, "%ld.%04x.%04x@%s",
694                 time(NULL), getpid(), ++serialnum, config.c_fqdn);
695         msg->cm_fields['I'] = strdoop(buf);
696
697         /*
698          * FIXME ... right now we're just sending a bounce; we really want to
699          * include the text of the bounced message.
700          */
701         if (msg->cm_fields['M'] != NULL) {
702                 phree(msg->cm_fields['M']);
703         }
704         msg->cm_fields['M'] = strdoop(reason);
705         msg->cm_format_type = 0;
706
707         /*
708          * Turn the message around
709          */
710         if (msg->cm_fields['R'] == NULL) {
711                 phree(msg->cm_fields['R']);
712         }
713
714         if (msg->cm_fields['D'] == NULL) {
715                 phree(msg->cm_fields['D']);
716         }
717
718         msg->cm_fields['R'] = msg->cm_fields['A'];
719         msg->cm_fields['D'] = msg->cm_fields['N'];
720         msg->cm_fields['A'] = strdoop(BOUNCESOURCE);
721         msg->cm_fields['N'] = strdoop(config.c_nodename);
722         
723         if (!strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
724                 phree(msg->cm_fields['D']);
725         }
726
727         /*
728          * If this is a bounce of a bounce, send it to the Aide> room
729          * instead of looping around forever
730          */
731         if (msg->cm_fields['D'] == NULL) if (msg->cm_fields['R'] != NULL)
732            if (!strcasecmp(msg->cm_fields['R'], BOUNCESOURCE)) {
733                 phree(msg->cm_fields['R']);
734                 if (msg->cm_fields['C'] != NULL) {
735                         phree(msg->cm_fields['C']);
736                 }
737                 msg->cm_fields['C'] = strdoop(AIDEROOM);
738         }
739
740         /* prepend our node to the path */
741         if (msg->cm_fields['P'] != NULL) {
742                 oldpath = msg->cm_fields['P'];
743                 msg->cm_fields['P'] = NULL;
744         }
745         else {
746                 oldpath = strdoop("unknown_user");
747         }
748         msg->cm_fields['P'] = mallok(strlen(oldpath) + SIZ);
749         sprintf(msg->cm_fields['P'], "%s!%s", config.c_nodename, oldpath);
750         phree(oldpath);
751
752         /* serialize the message */
753         serialize_message(&sermsg, msg);
754
755         /* now send it */
756         sprintf(filename, "./network/spoolin/bounce.%04x.%04x",
757                 getpid(), serialnum);
758
759         fp = fopen(filename, "ab");
760         if (fp != NULL) {
761                 fwrite(sermsg.ser,
762                         sermsg.len, 1, fp);
763                 fclose(fp);
764         }
765         phree(sermsg.ser);
766         CtdlFreeMessage(msg);
767         lprintf(9, "leaving network_bounce()\n");
768 }
769
770
771
772
773 /*
774  * Process a buffer containing a single message from a single file
775  * from the inbound queue 
776  */
777 void network_process_buffer(char *buffer, long size) {
778         struct CtdlMessage *msg;
779         long pos;
780         int field;
781         int a;
782         int e = MES_LOCAL;
783         struct usersupp tempUS;
784         char recp[SIZ];
785         char target_room[ROOMNAMELEN];
786         struct ser_ret sermsg;
787         char *oldpath = NULL;
788         char filename[SIZ];
789         FILE *fp;
790
791         /* Set default target room to trash */
792         strcpy(target_room, TWITROOM);
793
794         /* Load the message into memory */
795         msg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
796         memset(msg, 0, sizeof(struct CtdlMessage));
797         msg->cm_magic = CTDLMESSAGE_MAGIC;
798         msg->cm_anon_type = buffer[1];
799         msg->cm_format_type = buffer[2];
800
801         for (pos = 3; pos < size; ++pos) {
802                 field = buffer[pos];
803                 msg->cm_fields[field] = strdoop(&buffer[pos+1]);
804                 pos = pos + strlen(&buffer[(int)pos]);
805         }
806
807         /* Check for message routing */
808         if (msg->cm_fields['D'] != NULL) {
809                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
810
811                         /* route the message */
812                         if (is_valid_node(NULL, NULL,
813                            msg->cm_fields['D']) == 0) {
814
815                                 /* prepend our node to the path */
816                                 if (msg->cm_fields['P'] != NULL) {
817                                         oldpath = msg->cm_fields['P'];
818                                         msg->cm_fields['P'] = NULL;
819                                 }
820                                 else {
821                                         oldpath = strdoop("unknown_user");
822                                 }
823                                 msg->cm_fields['P'] =
824                                         mallok(strlen(oldpath) + SIZ);
825                                 sprintf(msg->cm_fields['P'], "%s!%s",
826                                         config.c_nodename, oldpath);
827                                 phree(oldpath);
828
829                                 /* serialize the message */
830                                 serialize_message(&sermsg, msg);
831
832                                 /* now send it */
833                                 sprintf(filename,
834                                         "./network/spoolout/%s",
835                                         msg->cm_fields['D']);
836                                 fp = fopen(filename, "ab");
837                                 if (fp != NULL) {
838                                         fwrite(sermsg.ser,
839                                                 sermsg.len, 1, fp);
840                                         fclose(fp);
841                                 }
842                                 phree(sermsg.ser);
843                                 CtdlFreeMessage(msg);
844                                 return;
845                         }
846                         
847                         else {  /* invalid destination node name */
848
849                                 network_bounce(msg,
850 "A message you sent could not be delivered due to an invalid destination node"
851 " name.  Please check the address and try sending the message again.\n");
852                                 msg = NULL;
853                                 return;
854
855                         }
856                 }
857         }
858
859         /* FIXME check to see if we already have this message */
860
861         /* Learn network topology from the path */
862         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
863                 network_learn_topology(msg->cm_fields['N'], 
864                                         msg->cm_fields['P']);
865         }
866
867         /* Does it have a recipient?  If so, validate it... */
868         if (msg->cm_fields['R'] != NULL) {
869
870                 safestrncpy(recp, msg->cm_fields['R'], sizeof(recp));
871
872                 e = alias(recp);        /* alias and mail type */
873                 if ((recp[0] == 0) || (e == MES_ERROR)) {
874
875                         network_bounce(msg,
876 "A message you sent could not be delivered due to an invalid address.\n"
877 "Please check the address and try sending the message again.\n");
878                         msg = NULL;
879                         return;
880
881                 }
882                 else if (e == MES_LOCAL) {
883                         a = getuser(&tempUS, recp);
884                         if (a != 0) {
885
886                                 network_bounce(msg,
887 "A message you sent could not be delivered because the user does not exist\n"
888 "on this system.  Please check the address and try again.\n");
889                                 msg = NULL;
890                                 return;
891
892                         }
893                         else {
894                                 MailboxName(target_room, &tempUS, MAILROOM);
895                         }
896                 }
897         }
898
899         else if (msg->cm_fields['C'] != NULL) {
900                 safestrncpy(target_room,
901                         msg->cm_fields['C'],
902                         sizeof target_room);
903         }
904
905         else if (msg->cm_fields['O'] != NULL) {
906                 safestrncpy(target_room,
907                         msg->cm_fields['O'],
908                         sizeof target_room);
909         }
910
911         /* save the message into a room */
912         msg->cm_flags = CM_SKIP_HOOKS;
913         CtdlSaveMsg(msg, "", target_room, 0);
914         CtdlFreeMessage(msg);
915 }
916
917
918 /*
919  * Process a single message from a single file from the inbound queue 
920  */
921 void network_process_message(FILE *fp, long msgstart, long msgend) {
922         long hold_pos;
923         long size;
924         char *buffer;
925
926         hold_pos = ftell(fp);
927         size = msgend - msgstart + 1;
928         buffer = mallok(size);
929         if (buffer != NULL) {
930                 fseek(fp, msgstart, SEEK_SET);
931                 fread(buffer, size, 1, fp);
932                 network_process_buffer(buffer, size);
933                 phree(buffer);
934         }
935
936         fseek(fp, hold_pos, SEEK_SET);
937 }
938
939
940 /*
941  * Process a single file from the inbound queue 
942  */
943 void network_process_file(char *filename) {
944         FILE *fp;
945         long msgstart = (-1L);
946         long msgend = (-1L);
947         long msgcur = 0L;
948         int ch;
949
950         lprintf(7, "network: processing <%s>\n", filename);
951
952         fp = fopen(filename, "rb");
953         if (fp == NULL) {
954                 lprintf(5, "Error opening %s: %s\n",
955                         filename, strerror(errno));
956                 return;
957         }
958
959         /* Look for messages in the data stream and break them out */
960         while (ch = getc(fp), ch >= 0) {
961         
962                 if (ch == 255) {
963                         if (msgstart >= 0L) {
964                                 msgend = msgcur - 1;
965                                 network_process_message(fp, msgstart, msgend);
966                         }
967                         msgstart = msgcur;
968                 }
969
970                 ++msgcur;
971         }
972
973         msgend = msgcur - 1;
974         if (msgstart >= 0L) {
975                 network_process_message(fp, msgstart, msgend);
976         }
977
978         fclose(fp);
979         unlink(filename);
980 }
981
982
983 /*
984  * Process anything in the inbound queue
985  */
986 void network_do_spoolin(void) {
987         DIR *dp;
988         struct dirent *d;
989         char filename[SIZ];
990
991         dp = opendir("./network/spoolin");
992         if (dp == NULL) return;
993
994         while (d = readdir(dp), d != NULL) {
995                 sprintf(filename, "./network/spoolin/%s", d->d_name);
996                 network_process_file(filename);
997         }
998
999
1000         closedir(dp);
1001 }
1002
1003
1004
1005
1006
1007 /*
1008  * receive network spool from the remote system
1009  */
1010 void receive_spool(int sock, char *remote_nodename) {
1011         long download_len;
1012         long bytes_received;
1013         char buf[SIZ];
1014         static char pbuf[IGNET_PACKET_SIZE];
1015         char tempfilename[PATH_MAX];
1016         long plen;
1017         FILE *fp;
1018
1019         strcpy(tempfilename, tmpnam(NULL));
1020         if (sock_puts(sock, "NDOP") < 0) return;
1021         if (sock_gets(sock, buf) < 0) return;
1022         lprintf(9, "<%s\n", buf);
1023         if (buf[0] != '2') {
1024                 return;
1025         }
1026         download_len = extract_long(&buf[4], 0);
1027
1028         bytes_received = 0L;
1029         fp = fopen(tempfilename, "w");
1030         if (fp == NULL) {
1031                 lprintf(9, "cannot open download file locally: %s\n",
1032                         strerror(errno));
1033                 return;
1034         }
1035
1036         while (bytes_received < download_len) {
1037                 sprintf(buf, "READ %ld|%ld",
1038                         bytes_received,
1039                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1040                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1041                 if (sock_puts(sock, buf) < 0) {
1042                         fclose(fp);
1043                         unlink(tempfilename);
1044                         return;
1045                 }
1046                 if (sock_gets(sock, buf) < 0) {
1047                         fclose(fp);
1048                         unlink(tempfilename);
1049                         return;
1050                 }
1051                 if (buf[0] == '6') {
1052                         plen = extract_long(&buf[4], 0);
1053                         if (sock_read(sock, pbuf, plen) < 0) {
1054                                 fclose(fp);
1055                                 unlink(tempfilename);
1056                                 return;
1057                         }
1058                         fwrite((char *) pbuf, plen, 1, fp);
1059                         bytes_received = bytes_received + plen;
1060                 }
1061         }
1062
1063         fclose(fp);
1064         if (sock_puts(sock, "CLOS") < 0) {
1065                 unlink(tempfilename);
1066                 return;
1067         }
1068         if (sock_gets(sock, buf) < 0) {
1069                 unlink(tempfilename);
1070                 return;
1071         }
1072         lprintf(9, "%s\n", buf);
1073         sprintf(buf, "mv %s ./network/spoolin/%s.%ld",
1074                 tempfilename, remote_nodename, (long) getpid());
1075         system(buf);
1076 }
1077
1078
1079
1080 /*
1081  * transmit network spool to the remote system
1082  */
1083 void transmit_spool(int sock, char *remote_nodename)
1084 {
1085         char buf[SIZ];
1086         char pbuf[4096];
1087         long plen;
1088         long bytes_to_write, thisblock;
1089         int fd;
1090         char sfname[128];
1091
1092         if (sock_puts(sock, "NUOP") < 0) return;
1093         if (sock_gets(sock, buf) < 0) return;
1094         lprintf(9, "<%s\n", buf);
1095         if (buf[0] != '2') {
1096                 return;
1097         }
1098
1099         sprintf(sfname, "./network/spoolout/%s", remote_nodename);
1100         fd = open(sfname, O_RDONLY);
1101         if (fd < 0) {
1102                 if (errno == ENOENT) {
1103                         lprintf(9, "Nothing to send.\n");
1104                 } else {
1105                         lprintf(5, "cannot open upload file locally: %s\n",
1106                                 strerror(errno));
1107                 }
1108                 return;
1109         }
1110         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1111                 bytes_to_write = plen;
1112                 while (bytes_to_write > 0L) {
1113                         sprintf(buf, "WRIT %ld", bytes_to_write);
1114                         if (sock_puts(sock, buf) < 0) {
1115                                 close(fd);
1116                                 return;
1117                         }
1118                         if (sock_gets(sock, buf) < 0) {
1119                                 close(fd);
1120                                 return;
1121                         }
1122                         thisblock = atol(&buf[4]);
1123                         if (buf[0] == '7') {
1124                                 if (sock_write(sock, pbuf,
1125                                    (int) thisblock) < 0) {
1126                                         close(fd);
1127                                         return;
1128                                 }
1129                                 bytes_to_write = bytes_to_write - thisblock;
1130                         } else {
1131                                 goto ABORTUPL;
1132                         }
1133                 }
1134         }
1135
1136 ABORTUPL:
1137         close(fd);
1138         if (sock_puts(sock, "UCLS 1") < 0) return;
1139         if (sock_gets(sock, buf) < 0) return;
1140         lprintf(9, "<%s\n", buf);
1141         if (buf[0] == '2') {
1142                 unlink(sfname);
1143         }
1144 }
1145
1146
1147
1148 /*
1149  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1150  */
1151 void network_poll_node(char *node, char *secret, char *host, char *port) {
1152         int sock;
1153         char buf[SIZ];
1154
1155         if (network_talking_to(node, NTT_CHECK)) return;
1156         network_talking_to(node, NTT_ADD);
1157         lprintf(5, "Polling node <%s> at %s:%s\n", node, host, port);
1158
1159         sock = sock_connect(host, port, "tcp");
1160         if (sock < 0) {
1161                 lprintf(7, "Could not connect: %s\n", strerror(errno));
1162                 network_talking_to(node, NTT_REMOVE);
1163                 return;
1164         }
1165         
1166         lprintf(9, "Connected!\n");
1167
1168         /* Read the server greeting */
1169         if (sock_gets(sock, buf) < 0) goto bail;
1170         lprintf(9, ">%s\n", buf);
1171
1172         /* Identify ourselves */
1173         sprintf(buf, "NETP %s|%s", config.c_nodename, secret);
1174         lprintf(9, "<%s\n", buf);
1175         if (sock_puts(sock, buf) <0) goto bail;
1176         if (sock_gets(sock, buf) < 0) goto bail;
1177         lprintf(9, ">%s\n", buf);
1178         if (buf[0] != '2') goto bail;
1179
1180         /* At this point we are authenticated. */
1181         receive_spool(sock, node);
1182         transmit_spool(sock, node);
1183
1184         sock_puts(sock, "QUIT");
1185 bail:   sock_close(sock);
1186         network_talking_to(node, NTT_REMOVE);
1187 }
1188
1189
1190
1191 /*
1192  * Poll other Citadel nodes and transfer inbound/outbound network data.
1193  */
1194 void network_poll_other_citadel_nodes(void) {
1195         char *ignetcfg = NULL;
1196         int i;
1197         char linebuf[SIZ];
1198         char node[SIZ];
1199         char host[SIZ];
1200         char port[SIZ];
1201         char secret[SIZ];
1202
1203         ignetcfg = CtdlGetSysConfig(IGNETCFG);
1204         if (ignetcfg == NULL) return;   /* no nodes defined */
1205
1206         /* Use the string tokenizer to grab one line at a time */
1207         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
1208                 extract_token(linebuf, ignetcfg, i, '\n');
1209                 extract(node, linebuf, 0);
1210                 extract(secret, linebuf, 1);
1211                 extract(host, linebuf, 2);
1212                 extract(port, linebuf, 3);
1213                 if ( (strlen(node) > 0) && (strlen(secret) > 0) 
1214                    && (strlen(host) > 0) && strlen(port) > 0) {
1215                         network_poll_node(node, secret, host, port);
1216                 }
1217         }
1218
1219         phree(ignetcfg);
1220 }
1221
1222
1223
1224
1225
1226
1227
1228 /*
1229  * network_do_queue()
1230  * 
1231  * Run through the rooms doing various types of network stuff.
1232  */
1233 void network_do_queue(void) {
1234         static int doing_queue = 0;
1235         static time_t last_run = 0L;
1236         struct RoomProcList *ptr;
1237
1238         /*
1239          * Run no more frequently than once every n seconds
1240          */
1241         if ( (time(NULL) - last_run) < NETWORK_QUEUE_FREQUENCY ) return;
1242
1243         /*
1244          * This is a simple concurrency check to make sure only one queue run
1245          * is done at a time.  We could do this with a mutex, but since we
1246          * don't really require extremely fine granularity here, we'll do it
1247          * with a static variable instead.
1248          */
1249         if (doing_queue) return;
1250         doing_queue = 1;
1251         last_run = time(NULL);
1252
1253         /*
1254          * Poll other Citadel nodes.
1255          */
1256         network_poll_other_citadel_nodes();
1257
1258         /*
1259          * Load the network map into memory.
1260          */
1261         read_network_map();
1262
1263         /* 
1264          * Go ahead and run the queue
1265          */
1266         lprintf(7, "network: loading outbound queue\n");
1267         ForEachRoom(network_queue_room, NULL);
1268
1269         lprintf(7, "network: running outbound queue\n");
1270         while (rplist != NULL) {
1271                 network_spoolout_room(rplist->name);
1272                 ptr = rplist;
1273                 rplist = rplist->next;
1274                 phree(ptr);
1275         }
1276
1277         lprintf(7, "network: processing inbound queue\n");
1278         network_do_spoolin();
1279
1280         write_network_map();
1281
1282         lprintf(7, "network: queue run completed\n");
1283         doing_queue = 0;
1284 }
1285
1286
1287
1288 /*
1289  * cmd_netp() - authenticate to the server as another Citadel node polling
1290  *              for network traffic
1291  */
1292 void cmd_netp(char *cmdbuf)
1293 {
1294         char node[SIZ];
1295         char pass[SIZ];
1296
1297         char secret[SIZ];
1298         char nexthop[SIZ];
1299
1300         extract(node, cmdbuf, 0);
1301         extract(pass, cmdbuf, 1);
1302
1303         if (is_valid_node(nexthop, secret, node) != 0) {
1304                 cprintf("%d authentication failed\n", ERROR);
1305                 return;
1306         }
1307
1308         if (strcasecmp(pass, secret)) {
1309                 cprintf("%d authentication failed\n", ERROR);
1310                 return;
1311         }
1312
1313         safestrncpy(CC->net_node, node, sizeof CC->net_node);
1314         cprintf("%d authenticated as network node '%s'\n", OK,
1315                 CC->net_node);
1316 }
1317
1318
1319
1320 /*
1321  * Module entry point
1322  */
1323 char *Dynamic_Module_Init(void)
1324 {
1325         CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1326         CtdlRegisterProtoHook(cmd_snet, "SNET", "Get network config");
1327         CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1328         CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1329         return "$Id$";
1330 }