4 * This module handles shared rooms, inter-Citadel mail, and outbound
5 * mailing list processing.
7 * Copyright (C) 2000-2005 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;
456 if (sc->num_msgs_spooled < 1) {
457 fclose(sc->digestfp);
462 msg = malloc(sizeof(struct CtdlMessage));
463 memset(msg, 0, sizeof(struct CtdlMessage));
464 msg->cm_magic = CTDLMESSAGE_MAGIC;
465 msg->cm_format_type = FMT_RFC822;
466 msg->cm_anon_type = MES_NORMAL;
468 sprintf(buf, "%ld", time(NULL));
469 msg->cm_fields['T'] = strdup(buf);
470 msg->cm_fields['A'] = strdup(CC->room.QRname);
471 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
472 msg->cm_fields['U'] = strdup(buf);
473 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
474 for (i=0; buf[i]; ++i) {
475 if (isspace(buf[i])) buf[i]='_';
476 buf[i] = tolower(buf[i]);
478 msg->cm_fields['F'] = strdup(buf);
479 msg->cm_fields['R'] = strdup(buf);
482 * Go fetch the contents of the digest
484 fseek(sc->digestfp, 0L, SEEK_END);
485 msglen = ftell(sc->digestfp);
487 msg->cm_fields['M'] = malloc(msglen + 1);
488 fseek(sc->digestfp, 0L, SEEK_SET);
489 fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
490 msg->cm_fields['M'][msglen] = 0;
492 fclose(sc->digestfp);
495 /* Now generate the delivery instructions */
498 * Figure out how big a buffer we need to allocate
500 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
501 recps_len = recps_len + strlen(nptr->name) + 2;
504 recps = malloc(recps_len);
507 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
514 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
515 if (nptr != sc->digestrecps) {
518 strcat(recps, nptr->name);
521 /* Now submit the message */
522 valid = validate_recipients(recps, NULL, 0);
524 CtdlSubmitMsg(msg, valid, NULL, 0);
525 CtdlFreeMessage(msg);
526 free_recipients(valid);
531 * Deliver list messages to everyone on the list ... efficiently
533 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
535 size_t recps_len = SIZ;
536 struct recptypes *valid;
539 /* Don't do this if there were no recipients! */
540 if (sc->listrecps == NULL) return;
542 /* Now generate the delivery instructions */
545 * Figure out how big a buffer we need to allocate
547 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
548 recps_len = recps_len + strlen(nptr->name) + 2;
551 recps = malloc(recps_len);
554 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
561 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
562 if (nptr != sc->listrecps) {
565 strcat(recps, nptr->name);
568 /* Now submit the message */
569 valid = validate_recipients(recps, NULL, 0);
571 CtdlSubmitMsg(msg, valid, NULL, 0);
572 free_recipients(valid);
573 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
580 * Spools out one message from the list.
582 void network_spool_msg(long msgnum, void *userdata) {
585 char *newpath = NULL;
586 size_t instr_len = SIZ;
587 struct CtdlMessage *msg = NULL;
590 struct ser_ret sermsg;
592 char filename[PATH_MAX];
596 int delete_after_send = 0; /* Set to 1 to delete after spooling */
597 int ok_to_participate = 0;
598 struct recptypes *valid;
600 sc = (SpoolControl *)userdata;
603 * Process mailing list recipients
606 if (sc->listrecps != NULL) {
607 /* Fetch the message. We're going to need to modify it
608 * in order to insert the [list name] in it, etc.
610 msg = CtdlFetchMessage(msgnum, 1);
613 /* Prepend "[List name]" to the subject */
614 if (msg->cm_fields['U'] == NULL) {
615 msg->cm_fields['U'] = strdup("(no subject)");
617 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
618 free(msg->cm_fields['U']);
619 msg->cm_fields['U'] = strdup(buf);
621 /* Set the recipient of the list message to the
622 * email address of the room itself.
623 * FIXME ... I want to be able to pick any address
625 if (msg->cm_fields['R'] != NULL) {
626 free(msg->cm_fields['R']);
628 msg->cm_fields['R'] = malloc(256);
629 snprintf(msg->cm_fields['R'], 256,
630 "room_%s@%s", CC->room.QRname,
632 for (i=0; msg->cm_fields['R'][i]; ++i) {
633 if (isspace(msg->cm_fields['R'][i])) {
634 msg->cm_fields['R'][i] = '_';
638 /* Handle delivery */
639 network_deliver_list(msg, sc);
640 CtdlFreeMessage(msg);
645 * Process digest recipients
647 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
648 msg = CtdlFetchMessage(msgnum, 1);
650 fprintf(sc->digestfp, " -----------------------------------"
651 "------------------------------------"
653 fprintf(sc->digestfp, "From: ");
654 if (msg->cm_fields['A'] != NULL) {
655 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
657 if (msg->cm_fields['F'] != NULL) {
658 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
660 else if (msg->cm_fields['N'] != NULL) {
661 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
663 fprintf(sc->digestfp, "\n");
664 if (msg->cm_fields['U'] != NULL) {
665 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
668 CC->redirect_buffer = malloc(SIZ);
669 CC->redirect_len = 0;
670 CC->redirect_alloc = SIZ;
672 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
673 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
675 striplt(CC->redirect_buffer);
676 fprintf(sc->digestfp, "\n%s\n", CC->redirect_buffer);
678 free(CC->redirect_buffer);
679 CC->redirect_buffer = NULL;
680 CC->redirect_len = 0;
681 CC->redirect_alloc = 0;
683 sc->num_msgs_spooled += 1;
689 * Process client-side list participations for this room
692 if (sc->participates != NULL) {
693 msg = CtdlFetchMessage(msgnum, 1);
696 /* Only send messages which originated on our own Citadel
697 * network, otherwise we'll end up sending the remote
698 * mailing list's messages back to it, which is rude...
700 ok_to_participate = 0;
701 if (msg->cm_fields['N'] != NULL) {
702 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
703 ok_to_participate = 1;
705 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
706 ok_to_participate = 1;
709 if (ok_to_participate) {
710 if (msg->cm_fields['F'] != NULL) {
711 free(msg->cm_fields['F']);
713 msg->cm_fields['F'] = malloc(SIZ);
714 /* Replace the Internet email address of the actual
715 * author with the email address of the room itself,
716 * so the remote listserv doesn't reject us.
717 * FIXME ... I want to be able to pick any address
719 snprintf(msg->cm_fields['F'], SIZ,
720 "room_%s@%s", CC->room.QRname,
722 for (i=0; msg->cm_fields['F'][i]; ++i) {
723 if (isspace(msg->cm_fields['F'][i])) {
724 msg->cm_fields['F'][i] = '_';
729 * Figure out how big a buffer we need to allocate
731 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
733 if (msg->cm_fields['R'] == NULL) {
734 free(msg->cm_fields['R']);
736 msg->cm_fields['R'] = strdup(nptr->name);
738 valid = validate_recipients(nptr->name, NULL, 0);
739 CtdlSubmitMsg(msg, valid, "", 0);
740 free_recipients(valid);
744 CtdlFreeMessage(msg);
749 * Process IGnet push shares
751 msg = CtdlFetchMessage(msgnum, 1);
755 /* Prepend our node name to the Path field whenever
756 * sending a message to another IGnet node
758 if (msg->cm_fields['P'] == NULL) {
759 msg->cm_fields['P'] = strdup("username");
761 newpath_len = strlen(msg->cm_fields['P']) +
762 strlen(config.c_nodename) + 2;
763 newpath = malloc(newpath_len);
764 snprintf(newpath, newpath_len, "%s!%s",
765 config.c_nodename, msg->cm_fields['P']);
766 free(msg->cm_fields['P']);
767 msg->cm_fields['P'] = newpath;
770 * Determine if this message is set to be deleted
771 * after sending out on the network
773 if (msg->cm_fields['S'] != NULL) {
774 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
775 delete_after_send = 1;
779 /* Now send it to every node */
780 if (sc->ignet_push_shares != NULL)
781 for (mptr = sc->ignet_push_shares; mptr != NULL;
786 /* Check for valid node name */
787 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
788 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
792 /* Check for split horizon */
793 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
794 bang = num_tokens(msg->cm_fields['P'], '!');
795 if (bang > 1) for (i=0; i<(bang-1); ++i) {
796 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
797 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
798 buf, mptr->remote_nodename) ;
799 if (!strcasecmp(buf, mptr->remote_nodename)) {
801 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
802 mptr->remote_nodename);
805 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
809 /* Send the message */
813 * Force the message to appear in the correct room
814 * on the far end by setting the C field correctly
816 if (msg->cm_fields['C'] != NULL) {
817 free(msg->cm_fields['C']);
819 if (!IsEmptyStr(mptr->remote_roomname)) {
820 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
823 msg->cm_fields['C'] = strdup(CC->room.QRname);
826 /* serialize it for transmission */
827 serialize_message(&sermsg, msg);
828 if (sermsg.len > 0) {
830 /* write it to the spool file */
831 snprintf(filename, sizeof filename,"%s/%s",
833 mptr->remote_nodename);
834 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
835 fp = fopen(filename, "ab");
842 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
845 /* free the serialized version */
851 CtdlFreeMessage(msg);
854 /* update lastsent */
855 sc->lastsent = msgnum;
857 /* Delete this message if delete-after-send is set */
858 if (delete_after_send) {
859 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
865 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
871 char roomname[ROOMNAMELEN];
874 int skipthisline = 0;
875 namelist *nptr = NULL;
876 maplist *mptr = NULL;
879 fp = fopen(filename, "r");
883 sc = malloc(sizeof(SpoolControl));
884 memset(sc, 0, sizeof(SpoolControl));
887 while (fgets(buf, sizeof buf, fp) != NULL) {
888 buf[strlen(buf)-1] = 0;
890 extract_token(instr, buf, 0, '|', sizeof instr);
891 if (!strcasecmp(instr, "lastsent")) {
892 sc->lastsent = extract_long(buf, 1);
894 else if (!strcasecmp(instr, "listrecp")) {
896 malloc(sizeof(namelist));
897 nptr->next = sc->listrecps;
898 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
899 sc->listrecps = nptr;
901 else if (!strcasecmp(instr, "participate")) {
903 malloc(sizeof(namelist));
904 nptr->next = sc->participates;
905 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
906 sc->participates = nptr;
908 else if (!strcasecmp(instr, "digestrecp")) {
910 malloc(sizeof(namelist));
911 nptr->next = sc->digestrecps;
912 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
913 sc->digestrecps = nptr;
915 else if (!strcasecmp(instr, "ignet_push_share")) {
916 extract_token(nodename, buf, 1, '|', sizeof nodename);
917 extract_token(roomname, buf, 2, '|', sizeof roomname);
918 mptr = (maplist *) malloc(sizeof(maplist));
919 mptr->next = sc->ignet_push_shares;
920 strcpy(mptr->remote_nodename, nodename);
921 strcpy(mptr->remote_roomname, roomname);
922 sc->ignet_push_shares = mptr;
925 /* Preserve 'other' lines ... *unless* they happen to
926 * be subscribe/unsubscribe pendings with expired
930 if (!strncasecmp(buf, "subpending|", 11)) {
931 if (time(NULL) - extract_long(buf, 4) > EXP) {
935 if (!strncasecmp(buf, "unsubpending|", 13)) {
936 if (time(NULL) - extract_long(buf, 3) > EXP) {
941 if (skipthisline == 0) {
942 linesize = strlen(buf);
943 sc->misc = realloc(sc->misc,
944 (miscsize + linesize + 2) );
945 sprintf(&sc->misc[miscsize], "%s\n", buf);
946 miscsize = miscsize + linesize + 1;
956 void free_spoolcontrol_struct(SpoolControl **scc)
959 namelist *nptr = NULL;
960 maplist *mptr = NULL;
963 while (sc->listrecps != NULL) {
964 nptr = sc->listrecps->next;
966 sc->listrecps = nptr;
968 /* Do the same for digestrecps */
969 while (sc->digestrecps != NULL) {
970 nptr = sc->digestrecps->next;
971 free(sc->digestrecps);
972 sc->digestrecps = nptr;
974 /* Do the same for participates */
975 while (sc->participates != NULL) {
976 nptr = sc->participates->next;
977 free(sc->participates);
978 sc->participates = nptr;
980 while (sc->ignet_push_shares != NULL) {
981 mptr = sc->ignet_push_shares->next;
982 free(sc->ignet_push_shares);
983 sc->ignet_push_shares = mptr;
990 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
994 namelist *nptr = NULL;
995 maplist *mptr = NULL;
998 fp = fopen(filename, "w");
1000 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1001 filename, strerror(errno));
1002 free_spoolcontrol_struct(scc);
1005 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1007 /* Write out the listrecps while freeing from memory at the
1008 * same time. Am I clever or what? :)
1010 while (sc->listrecps != NULL) {
1011 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1012 nptr = sc->listrecps->next;
1013 free(sc->listrecps);
1014 sc->listrecps = nptr;
1016 /* Do the same for digestrecps */
1017 while (sc->digestrecps != NULL) {
1018 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1019 nptr = sc->digestrecps->next;
1020 free(sc->digestrecps);
1021 sc->digestrecps = nptr;
1023 /* Do the same for participates */
1024 while (sc->participates != NULL) {
1025 fprintf(fp, "participate|%s\n", sc->participates->name);
1026 nptr = sc->participates->next;
1027 free(sc->participates);
1028 sc->participates = nptr;
1030 while (sc->ignet_push_shares != NULL) {
1031 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1032 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1033 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1036 mptr = sc->ignet_push_shares->next;
1037 free(sc->ignet_push_shares);
1038 sc->ignet_push_shares = mptr;
1040 if (sc->misc != NULL) {
1041 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1051 int is_recipient(SpoolControl *sc, const char *Name)
1057 nptr = sc->listrecps;
1058 while (nptr != NULL) {
1059 if (strncmp(Name, nptr->name, len)==0)
1063 /* Do the same for digestrecps */
1064 nptr = sc->digestrecps;
1065 while (nptr != NULL) {
1066 if (strncmp(Name, nptr->name, len)==0)
1070 /* Do the same for participates */
1071 nptr = sc->participates;
1072 while (nptr != NULL) {
1073 if (strncmp(Name, nptr->name, len)==0)
1082 * Batch up and send all outbound traffic from the current room
1084 void network_spoolout_room(char *room_to_spool) {
1086 char filename[PATH_MAX];
1091 * If the room doesn't exist, don't try to perform its networking tasks.
1092 * Normally this should never happen, but once in a while maybe a room gets
1093 * queued for networking and then deleted before it can happen.
1095 if (getroom(&CC->room, room_to_spool) != 0) {
1096 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1100 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1101 begin_critical_section(S_NETCONFIGS);
1103 /* Only do net processing for rooms that have netconfigs */
1104 if (!read_spoolcontrol_file(&sc, filename))
1106 end_critical_section(S_NETCONFIGS);
1109 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1111 /* If there are digest recipients, we have to build a digest */
1112 if (sc->digestrecps != NULL) {
1113 sc->digestfp = tmpfile();
1114 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1117 /* Do something useful */
1118 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1119 network_spool_msg, sc);
1121 /* If we wrote a digest, deliver it and then close it */
1122 snprintf(buf, sizeof buf, "room_%s@%s",
1123 CC->room.QRname, config.c_fqdn);
1124 for (i=0; buf[i]; ++i) {
1125 buf[i] = tolower(buf[i]);
1126 if (isspace(buf[i])) buf[i] = '_';
1128 if (sc->digestfp != NULL) {
1129 fprintf(sc->digestfp, " -----------------------------------"
1130 "------------------------------------"
1132 "You are subscribed to the '%s' "
1134 "To post to the list: %s\n",
1135 CC->room.QRname, buf
1137 network_deliver_digest(sc); /* deliver and close */
1140 /* Now rewrite the config file */
1141 writenfree_spoolcontrol_file (&sc, filename);
1142 end_critical_section(S_NETCONFIGS);
1148 * Send the *entire* contents of the current room to one specific network node,
1149 * ignoring anything we know about which messages have already undergone
1150 * network processing. This can be used to bring a new node into sync.
1152 int network_sync_to(char *target_node) {
1154 int num_spooled = 0;
1160 char filename[PATH_MAX];
1163 /* Grab the configuration line we're looking for */
1164 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1165 begin_critical_section(S_NETCONFIGS);
1166 fp = fopen(filename, "r");
1168 end_critical_section(S_NETCONFIGS);
1171 while (fgets(buf, sizeof buf, fp) != NULL) {
1172 buf[strlen(buf)-1] = 0;
1173 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1174 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1175 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1176 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1177 && (!strcasecmp(sc_node, target_node)) ) {
1180 /* Concise syntax because we don't need a full linked-list */
1181 memset(&sc, 0, sizeof(SpoolControl));
1182 sc.ignet_push_shares = (maplist *)
1183 malloc(sizeof(maplist));
1184 sc.ignet_push_shares->next = NULL;
1185 safestrncpy(sc.ignet_push_shares->remote_nodename,
1187 sizeof sc.ignet_push_shares->remote_nodename);
1188 safestrncpy(sc.ignet_push_shares->remote_roomname,
1190 sizeof sc.ignet_push_shares->remote_roomname);
1194 end_critical_section(S_NETCONFIGS);
1196 if (!found_node) return(-1);
1198 /* Send ALL messages */
1199 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1200 network_spool_msg, &sc);
1202 /* Concise cleanup because we know there's only one node in the sc */
1203 free(sc.ignet_push_shares);
1205 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1206 num_spooled, target_node);
1207 return(num_spooled);
1212 * Implements the NSYN command
1214 void cmd_nsyn(char *argbuf) {
1216 char target_node[256];
1218 if (CtdlAccessCheck(ac_aide)) return;
1220 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1221 num_spooled = network_sync_to(target_node);
1222 if (num_spooled >= 0) {
1223 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1226 cprintf("%d No such room/node share exists.\n",
1227 ERROR + ROOM_NOT_FOUND);
1234 * Batch up and send all outbound traffic from the current room
1236 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1237 struct RoomProcList *ptr;
1239 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1240 if (ptr == NULL) return;
1242 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1243 begin_critical_section(S_RPLIST);
1246 end_critical_section(S_RPLIST);
1249 void destroy_network_queue_room(void)
1251 struct RoomProcList *cur, *p;
1252 NetMap *nmcur, *nmp;
1255 begin_critical_section(S_RPLIST);
1263 end_critical_section(S_RPLIST);
1266 while (nmcur != NULL)
1273 if (working_ignetcfg != NULL)
1274 free (working_ignetcfg);
1275 working_ignetcfg = NULL;
1280 * Learn topology from path fields
1282 void network_learn_topology(char *node, char *path) {
1286 strcpy(nexthop, "");
1288 if (num_tokens(path, '!') < 3) return;
1289 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1290 if (!strcasecmp(nmptr->nodename, node)) {
1291 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1292 nmptr->lastcontact = time(NULL);
1298 /* If we got here then it's not in the map, so add it. */
1299 nmptr = (NetMap *) malloc(sizeof (NetMap));
1300 strcpy(nmptr->nodename, node);
1301 nmptr->lastcontact = time(NULL);
1302 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1303 nmptr->next = the_netmap;
1312 * Bounce a message back to the sender
1314 void network_bounce(struct CtdlMessage *msg, char *reason) {
1315 char *oldpath = NULL;
1317 char bouncesource[SIZ];
1318 char recipient[SIZ];
1319 struct recptypes *valid = NULL;
1320 char force_room[ROOMNAMELEN];
1321 static int serialnum = 0;
1324 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1326 if (msg == NULL) return;
1328 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1331 * Give it a fresh message ID
1333 if (msg->cm_fields['I'] != NULL) {
1334 free(msg->cm_fields['I']);
1336 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1337 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1338 msg->cm_fields['I'] = strdup(buf);
1341 * FIXME ... right now we're just sending a bounce; we really want to
1342 * include the text of the bounced message.
1344 if (msg->cm_fields['M'] != NULL) {
1345 free(msg->cm_fields['M']);
1347 msg->cm_fields['M'] = strdup(reason);
1348 msg->cm_format_type = 0;
1351 * Turn the message around
1353 if (msg->cm_fields['R'] == NULL) {
1354 free(msg->cm_fields['R']);
1357 if (msg->cm_fields['D'] == NULL) {
1358 free(msg->cm_fields['D']);
1361 snprintf(recipient, sizeof recipient, "%s@%s",
1362 msg->cm_fields['A'], msg->cm_fields['N']);
1364 if (msg->cm_fields['A'] == NULL) {
1365 free(msg->cm_fields['A']);
1368 if (msg->cm_fields['N'] == NULL) {
1369 free(msg->cm_fields['N']);
1372 if (msg->cm_fields['U'] == NULL) {
1373 free(msg->cm_fields['U']);
1376 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1377 msg->cm_fields['N'] = strdup(config.c_nodename);
1378 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1380 /* prepend our node to the path */
1381 if (msg->cm_fields['P'] != NULL) {
1382 oldpath = msg->cm_fields['P'];
1383 msg->cm_fields['P'] = NULL;
1386 oldpath = strdup("unknown_user");
1388 size = strlen(oldpath) + SIZ;
1389 msg->cm_fields['P'] = malloc(size);
1390 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1393 /* Now submit the message */
1394 valid = validate_recipients(recipient, NULL, 0);
1395 if (valid != NULL) if (valid->num_error != 0) {
1396 free_recipients(valid);
1399 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1400 strcpy(force_room, config.c_aideroom);
1403 strcpy(force_room, "");
1405 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1406 strcpy(force_room, config.c_aideroom);
1408 CtdlSubmitMsg(msg, valid, force_room, 0);
1411 if (valid != NULL) free_recipients(valid);
1412 CtdlFreeMessage(msg);
1413 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1420 * Process a buffer containing a single message from a single file
1421 * from the inbound queue
1423 void network_process_buffer(char *buffer, long size) {
1424 struct CtdlMessage *msg = NULL;
1427 struct recptypes *recp = NULL;
1428 char target_room[ROOMNAMELEN];
1429 struct ser_ret sermsg;
1430 char *oldpath = NULL;
1431 char filename[PATH_MAX];
1434 unsigned char firstbyte;
1435 unsigned char lastbyte;
1437 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1438 firstbyte = buffer[0];
1439 lastbyte = buffer[size-1];
1440 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1441 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1442 size, firstbyte, lastbyte);
1446 /* Set default target room to trash */
1447 strcpy(target_room, TWITROOM);
1449 /* Load the message into memory */
1450 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1451 memset(msg, 0, sizeof(struct CtdlMessage));
1452 msg->cm_magic = CTDLMESSAGE_MAGIC;
1453 msg->cm_anon_type = buffer[1];
1454 msg->cm_format_type = buffer[2];
1456 for (pos = 3; pos < size; ++pos) {
1457 field = buffer[pos];
1458 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1459 pos = pos + strlen(&buffer[(int)pos]);
1462 /* Check for message routing */
1463 if (msg->cm_fields['D'] != NULL) {
1464 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1466 /* route the message */
1467 strcpy(nexthop, "");
1468 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1469 /* prepend our node to the path */
1470 if (msg->cm_fields['P'] != NULL) {
1471 oldpath = msg->cm_fields['P'];
1472 msg->cm_fields['P'] = NULL;
1475 oldpath = strdup("unknown_user");
1477 size = strlen(oldpath) + SIZ;
1478 msg->cm_fields['P'] = malloc(size);
1479 snprintf(msg->cm_fields['P'], size, "%s!%s",
1480 config.c_nodename, oldpath);
1483 /* serialize the message */
1484 serialize_message(&sermsg, msg);
1487 if (IsEmptyStr(nexthop)) {
1488 strcpy(nexthop, msg->cm_fields['D']);
1495 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1496 fp = fopen(filename, "ab");
1503 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1506 CtdlFreeMessage(msg);
1510 else { /* invalid destination node name */
1513 "A message you sent could not be delivered due to an invalid destination node"
1514 " name. Please check the address and try sending the message again.\n");
1523 * Check to see if we already have a copy of this message, and
1524 * abort its processing if so. (We used to post a warning to Aide>
1525 * every time this happened, but the network is now so densely
1526 * connected that it's inevitable.)
1528 if (network_usetable(msg) != 0) {
1529 CtdlFreeMessage(msg);
1533 /* Learn network topology from the path */
1534 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1535 network_learn_topology(msg->cm_fields['N'],
1536 msg->cm_fields['P']);
1539 /* Is the sending node giving us a very persuasive suggestion about
1540 * which room this message should be saved in? If so, go with that.
1542 if (msg->cm_fields['C'] != NULL) {
1543 safestrncpy(target_room,
1544 msg->cm_fields['C'],
1545 sizeof target_room);
1548 /* Otherwise, does it have a recipient? If so, validate it... */
1549 else if (msg->cm_fields['R'] != NULL) {
1550 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1551 if (recp != NULL) if (recp->num_error != 0) {
1553 "A message you sent could not be delivered due to an invalid address.\n"
1554 "Please check the address and try sending the message again.\n");
1556 free_recipients(recp);
1559 strcpy(target_room, ""); /* no target room if mail */
1562 /* Our last shot at finding a home for this message is to see if
1563 * it has the O field (Originating room) set.
1565 else if (msg->cm_fields['O'] != NULL) {
1566 safestrncpy(target_room,
1567 msg->cm_fields['O'],
1568 sizeof target_room);
1571 /* Strip out fields that are only relevant during transit */
1572 if (msg->cm_fields['D'] != NULL) {
1573 free(msg->cm_fields['D']);
1574 msg->cm_fields['D'] = NULL;
1576 if (msg->cm_fields['C'] != NULL) {
1577 free(msg->cm_fields['C']);
1578 msg->cm_fields['C'] = NULL;
1581 /* save the message into a room */
1582 if (PerformNetprocHooks(msg, target_room) == 0) {
1583 msg->cm_flags = CM_SKIP_HOOKS;
1584 CtdlSubmitMsg(msg, recp, target_room, 0);
1586 CtdlFreeMessage(msg);
1587 free_recipients(recp);
1592 * Process a single message from a single file from the inbound queue
1594 void network_process_message(FILE *fp, long msgstart, long msgend) {
1599 hold_pos = ftell(fp);
1600 size = msgend - msgstart + 1;
1601 buffer = malloc(size);
1602 if (buffer != NULL) {
1603 fseek(fp, msgstart, SEEK_SET);
1604 fread(buffer, size, 1, fp);
1605 network_process_buffer(buffer, size);
1609 fseek(fp, hold_pos, SEEK_SET);
1614 * Process a single file from the inbound queue
1616 void network_process_file(char *filename) {
1618 long msgstart = (-1L);
1619 long msgend = (-1L);
1624 fp = fopen(filename, "rb");
1626 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1630 fseek(fp, 0L, SEEK_END);
1631 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1634 /* Look for messages in the data stream and break them out */
1635 while (ch = getc(fp), ch >= 0) {
1638 if (msgstart >= 0L) {
1639 msgend = msgcur - 1;
1640 network_process_message(fp, msgstart, msgend);
1648 msgend = msgcur - 1;
1649 if (msgstart >= 0L) {
1650 network_process_message(fp, msgstart, msgend);
1659 * Process anything in the inbound queue
1661 void network_do_spoolin(void) {
1664 struct stat statbuf;
1665 char filename[PATH_MAX];
1666 static time_t last_spoolin_mtime = 0L;
1669 * Check the spoolin directory's modification time. If it hasn't
1670 * been touched, we don't need to scan it.
1672 if (stat(ctdl_netin_dir, &statbuf)) return;
1673 if (statbuf.st_mtime == last_spoolin_mtime) {
1674 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1677 last_spoolin_mtime = statbuf.st_mtime;
1678 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1681 * Ok, there's something interesting in there, so scan it.
1683 dp = opendir(ctdl_netin_dir);
1684 if (dp == NULL) return;
1686 while (d = readdir(dp), d != NULL) {
1687 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1693 network_process_file(filename);
1701 * Delete any files in the outbound queue that were intended
1702 * to be sent to nodes which no longer exist.
1704 void network_purge_spoolout(void) {
1707 char filename[PATH_MAX];
1711 dp = opendir(ctdl_netout_dir);
1712 if (dp == NULL) return;
1714 while (d = readdir(dp), d != NULL) {
1715 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1723 strcpy(nexthop, "");
1724 i = is_valid_node(nexthop, NULL, d->d_name);
1726 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1737 * receive network spool from the remote system
1739 void receive_spool(int sock, char *remote_nodename) {
1740 long download_len = 0L;
1741 long bytes_received = 0L;
1742 long bytes_copied = 0L;
1744 static char pbuf[IGNET_PACKET_SIZE];
1745 char tempfilename[PATH_MAX];
1746 char filename[PATH_MAX];
1750 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
1751 if (sock_puts(sock, "NDOP") < 0) return;
1752 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1753 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1754 if (buf[0] != '2') {
1757 download_len = extract_long(&buf[4], 0);
1759 bytes_received = 0L;
1760 fp = fopen(tempfilename, "w");
1762 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1767 while (bytes_received < download_len) {
1769 * If shutting down we can exit here and unlink the temp file.
1770 * this shouldn't loose us any messages.
1772 if (CtdlThreadCheckStop())
1775 unlink(tempfilename);
1778 snprintf(buf, sizeof buf, "READ %ld|%ld",
1780 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1781 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1782 if (sock_puts(sock, buf) < 0) {
1784 unlink(tempfilename);
1787 if (sock_getln(sock, buf, sizeof buf) < 0) {
1789 unlink(tempfilename);
1792 if (buf[0] == '6') {
1793 plen = extract_long(&buf[4], 0);
1794 if (sock_read(sock, pbuf, plen, 1) < 0) {
1796 unlink(tempfilename);
1799 fwrite((char *) pbuf, plen, 1, fp);
1800 bytes_received = bytes_received + plen;
1805 /** Last chance for shutdown exit */
1806 if (CtdlThreadCheckStop())
1808 unlink(tempfilename);
1811 if (sock_puts(sock, "CLOS") < 0) {
1812 unlink(tempfilename);
1816 * From here on we must complete or messages will get lost
1818 if (sock_getln(sock, buf, sizeof buf) < 0) {
1819 unlink(tempfilename);
1822 if (download_len > 0) {
1823 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1825 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1827 /* Now copy the temp file to its permanent location.
1828 * (We copy instead of link because they may be on different filesystems)
1830 begin_critical_section(S_NETSPOOL);
1838 fp = fopen(tempfilename, "r");
1840 newfp = fopen(filename, "w");
1841 if (newfp != NULL) {
1843 while (bytes_copied < download_len) {
1844 plen = download_len - bytes_copied;
1845 if (plen > sizeof buf) {
1848 fread(buf, plen, 1, fp);
1849 fwrite(buf, plen, 1, newfp);
1850 bytes_copied += plen;
1856 end_critical_section(S_NETSPOOL);
1857 unlink(tempfilename);
1863 * transmit network spool to the remote system
1865 void transmit_spool(int sock, char *remote_nodename)
1870 long bytes_to_write, thisblock, bytes_written;
1874 if (sock_puts(sock, "NUOP") < 0) return;
1875 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1876 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1877 if (buf[0] != '2') {
1881 snprintf(sfname, sizeof sfname,
1885 fd = open(sfname, O_RDONLY);
1887 if (errno != ENOENT) {
1888 CtdlLogPrintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1894 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1895 bytes_to_write = plen;
1896 while (bytes_to_write > 0L) {
1897 /** Exit if shutting down */
1898 if (CtdlThreadCheckStop())
1904 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1905 if (sock_puts(sock, buf) < 0) {
1909 if (sock_getln(sock, buf, sizeof buf) < 0) {
1913 thisblock = atol(&buf[4]);
1914 if (buf[0] == '7') {
1915 if (sock_write(sock, pbuf,
1916 (int) thisblock) < 0) {
1920 bytes_to_write -= thisblock;
1921 bytes_written += thisblock;
1930 /** Last chance for shutdown exit */
1931 if(CtdlThreadCheckStop())
1934 if (sock_puts(sock, "UCLS 1") < 0) return;
1936 * From here on we must complete or messages will get lost
1938 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1939 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n",
1940 bytes_written, remote_nodename);
1941 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1942 if (buf[0] == '2') {
1943 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
1951 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1953 void network_poll_node(char *node, char *secret, char *host, char *port) {
1957 char connected_to[SIZ];
1959 if (network_talking_to(node, NTT_CHECK)) return;
1960 network_talking_to(node, NTT_ADD);
1961 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
1963 sock = sock_connect(host, port, "tcp");
1965 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1966 network_talking_to(node, NTT_REMOVE);
1970 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
1972 /* Read the server greeting */
1973 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
1974 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
1976 /* Check that the remote is who we think it is and warn the Aide if not */
1977 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
1978 if (strcmp(connected_to, node))
1980 snprintf (err_buf, sizeof(err_buf), "Connected to node \"%s\" but I was expecting to connect to node \"%s\".", connected_to, node);
1981 aide_message(err_buf, "IGNet Networking error.");
1984 /* Identify ourselves */
1985 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1986 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1987 if (sock_puts(sock, buf) <0) goto bail;
1988 if (sock_getln(sock, buf, sizeof buf) < 0) goto bail;
1989 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
1990 if (buf[0] != '2') goto bail;
1992 /* At this point we are authenticated. */
1993 if (!CtdlThreadCheckStop())
1994 receive_spool(sock, node);
1995 if (!CtdlThreadCheckStop())
1996 transmit_spool(sock, node);
1998 sock_puts(sock, "QUIT");
1999 bail: sock_close(sock);
2000 network_talking_to(node, NTT_REMOVE);
2006 * Poll other Citadel nodes and transfer inbound/outbound network data.
2007 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2008 * only nodes to which we have data to send.
2010 void network_poll_other_citadel_nodes(int full_poll) {
2018 char spoolfile[256];
2020 if (working_ignetcfg == NULL) {
2021 CtdlLogPrintf(CTDL_DEBUG, "No nodes defined - not polling\n");
2025 /* Use the string tokenizer to grab one line at a time */
2026 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2027 if(CtdlThreadCheckStop())
2029 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2030 extract_token(node, linebuf, 0, '|', sizeof node);
2031 extract_token(secret, linebuf, 1, '|', sizeof secret);
2032 extract_token(host, linebuf, 2, '|', sizeof host);
2033 extract_token(port, linebuf, 3, '|', sizeof port);
2034 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2035 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2043 if (access(spoolfile, R_OK) == 0) {
2048 network_poll_node(node, secret, host, port);
2059 * It's ok if these directories already exist. Just fail silently.
2061 void create_spool_dirs(void) {
2062 mkdir(ctdl_spool_dir, 0700);
2063 chown(ctdl_spool_dir, CTDLUID, (-1));
2064 mkdir(ctdl_netin_dir, 0700);
2065 chown(ctdl_netin_dir, CTDLUID, (-1));
2066 mkdir(ctdl_netout_dir, 0700);
2067 chown(ctdl_netout_dir, CTDLUID, (-1));
2075 * network_do_queue()
2077 * Run through the rooms doing various types of network stuff.
2079 void *network_do_queue(void *args) {
2080 static time_t last_run = 0L;
2081 struct RoomProcList *ptr;
2082 int full_processing = 1;
2083 struct CitContext networkerCC;
2085 /* Give the networker its own private CitContext */
2086 CtdlFillPrivateContext(&networkerCC, "network");
2087 citthread_setspecific(MyConKey, (void *)&networkerCC );
2090 * Run the full set of processing tasks no more frequently
2091 * than once every n seconds
2093 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2094 full_processing = 0;
2095 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n", config.c_net_freq - (time(NULL)- last_run));
2099 * This is a simple concurrency check to make sure only one queue run
2100 * is done at a time. We could do this with a mutex, but since we
2101 * don't really require extremely fine granularity here, we'll do it
2102 * with a static variable instead.
2104 if (doing_queue) return NULL;
2107 /* Load the IGnet Configuration into memory */
2108 load_working_ignetcfg();
2111 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2112 * then we poll everyone. Otherwise we only poll nodes we have stuff
2115 network_poll_other_citadel_nodes(full_processing);
2118 * Load the network map and filter list into memory.
2121 filterlist = load_filter_list();
2124 * Go ahead and run the queue
2126 if (full_processing && !CtdlThreadCheckStop()) {
2127 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2128 ForEachRoom(network_queue_room, NULL);
2131 if (rplist != NULL) {
2132 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2133 while (rplist != NULL && !CtdlThreadCheckStop()) {
2134 char spoolroomname[ROOMNAMELEN];
2135 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2136 begin_critical_section(S_RPLIST);
2138 /* pop this record off the list */
2140 rplist = rplist->next;
2143 /* invalidate any duplicate entries to prevent double processing */
2144 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2145 if (!strcasecmp(ptr->name, spoolroomname)) {
2150 end_critical_section(S_RPLIST);
2151 if (spoolroomname[0] != 0) {
2152 network_spoolout_room(spoolroomname);
2157 /* If there is anything in the inbound queue, process it */
2158 if (!CtdlThreadCheckStop())
2159 network_do_spoolin();
2161 /* Save the network map back to disk */
2162 write_network_map();
2164 /* Free the filter list in memory */
2165 free_filter_list(filterlist);
2168 network_purge_spoolout();
2170 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2172 if (full_processing) {
2173 last_run = time(NULL);
2177 if (!CtdlThreadCheckStop()) // Only reschedule if system is not stopping
2178 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, time(NULL) + 60);
2180 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2186 * cmd_netp() - authenticate to the server as another Citadel node polling
2187 * for network traffic
2189 void cmd_netp(char *cmdbuf)
2200 extract_token(node, cmdbuf, 0, '|', sizeof node);
2201 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2204 CtdlLogPrintf(CTDL_WARNING, "Network node <%s> refused - spooling", node);
2205 cprintf("%d spooling - try again in a few minutes\n",
2206 ERROR + RESOURCE_BUSY);
2210 /* load the IGnet Configuration to check node validity */
2211 load_working_ignetcfg();
2212 v = is_valid_node(nexthop, secret, node);
2215 snprintf (err_buf, sizeof(err_buf), "Unknown node <%s>\n", node);
2216 CtdlLogPrintf(CTDL_WARNING, err_buf);
2217 cprintf("%d authentication failed\n",
2218 ERROR + PASSWORD_REQUIRED);
2219 aide_message(err_buf, "IGNet Networking.");
2223 if (strcasecmp(pass, secret)) {
2224 snprintf (err_buf, sizeof(err_buf), "Bad password for network node <%s>", node);
2225 CtdlLogPrintf(CTDL_WARNING, err_buf);
2226 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2227 aide_message(err_buf, "IGNet Networking.");
2231 if (network_talking_to(node, NTT_CHECK)) {
2232 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2233 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2237 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2238 network_talking_to(node, NTT_ADD);
2239 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in\n", CC->net_node);
2240 cprintf("%d authenticated as network node '%s'\n", CIT_OK,
2244 int network_room_handler (struct ctdlroom *room)
2246 network_queue_room(room, NULL);
2251 * Module entry point
2253 CTDL_MODULE_INIT(network)
2257 create_spool_dirs();
2258 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2259 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2260 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2261 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2262 CtdlRegisterRoomHook(network_room_handler);
2263 CtdlRegisterCleanupHook(destroy_network_queue_room);
2266 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2267 /* return our Subversion id for the Log */