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;
89 * Keep track of what messages to reject
91 struct FilterList *load_filter_list(void) {
92 char *serialized_list = NULL;
95 struct FilterList *newlist = NULL;
96 struct FilterList *nptr;
98 serialized_list = CtdlGetSysConfig(FILTERLIST);
99 if (serialized_list == NULL) return(NULL); /* if null, no entries */
101 /* Use the string tokenizer to grab one line at a time */
102 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
103 extract_token(buf, serialized_list, i, '\n');
104 nptr = (struct FilterList *) mallok(sizeof(struct FilterList));
105 extract(nptr->fl_user, buf, 0);
106 striplt(nptr->fl_user);
107 extract(nptr->fl_room, buf, 1);
108 striplt(nptr->fl_room);
109 extract(nptr->fl_node, buf, 2);
110 striplt(nptr->fl_node);
112 /* Cowardly refuse to add an any/any/any entry that would
113 * end up filtering every single message.
115 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
116 + strlen(nptr->fl_node) == 0) {
120 nptr->next = newlist;
125 phree(serialized_list);
130 void free_filter_list(struct FilterList *fl) {
131 if (fl == NULL) return;
132 free_filter_list(fl->next);
139 * Check the use table. This is a list of messages which have recently
140 * arrived on the system. It is maintained and queried to prevent the same
141 * message from being entered into the database multiple times if it happens
142 * to arrive multiple times by accident.
144 int network_usetable(struct CtdlMessage *msg) {
147 struct cdbdata *cdbut;
150 /* Bail out if we can't generate a message ID */
154 if (msg->cm_fields['I'] == NULL) {
157 if (strlen(msg->cm_fields['I']) == 0) {
161 /* Generate the message ID */
162 strcpy(msgid, msg->cm_fields['I']);
163 if (haschar(msgid, '@') == 0) {
165 if (msg->cm_fields['N'] != NULL) {
166 strcat(msgid, msg->cm_fields['N']);
173 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
179 /* If we got to this point, it's unique: add it. */
180 strcpy(ut.ut_msgid, msgid);
181 ut.ut_timestamp = time(NULL);
182 cdb_store(CDB_USETABLE, msgid, strlen(msgid),
183 &ut, sizeof(struct UseTable) );
189 * Read the network map from its configuration file into memory.
191 void read_network_map(void) {
192 char *serialized_map = NULL;
195 struct NetMap *nmptr;
197 serialized_map = CtdlGetSysConfig(IGNETMAP);
198 if (serialized_map == NULL) return; /* if null, no entries */
200 /* Use the string tokenizer to grab one line at a time */
201 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
202 extract_token(buf, serialized_map, i, '\n');
203 nmptr = (struct NetMap *) mallok(sizeof(struct NetMap));
204 extract(nmptr->nodename, buf, 0);
205 nmptr->lastcontact = extract_long(buf, 1);
206 extract(nmptr->nexthop, buf, 2);
207 nmptr->next = the_netmap;
211 phree(serialized_map);
216 * Write the network map from memory back to the configuration file.
218 void write_network_map(void) {
219 char *serialized_map = NULL;
220 struct NetMap *nmptr;
222 serialized_map = strdoop("");
224 if (the_netmap != NULL) {
225 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
226 serialized_map = reallok(serialized_map,
227 (strlen(serialized_map)+SIZ) );
228 if (strlen(nmptr->nodename) > 0) {
229 snprintf(&serialized_map[strlen(serialized_map)],
233 (long)nmptr->lastcontact,
239 CtdlPutSysConfig(IGNETMAP, serialized_map);
240 phree(serialized_map);
242 /* Now free the list */
243 while (the_netmap != NULL) {
244 nmptr = the_netmap->next;
253 * Check the network map and determine whether the supplied node name is
254 * valid. If it is not a neighbor node, supply the name of a neighbor node
255 * which is the next hop. If it *is* a neighbor node, we also fill in the
258 int is_valid_node(char *nexthop, char *secret, char *node) {
259 char *ignetcfg = NULL;
264 struct NetMap *nmptr;
271 * First try the neighbor nodes
273 ignetcfg = CtdlGetSysConfig(IGNETCFG);
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);
303 return(retval); /* yup, it's a direct neighbor */
307 * If we get to this point we have to see if we know the next hop
309 if (the_netmap != NULL) {
310 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
311 if (!strcasecmp(nmptr->nodename, node)) {
312 if (nexthop != NULL) {
313 strcpy(nexthop, nmptr->nexthop);
321 * If we get to this point, the supplied node name is bogus.
323 lprintf(5, "Invalid node name <%s>\n", node);
331 void cmd_gnet(char *argbuf) {
336 if (CtdlAccessCheck(ac_room_aide)) return;
337 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
338 cprintf("%d Network settings for room #%ld <%s>\n",
340 CC->room.QRnumber, CC->room.QRname);
342 fp = fopen(filename, "r");
344 while (fgets(buf, sizeof buf, fp) != NULL) {
345 buf[strlen(buf)-1] = 0;
346 cprintf("%s\n", buf);
355 void cmd_snet(char *argbuf) {
356 char tempfilename[SIZ];
361 if (CtdlAccessCheck(ac_room_aide)) return;
362 safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
363 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
365 fp = fopen(tempfilename, "w");
367 cprintf("%d Cannot open %s: %s\n",
368 ERROR+INTERNAL_ERROR,
373 cprintf("%d %s\n", SEND_LISTING, tempfilename);
374 while (client_gets(buf), strcmp(buf, "000")) {
375 fprintf(fp, "%s\n", buf);
379 /* Now copy the temp file to its permanent location
380 * (We use /bin/mv instead of link() because they may be on
381 * different filesystems)
384 snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
385 begin_critical_section(S_NETCONFIGS);
387 end_critical_section(S_NETCONFIGS);
392 * Spools out one message from the list.
394 void network_spool_msg(long msgnum, void *userdata) {
395 struct SpoolControl *sc;
398 char *newpath = NULL;
400 size_t instr_len = SIZ;
401 struct CtdlMessage *msg = NULL;
402 struct CtdlMessage *imsg;
403 struct namelist *nptr;
404 struct ser_ret sermsg;
410 int delete_after_send = 0; /* Set to 1 to delete after spooling */
412 sc = (struct SpoolControl *)userdata;
415 * Process mailing list recipients
417 if (sc->listrecps != NULL) {
419 /* First, copy it to the spoolout room */
420 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
421 if (err != 0) return;
424 * Figure out how big a buffer we need to allocate
426 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
427 instr_len = instr_len + strlen(nptr->name);
433 lprintf(9, "Generating delivery instructions\n");
434 instr = mallok(instr_len);
436 lprintf(1, "Cannot allocate %ld bytes for instr...\n",
440 snprintf(instr, instr_len,
441 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
442 "bounceto|postmaster@%s\n" ,
443 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
445 /* Generate delivery instructions for each recipient */
446 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
447 size_t tmp = strlen(instr);
448 snprintf(&instr[tmp], instr_len - tmp,
449 "remote|%s|0||\n", nptr->name);
453 * Generate a message from the instructions
455 imsg = mallok(sizeof(struct CtdlMessage));
456 memset(imsg, 0, sizeof(struct CtdlMessage));
457 imsg->cm_magic = CTDLMESSAGE_MAGIC;
458 imsg->cm_anon_type = MES_NORMAL;
459 imsg->cm_format_type = FMT_RFC822;
460 imsg->cm_fields['A'] = strdoop("Citadel");
461 imsg->cm_fields['M'] = instr;
463 /* Save delivery instructions in spoolout room */
464 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
465 CtdlFreeMessage(imsg);
469 * Process digest recipients
471 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
472 fprintf(sc->digestfp, " -----------------------------------"
473 "------------------------------------"
475 CtdlRedirectOutput(sc->digestfp, -1);
476 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 0);
477 CtdlRedirectOutput(NULL, -1);
478 sc->num_msgs_spooled += 1;
482 * Process IGnet push shares
484 if (sc->ignet_push_shares != NULL) {
486 msg = CtdlFetchMessage(msgnum);
490 /* Prepend our node name to the Path field whenever
491 * sending a message to another IGnet node
493 if (msg->cm_fields['P'] == NULL) {
494 msg->cm_fields['P'] = strdoop("username");
496 newpath_len = strlen(msg->cm_fields['P']) +
497 strlen(config.c_nodename) + 2;
498 newpath = mallok(newpath_len);
499 snprintf(newpath, newpath_len, "%s!%s",
500 config.c_nodename, msg->cm_fields['P']);
501 phree(msg->cm_fields['P']);
502 msg->cm_fields['P'] = newpath;
505 * Force the message to appear in the correct room
506 * on the far end by setting the C field correctly
508 if (msg->cm_fields['C'] != NULL) {
509 phree(msg->cm_fields['C']);
511 msg->cm_fields['C'] = strdoop(CC->room.QRname);
514 * Determine if this message is set to be deleted
515 * after sending out on the network
517 if (msg->cm_fields['S'] != NULL) {
518 if (!strcasecmp(msg->cm_fields['S'],
520 delete_after_send = 1;
525 * Now serialize it for transmission
527 serialize_message(&sermsg, msg);
529 /* Now send it to every node */
530 for (nptr = sc->ignet_push_shares; nptr != NULL;
535 /* Check for valid node name */
536 if (is_valid_node(NULL,NULL,nptr->name) != 0) {
537 lprintf(3, "Invalid node <%s>\n",
542 /* Check for split horizon */
543 lprintf(9, "Path is %s\n", msg->cm_fields['P']);
544 bang = num_tokens(msg->cm_fields['P'], '!');
545 if (bang > 1) for (i=0; i<(bang-1); ++i) {
546 extract_token(buf, msg->cm_fields['P'],
548 if (!strcasecmp(buf, nptr->name)) {
553 /* Send the message */
555 snprintf(filename, sizeof filename,
556 "./network/spoolout/%s",
558 fp = fopen(filename, "ab");
567 CtdlFreeMessage(msg);
571 /* update lastsent */
572 sc->lastsent = msgnum;
574 /* Delete this message if delete-after-send is set */
575 if (delete_after_send) {
576 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
583 * Deliver digest messages
585 void network_deliver_digest(struct SpoolControl *sc) {
588 struct CtdlMessage *msg;
592 size_t instr_len = SIZ;
593 struct CtdlMessage *imsg;
594 struct namelist *nptr;
596 if (sc->num_msgs_spooled < 1) {
597 fclose(sc->digestfp);
602 msg = mallok(sizeof(struct CtdlMessage));
603 memset(msg, 0, sizeof(struct CtdlMessage));
604 msg->cm_magic = CTDLMESSAGE_MAGIC;
605 msg->cm_format_type = FMT_RFC822;
606 msg->cm_anon_type = MES_NORMAL;
608 sprintf(buf, "%ld", time(NULL));
609 msg->cm_fields['T'] = strdoop(buf);
610 msg->cm_fields['A'] = strdoop(CC->room.QRname);
611 msg->cm_fields['U'] = strdoop(CC->room.QRname);
612 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
613 for (i=0; i<strlen(buf); ++i) {
614 if (isspace(buf[i])) buf[i]='_';
615 buf[i] = tolower(buf[i]);
617 msg->cm_fields['F'] = strdoop(buf);
619 fseek(sc->digestfp, 0L, SEEK_END);
620 msglen = ftell(sc->digestfp);
622 msg->cm_fields['M'] = mallok(msglen + 1);
623 fseek(sc->digestfp, 0L, SEEK_SET);
624 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
625 msg->cm_fields['M'][msglen] = 0;
627 fclose(sc->digestfp);
630 msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
631 CtdlFreeMessage(msg);
633 /* Now generate the delivery instructions */
636 * Figure out how big a buffer we need to allocate
638 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
639 instr_len = instr_len + strlen(nptr->name);
645 lprintf(9, "Generating delivery instructions\n");
646 instr = mallok(instr_len);
648 lprintf(1, "Cannot allocate %ld bytes for instr...\n",
652 snprintf(instr, instr_len,
653 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
654 "bounceto|postmaster@%s\n" ,
655 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
657 /* Generate delivery instructions for each recipient */
658 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
659 size_t tmp = strlen(instr);
660 snprintf(&instr[tmp], instr_len - tmp,
661 "remote|%s|0||\n", nptr->name);
665 * Generate a message from the instructions
667 imsg = mallok(sizeof(struct CtdlMessage));
668 memset(imsg, 0, sizeof(struct CtdlMessage));
669 imsg->cm_magic = CTDLMESSAGE_MAGIC;
670 imsg->cm_anon_type = MES_NORMAL;
671 imsg->cm_format_type = FMT_RFC822;
672 imsg->cm_fields['A'] = strdoop("Citadel");
673 imsg->cm_fields['M'] = instr;
675 /* Save delivery instructions in spoolout room */
676 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
677 CtdlFreeMessage(imsg);
682 * Batch up and send all outbound traffic from the current room
684 void network_spoolout_room(char *room_to_spool) {
689 struct SpoolControl sc;
690 struct namelist *nptr;
693 int skipthisline = 0;
696 if (getroom(&CC->room, room_to_spool) != 0) {
697 lprintf(1, "ERROR: cannot load <%s>\n", room_to_spool);
701 memset(&sc, 0, sizeof(struct SpoolControl));
702 assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
704 begin_critical_section(S_NETCONFIGS);
705 end_critical_section(S_NETCONFIGS);
707 fp = fopen(filename, "r");
709 end_critical_section(S_NETCONFIGS);
713 lprintf(5, "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 mallok(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 mallok(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 nptr = (struct namelist *)
738 mallok(sizeof(struct namelist));
739 nptr->next = sc.ignet_push_shares;
740 extract(nptr->name, buf, 1);
741 sc.ignet_push_shares = nptr;
744 /* Preserve 'other' lines ... *unless* they happen to
745 * be subscribe/unsubscribe pendings with expired
749 if (!strncasecmp(buf, "subpending|", 11)) {
750 if (time(NULL) - extract_long(buf, 4) > EXP) {
754 if (!strncasecmp(buf, "unsubpending|", 13)) {
755 if (time(NULL) - extract_long(buf, 3) > EXP) {
760 if (skipthisline == 0) {
761 linesize = strlen(buf);
762 sc.misc = realloc(sc.misc,
763 (miscsize + linesize + 2) );
764 sprintf(&sc.misc[miscsize], "%s\n", buf);
765 miscsize = miscsize + linesize + 1;
773 /* If there are digest recipients, we have to build a digest */
774 if (sc.digestrecps != NULL) {
775 sc.digestfp = tmpfile();
776 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
779 /* Do something useful */
780 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
781 network_spool_msg, &sc);
783 /* If we wrote a digest, deliver it and then close it */
784 snprintf(buf, sizeof buf, "room_%s@%s",
785 CC->room.QRname, config.c_fqdn);
786 for (i=0; i<strlen(buf); ++i) {
787 buf[i] = tolower(buf[i]);
788 if (isspace(buf[i])) buf[i] = '_';
790 if (sc.digestfp != NULL) {
791 fprintf(sc.digestfp, " -----------------------------------"
792 "------------------------------------"
794 "You are subscribed to the '%s' "
796 "To post to the list: %s\n",
799 network_deliver_digest(&sc); /* deliver and close */
802 /* Now rewrite the config file */
803 fp = fopen(filename, "w");
805 lprintf(1, "ERROR: cannot open %s: %s\n",
806 filename, strerror(errno));
809 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
811 /* Write out the listrecps while freeing from memory at the
812 * same time. Am I clever or what? :)
814 while (sc.listrecps != NULL) {
815 fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
816 nptr = sc.listrecps->next;
820 /* Do the same for digestrecps */
821 while (sc.digestrecps != NULL) {
822 fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
823 nptr = sc.digestrecps->next;
824 phree(sc.digestrecps);
825 sc.digestrecps = nptr;
827 while (sc.ignet_push_shares != NULL) {
828 fprintf(fp, "ignet_push_share|%s\n",
829 sc.ignet_push_shares->name);
830 nptr = sc.ignet_push_shares->next;
831 phree(sc.ignet_push_shares);
832 sc.ignet_push_shares = nptr;
834 if (sc.misc != NULL) {
835 fwrite(sc.misc, strlen(sc.misc), 1, fp);
841 end_critical_section(S_NETCONFIGS);
847 * Send the *entire* contents of the current room to one specific network node,
848 * ignoring anything we know about which messages have already undergone
849 * network processing. This can be used to bring a new node into sync.
851 int network_sync_to(char *target_node) {
852 struct SpoolControl sc;
855 /* Concise syntax because we don't need a full linked-list */
856 sc.ignet_push_shares = (struct namelist *)
857 mallok(sizeof(struct namelist));
858 sc.ignet_push_shares->next = NULL;
859 safestrncpy(sc.ignet_push_shares->name,
861 sizeof sc.ignet_push_shares->name);
863 /* Send ALL messages */
864 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
865 network_spool_msg, &sc);
867 /* Concise cleanup because we know there's only one node in the sc */
868 phree(sc.ignet_push_shares);
870 lprintf(7, "Synchronized %d messages to <%s>\n",
871 num_spooled, target_node);
877 * Implements the NSYN command
879 void cmd_nsyn(char *argbuf) {
881 char target_node[SIZ];
883 if (CtdlAccessCheck(ac_aide)) return;
885 extract(target_node, argbuf, 0);
886 num_spooled = network_sync_to(target_node);
887 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
893 * Batch up and send all outbound traffic from the current room
895 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
896 struct RoomProcList *ptr;
898 ptr = (struct RoomProcList *) mallok(sizeof (struct RoomProcList));
899 if (ptr == NULL) return;
901 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
908 * Learn topology from path fields
910 void network_learn_topology(char *node, char *path) {
912 struct NetMap *nmptr;
916 if (num_tokens(path, '!') < 3) return;
917 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
918 if (!strcasecmp(nmptr->nodename, node)) {
919 extract_token(nmptr->nexthop, path, 0, '!');
920 nmptr->lastcontact = time(NULL);
925 /* If we got here then it's not in the map, so add it. */
926 nmptr = (struct NetMap *) mallok(sizeof (struct NetMap));
927 strcpy(nmptr->nodename, node);
928 nmptr->lastcontact = time(NULL);
929 extract_token(nmptr->nexthop, path, 0, '!');
930 nmptr->next = the_netmap;
938 * Bounce a message back to the sender
940 void network_bounce(struct CtdlMessage *msg, char *reason) {
941 char *oldpath = NULL;
943 char bouncesource[SIZ];
945 struct recptypes *valid = NULL;
946 char force_room[ROOMNAMELEN];
947 static int serialnum = 0;
950 lprintf(9, "entering network_bounce()\n");
952 if (msg == NULL) return;
954 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
957 * Give it a fresh message ID
959 if (msg->cm_fields['I'] != NULL) {
960 phree(msg->cm_fields['I']);
962 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
963 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
964 msg->cm_fields['I'] = strdoop(buf);
967 * FIXME ... right now we're just sending a bounce; we really want to
968 * include the text of the bounced message.
970 if (msg->cm_fields['M'] != NULL) {
971 phree(msg->cm_fields['M']);
973 msg->cm_fields['M'] = strdoop(reason);
974 msg->cm_format_type = 0;
977 * Turn the message around
979 if (msg->cm_fields['R'] == NULL) {
980 phree(msg->cm_fields['R']);
983 if (msg->cm_fields['D'] == NULL) {
984 phree(msg->cm_fields['D']);
987 snprintf(recipient, sizeof recipient, "%s@%s",
988 msg->cm_fields['A'], msg->cm_fields['N']);
990 if (msg->cm_fields['A'] == NULL) {
991 phree(msg->cm_fields['A']);
994 if (msg->cm_fields['N'] == NULL) {
995 phree(msg->cm_fields['N']);
998 msg->cm_fields['A'] = strdoop(BOUNCESOURCE);
999 msg->cm_fields['N'] = strdoop(config.c_nodename);
1002 /* prepend our node to the path */
1003 if (msg->cm_fields['P'] != NULL) {
1004 oldpath = msg->cm_fields['P'];
1005 msg->cm_fields['P'] = NULL;
1008 oldpath = strdoop("unknown_user");
1010 size = strlen(oldpath) + SIZ;
1011 msg->cm_fields['P'] = mallok(size);
1012 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1015 /* Now submit the message */
1016 valid = validate_recipients(recipient);
1017 if (valid != NULL) if (valid->num_error > 0) {
1021 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1022 strcpy(force_room, config.c_aideroom);
1025 strcpy(force_room, "");
1027 if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1028 strcpy(force_room, config.c_aideroom);
1030 CtdlSubmitMsg(msg, valid, force_room);
1033 if (valid != NULL) phree(valid);
1034 CtdlFreeMessage(msg);
1035 lprintf(9, "leaving network_bounce()\n");
1042 * Process a buffer containing a single message from a single file
1043 * from the inbound queue
1045 void network_process_buffer(char *buffer, long size) {
1046 struct CtdlMessage *msg;
1049 struct recptypes *recp = NULL;
1050 char target_room[ROOMNAMELEN];
1051 struct ser_ret sermsg;
1052 char *oldpath = NULL;
1057 /* Set default target room to trash */
1058 strcpy(target_room, TWITROOM);
1060 /* Load the message into memory */
1061 msg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
1062 memset(msg, 0, sizeof(struct CtdlMessage));
1063 msg->cm_magic = CTDLMESSAGE_MAGIC;
1064 msg->cm_anon_type = buffer[1];
1065 msg->cm_format_type = buffer[2];
1067 for (pos = 3; pos < size; ++pos) {
1068 field = buffer[pos];
1069 msg->cm_fields[field] = strdoop(&buffer[pos+1]);
1070 pos = pos + strlen(&buffer[(int)pos]);
1073 /* Check for message routing */
1074 if (msg->cm_fields['D'] != NULL) {
1075 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1077 /* route the message */
1078 strcpy(nexthop, "");
1079 if (is_valid_node(nexthop, NULL,
1080 msg->cm_fields['D']) == 0) {
1082 /* prepend our node to the path */
1083 if (msg->cm_fields['P'] != NULL) {
1084 oldpath = msg->cm_fields['P'];
1085 msg->cm_fields['P'] = NULL;
1088 oldpath = strdoop("unknown_user");
1090 size = strlen(oldpath) + SIZ;
1091 msg->cm_fields['P'] = mallok(size);
1092 snprintf(msg->cm_fields['P'], size, "%s!%s",
1093 config.c_nodename, oldpath);
1096 /* serialize the message */
1097 serialize_message(&sermsg, msg);
1100 if (strlen(nexthop) == 0) {
1101 strcpy(nexthop, msg->cm_fields['D']);
1103 snprintf(filename, sizeof filename,
1104 "./network/spoolout/%s", nexthop);
1105 fp = fopen(filename, "ab");
1112 CtdlFreeMessage(msg);
1116 else { /* invalid destination node name */
1119 "A message you sent could not be delivered due to an invalid destination node"
1120 " name. Please check the address and try sending the message again.\n");
1129 * Check to see if we already have a copy of this message, and
1130 * abort its processing if so. (We used to post a warning to Aide>
1131 * every time this happened, but the network is now so densely
1132 * connected that it's inevitable.)
1134 if (network_usetable(msg) != 0) {
1138 /* Learn network topology from the path */
1139 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1140 network_learn_topology(msg->cm_fields['N'],
1141 msg->cm_fields['P']);
1144 /* Does it have a recipient? If so, validate it... */
1145 if (msg->cm_fields['R'] != NULL) {
1146 recp = validate_recipients(msg->cm_fields['R']);
1147 if (recp != NULL) if (recp->num_error > 0) {
1149 "A message you sent could not be delivered due to an invalid address.\n"
1150 "Please check the address and try sending the message again.\n");
1155 strcpy(target_room, ""); /* no target room if mail */
1158 else if (msg->cm_fields['C'] != NULL) {
1159 safestrncpy(target_room,
1160 msg->cm_fields['C'],
1161 sizeof target_room);
1164 else if (msg->cm_fields['O'] != NULL) {
1165 safestrncpy(target_room,
1166 msg->cm_fields['O'],
1167 sizeof target_room);
1170 /* Strip out fields that are only relevant during transit */
1171 if (msg->cm_fields['D'] != NULL) {
1172 phree(msg->cm_fields['D']);
1173 msg->cm_fields['D'] = NULL;
1175 if (msg->cm_fields['C'] != NULL) {
1176 phree(msg->cm_fields['C']);
1177 msg->cm_fields['C'] = NULL;
1180 /* save the message into a room */
1181 if (PerformNetprocHooks(msg, target_room) == 0) {
1182 msg->cm_flags = CM_SKIP_HOOKS;
1183 CtdlSubmitMsg(msg, recp, target_room);
1185 CtdlFreeMessage(msg);
1191 * Process a single message from a single file from the inbound queue
1193 void network_process_message(FILE *fp, long msgstart, long msgend) {
1198 hold_pos = ftell(fp);
1199 size = msgend - msgstart + 1;
1200 buffer = mallok(size);
1201 if (buffer != NULL) {
1202 fseek(fp, msgstart, SEEK_SET);
1203 fread(buffer, size, 1, fp);
1204 network_process_buffer(buffer, size);
1208 fseek(fp, hold_pos, SEEK_SET);
1213 * Process a single file from the inbound queue
1215 void network_process_file(char *filename) {
1217 long msgstart = (-1L);
1218 long msgend = (-1L);
1223 fp = fopen(filename, "rb");
1225 lprintf(5, "Error opening %s: %s\n",
1226 filename, strerror(errno));
1230 lprintf(5, "network: processing <%s>\n", filename);
1232 /* Look for messages in the data stream and break them out */
1233 while (ch = getc(fp), ch >= 0) {
1236 if (msgstart >= 0L) {
1237 msgend = msgcur - 1;
1238 network_process_message(fp, msgstart, msgend);
1246 msgend = msgcur - 1;
1247 if (msgstart >= 0L) {
1248 network_process_message(fp, msgstart, msgend);
1257 * Process anything in the inbound queue
1259 void network_do_spoolin(void) {
1264 dp = opendir("./network/spoolin");
1265 if (dp == NULL) return;
1267 while (d = readdir(dp), d != NULL) {
1268 snprintf(filename, sizeof filename,
1269 "./network/spoolin/%s", d->d_name);
1270 network_process_file(filename);
1282 * receive network spool from the remote system
1284 void receive_spool(int sock, char *remote_nodename) {
1286 long bytes_received;
1288 static char pbuf[IGNET_PACKET_SIZE];
1289 char tempfilename[PATH_MAX];
1293 strcpy(tempfilename, tmpnam(NULL));
1294 if (sock_puts(sock, "NDOP") < 0) return;
1295 if (sock_gets(sock, buf) < 0) return;
1296 lprintf(9, "<%s\n", buf);
1297 if (buf[0] != '2') {
1300 download_len = extract_long(&buf[4], 0);
1302 bytes_received = 0L;
1303 fp = fopen(tempfilename, "w");
1305 lprintf(9, "cannot open download file locally: %s\n",
1310 while (bytes_received < download_len) {
1311 snprintf(buf, sizeof buf, "READ %ld|%ld",
1313 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1314 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1315 if (sock_puts(sock, buf) < 0) {
1317 unlink(tempfilename);
1320 if (sock_gets(sock, buf) < 0) {
1322 unlink(tempfilename);
1325 if (buf[0] == '6') {
1326 plen = extract_long(&buf[4], 0);
1327 if (sock_read(sock, pbuf, plen) < 0) {
1329 unlink(tempfilename);
1332 fwrite((char *) pbuf, plen, 1, fp);
1333 bytes_received = bytes_received + plen;
1338 if (sock_puts(sock, "CLOS") < 0) {
1339 unlink(tempfilename);
1342 if (sock_gets(sock, buf) < 0) {
1343 unlink(tempfilename);
1346 lprintf(9, "%s\n", buf);
1347 snprintf(buf, sizeof buf, "mv %s ./network/spoolin/%s.%ld",
1348 tempfilename, remote_nodename, (long) getpid());
1355 * transmit network spool to the remote system
1357 void transmit_spool(int sock, char *remote_nodename)
1362 long bytes_to_write, thisblock;
1366 if (sock_puts(sock, "NUOP") < 0) return;
1367 if (sock_gets(sock, buf) < 0) return;
1368 lprintf(9, "<%s\n", buf);
1369 if (buf[0] != '2') {
1373 snprintf(sfname, sizeof sfname, "./network/spoolout/%s", remote_nodename);
1374 fd = open(sfname, O_RDONLY);
1376 if (errno == ENOENT) {
1377 lprintf(9, "Nothing to send.\n");
1379 lprintf(5, "cannot open upload file locally: %s\n",
1384 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1385 bytes_to_write = plen;
1386 while (bytes_to_write > 0L) {
1387 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1388 if (sock_puts(sock, buf) < 0) {
1392 if (sock_gets(sock, buf) < 0) {
1396 thisblock = atol(&buf[4]);
1397 if (buf[0] == '7') {
1398 if (sock_write(sock, pbuf,
1399 (int) thisblock) < 0) {
1403 bytes_to_write = bytes_to_write - thisblock;
1412 if (sock_puts(sock, "UCLS 1") < 0) return;
1413 if (sock_gets(sock, buf) < 0) return;
1414 lprintf(9, "<%s\n", buf);
1415 if (buf[0] == '2') {
1423 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1425 void network_poll_node(char *node, char *secret, char *host, char *port) {
1429 if (network_talking_to(node, NTT_CHECK)) return;
1430 network_talking_to(node, NTT_ADD);
1431 lprintf(5, "Polling node <%s> at %s:%s\n", node, host, port);
1433 sock = sock_connect(host, port, "tcp");
1435 lprintf(7, "Could not connect: %s\n", strerror(errno));
1436 network_talking_to(node, NTT_REMOVE);
1440 lprintf(9, "Connected!\n");
1442 /* Read the server greeting */
1443 if (sock_gets(sock, buf) < 0) goto bail;
1444 lprintf(9, ">%s\n", buf);
1446 /* Identify ourselves */
1447 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1448 lprintf(9, "<%s\n", buf);
1449 if (sock_puts(sock, buf) <0) goto bail;
1450 if (sock_gets(sock, buf) < 0) goto bail;
1451 lprintf(9, ">%s\n", buf);
1452 if (buf[0] != '2') goto bail;
1454 /* At this point we are authenticated. */
1455 receive_spool(sock, node);
1456 transmit_spool(sock, node);
1458 sock_puts(sock, "QUIT");
1459 bail: sock_close(sock);
1460 network_talking_to(node, NTT_REMOVE);
1466 * Poll other Citadel nodes and transfer inbound/outbound network data.
1467 * Set "full" to nonzero to force a poll of every node, or to zero to poll
1468 * only nodes to which we have data to send.
1470 void network_poll_other_citadel_nodes(int full_poll) {
1471 char *ignetcfg = NULL;
1479 char spoolfile[SIZ];
1481 ignetcfg = CtdlGetSysConfig(IGNETCFG);
1482 if (ignetcfg == NULL) return; /* no nodes defined */
1484 /* Use the string tokenizer to grab one line at a time */
1485 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
1486 extract_token(linebuf, ignetcfg, i, '\n');
1487 extract(node, linebuf, 0);
1488 extract(secret, linebuf, 1);
1489 extract(host, linebuf, 2);
1490 extract(port, linebuf, 3);
1491 if ( (strlen(node) > 0) && (strlen(secret) > 0)
1492 && (strlen(host) > 0) && strlen(port) > 0) {
1495 sprintf(spoolfile, "./network/spoolout/%s",
1497 if (access(spoolfile, R_OK) == 0) {
1502 network_poll_node(node, secret, host, port);
1517 * network_do_queue()
1519 * Run through the rooms doing various types of network stuff.
1521 void network_do_queue(void) {
1522 static time_t last_run = 0L;
1523 struct RoomProcList *ptr;
1524 int full_processing = 1;
1527 * Run the full set of processing tasks no more frequently
1528 * than once every n seconds
1530 if ( (time(NULL) - last_run) < config.c_net_freq ) {
1531 full_processing = 0;
1535 * This is a simple concurrency check to make sure only one queue run
1536 * is done at a time. We could do this with a mutex, but since we
1537 * don't really require extremely fine granularity here, we'll do it
1538 * with a static variable instead.
1540 if (doing_queue) return;
1544 * Poll other Citadel nodes. Maybe. If "full_processing" is set
1545 * then we poll everyone. Otherwise we only poll nodes we have stuff
1548 network_poll_other_citadel_nodes(full_processing);
1551 * Load the network map and filter list into memory.
1554 filterlist = load_filter_list();
1557 * Go ahead and run the queue
1559 if (full_processing) {
1560 lprintf(7, "network: loading outbound queue\n");
1561 ForEachRoom(network_queue_room, NULL);
1563 lprintf(7, "network: running outbound queue\n");
1564 while (rplist != NULL) {
1565 network_spoolout_room(rplist->name);
1567 rplist = rplist->next;
1572 lprintf(7, "network: processing inbound queue\n");
1573 network_do_spoolin();
1575 /* Save the network map back to disk */
1576 write_network_map();
1578 /* Free the filter list in memory */
1579 free_filter_list(filterlist);
1582 lprintf(7, "network: queue run completed\n");
1584 if (full_processing) {
1585 last_run = time(NULL);
1593 * cmd_netp() - authenticate to the server as another Citadel node polling
1594 * for network traffic
1596 void cmd_netp(char *cmdbuf)
1605 cprintf("%d spooling - try again in a few minutes\n", ERROR);
1609 extract(node, cmdbuf, 0);
1610 extract(pass, cmdbuf, 1);
1612 if (is_valid_node(nexthop, secret, node) != 0) {
1613 cprintf("%d authentication failed\n", ERROR);
1617 if (strcasecmp(pass, secret)) {
1618 cprintf("%d authentication failed\n", ERROR);
1622 if (network_talking_to(node, NTT_CHECK)) {
1623 cprintf("%d Already talking to %s right now\n", ERROR, node);
1627 safestrncpy(CC->net_node, node, sizeof CC->net_node);
1628 network_talking_to(node, NTT_ADD);
1629 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
1638 * Module entry point
1640 char *serv_network_init(void)
1642 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1643 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1644 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1645 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
1646 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);