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;
90 char *working_ignetcfg = NULL;
93 * Keep track of what messages to reject
95 struct FilterList *load_filter_list(void) {
96 char *serialized_list = NULL;
99 struct FilterList *newlist = NULL;
100 struct FilterList *nptr;
102 serialized_list = CtdlGetSysConfig(FILTERLIST);
103 if (serialized_list == NULL) return(NULL); /* if null, no entries */
105 /* Use the string tokenizer to grab one line at a time */
106 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
107 extract_token(buf, serialized_list, i, '\n');
108 nptr = (struct FilterList *) malloc(sizeof(struct FilterList));
109 extract(nptr->fl_user, buf, 0);
110 striplt(nptr->fl_user);
111 extract(nptr->fl_room, buf, 1);
112 striplt(nptr->fl_room);
113 extract(nptr->fl_node, buf, 2);
114 striplt(nptr->fl_node);
116 /* Cowardly refuse to add an any/any/any entry that would
117 * end up filtering every single message.
119 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
120 + strlen(nptr->fl_node) == 0) {
124 nptr->next = newlist;
129 free(serialized_list);
134 void free_filter_list(struct FilterList *fl) {
135 if (fl == NULL) return;
136 free_filter_list(fl->next);
143 * Check the use table. This is a list of messages which have recently
144 * arrived on the system. It is maintained and queried to prevent the same
145 * message from being entered into the database multiple times if it happens
146 * to arrive multiple times by accident.
148 int network_usetable(struct CtdlMessage *msg) {
151 struct cdbdata *cdbut;
154 /* Bail out if we can't generate a message ID */
158 if (msg->cm_fields['I'] == NULL) {
161 if (strlen(msg->cm_fields['I']) == 0) {
165 /* Generate the message ID */
166 strcpy(msgid, msg->cm_fields['I']);
167 if (haschar(msgid, '@') == 0) {
169 if (msg->cm_fields['N'] != NULL) {
170 strcat(msgid, msg->cm_fields['N']);
177 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
183 /* If we got to this point, it's unique: add it. */
184 strcpy(ut.ut_msgid, msgid);
185 ut.ut_timestamp = time(NULL);
186 cdb_store(CDB_USETABLE, msgid, strlen(msgid),
187 &ut, sizeof(struct UseTable) );
193 * Read the network map from its configuration file into memory.
195 void read_network_map(void) {
196 char *serialized_map = NULL;
199 struct NetMap *nmptr;
201 serialized_map = CtdlGetSysConfig(IGNETMAP);
202 if (serialized_map == NULL) return; /* if null, no entries */
204 /* Use the string tokenizer to grab one line at a time */
205 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
206 extract_token(buf, serialized_map, i, '\n');
207 nmptr = (struct NetMap *) malloc(sizeof(struct NetMap));
208 extract(nmptr->nodename, buf, 0);
209 nmptr->lastcontact = extract_long(buf, 1);
210 extract(nmptr->nexthop, buf, 2);
211 nmptr->next = the_netmap;
215 free(serialized_map);
220 * Write the network map from memory back to the configuration file.
222 void write_network_map(void) {
223 char *serialized_map = NULL;
224 struct NetMap *nmptr;
226 serialized_map = strdup("");
228 if (the_netmap != NULL) {
229 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
230 serialized_map = realloc(serialized_map,
231 (strlen(serialized_map)+SIZ) );
232 if (strlen(nmptr->nodename) > 0) {
233 snprintf(&serialized_map[strlen(serialized_map)],
237 (long)nmptr->lastcontact,
243 CtdlPutSysConfig(IGNETMAP, serialized_map);
244 free(serialized_map);
246 /* Now free the list */
247 while (the_netmap != NULL) {
248 nmptr = the_netmap->next;
257 * Check the network map and determine whether the supplied node name is
258 * valid. If it is not a neighbor node, supply the name of a neighbor node
259 * which is the next hop. If it *is* a neighbor node, we also fill in the
262 int is_valid_node(char *nexthop, char *secret, char *node) {
267 struct NetMap *nmptr;
274 * First try the neighbor nodes
276 if (working_ignetcfg == NULL) {
277 if (nexthop != NULL) {
284 if (nexthop != NULL) {
288 /* Use the string tokenizer to grab one line at a time */
289 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
290 extract_token(linebuf, working_ignetcfg, i, '\n');
291 extract(buf, linebuf, 0);
292 if (!strcasecmp(buf, node)) {
293 if (nexthop != NULL) {
296 if (secret != NULL) {
297 extract(secret, linebuf, 1);
304 return(retval); /* yup, it's a direct neighbor */
308 * If we get to this point we have to see if we know the next hop
310 if (the_netmap != NULL) {
311 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
312 if (!strcasecmp(nmptr->nodename, node)) {
313 if (nexthop != NULL) {
314 strcpy(nexthop, nmptr->nexthop);
322 * If we get to this point, the supplied node name is bogus.
324 lprintf(CTDL_ERR, "Invalid node name <%s>\n", node);
332 void cmd_gnet(char *argbuf) {
337 if (CtdlAccessCheck(ac_room_aide)) return;
338 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
339 cprintf("%d Network settings for room #%ld <%s>\n",
341 CC->room.QRnumber, CC->room.QRname);
343 fp = fopen(filename, "r");
345 while (fgets(buf, sizeof buf, fp) != NULL) {
346 buf[strlen(buf)-1] = 0;
347 cprintf("%s\n", buf);
356 void cmd_snet(char *argbuf) {
357 char tempfilename[SIZ];
362 if (CtdlAccessCheck(ac_room_aide)) return;
363 safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
364 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
366 fp = fopen(tempfilename, "w");
368 cprintf("%d Cannot open %s: %s\n",
369 ERROR + INTERNAL_ERROR,
374 cprintf("%d %s\n", SEND_LISTING, tempfilename);
375 while (client_gets(buf), strcmp(buf, "000")) {
376 fprintf(fp, "%s\n", buf);
380 /* Now copy the temp file to its permanent location
381 * (We use /bin/mv instead of link() because they may be on
382 * different filesystems)
385 snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
386 begin_critical_section(S_NETCONFIGS);
388 end_critical_section(S_NETCONFIGS);
393 * Spools out one message from the list.
395 void network_spool_msg(long msgnum, void *userdata) {
396 struct SpoolControl *sc;
399 char *newpath = NULL;
401 size_t instr_len = SIZ;
402 struct CtdlMessage *msg = NULL;
403 struct CtdlMessage *imsg;
404 struct namelist *nptr;
405 struct ser_ret sermsg;
411 int delete_after_send = 0; /* Set to 1 to delete after spooling */
413 sc = (struct SpoolControl *)userdata;
416 * Process mailing list recipients
418 if (sc->listrecps != NULL) {
420 /* First, copy it to the spoolout room */
421 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
422 if (err != 0) return;
425 * Figure out how big a buffer we need to allocate
427 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
428 instr_len = instr_len + strlen(nptr->name);
434 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
435 instr = malloc(instr_len);
437 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
441 snprintf(instr, instr_len,
442 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
443 "bounceto|postmaster@%s\n" ,
444 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
446 /* Generate delivery instructions for each recipient */
447 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
448 size_t tmp = strlen(instr);
449 snprintf(&instr[tmp], instr_len - tmp,
450 "remote|%s|0||\n", nptr->name);
454 * Generate a message from the instructions
456 imsg = malloc(sizeof(struct CtdlMessage));
457 memset(imsg, 0, sizeof(struct CtdlMessage));
458 imsg->cm_magic = CTDLMESSAGE_MAGIC;
459 imsg->cm_anon_type = MES_NORMAL;
460 imsg->cm_format_type = FMT_RFC822;
461 imsg->cm_fields['A'] = strdup("Citadel");
462 imsg->cm_fields['M'] = instr;
464 /* Save delivery instructions in spoolout room */
465 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
466 CtdlFreeMessage(imsg);
470 * Process digest recipients
472 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
473 fprintf(sc->digestfp, " -----------------------------------"
474 "------------------------------------"
476 CtdlRedirectOutput(sc->digestfp, -1);
477 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
478 CtdlRedirectOutput(NULL, -1);
479 sc->num_msgs_spooled += 1;
483 * Process IGnet push shares
485 if (sc->ignet_push_shares != NULL) {
487 msg = CtdlFetchMessage(msgnum, 1);
491 /* Prepend our node name to the Path field whenever
492 * sending a message to another IGnet node
494 if (msg->cm_fields['P'] == NULL) {
495 msg->cm_fields['P'] = strdup("username");
497 newpath_len = strlen(msg->cm_fields['P']) +
498 strlen(config.c_nodename) + 2;
499 newpath = malloc(newpath_len);
500 snprintf(newpath, newpath_len, "%s!%s",
501 config.c_nodename, msg->cm_fields['P']);
502 free(msg->cm_fields['P']);
503 msg->cm_fields['P'] = newpath;
506 * Force the message to appear in the correct room
507 * on the far end by setting the C field correctly
509 if (msg->cm_fields['C'] != NULL) {
510 free(msg->cm_fields['C']);
512 msg->cm_fields['C'] = strdup(CC->room.QRname);
515 * Determine if this message is set to be deleted
516 * after sending out on the network
518 if (msg->cm_fields['S'] != NULL) {
519 if (!strcasecmp(msg->cm_fields['S'],
521 delete_after_send = 1;
526 * Now serialize it for transmission
528 serialize_message(&sermsg, msg);
530 /* Now send it to every node */
531 for (nptr = sc->ignet_push_shares; nptr != NULL;
536 /* Check for valid node name */
537 if (is_valid_node(NULL, NULL, nptr->name) != 0) {
538 lprintf(CTDL_ERR, "Invalid node <%s>\n",
543 /* Check for split horizon */
544 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
545 bang = num_tokens(msg->cm_fields['P'], '!');
546 if (bang > 1) for (i=0; i<(bang-1); ++i) {
547 extract_token(buf, msg->cm_fields['P'],
549 if (!strcasecmp(buf, nptr->name)) {
554 /* Send the message */
556 snprintf(filename, sizeof filename,
557 "./network/spoolout/%s",
559 fp = fopen(filename, "ab");
568 CtdlFreeMessage(msg);
572 /* update lastsent */
573 sc->lastsent = msgnum;
575 /* Delete this message if delete-after-send is set */
576 if (delete_after_send) {
577 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
584 * Deliver digest messages
586 void network_deliver_digest(struct SpoolControl *sc) {
589 struct CtdlMessage *msg;
593 size_t instr_len = SIZ;
594 struct CtdlMessage *imsg;
595 struct namelist *nptr;
597 if (sc->num_msgs_spooled < 1) {
598 fclose(sc->digestfp);
603 msg = malloc(sizeof(struct CtdlMessage));
604 memset(msg, 0, sizeof(struct CtdlMessage));
605 msg->cm_magic = CTDLMESSAGE_MAGIC;
606 msg->cm_format_type = FMT_RFC822;
607 msg->cm_anon_type = MES_NORMAL;
609 sprintf(buf, "%ld", time(NULL));
610 msg->cm_fields['T'] = strdup(buf);
611 msg->cm_fields['A'] = strdup(CC->room.QRname);
612 msg->cm_fields['U'] = strdup(CC->room.QRname);
613 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
614 for (i=0; i<strlen(buf); ++i) {
615 if (isspace(buf[i])) buf[i]='_';
616 buf[i] = tolower(buf[i]);
618 msg->cm_fields['F'] = strdup(buf);
620 fseek(sc->digestfp, 0L, SEEK_END);
621 msglen = ftell(sc->digestfp);
623 msg->cm_fields['M'] = malloc(msglen + 1);
624 fseek(sc->digestfp, 0L, SEEK_SET);
625 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
626 msg->cm_fields['M'][msglen] = 0;
628 fclose(sc->digestfp);
631 msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
632 CtdlFreeMessage(msg);
634 /* Now generate the delivery instructions */
637 * Figure out how big a buffer we need to allocate
639 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
640 instr_len = instr_len + strlen(nptr->name);
646 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
647 instr = malloc(instr_len);
649 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
653 snprintf(instr, instr_len,
654 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
655 "bounceto|postmaster@%s\n" ,
656 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
658 /* Generate delivery instructions for each recipient */
659 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
660 size_t tmp = strlen(instr);
661 snprintf(&instr[tmp], instr_len - tmp,
662 "remote|%s|0||\n", nptr->name);
666 * Generate a message from the instructions
668 imsg = malloc(sizeof(struct CtdlMessage));
669 memset(imsg, 0, sizeof(struct CtdlMessage));
670 imsg->cm_magic = CTDLMESSAGE_MAGIC;
671 imsg->cm_anon_type = MES_NORMAL;
672 imsg->cm_format_type = FMT_RFC822;
673 imsg->cm_fields['A'] = strdup("Citadel");
674 imsg->cm_fields['M'] = instr;
676 /* Save delivery instructions in spoolout room */
677 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
678 CtdlFreeMessage(imsg);
683 * Batch up and send all outbound traffic from the current room
685 void network_spoolout_room(char *room_to_spool) {
690 struct SpoolControl sc;
691 struct namelist *nptr = NULL;
694 int skipthisline = 0;
697 if (getroom(&CC->room, room_to_spool) != 0) {
698 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
702 memset(&sc, 0, sizeof(struct SpoolControl));
703 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
705 begin_critical_section(S_NETCONFIGS);
707 fp = fopen(filename, "r");
709 end_critical_section(S_NETCONFIGS);
713 lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
715 while (fgets(buf, sizeof buf, fp) != NULL) {
716 buf[strlen(buf)-1] = 0;
718 extract(instr, buf, 0);
719 if (!strcasecmp(instr, "lastsent")) {
720 sc.lastsent = extract_long(buf, 1);
722 else if (!strcasecmp(instr, "listrecp")) {
723 nptr = (struct namelist *)
724 malloc(sizeof(struct namelist));
725 nptr->next = sc.listrecps;
726 extract(nptr->name, buf, 1);
729 else if (!strcasecmp(instr, "digestrecp")) {
730 nptr = (struct namelist *)
731 malloc(sizeof(struct namelist));
732 nptr->next = sc.digestrecps;
733 extract(nptr->name, buf, 1);
734 sc.digestrecps = nptr;
736 else if (!strcasecmp(instr, "ignet_push_share")) {
737 /* by checking each node's validity, we automatically
738 * purge nodes which do not exist from room network
739 * configurations at this time.
741 nptr = (struct namelist *)
742 malloc(sizeof(struct namelist));
743 nptr->next = sc.ignet_push_shares;
744 extract(nptr->name, buf, 1);
745 if (is_valid_node(NULL, NULL, nptr->name) == 0) {
746 sc.ignet_push_shares = nptr;
753 /* Preserve 'other' lines ... *unless* they happen to
754 * be subscribe/unsubscribe pendings with expired
758 if (!strncasecmp(buf, "subpending|", 11)) {
759 if (time(NULL) - extract_long(buf, 4) > EXP) {
763 if (!strncasecmp(buf, "unsubpending|", 13)) {
764 if (time(NULL) - extract_long(buf, 3) > EXP) {
769 if (skipthisline == 0) {
770 linesize = strlen(buf);
771 sc.misc = realloc(sc.misc,
772 (miscsize + linesize + 2) );
773 sprintf(&sc.misc[miscsize], "%s\n", buf);
774 miscsize = miscsize + linesize + 1;
782 /* If there are digest recipients, we have to build a digest */
783 if (sc.digestrecps != NULL) {
784 sc.digestfp = tmpfile();
785 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
788 /* Do something useful */
789 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
790 network_spool_msg, &sc);
792 /* If we wrote a digest, deliver it and then close it */
793 snprintf(buf, sizeof buf, "room_%s@%s",
794 CC->room.QRname, config.c_fqdn);
795 for (i=0; i<strlen(buf); ++i) {
796 buf[i] = tolower(buf[i]);
797 if (isspace(buf[i])) buf[i] = '_';
799 if (sc.digestfp != NULL) {
800 fprintf(sc.digestfp, " -----------------------------------"
801 "------------------------------------"
803 "You are subscribed to the '%s' "
805 "To post to the list: %s\n",
808 network_deliver_digest(&sc); /* deliver and close */
811 /* Now rewrite the config file */
812 fp = fopen(filename, "w");
814 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
815 filename, strerror(errno));
818 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
820 /* Write out the listrecps while freeing from memory at the
821 * same time. Am I clever or what? :)
823 while (sc.listrecps != NULL) {
824 fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
825 nptr = sc.listrecps->next;
829 /* Do the same for digestrecps */
830 while (sc.digestrecps != NULL) {
831 fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
832 nptr = sc.digestrecps->next;
833 free(sc.digestrecps);
834 sc.digestrecps = nptr;
836 while (sc.ignet_push_shares != NULL) {
837 /* by checking each node's validity, we automatically
838 * purge nodes which do not exist from room network
839 * configurations at this time.
841 if (is_valid_node(NULL, NULL, sc.ignet_push_shares->name) == 0) {
843 fprintf(fp, "ignet_push_share|%s\n",
844 sc.ignet_push_shares->name);
845 nptr = sc.ignet_push_shares->next;
846 free(sc.ignet_push_shares);
847 sc.ignet_push_shares = nptr;
849 if (sc.misc != NULL) {
850 fwrite(sc.misc, strlen(sc.misc), 1, fp);
856 end_critical_section(S_NETCONFIGS);
862 * Send the *entire* contents of the current room to one specific network node,
863 * ignoring anything we know about which messages have already undergone
864 * network processing. This can be used to bring a new node into sync.
866 int network_sync_to(char *target_node) {
867 struct SpoolControl sc;
870 /* Concise syntax because we don't need a full linked-list */
871 memset(&sc, 0, sizeof(struct SpoolControl));
872 sc.ignet_push_shares = (struct namelist *)
873 malloc(sizeof(struct namelist));
874 sc.ignet_push_shares->next = NULL;
875 safestrncpy(sc.ignet_push_shares->name,
877 sizeof sc.ignet_push_shares->name);
879 /* Send ALL messages */
880 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
881 network_spool_msg, &sc);
883 /* Concise cleanup because we know there's only one node in the sc */
884 free(sc.ignet_push_shares);
886 lprintf(CTDL_INFO, "Synchronized %d messages to <%s>\n",
887 num_spooled, target_node);
893 * Implements the NSYN command
895 void cmd_nsyn(char *argbuf) {
897 char target_node[SIZ];
899 if (CtdlAccessCheck(ac_aide)) return;
901 extract(target_node, argbuf, 0);
902 num_spooled = network_sync_to(target_node);
903 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
909 * Batch up and send all outbound traffic from the current room
911 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
912 struct RoomProcList *ptr;
914 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
915 if (ptr == NULL) return;
917 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
924 * Learn topology from path fields
926 void network_learn_topology(char *node, char *path) {
928 struct NetMap *nmptr;
932 if (num_tokens(path, '!') < 3) return;
933 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
934 if (!strcasecmp(nmptr->nodename, node)) {
935 extract_token(nmptr->nexthop, path, 0, '!');
936 nmptr->lastcontact = time(NULL);
941 /* If we got here then it's not in the map, so add it. */
942 nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
943 strcpy(nmptr->nodename, node);
944 nmptr->lastcontact = time(NULL);
945 extract_token(nmptr->nexthop, path, 0, '!');
946 nmptr->next = the_netmap;
954 * Bounce a message back to the sender
956 void network_bounce(struct CtdlMessage *msg, char *reason) {
957 char *oldpath = NULL;
959 char bouncesource[SIZ];
961 struct recptypes *valid = NULL;
962 char force_room[ROOMNAMELEN];
963 static int serialnum = 0;
966 lprintf(CTDL_DEBUG, "entering network_bounce()\n");
968 if (msg == NULL) return;
970 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
973 * Give it a fresh message ID
975 if (msg->cm_fields['I'] != NULL) {
976 free(msg->cm_fields['I']);
978 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
979 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
980 msg->cm_fields['I'] = strdup(buf);
983 * FIXME ... right now we're just sending a bounce; we really want to
984 * include the text of the bounced message.
986 if (msg->cm_fields['M'] != NULL) {
987 free(msg->cm_fields['M']);
989 msg->cm_fields['M'] = strdup(reason);
990 msg->cm_format_type = 0;
993 * Turn the message around
995 if (msg->cm_fields['R'] == NULL) {
996 free(msg->cm_fields['R']);
999 if (msg->cm_fields['D'] == NULL) {
1000 free(msg->cm_fields['D']);
1003 snprintf(recipient, sizeof recipient, "%s@%s",
1004 msg->cm_fields['A'], msg->cm_fields['N']);
1006 if (msg->cm_fields['A'] == NULL) {
1007 free(msg->cm_fields['A']);
1010 if (msg->cm_fields['N'] == NULL) {
1011 free(msg->cm_fields['N']);
1014 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1015 msg->cm_fields['N'] = strdup(config.c_nodename);
1018 /* prepend our node to the path */
1019 if (msg->cm_fields['P'] != NULL) {
1020 oldpath = msg->cm_fields['P'];
1021 msg->cm_fields['P'] = NULL;
1024 oldpath = strdup("unknown_user");
1026 size = strlen(oldpath) + SIZ;
1027 msg->cm_fields['P'] = malloc(size);
1028 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1031 /* Now submit the message */
1032 valid = validate_recipients(recipient);
1033 if (valid != NULL) if (valid->num_error > 0) {
1037 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1038 strcpy(force_room, config.c_aideroom);
1041 strcpy(force_room, "");
1043 if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1044 strcpy(force_room, config.c_aideroom);
1046 CtdlSubmitMsg(msg, valid, force_room);
1049 if (valid != NULL) free(valid);
1050 CtdlFreeMessage(msg);
1051 lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1058 * Process a buffer containing a single message from a single file
1059 * from the inbound queue
1061 void network_process_buffer(char *buffer, long size) {
1062 struct CtdlMessage *msg;
1065 struct recptypes *recp = NULL;
1066 char target_room[ROOMNAMELEN];
1067 struct ser_ret sermsg;
1068 char *oldpath = NULL;
1072 unsigned char firstbyte;
1073 unsigned char lastbyte;
1075 /* Validate just a little bit. First byte should be FF and
1076 * last byte should be 00.
1078 memcpy(&firstbyte, &buffer[0], 1);
1079 memcpy(&lastbyte, &buffer[size-1], 1);
1080 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1081 lprintf(CTDL_ERR, "Corrupt message! Ignoring.\n");
1085 /* Set default target room to trash */
1086 strcpy(target_room, TWITROOM);
1088 /* Load the message into memory */
1089 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1090 memset(msg, 0, sizeof(struct CtdlMessage));
1091 msg->cm_magic = CTDLMESSAGE_MAGIC;
1092 msg->cm_anon_type = buffer[1];
1093 msg->cm_format_type = buffer[2];
1095 for (pos = 3; pos < size; ++pos) {
1096 field = buffer[pos];
1097 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1098 pos = pos + strlen(&buffer[(int)pos]);
1101 /* Check for message routing */
1102 if (msg->cm_fields['D'] != NULL) {
1103 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1105 /* route the message */
1106 strcpy(nexthop, "");
1107 if (is_valid_node(nexthop, NULL,
1108 msg->cm_fields['D']) == 0) {
1110 /* prepend our node to the path */
1111 if (msg->cm_fields['P'] != NULL) {
1112 oldpath = msg->cm_fields['P'];
1113 msg->cm_fields['P'] = NULL;
1116 oldpath = strdup("unknown_user");
1118 size = strlen(oldpath) + SIZ;
1119 msg->cm_fields['P'] = malloc(size);
1120 snprintf(msg->cm_fields['P'], size, "%s!%s",
1121 config.c_nodename, oldpath);
1124 /* serialize the message */
1125 serialize_message(&sermsg, msg);
1128 if (strlen(nexthop) == 0) {
1129 strcpy(nexthop, msg->cm_fields['D']);
1131 snprintf(filename, sizeof filename,
1132 "./network/spoolout/%s", nexthop);
1133 fp = fopen(filename, "ab");
1140 CtdlFreeMessage(msg);
1144 else { /* invalid destination node name */
1147 "A message you sent could not be delivered due to an invalid destination node"
1148 " name. Please check the address and try sending the message again.\n");
1157 * Check to see if we already have a copy of this message, and
1158 * abort its processing if so. (We used to post a warning to Aide>
1159 * every time this happened, but the network is now so densely
1160 * connected that it's inevitable.)
1162 if (network_usetable(msg) != 0) {
1166 /* Learn network topology from the path */
1167 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1168 network_learn_topology(msg->cm_fields['N'],
1169 msg->cm_fields['P']);
1172 /* Is the sending node giving us a very persuasive suggestion about
1173 * which room this message should be saved in? If so, go with that.
1175 if (msg->cm_fields['C'] != NULL) {
1176 safestrncpy(target_room,
1177 msg->cm_fields['C'],
1178 sizeof target_room);
1181 /* Otherwise, does it have a recipient? If so, validate it... */
1182 else if (msg->cm_fields['R'] != NULL) {
1183 recp = validate_recipients(msg->cm_fields['R']);
1184 if (recp != NULL) if (recp->num_error > 0) {
1186 "A message you sent could not be delivered due to an invalid address.\n"
1187 "Please check the address and try sending the message again.\n");
1192 strcpy(target_room, ""); /* no target room if mail */
1195 /* Our last shot at finding a home for this message is to see if
1196 * it has the O field (Originating room) set.
1198 else if (msg->cm_fields['O'] != NULL) {
1199 safestrncpy(target_room,
1200 msg->cm_fields['O'],
1201 sizeof target_room);
1204 /* Strip out fields that are only relevant during transit */
1205 if (msg->cm_fields['D'] != NULL) {
1206 free(msg->cm_fields['D']);
1207 msg->cm_fields['D'] = NULL;
1209 if (msg->cm_fields['C'] != NULL) {
1210 free(msg->cm_fields['C']);
1211 msg->cm_fields['C'] = NULL;
1214 /* save the message into a room */
1215 if (PerformNetprocHooks(msg, target_room) == 0) {
1216 msg->cm_flags = CM_SKIP_HOOKS;
1217 CtdlSubmitMsg(msg, recp, target_room);
1219 CtdlFreeMessage(msg);
1225 * Process a single message from a single file from the inbound queue
1227 void network_process_message(FILE *fp, long msgstart, long msgend) {
1232 hold_pos = ftell(fp);
1233 size = msgend - msgstart + 1;
1234 buffer = malloc(size);
1235 if (buffer != NULL) {
1236 fseek(fp, msgstart, SEEK_SET);
1237 fread(buffer, size, 1, fp);
1238 network_process_buffer(buffer, size);
1242 fseek(fp, hold_pos, SEEK_SET);
1247 * Process a single file from the inbound queue
1249 void network_process_file(char *filename) {
1251 long msgstart = (-1L);
1252 long msgend = (-1L);
1257 fp = fopen(filename, "rb");
1259 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1260 filename, strerror(errno));
1264 lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1266 /* Look for messages in the data stream and break them out */
1267 while (ch = getc(fp), ch >= 0) {
1270 if (msgstart >= 0L) {
1271 msgend = msgcur - 1;
1272 network_process_message(fp, msgstart, msgend);
1280 msgend = msgcur - 1;
1281 if (msgstart >= 0L) {
1282 network_process_message(fp, msgstart, msgend);
1291 * Process anything in the inbound queue
1293 void network_do_spoolin(void) {
1298 dp = opendir("./network/spoolin");
1299 if (dp == NULL) return;
1301 while (d = readdir(dp), d != NULL) {
1302 snprintf(filename, sizeof filename,
1303 "./network/spoolin/%s", d->d_name);
1304 network_process_file(filename);
1313 * Delete any files in the outbound queue that were intended
1314 * to be sent to nodes which no longer exist.
1316 void network_purge_spoolout(void) {
1323 dp = opendir("./network/spoolout");
1324 if (dp == NULL) return;
1326 while (d = readdir(dp), d != NULL) {
1327 snprintf(filename, sizeof filename,
1328 "./network/spoolout/%s", d->d_name);
1330 strcpy(nexthop, "");
1331 i = is_valid_node(nexthop, NULL, d->d_name);
1333 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1345 * receive network spool from the remote system
1347 void receive_spool(int sock, char *remote_nodename) {
1349 long bytes_received;
1351 static char pbuf[IGNET_PACKET_SIZE];
1352 char tempfilename[PATH_MAX];
1356 strcpy(tempfilename, tmpnam(NULL));
1357 if (sock_puts(sock, "NDOP") < 0) return;
1358 if (sock_gets(sock, buf) < 0) return;
1359 lprintf(CTDL_DEBUG, "<%s\n", buf);
1360 if (buf[0] != '2') {
1363 download_len = extract_long(&buf[4], 0);
1365 bytes_received = 0L;
1366 fp = fopen(tempfilename, "w");
1368 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1373 while (bytes_received < download_len) {
1374 snprintf(buf, sizeof buf, "READ %ld|%ld",
1376 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1377 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1378 if (sock_puts(sock, buf) < 0) {
1380 unlink(tempfilename);
1383 if (sock_gets(sock, buf) < 0) {
1385 unlink(tempfilename);
1388 if (buf[0] == '6') {
1389 plen = extract_long(&buf[4], 0);
1390 if (sock_read(sock, pbuf, plen) < 0) {
1392 unlink(tempfilename);
1395 fwrite((char *) pbuf, plen, 1, fp);
1396 bytes_received = bytes_received + plen;
1401 if (sock_puts(sock, "CLOS") < 0) {
1402 unlink(tempfilename);
1405 if (sock_gets(sock, buf) < 0) {
1406 unlink(tempfilename);
1409 lprintf(CTDL_DEBUG, "%s\n", buf);
1410 snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1411 tempfilename, remote_nodename, (long) getpid());
1418 * transmit network spool to the remote system
1420 void transmit_spool(int sock, char *remote_nodename)
1425 long bytes_to_write, thisblock;
1429 if (sock_puts(sock, "NUOP") < 0) return;
1430 if (sock_gets(sock, buf) < 0) return;
1431 lprintf(CTDL_DEBUG, "<%s\n", buf);
1432 if (buf[0] != '2') {
1436 snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1437 fd = open(sfname, O_RDONLY);
1439 if (errno == ENOENT) {
1440 lprintf(CTDL_INFO, "Nothing to send.\n");
1442 lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1447 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1448 bytes_to_write = plen;
1449 while (bytes_to_write > 0L) {
1450 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1451 if (sock_puts(sock, buf) < 0) {
1455 if (sock_gets(sock, buf) < 0) {
1459 thisblock = atol(&buf[4]);
1460 if (buf[0] == '7') {
1461 if (sock_write(sock, pbuf,
1462 (int) thisblock) < 0) {
1466 bytes_to_write = bytes_to_write - thisblock;
1475 if (sock_puts(sock, "UCLS 1") < 0) return;
1476 if (sock_gets(sock, buf) < 0) return;
1477 lprintf(CTDL_DEBUG, "<%s\n", buf);
1478 if (buf[0] == '2') {
1486 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1488 void network_poll_node(char *node, char *secret, char *host, char *port) {
1492 if (network_talking_to(node, NTT_CHECK)) return;
1493 network_talking_to(node, NTT_ADD);
1494 lprintf(CTDL_INFO, "Polling node <%s> at %s:%s\n", node, host, port);
1496 sock = sock_connect(host, port, "tcp");
1498 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1499 network_talking_to(node, NTT_REMOVE);
1503 lprintf(CTDL_DEBUG, "Connected!\n");
1505 /* Read the server greeting */
1506 if (sock_gets(sock, buf) < 0) goto bail;
1507 lprintf(CTDL_DEBUG, ">%s\n", buf);
1509 /* Identify ourselves */
1510 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1511 lprintf(CTDL_DEBUG, "<%s\n", buf);
1512 if (sock_puts(sock, buf) <0) goto bail;
1513 if (sock_gets(sock, buf) < 0) goto bail;
1514 lprintf(CTDL_DEBUG, ">%s\n", buf);
1515 if (buf[0] != '2') goto bail;
1517 /* At this point we are authenticated. */
1518 receive_spool(sock, node);
1519 transmit_spool(sock, node);
1521 sock_puts(sock, "QUIT");
1522 bail: sock_close(sock);
1523 network_talking_to(node, NTT_REMOVE);
1529 * Poll other Citadel nodes and transfer inbound/outbound network data.
1530 * Set "full" to nonzero to force a poll of every node, or to zero to poll
1531 * only nodes to which we have data to send.
1533 void network_poll_other_citadel_nodes(int full_poll) {
1541 char spoolfile[SIZ];
1543 if (working_ignetcfg == NULL) return; /* no nodes defined */
1545 /* Use the string tokenizer to grab one line at a time */
1546 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1547 extract_token(linebuf, working_ignetcfg, i, '\n');
1548 extract(node, linebuf, 0);
1549 extract(secret, linebuf, 1);
1550 extract(host, linebuf, 2);
1551 extract(port, linebuf, 3);
1552 if ( (strlen(node) > 0) && (strlen(secret) > 0)
1553 && (strlen(host) > 0) && strlen(port) > 0) {
1556 sprintf(spoolfile, "./network/spoolout/%s",
1558 if (access(spoolfile, R_OK) == 0) {
1563 network_poll_node(node, secret, host, port);
1577 * network_do_queue()
1579 * Run through the rooms doing various types of network stuff.
1581 void network_do_queue(void) {
1582 static time_t last_run = 0L;
1583 struct RoomProcList *ptr;
1584 int full_processing = 1;
1587 * Run the full set of processing tasks no more frequently
1588 * than once every n seconds
1590 if ( (time(NULL) - last_run) < config.c_net_freq ) {
1591 full_processing = 0;
1595 * This is a simple concurrency check to make sure only one queue run
1596 * is done at a time. We could do this with a mutex, but since we
1597 * don't really require extremely fine granularity here, we'll do it
1598 * with a static variable instead.
1600 if (doing_queue) return;
1603 /* Load the IGnet Configuration into memory */
1604 if (working_ignetcfg == NULL) {
1605 working_ignetcfg = CtdlGetSysConfig(IGNETCFG);
1609 * Poll other Citadel nodes. Maybe. If "full_processing" is set
1610 * then we poll everyone. Otherwise we only poll nodes we have stuff
1613 network_poll_other_citadel_nodes(full_processing);
1616 * Load the network map and filter list into memory.
1619 filterlist = load_filter_list();
1622 * Go ahead and run the queue
1624 if (full_processing) {
1625 lprintf(CTDL_INFO, "network: loading outbound queue\n");
1626 ForEachRoom(network_queue_room, NULL);
1628 lprintf(CTDL_INFO, "network: running outbound queue\n");
1629 while (rplist != NULL) {
1630 network_spoolout_room(rplist->name);
1632 rplist = rplist->next;
1637 lprintf(CTDL_INFO, "network: processing inbound queue\n");
1638 network_do_spoolin();
1640 /* Save the network map back to disk */
1641 write_network_map();
1643 /* Free the filter list in memory */
1644 free_filter_list(filterlist);
1647 network_purge_spoolout();
1649 lprintf(CTDL_INFO, "network: queue run completed\n");
1651 if (full_processing) {
1652 last_run = time(NULL);
1656 free(working_ignetcfg);
1661 * cmd_netp() - authenticate to the server as another Citadel node polling
1662 * for network traffic
1664 void cmd_netp(char *cmdbuf)
1673 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
1677 extract(node, cmdbuf, 0);
1678 extract(pass, cmdbuf, 1);
1680 if (is_valid_node(nexthop, secret, node) != 0) {
1681 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1685 if (strcasecmp(pass, secret)) {
1686 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
1690 if (network_talking_to(node, NTT_CHECK)) {
1691 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
1695 safestrncpy(CC->net_node, node, sizeof CC->net_node);
1696 network_talking_to(node, NTT_ADD);
1697 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1703 * This handler detects changes being made to the system's IGnet
1706 int netconfig_aftersave(struct CtdlMessage *msg) {
1710 /* If this isn't the configuration room, or if this isn't a MIME
1711 * message, don't bother.
1713 if (strcasecmp(msg->cm_fields['O'], SYSCONFIGROOM)) return(0);
1714 if (msg->cm_format_type != 4) return(0);
1716 ptr = msg->cm_fields['M'];
1717 while (ptr != NULL) {
1719 linelen = strcspn(ptr, "\n");
1720 if (linelen == 0) return(0); /* end of headers */
1722 if (!strncasecmp(ptr, "Content-type: ", 14)) {
1723 if (!strncasecmp(&ptr[14], IGNETCFG,
1724 strlen(IGNETCFG))) {
1725 if (ignetcfg != NULL) free(ignetcfg);
1730 ptr = strchr((char *)ptr, '\n');
1731 if (ptr != NULL) ++ptr;
1741 * Module entry point
1743 char *serv_network_init(void)
1745 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1746 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1747 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1748 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1749 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
1750 CtdlRegisterMessageHook(netconfig_aftersave, EVT_AFTERSAVE);