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;
88 char *ignetcfg = NULL;
91 * Keep track of what messages to reject
93 struct FilterList *load_filter_list(void) {
94 char *serialized_list = NULL;
97 struct FilterList *newlist = NULL;
98 struct FilterList *nptr;
100 serialized_list = CtdlGetSysConfig(FILTERLIST);
101 if (serialized_list == NULL) return(NULL); /* if null, no entries */
103 /* Use the string tokenizer to grab one line at a time */
104 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
105 extract_token(buf, serialized_list, i, '\n');
106 nptr = (struct FilterList *) malloc(sizeof(struct FilterList));
107 extract(nptr->fl_user, buf, 0);
108 striplt(nptr->fl_user);
109 extract(nptr->fl_room, buf, 1);
110 striplt(nptr->fl_room);
111 extract(nptr->fl_node, buf, 2);
112 striplt(nptr->fl_node);
114 /* Cowardly refuse to add an any/any/any entry that would
115 * end up filtering every single message.
117 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
118 + strlen(nptr->fl_node) == 0) {
122 nptr->next = newlist;
127 free(serialized_list);
132 void free_filter_list(struct FilterList *fl) {
133 if (fl == NULL) return;
134 free_filter_list(fl->next);
141 * Check the use table. This is a list of messages which have recently
142 * arrived on the system. It is maintained and queried to prevent the same
143 * message from being entered into the database multiple times if it happens
144 * to arrive multiple times by accident.
146 int network_usetable(struct CtdlMessage *msg) {
149 struct cdbdata *cdbut;
152 /* Bail out if we can't generate a message ID */
156 if (msg->cm_fields['I'] == NULL) {
159 if (strlen(msg->cm_fields['I']) == 0) {
163 /* Generate the message ID */
164 strcpy(msgid, msg->cm_fields['I']);
165 if (haschar(msgid, '@') == 0) {
167 if (msg->cm_fields['N'] != NULL) {
168 strcat(msgid, msg->cm_fields['N']);
175 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
181 /* If we got to this point, it's unique: add it. */
182 strcpy(ut.ut_msgid, msgid);
183 ut.ut_timestamp = time(NULL);
184 cdb_store(CDB_USETABLE, msgid, strlen(msgid),
185 &ut, sizeof(struct UseTable) );
191 * Read the network map from its configuration file into memory.
193 void read_network_map(void) {
194 char *serialized_map = NULL;
197 struct NetMap *nmptr;
199 serialized_map = CtdlGetSysConfig(IGNETMAP);
200 if (serialized_map == NULL) return; /* if null, no entries */
202 /* Use the string tokenizer to grab one line at a time */
203 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
204 extract_token(buf, serialized_map, i, '\n');
205 nmptr = (struct NetMap *) malloc(sizeof(struct NetMap));
206 extract(nmptr->nodename, buf, 0);
207 nmptr->lastcontact = extract_long(buf, 1);
208 extract(nmptr->nexthop, buf, 2);
209 nmptr->next = the_netmap;
213 free(serialized_map);
218 * Write the network map from memory back to the configuration file.
220 void write_network_map(void) {
221 char *serialized_map = NULL;
222 struct NetMap *nmptr;
224 serialized_map = strdup("");
226 if (the_netmap != NULL) {
227 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
228 serialized_map = realloc(serialized_map,
229 (strlen(serialized_map)+SIZ) );
230 if (strlen(nmptr->nodename) > 0) {
231 snprintf(&serialized_map[strlen(serialized_map)],
235 (long)nmptr->lastcontact,
241 CtdlPutSysConfig(IGNETMAP, serialized_map);
242 free(serialized_map);
244 /* Now free the list */
245 while (the_netmap != NULL) {
246 nmptr = the_netmap->next;
255 * Check the network map and determine whether the supplied node name is
256 * valid. If it is not a neighbor node, supply the name of a neighbor node
257 * which is the next hop. If it *is* a neighbor node, we also fill in the
260 int is_valid_node(char *nexthop, char *secret, char *node) {
265 struct NetMap *nmptr;
272 * First try the neighbor nodes
274 if (ignetcfg == NULL) {
275 if (nexthop != NULL) {
282 if (nexthop != NULL) {
286 /* Use the string tokenizer to grab one line at a time */
287 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
288 extract_token(linebuf, ignetcfg, i, '\n');
289 extract(buf, linebuf, 0);
290 if (!strcasecmp(buf, node)) {
291 if (nexthop != NULL) {
294 if (secret != NULL) {
295 extract(secret, linebuf, 1);
302 return(retval); /* yup, it's a direct neighbor */
306 * If we get to this point we have to see if we know the next hop
308 if (the_netmap != NULL) {
309 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
310 if (!strcasecmp(nmptr->nodename, node)) {
311 if (nexthop != NULL) {
312 strcpy(nexthop, nmptr->nexthop);
320 * If we get to this point, the supplied node name is bogus.
322 lprintf(CTDL_ERR, "Invalid node name <%s>\n", node);
330 void cmd_gnet(char *argbuf) {
335 if (CtdlAccessCheck(ac_room_aide)) return;
336 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
337 cprintf("%d Network settings for room #%ld <%s>\n",
339 CC->room.QRnumber, CC->room.QRname);
341 fp = fopen(filename, "r");
343 while (fgets(buf, sizeof buf, fp) != NULL) {
344 buf[strlen(buf)-1] = 0;
345 cprintf("%s\n", buf);
354 void cmd_snet(char *argbuf) {
355 char tempfilename[SIZ];
360 if (CtdlAccessCheck(ac_room_aide)) return;
361 safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
362 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
364 fp = fopen(tempfilename, "w");
366 cprintf("%d Cannot open %s: %s\n",
367 ERROR + INTERNAL_ERROR,
372 cprintf("%d %s\n", SEND_LISTING, tempfilename);
373 while (client_gets(buf), strcmp(buf, "000")) {
374 fprintf(fp, "%s\n", buf);
378 /* Now copy the temp file to its permanent location
379 * (We use /bin/mv instead of link() because they may be on
380 * different filesystems)
383 snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
384 begin_critical_section(S_NETCONFIGS);
386 end_critical_section(S_NETCONFIGS);
391 * Spools out one message from the list.
393 void network_spool_msg(long msgnum, void *userdata) {
394 struct SpoolControl *sc;
397 char *newpath = NULL;
399 size_t instr_len = SIZ;
400 struct CtdlMessage *msg = NULL;
401 struct CtdlMessage *imsg;
402 struct namelist *nptr;
403 struct ser_ret sermsg;
409 int delete_after_send = 0; /* Set to 1 to delete after spooling */
411 sc = (struct SpoolControl *)userdata;
414 * Process mailing list recipients
416 if (sc->listrecps != NULL) {
418 /* First, copy it to the spoolout room */
419 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
420 if (err != 0) return;
423 * Figure out how big a buffer we need to allocate
425 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
426 instr_len = instr_len + strlen(nptr->name);
432 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
433 instr = malloc(instr_len);
435 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
439 snprintf(instr, instr_len,
440 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
441 "bounceto|postmaster@%s\n" ,
442 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
444 /* Generate delivery instructions for each recipient */
445 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
446 size_t tmp = strlen(instr);
447 snprintf(&instr[tmp], instr_len - tmp,
448 "remote|%s|0||\n", nptr->name);
452 * Generate a message from the instructions
454 imsg = malloc(sizeof(struct CtdlMessage));
455 memset(imsg, 0, sizeof(struct CtdlMessage));
456 imsg->cm_magic = CTDLMESSAGE_MAGIC;
457 imsg->cm_anon_type = MES_NORMAL;
458 imsg->cm_format_type = FMT_RFC822;
459 imsg->cm_fields['A'] = strdup("Citadel");
460 imsg->cm_fields['M'] = instr;
462 /* Save delivery instructions in spoolout room */
463 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
464 CtdlFreeMessage(imsg);
468 * Process digest recipients
470 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
471 fprintf(sc->digestfp, " -----------------------------------"
472 "------------------------------------"
474 CtdlRedirectOutput(sc->digestfp, -1);
475 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
476 CtdlRedirectOutput(NULL, -1);
477 sc->num_msgs_spooled += 1;
481 * Process IGnet push shares
483 if (sc->ignet_push_shares != NULL) {
485 msg = CtdlFetchMessage(msgnum, 1);
489 /* Prepend our node name to the Path field whenever
490 * sending a message to another IGnet node
492 if (msg->cm_fields['P'] == NULL) {
493 msg->cm_fields['P'] = strdup("username");
495 newpath_len = strlen(msg->cm_fields['P']) +
496 strlen(config.c_nodename) + 2;
497 newpath = malloc(newpath_len);
498 snprintf(newpath, newpath_len, "%s!%s",
499 config.c_nodename, msg->cm_fields['P']);
500 free(msg->cm_fields['P']);
501 msg->cm_fields['P'] = newpath;
504 * Force the message to appear in the correct room
505 * on the far end by setting the C field correctly
507 if (msg->cm_fields['C'] != NULL) {
508 free(msg->cm_fields['C']);
510 msg->cm_fields['C'] = strdup(CC->room.QRname);
513 * Determine if this message is set to be deleted
514 * after sending out on the network
516 if (msg->cm_fields['S'] != NULL) {
517 if (!strcasecmp(msg->cm_fields['S'],
519 delete_after_send = 1;
524 * Now serialize it for transmission
526 serialize_message(&sermsg, msg);
528 /* Now send it to every node */
529 for (nptr = sc->ignet_push_shares; nptr != NULL;
534 /* Check for valid node name */
535 if (is_valid_node(NULL, NULL, nptr->name) != 0) {
536 lprintf(CTDL_ERR, "Invalid node <%s>\n",
541 /* Check for split horizon */
542 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
543 bang = num_tokens(msg->cm_fields['P'], '!');
544 if (bang > 1) for (i=0; i<(bang-1); ++i) {
545 extract_token(buf, msg->cm_fields['P'],
547 if (!strcasecmp(buf, nptr->name)) {
552 /* Send the message */
554 snprintf(filename, sizeof filename,
555 "./network/spoolout/%s",
557 fp = fopen(filename, "ab");
566 CtdlFreeMessage(msg);
570 /* update lastsent */
571 sc->lastsent = msgnum;
573 /* Delete this message if delete-after-send is set */
574 if (delete_after_send) {
575 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
582 * Deliver digest messages
584 void network_deliver_digest(struct SpoolControl *sc) {
587 struct CtdlMessage *msg;
591 size_t instr_len = SIZ;
592 struct CtdlMessage *imsg;
593 struct namelist *nptr;
595 if (sc->num_msgs_spooled < 1) {
596 fclose(sc->digestfp);
601 msg = malloc(sizeof(struct CtdlMessage));
602 memset(msg, 0, sizeof(struct CtdlMessage));
603 msg->cm_magic = CTDLMESSAGE_MAGIC;
604 msg->cm_format_type = FMT_RFC822;
605 msg->cm_anon_type = MES_NORMAL;
607 sprintf(buf, "%ld", time(NULL));
608 msg->cm_fields['T'] = strdup(buf);
609 msg->cm_fields['A'] = strdup(CC->room.QRname);
610 msg->cm_fields['U'] = strdup(CC->room.QRname);
611 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
612 for (i=0; i<strlen(buf); ++i) {
613 if (isspace(buf[i])) buf[i]='_';
614 buf[i] = tolower(buf[i]);
616 msg->cm_fields['F'] = strdup(buf);
618 fseek(sc->digestfp, 0L, SEEK_END);
619 msglen = ftell(sc->digestfp);
621 msg->cm_fields['M'] = malloc(msglen + 1);
622 fseek(sc->digestfp, 0L, SEEK_SET);
623 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
624 msg->cm_fields['M'][msglen] = 0;
626 fclose(sc->digestfp);
629 msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
630 CtdlFreeMessage(msg);
632 /* Now generate the delivery instructions */
635 * Figure out how big a buffer we need to allocate
637 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
638 instr_len = instr_len + strlen(nptr->name);
644 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
645 instr = malloc(instr_len);
647 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
651 snprintf(instr, instr_len,
652 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
653 "bounceto|postmaster@%s\n" ,
654 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
656 /* Generate delivery instructions for each recipient */
657 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
658 size_t tmp = strlen(instr);
659 snprintf(&instr[tmp], instr_len - tmp,
660 "remote|%s|0||\n", nptr->name);
664 * Generate a message from the instructions
666 imsg = malloc(sizeof(struct CtdlMessage));
667 memset(imsg, 0, sizeof(struct CtdlMessage));
668 imsg->cm_magic = CTDLMESSAGE_MAGIC;
669 imsg->cm_anon_type = MES_NORMAL;
670 imsg->cm_format_type = FMT_RFC822;
671 imsg->cm_fields['A'] = strdup("Citadel");
672 imsg->cm_fields['M'] = instr;
674 /* Save delivery instructions in spoolout room */
675 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
676 CtdlFreeMessage(imsg);
681 * Batch up and send all outbound traffic from the current room
683 void network_spoolout_room(char *room_to_spool) {
688 struct SpoolControl sc;
689 struct namelist *nptr = NULL;
692 int skipthisline = 0;
695 if (getroom(&CC->room, room_to_spool) != 0) {
696 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
700 memset(&sc, 0, sizeof(struct SpoolControl));
701 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
703 begin_critical_section(S_NETCONFIGS);
705 fp = fopen(filename, "r");
707 end_critical_section(S_NETCONFIGS);
711 lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
713 while (fgets(buf, sizeof buf, fp) != NULL) {
714 buf[strlen(buf)-1] = 0;
716 extract(instr, buf, 0);
717 if (!strcasecmp(instr, "lastsent")) {
718 sc.lastsent = extract_long(buf, 1);
720 else if (!strcasecmp(instr, "listrecp")) {
721 nptr = (struct namelist *)
722 malloc(sizeof(struct namelist));
723 nptr->next = sc.listrecps;
724 extract(nptr->name, buf, 1);
727 else if (!strcasecmp(instr, "digestrecp")) {
728 nptr = (struct namelist *)
729 malloc(sizeof(struct namelist));
730 nptr->next = sc.digestrecps;
731 extract(nptr->name, buf, 1);
732 sc.digestrecps = nptr;
734 else if (!strcasecmp(instr, "ignet_push_share")) {
735 /* by checking each node's validity, we automatically
736 * purge nodes which do not exist from room network
737 * configurations at this time.
739 if (is_valid_node(NULL, NULL, buf) == 0) {
740 nptr = (struct namelist *)
741 malloc(sizeof(struct namelist));
742 nptr->next = sc.ignet_push_shares;
743 extract(nptr->name, buf, 1);
744 sc.ignet_push_shares = nptr;
748 /* Preserve 'other' lines ... *unless* they happen to
749 * be subscribe/unsubscribe pendings with expired
753 if (!strncasecmp(buf, "subpending|", 11)) {
754 if (time(NULL) - extract_long(buf, 4) > EXP) {
758 if (!strncasecmp(buf, "unsubpending|", 13)) {
759 if (time(NULL) - extract_long(buf, 3) > EXP) {
764 if (skipthisline == 0) {
765 linesize = strlen(buf);
766 sc.misc = realloc(sc.misc,
767 (miscsize + linesize + 2) );
768 sprintf(&sc.misc[miscsize], "%s\n", buf);
769 miscsize = miscsize + linesize + 1;
777 /* If there are digest recipients, we have to build a digest */
778 if (sc.digestrecps != NULL) {
779 sc.digestfp = tmpfile();
780 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
783 /* Do something useful */
784 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
785 network_spool_msg, &sc);
787 /* If we wrote a digest, deliver it and then close it */
788 snprintf(buf, sizeof buf, "room_%s@%s",
789 CC->room.QRname, config.c_fqdn);
790 for (i=0; i<strlen(buf); ++i) {
791 buf[i] = tolower(buf[i]);
792 if (isspace(buf[i])) buf[i] = '_';
794 if (sc.digestfp != NULL) {
795 fprintf(sc.digestfp, " -----------------------------------"
796 "------------------------------------"
798 "You are subscribed to the '%s' "
800 "To post to the list: %s\n",
803 network_deliver_digest(&sc); /* deliver and close */
806 /* Now rewrite the config file */
807 fp = fopen(filename, "w");
809 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
810 filename, strerror(errno));
813 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
815 /* Write out the listrecps while freeing from memory at the
816 * same time. Am I clever or what? :)
818 while (sc.listrecps != NULL) {
819 fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
820 nptr = sc.listrecps->next;
824 /* Do the same for digestrecps */
825 while (sc.digestrecps != NULL) {
826 fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
827 nptr = sc.digestrecps->next;
828 free(sc.digestrecps);
829 sc.digestrecps = nptr;
831 while (sc.ignet_push_shares != NULL) {
832 /* by checking each node's validity, we automatically
833 * purge nodes which do not exist from room network
834 * configurations at this time.
836 if (is_valid_node(NULL, NULL, sc.ignet_push_shares->name) == 0) {
838 fprintf(fp, "ignet_push_share|%s\n",
839 sc.ignet_push_shares->name);
840 nptr = sc.ignet_push_shares->next;
841 free(sc.ignet_push_shares);
842 sc.ignet_push_shares = nptr;
844 if (sc.misc != NULL) {
845 fwrite(sc.misc, strlen(sc.misc), 1, fp);
851 end_critical_section(S_NETCONFIGS);
857 * Send the *entire* contents of the current room to one specific network node,
858 * ignoring anything we know about which messages have already undergone
859 * network processing. This can be used to bring a new node into sync.
861 int network_sync_to(char *target_node) {
862 struct SpoolControl sc;
865 /* Concise syntax because we don't need a full linked-list */
866 memset(&sc, 0, sizeof(struct SpoolControl));
867 sc.ignet_push_shares = (struct namelist *)
868 malloc(sizeof(struct namelist));
869 sc.ignet_push_shares->next = NULL;
870 safestrncpy(sc.ignet_push_shares->name,
872 sizeof sc.ignet_push_shares->name);
874 /* Send ALL messages */
875 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
876 network_spool_msg, &sc);
878 /* Concise cleanup because we know there's only one node in the sc */
879 free(sc.ignet_push_shares);
881 lprintf(CTDL_INFO, "Synchronized %d messages to <%s>\n",
882 num_spooled, target_node);
888 * Implements the NSYN command
890 void cmd_nsyn(char *argbuf) {
892 char target_node[SIZ];
894 if (CtdlAccessCheck(ac_aide)) return;
896 extract(target_node, argbuf, 0);
897 num_spooled = network_sync_to(target_node);
898 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
904 * Batch up and send all outbound traffic from the current room
906 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
907 struct RoomProcList *ptr;
909 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
910 if (ptr == NULL) return;
912 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
919 * Learn topology from path fields
921 void network_learn_topology(char *node, char *path) {
923 struct NetMap *nmptr;
927 if (num_tokens(path, '!') < 3) return;
928 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
929 if (!strcasecmp(nmptr->nodename, node)) {
930 extract_token(nmptr->nexthop, path, 0, '!');
931 nmptr->lastcontact = time(NULL);
936 /* If we got here then it's not in the map, so add it. */
937 nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
938 strcpy(nmptr->nodename, node);
939 nmptr->lastcontact = time(NULL);
940 extract_token(nmptr->nexthop, path, 0, '!');
941 nmptr->next = the_netmap;
949 * Bounce a message back to the sender
951 void network_bounce(struct CtdlMessage *msg, char *reason) {
952 char *oldpath = NULL;
954 char bouncesource[SIZ];
956 struct recptypes *valid = NULL;
957 char force_room[ROOMNAMELEN];
958 static int serialnum = 0;
961 lprintf(CTDL_DEBUG, "entering network_bounce()\n");
963 if (msg == NULL) return;
965 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
968 * Give it a fresh message ID
970 if (msg->cm_fields['I'] != NULL) {
971 free(msg->cm_fields['I']);
973 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
974 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
975 msg->cm_fields['I'] = strdup(buf);
978 * FIXME ... right now we're just sending a bounce; we really want to
979 * include the text of the bounced message.
981 if (msg->cm_fields['M'] != NULL) {
982 free(msg->cm_fields['M']);
984 msg->cm_fields['M'] = strdup(reason);
985 msg->cm_format_type = 0;
988 * Turn the message around
990 if (msg->cm_fields['R'] == NULL) {
991 free(msg->cm_fields['R']);
994 if (msg->cm_fields['D'] == NULL) {
995 free(msg->cm_fields['D']);
998 snprintf(recipient, sizeof recipient, "%s@%s",
999 msg->cm_fields['A'], msg->cm_fields['N']);
1001 if (msg->cm_fields['A'] == NULL) {
1002 free(msg->cm_fields['A']);
1005 if (msg->cm_fields['N'] == NULL) {
1006 free(msg->cm_fields['N']);
1009 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1010 msg->cm_fields['N'] = strdup(config.c_nodename);
1013 /* prepend our node to the path */
1014 if (msg->cm_fields['P'] != NULL) {
1015 oldpath = msg->cm_fields['P'];
1016 msg->cm_fields['P'] = NULL;
1019 oldpath = strdup("unknown_user");
1021 size = strlen(oldpath) + SIZ;
1022 msg->cm_fields['P'] = malloc(size);
1023 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1026 /* Now submit the message */
1027 valid = validate_recipients(recipient);
1028 if (valid != NULL) if (valid->num_error > 0) {
1032 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1033 strcpy(force_room, config.c_aideroom);
1036 strcpy(force_room, "");
1038 if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1039 strcpy(force_room, config.c_aideroom);
1041 CtdlSubmitMsg(msg, valid, force_room);
1044 if (valid != NULL) free(valid);
1045 CtdlFreeMessage(msg);
1046 lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1053 * Process a buffer containing a single message from a single file
1054 * from the inbound queue
1056 void network_process_buffer(char *buffer, long size) {
1057 struct CtdlMessage *msg;
1060 struct recptypes *recp = NULL;
1061 char target_room[ROOMNAMELEN];
1062 struct ser_ret sermsg;
1063 char *oldpath = NULL;
1067 unsigned char firstbyte;
1068 unsigned char lastbyte;
1070 /* Validate just a little bit. First byte should be FF and
1071 * last byte should be 00.
1073 memcpy(&firstbyte, &buffer[0], 1);
1074 memcpy(&lastbyte, &buffer[size-1], 1);
1075 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1076 lprintf(CTDL_ERR, "Corrupt message! Ignoring.\n");
1080 /* Set default target room to trash */
1081 strcpy(target_room, TWITROOM);
1083 /* Load the message into memory */
1084 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1085 memset(msg, 0, sizeof(struct CtdlMessage));
1086 msg->cm_magic = CTDLMESSAGE_MAGIC;
1087 msg->cm_anon_type = buffer[1];
1088 msg->cm_format_type = buffer[2];
1090 for (pos = 3; pos < size; ++pos) {
1091 field = buffer[pos];
1092 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1093 pos = pos + strlen(&buffer[(int)pos]);
1096 /* Check for message routing */
1097 if (msg->cm_fields['D'] != NULL) {
1098 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1100 /* route the message */
1101 strcpy(nexthop, "");
1102 if (is_valid_node(nexthop, NULL,
1103 msg->cm_fields['D']) == 0) {
1105 /* prepend our node to the path */
1106 if (msg->cm_fields['P'] != NULL) {
1107 oldpath = msg->cm_fields['P'];
1108 msg->cm_fields['P'] = NULL;
1111 oldpath = strdup("unknown_user");
1113 size = strlen(oldpath) + SIZ;
1114 msg->cm_fields['P'] = malloc(size);
1115 snprintf(msg->cm_fields['P'], size, "%s!%s",
1116 config.c_nodename, oldpath);
1119 /* serialize the message */
1120 serialize_message(&sermsg, msg);
1123 if (strlen(nexthop) == 0) {
1124 strcpy(nexthop, msg->cm_fields['D']);
1126 snprintf(filename, sizeof filename,
1127 "./network/spoolout/%s", nexthop);
1128 fp = fopen(filename, "ab");
1135 CtdlFreeMessage(msg);
1139 else { /* invalid destination node name */
1142 "A message you sent could not be delivered due to an invalid destination node"
1143 " name. Please check the address and try sending the message again.\n");
1152 * Check to see if we already have a copy of this message, and
1153 * abort its processing if so. (We used to post a warning to Aide>
1154 * every time this happened, but the network is now so densely
1155 * connected that it's inevitable.)
1157 if (network_usetable(msg) != 0) {
1161 /* Learn network topology from the path */
1162 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1163 network_learn_topology(msg->cm_fields['N'],
1164 msg->cm_fields['P']);
1167 /* Is the sending node giving us a very persuasive suggestion about
1168 * which room this message should be saved in? If so, go with that.
1170 if (msg->cm_fields['C'] != NULL) {
1171 safestrncpy(target_room,
1172 msg->cm_fields['C'],
1173 sizeof target_room);
1176 /* Otherwise, does it have a recipient? If so, validate it... */
1177 else if (msg->cm_fields['R'] != NULL) {
1178 recp = validate_recipients(msg->cm_fields['R']);
1179 if (recp != NULL) if (recp->num_error > 0) {
1181 "A message you sent could not be delivered due to an invalid address.\n"
1182 "Please check the address and try sending the message again.\n");
1187 strcpy(target_room, ""); /* no target room if mail */
1190 /* Our last shot at finding a home for this message is to see if
1191 * it has the O field (Originating room) set.
1193 else if (msg->cm_fields['O'] != NULL) {
1194 safestrncpy(target_room,
1195 msg->cm_fields['O'],
1196 sizeof target_room);
1199 /* Strip out fields that are only relevant during transit */
1200 if (msg->cm_fields['D'] != NULL) {
1201 free(msg->cm_fields['D']);
1202 msg->cm_fields['D'] = NULL;
1204 if (msg->cm_fields['C'] != NULL) {
1205 free(msg->cm_fields['C']);
1206 msg->cm_fields['C'] = NULL;
1209 /* save the message into a room */
1210 if (PerformNetprocHooks(msg, target_room) == 0) {
1211 msg->cm_flags = CM_SKIP_HOOKS;
1212 CtdlSubmitMsg(msg, recp, target_room);
1214 CtdlFreeMessage(msg);
1220 * Process a single message from a single file from the inbound queue
1222 void network_process_message(FILE *fp, long msgstart, long msgend) {
1227 hold_pos = ftell(fp);
1228 size = msgend - msgstart + 1;
1229 buffer = malloc(size);
1230 if (buffer != NULL) {
1231 fseek(fp, msgstart, SEEK_SET);
1232 fread(buffer, size, 1, fp);
1233 network_process_buffer(buffer, size);
1237 fseek(fp, hold_pos, SEEK_SET);
1242 * Process a single file from the inbound queue
1244 void network_process_file(char *filename) {
1246 long msgstart = (-1L);
1247 long msgend = (-1L);
1252 fp = fopen(filename, "rb");
1254 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1255 filename, strerror(errno));
1259 lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1261 /* Look for messages in the data stream and break them out */
1262 while (ch = getc(fp), ch >= 0) {
1265 if (msgstart >= 0L) {
1266 msgend = msgcur - 1;
1267 network_process_message(fp, msgstart, msgend);
1275 msgend = msgcur - 1;
1276 if (msgstart >= 0L) {
1277 network_process_message(fp, msgstart, msgend);
1286 * Process anything in the inbound queue
1288 void network_do_spoolin(void) {
1293 dp = opendir("./network/spoolin");
1294 if (dp == NULL) return;
1296 while (d = readdir(dp), d != NULL) {
1297 snprintf(filename, sizeof filename,
1298 "./network/spoolin/%s", d->d_name);
1299 network_process_file(filename);
1308 * Delete any files in the outbound queue that were intended
1309 * to be sent to nodes which no longer exist.
1311 void network_purge_spoolout(void) {
1318 dp = opendir("./network/spoolout");
1319 if (dp == NULL) return;
1321 while (d = readdir(dp), d != NULL) {
1322 snprintf(filename, sizeof filename,
1323 "./network/spoolout/%s", d->d_name);
1325 strcpy(nexthop, "");
1326 i = is_valid_node(nexthop, NULL, d->d_name);
1328 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1340 * receive network spool from the remote system
1342 void receive_spool(int sock, char *remote_nodename) {
1344 long bytes_received;
1346 static char pbuf[IGNET_PACKET_SIZE];
1347 char tempfilename[PATH_MAX];
1351 strcpy(tempfilename, tmpnam(NULL));
1352 if (sock_puts(sock, "NDOP") < 0) return;
1353 if (sock_gets(sock, buf) < 0) return;
1354 lprintf(CTDL_DEBUG, "<%s\n", buf);
1355 if (buf[0] != '2') {
1358 download_len = extract_long(&buf[4], 0);
1360 bytes_received = 0L;
1361 fp = fopen(tempfilename, "w");
1363 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1368 while (bytes_received < download_len) {
1369 snprintf(buf, sizeof buf, "READ %ld|%ld",
1371 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1372 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1373 if (sock_puts(sock, buf) < 0) {
1375 unlink(tempfilename);
1378 if (sock_gets(sock, buf) < 0) {
1380 unlink(tempfilename);
1383 if (buf[0] == '6') {
1384 plen = extract_long(&buf[4], 0);
1385 if (sock_read(sock, pbuf, plen) < 0) {
1387 unlink(tempfilename);
1390 fwrite((char *) pbuf, plen, 1, fp);
1391 bytes_received = bytes_received + plen;
1396 if (sock_puts(sock, "CLOS") < 0) {
1397 unlink(tempfilename);
1400 if (sock_gets(sock, buf) < 0) {
1401 unlink(tempfilename);
1404 lprintf(CTDL_DEBUG, "%s\n", buf);
1405 snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1406 tempfilename, remote_nodename, (long) getpid());
1413 * transmit network spool to the remote system
1415 void transmit_spool(int sock, char *remote_nodename)
1420 long bytes_to_write, thisblock;
1424 if (sock_puts(sock, "NUOP") < 0) return;
1425 if (sock_gets(sock, buf) < 0) return;
1426 lprintf(CTDL_DEBUG, "<%s\n", buf);
1427 if (buf[0] != '2') {
1431 snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1432 fd = open(sfname, O_RDONLY);
1434 if (errno == ENOENT) {
1435 lprintf(CTDL_INFO, "Nothing to send.\n");
1437 lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1442 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1443 bytes_to_write = plen;
1444 while (bytes_to_write > 0L) {
1445 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1446 if (sock_puts(sock, buf) < 0) {
1450 if (sock_gets(sock, buf) < 0) {
1454 thisblock = atol(&buf[4]);
1455 if (buf[0] == '7') {
1456 if (sock_write(sock, pbuf,
1457 (int) thisblock) < 0) {
1461 bytes_to_write = bytes_to_write - thisblock;
1470 if (sock_puts(sock, "UCLS 1") < 0) return;
1471 if (sock_gets(sock, buf) < 0) return;
1472 lprintf(CTDL_DEBUG, "<%s\n", buf);
1473 if (buf[0] == '2') {
1481 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1483 void network_poll_node(char *node, char *secret, char *host, char *port) {
1487 if (network_talking_to(node, NTT_CHECK)) return;
1488 network_talking_to(node, NTT_ADD);
1489 lprintf(CTDL_INFO, "Polling node <%s> at %s:%s\n", node, host, port);
1491 sock = sock_connect(host, port, "tcp");
1493 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1494 network_talking_to(node, NTT_REMOVE);
1498 lprintf(CTDL_DEBUG, "Connected!\n");
1500 /* Read the server greeting */
1501 if (sock_gets(sock, buf) < 0) goto bail;
1502 lprintf(CTDL_DEBUG, ">%s\n", buf);
1504 /* Identify ourselves */
1505 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1506 lprintf(CTDL_DEBUG, "<%s\n", buf);
1507 if (sock_puts(sock, buf) <0) goto bail;
1508 if (sock_gets(sock, buf) < 0) goto bail;
1509 lprintf(CTDL_DEBUG, ">%s\n", buf);
1510 if (buf[0] != '2') goto bail;
1512 /* At this point we are authenticated. */
1513 receive_spool(sock, node);
1514 transmit_spool(sock, node);
1516 sock_puts(sock, "QUIT");
1517 bail: sock_close(sock);
1518 network_talking_to(node, NTT_REMOVE);
1524 * Poll other Citadel nodes and transfer inbound/outbound network data.
1525 * Set "full" to nonzero to force a poll of every node, or to zero to poll
1526 * only nodes to which we have data to send.
1528 void network_poll_other_citadel_nodes(int full_poll) {
1536 char spoolfile[SIZ];
1538 if (ignetcfg == NULL) return; /* no nodes defined */
1540 /* Use the string tokenizer to grab one line at a time */
1541 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
1542 extract_token(linebuf, ignetcfg, i, '\n');
1543 extract(node, linebuf, 0);
1544 extract(secret, linebuf, 1);
1545 extract(host, linebuf, 2);
1546 extract(port, linebuf, 3);
1547 if ( (strlen(node) > 0) && (strlen(secret) > 0)
1548 && (strlen(host) > 0) && strlen(port) > 0) {
1551 sprintf(spoolfile, "./network/spoolout/%s",
1553 if (access(spoolfile, R_OK) == 0) {
1558 network_poll_node(node, secret, host, port);
1572 * network_do_queue()
1574 * Run through the rooms doing various types of network stuff.
1576 void network_do_queue(void) {
1577 static time_t last_run = 0L;
1578 struct RoomProcList *ptr;
1579 int full_processing = 1;
1582 * Run the full set of processing tasks no more frequently
1583 * than once every n seconds
1585 if ( (time(NULL) - last_run) < config.c_net_freq ) {
1586 full_processing = 0;
1590 * This is a simple concurrency check to make sure only one queue run
1591 * is done at a time. We could do this with a mutex, but since we
1592 * don't really require extremely fine granularity here, we'll do it
1593 * with a static variable instead.
1595 if (doing_queue) return;
1598 /* Load the IGnet Configuration into memory */
1599 if (ignetcfg == NULL) {
1600 ignetcfg = CtdlGetSysConfig(IGNETCFG);
1604 * Poll other Citadel nodes. Maybe. If "full_processing" is set
1605 * then we poll everyone. Otherwise we only poll nodes we have stuff
1608 network_poll_other_citadel_nodes(full_processing);
1611 * Load the network map and filter list into memory.
1614 filterlist = load_filter_list();
1617 * Go ahead and run the queue
1619 if (full_processing) {
1620 lprintf(CTDL_INFO, "network: loading outbound queue\n");
1621 ForEachRoom(network_queue_room, NULL);
1623 lprintf(CTDL_INFO, "network: running outbound queue\n");
1624 while (rplist != NULL) {
1625 network_spoolout_room(rplist->name);
1627 rplist = rplist->next;
1632 lprintf(CTDL_INFO, "network: processing inbound queue\n");
1633 network_do_spoolin();
1635 /* Save the network map back to disk */
1636 write_network_map();
1638 /* Free the filter list in memory */
1639 free_filter_list(filterlist);
1642 network_purge_spoolout();
1644 lprintf(CTDL_INFO, "network: queue run completed\n");
1646 if (full_processing) {
1647 last_run = time(NULL);
1655 * cmd_netp() - authenticate to the server as another Citadel node polling
1656 * for network traffic
1658 void cmd_netp(char *cmdbuf)
1667 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
1671 extract(node, cmdbuf, 0);
1672 extract(pass, cmdbuf, 1);
1674 if (is_valid_node(nexthop, secret, node) != 0) {
1675 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1679 if (strcasecmp(pass, secret)) {
1680 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1684 if (network_talking_to(node, NTT_CHECK)) {
1685 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1689 safestrncpy(CC->net_node, node, sizeof CC->net_node);
1690 network_talking_to(node, NTT_ADD);
1691 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1697 * This handler detects changes being made to the system's IGnet
1700 int netconfig_aftersave(struct CtdlMessage *msg) {
1704 /* If this isn't the configuration room, or if this isn't a MIME
1705 * message, don't bother.
1707 if (strcasecmp(msg->cm_fields['O'], SYSCONFIGROOM)) return(0);
1708 if (msg->cm_format_type != 4) return(0);
1710 ptr = msg->cm_fields['M'];
1711 while (ptr != NULL) {
1713 linelen = strcspn(ptr, "\n");
1714 if (linelen == 0) return(0); /* end of headers */
1716 if (!strncasecmp(ptr, "Content-type: ", 14)) {
1717 if (!strncasecmp(&ptr[14], IGNETCFG,
1718 strlen(IGNETCFG))) {
1719 if (ignetcfg != NULL) free(ignetcfg);
1724 ptr = strchr((char *)ptr, '\n');
1725 if (ptr != NULL) ++ptr;
1735 * Module entry point
1737 char *serv_network_init(void)
1739 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1740 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1741 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1742 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1743 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1744 CtdlRegisterMessageHook(netconfig_aftersave, EVT_AFTERSAVE);