4 * This module handles shared rooms, inter-Citadel mail, and outbound
5 * mailing list processing.
7 * Copyright (c) 2000-2010 by the citadel.org team
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
24 * This is a fairly high-level type of critical section. It ensures that no
25 * two threads work on the netconfigs files at the same time. Since we do
26 * so many things inside these, here are the rules:
27 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
28 * 2. Do *not* perform any I/O with the client during these sections.
33 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
34 * requests that have not been confirmed will be deleted.
36 #define EXP 259200 /* three days */
48 #include <sys/types.h>
50 #if TIME_WITH_SYS_TIME
51 # include <sys/time.h>
55 # include <sys/time.h>
64 #include <libcitadel.h>
67 #include "citserver.h"
74 #include "internet_addressing.h"
75 #include "serv_network.h"
76 #include "clientsocket.h"
78 #include "citadel_dirs.h"
87 #include "ctdl_module.h"
91 /* Nonzero while we are doing network processing */
92 static int doing_queue = 0;
95 * When we do network processing, it's accomplished in two passes; one to
96 * gather a list of rooms and one to actually do them. It's ok that rplist
97 * is global; we have a mutex that keeps it safe.
99 struct RoomProcList *rplist = NULL;
102 * We build a map of network nodes during processing.
104 NetMap *the_netmap = NULL;
105 int netmap_changed = 0;
106 char *working_ignetcfg = NULL;
109 * Load or refresh the Citadel network (IGnet) configuration for this node.
111 void load_working_ignetcfg(void) {
115 cfg = CtdlGetSysConfig(IGNETCFG);
120 oldcfg = working_ignetcfg;
121 working_ignetcfg = cfg;
122 if (oldcfg != NULL) {
132 * Keep track of what messages to reject
134 FilterList *load_filter_list(void) {
135 char *serialized_list = NULL;
138 FilterList *newlist = NULL;
141 serialized_list = CtdlGetSysConfig(FILTERLIST);
142 if (serialized_list == NULL) return(NULL); /* if null, no entries */
144 /* Use the string tokenizer to grab one line at a time */
145 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
146 extract_token(buf, serialized_list, i, '\n', sizeof buf);
147 nptr = (FilterList *) malloc(sizeof(FilterList));
148 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
149 striplt(nptr->fl_user);
150 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
151 striplt(nptr->fl_room);
152 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
153 striplt(nptr->fl_node);
155 /* Cowardly refuse to add an any/any/any entry that would
156 * end up filtering every single message.
158 if (IsEmptyStr(nptr->fl_user) &&
159 IsEmptyStr(nptr->fl_room) &&
160 IsEmptyStr(nptr->fl_node)) {
164 nptr->next = newlist;
169 free(serialized_list);
174 void free_filter_list(FilterList *fl) {
175 if (fl == NULL) return;
176 free_filter_list(fl->next);
183 * Check the use table. This is a list of messages which have recently
184 * arrived on the system. It is maintained and queried to prevent the same
185 * message from being entered into the database multiple times if it happens
186 * to arrive multiple times by accident.
188 int network_usetable(struct CtdlMessage *msg) {
191 struct cdbdata *cdbut;
194 /* Bail out if we can't generate a message ID */
198 if (msg->cm_fields['I'] == NULL) {
201 if (IsEmptyStr(msg->cm_fields['I'])) {
205 /* Generate the message ID */
206 strcpy(msgid, msg->cm_fields['I']);
207 if (haschar(msgid, '@') == 0) {
209 if (msg->cm_fields['N'] != NULL) {
210 strcat(msgid, msg->cm_fields['N']);
217 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
220 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
224 /* If we got to this point, it's unique: add it. */
225 strcpy(ut.ut_msgid, msgid);
226 ut.ut_timestamp = time(NULL);
227 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
233 * Read the network map from its configuration file into memory.
235 void read_network_map(void) {
236 char *serialized_map = NULL;
241 serialized_map = CtdlGetSysConfig(IGNETMAP);
242 if (serialized_map == NULL) return; /* if null, no entries */
244 /* Use the string tokenizer to grab one line at a time */
245 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
246 extract_token(buf, serialized_map, i, '\n', sizeof buf);
247 nmptr = (NetMap *) malloc(sizeof(NetMap));
248 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
249 nmptr->lastcontact = extract_long(buf, 1);
250 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
251 nmptr->next = the_netmap;
255 free(serialized_map);
261 * Write the network map from memory back to the configuration file.
263 void write_network_map(void) {
264 char *serialized_map = NULL;
268 if (netmap_changed) {
269 serialized_map = strdup("");
271 if (the_netmap != NULL) {
272 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
273 serialized_map = realloc(serialized_map,
274 (strlen(serialized_map)+SIZ) );
275 if (!IsEmptyStr(nmptr->nodename)) {
276 snprintf(&serialized_map[strlen(serialized_map)],
280 (long)nmptr->lastcontact,
286 CtdlPutSysConfig(IGNETMAP, serialized_map);
287 free(serialized_map);
290 /* Now free the list */
291 while (the_netmap != NULL) {
292 nmptr = the_netmap->next;
302 * Check the network map and determine whether the supplied node name is
303 * valid. If it is not a neighbor node, supply the name of a neighbor node
304 * which is the next hop. If it *is* a neighbor node, we also fill in the
307 int is_valid_node(char *nexthop, char *secret, char *node) {
319 * First try the neighbor nodes
321 if (working_ignetcfg == NULL) {
322 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
323 if (nexthop != NULL) {
330 if (nexthop != NULL) {
334 /* Use the string tokenizer to grab one line at a time */
335 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
336 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
337 extract_token(buf, linebuf, 0, '|', sizeof buf);
338 if (!strcasecmp(buf, node)) {
339 if (nexthop != NULL) {
342 if (secret != NULL) {
343 extract_token(secret, linebuf, 1, '|', 256);
350 return(retval); /* yup, it's a direct neighbor */
354 * If we get to this point we have to see if we know the next hop
356 if (the_netmap != NULL) {
357 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
358 if (!strcasecmp(nmptr->nodename, node)) {
359 if (nexthop != NULL) {
360 strcpy(nexthop, nmptr->nexthop);
368 * If we get to this point, the supplied node name is bogus.
370 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
378 void cmd_gnet(char *argbuf) {
379 char filename[PATH_MAX];
383 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
384 /* users can edit the netconfigs for their own mailbox rooms */
386 else if (CtdlAccessCheck(ac_room_aide)) return;
388 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
389 cprintf("%d Network settings for room #%ld <%s>\n",
391 CC->room.QRnumber, CC->room.QRname);
393 fp = fopen(filename, "r");
395 while (fgets(buf, sizeof buf, fp) != NULL) {
396 buf[strlen(buf)-1] = 0;
397 cprintf("%s\n", buf);
406 void cmd_snet(char *argbuf) {
407 char tempfilename[PATH_MAX];
408 char filename[PATH_MAX];
414 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
415 /* users can edit the netconfigs for their own mailbox rooms */
417 else if (CtdlAccessCheck(ac_room_aide)) return;
419 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
420 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
422 fp = fopen(tempfilename, "w");
424 cprintf("%d Cannot open %s: %s\n",
425 ERROR + INTERNAL_ERROR,
430 cprintf("%d %s\n", SEND_LISTING, tempfilename);
431 while (client_getln(buf, sizeof buf) >= 0 && strcmp(buf, "000")) {
432 fprintf(fp, "%s\n", buf);
436 /* Now copy the temp file to its permanent location.
437 * (We copy instead of link because they may be on different filesystems)
439 begin_critical_section(S_NETCONFIGS);
440 fp = fopen(tempfilename, "r");
442 newfp = fopen(filename, "w");
444 while (fgets(buf, sizeof buf, fp) != NULL) {
445 fprintf(newfp, "%s", buf);
451 end_critical_section(S_NETCONFIGS);
452 unlink(tempfilename);
457 * Deliver digest messages
459 void network_deliver_digest(SpoolControl *sc) {
462 struct CtdlMessage *msg = NULL;
465 size_t recps_len = SIZ;
467 struct recptypes *valid;
471 if (sc->num_msgs_spooled < 1) {
472 fclose(sc->digestfp);
477 msg = malloc(sizeof(struct CtdlMessage));
478 memset(msg, 0, sizeof(struct CtdlMessage));
479 msg->cm_magic = CTDLMESSAGE_MAGIC;
480 msg->cm_format_type = FMT_RFC822;
481 msg->cm_anon_type = MES_NORMAL;
483 sprintf(buf, "%ld", time(NULL));
484 msg->cm_fields['T'] = strdup(buf);
485 msg->cm_fields['A'] = strdup(CC->room.QRname);
486 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
487 msg->cm_fields['U'] = strdup(buf);
488 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
489 for (i=0; buf[i]; ++i) {
490 if (isspace(buf[i])) buf[i]='_';
491 buf[i] = tolower(buf[i]);
493 msg->cm_fields['F'] = strdup(buf);
494 msg->cm_fields['R'] = strdup(buf);
496 /* Set the 'List-ID' header */
497 msg->cm_fields['L'] = malloc(1024);
498 snprintf(msg->cm_fields['L'], 1024,
499 "%s <%ld.list-id.%s>",
506 * Go fetch the contents of the digest
508 fseek(sc->digestfp, 0L, SEEK_END);
509 msglen = ftell(sc->digestfp);
511 msg->cm_fields['M'] = malloc(msglen + 1);
512 fseek(sc->digestfp, 0L, SEEK_SET);
513 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
514 msg->cm_fields['M'][siz] = '\0';
516 fclose(sc->digestfp);
519 /* Now generate the delivery instructions */
522 * Figure out how big a buffer we need to allocate
524 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
525 recps_len = recps_len + strlen(nptr->name) + 2;
528 recps = malloc(recps_len);
531 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
538 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
539 if (nptr != sc->digestrecps) {
542 strcat(recps, nptr->name);
545 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
546 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
548 /* Now submit the message */
549 valid = validate_recipients(recps, NULL, 0);
552 valid->bounce_to = strdup(bounce_to);
553 valid->envelope_from = strdup(bounce_to);
554 CtdlSubmitMsg(msg, valid, NULL, 0);
556 CtdlFreeMessage(msg);
557 free_recipients(valid);
562 * Deliver list messages to everyone on the list ... efficiently
564 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
566 size_t recps_len = SIZ;
567 struct recptypes *valid;
571 /* Don't do this if there were no recipients! */
572 if (sc->listrecps == NULL) return;
574 /* Now generate the delivery instructions */
577 * Figure out how big a buffer we need to allocate
579 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
580 recps_len = recps_len + strlen(nptr->name) + 2;
583 recps = malloc(recps_len);
586 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
593 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
594 if (nptr != sc->listrecps) {
597 strcat(recps, nptr->name);
600 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
601 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
603 /* Now submit the message */
604 valid = validate_recipients(recps, NULL, 0);
607 valid->bounce_to = strdup(bounce_to);
608 valid->envelope_from = strdup(bounce_to);
609 CtdlSubmitMsg(msg, valid, NULL, 0);
610 free_recipients(valid);
612 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
619 * Spools out one message from the list.
621 void network_spool_msg(long msgnum, void *userdata) {
624 char *newpath = NULL;
625 size_t instr_len = SIZ;
626 struct CtdlMessage *msg = NULL;
629 struct ser_ret sermsg;
631 char filename[PATH_MAX];
635 int delete_after_send = 0; /* Set to 1 to delete after spooling */
636 int ok_to_participate = 0;
637 struct recptypes *valid;
639 sc = (SpoolControl *)userdata;
642 * Process mailing list recipients
645 if (sc->listrecps != NULL) {
646 /* Fetch the message. We're going to need to modify it
647 * in order to insert the [list name] in it, etc.
649 msg = CtdlFetchMessage(msgnum, 1);
652 /* Set the 'List-ID' header */
653 if (msg->cm_fields['L'] != NULL) {
654 free(msg->cm_fields['L']);
656 msg->cm_fields['L'] = malloc(1024);
657 snprintf(msg->cm_fields['L'], 1024,
658 "%s <%ld.list-id.%s>",
664 /* Prepend "[List name]" to the subject */
665 if (msg->cm_fields['U'] == NULL) {
666 msg->cm_fields['U'] = strdup("(no subject)");
668 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
669 free(msg->cm_fields['U']);
670 msg->cm_fields['U'] = strdup(buf);
672 /* Set the recipient of the list message to the
673 * email address of the room itself.
674 * FIXME ... I want to be able to pick any address
676 if (msg->cm_fields['R'] != NULL) {
677 free(msg->cm_fields['R']);
679 msg->cm_fields['R'] = malloc(256);
680 snprintf(msg->cm_fields['R'], 256,
681 "room_%s@%s", CC->room.QRname,
683 for (i=0; msg->cm_fields['R'][i]; ++i) {
684 if (isspace(msg->cm_fields['R'][i])) {
685 msg->cm_fields['R'][i] = '_';
689 /* Handle delivery */
690 network_deliver_list(msg, sc);
691 CtdlFreeMessage(msg);
696 * Process digest recipients
698 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
699 msg = CtdlFetchMessage(msgnum, 1);
701 fprintf(sc->digestfp, " -----------------------------------"
702 "------------------------------------"
704 fprintf(sc->digestfp, "From: ");
705 if (msg->cm_fields['A'] != NULL) {
706 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
708 if (msg->cm_fields['F'] != NULL) {
709 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
711 else if (msg->cm_fields['N'] != NULL) {
712 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
714 fprintf(sc->digestfp, "\n");
715 if (msg->cm_fields['U'] != NULL) {
716 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
719 CC->redirect_buffer = malloc(SIZ);
720 CC->redirect_len = 0;
721 CC->redirect_alloc = SIZ;
723 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
724 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
726 striplt(CC->redirect_buffer);
727 fprintf(sc->digestfp, "\n%s\n", CC->redirect_buffer);
729 free(CC->redirect_buffer);
730 CC->redirect_buffer = NULL;
731 CC->redirect_len = 0;
732 CC->redirect_alloc = 0;
734 sc->num_msgs_spooled += 1;
740 * Process client-side list participations for this room
743 if (sc->participates != NULL) {
744 msg = CtdlFetchMessage(msgnum, 1);
747 /* Only send messages which originated on our own Citadel
748 * network, otherwise we'll end up sending the remote
749 * mailing list's messages back to it, which is rude...
751 ok_to_participate = 0;
752 if (msg->cm_fields['N'] != NULL) {
753 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
754 ok_to_participate = 1;
756 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
757 ok_to_participate = 1;
760 if (ok_to_participate) {
761 if (msg->cm_fields['F'] != NULL) {
762 free(msg->cm_fields['F']);
764 msg->cm_fields['F'] = malloc(SIZ);
765 /* Replace the Internet email address of the actual
766 * author with the email address of the room itself,
767 * so the remote listserv doesn't reject us.
768 * FIXME ... I want to be able to pick any address
770 snprintf(msg->cm_fields['F'], SIZ,
771 "room_%s@%s", CC->room.QRname,
773 for (i=0; msg->cm_fields['F'][i]; ++i) {
774 if (isspace(msg->cm_fields['F'][i])) {
775 msg->cm_fields['F'][i] = '_';
780 * Figure out how big a buffer we need to allocate
782 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
784 if (msg->cm_fields['R'] == NULL) {
785 free(msg->cm_fields['R']);
787 msg->cm_fields['R'] = strdup(nptr->name);
789 valid = validate_recipients(nptr->name, NULL, 0);
790 CtdlSubmitMsg(msg, valid, "", 0);
791 free_recipients(valid);
795 CtdlFreeMessage(msg);
800 * Process IGnet push shares
802 msg = CtdlFetchMessage(msgnum, 1);
806 /* Prepend our node name to the Path field whenever
807 * sending a message to another IGnet node
809 if (msg->cm_fields['P'] == NULL) {
810 msg->cm_fields['P'] = strdup("username");
812 newpath_len = strlen(msg->cm_fields['P']) +
813 strlen(config.c_nodename) + 2;
814 newpath = malloc(newpath_len);
815 snprintf(newpath, newpath_len, "%s!%s",
816 config.c_nodename, msg->cm_fields['P']);
817 free(msg->cm_fields['P']);
818 msg->cm_fields['P'] = newpath;
821 * Determine if this message is set to be deleted
822 * after sending out on the network
824 if (msg->cm_fields['S'] != NULL) {
825 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
826 delete_after_send = 1;
830 /* Now send it to every node */
831 if (sc->ignet_push_shares != NULL)
832 for (mptr = sc->ignet_push_shares; mptr != NULL;
837 /* Check for valid node name */
838 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
839 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
843 /* Check for split horizon */
844 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
845 bang = num_tokens(msg->cm_fields['P'], '!');
846 if (bang > 1) for (i=0; i<(bang-1); ++i) {
847 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
848 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
849 buf, mptr->remote_nodename) ;
850 if (!strcasecmp(buf, mptr->remote_nodename)) {
852 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
853 mptr->remote_nodename);
856 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
860 /* Send the message */
864 * Force the message to appear in the correct room
865 * on the far end by setting the C field correctly
867 if (msg->cm_fields['C'] != NULL) {
868 free(msg->cm_fields['C']);
870 if (!IsEmptyStr(mptr->remote_roomname)) {
871 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
874 msg->cm_fields['C'] = strdup(CC->room.QRname);
877 /* serialize it for transmission */
878 serialize_message(&sermsg, msg);
879 if (sermsg.len > 0) {
881 /* write it to the spool file */
882 snprintf(filename, sizeof filename,"%s/%s",
884 mptr->remote_nodename);
885 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
886 fp = fopen(filename, "ab");
893 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
896 /* free the serialized version */
902 CtdlFreeMessage(msg);
905 /* update lastsent */
906 sc->lastsent = msgnum;
908 /* Delete this message if delete-after-send is set */
909 if (delete_after_send) {
910 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
916 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
922 char roomname[ROOMNAMELEN];
925 int skipthisline = 0;
926 namelist *nptr = NULL;
927 maplist *mptr = NULL;
930 fp = fopen(filename, "r");
934 sc = malloc(sizeof(SpoolControl));
935 memset(sc, 0, sizeof(SpoolControl));
938 while (fgets(buf, sizeof buf, fp) != NULL) {
939 buf[strlen(buf)-1] = 0;
941 extract_token(instr, buf, 0, '|', sizeof instr);
942 if (!strcasecmp(instr, "lastsent")) {
943 sc->lastsent = extract_long(buf, 1);
945 else if (!strcasecmp(instr, "listrecp")) {
947 malloc(sizeof(namelist));
948 nptr->next = sc->listrecps;
949 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
950 sc->listrecps = nptr;
952 else if (!strcasecmp(instr, "participate")) {
954 malloc(sizeof(namelist));
955 nptr->next = sc->participates;
956 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
957 sc->participates = nptr;
959 else if (!strcasecmp(instr, "digestrecp")) {
961 malloc(sizeof(namelist));
962 nptr->next = sc->digestrecps;
963 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
964 sc->digestrecps = nptr;
966 else if (!strcasecmp(instr, "ignet_push_share")) {
967 extract_token(nodename, buf, 1, '|', sizeof nodename);
968 extract_token(roomname, buf, 2, '|', sizeof roomname);
969 mptr = (maplist *) malloc(sizeof(maplist));
970 mptr->next = sc->ignet_push_shares;
971 strcpy(mptr->remote_nodename, nodename);
972 strcpy(mptr->remote_roomname, roomname);
973 sc->ignet_push_shares = mptr;
976 /* Preserve 'other' lines ... *unless* they happen to
977 * be subscribe/unsubscribe pendings with expired
981 if (!strncasecmp(buf, "subpending|", 11)) {
982 if (time(NULL) - extract_long(buf, 4) > EXP) {
986 if (!strncasecmp(buf, "unsubpending|", 13)) {
987 if (time(NULL) - extract_long(buf, 3) > EXP) {
992 if (skipthisline == 0) {
993 linesize = strlen(buf);
994 sc->misc = realloc(sc->misc,
995 (miscsize + linesize + 2) );
996 sprintf(&sc->misc[miscsize], "%s\n", buf);
997 miscsize = miscsize + linesize + 1;
1007 void free_spoolcontrol_struct(SpoolControl **scc)
1010 namelist *nptr = NULL;
1011 maplist *mptr = NULL;
1014 while (sc->listrecps != NULL) {
1015 nptr = sc->listrecps->next;
1016 free(sc->listrecps);
1017 sc->listrecps = nptr;
1019 /* Do the same for digestrecps */
1020 while (sc->digestrecps != NULL) {
1021 nptr = sc->digestrecps->next;
1022 free(sc->digestrecps);
1023 sc->digestrecps = nptr;
1025 /* Do the same for participates */
1026 while (sc->participates != NULL) {
1027 nptr = sc->participates->next;
1028 free(sc->participates);
1029 sc->participates = nptr;
1031 while (sc->ignet_push_shares != NULL) {
1032 mptr = sc->ignet_push_shares->next;
1033 free(sc->ignet_push_shares);
1034 sc->ignet_push_shares = mptr;
1041 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1045 namelist *nptr = NULL;
1046 maplist *mptr = NULL;
1049 fp = fopen(filename, "w");
1051 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1052 filename, strerror(errno));
1053 free_spoolcontrol_struct(scc);
1056 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1058 /* Write out the listrecps while freeing from memory at the
1059 * same time. Am I clever or what? :)
1061 while (sc->listrecps != NULL) {
1062 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1063 nptr = sc->listrecps->next;
1064 free(sc->listrecps);
1065 sc->listrecps = nptr;
1067 /* Do the same for digestrecps */
1068 while (sc->digestrecps != NULL) {
1069 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1070 nptr = sc->digestrecps->next;
1071 free(sc->digestrecps);
1072 sc->digestrecps = nptr;
1074 /* Do the same for participates */
1075 while (sc->participates != NULL) {
1076 fprintf(fp, "participate|%s\n", sc->participates->name);
1077 nptr = sc->participates->next;
1078 free(sc->participates);
1079 sc->participates = nptr;
1081 while (sc->ignet_push_shares != NULL) {
1082 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1083 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1084 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1087 mptr = sc->ignet_push_shares->next;
1088 free(sc->ignet_push_shares);
1089 sc->ignet_push_shares = mptr;
1091 if (sc->misc != NULL) {
1092 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1102 int is_recipient(SpoolControl *sc, const char *Name)
1108 nptr = sc->listrecps;
1109 while (nptr != NULL) {
1110 if (strncmp(Name, nptr->name, len)==0)
1114 /* Do the same for digestrecps */
1115 nptr = sc->digestrecps;
1116 while (nptr != NULL) {
1117 if (strncmp(Name, nptr->name, len)==0)
1121 /* Do the same for participates */
1122 nptr = sc->participates;
1123 while (nptr != NULL) {
1124 if (strncmp(Name, nptr->name, len)==0)
1133 * Batch up and send all outbound traffic from the current room
1135 void network_spoolout_room(char *room_to_spool) {
1137 char filename[PATH_MAX];
1142 * If the room doesn't exist, don't try to perform its networking tasks.
1143 * Normally this should never happen, but once in a while maybe a room gets
1144 * queued for networking and then deleted before it can happen.
1146 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1147 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1151 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1152 begin_critical_section(S_NETCONFIGS);
1154 /* Only do net processing for rooms that have netconfigs */
1155 if (!read_spoolcontrol_file(&sc, filename))
1157 end_critical_section(S_NETCONFIGS);
1160 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1162 /* If there are digest recipients, we have to build a digest */
1163 if (sc->digestrecps != NULL) {
1164 sc->digestfp = tmpfile();
1165 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1168 /* Do something useful */
1169 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1170 network_spool_msg, sc);
1172 /* If we wrote a digest, deliver it and then close it */
1173 snprintf(buf, sizeof buf, "room_%s@%s",
1174 CC->room.QRname, config.c_fqdn);
1175 for (i=0; buf[i]; ++i) {
1176 buf[i] = tolower(buf[i]);
1177 if (isspace(buf[i])) buf[i] = '_';
1179 if (sc->digestfp != NULL) {
1180 fprintf(sc->digestfp, " -----------------------------------"
1181 "------------------------------------"
1183 "You are subscribed to the '%s' "
1185 "To post to the list: %s\n",
1186 CC->room.QRname, buf
1188 network_deliver_digest(sc); /* deliver and close */
1191 /* Now rewrite the config file */
1192 writenfree_spoolcontrol_file (&sc, filename);
1193 end_critical_section(S_NETCONFIGS);
1199 * Send the *entire* contents of the current room to one specific network node,
1200 * ignoring anything we know about which messages have already undergone
1201 * network processing. This can be used to bring a new node into sync.
1203 int network_sync_to(char *target_node) {
1205 int num_spooled = 0;
1211 char filename[PATH_MAX];
1214 /* Grab the configuration line we're looking for */
1215 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1216 begin_critical_section(S_NETCONFIGS);
1217 fp = fopen(filename, "r");
1219 end_critical_section(S_NETCONFIGS);
1222 while (fgets(buf, sizeof buf, fp) != NULL) {
1223 buf[strlen(buf)-1] = 0;
1224 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1225 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1226 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1227 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1228 && (!strcasecmp(sc_node, target_node)) ) {
1231 /* Concise syntax because we don't need a full linked-list */
1232 memset(&sc, 0, sizeof(SpoolControl));
1233 sc.ignet_push_shares = (maplist *)
1234 malloc(sizeof(maplist));
1235 sc.ignet_push_shares->next = NULL;
1236 safestrncpy(sc.ignet_push_shares->remote_nodename,
1238 sizeof sc.ignet_push_shares->remote_nodename);
1239 safestrncpy(sc.ignet_push_shares->remote_roomname,
1241 sizeof sc.ignet_push_shares->remote_roomname);
1245 end_critical_section(S_NETCONFIGS);
1247 if (!found_node) return(-1);
1249 /* Send ALL messages */
1250 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1251 network_spool_msg, &sc);
1253 /* Concise cleanup because we know there's only one node in the sc */
1254 free(sc.ignet_push_shares);
1256 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1257 num_spooled, target_node);
1258 return(num_spooled);
1263 * Implements the NSYN command
1265 void cmd_nsyn(char *argbuf) {
1267 char target_node[256];
1269 if (CtdlAccessCheck(ac_aide)) return;
1271 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1272 num_spooled = network_sync_to(target_node);
1273 if (num_spooled >= 0) {
1274 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1277 cprintf("%d No such room/node share exists.\n",
1278 ERROR + ROOM_NOT_FOUND);
1285 * Batch up and send all outbound traffic from the current room
1287 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1288 struct RoomProcList *ptr;
1290 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1291 if (ptr == NULL) return;
1293 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1294 begin_critical_section(S_RPLIST);
1297 end_critical_section(S_RPLIST);
1300 void destroy_network_queue_room(void)
1302 struct RoomProcList *cur, *p;
1303 NetMap *nmcur, *nmp;
1306 begin_critical_section(S_RPLIST);
1314 end_critical_section(S_RPLIST);
1317 while (nmcur != NULL)
1324 if (working_ignetcfg != NULL)
1325 free (working_ignetcfg);
1326 working_ignetcfg = NULL;
1331 * Learn topology from path fields
1333 void network_learn_topology(char *node, char *path) {
1337 strcpy(nexthop, "");
1339 if (num_tokens(path, '!') < 3) return;
1340 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1341 if (!strcasecmp(nmptr->nodename, node)) {
1342 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1343 nmptr->lastcontact = time(NULL);
1349 /* If we got here then it's not in the map, so add it. */
1350 nmptr = (NetMap *) malloc(sizeof (NetMap));
1351 strcpy(nmptr->nodename, node);
1352 nmptr->lastcontact = time(NULL);
1353 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1354 nmptr->next = the_netmap;
1363 * Bounce a message back to the sender
1365 void network_bounce(struct CtdlMessage *msg, char *reason) {
1366 char *oldpath = NULL;
1368 char bouncesource[SIZ];
1369 char recipient[SIZ];
1370 struct recptypes *valid = NULL;
1371 char force_room[ROOMNAMELEN];
1372 static int serialnum = 0;
1375 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1377 if (msg == NULL) return;
1379 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1382 * Give it a fresh message ID
1384 if (msg->cm_fields['I'] != NULL) {
1385 free(msg->cm_fields['I']);
1387 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1388 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1389 msg->cm_fields['I'] = strdup(buf);
1392 * FIXME ... right now we're just sending a bounce; we really want to
1393 * include the text of the bounced message.
1395 if (msg->cm_fields['M'] != NULL) {
1396 free(msg->cm_fields['M']);
1398 msg->cm_fields['M'] = strdup(reason);
1399 msg->cm_format_type = 0;
1402 * Turn the message around
1404 if (msg->cm_fields['R'] == NULL) {
1405 free(msg->cm_fields['R']);
1408 if (msg->cm_fields['D'] == NULL) {
1409 free(msg->cm_fields['D']);
1412 snprintf(recipient, sizeof recipient, "%s@%s",
1413 msg->cm_fields['A'], msg->cm_fields['N']);
1415 if (msg->cm_fields['A'] == NULL) {
1416 free(msg->cm_fields['A']);
1419 if (msg->cm_fields['N'] == NULL) {
1420 free(msg->cm_fields['N']);
1423 if (msg->cm_fields['U'] == NULL) {
1424 free(msg->cm_fields['U']);
1427 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1428 msg->cm_fields['N'] = strdup(config.c_nodename);
1429 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1431 /* prepend our node to the path */
1432 if (msg->cm_fields['P'] != NULL) {
1433 oldpath = msg->cm_fields['P'];
1434 msg->cm_fields['P'] = NULL;
1437 oldpath = strdup("unknown_user");
1439 size = strlen(oldpath) + SIZ;
1440 msg->cm_fields['P'] = malloc(size);
1441 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1444 /* Now submit the message */
1445 valid = validate_recipients(recipient, NULL, 0);
1446 if (valid != NULL) if (valid->num_error != 0) {
1447 free_recipients(valid);
1450 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1451 strcpy(force_room, config.c_aideroom);
1454 strcpy(force_room, "");
1456 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1457 strcpy(force_room, config.c_aideroom);
1459 CtdlSubmitMsg(msg, valid, force_room, 0);
1462 if (valid != NULL) free_recipients(valid);
1463 CtdlFreeMessage(msg);
1464 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1471 * Process a buffer containing a single message from a single file
1472 * from the inbound queue
1474 void network_process_buffer(char *buffer, long size) {
1475 struct CtdlMessage *msg = NULL;
1478 struct recptypes *recp = NULL;
1479 char target_room[ROOMNAMELEN];
1480 struct ser_ret sermsg;
1481 char *oldpath = NULL;
1482 char filename[PATH_MAX];
1485 unsigned char firstbyte;
1486 unsigned char lastbyte;
1488 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1490 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1491 firstbyte = buffer[0];
1492 lastbyte = buffer[size-1];
1493 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1494 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1495 size, firstbyte, lastbyte);
1499 /* Set default target room to trash */
1500 strcpy(target_room, TWITROOM);
1502 /* Load the message into memory */
1503 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1504 memset(msg, 0, sizeof(struct CtdlMessage));
1505 msg->cm_magic = CTDLMESSAGE_MAGIC;
1506 msg->cm_anon_type = buffer[1];
1507 msg->cm_format_type = buffer[2];
1509 for (pos = 3; pos < size; ++pos) {
1510 field = buffer[pos];
1511 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1512 pos = pos + strlen(&buffer[(int)pos]);
1515 /* Check for message routing */
1516 if (msg->cm_fields['D'] != NULL) {
1517 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1519 /* route the message */
1520 strcpy(nexthop, "");
1521 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1522 /* prepend our node to the path */
1523 if (msg->cm_fields['P'] != NULL) {
1524 oldpath = msg->cm_fields['P'];
1525 msg->cm_fields['P'] = NULL;
1528 oldpath = strdup("unknown_user");
1530 size = strlen(oldpath) + SIZ;
1531 msg->cm_fields['P'] = malloc(size);
1532 snprintf(msg->cm_fields['P'], size, "%s!%s",
1533 config.c_nodename, oldpath);
1536 /* serialize the message */
1537 serialize_message(&sermsg, msg);
1540 if (IsEmptyStr(nexthop)) {
1541 strcpy(nexthop, msg->cm_fields['D']);
1548 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1549 fp = fopen(filename, "ab");
1556 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1559 CtdlFreeMessage(msg);
1563 else { /* invalid destination node name */
1566 "A message you sent could not be delivered due to an invalid destination node"
1567 " name. Please check the address and try sending the message again.\n");
1576 * Check to see if we already have a copy of this message, and
1577 * abort its processing if so. (We used to post a warning to Aide>
1578 * every time this happened, but the network is now so densely
1579 * connected that it's inevitable.)
1581 if (network_usetable(msg) != 0) {
1582 CtdlFreeMessage(msg);
1586 /* Learn network topology from the path */
1587 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1588 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1591 /* Is the sending node giving us a very persuasive suggestion about
1592 * which room this message should be saved in? If so, go with that.
1594 if (msg->cm_fields['C'] != NULL) {
1595 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1598 /* Otherwise, does it have a recipient? If so, validate it... */
1599 else if (msg->cm_fields['R'] != NULL) {
1600 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1601 if (recp != NULL) if (recp->num_error != 0) {
1603 "A message you sent could not be delivered due to an invalid address.\n"
1604 "Please check the address and try sending the message again.\n");
1606 free_recipients(recp);
1607 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1610 strcpy(target_room, ""); /* no target room if mail */
1613 /* Our last shot at finding a home for this message is to see if
1614 * it has the O field (Originating room) set.
1616 else if (msg->cm_fields['O'] != NULL) {
1617 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1620 /* Strip out fields that are only relevant during transit */
1621 if (msg->cm_fields['D'] != NULL) {
1622 free(msg->cm_fields['D']);
1623 msg->cm_fields['D'] = NULL;
1625 if (msg->cm_fields['C'] != NULL) {
1626 free(msg->cm_fields['C']);
1627 msg->cm_fields['C'] = NULL;
1630 /* save the message into a room */
1631 if (PerformNetprocHooks(msg, target_room) == 0) {
1632 msg->cm_flags = CM_SKIP_HOOKS;
1633 CtdlSubmitMsg(msg, recp, target_room, 0);
1635 CtdlFreeMessage(msg);
1636 free_recipients(recp);
1641 * Process a single message from a single file from the inbound queue
1643 void network_process_message(FILE *fp, long msgstart, long msgend) {
1648 hold_pos = ftell(fp);
1649 size = msgend - msgstart + 1;
1650 buffer = malloc(size);
1651 if (buffer != NULL) {
1652 fseek(fp, msgstart, SEEK_SET);
1653 if (fread(buffer, size, 1, fp) > 0) {
1654 network_process_buffer(buffer, size);
1659 fseek(fp, hold_pos, SEEK_SET);
1664 * Process a single file from the inbound queue
1666 void network_process_file(char *filename) {
1668 long msgstart = (-1L);
1669 long msgend = (-1L);
1674 fp = fopen(filename, "rb");
1676 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1680 fseek(fp, 0L, SEEK_END);
1681 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1684 /* Look for messages in the data stream and break them out */
1685 while (ch = getc(fp), ch >= 0) {
1688 if (msgstart >= 0L) {
1689 msgend = msgcur - 1;
1690 network_process_message(fp, msgstart, msgend);
1698 msgend = msgcur - 1;
1699 if (msgstart >= 0L) {
1700 network_process_message(fp, msgstart, msgend);
1709 * Process anything in the inbound queue
1711 void network_do_spoolin(void) {
1714 struct stat statbuf;
1715 char filename[PATH_MAX];
1716 static time_t last_spoolin_mtime = 0L;
1719 * Check the spoolin directory's modification time. If it hasn't
1720 * been touched, we don't need to scan it.
1722 if (stat(ctdl_netin_dir, &statbuf)) return;
1723 if (statbuf.st_mtime == last_spoolin_mtime) {
1724 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1727 last_spoolin_mtime = statbuf.st_mtime;
1728 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1731 * Ok, there's something interesting in there, so scan it.
1733 dp = opendir(ctdl_netin_dir);
1734 if (dp == NULL) return;
1736 while (d = readdir(dp), d != NULL) {
1737 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1743 network_process_file(filename);
1751 * Delete any files in the outbound queue that were intended
1752 * to be sent to nodes which no longer exist.
1754 void network_purge_spoolout(void) {
1757 char filename[PATH_MAX];
1761 dp = opendir(ctdl_netout_dir);
1762 if (dp == NULL) return;
1764 while (d = readdir(dp), d != NULL) {
1765 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1773 strcpy(nexthop, "");
1774 i = is_valid_node(nexthop, NULL, d->d_name);
1776 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1787 * receive network spool from the remote system
1789 void receive_spool(int sock, char *remote_nodename) {
1791 long download_len = 0L;
1792 long bytes_received = 0L;
1793 long bytes_copied = 0L;
1795 static char pbuf[IGNET_PACKET_SIZE];
1796 char tempfilename[PATH_MAX];
1797 char filename[PATH_MAX];
1801 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
1802 if (sock_puts(sock, "NDOP") < 0) return;
1803 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1804 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1805 if (buf[0] != '2') {
1808 download_len = extract_long(&buf[4], 0);
1810 bytes_received = 0L;
1811 fp = fopen(tempfilename, "w");
1813 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1818 while (bytes_received < download_len) {
1820 * If shutting down we can exit here and unlink the temp file.
1821 * this shouldn't loose us any messages.
1823 if (CtdlThreadCheckStop())
1826 unlink(tempfilename);
1829 snprintf(buf, sizeof buf, "READ %ld|%ld",
1831 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1832 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1833 if (sock_puts(sock, buf) < 0) {
1835 unlink(tempfilename);
1838 if (sock_getln(sock, buf, sizeof buf) < 0) {
1840 unlink(tempfilename);
1843 if (buf[0] == '6') {
1844 plen = extract_long(&buf[4], 0);
1845 if (sock_read(sock, pbuf, plen, 1) < 0) {
1847 unlink(tempfilename);
1850 fwrite((char *) pbuf, plen, 1, fp);
1851 bytes_received = bytes_received + plen;
1856 /** Last chance for shutdown exit */
1857 if (CtdlThreadCheckStop())
1859 unlink(tempfilename);
1862 if (sock_puts(sock, "CLOS") < 0) {
1863 unlink(tempfilename);
1867 * From here on we must complete or messages will get lost
1869 if (sock_getln(sock, buf, sizeof buf) < 0) {
1870 unlink(tempfilename);
1873 if (download_len > 0) {
1874 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1876 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1878 /* Now copy the temp file to its permanent location.
1879 * (We copy instead of link because they may be on different filesystems)
1881 begin_critical_section(S_NETSPOOL);
1889 fp = fopen(tempfilename, "r");
1891 newfp = fopen(filename, "w");
1892 if (newfp != NULL) {
1894 while (bytes_copied < download_len) {
1895 plen = download_len - bytes_copied;
1896 if (plen > sizeof buf) {
1899 siz = fread(buf, plen, 1, fp);
1900 fwrite(buf, siz, 1, newfp);
1901 bytes_copied += plen;
1907 end_critical_section(S_NETSPOOL);
1908 unlink(tempfilename);
1914 * transmit network spool to the remote system
1916 void transmit_spool(int sock, char *remote_nodename)
1921 long bytes_to_write, thisblock, bytes_written;
1925 if (sock_puts(sock, "NUOP") < 0) return;
1926 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1927 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1928 if (buf[0] != '2') {
1932 snprintf(sfname, sizeof sfname,
1936 fd = open(sfname, O_RDONLY);
1938 if (errno != ENOENT) {
1939 CtdlLogPrintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1945 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1946 bytes_to_write = plen;
1947 while (bytes_to_write > 0L) {
1948 /** Exit if shutting down */
1949 if (CtdlThreadCheckStop())
1955 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1956 if (sock_puts(sock, buf) < 0) {
1960 if (sock_getln(sock, buf, sizeof buf) < 0) {
1964 thisblock = atol(&buf[4]);
1965 if (buf[0] == '7') {
1966 if (sock_write(sock, pbuf,
1967 (int) thisblock) < 0) {
1971 bytes_to_write -= thisblock;
1972 bytes_written += thisblock;
1981 /** Last chance for shutdown exit */
1982 if(CtdlThreadCheckStop())
1985 if (sock_puts(sock, "UCLS 1") < 0) return;
1987 * From here on we must complete or messages will get lost
1989 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1990 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n",
1991 bytes_written, remote_nodename);
1992 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1993 if (buf[0] == '2') {
1994 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2002 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2004 void network_poll_node(char *node, char *secret, char *host, char *port) {
2008 char connected_to[SIZ];
2010 if (network_talking_to(node, NTT_CHECK)) return;
2011 network_talking_to(node, NTT_ADD);
2012 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2014 sock = sock_connect(host, port, "tcp");
2016 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2017 network_talking_to(node, NTT_REMOVE);
2021 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2023 /* Read the server greeting */
2024 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
2025 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2027 /* Check that the remote is who we think it is and warn the Aide if not */
2028 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2029 if (strcmp(connected_to, node))
2031 snprintf (err_buf, sizeof(err_buf), "Connected to node \"%s\" but I was expecting to connect to node \"%s\".", connected_to, node);
2032 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2033 CtdlAideMessage(err_buf, "Network error");
2036 /* We're talking to the correct node. Now identify ourselves. */
2037 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2038 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2039 if (sock_puts(sock, buf) <0) goto bail;
2040 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
2041 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2042 if (buf[0] != '2') goto bail;
2044 /* At this point we are authenticated. */
2045 if (!CtdlThreadCheckStop())
2046 receive_spool(sock, node);
2047 if (!CtdlThreadCheckStop())
2048 transmit_spool(sock, node);
2051 sock_puts(sock, "QUIT");
2052 bail: sock_close(sock);
2053 network_talking_to(node, NTT_REMOVE);
2059 * Poll other Citadel nodes and transfer inbound/outbound network data.
2060 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2061 * only nodes to which we have data to send.
2063 void network_poll_other_citadel_nodes(int full_poll) {
2071 char spoolfile[256];
2073 if (working_ignetcfg == NULL) {
2074 CtdlLogPrintf(CTDL_DEBUG, "No nodes defined - not polling\n");
2078 /* Use the string tokenizer to grab one line at a time */
2079 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2080 if(CtdlThreadCheckStop())
2082 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2083 extract_token(node, linebuf, 0, '|', sizeof node);
2084 extract_token(secret, linebuf, 1, '|', sizeof secret);
2085 extract_token(host, linebuf, 2, '|', sizeof host);
2086 extract_token(port, linebuf, 3, '|', sizeof port);
2087 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2088 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2096 if (access(spoolfile, R_OK) == 0) {
2101 network_poll_node(node, secret, host, port);
2112 * It's ok if these directories already exist. Just fail silently.
2114 void create_spool_dirs(void) {
2115 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2116 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2117 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2118 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2119 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2120 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2121 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2122 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2123 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2124 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2125 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2126 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2134 * network_do_queue()
2136 * Run through the rooms doing various types of network stuff.
2138 void *network_do_queue(void *args) {
2139 static time_t last_run = 0L;
2140 struct RoomProcList *ptr;
2141 int full_processing = 1;
2142 struct CitContext networkerCC;
2144 /* Give the networker its own private CitContext */
2145 CtdlFillSystemContext(&networkerCC, "network");
2146 citthread_setspecific(MyConKey, (void *)&networkerCC );
2149 * Run the full set of processing tasks no more frequently
2150 * than once every n seconds
2152 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2153 full_processing = 0;
2154 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n", config.c_net_freq - (time(NULL)- last_run));
2158 * This is a simple concurrency check to make sure only one queue run
2159 * is done at a time. We could do this with a mutex, but since we
2160 * don't really require extremely fine granularity here, we'll do it
2161 * with a static variable instead.
2163 if (doing_queue) return NULL;
2166 /* Load the IGnet Configuration into memory */
2167 load_working_ignetcfg();
2170 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2171 * then we poll everyone. Otherwise we only poll nodes we have stuff
2174 network_poll_other_citadel_nodes(full_processing);
2177 * Load the network map and filter list into memory.
2180 filterlist = load_filter_list();
2183 * Go ahead and run the queue
2185 if (full_processing && !CtdlThreadCheckStop()) {
2186 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2187 CtdlForEachRoom(network_queue_room, NULL);
2190 if (rplist != NULL) {
2191 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2192 while (rplist != NULL && !CtdlThreadCheckStop()) {
2193 char spoolroomname[ROOMNAMELEN];
2194 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2195 begin_critical_section(S_RPLIST);
2197 /* pop this record off the list */
2199 rplist = rplist->next;
2202 /* invalidate any duplicate entries to prevent double processing */
2203 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2204 if (!strcasecmp(ptr->name, spoolroomname)) {
2209 end_critical_section(S_RPLIST);
2210 if (spoolroomname[0] != 0) {
2211 network_spoolout_room(spoolroomname);
2216 /* If there is anything in the inbound queue, process it */
2217 if (!CtdlThreadCheckStop())
2218 network_do_spoolin();
2220 /* Save the network map back to disk */
2221 write_network_map();
2223 /* Free the filter list in memory */
2224 free_filter_list(filterlist);
2227 network_purge_spoolout();
2229 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2231 if (full_processing) {
2232 last_run = time(NULL);
2236 if (!CtdlThreadCheckStop()) // Only reschedule if system is not stopping
2237 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, time(NULL) + 60);
2239 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2245 * cmd_netp() - authenticate to the server as another Citadel node polling
2246 * for network traffic
2248 void cmd_netp(char *cmdbuf)
2259 extract_token(node, cmdbuf, 0, '|', sizeof node);
2260 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2263 CtdlLogPrintf(CTDL_WARNING, "Network node <%s> refused - spooling\n", node);
2264 cprintf("%d spooling - try again in a few minutes\n", ERROR + RESOURCE_BUSY);
2268 /* load the IGnet Configuration to check node validity */
2269 load_working_ignetcfg();
2270 v = is_valid_node(nexthop, secret, node);
2273 snprintf(err_buf, sizeof err_buf,
2274 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2275 node, CC->cs_host, CC->cs_addr
2277 CtdlLogPrintf(CTDL_WARNING, err_buf);
2278 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2279 CtdlAideMessage(err_buf, "IGNet Networking.");
2283 if (strcasecmp(pass, secret)) {
2284 snprintf(err_buf, sizeof err_buf,
2285 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2286 CC->cs_host, CC->cs_addr, node
2288 CtdlLogPrintf(CTDL_WARNING, err_buf);
2289 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2290 CtdlAideMessage(err_buf, "IGNet Networking.");
2294 if (network_talking_to(node, NTT_CHECK)) {
2295 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2296 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2300 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2301 network_talking_to(node, NTT_ADD);
2302 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2303 CC->net_node, CC->cs_host, CC->cs_addr
2305 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2309 int network_room_handler (struct ctdlroom *room)
2311 network_queue_room(room, NULL);
2317 * Module entry point
2319 CTDL_MODULE_INIT(network)
2323 create_spool_dirs();
2324 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2325 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2326 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2327 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2328 CtdlRegisterRoomHook(network_room_handler);
2329 CtdlRegisterCleanupHook(destroy_network_queue_room);
2332 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2333 /* return our Subversion id for the Log */