4 * This module handles shared rooms, inter-Citadel mail, and outbound
5 * mailing list processing.
7 * Copyright (C) 2000-2009 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 */
35 #include <sys/types.h>
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
42 # include <sys/time.h>
51 #include <libcitadel.h>
54 #include "citserver.h"
62 #include "internet_addressing.h"
63 #include "serv_network.h"
64 #include "clientsocket.h"
66 #include "citadel_dirs.h"
74 #include "ctdl_module.h"
78 /* Nonzero while we are doing network processing */
79 static int doing_queue = 0;
82 * When we do network processing, it's accomplished in two passes; one to
83 * gather a list of rooms and one to actually do them. It's ok that rplist
84 * is global; we have a mutex that keeps it safe.
86 struct RoomProcList *rplist = NULL;
89 * We build a map of network nodes during processing.
91 NetMap *the_netmap = NULL;
92 int netmap_changed = 0;
93 char *working_ignetcfg = NULL;
96 * Load or refresh the Citadel network (IGnet) configuration for this node.
98 void load_working_ignetcfg(void) {
102 cfg = CtdlGetSysConfig(IGNETCFG);
107 oldcfg = working_ignetcfg;
108 working_ignetcfg = cfg;
109 if (oldcfg != NULL) {
119 * Keep track of what messages to reject
121 FilterList *load_filter_list(void) {
122 char *serialized_list = NULL;
125 FilterList *newlist = NULL;
128 serialized_list = CtdlGetSysConfig(FILTERLIST);
129 if (serialized_list == NULL) return(NULL); /* if null, no entries */
131 /* Use the string tokenizer to grab one line at a time */
132 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
133 extract_token(buf, serialized_list, i, '\n', sizeof buf);
134 nptr = (FilterList *) malloc(sizeof(FilterList));
135 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
136 striplt(nptr->fl_user);
137 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
138 striplt(nptr->fl_room);
139 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
140 striplt(nptr->fl_node);
142 /* Cowardly refuse to add an any/any/any entry that would
143 * end up filtering every single message.
145 if (IsEmptyStr(nptr->fl_user) &&
146 IsEmptyStr(nptr->fl_room) &&
147 IsEmptyStr(nptr->fl_node)) {
151 nptr->next = newlist;
156 free(serialized_list);
161 void free_filter_list(FilterList *fl) {
162 if (fl == NULL) return;
163 free_filter_list(fl->next);
170 * Check the use table. This is a list of messages which have recently
171 * arrived on the system. It is maintained and queried to prevent the same
172 * message from being entered into the database multiple times if it happens
173 * to arrive multiple times by accident.
175 int network_usetable(struct CtdlMessage *msg) {
178 struct cdbdata *cdbut;
181 /* Bail out if we can't generate a message ID */
185 if (msg->cm_fields['I'] == NULL) {
188 if (IsEmptyStr(msg->cm_fields['I'])) {
192 /* Generate the message ID */
193 strcpy(msgid, msg->cm_fields['I']);
194 if (haschar(msgid, '@') == 0) {
196 if (msg->cm_fields['N'] != NULL) {
197 strcat(msgid, msg->cm_fields['N']);
204 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
210 /* If we got to this point, it's unique: add it. */
211 strcpy(ut.ut_msgid, msgid);
212 ut.ut_timestamp = time(NULL);
213 cdb_store(CDB_USETABLE, msgid, strlen(msgid),
214 &ut, sizeof(struct UseTable) );
220 * Read the network map from its configuration file into memory.
222 void read_network_map(void) {
223 char *serialized_map = NULL;
228 serialized_map = CtdlGetSysConfig(IGNETMAP);
229 if (serialized_map == NULL) return; /* if null, no entries */
231 /* Use the string tokenizer to grab one line at a time */
232 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
233 extract_token(buf, serialized_map, i, '\n', sizeof buf);
234 nmptr = (NetMap *) malloc(sizeof(NetMap));
235 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
236 nmptr->lastcontact = extract_long(buf, 1);
237 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
238 nmptr->next = the_netmap;
242 free(serialized_map);
248 * Write the network map from memory back to the configuration file.
250 void write_network_map(void) {
251 char *serialized_map = NULL;
255 if (netmap_changed) {
256 serialized_map = strdup("");
258 if (the_netmap != NULL) {
259 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
260 serialized_map = realloc(serialized_map,
261 (strlen(serialized_map)+SIZ) );
262 if (!IsEmptyStr(nmptr->nodename)) {
263 snprintf(&serialized_map[strlen(serialized_map)],
267 (long)nmptr->lastcontact,
273 CtdlPutSysConfig(IGNETMAP, serialized_map);
274 free(serialized_map);
277 /* Now free the list */
278 while (the_netmap != NULL) {
279 nmptr = the_netmap->next;
289 * Check the network map and determine whether the supplied node name is
290 * valid. If it is not a neighbor node, supply the name of a neighbor node
291 * which is the next hop. If it *is* a neighbor node, we also fill in the
294 int is_valid_node(char *nexthop, char *secret, char *node) {
306 * First try the neighbor nodes
308 if (working_ignetcfg == NULL) {
309 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
310 if (nexthop != NULL) {
317 if (nexthop != NULL) {
321 /* Use the string tokenizer to grab one line at a time */
322 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
323 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
324 extract_token(buf, linebuf, 0, '|', sizeof buf);
325 if (!strcasecmp(buf, node)) {
326 if (nexthop != NULL) {
329 if (secret != NULL) {
330 extract_token(secret, linebuf, 1, '|', 256);
337 return(retval); /* yup, it's a direct neighbor */
341 * If we get to this point we have to see if we know the next hop
343 if (the_netmap != NULL) {
344 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
345 if (!strcasecmp(nmptr->nodename, node)) {
346 if (nexthop != NULL) {
347 strcpy(nexthop, nmptr->nexthop);
355 * If we get to this point, the supplied node name is bogus.
357 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
365 void cmd_gnet(char *argbuf) {
366 char filename[PATH_MAX];
370 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
371 /* users can edit the netconfigs for their own mailbox rooms */
373 else if (CtdlAccessCheck(ac_room_aide)) return;
375 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
376 cprintf("%d Network settings for room #%ld <%s>\n",
378 CC->room.QRnumber, CC->room.QRname);
380 fp = fopen(filename, "r");
382 while (fgets(buf, sizeof buf, fp) != NULL) {
383 buf[strlen(buf)-1] = 0;
384 cprintf("%s\n", buf);
393 void cmd_snet(char *argbuf) {
394 char tempfilename[PATH_MAX];
395 char filename[PATH_MAX];
401 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
402 /* users can edit the netconfigs for their own mailbox rooms */
404 else if (CtdlAccessCheck(ac_room_aide)) return;
406 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
407 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
409 fp = fopen(tempfilename, "w");
411 cprintf("%d Cannot open %s: %s\n",
412 ERROR + INTERNAL_ERROR,
417 cprintf("%d %s\n", SEND_LISTING, tempfilename);
418 while (client_getln(buf, sizeof buf) >= 0 && strcmp(buf, "000")) {
419 fprintf(fp, "%s\n", buf);
423 /* Now copy the temp file to its permanent location.
424 * (We copy instead of link because they may be on different filesystems)
426 begin_critical_section(S_NETCONFIGS);
427 fp = fopen(tempfilename, "r");
429 newfp = fopen(filename, "w");
431 while (fgets(buf, sizeof buf, fp) != NULL) {
432 fprintf(newfp, "%s", buf);
438 end_critical_section(S_NETCONFIGS);
439 unlink(tempfilename);
444 * Deliver digest messages
446 void network_deliver_digest(SpoolControl *sc) {
449 struct CtdlMessage *msg = NULL;
452 size_t recps_len = SIZ;
453 struct recptypes *valid;
457 if (sc->num_msgs_spooled < 1) {
458 fclose(sc->digestfp);
463 msg = malloc(sizeof(struct CtdlMessage));
464 memset(msg, 0, sizeof(struct CtdlMessage));
465 msg->cm_magic = CTDLMESSAGE_MAGIC;
466 msg->cm_format_type = FMT_RFC822;
467 msg->cm_anon_type = MES_NORMAL;
469 sprintf(buf, "%ld", time(NULL));
470 msg->cm_fields['T'] = strdup(buf);
471 msg->cm_fields['A'] = strdup(CC->room.QRname);
472 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
473 msg->cm_fields['U'] = strdup(buf);
474 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
475 for (i=0; buf[i]; ++i) {
476 if (isspace(buf[i])) buf[i]='_';
477 buf[i] = tolower(buf[i]);
479 msg->cm_fields['F'] = strdup(buf);
480 msg->cm_fields['R'] = strdup(buf);
482 /* Set the 'List-ID' header */
483 msg->cm_fields['L'] = malloc(1024);
484 snprintf(msg->cm_fields['L'], 1024,
485 "%s <%ld.list-id.%s>",
492 * Go fetch the contents of the digest
494 fseek(sc->digestfp, 0L, SEEK_END);
495 msglen = ftell(sc->digestfp);
497 msg->cm_fields['M'] = malloc(msglen + 1);
498 fseek(sc->digestfp, 0L, SEEK_SET);
499 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
500 msg->cm_fields['M'][msglen] = 0;
502 fclose(sc->digestfp);
505 /* Now generate the delivery instructions */
508 * Figure out how big a buffer we need to allocate
510 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
511 recps_len = recps_len + strlen(nptr->name) + 2;
514 recps = malloc(recps_len);
517 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
524 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
525 if (nptr != sc->digestrecps) {
528 strcat(recps, nptr->name);
531 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
532 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
534 /* Now submit the message */
535 valid = validate_recipients(recps, NULL, 0);
538 valid->bounce_to = strdup(bounce_to);
539 valid->envelope_from = strdup(bounce_to);
540 CtdlSubmitMsg(msg, valid, NULL, 0);
542 CtdlFreeMessage(msg);
543 free_recipients(valid);
548 * Deliver list messages to everyone on the list ... efficiently
550 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
552 size_t recps_len = SIZ;
553 struct recptypes *valid;
557 /* Don't do this if there were no recipients! */
558 if (sc->listrecps == NULL) return;
560 /* Now generate the delivery instructions */
563 * Figure out how big a buffer we need to allocate
565 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
566 recps_len = recps_len + strlen(nptr->name) + 2;
569 recps = malloc(recps_len);
572 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
579 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
580 if (nptr != sc->listrecps) {
583 strcat(recps, nptr->name);
586 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
587 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
589 /* Now submit the message */
590 valid = validate_recipients(recps, NULL, 0);
593 valid->bounce_to = strdup(bounce_to);
594 valid->envelope_from = strdup(bounce_to);
595 CtdlSubmitMsg(msg, valid, NULL, 0);
596 free_recipients(valid);
598 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
605 * Spools out one message from the list.
607 void network_spool_msg(long msgnum, void *userdata) {
610 char *newpath = NULL;
611 size_t instr_len = SIZ;
612 struct CtdlMessage *msg = NULL;
615 struct ser_ret sermsg;
617 char filename[PATH_MAX];
621 int delete_after_send = 0; /* Set to 1 to delete after spooling */
622 int ok_to_participate = 0;
623 struct recptypes *valid;
625 sc = (SpoolControl *)userdata;
628 * Process mailing list recipients
631 if (sc->listrecps != NULL) {
632 /* Fetch the message. We're going to need to modify it
633 * in order to insert the [list name] in it, etc.
635 msg = CtdlFetchMessage(msgnum, 1);
638 /* Set the 'List-ID' header */
639 if (msg->cm_fields['L'] != NULL) {
640 free(msg->cm_fields['L']);
642 msg->cm_fields['L'] = malloc(1024);
643 snprintf(msg->cm_fields['L'], 1024,
644 "%s <%ld.list-id.%s>",
650 /* Prepend "[List name]" to the subject */
651 if (msg->cm_fields['U'] == NULL) {
652 msg->cm_fields['U'] = strdup("(no subject)");
654 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
655 free(msg->cm_fields['U']);
656 msg->cm_fields['U'] = strdup(buf);
658 /* Set the recipient of the list message to the
659 * email address of the room itself.
660 * FIXME ... I want to be able to pick any address
662 if (msg->cm_fields['R'] != NULL) {
663 free(msg->cm_fields['R']);
665 msg->cm_fields['R'] = malloc(256);
666 snprintf(msg->cm_fields['R'], 256,
667 "room_%s@%s", CC->room.QRname,
669 for (i=0; msg->cm_fields['R'][i]; ++i) {
670 if (isspace(msg->cm_fields['R'][i])) {
671 msg->cm_fields['R'][i] = '_';
675 /* Handle delivery */
676 network_deliver_list(msg, sc);
677 CtdlFreeMessage(msg);
682 * Process digest recipients
684 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
685 msg = CtdlFetchMessage(msgnum, 1);
687 fprintf(sc->digestfp, " -----------------------------------"
688 "------------------------------------"
690 fprintf(sc->digestfp, "From: ");
691 if (msg->cm_fields['A'] != NULL) {
692 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
694 if (msg->cm_fields['F'] != NULL) {
695 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
697 else if (msg->cm_fields['N'] != NULL) {
698 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
700 fprintf(sc->digestfp, "\n");
701 if (msg->cm_fields['U'] != NULL) {
702 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
705 CC->redirect_buffer = malloc(SIZ);
706 CC->redirect_len = 0;
707 CC->redirect_alloc = SIZ;
709 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
710 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
712 striplt(CC->redirect_buffer);
713 fprintf(sc->digestfp, "\n%s\n", CC->redirect_buffer);
715 free(CC->redirect_buffer);
716 CC->redirect_buffer = NULL;
717 CC->redirect_len = 0;
718 CC->redirect_alloc = 0;
720 sc->num_msgs_spooled += 1;
726 * Process client-side list participations for this room
729 if (sc->participates != NULL) {
730 msg = CtdlFetchMessage(msgnum, 1);
733 /* Only send messages which originated on our own Citadel
734 * network, otherwise we'll end up sending the remote
735 * mailing list's messages back to it, which is rude...
737 ok_to_participate = 0;
738 if (msg->cm_fields['N'] != NULL) {
739 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
740 ok_to_participate = 1;
742 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
743 ok_to_participate = 1;
746 if (ok_to_participate) {
747 if (msg->cm_fields['F'] != NULL) {
748 free(msg->cm_fields['F']);
750 msg->cm_fields['F'] = malloc(SIZ);
751 /* Replace the Internet email address of the actual
752 * author with the email address of the room itself,
753 * so the remote listserv doesn't reject us.
754 * FIXME ... I want to be able to pick any address
756 snprintf(msg->cm_fields['F'], SIZ,
757 "room_%s@%s", CC->room.QRname,
759 for (i=0; msg->cm_fields['F'][i]; ++i) {
760 if (isspace(msg->cm_fields['F'][i])) {
761 msg->cm_fields['F'][i] = '_';
766 * Figure out how big a buffer we need to allocate
768 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
770 if (msg->cm_fields['R'] == NULL) {
771 free(msg->cm_fields['R']);
773 msg->cm_fields['R'] = strdup(nptr->name);
775 valid = validate_recipients(nptr->name, NULL, 0);
776 CtdlSubmitMsg(msg, valid, "", 0);
777 free_recipients(valid);
781 CtdlFreeMessage(msg);
786 * Process IGnet push shares
788 msg = CtdlFetchMessage(msgnum, 1);
792 /* Prepend our node name to the Path field whenever
793 * sending a message to another IGnet node
795 if (msg->cm_fields['P'] == NULL) {
796 msg->cm_fields['P'] = strdup("username");
798 newpath_len = strlen(msg->cm_fields['P']) +
799 strlen(config.c_nodename) + 2;
800 newpath = malloc(newpath_len);
801 snprintf(newpath, newpath_len, "%s!%s",
802 config.c_nodename, msg->cm_fields['P']);
803 free(msg->cm_fields['P']);
804 msg->cm_fields['P'] = newpath;
807 * Determine if this message is set to be deleted
808 * after sending out on the network
810 if (msg->cm_fields['S'] != NULL) {
811 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
812 delete_after_send = 1;
816 /* Now send it to every node */
817 if (sc->ignet_push_shares != NULL)
818 for (mptr = sc->ignet_push_shares; mptr != NULL;
823 /* Check for valid node name */
824 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
825 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
829 /* Check for split horizon */
830 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
831 bang = num_tokens(msg->cm_fields['P'], '!');
832 if (bang > 1) for (i=0; i<(bang-1); ++i) {
833 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
834 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
835 buf, mptr->remote_nodename) ;
836 if (!strcasecmp(buf, mptr->remote_nodename)) {
838 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
839 mptr->remote_nodename);
842 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
846 /* Send the message */
850 * Force the message to appear in the correct room
851 * on the far end by setting the C field correctly
853 if (msg->cm_fields['C'] != NULL) {
854 free(msg->cm_fields['C']);
856 if (!IsEmptyStr(mptr->remote_roomname)) {
857 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
860 msg->cm_fields['C'] = strdup(CC->room.QRname);
863 /* serialize it for transmission */
864 serialize_message(&sermsg, msg);
865 if (sermsg.len > 0) {
867 /* write it to the spool file */
868 snprintf(filename, sizeof filename,"%s/%s",
870 mptr->remote_nodename);
871 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
872 fp = fopen(filename, "ab");
879 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
882 /* free the serialized version */
888 CtdlFreeMessage(msg);
891 /* update lastsent */
892 sc->lastsent = msgnum;
894 /* Delete this message if delete-after-send is set */
895 if (delete_after_send) {
896 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
902 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
908 char roomname[ROOMNAMELEN];
911 int skipthisline = 0;
912 namelist *nptr = NULL;
913 maplist *mptr = NULL;
916 fp = fopen(filename, "r");
920 sc = malloc(sizeof(SpoolControl));
921 memset(sc, 0, sizeof(SpoolControl));
924 while (fgets(buf, sizeof buf, fp) != NULL) {
925 buf[strlen(buf)-1] = 0;
927 extract_token(instr, buf, 0, '|', sizeof instr);
928 if (!strcasecmp(instr, "lastsent")) {
929 sc->lastsent = extract_long(buf, 1);
931 else if (!strcasecmp(instr, "listrecp")) {
933 malloc(sizeof(namelist));
934 nptr->next = sc->listrecps;
935 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
936 sc->listrecps = nptr;
938 else if (!strcasecmp(instr, "participate")) {
940 malloc(sizeof(namelist));
941 nptr->next = sc->participates;
942 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
943 sc->participates = nptr;
945 else if (!strcasecmp(instr, "digestrecp")) {
947 malloc(sizeof(namelist));
948 nptr->next = sc->digestrecps;
949 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
950 sc->digestrecps = nptr;
952 else if (!strcasecmp(instr, "ignet_push_share")) {
953 extract_token(nodename, buf, 1, '|', sizeof nodename);
954 extract_token(roomname, buf, 2, '|', sizeof roomname);
955 mptr = (maplist *) malloc(sizeof(maplist));
956 mptr->next = sc->ignet_push_shares;
957 strcpy(mptr->remote_nodename, nodename);
958 strcpy(mptr->remote_roomname, roomname);
959 sc->ignet_push_shares = mptr;
962 /* Preserve 'other' lines ... *unless* they happen to
963 * be subscribe/unsubscribe pendings with expired
967 if (!strncasecmp(buf, "subpending|", 11)) {
968 if (time(NULL) - extract_long(buf, 4) > EXP) {
972 if (!strncasecmp(buf, "unsubpending|", 13)) {
973 if (time(NULL) - extract_long(buf, 3) > EXP) {
978 if (skipthisline == 0) {
979 linesize = strlen(buf);
980 sc->misc = realloc(sc->misc,
981 (miscsize + linesize + 2) );
982 sprintf(&sc->misc[miscsize], "%s\n", buf);
983 miscsize = miscsize + linesize + 1;
993 void free_spoolcontrol_struct(SpoolControl **scc)
996 namelist *nptr = NULL;
997 maplist *mptr = NULL;
1000 while (sc->listrecps != NULL) {
1001 nptr = sc->listrecps->next;
1002 free(sc->listrecps);
1003 sc->listrecps = nptr;
1005 /* Do the same for digestrecps */
1006 while (sc->digestrecps != NULL) {
1007 nptr = sc->digestrecps->next;
1008 free(sc->digestrecps);
1009 sc->digestrecps = nptr;
1011 /* Do the same for participates */
1012 while (sc->participates != NULL) {
1013 nptr = sc->participates->next;
1014 free(sc->participates);
1015 sc->participates = nptr;
1017 while (sc->ignet_push_shares != NULL) {
1018 mptr = sc->ignet_push_shares->next;
1019 free(sc->ignet_push_shares);
1020 sc->ignet_push_shares = mptr;
1027 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1031 namelist *nptr = NULL;
1032 maplist *mptr = NULL;
1035 fp = fopen(filename, "w");
1037 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1038 filename, strerror(errno));
1039 free_spoolcontrol_struct(scc);
1042 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1044 /* Write out the listrecps while freeing from memory at the
1045 * same time. Am I clever or what? :)
1047 while (sc->listrecps != NULL) {
1048 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1049 nptr = sc->listrecps->next;
1050 free(sc->listrecps);
1051 sc->listrecps = nptr;
1053 /* Do the same for digestrecps */
1054 while (sc->digestrecps != NULL) {
1055 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1056 nptr = sc->digestrecps->next;
1057 free(sc->digestrecps);
1058 sc->digestrecps = nptr;
1060 /* Do the same for participates */
1061 while (sc->participates != NULL) {
1062 fprintf(fp, "participate|%s\n", sc->participates->name);
1063 nptr = sc->participates->next;
1064 free(sc->participates);
1065 sc->participates = nptr;
1067 while (sc->ignet_push_shares != NULL) {
1068 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1069 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1070 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1073 mptr = sc->ignet_push_shares->next;
1074 free(sc->ignet_push_shares);
1075 sc->ignet_push_shares = mptr;
1077 if (sc->misc != NULL) {
1078 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1088 int is_recipient(SpoolControl *sc, const char *Name)
1094 nptr = sc->listrecps;
1095 while (nptr != NULL) {
1096 if (strncmp(Name, nptr->name, len)==0)
1100 /* Do the same for digestrecps */
1101 nptr = sc->digestrecps;
1102 while (nptr != NULL) {
1103 if (strncmp(Name, nptr->name, len)==0)
1107 /* Do the same for participates */
1108 nptr = sc->participates;
1109 while (nptr != NULL) {
1110 if (strncmp(Name, nptr->name, len)==0)
1119 * Batch up and send all outbound traffic from the current room
1121 void network_spoolout_room(char *room_to_spool) {
1123 char filename[PATH_MAX];
1128 * If the room doesn't exist, don't try to perform its networking tasks.
1129 * Normally this should never happen, but once in a while maybe a room gets
1130 * queued for networking and then deleted before it can happen.
1132 if (getroom(&CC->room, room_to_spool) != 0) {
1133 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1137 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1138 begin_critical_section(S_NETCONFIGS);
1140 /* Only do net processing for rooms that have netconfigs */
1141 if (!read_spoolcontrol_file(&sc, filename))
1143 end_critical_section(S_NETCONFIGS);
1146 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1148 /* If there are digest recipients, we have to build a digest */
1149 if (sc->digestrecps != NULL) {
1150 sc->digestfp = tmpfile();
1151 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1154 /* Do something useful */
1155 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1156 network_spool_msg, sc);
1158 /* If we wrote a digest, deliver it and then close it */
1159 snprintf(buf, sizeof buf, "room_%s@%s",
1160 CC->room.QRname, config.c_fqdn);
1161 for (i=0; buf[i]; ++i) {
1162 buf[i] = tolower(buf[i]);
1163 if (isspace(buf[i])) buf[i] = '_';
1165 if (sc->digestfp != NULL) {
1166 fprintf(sc->digestfp, " -----------------------------------"
1167 "------------------------------------"
1169 "You are subscribed to the '%s' "
1171 "To post to the list: %s\n",
1172 CC->room.QRname, buf
1174 network_deliver_digest(sc); /* deliver and close */
1177 /* Now rewrite the config file */
1178 writenfree_spoolcontrol_file (&sc, filename);
1179 end_critical_section(S_NETCONFIGS);
1185 * Send the *entire* contents of the current room to one specific network node,
1186 * ignoring anything we know about which messages have already undergone
1187 * network processing. This can be used to bring a new node into sync.
1189 int network_sync_to(char *target_node) {
1191 int num_spooled = 0;
1197 char filename[PATH_MAX];
1200 /* Grab the configuration line we're looking for */
1201 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1202 begin_critical_section(S_NETCONFIGS);
1203 fp = fopen(filename, "r");
1205 end_critical_section(S_NETCONFIGS);
1208 while (fgets(buf, sizeof buf, fp) != NULL) {
1209 buf[strlen(buf)-1] = 0;
1210 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1211 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1212 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1213 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1214 && (!strcasecmp(sc_node, target_node)) ) {
1217 /* Concise syntax because we don't need a full linked-list */
1218 memset(&sc, 0, sizeof(SpoolControl));
1219 sc.ignet_push_shares = (maplist *)
1220 malloc(sizeof(maplist));
1221 sc.ignet_push_shares->next = NULL;
1222 safestrncpy(sc.ignet_push_shares->remote_nodename,
1224 sizeof sc.ignet_push_shares->remote_nodename);
1225 safestrncpy(sc.ignet_push_shares->remote_roomname,
1227 sizeof sc.ignet_push_shares->remote_roomname);
1231 end_critical_section(S_NETCONFIGS);
1233 if (!found_node) return(-1);
1235 /* Send ALL messages */
1236 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1237 network_spool_msg, &sc);
1239 /* Concise cleanup because we know there's only one node in the sc */
1240 free(sc.ignet_push_shares);
1242 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1243 num_spooled, target_node);
1244 return(num_spooled);
1249 * Implements the NSYN command
1251 void cmd_nsyn(char *argbuf) {
1253 char target_node[256];
1255 if (CtdlAccessCheck(ac_aide)) return;
1257 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1258 num_spooled = network_sync_to(target_node);
1259 if (num_spooled >= 0) {
1260 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1263 cprintf("%d No such room/node share exists.\n",
1264 ERROR + ROOM_NOT_FOUND);
1271 * Batch up and send all outbound traffic from the current room
1273 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1274 struct RoomProcList *ptr;
1276 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1277 if (ptr == NULL) return;
1279 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1280 begin_critical_section(S_RPLIST);
1283 end_critical_section(S_RPLIST);
1286 void destroy_network_queue_room(void)
1288 struct RoomProcList *cur, *p;
1289 NetMap *nmcur, *nmp;
1292 begin_critical_section(S_RPLIST);
1300 end_critical_section(S_RPLIST);
1303 while (nmcur != NULL)
1310 if (working_ignetcfg != NULL)
1311 free (working_ignetcfg);
1312 working_ignetcfg = NULL;
1317 * Learn topology from path fields
1319 void network_learn_topology(char *node, char *path) {
1323 strcpy(nexthop, "");
1325 if (num_tokens(path, '!') < 3) return;
1326 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1327 if (!strcasecmp(nmptr->nodename, node)) {
1328 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1329 nmptr->lastcontact = time(NULL);
1335 /* If we got here then it's not in the map, so add it. */
1336 nmptr = (NetMap *) malloc(sizeof (NetMap));
1337 strcpy(nmptr->nodename, node);
1338 nmptr->lastcontact = time(NULL);
1339 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1340 nmptr->next = the_netmap;
1349 * Bounce a message back to the sender
1351 void network_bounce(struct CtdlMessage *msg, char *reason) {
1352 char *oldpath = NULL;
1354 char bouncesource[SIZ];
1355 char recipient[SIZ];
1356 struct recptypes *valid = NULL;
1357 char force_room[ROOMNAMELEN];
1358 static int serialnum = 0;
1361 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1363 if (msg == NULL) return;
1365 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1368 * Give it a fresh message ID
1370 if (msg->cm_fields['I'] != NULL) {
1371 free(msg->cm_fields['I']);
1373 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1374 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1375 msg->cm_fields['I'] = strdup(buf);
1378 * FIXME ... right now we're just sending a bounce; we really want to
1379 * include the text of the bounced message.
1381 if (msg->cm_fields['M'] != NULL) {
1382 free(msg->cm_fields['M']);
1384 msg->cm_fields['M'] = strdup(reason);
1385 msg->cm_format_type = 0;
1388 * Turn the message around
1390 if (msg->cm_fields['R'] == NULL) {
1391 free(msg->cm_fields['R']);
1394 if (msg->cm_fields['D'] == NULL) {
1395 free(msg->cm_fields['D']);
1398 snprintf(recipient, sizeof recipient, "%s@%s",
1399 msg->cm_fields['A'], msg->cm_fields['N']);
1401 if (msg->cm_fields['A'] == NULL) {
1402 free(msg->cm_fields['A']);
1405 if (msg->cm_fields['N'] == NULL) {
1406 free(msg->cm_fields['N']);
1409 if (msg->cm_fields['U'] == NULL) {
1410 free(msg->cm_fields['U']);
1413 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1414 msg->cm_fields['N'] = strdup(config.c_nodename);
1415 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1417 /* prepend our node to the path */
1418 if (msg->cm_fields['P'] != NULL) {
1419 oldpath = msg->cm_fields['P'];
1420 msg->cm_fields['P'] = NULL;
1423 oldpath = strdup("unknown_user");
1425 size = strlen(oldpath) + SIZ;
1426 msg->cm_fields['P'] = malloc(size);
1427 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1430 /* Now submit the message */
1431 valid = validate_recipients(recipient, NULL, 0);
1432 if (valid != NULL) if (valid->num_error != 0) {
1433 free_recipients(valid);
1436 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1437 strcpy(force_room, config.c_aideroom);
1440 strcpy(force_room, "");
1442 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1443 strcpy(force_room, config.c_aideroom);
1445 CtdlSubmitMsg(msg, valid, force_room, 0);
1448 if (valid != NULL) free_recipients(valid);
1449 CtdlFreeMessage(msg);
1450 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1457 * Process a buffer containing a single message from a single file
1458 * from the inbound queue
1460 void network_process_buffer(char *buffer, long size) {
1461 struct CtdlMessage *msg = NULL;
1464 struct recptypes *recp = NULL;
1465 char target_room[ROOMNAMELEN];
1466 struct ser_ret sermsg;
1467 char *oldpath = NULL;
1468 char filename[PATH_MAX];
1471 unsigned char firstbyte;
1472 unsigned char lastbyte;
1474 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1475 firstbyte = buffer[0];
1476 lastbyte = buffer[size-1];
1477 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1478 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1479 size, firstbyte, lastbyte);
1483 /* Set default target room to trash */
1484 strcpy(target_room, TWITROOM);
1486 /* Load the message into memory */
1487 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1488 memset(msg, 0, sizeof(struct CtdlMessage));
1489 msg->cm_magic = CTDLMESSAGE_MAGIC;
1490 msg->cm_anon_type = buffer[1];
1491 msg->cm_format_type = buffer[2];
1493 for (pos = 3; pos < size; ++pos) {
1494 field = buffer[pos];
1495 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1496 pos = pos + strlen(&buffer[(int)pos]);
1499 /* Check for message routing */
1500 if (msg->cm_fields['D'] != NULL) {
1501 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1503 /* route the message */
1504 strcpy(nexthop, "");
1505 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1506 /* prepend our node to the path */
1507 if (msg->cm_fields['P'] != NULL) {
1508 oldpath = msg->cm_fields['P'];
1509 msg->cm_fields['P'] = NULL;
1512 oldpath = strdup("unknown_user");
1514 size = strlen(oldpath) + SIZ;
1515 msg->cm_fields['P'] = malloc(size);
1516 snprintf(msg->cm_fields['P'], size, "%s!%s",
1517 config.c_nodename, oldpath);
1520 /* serialize the message */
1521 serialize_message(&sermsg, msg);
1524 if (IsEmptyStr(nexthop)) {
1525 strcpy(nexthop, msg->cm_fields['D']);
1532 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1533 fp = fopen(filename, "ab");
1540 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1543 CtdlFreeMessage(msg);
1547 else { /* invalid destination node name */
1550 "A message you sent could not be delivered due to an invalid destination node"
1551 " name. Please check the address and try sending the message again.\n");
1560 * Check to see if we already have a copy of this message, and
1561 * abort its processing if so. (We used to post a warning to Aide>
1562 * every time this happened, but the network is now so densely
1563 * connected that it's inevitable.)
1565 if (network_usetable(msg) != 0) {
1566 CtdlFreeMessage(msg);
1570 /* Learn network topology from the path */
1571 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1572 network_learn_topology(msg->cm_fields['N'],
1573 msg->cm_fields['P']);
1576 /* Is the sending node giving us a very persuasive suggestion about
1577 * which room this message should be saved in? If so, go with that.
1579 if (msg->cm_fields['C'] != NULL) {
1580 safestrncpy(target_room,
1581 msg->cm_fields['C'],
1582 sizeof target_room);
1585 /* Otherwise, does it have a recipient? If so, validate it... */
1586 else if (msg->cm_fields['R'] != NULL) {
1587 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1588 if (recp != NULL) if (recp->num_error != 0) {
1590 "A message you sent could not be delivered due to an invalid address.\n"
1591 "Please check the address and try sending the message again.\n");
1593 free_recipients(recp);
1596 strcpy(target_room, ""); /* no target room if mail */
1599 /* Our last shot at finding a home for this message is to see if
1600 * it has the O field (Originating room) set.
1602 else if (msg->cm_fields['O'] != NULL) {
1603 safestrncpy(target_room,
1604 msg->cm_fields['O'],
1605 sizeof target_room);
1608 /* Strip out fields that are only relevant during transit */
1609 if (msg->cm_fields['D'] != NULL) {
1610 free(msg->cm_fields['D']);
1611 msg->cm_fields['D'] = NULL;
1613 if (msg->cm_fields['C'] != NULL) {
1614 free(msg->cm_fields['C']);
1615 msg->cm_fields['C'] = NULL;
1618 /* save the message into a room */
1619 if (PerformNetprocHooks(msg, target_room) == 0) {
1620 msg->cm_flags = CM_SKIP_HOOKS;
1621 CtdlSubmitMsg(msg, recp, target_room, 0);
1623 CtdlFreeMessage(msg);
1624 free_recipients(recp);
1629 * Process a single message from a single file from the inbound queue
1631 void network_process_message(FILE *fp, long msgstart, long msgend) {
1636 hold_pos = ftell(fp);
1637 size = msgend - msgstart + 1;
1638 buffer = malloc(size);
1639 if (buffer != NULL) {
1640 fseek(fp, msgstart, SEEK_SET);
1641 fread(buffer, size, 1, fp);
1642 network_process_buffer(buffer, size);
1646 fseek(fp, hold_pos, SEEK_SET);
1651 * Process a single file from the inbound queue
1653 void network_process_file(char *filename) {
1655 long msgstart = (-1L);
1656 long msgend = (-1L);
1661 fp = fopen(filename, "rb");
1663 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1667 fseek(fp, 0L, SEEK_END);
1668 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1671 /* Look for messages in the data stream and break them out */
1672 while (ch = getc(fp), ch >= 0) {
1675 if (msgstart >= 0L) {
1676 msgend = msgcur - 1;
1677 network_process_message(fp, msgstart, msgend);
1685 msgend = msgcur - 1;
1686 if (msgstart >= 0L) {
1687 network_process_message(fp, msgstart, msgend);
1696 * Process anything in the inbound queue
1698 void network_do_spoolin(void) {
1701 struct stat statbuf;
1702 char filename[PATH_MAX];
1703 static time_t last_spoolin_mtime = 0L;
1706 * Check the spoolin directory's modification time. If it hasn't
1707 * been touched, we don't need to scan it.
1709 if (stat(ctdl_netin_dir, &statbuf)) return;
1710 if (statbuf.st_mtime == last_spoolin_mtime) {
1711 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1714 last_spoolin_mtime = statbuf.st_mtime;
1715 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1718 * Ok, there's something interesting in there, so scan it.
1720 dp = opendir(ctdl_netin_dir);
1721 if (dp == NULL) return;
1723 while (d = readdir(dp), d != NULL) {
1724 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1730 network_process_file(filename);
1738 * Delete any files in the outbound queue that were intended
1739 * to be sent to nodes which no longer exist.
1741 void network_purge_spoolout(void) {
1744 char filename[PATH_MAX];
1748 dp = opendir(ctdl_netout_dir);
1749 if (dp == NULL) return;
1751 while (d = readdir(dp), d != NULL) {
1752 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1760 strcpy(nexthop, "");
1761 i = is_valid_node(nexthop, NULL, d->d_name);
1763 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1774 * receive network spool from the remote system
1776 void receive_spool(int sock, char *remote_nodename) {
1777 long download_len = 0L;
1778 long bytes_received = 0L;
1779 long bytes_copied = 0L;
1781 static char pbuf[IGNET_PACKET_SIZE];
1782 char tempfilename[PATH_MAX];
1783 char filename[PATH_MAX];
1787 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
1788 if (sock_puts(sock, "NDOP") < 0) return;
1789 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1790 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1791 if (buf[0] != '2') {
1794 download_len = extract_long(&buf[4], 0);
1796 bytes_received = 0L;
1797 fp = fopen(tempfilename, "w");
1799 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1804 while (bytes_received < download_len) {
1806 * If shutting down we can exit here and unlink the temp file.
1807 * this shouldn't loose us any messages.
1809 if (CtdlThreadCheckStop())
1812 unlink(tempfilename);
1815 snprintf(buf, sizeof buf, "READ %ld|%ld",
1817 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1818 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1819 if (sock_puts(sock, buf) < 0) {
1821 unlink(tempfilename);
1824 if (sock_getln(sock, buf, sizeof buf) < 0) {
1826 unlink(tempfilename);
1829 if (buf[0] == '6') {
1830 plen = extract_long(&buf[4], 0);
1831 if (sock_read(sock, pbuf, plen, 1) < 0) {
1833 unlink(tempfilename);
1836 fwrite((char *) pbuf, plen, 1, fp);
1837 bytes_received = bytes_received + plen;
1842 /** Last chance for shutdown exit */
1843 if (CtdlThreadCheckStop())
1845 unlink(tempfilename);
1848 if (sock_puts(sock, "CLOS") < 0) {
1849 unlink(tempfilename);
1853 * From here on we must complete or messages will get lost
1855 if (sock_getln(sock, buf, sizeof buf) < 0) {
1856 unlink(tempfilename);
1859 if (download_len > 0) {
1860 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1862 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1864 /* Now copy the temp file to its permanent location.
1865 * (We copy instead of link because they may be on different filesystems)
1867 begin_critical_section(S_NETSPOOL);
1875 fp = fopen(tempfilename, "r");
1877 newfp = fopen(filename, "w");
1878 if (newfp != NULL) {
1880 while (bytes_copied < download_len) {
1881 plen = download_len - bytes_copied;
1882 if (plen > sizeof buf) {
1885 fread(buf, plen, 1, fp);
1886 fwrite(buf, plen, 1, newfp);
1887 bytes_copied += plen;
1893 end_critical_section(S_NETSPOOL);
1894 unlink(tempfilename);
1900 * transmit network spool to the remote system
1902 void transmit_spool(int sock, char *remote_nodename)
1907 long bytes_to_write, thisblock, bytes_written;
1911 if (sock_puts(sock, "NUOP") < 0) return;
1912 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1913 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1914 if (buf[0] != '2') {
1918 snprintf(sfname, sizeof sfname,
1922 fd = open(sfname, O_RDONLY);
1924 if (errno != ENOENT) {
1925 CtdlLogPrintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1931 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1932 bytes_to_write = plen;
1933 while (bytes_to_write > 0L) {
1934 /** Exit if shutting down */
1935 if (CtdlThreadCheckStop())
1941 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1942 if (sock_puts(sock, buf) < 0) {
1946 if (sock_getln(sock, buf, sizeof buf) < 0) {
1950 thisblock = atol(&buf[4]);
1951 if (buf[0] == '7') {
1952 if (sock_write(sock, pbuf,
1953 (int) thisblock) < 0) {
1957 bytes_to_write -= thisblock;
1958 bytes_written += thisblock;
1967 /** Last chance for shutdown exit */
1968 if(CtdlThreadCheckStop())
1971 if (sock_puts(sock, "UCLS 1") < 0) return;
1973 * From here on we must complete or messages will get lost
1975 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1976 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n",
1977 bytes_written, remote_nodename);
1978 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1979 if (buf[0] == '2') {
1980 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
1988 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1990 void network_poll_node(char *node, char *secret, char *host, char *port) {
1994 char connected_to[SIZ];
1996 if (network_talking_to(node, NTT_CHECK)) return;
1997 network_talking_to(node, NTT_ADD);
1998 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2000 sock = sock_connect(host, port, "tcp");
2002 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2003 network_talking_to(node, NTT_REMOVE);
2007 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2009 /* Read the server greeting */
2010 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
2011 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2013 /* Check that the remote is who we think it is and warn the Aide if not */
2014 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2015 if (strcmp(connected_to, node))
2017 snprintf (err_buf, sizeof(err_buf), "Connected to node \"%s\" but I was expecting to connect to node \"%s\".", connected_to, node);
2018 aide_message(err_buf, "IGNet Networking error.");
2021 /* Identify ourselves */
2022 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2023 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2024 if (sock_puts(sock, buf) <0) goto bail;
2025 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
2026 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2027 if (buf[0] != '2') goto bail;
2029 /* At this point we are authenticated. */
2030 if (!CtdlThreadCheckStop())
2031 receive_spool(sock, node);
2032 if (!CtdlThreadCheckStop())
2033 transmit_spool(sock, node);
2035 sock_puts(sock, "QUIT");
2036 bail: sock_close(sock);
2037 network_talking_to(node, NTT_REMOVE);
2043 * Poll other Citadel nodes and transfer inbound/outbound network data.
2044 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2045 * only nodes to which we have data to send.
2047 void network_poll_other_citadel_nodes(int full_poll) {
2055 char spoolfile[256];
2057 if (working_ignetcfg == NULL) {
2058 CtdlLogPrintf(CTDL_DEBUG, "No nodes defined - not polling\n");
2062 /* Use the string tokenizer to grab one line at a time */
2063 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2064 if(CtdlThreadCheckStop())
2066 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2067 extract_token(node, linebuf, 0, '|', sizeof node);
2068 extract_token(secret, linebuf, 1, '|', sizeof secret);
2069 extract_token(host, linebuf, 2, '|', sizeof host);
2070 extract_token(port, linebuf, 3, '|', sizeof port);
2071 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2072 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2080 if (access(spoolfile, R_OK) == 0) {
2085 network_poll_node(node, secret, host, port);
2096 * It's ok if these directories already exist. Just fail silently.
2098 void create_spool_dirs(void) {
2099 mkdir(ctdl_spool_dir, 0700);
2100 chown(ctdl_spool_dir, CTDLUID, (-1));
2101 mkdir(ctdl_netin_dir, 0700);
2102 chown(ctdl_netin_dir, CTDLUID, (-1));
2103 mkdir(ctdl_netout_dir, 0700);
2104 chown(ctdl_netout_dir, CTDLUID, (-1));
2112 * network_do_queue()
2114 * Run through the rooms doing various types of network stuff.
2116 void *network_do_queue(void *args) {
2117 static time_t last_run = 0L;
2118 struct RoomProcList *ptr;
2119 int full_processing = 1;
2120 struct CitContext networkerCC;
2122 /* Give the networker its own private CitContext */
2123 CtdlFillSystemContext(&networkerCC, "network");
2124 citthread_setspecific(MyConKey, (void *)&networkerCC );
2127 * Run the full set of processing tasks no more frequently
2128 * than once every n seconds
2130 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2131 full_processing = 0;
2132 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n", config.c_net_freq - (time(NULL)- last_run));
2136 * This is a simple concurrency check to make sure only one queue run
2137 * is done at a time. We could do this with a mutex, but since we
2138 * don't really require extremely fine granularity here, we'll do it
2139 * with a static variable instead.
2141 if (doing_queue) return NULL;
2144 /* Load the IGnet Configuration into memory */
2145 load_working_ignetcfg();
2148 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2149 * then we poll everyone. Otherwise we only poll nodes we have stuff
2152 network_poll_other_citadel_nodes(full_processing);
2155 * Load the network map and filter list into memory.
2158 filterlist = load_filter_list();
2161 * Go ahead and run the queue
2163 if (full_processing && !CtdlThreadCheckStop()) {
2164 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2165 ForEachRoom(network_queue_room, NULL);
2168 if (rplist != NULL) {
2169 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2170 while (rplist != NULL && !CtdlThreadCheckStop()) {
2171 char spoolroomname[ROOMNAMELEN];
2172 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2173 begin_critical_section(S_RPLIST);
2175 /* pop this record off the list */
2177 rplist = rplist->next;
2180 /* invalidate any duplicate entries to prevent double processing */
2181 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2182 if (!strcasecmp(ptr->name, spoolroomname)) {
2187 end_critical_section(S_RPLIST);
2188 if (spoolroomname[0] != 0) {
2189 network_spoolout_room(spoolroomname);
2194 /* If there is anything in the inbound queue, process it */
2195 if (!CtdlThreadCheckStop())
2196 network_do_spoolin();
2198 /* Save the network map back to disk */
2199 write_network_map();
2201 /* Free the filter list in memory */
2202 free_filter_list(filterlist);
2205 network_purge_spoolout();
2207 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2209 if (full_processing) {
2210 last_run = time(NULL);
2214 if (!CtdlThreadCheckStop()) // Only reschedule if system is not stopping
2215 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, time(NULL) + 60);
2217 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2223 * cmd_netp() - authenticate to the server as another Citadel node polling
2224 * for network traffic
2226 void cmd_netp(char *cmdbuf)
2237 extract_token(node, cmdbuf, 0, '|', sizeof node);
2238 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2241 CtdlLogPrintf(CTDL_WARNING, "Network node <%s> refused - spooling\n", node);
2242 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
2246 /* load the IGnet Configuration to check node validity */
2247 load_working_ignetcfg();
2248 v = is_valid_node(nexthop, secret, node);
2251 snprintf(err_buf, sizeof err_buf,
2252 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2253 node, CC->cs_host, CC->cs_addr
2255 CtdlLogPrintf(CTDL_WARNING, err_buf);
2256 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2257 aide_message(err_buf, "IGNet Networking.");
2261 if (strcasecmp(pass, secret)) {
2262 snprintf(err_buf, sizeof err_buf,
2263 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2264 CC->cs_host, CC->cs_addr, node
2266 CtdlLogPrintf(CTDL_WARNING, err_buf);
2267 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2268 aide_message(err_buf, "IGNet Networking.");
2272 if (network_talking_to(node, NTT_CHECK)) {
2273 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2274 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2278 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2279 network_talking_to(node, NTT_ADD);
2280 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2281 CC->net_node, CC->cs_host, CC->cs_addr
2283 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2287 int network_room_handler (struct ctdlroom *room)
2289 network_queue_room(room, NULL);
2295 * Module entry point
2297 CTDL_MODULE_INIT(network)
2301 create_spool_dirs();
2302 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2303 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2304 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2305 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2306 CtdlRegisterRoomHook(network_room_handler);
2307 CtdlRegisterCleanupHook(destroy_network_queue_room);
2310 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2311 /* return our Subversion id for the Log */