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);
392 while (client_gets(buf), strcmp(buf, "000")) {
393 fprintf(fp, "%s\n", buf);
397 /* Now copy the temp file to its permanent location
398 * (We use /bin/mv instead of link() because they may be on
399 * different filesystems)
402 snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
403 begin_critical_section(S_NETCONFIGS);
405 end_critical_section(S_NETCONFIGS);
410 * Spools out one message from the list.
412 void network_spool_msg(long msgnum, void *userdata) {
413 struct SpoolControl *sc;
416 char *newpath = NULL;
418 size_t instr_len = SIZ;
419 struct CtdlMessage *msg = NULL;
420 struct CtdlMessage *imsg;
421 struct namelist *nptr;
422 struct ser_ret sermsg;
428 int delete_after_send = 0; /* Set to 1 to delete after spooling */
430 sc = (struct SpoolControl *)userdata;
433 * Process mailing list recipients
435 if (sc->listrecps != NULL) {
437 /* First, copy it to the spoolout room */
438 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
439 if (err != 0) return;
442 * Figure out how big a buffer we need to allocate
444 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
445 instr_len = instr_len + strlen(nptr->name);
451 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
452 instr = malloc(instr_len);
454 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
458 snprintf(instr, instr_len,
459 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
460 "bounceto|postmaster@%s\n" ,
461 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
463 /* Generate delivery instructions for each recipient */
464 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
465 size_t tmp = strlen(instr);
466 snprintf(&instr[tmp], instr_len - tmp,
467 "remote|%s|0||\n", nptr->name);
471 * Generate a message from the instructions
473 imsg = malloc(sizeof(struct CtdlMessage));
474 memset(imsg, 0, sizeof(struct CtdlMessage));
475 imsg->cm_magic = CTDLMESSAGE_MAGIC;
476 imsg->cm_anon_type = MES_NORMAL;
477 imsg->cm_format_type = FMT_RFC822;
478 imsg->cm_fields['A'] = strdup("Citadel");
479 imsg->cm_fields['M'] = instr;
481 /* Save delivery instructions in spoolout room */
482 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
483 CtdlFreeMessage(imsg);
487 * Process digest recipients
489 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
490 fprintf(sc->digestfp, " -----------------------------------"
491 "------------------------------------"
493 CtdlRedirectOutput(sc->digestfp, -1);
494 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
495 CtdlRedirectOutput(NULL, -1);
496 sc->num_msgs_spooled += 1;
500 * Process IGnet push shares
502 if (sc->ignet_push_shares != NULL) {
504 msg = CtdlFetchMessage(msgnum, 1);
508 /* Prepend our node name to the Path field whenever
509 * sending a message to another IGnet node
511 if (msg->cm_fields['P'] == NULL) {
512 msg->cm_fields['P'] = strdup("username");
514 newpath_len = strlen(msg->cm_fields['P']) +
515 strlen(config.c_nodename) + 2;
516 newpath = malloc(newpath_len);
517 snprintf(newpath, newpath_len, "%s!%s",
518 config.c_nodename, msg->cm_fields['P']);
519 free(msg->cm_fields['P']);
520 msg->cm_fields['P'] = newpath;
523 * Force the message to appear in the correct room
524 * on the far end by setting the C field correctly
526 if (msg->cm_fields['C'] != NULL) {
527 free(msg->cm_fields['C']);
529 msg->cm_fields['C'] = strdup(CC->room.QRname);
532 * Determine if this message is set to be deleted
533 * after sending out on the network
535 if (msg->cm_fields['S'] != NULL) {
536 if (!strcasecmp(msg->cm_fields['S'],
538 delete_after_send = 1;
543 * Now serialize it for transmission
545 serialize_message(&sermsg, msg);
547 /* Now send it to every node */
548 for (nptr = sc->ignet_push_shares; nptr != NULL;
553 /* Check for valid node name */
554 if (is_valid_node(NULL, NULL, nptr->name) != 0) {
555 lprintf(CTDL_ERR, "Invalid node <%s>\n",
560 /* Check for split horizon */
561 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
562 bang = num_tokens(msg->cm_fields['P'], '!');
563 if (bang > 1) for (i=0; i<(bang-1); ++i) {
564 extract_token(buf, msg->cm_fields['P'],
566 if (!strcasecmp(buf, nptr->name)) {
571 /* Send the message */
573 snprintf(filename, sizeof filename,
574 "./network/spoolout/%s",
576 fp = fopen(filename, "ab");
585 CtdlFreeMessage(msg);
589 /* update lastsent */
590 sc->lastsent = msgnum;
592 /* Delete this message if delete-after-send is set */
593 if (delete_after_send) {
594 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
601 * Deliver digest messages
603 void network_deliver_digest(struct SpoolControl *sc) {
606 struct CtdlMessage *msg;
610 size_t instr_len = SIZ;
611 struct CtdlMessage *imsg;
612 struct namelist *nptr;
614 if (sc->num_msgs_spooled < 1) {
615 fclose(sc->digestfp);
620 msg = malloc(sizeof(struct CtdlMessage));
621 memset(msg, 0, sizeof(struct CtdlMessage));
622 msg->cm_magic = CTDLMESSAGE_MAGIC;
623 msg->cm_format_type = FMT_RFC822;
624 msg->cm_anon_type = MES_NORMAL;
626 sprintf(buf, "%ld", time(NULL));
627 msg->cm_fields['T'] = strdup(buf);
628 msg->cm_fields['A'] = strdup(CC->room.QRname);
629 msg->cm_fields['U'] = strdup(CC->room.QRname);
630 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
631 for (i=0; i<strlen(buf); ++i) {
632 if (isspace(buf[i])) buf[i]='_';
633 buf[i] = tolower(buf[i]);
635 msg->cm_fields['F'] = strdup(buf);
637 fseek(sc->digestfp, 0L, SEEK_END);
638 msglen = ftell(sc->digestfp);
640 msg->cm_fields['M'] = malloc(msglen + 1);
641 fseek(sc->digestfp, 0L, SEEK_SET);
642 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
643 msg->cm_fields['M'][msglen] = 0;
645 fclose(sc->digestfp);
648 msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
649 CtdlFreeMessage(msg);
651 /* Now generate the delivery instructions */
654 * Figure out how big a buffer we need to allocate
656 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
657 instr_len = instr_len + strlen(nptr->name);
663 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
664 instr = malloc(instr_len);
666 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
670 snprintf(instr, instr_len,
671 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
672 "bounceto|postmaster@%s\n" ,
673 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
675 /* Generate delivery instructions for each recipient */
676 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
677 size_t tmp = strlen(instr);
678 snprintf(&instr[tmp], instr_len - tmp,
679 "remote|%s|0||\n", nptr->name);
683 * Generate a message from the instructions
685 imsg = malloc(sizeof(struct CtdlMessage));
686 memset(imsg, 0, sizeof(struct CtdlMessage));
687 imsg->cm_magic = CTDLMESSAGE_MAGIC;
688 imsg->cm_anon_type = MES_NORMAL;
689 imsg->cm_format_type = FMT_RFC822;
690 imsg->cm_fields['A'] = strdup("Citadel");
691 imsg->cm_fields['M'] = instr;
693 /* Save delivery instructions in spoolout room */
694 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
695 CtdlFreeMessage(imsg);
700 * Batch up and send all outbound traffic from the current room
702 void network_spoolout_room(char *room_to_spool) {
709 struct SpoolControl sc;
710 struct namelist *nptr = NULL;
713 int skipthisline = 0;
716 if (getroom(&CC->room, room_to_spool) != 0) {
717 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
721 memset(&sc, 0, sizeof(struct SpoolControl));
722 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
724 begin_critical_section(S_NETCONFIGS);
726 fp = fopen(filename, "r");
728 end_critical_section(S_NETCONFIGS);
732 lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
734 while (fgets(buf, sizeof buf, fp) != NULL) {
735 buf[strlen(buf)-1] = 0;
737 extract(instr, buf, 0);
738 if (!strcasecmp(instr, "lastsent")) {
739 sc.lastsent = extract_long(buf, 1);
741 else if (!strcasecmp(instr, "listrecp")) {
742 nptr = (struct namelist *)
743 malloc(sizeof(struct namelist));
744 nptr->next = sc.listrecps;
745 extract(nptr->name, buf, 1);
748 else if (!strcasecmp(instr, "digestrecp")) {
749 nptr = (struct namelist *)
750 malloc(sizeof(struct namelist));
751 nptr->next = sc.digestrecps;
752 extract(nptr->name, buf, 1);
753 sc.digestrecps = nptr;
755 else if (!strcasecmp(instr, "ignet_push_share")) {
756 /* by checking each node's validity, we automatically
757 * purge nodes which do not exist from room network
758 * configurations at this time.
760 extract(nodename, buf, 1);
761 strcpy(nexthop, "xxx");
762 if (is_valid_node(nexthop, NULL, nodename) == 0) {
763 if (strlen(nexthop) == 0) {
764 nptr = (struct namelist *)
765 malloc(sizeof(struct namelist));
766 nptr->next = sc.ignet_push_shares;
767 strcpy(nptr->name, nodename);
768 sc.ignet_push_shares = nptr;
773 /* Preserve 'other' lines ... *unless* they happen to
774 * be subscribe/unsubscribe pendings with expired
778 if (!strncasecmp(buf, "subpending|", 11)) {
779 if (time(NULL) - extract_long(buf, 4) > EXP) {
783 if (!strncasecmp(buf, "unsubpending|", 13)) {
784 if (time(NULL) - extract_long(buf, 3) > EXP) {
789 if (skipthisline == 0) {
790 linesize = strlen(buf);
791 sc.misc = realloc(sc.misc,
792 (miscsize + linesize + 2) );
793 sprintf(&sc.misc[miscsize], "%s\n", buf);
794 miscsize = miscsize + linesize + 1;
802 /* If there are digest recipients, we have to build a digest */
803 if (sc.digestrecps != NULL) {
804 sc.digestfp = tmpfile();
805 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
808 /* Do something useful */
809 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
810 network_spool_msg, &sc);
812 /* If we wrote a digest, deliver it and then close it */
813 snprintf(buf, sizeof buf, "room_%s@%s",
814 CC->room.QRname, config.c_fqdn);
815 for (i=0; i<strlen(buf); ++i) {
816 buf[i] = tolower(buf[i]);
817 if (isspace(buf[i])) buf[i] = '_';
819 if (sc.digestfp != NULL) {
820 fprintf(sc.digestfp, " -----------------------------------"
821 "------------------------------------"
823 "You are subscribed to the '%s' "
825 "To post to the list: %s\n",
828 network_deliver_digest(&sc); /* deliver and close */
831 /* Now rewrite the config file */
832 fp = fopen(filename, "w");
834 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
835 filename, strerror(errno));
838 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
840 /* Write out the listrecps while freeing from memory at the
841 * same time. Am I clever or what? :)
843 while (sc.listrecps != NULL) {
844 fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
845 nptr = sc.listrecps->next;
849 /* Do the same for digestrecps */
850 while (sc.digestrecps != NULL) {
851 fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
852 nptr = sc.digestrecps->next;
853 free(sc.digestrecps);
854 sc.digestrecps = nptr;
856 while (sc.ignet_push_shares != NULL) {
857 /* by checking each node's validity, we automatically
858 * purge nodes which do not exist from room network
859 * configurations at this time.
861 if (is_valid_node(NULL, NULL, sc.ignet_push_shares->name) == 0) {
863 fprintf(fp, "ignet_push_share|%s\n",
864 sc.ignet_push_shares->name);
865 nptr = sc.ignet_push_shares->next;
866 free(sc.ignet_push_shares);
867 sc.ignet_push_shares = nptr;
869 if (sc.misc != NULL) {
870 fwrite(sc.misc, strlen(sc.misc), 1, fp);
876 end_critical_section(S_NETCONFIGS);
882 * Send the *entire* contents of the current room to one specific network node,
883 * ignoring anything we know about which messages have already undergone
884 * network processing. This can be used to bring a new node into sync.
886 int network_sync_to(char *target_node) {
887 struct SpoolControl sc;
890 /* Concise syntax because we don't need a full linked-list */
891 memset(&sc, 0, sizeof(struct SpoolControl));
892 sc.ignet_push_shares = (struct namelist *)
893 malloc(sizeof(struct namelist));
894 sc.ignet_push_shares->next = NULL;
895 safestrncpy(sc.ignet_push_shares->name,
897 sizeof sc.ignet_push_shares->name);
899 /* Send ALL messages */
900 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
901 network_spool_msg, &sc);
903 /* Concise cleanup because we know there's only one node in the sc */
904 free(sc.ignet_push_shares);
906 lprintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
907 num_spooled, target_node);
913 * Implements the NSYN command
915 void cmd_nsyn(char *argbuf) {
917 char target_node[SIZ];
919 if (CtdlAccessCheck(ac_aide)) return;
921 extract(target_node, argbuf, 0);
922 num_spooled = network_sync_to(target_node);
923 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
929 * Batch up and send all outbound traffic from the current room
931 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
932 struct RoomProcList *ptr;
934 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
935 if (ptr == NULL) return;
937 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
944 * Learn topology from path fields
946 void network_learn_topology(char *node, char *path) {
948 struct NetMap *nmptr;
952 if (num_tokens(path, '!') < 3) return;
953 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
954 if (!strcasecmp(nmptr->nodename, node)) {
955 extract_token(nmptr->nexthop, path, 0, '!');
956 nmptr->lastcontact = time(NULL);
961 /* If we got here then it's not in the map, so add it. */
962 nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
963 strcpy(nmptr->nodename, node);
964 nmptr->lastcontact = time(NULL);
965 extract_token(nmptr->nexthop, path, 0, '!');
966 nmptr->next = the_netmap;
974 * Bounce a message back to the sender
976 void network_bounce(struct CtdlMessage *msg, char *reason) {
977 char *oldpath = NULL;
979 char bouncesource[SIZ];
981 struct recptypes *valid = NULL;
982 char force_room[ROOMNAMELEN];
983 static int serialnum = 0;
986 lprintf(CTDL_DEBUG, "entering network_bounce()\n");
988 if (msg == NULL) return;
990 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
993 * Give it a fresh message ID
995 if (msg->cm_fields['I'] != NULL) {
996 free(msg->cm_fields['I']);
998 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
999 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1000 msg->cm_fields['I'] = strdup(buf);
1003 * FIXME ... right now we're just sending a bounce; we really want to
1004 * include the text of the bounced message.
1006 if (msg->cm_fields['M'] != NULL) {
1007 free(msg->cm_fields['M']);
1009 msg->cm_fields['M'] = strdup(reason);
1010 msg->cm_format_type = 0;
1013 * Turn the message around
1015 if (msg->cm_fields['R'] == NULL) {
1016 free(msg->cm_fields['R']);
1019 if (msg->cm_fields['D'] == NULL) {
1020 free(msg->cm_fields['D']);
1023 snprintf(recipient, sizeof recipient, "%s@%s",
1024 msg->cm_fields['A'], msg->cm_fields['N']);
1026 if (msg->cm_fields['A'] == NULL) {
1027 free(msg->cm_fields['A']);
1030 if (msg->cm_fields['N'] == NULL) {
1031 free(msg->cm_fields['N']);
1034 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1035 msg->cm_fields['N'] = strdup(config.c_nodename);
1038 /* prepend our node to the path */
1039 if (msg->cm_fields['P'] != NULL) {
1040 oldpath = msg->cm_fields['P'];
1041 msg->cm_fields['P'] = NULL;
1044 oldpath = strdup("unknown_user");
1046 size = strlen(oldpath) + SIZ;
1047 msg->cm_fields['P'] = malloc(size);
1048 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1051 /* Now submit the message */
1052 valid = validate_recipients(recipient);
1053 if (valid != NULL) if (valid->num_error > 0) {
1057 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1058 strcpy(force_room, config.c_aideroom);
1061 strcpy(force_room, "");
1063 if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1064 strcpy(force_room, config.c_aideroom);
1066 CtdlSubmitMsg(msg, valid, force_room);
1069 if (valid != NULL) free(valid);
1070 CtdlFreeMessage(msg);
1071 lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1078 * Process a buffer containing a single message from a single file
1079 * from the inbound queue
1081 void network_process_buffer(char *buffer, long size) {
1082 struct CtdlMessage *msg;
1085 struct recptypes *recp = NULL;
1086 char target_room[ROOMNAMELEN];
1087 struct ser_ret sermsg;
1088 char *oldpath = NULL;
1092 unsigned char firstbyte;
1093 unsigned char lastbyte;
1095 /* Validate just a little bit. First byte should be FF and
1096 * last byte should be 00.
1098 memcpy(&firstbyte, &buffer[0], 1);
1099 memcpy(&lastbyte, &buffer[size-1], 1);
1100 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1101 lprintf(CTDL_ERR, "Corrupt message! Ignoring.\n");
1105 /* Set default target room to trash */
1106 strcpy(target_room, TWITROOM);
1108 /* Load the message into memory */
1109 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1110 memset(msg, 0, sizeof(struct CtdlMessage));
1111 msg->cm_magic = CTDLMESSAGE_MAGIC;
1112 msg->cm_anon_type = buffer[1];
1113 msg->cm_format_type = buffer[2];
1115 for (pos = 3; pos < size; ++pos) {
1116 field = buffer[pos];
1117 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1118 pos = pos + strlen(&buffer[(int)pos]);
1121 /* Check for message routing */
1122 if (msg->cm_fields['D'] != NULL) {
1123 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1125 /* route the message */
1126 strcpy(nexthop, "");
1127 if (is_valid_node(nexthop, NULL,
1128 msg->cm_fields['D']) == 0) {
1130 /* prepend our node to the path */
1131 if (msg->cm_fields['P'] != NULL) {
1132 oldpath = msg->cm_fields['P'];
1133 msg->cm_fields['P'] = NULL;
1136 oldpath = strdup("unknown_user");
1138 size = strlen(oldpath) + SIZ;
1139 msg->cm_fields['P'] = malloc(size);
1140 snprintf(msg->cm_fields['P'], size, "%s!%s",
1141 config.c_nodename, oldpath);
1144 /* serialize the message */
1145 serialize_message(&sermsg, msg);
1148 if (strlen(nexthop) == 0) {
1149 strcpy(nexthop, msg->cm_fields['D']);
1151 snprintf(filename, sizeof filename,
1152 "./network/spoolout/%s", nexthop);
1153 fp = fopen(filename, "ab");
1160 CtdlFreeMessage(msg);
1164 else { /* invalid destination node name */
1167 "A message you sent could not be delivered due to an invalid destination node"
1168 " name. Please check the address and try sending the message again.\n");
1177 * Check to see if we already have a copy of this message, and
1178 * abort its processing if so. (We used to post a warning to Aide>
1179 * every time this happened, but the network is now so densely
1180 * connected that it's inevitable.)
1182 if (network_usetable(msg) != 0) {
1186 /* Learn network topology from the path */
1187 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1188 network_learn_topology(msg->cm_fields['N'],
1189 msg->cm_fields['P']);
1192 /* Is the sending node giving us a very persuasive suggestion about
1193 * which room this message should be saved in? If so, go with that.
1195 if (msg->cm_fields['C'] != NULL) {
1196 safestrncpy(target_room,
1197 msg->cm_fields['C'],
1198 sizeof target_room);
1201 /* Otherwise, does it have a recipient? If so, validate it... */
1202 else if (msg->cm_fields['R'] != NULL) {
1203 recp = validate_recipients(msg->cm_fields['R']);
1204 if (recp != NULL) if (recp->num_error > 0) {
1206 "A message you sent could not be delivered due to an invalid address.\n"
1207 "Please check the address and try sending the message again.\n");
1212 strcpy(target_room, ""); /* no target room if mail */
1215 /* Our last shot at finding a home for this message is to see if
1216 * it has the O field (Originating room) set.
1218 else if (msg->cm_fields['O'] != NULL) {
1219 safestrncpy(target_room,
1220 msg->cm_fields['O'],
1221 sizeof target_room);
1224 /* Strip out fields that are only relevant during transit */
1225 if (msg->cm_fields['D'] != NULL) {
1226 free(msg->cm_fields['D']);
1227 msg->cm_fields['D'] = NULL;
1229 if (msg->cm_fields['C'] != NULL) {
1230 free(msg->cm_fields['C']);
1231 msg->cm_fields['C'] = NULL;
1234 /* save the message into a room */
1235 if (PerformNetprocHooks(msg, target_room) == 0) {
1236 msg->cm_flags = CM_SKIP_HOOKS;
1237 CtdlSubmitMsg(msg, recp, target_room);
1239 CtdlFreeMessage(msg);
1245 * Process a single message from a single file from the inbound queue
1247 void network_process_message(FILE *fp, long msgstart, long msgend) {
1252 hold_pos = ftell(fp);
1253 size = msgend - msgstart + 1;
1254 buffer = malloc(size);
1255 if (buffer != NULL) {
1256 fseek(fp, msgstart, SEEK_SET);
1257 fread(buffer, size, 1, fp);
1258 network_process_buffer(buffer, size);
1262 fseek(fp, hold_pos, SEEK_SET);
1267 * Process a single file from the inbound queue
1269 void network_process_file(char *filename) {
1271 long msgstart = (-1L);
1272 long msgend = (-1L);
1277 fp = fopen(filename, "rb");
1279 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1280 filename, strerror(errno));
1284 lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1286 /* Look for messages in the data stream and break them out */
1287 while (ch = getc(fp), ch >= 0) {
1290 if (msgstart >= 0L) {
1291 msgend = msgcur - 1;
1292 network_process_message(fp, msgstart, msgend);
1300 msgend = msgcur - 1;
1301 if (msgstart >= 0L) {
1302 network_process_message(fp, msgstart, msgend);
1311 * Process anything in the inbound queue
1313 void network_do_spoolin(void) {
1318 dp = opendir("./network/spoolin");
1319 if (dp == NULL) return;
1321 while (d = readdir(dp), d != NULL) {
1322 snprintf(filename, sizeof filename,
1323 "./network/spoolin/%s", d->d_name);
1324 network_process_file(filename);
1333 * Delete any files in the outbound queue that were intended
1334 * to be sent to nodes which no longer exist.
1336 void network_purge_spoolout(void) {
1343 dp = opendir("./network/spoolout");
1344 if (dp == NULL) return;
1346 while (d = readdir(dp), d != NULL) {
1347 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1349 snprintf(filename, sizeof filename,
1350 "./network/spoolout/%s", d->d_name);
1352 strcpy(nexthop, "");
1353 i = is_valid_node(nexthop, NULL, d->d_name);
1355 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1367 * receive network spool from the remote system
1369 void receive_spool(int sock, char *remote_nodename) {
1371 long bytes_received;
1373 static char pbuf[IGNET_PACKET_SIZE];
1374 char tempfilename[PATH_MAX];
1378 strcpy(tempfilename, tmpnam(NULL));
1379 if (sock_puts(sock, "NDOP") < 0) return;
1380 if (sock_gets(sock, buf) < 0) return;
1381 lprintf(CTDL_DEBUG, "<%s\n", buf);
1382 if (buf[0] != '2') {
1385 download_len = extract_long(&buf[4], 0);
1387 bytes_received = 0L;
1388 fp = fopen(tempfilename, "w");
1390 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1395 while (bytes_received < download_len) {
1396 snprintf(buf, sizeof buf, "READ %ld|%ld",
1398 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1399 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1400 if (sock_puts(sock, buf) < 0) {
1402 unlink(tempfilename);
1405 if (sock_gets(sock, buf) < 0) {
1407 unlink(tempfilename);
1410 if (buf[0] == '6') {
1411 plen = extract_long(&buf[4], 0);
1412 if (sock_read(sock, pbuf, plen) < 0) {
1414 unlink(tempfilename);
1417 fwrite((char *) pbuf, plen, 1, fp);
1418 bytes_received = bytes_received + plen;
1423 if (sock_puts(sock, "CLOS") < 0) {
1424 unlink(tempfilename);
1427 if (sock_gets(sock, buf) < 0) {
1428 unlink(tempfilename);
1431 if (download_len > 0)
1432 lprintf(CTDL_NOTICE, "Received %ld octets from <%s>",
1433 download_len, remote_nodename);
1434 lprintf(CTDL_DEBUG, "%s", buf);
1435 snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1436 tempfilename, remote_nodename, (long) getpid());
1443 * transmit network spool to the remote system
1445 void transmit_spool(int sock, char *remote_nodename)
1450 long bytes_to_write, thisblock, bytes_written;
1454 if (sock_puts(sock, "NUOP") < 0) return;
1455 if (sock_gets(sock, buf) < 0) return;
1456 lprintf(CTDL_DEBUG, "<%s\n", buf);
1457 if (buf[0] != '2') {
1461 snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1462 fd = open(sfname, O_RDONLY);
1464 if (errno != ENOENT) {
1465 lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1471 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1472 bytes_to_write = plen;
1473 while (bytes_to_write > 0L) {
1474 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1475 if (sock_puts(sock, buf) < 0) {
1479 if (sock_gets(sock, buf) < 0) {
1483 thisblock = atol(&buf[4]);
1484 if (buf[0] == '7') {
1485 if (sock_write(sock, pbuf,
1486 (int) thisblock) < 0) {
1490 bytes_to_write -= thisblock;
1491 bytes_written += thisblock;
1500 if (sock_puts(sock, "UCLS 1") < 0) return;
1501 if (sock_gets(sock, buf) < 0) return;
1502 lprintf(CTDL_NOTICE, "Sent %ld octets to <%s>",
1503 bytes_written, remote_nodename);
1504 lprintf(CTDL_DEBUG, "<%s\n", buf);
1505 if (buf[0] == '2') {
1513 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1515 void network_poll_node(char *node, char *secret, char *host, char *port) {
1519 if (network_talking_to(node, NTT_CHECK)) return;
1520 network_talking_to(node, NTT_ADD);
1521 lprintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
1523 sock = sock_connect(host, port, "tcp");
1525 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1526 network_talking_to(node, NTT_REMOVE);
1530 lprintf(CTDL_DEBUG, "Connected!\n");
1532 /* Read the server greeting */
1533 if (sock_gets(sock, buf) < 0) goto bail;
1534 lprintf(CTDL_DEBUG, ">%s\n", buf);
1536 /* Identify ourselves */
1537 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1538 lprintf(CTDL_DEBUG, "<%s\n", buf);
1539 if (sock_puts(sock, buf) <0) goto bail;
1540 if (sock_gets(sock, buf) < 0) goto bail;
1541 lprintf(CTDL_DEBUG, ">%s\n", buf);
1542 if (buf[0] != '2') goto bail;
1544 /* At this point we are authenticated. */
1545 receive_spool(sock, node);
1546 transmit_spool(sock, node);
1548 sock_puts(sock, "QUIT");
1549 bail: sock_close(sock);
1550 network_talking_to(node, NTT_REMOVE);
1556 * Poll other Citadel nodes and transfer inbound/outbound network data.
1557 * Set "full" to nonzero to force a poll of every node, or to zero to poll
1558 * only nodes to which we have data to send.
1560 void network_poll_other_citadel_nodes(int full_poll) {
1568 char spoolfile[SIZ];
1570 if (working_ignetcfg == NULL) {
1571 lprintf(CTDL_DEBUG, "No nodes defined - not polling\n");
1575 /* Use the string tokenizer to grab one line at a time */
1576 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1577 extract_token(linebuf, working_ignetcfg, i, '\n');
1578 extract(node, linebuf, 0);
1579 extract(secret, linebuf, 1);
1580 extract(host, linebuf, 2);
1581 extract(port, linebuf, 3);
1582 if ( (strlen(node) > 0) && (strlen(secret) > 0)
1583 && (strlen(host) > 0) && strlen(port) > 0) {
1586 sprintf(spoolfile, "./network/spoolout/%s",
1588 if (access(spoolfile, R_OK) == 0) {
1593 network_poll_node(node, secret, host, port);
1607 * network_do_queue()
1609 * Run through the rooms doing various types of network stuff.
1611 void network_do_queue(void) {
1612 static time_t last_run = 0L;
1613 struct RoomProcList *ptr;
1614 int full_processing = 1;
1617 * Run the full set of processing tasks no more frequently
1618 * than once every n seconds
1620 if ( (time(NULL) - last_run) < config.c_net_freq ) {
1621 full_processing = 0;
1625 * This is a simple concurrency check to make sure only one queue run
1626 * is done at a time. We could do this with a mutex, but since we
1627 * don't really require extremely fine granularity here, we'll do it
1628 * with a static variable instead.
1630 if (doing_queue) return;
1633 /* Load the IGnet Configuration into memory */
1634 load_working_ignetcfg();
1637 * Poll other Citadel nodes. Maybe. If "full_processing" is set
1638 * then we poll everyone. Otherwise we only poll nodes we have stuff
1641 network_poll_other_citadel_nodes(full_processing);
1644 * Load the network map and filter list into memory.
1647 filterlist = load_filter_list();
1650 * Go ahead and run the queue
1652 if (full_processing) {
1653 lprintf(CTDL_DEBUG, "network: loading outbound queue\n");
1654 ForEachRoom(network_queue_room, NULL);
1656 lprintf(CTDL_DEBUG, "network: running outbound queue\n");
1657 while (rplist != NULL) {
1658 network_spoolout_room(rplist->name);
1660 rplist = rplist->next;
1665 lprintf(CTDL_DEBUG, "network: processing inbound queue\n");
1666 network_do_spoolin();
1668 /* Save the network map back to disk */
1669 write_network_map();
1671 /* Free the filter list in memory */
1672 free_filter_list(filterlist);
1675 network_purge_spoolout();
1677 lprintf(CTDL_DEBUG, "network: queue run completed\n");
1679 if (full_processing) {
1680 last_run = time(NULL);
1688 * cmd_netp() - authenticate to the server as another Citadel node polling
1689 * for network traffic
1691 void cmd_netp(char *cmdbuf)
1701 extract(node, cmdbuf, 0);
1702 extract(pass, cmdbuf, 1);
1705 lprintf(CTDL_WARNING, "Network node <%s> refused - spooling", node);
1706 cprintf("%d spooling - try again in a few minutes\n",
1707 ERROR + RESOURCE_BUSY);
1711 /* load the IGnet Configuration to check node validity */
1712 load_working_ignetcfg();
1713 v = is_valid_node(nexthop, secret, node);
1716 lprintf(CTDL_WARNING, "Unknown node <%s>", node);
1717 cprintf("%d authentication failed\n",
1718 ERROR + PASSWORD_REQUIRED);
1722 if (strcasecmp(pass, secret)) {
1723 lprintf(CTDL_WARNING, "Bad password for network node <%s>", node);
1724 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1728 if (network_talking_to(node, NTT_CHECK)) {
1729 lprintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
1730 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1734 safestrncpy(CC->net_node, node, sizeof CC->net_node);
1735 network_talking_to(node, NTT_ADD);
1736 lprintf(CTDL_NOTICE, "Network node <%s> logged in", CC->net_node);
1737 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1744 * Module entry point
1746 char *serv_network_init(void)
1748 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1749 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1750 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1751 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1752 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);