4 * This module handles shared rooms, inter-Citadel mail, and outbound
5 * mailing list processing.
7 * Copyright (C) 2000-2002 by Art Cancro and others.
8 * This code is released under the terms of the GNU General Public License.
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.
20 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
21 * requests that have not been confirmed will be deleted.
23 #define EXP 259200 /* three days */
34 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
52 #include "sysdep_decls.h"
53 #include "citserver.h"
56 #include "serv_extensions.h"
63 #include "internet_addressing.h"
64 #include "serv_network.h"
65 #include "clientsocket.h"
72 /* Nonzero while we are doing outbound network processing */
73 static int doing_queue = 0;
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.
81 struct RoomProcList *rplist = NULL;
84 * We build a map of network nodes during processing.
86 struct NetMap *the_netmap = NULL;
87 char *working_ignetcfg = NULL;
90 * Load or refresh the Citadel network (IGnet) configuration for this node.
92 void load_working_ignetcfg(void) {
95 cfg = CtdlGetSysConfig(IGNETCFG);
100 working_ignetcfg = realloc(working_ignetcfg, strlen(cfg) + 1 );
101 strcpy(working_ignetcfg, cfg);
109 * Keep track of what messages to reject
111 struct FilterList *load_filter_list(void) {
112 char *serialized_list = NULL;
115 struct FilterList *newlist = NULL;
116 struct FilterList *nptr;
118 serialized_list = CtdlGetSysConfig(FILTERLIST);
119 if (serialized_list == NULL) return(NULL); /* if null, no entries */
121 /* Use the string tokenizer to grab one line at a time */
122 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
123 extract_token(buf, serialized_list, i, '\n');
124 nptr = (struct FilterList *) malloc(sizeof(struct FilterList));
125 extract(nptr->fl_user, buf, 0);
126 striplt(nptr->fl_user);
127 extract(nptr->fl_room, buf, 1);
128 striplt(nptr->fl_room);
129 extract(nptr->fl_node, buf, 2);
130 striplt(nptr->fl_node);
132 /* Cowardly refuse to add an any/any/any entry that would
133 * end up filtering every single message.
135 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
136 + strlen(nptr->fl_node) == 0) {
140 nptr->next = newlist;
145 free(serialized_list);
150 void free_filter_list(struct FilterList *fl) {
151 if (fl == NULL) return;
152 free_filter_list(fl->next);
159 * Check the use table. This is a list of messages which have recently
160 * arrived on the system. It is maintained and queried to prevent the same
161 * message from being entered into the database multiple times if it happens
162 * to arrive multiple times by accident.
164 int network_usetable(struct CtdlMessage *msg) {
167 struct cdbdata *cdbut;
170 /* Bail out if we can't generate a message ID */
174 if (msg->cm_fields['I'] == NULL) {
177 if (strlen(msg->cm_fields['I']) == 0) {
181 /* Generate the message ID */
182 strcpy(msgid, msg->cm_fields['I']);
183 if (haschar(msgid, '@') == 0) {
185 if (msg->cm_fields['N'] != NULL) {
186 strcat(msgid, msg->cm_fields['N']);
193 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
199 /* If we got to this point, it's unique: add it. */
200 strcpy(ut.ut_msgid, msgid);
201 ut.ut_timestamp = time(NULL);
202 cdb_store(CDB_USETABLE, msgid, strlen(msgid),
203 &ut, sizeof(struct UseTable) );
209 * Read the network map from its configuration file into memory.
211 void read_network_map(void) {
212 char *serialized_map = NULL;
215 struct NetMap *nmptr;
217 serialized_map = CtdlGetSysConfig(IGNETMAP);
218 if (serialized_map == NULL) return; /* if null, no entries */
220 /* Use the string tokenizer to grab one line at a time */
221 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
222 extract_token(buf, serialized_map, i, '\n');
223 nmptr = (struct NetMap *) malloc(sizeof(struct NetMap));
224 extract(nmptr->nodename, buf, 0);
225 nmptr->lastcontact = extract_long(buf, 1);
226 extract(nmptr->nexthop, buf, 2);
227 nmptr->next = the_netmap;
231 free(serialized_map);
236 * Write the network map from memory back to the configuration file.
238 void write_network_map(void) {
239 char *serialized_map = NULL;
240 struct NetMap *nmptr;
242 serialized_map = strdup("");
244 if (the_netmap != NULL) {
245 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
246 serialized_map = realloc(serialized_map,
247 (strlen(serialized_map)+SIZ) );
248 if (strlen(nmptr->nodename) > 0) {
249 snprintf(&serialized_map[strlen(serialized_map)],
253 (long)nmptr->lastcontact,
259 CtdlPutSysConfig(IGNETMAP, serialized_map);
260 free(serialized_map);
262 /* Now free the list */
263 while (the_netmap != NULL) {
264 nmptr = the_netmap->next;
273 * Check the network map and determine whether the supplied node name is
274 * valid. If it is not a neighbor node, supply the name of a neighbor node
275 * which is the next hop. If it *is* a neighbor node, we also fill in the
278 int is_valid_node(char *nexthop, char *secret, char *node) {
283 struct NetMap *nmptr;
290 * First try the neighbor nodes
292 if (working_ignetcfg == NULL) {
293 lprintf(CTDL_ERR, "working_ignetcfg is NULL!");
294 if (nexthop != NULL) {
301 if (nexthop != NULL) {
305 /* Use the string tokenizer to grab one line at a time */
306 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
307 extract_token(linebuf, working_ignetcfg, i, '\n');
308 extract(buf, linebuf, 0);
309 if (!strcasecmp(buf, node)) {
310 if (nexthop != NULL) {
313 if (secret != NULL) {
314 extract(secret, linebuf, 1);
321 return(retval); /* yup, it's a direct neighbor */
325 * If we get to this point we have to see if we know the next hop
327 if (the_netmap != NULL) {
328 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
329 if (!strcasecmp(nmptr->nodename, node)) {
330 if (nexthop != NULL) {
331 strcpy(nexthop, nmptr->nexthop);
339 * If we get to this point, the supplied node name is bogus.
341 lprintf(CTDL_ERR, "Invalid node name <%s>\n", node);
349 void cmd_gnet(char *argbuf) {
354 if (CtdlAccessCheck(ac_room_aide)) return;
355 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
356 cprintf("%d Network settings for room #%ld <%s>\n",
358 CC->room.QRnumber, CC->room.QRname);
360 fp = fopen(filename, "r");
362 while (fgets(buf, sizeof buf, fp) != NULL) {
363 buf[strlen(buf)-1] = 0;
364 cprintf("%s\n", buf);
373 void cmd_snet(char *argbuf) {
374 char tempfilename[SIZ];
379 if (CtdlAccessCheck(ac_room_aide)) return;
380 safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
381 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
383 fp = fopen(tempfilename, "w");
385 cprintf("%d Cannot open %s: %s\n",
386 ERROR + INTERNAL_ERROR,
391 cprintf("%d %s\n", SEND_LISTING, tempfilename);
393 while (client_gets(buf), strcmp(buf, "000")) {
394 fprintf(fp, "%s\n", buf);
398 /* Now copy the temp file to its permanent location
399 * (We use /bin/mv instead of link() because they may be on
400 * different filesystems)
403 snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
404 begin_critical_section(S_NETCONFIGS);
406 end_critical_section(S_NETCONFIGS);
411 * Spools out one message from the list.
413 void network_spool_msg(long msgnum, void *userdata) {
414 struct SpoolControl *sc;
417 char *newpath = NULL;
419 size_t instr_len = SIZ;
420 struct CtdlMessage *msg = NULL;
421 struct CtdlMessage *imsg;
422 struct namelist *nptr;
423 struct ser_ret sermsg;
429 int delete_after_send = 0; /* Set to 1 to delete after spooling */
431 sc = (struct SpoolControl *)userdata;
434 * Process mailing list recipients
436 if (sc->listrecps != NULL) {
438 /* First, copy it to the spoolout room */
439 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
440 if (err != 0) return;
443 * Figure out how big a buffer we need to allocate
445 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
446 instr_len = instr_len + strlen(nptr->name);
452 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
453 instr = malloc(instr_len);
455 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
459 snprintf(instr, instr_len,
460 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
461 "bounceto|postmaster@%s\n" ,
462 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
464 /* Generate delivery instructions for each recipient */
465 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
466 size_t tmp = strlen(instr);
467 snprintf(&instr[tmp], instr_len - tmp,
468 "remote|%s|0||\n", nptr->name);
472 * Generate a message from the instructions
474 imsg = malloc(sizeof(struct CtdlMessage));
475 memset(imsg, 0, sizeof(struct CtdlMessage));
476 imsg->cm_magic = CTDLMESSAGE_MAGIC;
477 imsg->cm_anon_type = MES_NORMAL;
478 imsg->cm_format_type = FMT_RFC822;
479 imsg->cm_fields['A'] = strdup("Citadel");
480 imsg->cm_fields['M'] = instr;
482 /* Save delivery instructions in spoolout room */
483 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
484 CtdlFreeMessage(imsg);
488 * Process digest recipients
490 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
491 fprintf(sc->digestfp, " -----------------------------------"
492 "------------------------------------"
494 CtdlRedirectOutput(sc->digestfp, -1);
495 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
496 CtdlRedirectOutput(NULL, -1);
497 sc->num_msgs_spooled += 1;
501 * Process IGnet push shares
503 if (sc->ignet_push_shares != NULL) {
505 msg = CtdlFetchMessage(msgnum, 1);
509 /* Prepend our node name to the Path field whenever
510 * sending a message to another IGnet node
512 if (msg->cm_fields['P'] == NULL) {
513 msg->cm_fields['P'] = strdup("username");
515 newpath_len = strlen(msg->cm_fields['P']) +
516 strlen(config.c_nodename) + 2;
517 newpath = malloc(newpath_len);
518 snprintf(newpath, newpath_len, "%s!%s",
519 config.c_nodename, msg->cm_fields['P']);
520 free(msg->cm_fields['P']);
521 msg->cm_fields['P'] = newpath;
524 * Force the message to appear in the correct room
525 * on the far end by setting the C field correctly
527 if (msg->cm_fields['C'] != NULL) {
528 free(msg->cm_fields['C']);
530 msg->cm_fields['C'] = strdup(CC->room.QRname);
533 * Determine if this message is set to be deleted
534 * after sending out on the network
536 if (msg->cm_fields['S'] != NULL) {
537 if (!strcasecmp(msg->cm_fields['S'],
539 delete_after_send = 1;
544 * Now serialize it for transmission
546 serialize_message(&sermsg, msg);
548 /* Now send it to every node */
549 for (nptr = sc->ignet_push_shares; nptr != NULL;
554 /* Check for valid node name */
555 if (is_valid_node(NULL, NULL, nptr->name) != 0) {
556 lprintf(CTDL_ERR, "Invalid node <%s>\n",
561 /* Check for split horizon */
562 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
563 bang = num_tokens(msg->cm_fields['P'], '!');
564 if (bang > 1) for (i=0; i<(bang-1); ++i) {
565 extract_token(buf, msg->cm_fields['P'],
567 if (!strcasecmp(buf, nptr->name)) {
572 /* Send the message */
574 snprintf(filename, sizeof filename,
575 "./network/spoolout/%s",
577 fp = fopen(filename, "ab");
586 CtdlFreeMessage(msg);
590 /* update lastsent */
591 sc->lastsent = msgnum;
593 /* Delete this message if delete-after-send is set */
594 if (delete_after_send) {
595 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
602 * Deliver digest messages
604 void network_deliver_digest(struct SpoolControl *sc) {
607 struct CtdlMessage *msg;
611 size_t instr_len = SIZ;
612 struct CtdlMessage *imsg;
613 struct namelist *nptr;
615 if (sc->num_msgs_spooled < 1) {
616 fclose(sc->digestfp);
621 msg = malloc(sizeof(struct CtdlMessage));
622 memset(msg, 0, sizeof(struct CtdlMessage));
623 msg->cm_magic = CTDLMESSAGE_MAGIC;
624 msg->cm_format_type = FMT_RFC822;
625 msg->cm_anon_type = MES_NORMAL;
627 sprintf(buf, "%ld", time(NULL));
628 msg->cm_fields['T'] = strdup(buf);
629 msg->cm_fields['A'] = strdup(CC->room.QRname);
630 msg->cm_fields['U'] = strdup(CC->room.QRname);
631 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
632 for (i=0; i<strlen(buf); ++i) {
633 if (isspace(buf[i])) buf[i]='_';
634 buf[i] = tolower(buf[i]);
636 msg->cm_fields['F'] = strdup(buf);
638 fseek(sc->digestfp, 0L, SEEK_END);
639 msglen = ftell(sc->digestfp);
641 msg->cm_fields['M'] = malloc(msglen + 1);
642 fseek(sc->digestfp, 0L, SEEK_SET);
643 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
644 msg->cm_fields['M'][msglen] = 0;
646 fclose(sc->digestfp);
649 msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
650 CtdlFreeMessage(msg);
652 /* Now generate the delivery instructions */
655 * Figure out how big a buffer we need to allocate
657 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
658 instr_len = instr_len + strlen(nptr->name);
664 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
665 instr = malloc(instr_len);
667 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
671 snprintf(instr, instr_len,
672 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
673 "bounceto|postmaster@%s\n" ,
674 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
676 /* Generate delivery instructions for each recipient */
677 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
678 size_t tmp = strlen(instr);
679 snprintf(&instr[tmp], instr_len - tmp,
680 "remote|%s|0||\n", nptr->name);
684 * Generate a message from the instructions
686 imsg = malloc(sizeof(struct CtdlMessage));
687 memset(imsg, 0, sizeof(struct CtdlMessage));
688 imsg->cm_magic = CTDLMESSAGE_MAGIC;
689 imsg->cm_anon_type = MES_NORMAL;
690 imsg->cm_format_type = FMT_RFC822;
691 imsg->cm_fields['A'] = strdup("Citadel");
692 imsg->cm_fields['M'] = instr;
694 /* Save delivery instructions in spoolout room */
695 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
696 CtdlFreeMessage(imsg);
701 * Batch up and send all outbound traffic from the current room
703 void network_spoolout_room(char *room_to_spool) {
710 struct SpoolControl sc;
711 struct namelist *nptr = NULL;
714 int skipthisline = 0;
717 if (getroom(&CC->room, room_to_spool) != 0) {
718 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
722 memset(&sc, 0, sizeof(struct SpoolControl));
723 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
725 begin_critical_section(S_NETCONFIGS);
727 fp = fopen(filename, "r");
729 end_critical_section(S_NETCONFIGS);
733 lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
735 while (fgets(buf, sizeof buf, fp) != NULL) {
736 buf[strlen(buf)-1] = 0;
738 extract(instr, buf, 0);
739 if (!strcasecmp(instr, "lastsent")) {
740 sc.lastsent = extract_long(buf, 1);
742 else if (!strcasecmp(instr, "listrecp")) {
743 nptr = (struct namelist *)
744 malloc(sizeof(struct namelist));
745 nptr->next = sc.listrecps;
746 extract(nptr->name, buf, 1);
749 else if (!strcasecmp(instr, "digestrecp")) {
750 nptr = (struct namelist *)
751 malloc(sizeof(struct namelist));
752 nptr->next = sc.digestrecps;
753 extract(nptr->name, buf, 1);
754 sc.digestrecps = nptr;
756 else if (!strcasecmp(instr, "ignet_push_share")) {
757 /* by checking each node's validity, we automatically
758 * purge nodes which do not exist from room network
759 * configurations at this time.
761 extract(nodename, buf, 1);
762 strcpy(nexthop, "xxx");
763 if (is_valid_node(nexthop, NULL, nodename) == 0) {
764 if (strlen(nexthop) == 0) {
765 nptr = (struct namelist *)
766 malloc(sizeof(struct namelist));
767 nptr->next = sc.ignet_push_shares;
768 strcpy(nptr->name, nodename);
769 sc.ignet_push_shares = nptr;
774 /* Preserve 'other' lines ... *unless* they happen to
775 * be subscribe/unsubscribe pendings with expired
779 if (!strncasecmp(buf, "subpending|", 11)) {
780 if (time(NULL) - extract_long(buf, 4) > EXP) {
784 if (!strncasecmp(buf, "unsubpending|", 13)) {
785 if (time(NULL) - extract_long(buf, 3) > EXP) {
790 if (skipthisline == 0) {
791 linesize = strlen(buf);
792 sc.misc = realloc(sc.misc,
793 (miscsize + linesize + 2) );
794 sprintf(&sc.misc[miscsize], "%s\n", buf);
795 miscsize = miscsize + linesize + 1;
803 /* If there are digest recipients, we have to build a digest */
804 if (sc.digestrecps != NULL) {
805 sc.digestfp = tmpfile();
806 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
809 /* Do something useful */
810 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
811 network_spool_msg, &sc);
813 /* If we wrote a digest, deliver it and then close it */
814 snprintf(buf, sizeof buf, "room_%s@%s",
815 CC->room.QRname, config.c_fqdn);
816 for (i=0; i<strlen(buf); ++i) {
817 buf[i] = tolower(buf[i]);
818 if (isspace(buf[i])) buf[i] = '_';
820 if (sc.digestfp != NULL) {
821 fprintf(sc.digestfp, " -----------------------------------"
822 "------------------------------------"
824 "You are subscribed to the '%s' "
826 "To post to the list: %s\n",
829 network_deliver_digest(&sc); /* deliver and close */
832 /* Now rewrite the config file */
833 fp = fopen(filename, "w");
835 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
836 filename, strerror(errno));
839 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
841 /* Write out the listrecps while freeing from memory at the
842 * same time. Am I clever or what? :)
844 while (sc.listrecps != NULL) {
845 fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
846 nptr = sc.listrecps->next;
850 /* Do the same for digestrecps */
851 while (sc.digestrecps != NULL) {
852 fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
853 nptr = sc.digestrecps->next;
854 free(sc.digestrecps);
855 sc.digestrecps = nptr;
857 while (sc.ignet_push_shares != NULL) {
858 /* by checking each node's validity, we automatically
859 * purge nodes which do not exist from room network
860 * configurations at this time.
862 if (is_valid_node(NULL, NULL, sc.ignet_push_shares->name) == 0) {
864 fprintf(fp, "ignet_push_share|%s\n",
865 sc.ignet_push_shares->name);
866 nptr = sc.ignet_push_shares->next;
867 free(sc.ignet_push_shares);
868 sc.ignet_push_shares = nptr;
870 if (sc.misc != NULL) {
871 fwrite(sc.misc, strlen(sc.misc), 1, fp);
877 end_critical_section(S_NETCONFIGS);
883 * Send the *entire* contents of the current room to one specific network node,
884 * ignoring anything we know about which messages have already undergone
885 * network processing. This can be used to bring a new node into sync.
887 int network_sync_to(char *target_node) {
888 struct SpoolControl sc;
891 /* Concise syntax because we don't need a full linked-list */
892 memset(&sc, 0, sizeof(struct SpoolControl));
893 sc.ignet_push_shares = (struct namelist *)
894 malloc(sizeof(struct namelist));
895 sc.ignet_push_shares->next = NULL;
896 safestrncpy(sc.ignet_push_shares->name,
898 sizeof sc.ignet_push_shares->name);
900 /* Send ALL messages */
901 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
902 network_spool_msg, &sc);
904 /* Concise cleanup because we know there's only one node in the sc */
905 free(sc.ignet_push_shares);
907 lprintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
908 num_spooled, target_node);
914 * Implements the NSYN command
916 void cmd_nsyn(char *argbuf) {
918 char target_node[SIZ];
920 if (CtdlAccessCheck(ac_aide)) return;
922 extract(target_node, argbuf, 0);
923 num_spooled = network_sync_to(target_node);
924 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
930 * Batch up and send all outbound traffic from the current room
932 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
933 struct RoomProcList *ptr;
935 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
936 if (ptr == NULL) return;
938 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
945 * Learn topology from path fields
947 void network_learn_topology(char *node, char *path) {
949 struct NetMap *nmptr;
953 if (num_tokens(path, '!') < 3) return;
954 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
955 if (!strcasecmp(nmptr->nodename, node)) {
956 extract_token(nmptr->nexthop, path, 0, '!');
957 nmptr->lastcontact = time(NULL);
962 /* If we got here then it's not in the map, so add it. */
963 nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
964 strcpy(nmptr->nodename, node);
965 nmptr->lastcontact = time(NULL);
966 extract_token(nmptr->nexthop, path, 0, '!');
967 nmptr->next = the_netmap;
975 * Bounce a message back to the sender
977 void network_bounce(struct CtdlMessage *msg, char *reason) {
978 char *oldpath = NULL;
980 char bouncesource[SIZ];
982 struct recptypes *valid = NULL;
983 char force_room[ROOMNAMELEN];
984 static int serialnum = 0;
987 lprintf(CTDL_DEBUG, "entering network_bounce()\n");
989 if (msg == NULL) return;
991 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
994 * Give it a fresh message ID
996 if (msg->cm_fields['I'] != NULL) {
997 free(msg->cm_fields['I']);
999 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1000 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1001 msg->cm_fields['I'] = strdup(buf);
1004 * FIXME ... right now we're just sending a bounce; we really want to
1005 * include the text of the bounced message.
1007 if (msg->cm_fields['M'] != NULL) {
1008 free(msg->cm_fields['M']);
1010 msg->cm_fields['M'] = strdup(reason);
1011 msg->cm_format_type = 0;
1014 * Turn the message around
1016 if (msg->cm_fields['R'] == NULL) {
1017 free(msg->cm_fields['R']);
1020 if (msg->cm_fields['D'] == NULL) {
1021 free(msg->cm_fields['D']);
1024 snprintf(recipient, sizeof recipient, "%s@%s",
1025 msg->cm_fields['A'], msg->cm_fields['N']);
1027 if (msg->cm_fields['A'] == NULL) {
1028 free(msg->cm_fields['A']);
1031 if (msg->cm_fields['N'] == NULL) {
1032 free(msg->cm_fields['N']);
1035 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1036 msg->cm_fields['N'] = strdup(config.c_nodename);
1039 /* prepend our node to the path */
1040 if (msg->cm_fields['P'] != NULL) {
1041 oldpath = msg->cm_fields['P'];
1042 msg->cm_fields['P'] = NULL;
1045 oldpath = strdup("unknown_user");
1047 size = strlen(oldpath) + SIZ;
1048 msg->cm_fields['P'] = malloc(size);
1049 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1052 /* Now submit the message */
1053 valid = validate_recipients(recipient);
1054 if (valid != NULL) if (valid->num_error > 0) {
1058 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1059 strcpy(force_room, config.c_aideroom);
1062 strcpy(force_room, "");
1064 if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1065 strcpy(force_room, config.c_aideroom);
1067 CtdlSubmitMsg(msg, valid, force_room);
1070 if (valid != NULL) free(valid);
1071 CtdlFreeMessage(msg);
1072 lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1079 * Process a buffer containing a single message from a single file
1080 * from the inbound queue
1082 void network_process_buffer(char *buffer, long size) {
1083 struct CtdlMessage *msg;
1086 struct recptypes *recp = NULL;
1087 char target_room[ROOMNAMELEN];
1088 struct ser_ret sermsg;
1089 char *oldpath = NULL;
1093 unsigned char firstbyte;
1094 unsigned char lastbyte;
1096 /* Validate just a little bit. First byte should be FF and
1097 * last byte should be 00.
1099 memcpy(&firstbyte, &buffer[0], 1);
1100 memcpy(&lastbyte, &buffer[size-1], 1);
1101 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1102 lprintf(CTDL_ERR, "Corrupt message! Ignoring.\n");
1106 /* Set default target room to trash */
1107 strcpy(target_room, TWITROOM);
1109 /* Load the message into memory */
1110 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1111 memset(msg, 0, sizeof(struct CtdlMessage));
1112 msg->cm_magic = CTDLMESSAGE_MAGIC;
1113 msg->cm_anon_type = buffer[1];
1114 msg->cm_format_type = buffer[2];
1116 for (pos = 3; pos < size; ++pos) {
1117 field = buffer[pos];
1118 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1119 pos = pos + strlen(&buffer[(int)pos]);
1122 /* Check for message routing */
1123 if (msg->cm_fields['D'] != NULL) {
1124 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1126 /* route the message */
1127 strcpy(nexthop, "");
1128 if (is_valid_node(nexthop, NULL,
1129 msg->cm_fields['D']) == 0) {
1131 /* prepend our node to the path */
1132 if (msg->cm_fields['P'] != NULL) {
1133 oldpath = msg->cm_fields['P'];
1134 msg->cm_fields['P'] = NULL;
1137 oldpath = strdup("unknown_user");
1139 size = strlen(oldpath) + SIZ;
1140 msg->cm_fields['P'] = malloc(size);
1141 snprintf(msg->cm_fields['P'], size, "%s!%s",
1142 config.c_nodename, oldpath);
1145 /* serialize the message */
1146 serialize_message(&sermsg, msg);
1149 if (strlen(nexthop) == 0) {
1150 strcpy(nexthop, msg->cm_fields['D']);
1152 snprintf(filename, sizeof filename,
1153 "./network/spoolout/%s", nexthop);
1154 fp = fopen(filename, "ab");
1161 CtdlFreeMessage(msg);
1165 else { /* invalid destination node name */
1168 "A message you sent could not be delivered due to an invalid destination node"
1169 " name. Please check the address and try sending the message again.\n");
1178 * Check to see if we already have a copy of this message, and
1179 * abort its processing if so. (We used to post a warning to Aide>
1180 * every time this happened, but the network is now so densely
1181 * connected that it's inevitable.)
1183 if (network_usetable(msg) != 0) {
1187 /* Learn network topology from the path */
1188 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1189 network_learn_topology(msg->cm_fields['N'],
1190 msg->cm_fields['P']);
1193 /* Is the sending node giving us a very persuasive suggestion about
1194 * which room this message should be saved in? If so, go with that.
1196 if (msg->cm_fields['C'] != NULL) {
1197 safestrncpy(target_room,
1198 msg->cm_fields['C'],
1199 sizeof target_room);
1202 /* Otherwise, does it have a recipient? If so, validate it... */
1203 else if (msg->cm_fields['R'] != NULL) {
1204 recp = validate_recipients(msg->cm_fields['R']);
1205 if (recp != NULL) if (recp->num_error > 0) {
1207 "A message you sent could not be delivered due to an invalid address.\n"
1208 "Please check the address and try sending the message again.\n");
1213 strcpy(target_room, ""); /* no target room if mail */
1216 /* Our last shot at finding a home for this message is to see if
1217 * it has the O field (Originating room) set.
1219 else if (msg->cm_fields['O'] != NULL) {
1220 safestrncpy(target_room,
1221 msg->cm_fields['O'],
1222 sizeof target_room);
1225 /* Strip out fields that are only relevant during transit */
1226 if (msg->cm_fields['D'] != NULL) {
1227 free(msg->cm_fields['D']);
1228 msg->cm_fields['D'] = NULL;
1230 if (msg->cm_fields['C'] != NULL) {
1231 free(msg->cm_fields['C']);
1232 msg->cm_fields['C'] = NULL;
1235 /* save the message into a room */
1236 if (PerformNetprocHooks(msg, target_room) == 0) {
1237 msg->cm_flags = CM_SKIP_HOOKS;
1238 CtdlSubmitMsg(msg, recp, target_room);
1240 CtdlFreeMessage(msg);
1246 * Process a single message from a single file from the inbound queue
1248 void network_process_message(FILE *fp, long msgstart, long msgend) {
1253 hold_pos = ftell(fp);
1254 size = msgend - msgstart + 1;
1255 buffer = malloc(size);
1256 if (buffer != NULL) {
1257 fseek(fp, msgstart, SEEK_SET);
1258 fread(buffer, size, 1, fp);
1259 network_process_buffer(buffer, size);
1263 fseek(fp, hold_pos, SEEK_SET);
1268 * Process a single file from the inbound queue
1270 void network_process_file(char *filename) {
1272 long msgstart = (-1L);
1273 long msgend = (-1L);
1278 fp = fopen(filename, "rb");
1280 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1281 filename, strerror(errno));
1285 lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1287 /* Look for messages in the data stream and break them out */
1288 while (ch = getc(fp), ch >= 0) {
1291 if (msgstart >= 0L) {
1292 msgend = msgcur - 1;
1293 network_process_message(fp, msgstart, msgend);
1301 msgend = msgcur - 1;
1302 if (msgstart >= 0L) {
1303 network_process_message(fp, msgstart, msgend);
1312 * Process anything in the inbound queue
1314 void network_do_spoolin(void) {
1319 dp = opendir("./network/spoolin");
1320 if (dp == NULL) return;
1322 while (d = readdir(dp), d != NULL) {
1323 snprintf(filename, sizeof filename,
1324 "./network/spoolin/%s", d->d_name);
1325 network_process_file(filename);
1334 * Delete any files in the outbound queue that were intended
1335 * to be sent to nodes which no longer exist.
1337 void network_purge_spoolout(void) {
1344 dp = opendir("./network/spoolout");
1345 if (dp == NULL) return;
1347 while (d = readdir(dp), d != NULL) {
1348 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1350 snprintf(filename, sizeof filename,
1351 "./network/spoolout/%s", d->d_name);
1353 strcpy(nexthop, "");
1354 i = is_valid_node(nexthop, NULL, d->d_name);
1356 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1368 * receive network spool from the remote system
1370 void receive_spool(int sock, char *remote_nodename) {
1372 long bytes_received;
1374 static char pbuf[IGNET_PACKET_SIZE];
1375 char tempfilename[PATH_MAX];
1379 strcpy(tempfilename, tmpnam(NULL));
1380 if (sock_puts(sock, "NDOP") < 0) return;
1381 if (sock_gets(sock, buf) < 0) return;
1382 lprintf(CTDL_DEBUG, "<%s\n", buf);
1383 if (buf[0] != '2') {
1386 download_len = extract_long(&buf[4], 0);
1388 bytes_received = 0L;
1389 fp = fopen(tempfilename, "w");
1391 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1396 while (bytes_received < download_len) {
1397 snprintf(buf, sizeof buf, "READ %ld|%ld",
1399 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1400 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1401 if (sock_puts(sock, buf) < 0) {
1403 unlink(tempfilename);
1406 if (sock_gets(sock, buf) < 0) {
1408 unlink(tempfilename);
1411 if (buf[0] == '6') {
1412 plen = extract_long(&buf[4], 0);
1413 if (sock_read(sock, pbuf, plen) < 0) {
1415 unlink(tempfilename);
1418 fwrite((char *) pbuf, plen, 1, fp);
1419 bytes_received = bytes_received + plen;
1424 if (sock_puts(sock, "CLOS") < 0) {
1425 unlink(tempfilename);
1428 if (sock_gets(sock, buf) < 0) {
1429 unlink(tempfilename);
1432 if (download_len > 0)
1433 lprintf(CTDL_NOTICE, "Received %ld octets from <%s>",
1434 download_len, remote_nodename);
1435 lprintf(CTDL_DEBUG, "%s", buf);
1436 snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1437 tempfilename, remote_nodename, (long) getpid());
1444 * transmit network spool to the remote system
1446 void transmit_spool(int sock, char *remote_nodename)
1451 long bytes_to_write, thisblock, bytes_written;
1455 if (sock_puts(sock, "NUOP") < 0) return;
1456 if (sock_gets(sock, buf) < 0) return;
1457 lprintf(CTDL_DEBUG, "<%s\n", buf);
1458 if (buf[0] != '2') {
1462 snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1463 fd = open(sfname, O_RDONLY);
1465 if (errno != ENOENT) {
1466 lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1472 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1473 bytes_to_write = plen;
1474 while (bytes_to_write > 0L) {
1475 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1476 if (sock_puts(sock, buf) < 0) {
1480 if (sock_gets(sock, buf) < 0) {
1484 thisblock = atol(&buf[4]);
1485 if (buf[0] == '7') {
1486 if (sock_write(sock, pbuf,
1487 (int) thisblock) < 0) {
1491 bytes_to_write -= thisblock;
1492 bytes_written += thisblock;
1501 if (sock_puts(sock, "UCLS 1") < 0) return;
1502 if (sock_gets(sock, buf) < 0) return;
1503 lprintf(CTDL_NOTICE, "Sent %ld octets to <%s>",
1504 bytes_written, remote_nodename);
1505 lprintf(CTDL_DEBUG, "<%s\n", buf);
1506 if (buf[0] == '2') {
1514 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1516 void network_poll_node(char *node, char *secret, char *host, char *port) {
1520 if (network_talking_to(node, NTT_CHECK)) return;
1521 network_talking_to(node, NTT_ADD);
1522 lprintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
1524 sock = sock_connect(host, port, "tcp");
1526 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1527 network_talking_to(node, NTT_REMOVE);
1531 lprintf(CTDL_DEBUG, "Connected!\n");
1533 /* Read the server greeting */
1534 if (sock_gets(sock, buf) < 0) goto bail;
1535 lprintf(CTDL_DEBUG, ">%s\n", buf);
1537 /* Identify ourselves */
1538 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1539 lprintf(CTDL_DEBUG, "<%s\n", buf);
1540 if (sock_puts(sock, buf) <0) goto bail;
1541 if (sock_gets(sock, buf) < 0) goto bail;
1542 lprintf(CTDL_DEBUG, ">%s\n", buf);
1543 if (buf[0] != '2') goto bail;
1545 /* At this point we are authenticated. */
1546 receive_spool(sock, node);
1547 transmit_spool(sock, node);
1549 sock_puts(sock, "QUIT");
1550 bail: sock_close(sock);
1551 network_talking_to(node, NTT_REMOVE);
1557 * Poll other Citadel nodes and transfer inbound/outbound network data.
1558 * Set "full" to nonzero to force a poll of every node, or to zero to poll
1559 * only nodes to which we have data to send.
1561 void network_poll_other_citadel_nodes(int full_poll) {
1569 char spoolfile[SIZ];
1571 if (working_ignetcfg == NULL) {
1572 lprintf(CTDL_DEBUG, "No nodes defined - not polling\n");
1576 /* Use the string tokenizer to grab one line at a time */
1577 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1578 extract_token(linebuf, working_ignetcfg, i, '\n');
1579 extract(node, linebuf, 0);
1580 extract(secret, linebuf, 1);
1581 extract(host, linebuf, 2);
1582 extract(port, linebuf, 3);
1583 if ( (strlen(node) > 0) && (strlen(secret) > 0)
1584 && (strlen(host) > 0) && strlen(port) > 0) {
1587 sprintf(spoolfile, "./network/spoolout/%s",
1589 if (access(spoolfile, R_OK) == 0) {
1594 network_poll_node(node, secret, host, port);
1608 * network_do_queue()
1610 * Run through the rooms doing various types of network stuff.
1612 void network_do_queue(void) {
1613 static time_t last_run = 0L;
1614 struct RoomProcList *ptr;
1615 int full_processing = 1;
1618 * Run the full set of processing tasks no more frequently
1619 * than once every n seconds
1621 if ( (time(NULL) - last_run) < config.c_net_freq ) {
1622 full_processing = 0;
1626 * This is a simple concurrency check to make sure only one queue run
1627 * is done at a time. We could do this with a mutex, but since we
1628 * don't really require extremely fine granularity here, we'll do it
1629 * with a static variable instead.
1631 if (doing_queue) return;
1634 /* Load the IGnet Configuration into memory */
1635 load_working_ignetcfg();
1638 * Poll other Citadel nodes. Maybe. If "full_processing" is set
1639 * then we poll everyone. Otherwise we only poll nodes we have stuff
1642 network_poll_other_citadel_nodes(full_processing);
1645 * Load the network map and filter list into memory.
1648 filterlist = load_filter_list();
1651 * Go ahead and run the queue
1653 if (full_processing) {
1654 lprintf(CTDL_DEBUG, "network: loading outbound queue\n");
1655 ForEachRoom(network_queue_room, NULL);
1657 lprintf(CTDL_DEBUG, "network: running outbound queue\n");
1658 while (rplist != NULL) {
1659 network_spoolout_room(rplist->name);
1661 rplist = rplist->next;
1666 lprintf(CTDL_DEBUG, "network: processing inbound queue\n");
1667 network_do_spoolin();
1669 /* Save the network map back to disk */
1670 write_network_map();
1672 /* Free the filter list in memory */
1673 free_filter_list(filterlist);
1676 network_purge_spoolout();
1678 lprintf(CTDL_DEBUG, "network: queue run completed\n");
1680 if (full_processing) {
1681 last_run = time(NULL);
1689 * cmd_netp() - authenticate to the server as another Citadel node polling
1690 * for network traffic
1692 void cmd_netp(char *cmdbuf)
1702 extract(node, cmdbuf, 0);
1703 extract(pass, cmdbuf, 1);
1706 lprintf(CTDL_WARNING, "Network node <%s> refused - spooling", node);
1707 cprintf("%d spooling - try again in a few minutes\n",
1708 ERROR + RESOURCE_BUSY);
1712 /* load the IGnet Configuration to check node validity */
1713 load_working_ignetcfg();
1714 v = is_valid_node(nexthop, secret, node);
1717 lprintf(CTDL_WARNING, "Unknown node <%s>", node);
1718 cprintf("%d authentication failed\n",
1719 ERROR + PASSWORD_REQUIRED);
1723 if (strcasecmp(pass, secret)) {
1724 lprintf(CTDL_WARNING, "Bad password for network node <%s>", node);
1725 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1729 if (network_talking_to(node, NTT_CHECK)) {
1730 lprintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
1731 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1735 safestrncpy(CC->net_node, node, sizeof CC->net_node);
1736 network_talking_to(node, NTT_ADD);
1737 lprintf(CTDL_NOTICE, "Network node <%s> logged in", CC->net_node);
1738 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1745 * Module entry point
1747 char *serv_network_init(void)
1749 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1750 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1751 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1752 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1753 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);