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"
73 #include "internet_addressing.h"
74 #include "serv_network.h"
75 #include "clientsocket.h"
77 #include "citadel_dirs.h"
86 #include "ctdl_module.h"
90 /* Nonzero while we are doing network processing */
91 static int doing_queue = 0;
94 * When we do network processing, it's accomplished in two passes; one to
95 * gather a list of rooms and one to actually do them. It's ok that rplist
96 * is global; we have a mutex that keeps it safe.
98 struct RoomProcList *rplist = NULL;
101 * We build a map of network nodes during processing.
103 NetMap *the_netmap = NULL;
104 int netmap_changed = 0;
105 char *working_ignetcfg = NULL;
108 * Load or refresh the Citadel network (IGnet) configuration for this node.
110 void load_working_ignetcfg(void) {
114 cfg = CtdlGetSysConfig(IGNETCFG);
119 oldcfg = working_ignetcfg;
120 working_ignetcfg = cfg;
121 if (oldcfg != NULL) {
131 * Keep track of what messages to reject
133 FilterList *load_filter_list(void) {
134 char *serialized_list = NULL;
137 FilterList *newlist = NULL;
140 serialized_list = CtdlGetSysConfig(FILTERLIST);
141 if (serialized_list == NULL) return(NULL); /* if null, no entries */
143 /* Use the string tokenizer to grab one line at a time */
144 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
145 extract_token(buf, serialized_list, i, '\n', sizeof buf);
146 nptr = (FilterList *) malloc(sizeof(FilterList));
147 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
148 striplt(nptr->fl_user);
149 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
150 striplt(nptr->fl_room);
151 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
152 striplt(nptr->fl_node);
154 /* Cowardly refuse to add an any/any/any entry that would
155 * end up filtering every single message.
157 if (IsEmptyStr(nptr->fl_user) &&
158 IsEmptyStr(nptr->fl_room) &&
159 IsEmptyStr(nptr->fl_node)) {
163 nptr->next = newlist;
168 free(serialized_list);
173 void free_filter_list(FilterList *fl) {
174 if (fl == NULL) return;
175 free_filter_list(fl->next);
182 * Check the use table. This is a list of messages which have recently
183 * arrived on the system. It is maintained and queried to prevent the same
184 * message from being entered into the database multiple times if it happens
185 * to arrive multiple times by accident.
187 int network_usetable(struct CtdlMessage *msg) {
190 struct cdbdata *cdbut;
193 /* Bail out if we can't generate a message ID */
197 if (msg->cm_fields['I'] == NULL) {
200 if (IsEmptyStr(msg->cm_fields['I'])) {
204 /* Generate the message ID */
205 strcpy(msgid, msg->cm_fields['I']);
206 if (haschar(msgid, '@') == 0) {
208 if (msg->cm_fields['N'] != NULL) {
209 strcat(msgid, msg->cm_fields['N']);
216 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
219 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
223 /* If we got to this point, it's unique: add it. */
224 strcpy(ut.ut_msgid, msgid);
225 ut.ut_timestamp = time(NULL);
226 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
232 * Read the network map from its configuration file into memory.
234 void read_network_map(void) {
235 char *serialized_map = NULL;
240 serialized_map = CtdlGetSysConfig(IGNETMAP);
241 if (serialized_map == NULL) return; /* if null, no entries */
243 /* Use the string tokenizer to grab one line at a time */
244 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
245 extract_token(buf, serialized_map, i, '\n', sizeof buf);
246 nmptr = (NetMap *) malloc(sizeof(NetMap));
247 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
248 nmptr->lastcontact = extract_long(buf, 1);
249 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
250 nmptr->next = the_netmap;
254 free(serialized_map);
260 * Write the network map from memory back to the configuration file.
262 void write_network_map(void) {
263 char *serialized_map = NULL;
267 if (netmap_changed) {
268 serialized_map = strdup("");
270 if (the_netmap != NULL) {
271 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
272 serialized_map = realloc(serialized_map,
273 (strlen(serialized_map)+SIZ) );
274 if (!IsEmptyStr(nmptr->nodename)) {
275 snprintf(&serialized_map[strlen(serialized_map)],
279 (long)nmptr->lastcontact,
285 CtdlPutSysConfig(IGNETMAP, serialized_map);
286 free(serialized_map);
289 /* Now free the list */
290 while (the_netmap != NULL) {
291 nmptr = the_netmap->next;
301 * Check the network map and determine whether the supplied node name is
302 * valid. If it is not a neighbor node, supply the name of a neighbor node
303 * which is the next hop. If it *is* a neighbor node, we also fill in the
306 int is_valid_node(char *nexthop, char *secret, char *node) {
318 * First try the neighbor nodes
320 if (working_ignetcfg == NULL) {
321 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
322 if (nexthop != NULL) {
329 if (nexthop != NULL) {
333 /* Use the string tokenizer to grab one line at a time */
334 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
335 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
336 extract_token(buf, linebuf, 0, '|', sizeof buf);
337 if (!strcasecmp(buf, node)) {
338 if (nexthop != NULL) {
341 if (secret != NULL) {
342 extract_token(secret, linebuf, 1, '|', 256);
349 return(retval); /* yup, it's a direct neighbor */
353 * If we get to this point we have to see if we know the next hop
355 if (the_netmap != NULL) {
356 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
357 if (!strcasecmp(nmptr->nodename, node)) {
358 if (nexthop != NULL) {
359 strcpy(nexthop, nmptr->nexthop);
367 * If we get to this point, the supplied node name is bogus.
369 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
377 void cmd_gnet(char *argbuf) {
378 char filename[PATH_MAX];
382 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
383 /* users can edit the netconfigs for their own mailbox rooms */
385 else if (CtdlAccessCheck(ac_room_aide)) return;
387 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
388 cprintf("%d Network settings for room #%ld <%s>\n",
390 CC->room.QRnumber, CC->room.QRname);
392 fp = fopen(filename, "r");
394 while (fgets(buf, sizeof buf, fp) != NULL) {
395 buf[strlen(buf)-1] = 0;
396 cprintf("%s\n", buf);
405 void cmd_snet(char *argbuf) {
406 char tempfilename[PATH_MAX];
407 char filename[PATH_MAX];
416 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
417 /* users can edit the netconfigs for their own mailbox rooms */
419 else if (CtdlAccessCheck(ac_room_aide)) return;
421 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
422 memcpy(tempfilename, filename, len + 1);
424 memset(&StatBuf, 0, sizeof(struct stat));
425 if (stat(filename, &StatBuf) == -1)
426 StatBuf.st_size = 80; /* Not there? guess 80 chars line. */
428 sprintf(tempfilename + len, ".%d", CC->cs_pid);
430 TmpFD = open(tempfilename, O_CREAT|O_EXCL);
434 char *tmp = malloc(StatBuf.st_size * 2);
435 memset(tmp, 0, StatBuf.st_size * 2);
436 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
441 cprintf("%d Unable to allocate the space required for %s: %s\n",
442 ERROR + INTERNAL_ERROR,
447 lseek(TmpFD, SEEK_SET, 0);
450 cprintf("%d Unable to allocate the space required for %s: %s\n",
451 ERROR + INTERNAL_ERROR,
459 cprintf("%d %s\n", SEND_LISTING, tempfilename);
462 while (rc = CtdlClientGetLine(Line),
465 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
467 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
468 write(TmpFD, ChrPtr(Line), StrLength(Line));
469 len += StrLength(Line);
472 ftruncate(TmpFD, len + 1);
475 /* Now copy the temp file to its permanent location.
476 * (We copy instead of link because they may be on different filesystems)
478 begin_critical_section(S_NETCONFIGS);
479 rename(filename, tempfilename);
480 end_critical_section(S_NETCONFIGS);
485 * Deliver digest messages
487 void network_deliver_digest(SpoolControl *sc) {
490 struct CtdlMessage *msg = NULL;
493 size_t recps_len = SIZ;
495 struct recptypes *valid;
499 if (sc->num_msgs_spooled < 1) {
500 fclose(sc->digestfp);
505 msg = malloc(sizeof(struct CtdlMessage));
506 memset(msg, 0, sizeof(struct CtdlMessage));
507 msg->cm_magic = CTDLMESSAGE_MAGIC;
508 msg->cm_format_type = FMT_RFC822;
509 msg->cm_anon_type = MES_NORMAL;
511 sprintf(buf, "%ld", time(NULL));
512 msg->cm_fields['T'] = strdup(buf);
513 msg->cm_fields['A'] = strdup(CC->room.QRname);
514 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
515 msg->cm_fields['U'] = strdup(buf);
516 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
517 for (i=0; buf[i]; ++i) {
518 if (isspace(buf[i])) buf[i]='_';
519 buf[i] = tolower(buf[i]);
521 msg->cm_fields['F'] = strdup(buf);
522 msg->cm_fields['R'] = strdup(buf);
524 /* Set the 'List-ID' header */
525 msg->cm_fields['L'] = malloc(1024);
526 snprintf(msg->cm_fields['L'], 1024,
527 "%s <%ld.list-id.%s>",
534 * Go fetch the contents of the digest
536 fseek(sc->digestfp, 0L, SEEK_END);
537 msglen = ftell(sc->digestfp);
539 msg->cm_fields['M'] = malloc(msglen + 1);
540 fseek(sc->digestfp, 0L, SEEK_SET);
541 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
542 msg->cm_fields['M'][msglen] = '\0';
544 fclose(sc->digestfp);
547 /* Now generate the delivery instructions */
550 * Figure out how big a buffer we need to allocate
552 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
553 recps_len = recps_len + strlen(nptr->name) + 2;
556 recps = malloc(recps_len);
559 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
566 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
567 if (nptr != sc->digestrecps) {
570 strcat(recps, nptr->name);
573 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
574 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
576 /* Now submit the message */
577 valid = validate_recipients(recps, NULL, 0);
580 valid->bounce_to = strdup(bounce_to);
581 valid->envelope_from = strdup(bounce_to);
582 CtdlSubmitMsg(msg, valid, NULL, 0);
584 CtdlFreeMessage(msg);
585 free_recipients(valid);
590 * Deliver list messages to everyone on the list ... efficiently
592 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
594 size_t recps_len = SIZ;
595 struct recptypes *valid;
599 /* Don't do this if there were no recipients! */
600 if (sc->listrecps == NULL) return;
602 /* Now generate the delivery instructions */
605 * Figure out how big a buffer we need to allocate
607 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
608 recps_len = recps_len + strlen(nptr->name) + 2;
611 recps = malloc(recps_len);
614 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
621 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
622 if (nptr != sc->listrecps) {
625 strcat(recps, nptr->name);
628 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
629 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
631 /* Now submit the message */
632 valid = validate_recipients(recps, NULL, 0);
635 valid->bounce_to = strdup(bounce_to);
636 valid->envelope_from = strdup(bounce_to);
637 CtdlSubmitMsg(msg, valid, NULL, 0);
638 free_recipients(valid);
640 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
647 * Spools out one message from the list.
649 void network_spool_msg(long msgnum, void *userdata) {
652 char *newpath = NULL;
653 size_t instr_len = SIZ;
654 struct CtdlMessage *msg = NULL;
657 struct ser_ret sermsg;
659 char filename[PATH_MAX];
663 int delete_after_send = 0; /* Set to 1 to delete after spooling */
664 int ok_to_participate = 0;
665 struct recptypes *valid;
667 sc = (SpoolControl *)userdata;
670 * Process mailing list recipients
673 if (sc->listrecps != NULL) {
674 /* Fetch the message. We're going to need to modify it
675 * in order to insert the [list name] in it, etc.
677 msg = CtdlFetchMessage(msgnum, 1);
679 if (msg->cm_fields['V'] == NULL){
680 /* local message, no enVelope */
683 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
684 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
685 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
687 msg->cm_fields['K'] = SmashStrBuf(&Buf);
690 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
692 /* Set the 'List-ID' header */
693 if (msg->cm_fields['L'] != NULL) {
694 free(msg->cm_fields['L']);
696 msg->cm_fields['L'] = malloc(1024);
697 snprintf(msg->cm_fields['L'], 1024,
698 "%s <%ld.list-id.%s>",
704 /* Prepend "[List name]" to the subject */
705 if (msg->cm_fields['U'] == NULL) {
706 msg->cm_fields['U'] = strdup("(no subject)");
708 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
709 free(msg->cm_fields['U']);
710 msg->cm_fields['U'] = strdup(buf);
712 /* Set the recipient of the list message to the
713 * email address of the room itself.
714 * FIXME ... I want to be able to pick any address
716 if (msg->cm_fields['R'] != NULL) {
717 free(msg->cm_fields['R']);
719 msg->cm_fields['R'] = malloc(256);
720 snprintf(msg->cm_fields['R'], 256,
721 "room_%s@%s", CC->room.QRname,
723 for (i=0; msg->cm_fields['R'][i]; ++i) {
724 if (isspace(msg->cm_fields['R'][i])) {
725 msg->cm_fields['R'][i] = '_';
729 /* Handle delivery */
730 network_deliver_list(msg, sc);
731 CtdlFreeMessage(msg);
736 * Process digest recipients
738 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
739 msg = CtdlFetchMessage(msgnum, 1);
741 fprintf(sc->digestfp, " -----------------------------------"
742 "------------------------------------"
744 fprintf(sc->digestfp, "From: ");
745 if (msg->cm_fields['A'] != NULL) {
746 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
748 if (msg->cm_fields['F'] != NULL) {
749 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
751 else if (msg->cm_fields['N'] != NULL) {
752 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
754 fprintf(sc->digestfp, "\n");
755 if (msg->cm_fields['U'] != NULL) {
756 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
759 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
761 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
762 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
764 StrBufTrim(CC->redirect_buffer);
765 fwrite(HKEY("\n"), 1, sc->digestfp);
766 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
767 fwrite(HKEY("\n"), 1, sc->digestfp);
769 FreeStrBuf(&CC->redirect_buffer);
771 sc->num_msgs_spooled += 1;
777 * Process client-side list participations for this room
780 if (sc->participates != NULL) {
781 msg = CtdlFetchMessage(msgnum, 1);
784 /* Only send messages which originated on our own Citadel
785 * network, otherwise we'll end up sending the remote
786 * mailing list's messages back to it, which is rude...
788 ok_to_participate = 0;
789 if (msg->cm_fields['N'] != NULL) {
790 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
791 ok_to_participate = 1;
793 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
794 ok_to_participate = 1;
797 if (ok_to_participate) {
798 if (msg->cm_fields['F'] != NULL) {
799 free(msg->cm_fields['F']);
801 msg->cm_fields['F'] = malloc(SIZ);
802 /* Replace the Internet email address of the actual
803 * author with the email address of the room itself,
804 * so the remote listserv doesn't reject us.
805 * FIXME ... I want to be able to pick any address
807 snprintf(msg->cm_fields['F'], SIZ,
808 "room_%s@%s", CC->room.QRname,
810 for (i=0; msg->cm_fields['F'][i]; ++i) {
811 if (isspace(msg->cm_fields['F'][i])) {
812 msg->cm_fields['F'][i] = '_';
817 * Figure out how big a buffer we need to allocate
819 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
821 if (msg->cm_fields['R'] == NULL) {
822 free(msg->cm_fields['R']);
824 msg->cm_fields['R'] = strdup(nptr->name);
826 valid = validate_recipients(nptr->name, NULL, 0);
827 CtdlSubmitMsg(msg, valid, "", 0);
828 free_recipients(valid);
832 CtdlFreeMessage(msg);
837 * Process IGnet push shares
839 msg = CtdlFetchMessage(msgnum, 1);
843 /* Prepend our node name to the Path field whenever
844 * sending a message to another IGnet node
846 if (msg->cm_fields['P'] == NULL) {
847 msg->cm_fields['P'] = strdup("username");
849 newpath_len = strlen(msg->cm_fields['P']) +
850 strlen(config.c_nodename) + 2;
851 newpath = malloc(newpath_len);
852 snprintf(newpath, newpath_len, "%s!%s",
853 config.c_nodename, msg->cm_fields['P']);
854 free(msg->cm_fields['P']);
855 msg->cm_fields['P'] = newpath;
858 * Determine if this message is set to be deleted
859 * after sending out on the network
861 if (msg->cm_fields['S'] != NULL) {
862 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
863 delete_after_send = 1;
867 /* Now send it to every node */
868 if (sc->ignet_push_shares != NULL)
869 for (mptr = sc->ignet_push_shares; mptr != NULL;
874 /* Check for valid node name */
875 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
876 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
880 /* Check for split horizon */
881 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
882 bang = num_tokens(msg->cm_fields['P'], '!');
883 if (bang > 1) for (i=0; i<(bang-1); ++i) {
884 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
885 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
886 buf, mptr->remote_nodename) ;
887 if (!strcasecmp(buf, mptr->remote_nodename)) {
889 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
890 mptr->remote_nodename);
893 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
897 /* Send the message */
901 * Force the message to appear in the correct room
902 * on the far end by setting the C field correctly
904 if (msg->cm_fields['C'] != NULL) {
905 free(msg->cm_fields['C']);
907 if (!IsEmptyStr(mptr->remote_roomname)) {
908 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
911 msg->cm_fields['C'] = strdup(CC->room.QRname);
914 /* serialize it for transmission */
915 serialize_message(&sermsg, msg);
916 if (sermsg.len > 0) {
918 /* write it to a spool file */
919 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
921 mptr->remote_nodename,
925 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
926 fp = fopen(filename, "ab");
933 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
936 /* free the serialized version */
942 CtdlFreeMessage(msg);
945 /* update lastsent */
946 sc->lastsent = msgnum;
948 /* Delete this message if delete-after-send is set */
949 if (delete_after_send) {
950 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
956 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
962 char roomname[ROOMNAMELEN];
965 int skipthisline = 0;
966 namelist *nptr = NULL;
967 maplist *mptr = NULL;
970 fp = fopen(filename, "r");
974 sc = malloc(sizeof(SpoolControl));
975 memset(sc, 0, sizeof(SpoolControl));
978 while (fgets(buf, sizeof buf, fp) != NULL) {
979 buf[strlen(buf)-1] = 0;
981 extract_token(instr, buf, 0, '|', sizeof instr);
982 if (!strcasecmp(instr, strof(lastsent))) {
983 sc->lastsent = extract_long(buf, 1);
985 else if (!strcasecmp(instr, strof(listrecp))) {
987 malloc(sizeof(namelist));
988 nptr->next = sc->listrecps;
989 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
990 sc->listrecps = nptr;
992 else if (!strcasecmp(instr, strof(participate))) {
994 malloc(sizeof(namelist));
995 nptr->next = sc->participates;
996 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
997 sc->participates = nptr;
999 else if (!strcasecmp(instr, strof(digestrecp))) {
1001 malloc(sizeof(namelist));
1002 nptr->next = sc->digestrecps;
1003 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1004 sc->digestrecps = nptr;
1006 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1007 extract_token(nodename, buf, 1, '|', sizeof nodename);
1008 extract_token(roomname, buf, 2, '|', sizeof roomname);
1009 mptr = (maplist *) malloc(sizeof(maplist));
1010 mptr->next = sc->ignet_push_shares;
1011 strcpy(mptr->remote_nodename, nodename);
1012 strcpy(mptr->remote_roomname, roomname);
1013 sc->ignet_push_shares = mptr;
1016 /* Preserve 'other' lines ... *unless* they happen to
1017 * be subscribe/unsubscribe pendings with expired
1021 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1022 if (time(NULL) - extract_long(buf, 4) > EXP) {
1026 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1027 if (time(NULL) - extract_long(buf, 3) > EXP) {
1032 if (skipthisline == 0) {
1033 linesize = strlen(buf);
1034 sc->misc = realloc(sc->misc,
1035 (miscsize + linesize + 2) );
1036 sprintf(&sc->misc[miscsize], "%s\n", buf);
1037 miscsize = miscsize + linesize + 1;
1047 void free_spoolcontrol_struct(SpoolControl **scc)
1050 namelist *nptr = NULL;
1051 maplist *mptr = NULL;
1054 while (sc->listrecps != NULL) {
1055 nptr = sc->listrecps->next;
1056 free(sc->listrecps);
1057 sc->listrecps = nptr;
1059 /* Do the same for digestrecps */
1060 while (sc->digestrecps != NULL) {
1061 nptr = sc->digestrecps->next;
1062 free(sc->digestrecps);
1063 sc->digestrecps = nptr;
1065 /* Do the same for participates */
1066 while (sc->participates != NULL) {
1067 nptr = sc->participates->next;
1068 free(sc->participates);
1069 sc->participates = nptr;
1071 while (sc->ignet_push_shares != NULL) {
1072 mptr = sc->ignet_push_shares->next;
1073 free(sc->ignet_push_shares);
1074 sc->ignet_push_shares = mptr;
1081 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1085 namelist *nptr = NULL;
1086 maplist *mptr = NULL;
1089 fp = fopen(filename, "w");
1091 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1092 filename, strerror(errno));
1093 free_spoolcontrol_struct(scc);
1096 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1098 /* Write out the listrecps while freeing from memory at the
1099 * same time. Am I clever or what? :)
1101 while (sc->listrecps != NULL) {
1102 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1103 nptr = sc->listrecps->next;
1104 free(sc->listrecps);
1105 sc->listrecps = nptr;
1107 /* Do the same for digestrecps */
1108 while (sc->digestrecps != NULL) {
1109 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1110 nptr = sc->digestrecps->next;
1111 free(sc->digestrecps);
1112 sc->digestrecps = nptr;
1114 /* Do the same for participates */
1115 while (sc->participates != NULL) {
1116 fprintf(fp, "participate|%s\n", sc->participates->name);
1117 nptr = sc->participates->next;
1118 free(sc->participates);
1119 sc->participates = nptr;
1121 while (sc->ignet_push_shares != NULL) {
1122 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1123 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1124 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1127 mptr = sc->ignet_push_shares->next;
1128 free(sc->ignet_push_shares);
1129 sc->ignet_push_shares = mptr;
1131 if (sc->misc != NULL) {
1132 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1142 int is_recipient(SpoolControl *sc, const char *Name)
1148 nptr = sc->listrecps;
1149 while (nptr != NULL) {
1150 if (strncmp(Name, nptr->name, len)==0)
1154 /* Do the same for digestrecps */
1155 nptr = sc->digestrecps;
1156 while (nptr != NULL) {
1157 if (strncmp(Name, nptr->name, len)==0)
1161 /* Do the same for participates */
1162 nptr = sc->participates;
1163 while (nptr != NULL) {
1164 if (strncmp(Name, nptr->name, len)==0)
1173 * Batch up and send all outbound traffic from the current room
1175 void network_spoolout_room(char *room_to_spool) {
1177 char filename[PATH_MAX];
1182 * If the room doesn't exist, don't try to perform its networking tasks.
1183 * Normally this should never happen, but once in a while maybe a room gets
1184 * queued for networking and then deleted before it can happen.
1186 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1187 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1191 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1192 begin_critical_section(S_NETCONFIGS);
1194 /* Only do net processing for rooms that have netconfigs */
1195 if (!read_spoolcontrol_file(&sc, filename))
1197 end_critical_section(S_NETCONFIGS);
1200 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1202 /* If there are digest recipients, we have to build a digest */
1203 if (sc->digestrecps != NULL) {
1204 sc->digestfp = tmpfile();
1205 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1208 /* Do something useful */
1209 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1210 network_spool_msg, sc);
1212 /* If we wrote a digest, deliver it and then close it */
1213 snprintf(buf, sizeof buf, "room_%s@%s",
1214 CC->room.QRname, config.c_fqdn);
1215 for (i=0; buf[i]; ++i) {
1216 buf[i] = tolower(buf[i]);
1217 if (isspace(buf[i])) buf[i] = '_';
1219 if (sc->digestfp != NULL) {
1220 fprintf(sc->digestfp, " -----------------------------------"
1221 "------------------------------------"
1223 "You are subscribed to the '%s' "
1225 "To post to the list: %s\n",
1226 CC->room.QRname, buf
1228 network_deliver_digest(sc); /* deliver and close */
1231 /* Now rewrite the config file */
1232 writenfree_spoolcontrol_file (&sc, filename);
1233 end_critical_section(S_NETCONFIGS);
1239 * Send the *entire* contents of the current room to one specific network node,
1240 * ignoring anything we know about which messages have already undergone
1241 * network processing. This can be used to bring a new node into sync.
1243 int network_sync_to(char *target_node) {
1245 int num_spooled = 0;
1251 char filename[PATH_MAX];
1254 /* Grab the configuration line we're looking for */
1255 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1256 begin_critical_section(S_NETCONFIGS);
1257 fp = fopen(filename, "r");
1259 end_critical_section(S_NETCONFIGS);
1262 while (fgets(buf, sizeof buf, fp) != NULL) {
1263 buf[strlen(buf)-1] = 0;
1264 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1265 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1266 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1267 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1268 && (!strcasecmp(sc_node, target_node)) ) {
1271 /* Concise syntax because we don't need a full linked-list */
1272 memset(&sc, 0, sizeof(SpoolControl));
1273 sc.ignet_push_shares = (maplist *)
1274 malloc(sizeof(maplist));
1275 sc.ignet_push_shares->next = NULL;
1276 safestrncpy(sc.ignet_push_shares->remote_nodename,
1278 sizeof sc.ignet_push_shares->remote_nodename);
1279 safestrncpy(sc.ignet_push_shares->remote_roomname,
1281 sizeof sc.ignet_push_shares->remote_roomname);
1285 end_critical_section(S_NETCONFIGS);
1287 if (!found_node) return(-1);
1289 /* Send ALL messages */
1290 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1291 network_spool_msg, &sc);
1293 /* Concise cleanup because we know there's only one node in the sc */
1294 free(sc.ignet_push_shares);
1296 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1297 num_spooled, target_node);
1298 return(num_spooled);
1303 * Implements the NSYN command
1305 void cmd_nsyn(char *argbuf) {
1307 char target_node[256];
1309 if (CtdlAccessCheck(ac_aide)) return;
1311 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1312 num_spooled = network_sync_to(target_node);
1313 if (num_spooled >= 0) {
1314 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1317 cprintf("%d No such room/node share exists.\n",
1318 ERROR + ROOM_NOT_FOUND);
1325 * Batch up and send all outbound traffic from the current room
1327 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1328 struct RoomProcList *ptr;
1330 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1331 if (ptr == NULL) return;
1333 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1334 begin_critical_section(S_RPLIST);
1337 end_critical_section(S_RPLIST);
1340 void destroy_network_queue_room(void)
1342 struct RoomProcList *cur, *p;
1343 NetMap *nmcur, *nmp;
1346 begin_critical_section(S_RPLIST);
1354 end_critical_section(S_RPLIST);
1357 while (nmcur != NULL)
1364 if (working_ignetcfg != NULL)
1365 free (working_ignetcfg);
1366 working_ignetcfg = NULL;
1371 * Learn topology from path fields
1373 void network_learn_topology(char *node, char *path) {
1377 strcpy(nexthop, "");
1379 if (num_tokens(path, '!') < 3) return;
1380 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1381 if (!strcasecmp(nmptr->nodename, node)) {
1382 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1383 nmptr->lastcontact = time(NULL);
1389 /* If we got here then it's not in the map, so add it. */
1390 nmptr = (NetMap *) malloc(sizeof (NetMap));
1391 strcpy(nmptr->nodename, node);
1392 nmptr->lastcontact = time(NULL);
1393 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1394 nmptr->next = the_netmap;
1403 * Bounce a message back to the sender
1405 void network_bounce(struct CtdlMessage *msg, char *reason) {
1406 char *oldpath = NULL;
1408 char bouncesource[SIZ];
1409 char recipient[SIZ];
1410 struct recptypes *valid = NULL;
1411 char force_room[ROOMNAMELEN];
1412 static int serialnum = 0;
1415 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1417 if (msg == NULL) return;
1419 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1422 * Give it a fresh message ID
1424 if (msg->cm_fields['I'] != NULL) {
1425 free(msg->cm_fields['I']);
1427 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1428 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1429 msg->cm_fields['I'] = strdup(buf);
1432 * FIXME ... right now we're just sending a bounce; we really want to
1433 * include the text of the bounced message.
1435 if (msg->cm_fields['M'] != NULL) {
1436 free(msg->cm_fields['M']);
1438 msg->cm_fields['M'] = strdup(reason);
1439 msg->cm_format_type = 0;
1442 * Turn the message around
1444 if (msg->cm_fields['R'] == NULL) {
1445 free(msg->cm_fields['R']);
1448 if (msg->cm_fields['D'] == NULL) {
1449 free(msg->cm_fields['D']);
1452 snprintf(recipient, sizeof recipient, "%s@%s",
1453 msg->cm_fields['A'], msg->cm_fields['N']);
1455 if (msg->cm_fields['A'] == NULL) {
1456 free(msg->cm_fields['A']);
1459 if (msg->cm_fields['N'] == NULL) {
1460 free(msg->cm_fields['N']);
1463 if (msg->cm_fields['U'] == NULL) {
1464 free(msg->cm_fields['U']);
1467 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1468 msg->cm_fields['N'] = strdup(config.c_nodename);
1469 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1471 /* prepend our node to the path */
1472 if (msg->cm_fields['P'] != NULL) {
1473 oldpath = msg->cm_fields['P'];
1474 msg->cm_fields['P'] = NULL;
1477 oldpath = strdup("unknown_user");
1479 size = strlen(oldpath) + SIZ;
1480 msg->cm_fields['P'] = malloc(size);
1481 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1484 /* Now submit the message */
1485 valid = validate_recipients(recipient, NULL, 0);
1486 if (valid != NULL) if (valid->num_error != 0) {
1487 free_recipients(valid);
1490 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1491 strcpy(force_room, config.c_aideroom);
1494 strcpy(force_room, "");
1496 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1497 strcpy(force_room, config.c_aideroom);
1499 CtdlSubmitMsg(msg, valid, force_room, 0);
1502 if (valid != NULL) free_recipients(valid);
1503 CtdlFreeMessage(msg);
1504 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1511 * Process a buffer containing a single message from a single file
1512 * from the inbound queue
1514 void network_process_buffer(char *buffer, long size) {
1515 struct CtdlMessage *msg = NULL;
1518 struct recptypes *recp = NULL;
1519 char target_room[ROOMNAMELEN];
1520 struct ser_ret sermsg;
1521 char *oldpath = NULL;
1522 char filename[PATH_MAX];
1525 unsigned char firstbyte;
1526 unsigned char lastbyte;
1528 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1530 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1531 firstbyte = buffer[0];
1532 lastbyte = buffer[size-1];
1533 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1534 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1535 size, firstbyte, lastbyte);
1539 /* Set default target room to trash */
1540 strcpy(target_room, TWITROOM);
1542 /* Load the message into memory */
1543 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1544 memset(msg, 0, sizeof(struct CtdlMessage));
1545 msg->cm_magic = CTDLMESSAGE_MAGIC;
1546 msg->cm_anon_type = buffer[1];
1547 msg->cm_format_type = buffer[2];
1549 for (pos = 3; pos < size; ++pos) {
1550 field = buffer[pos];
1551 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1552 pos = pos + strlen(&buffer[(int)pos]);
1555 /* Check for message routing */
1556 if (msg->cm_fields['D'] != NULL) {
1557 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1559 /* route the message */
1560 strcpy(nexthop, "");
1561 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1562 /* prepend our node to the path */
1563 if (msg->cm_fields['P'] != NULL) {
1564 oldpath = msg->cm_fields['P'];
1565 msg->cm_fields['P'] = NULL;
1568 oldpath = strdup("unknown_user");
1570 size = strlen(oldpath) + SIZ;
1571 msg->cm_fields['P'] = malloc(size);
1572 snprintf(msg->cm_fields['P'], size, "%s!%s",
1573 config.c_nodename, oldpath);
1576 /* serialize the message */
1577 serialize_message(&sermsg, msg);
1580 if (IsEmptyStr(nexthop)) {
1581 strcpy(nexthop, msg->cm_fields['D']);
1591 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1592 fp = fopen(filename, "ab");
1594 fwrite(sermsg.ser, sermsg.len, 1, fp);
1598 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1601 CtdlFreeMessage(msg);
1605 else { /* invalid destination node name */
1608 "A message you sent could not be delivered due to an invalid destination node"
1609 " name. Please check the address and try sending the message again.\n");
1618 * Check to see if we already have a copy of this message, and
1619 * abort its processing if so. (We used to post a warning to Aide>
1620 * every time this happened, but the network is now so densely
1621 * connected that it's inevitable.)
1623 if (network_usetable(msg) != 0) {
1624 CtdlFreeMessage(msg);
1628 /* Learn network topology from the path */
1629 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1630 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1633 /* Is the sending node giving us a very persuasive suggestion about
1634 * which room this message should be saved in? If so, go with that.
1636 if (msg->cm_fields['C'] != NULL) {
1637 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1640 /* Otherwise, does it have a recipient? If so, validate it... */
1641 else if (msg->cm_fields['R'] != NULL) {
1642 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1643 if (recp != NULL) if (recp->num_error != 0) {
1645 "A message you sent could not be delivered due to an invalid address.\n"
1646 "Please check the address and try sending the message again.\n");
1648 free_recipients(recp);
1649 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1652 strcpy(target_room, ""); /* no target room if mail */
1655 /* Our last shot at finding a home for this message is to see if
1656 * it has the O field (Originating room) set.
1658 else if (msg->cm_fields['O'] != NULL) {
1659 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1662 /* Strip out fields that are only relevant during transit */
1663 if (msg->cm_fields['D'] != NULL) {
1664 free(msg->cm_fields['D']);
1665 msg->cm_fields['D'] = NULL;
1667 if (msg->cm_fields['C'] != NULL) {
1668 free(msg->cm_fields['C']);
1669 msg->cm_fields['C'] = NULL;
1672 /* save the message into a room */
1673 if (PerformNetprocHooks(msg, target_room) == 0) {
1674 msg->cm_flags = CM_SKIP_HOOKS;
1675 CtdlSubmitMsg(msg, recp, target_room, 0);
1677 CtdlFreeMessage(msg);
1678 free_recipients(recp);
1683 * Process a single message from a single file from the inbound queue
1685 void network_process_message(FILE *fp, long msgstart, long msgend) {
1690 hold_pos = ftell(fp);
1691 size = msgend - msgstart + 1;
1692 buffer = malloc(size);
1693 if (buffer != NULL) {
1694 fseek(fp, msgstart, SEEK_SET);
1695 if (fread(buffer, size, 1, fp) > 0) {
1696 network_process_buffer(buffer, size);
1701 fseek(fp, hold_pos, SEEK_SET);
1706 * Process a single file from the inbound queue
1708 void network_process_file(char *filename) {
1710 long msgstart = (-1L);
1711 long msgend = (-1L);
1716 fp = fopen(filename, "rb");
1718 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1722 fseek(fp, 0L, SEEK_END);
1723 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1726 /* Look for messages in the data stream and break them out */
1727 while (ch = getc(fp), ch >= 0) {
1730 if (msgstart >= 0L) {
1731 msgend = msgcur - 1;
1732 network_process_message(fp, msgstart, msgend);
1740 msgend = msgcur - 1;
1741 if (msgstart >= 0L) {
1742 network_process_message(fp, msgstart, msgend);
1751 * Process anything in the inbound queue
1753 void network_do_spoolin(void) {
1756 struct stat statbuf;
1757 char filename[PATH_MAX];
1758 static time_t last_spoolin_mtime = 0L;
1761 * Check the spoolin directory's modification time. If it hasn't
1762 * been touched, we don't need to scan it.
1764 if (stat(ctdl_netin_dir, &statbuf)) return;
1765 if (statbuf.st_mtime == last_spoolin_mtime) {
1766 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1769 last_spoolin_mtime = statbuf.st_mtime;
1770 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1773 * Ok, there's something interesting in there, so scan it.
1775 dp = opendir(ctdl_netin_dir);
1776 if (dp == NULL) return;
1778 while (d = readdir(dp), d != NULL) {
1779 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1786 network_process_file(filename);
1794 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1795 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1797 void network_consolidate_spoolout(void) {
1800 char filename[PATH_MAX];
1806 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1807 dp = opendir(ctdl_netout_dir);
1808 if (dp == NULL) return;
1809 while (d = readdir(dp), d != NULL) {
1811 (strcmp(d->d_name, "."))
1812 && (strcmp(d->d_name, ".."))
1813 && (strchr(d->d_name, '@') != NULL)
1815 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1816 ptr = strchr(nexthop, '@');
1826 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1827 if (network_talking_to(nexthop, NTT_CHECK)) {
1828 CtdlLogPrintf(CTDL_DEBUG,
1829 "Currently online with %s - skipping for now\n",
1834 network_talking_to(nexthop, NTT_ADD);
1835 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1837 ctdl_netout_dir, nexthop,
1841 network_talking_to(nexthop, NTT_REMOVE);
1847 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1849 dp = opendir(ctdl_netout_dir);
1850 if (dp == NULL) return;
1852 while (d = readdir(dp), d != NULL) {
1853 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1855 ptr = strchr(d->d_name, '@');
1865 strcpy(nexthop, "");
1866 i = is_valid_node(nexthop, NULL, d->d_name);
1868 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1879 * receive network spool from the remote system
1881 void receive_spool(int *sock, char *remote_nodename) {
1882 long download_len = 0L;
1883 long bytes_received = 0L;
1885 static char pbuf[IGNET_PACKET_SIZE];
1886 char tempfilename[PATH_MAX];
1887 char permfilename[PATH_MAX];
1891 snprintf(tempfilename,
1892 sizeof tempfilename,
1900 snprintf(permfilename,
1901 sizeof permfilename,
1909 if (sock_puts(sock, "NDOP") < 0) return;
1910 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1911 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1912 if (buf[0] != '2') {
1915 download_len = extract_long(&buf[4], 0);
1917 if (download_len>0) {
1918 bytes_received = 0L;
1919 fp = fopen(tempfilename, "w");
1921 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1926 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1927 while (bytes_received < download_len) {
1929 * If shutting down we can exit here and unlink the temp file.
1930 * this shouldn't loose us any messages.
1932 if (CtdlThreadCheckStop())
1935 unlink(tempfilename);
1938 snprintf(buf, sizeof buf, "READ %ld|%ld",
1940 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1941 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1943 if (sock_puts(sock, buf) < 0) {
1945 unlink(tempfilename);
1948 if (sock_getln(sock, buf, sizeof buf) < 0) {
1950 unlink(tempfilename);
1954 if (buf[0] == '6') {
1955 plen = extract_long(&buf[4], 0);
1956 if (sock_read(sock, pbuf, plen, 1) < 0) {
1958 unlink(tempfilename);
1961 fwrite((char *) pbuf, plen, 1, fp);
1962 bytes_received = bytes_received + plen;
1968 /* Last chance for shutdown exit */
1969 if (CtdlThreadCheckStop())
1971 unlink(tempfilename);
1975 if (sock_puts(sock, "CLOS") < 0) {
1976 unlink(tempfilename);
1981 * From here on we must complete or messages will get lost
1983 if (sock_getln(sock, buf, sizeof buf) < 0) {
1984 unlink(tempfilename);
1987 if (download_len > 0) {
1988 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1990 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1992 /* Now move the temp file to its permanent location.
1994 if (link(tempfilename, permfilename) != 0) {
1995 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
1996 tempfilename, permfilename, strerror(errno)
1999 unlink(tempfilename);
2005 * transmit network spool to the remote system
2007 void transmit_spool(int *sock, char *remote_nodename)
2012 long bytes_to_write, thisblock, bytes_written;
2016 if (sock_puts(sock, "NUOP") < 0) return;
2017 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2018 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2019 if (buf[0] != '2') {
2023 snprintf(sfname, sizeof sfname,
2028 fd = open(sfname, O_RDONLY);
2030 if (errno != ENOENT) {
2031 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2036 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2037 bytes_to_write = plen;
2038 while (bytes_to_write > 0L) {
2039 /* Exit if shutting down */
2040 if (CtdlThreadCheckStop())
2046 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2047 if (sock_puts(sock, buf) < 0) {
2051 if (sock_getln(sock, buf, sizeof buf) < 0) {
2055 thisblock = atol(&buf[4]);
2056 if (buf[0] == '7') {
2057 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2061 bytes_to_write -= thisblock;
2062 bytes_written += thisblock;
2072 /* Last chance for shutdown exit */
2073 if(CtdlThreadCheckStop())
2076 if (sock_puts(sock, "UCLS 1") < 0) return;
2079 * From here on we must complete or messages will get lost
2081 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2082 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2083 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2084 if (buf[0] == '2') {
2085 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2093 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2095 void network_poll_node(char *node, char *secret, char *host, char *port) {
2099 char connected_to[SIZ];
2102 if (network_talking_to(node, NTT_CHECK)) return;
2103 network_talking_to(node, NTT_ADD);
2104 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2105 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2107 sock = sock_connect(host, port, "tcp");
2109 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2110 network_talking_to(node, NTT_REMOVE);
2114 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2115 CCC->sReadBuf = NewStrBuf();
2116 CCC->sMigrateBuf = NewStrBuf();
2119 /* Read the server greeting */
2120 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2121 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2123 /* Check that the remote is who we think it is and warn the Aide if not */
2124 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2125 if (strcmp(connected_to, node))
2127 snprintf(err_buf, sizeof(err_buf),
2128 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2131 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2132 CtdlAideMessage(err_buf, "Network error");
2135 /* We're talking to the correct node. Now identify ourselves. */
2136 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2137 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2138 if (sock_puts(&sock, buf) <0) goto bail;
2139 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2140 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2141 if (buf[0] != '2') {
2145 /* At this point we are authenticated. */
2146 if (!CtdlThreadCheckStop())
2147 receive_spool(&sock, node);
2148 if (!CtdlThreadCheckStop())
2149 transmit_spool(&sock, node);
2152 sock_puts(&sock, "QUIT");
2154 FreeStrBuf(&CCC->sReadBuf);
2155 FreeStrBuf(&CCC->sMigrateBuf);
2158 network_talking_to(node, NTT_REMOVE);
2164 * Poll other Citadel nodes and transfer inbound/outbound network data.
2165 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2166 * only nodes to which we have data to send.
2168 void network_poll_other_citadel_nodes(int full_poll) {
2176 char spoolfile[256];
2178 if (working_ignetcfg == NULL) {
2179 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2183 /* Use the string tokenizer to grab one line at a time */
2184 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2185 if(CtdlThreadCheckStop())
2187 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2188 extract_token(node, linebuf, 0, '|', sizeof node);
2189 extract_token(secret, linebuf, 1, '|', sizeof secret);
2190 extract_token(host, linebuf, 2, '|', sizeof host);
2191 extract_token(port, linebuf, 3, '|', sizeof port);
2192 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2193 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2202 if (access(spoolfile, R_OK) == 0) {
2207 network_poll_node(node, secret, host, port);
2218 * It's ok if these directories already exist. Just fail silently.
2220 void create_spool_dirs(void) {
2221 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2222 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2223 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2224 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2225 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2226 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2227 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2228 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2229 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2230 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2231 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2232 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2233 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2234 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2235 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2236 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2244 * network_do_queue()
2246 * Run through the rooms doing various types of network stuff.
2248 void *network_do_queue(void *args) {
2249 static time_t last_run = 0L;
2250 struct RoomProcList *ptr;
2251 int full_processing = 1;
2252 struct CitContext networkerCC;
2254 /* Give the networker its own private CitContext */
2255 CtdlFillSystemContext(&networkerCC, "network");
2256 citthread_setspecific(MyConKey, (void *)&networkerCC );
2259 * Run the full set of processing tasks no more frequently
2260 * than once every n seconds
2262 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2263 full_processing = 0;
2264 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2265 config.c_net_freq - (time(NULL)- last_run)
2270 * This is a simple concurrency check to make sure only one queue run
2271 * is done at a time. We could do this with a mutex, but since we
2272 * don't really require extremely fine granularity here, we'll do it
2273 * with a static variable instead.
2276 CtdlClearSystemContext();
2281 /* Load the IGnet Configuration into memory */
2282 load_working_ignetcfg();
2285 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2286 * then we poll everyone. Otherwise we only poll nodes we have stuff
2289 network_poll_other_citadel_nodes(full_processing);
2292 * Load the network map and filter list into memory.
2295 filterlist = load_filter_list();
2298 * Go ahead and run the queue
2300 if (full_processing && !CtdlThreadCheckStop()) {
2301 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2302 CtdlForEachRoom(network_queue_room, NULL);
2305 if (rplist != NULL) {
2306 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2307 while (rplist != NULL && !CtdlThreadCheckStop()) {
2308 char spoolroomname[ROOMNAMELEN];
2309 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2310 begin_critical_section(S_RPLIST);
2312 /* pop this record off the list */
2314 rplist = rplist->next;
2317 /* invalidate any duplicate entries to prevent double processing */
2318 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2319 if (!strcasecmp(ptr->name, spoolroomname)) {
2324 end_critical_section(S_RPLIST);
2325 if (spoolroomname[0] != 0) {
2326 network_spoolout_room(spoolroomname);
2331 /* If there is anything in the inbound queue, process it */
2332 if (!CtdlThreadCheckStop()) {
2333 network_do_spoolin();
2336 /* Save the network map back to disk */
2337 write_network_map();
2339 /* Free the filter list in memory */
2340 free_filter_list(filterlist);
2343 network_consolidate_spoolout();
2345 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2347 if (full_processing) {
2348 last_run = time(NULL);
2353 /* Reschedule this task to happen again periodically, unless the thread system indicates
2354 * that the server is shutting down.
2356 if (!CtdlThreadCheckStop()) {
2357 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK,
2358 network_do_queue, NULL, time(NULL) + 60
2362 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2364 CtdlClearSystemContext();
2370 * cmd_netp() - authenticate to the server as another Citadel node polling
2371 * for network traffic
2373 void cmd_netp(char *cmdbuf)
2384 extract_token(node, cmdbuf, 0, '|', sizeof node);
2385 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2387 /* load the IGnet Configuration to check node validity */
2388 load_working_ignetcfg();
2389 v = is_valid_node(nexthop, secret, node);
2392 snprintf(err_buf, sizeof err_buf,
2393 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2394 node, CC->cs_host, CC->cs_addr
2396 CtdlLogPrintf(CTDL_WARNING, err_buf);
2397 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2398 CtdlAideMessage(err_buf, "IGNet Networking.");
2402 if (strcasecmp(pass, secret)) {
2403 snprintf(err_buf, sizeof err_buf,
2404 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2405 CC->cs_host, CC->cs_addr, node
2407 CtdlLogPrintf(CTDL_WARNING, err_buf);
2408 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2409 CtdlAideMessage(err_buf, "IGNet Networking.");
2413 if (network_talking_to(node, NTT_CHECK)) {
2414 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2415 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2419 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2420 network_talking_to(node, NTT_ADD);
2421 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2422 CC->net_node, CC->cs_host, CC->cs_addr
2424 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2428 int network_room_handler (struct ctdlroom *room)
2430 network_queue_room(room, NULL);
2436 * Module entry point
2438 CTDL_MODULE_INIT(network)
2442 create_spool_dirs();
2443 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2444 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2445 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2446 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2447 CtdlRegisterRoomHook(network_room_handler);
2448 CtdlRegisterCleanupHook(destroy_network_queue_room);
2451 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2452 /* return our Subversion id for the Log */