2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2010 by the citadel.org team
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
22 * This is a fairly high-level type of critical section. It ensures that no
23 * two threads work on the netconfigs files at the same time. Since we do
24 * so many things inside these, here are the rules:
25 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26 * 2. Do *not* perform any I/O with the client during these sections.
31 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32 * requests that have not been confirmed will be deleted.
34 #define EXP 259200 /* three days */
46 #include <sys/types.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
53 # include <sys/time.h>
62 #include <libcitadel.h>
65 #include "citserver.h"
71 #include "internet_addressing.h"
72 #include "serv_network.h"
73 #include "clientsocket.h"
75 #include "citadel_dirs.h"
84 #include "ctdl_module.h"
88 /* Nonzero while we are doing network processing */
89 static int doing_queue = 0;
92 * When we do network processing, it's accomplished in two passes; one to
93 * gather a list of rooms and one to actually do them. It's ok that rplist
94 * is global; we have a mutex that keeps it safe.
96 struct RoomProcList *rplist = NULL;
99 * We build a map of network nodes during processing.
101 NetMap *the_netmap = NULL;
102 int netmap_changed = 0;
103 char *working_ignetcfg = NULL;
106 * Load or refresh the Citadel network (IGnet) configuration for this node.
108 void load_working_ignetcfg(void) {
112 cfg = CtdlGetSysConfig(IGNETCFG);
117 oldcfg = working_ignetcfg;
118 working_ignetcfg = cfg;
119 if (oldcfg != NULL) {
129 * Keep track of what messages to reject
131 FilterList *load_filter_list(void) {
132 char *serialized_list = NULL;
135 FilterList *newlist = NULL;
138 serialized_list = CtdlGetSysConfig(FILTERLIST);
139 if (serialized_list == NULL) return(NULL); /* if null, no entries */
141 /* Use the string tokenizer to grab one line at a time */
142 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
143 extract_token(buf, serialized_list, i, '\n', sizeof buf);
144 nptr = (FilterList *) malloc(sizeof(FilterList));
145 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
146 striplt(nptr->fl_user);
147 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
148 striplt(nptr->fl_room);
149 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
150 striplt(nptr->fl_node);
152 /* Cowardly refuse to add an any/any/any entry that would
153 * end up filtering every single message.
155 if (IsEmptyStr(nptr->fl_user) &&
156 IsEmptyStr(nptr->fl_room) &&
157 IsEmptyStr(nptr->fl_node)) {
161 nptr->next = newlist;
166 free(serialized_list);
171 void free_filter_list(FilterList *fl) {
172 if (fl == NULL) return;
173 free_filter_list(fl->next);
180 * Check the use table. This is a list of messages which have recently
181 * arrived on the system. It is maintained and queried to prevent the same
182 * message from being entered into the database multiple times if it happens
183 * to arrive multiple times by accident.
185 int network_usetable(struct CtdlMessage *msg) {
188 struct cdbdata *cdbut;
191 /* Bail out if we can't generate a message ID */
195 if (msg->cm_fields['I'] == NULL) {
198 if (IsEmptyStr(msg->cm_fields['I'])) {
202 /* Generate the message ID */
203 strcpy(msgid, msg->cm_fields['I']);
204 if (haschar(msgid, '@') == 0) {
206 if (msg->cm_fields['N'] != NULL) {
207 strcat(msgid, msg->cm_fields['N']);
214 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
217 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
221 /* If we got to this point, it's unique: add it. */
222 strcpy(ut.ut_msgid, msgid);
223 ut.ut_timestamp = time(NULL);
224 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
230 * Read the network map from its configuration file into memory.
232 void read_network_map(void) {
233 char *serialized_map = NULL;
238 serialized_map = CtdlGetSysConfig(IGNETMAP);
239 if (serialized_map == NULL) return; /* if null, no entries */
241 /* Use the string tokenizer to grab one line at a time */
242 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
243 extract_token(buf, serialized_map, i, '\n', sizeof buf);
244 nmptr = (NetMap *) malloc(sizeof(NetMap));
245 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
246 nmptr->lastcontact = extract_long(buf, 1);
247 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
248 nmptr->next = the_netmap;
252 free(serialized_map);
258 * Write the network map from memory back to the configuration file.
260 void write_network_map(void) {
261 char *serialized_map = NULL;
265 if (netmap_changed) {
266 serialized_map = strdup("");
268 if (the_netmap != NULL) {
269 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
270 serialized_map = realloc(serialized_map,
271 (strlen(serialized_map)+SIZ) );
272 if (!IsEmptyStr(nmptr->nodename)) {
273 snprintf(&serialized_map[strlen(serialized_map)],
277 (long)nmptr->lastcontact,
283 CtdlPutSysConfig(IGNETMAP, serialized_map);
284 free(serialized_map);
287 /* Now free the list */
288 while (the_netmap != NULL) {
289 nmptr = the_netmap->next;
299 * Check the network map and determine whether the supplied node name is
300 * valid. If it is not a neighbor node, supply the name of a neighbor node
301 * which is the next hop. If it *is* a neighbor node, we also fill in the
304 int is_valid_node(char *nexthop, char *secret, char *node) {
316 * First try the neighbor nodes
318 if (working_ignetcfg == NULL) {
319 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
320 if (nexthop != NULL) {
327 if (nexthop != NULL) {
331 /* Use the string tokenizer to grab one line at a time */
332 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
333 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
334 extract_token(buf, linebuf, 0, '|', sizeof buf);
335 if (!strcasecmp(buf, node)) {
336 if (nexthop != NULL) {
339 if (secret != NULL) {
340 extract_token(secret, linebuf, 1, '|', 256);
347 return(retval); /* yup, it's a direct neighbor */
351 * If we get to this point we have to see if we know the next hop
353 if (the_netmap != NULL) {
354 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
355 if (!strcasecmp(nmptr->nodename, node)) {
356 if (nexthop != NULL) {
357 strcpy(nexthop, nmptr->nexthop);
365 * If we get to this point, the supplied node name is bogus.
367 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
375 void cmd_gnet(char *argbuf) {
376 char filename[PATH_MAX];
380 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
381 /* users can edit the netconfigs for their own mailbox rooms */
383 else if (CtdlAccessCheck(ac_room_aide)) return;
385 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
386 cprintf("%d Network settings for room #%ld <%s>\n",
388 CC->room.QRnumber, CC->room.QRname);
390 fp = fopen(filename, "r");
392 while (fgets(buf, sizeof buf, fp) != NULL) {
393 buf[strlen(buf)-1] = 0;
394 cprintf("%s\n", buf);
403 void cmd_snet(char *argbuf) {
404 char tempfilename[PATH_MAX];
405 char filename[PATH_MAX];
414 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
415 /* users can edit the netconfigs for their own mailbox rooms */
417 else if (CtdlAccessCheck(ac_room_aide)) return;
419 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
420 memcpy(tempfilename, filename, len + 1);
422 memset(&StatBuf, 0, sizeof(struct stat));
423 if (stat(filename, &StatBuf) == -1)
424 StatBuf.st_size = 80; /* Not there? guess 80 chars line. */
426 sprintf(tempfilename + len, ".%d", CC->cs_pid);
428 TmpFD = open(tempfilename, O_CREAT|O_EXCL);
432 char *tmp = malloc(StatBuf.st_size * 2);
433 memset(tmp, 0, StatBuf.st_size * 2);
434 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
439 cprintf("%d Unable to allocate the space required for %s: %s\n",
440 ERROR + INTERNAL_ERROR,
445 lseek(TmpFD, SEEK_SET, 0);
448 cprintf("%d Unable to allocate the space required for %s: %s\n",
449 ERROR + INTERNAL_ERROR,
457 cprintf("%d %s\n", SEND_LISTING, tempfilename);
460 while (rc = CtdlClientGetLine(Line),
463 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
465 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
466 write(TmpFD, ChrPtr(Line), StrLength(Line));
467 len += StrLength(Line);
470 ftruncate(TmpFD, len + 1);
473 /* Now copy the temp file to its permanent location.
474 * (We copy instead of link because they may be on different filesystems)
476 begin_critical_section(S_NETCONFIGS);
477 rename(filename, tempfilename);
478 end_critical_section(S_NETCONFIGS);
483 * Deliver digest messages
485 void network_deliver_digest(SpoolControl *sc) {
488 struct CtdlMessage *msg = NULL;
491 size_t recps_len = SIZ;
493 struct recptypes *valid;
497 if (sc->num_msgs_spooled < 1) {
498 fclose(sc->digestfp);
503 msg = malloc(sizeof(struct CtdlMessage));
504 memset(msg, 0, sizeof(struct CtdlMessage));
505 msg->cm_magic = CTDLMESSAGE_MAGIC;
506 msg->cm_format_type = FMT_RFC822;
507 msg->cm_anon_type = MES_NORMAL;
509 sprintf(buf, "%ld", time(NULL));
510 msg->cm_fields['T'] = strdup(buf);
511 msg->cm_fields['A'] = strdup(CC->room.QRname);
512 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
513 msg->cm_fields['U'] = strdup(buf);
514 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
515 for (i=0; buf[i]; ++i) {
516 if (isspace(buf[i])) buf[i]='_';
517 buf[i] = tolower(buf[i]);
519 msg->cm_fields['F'] = strdup(buf);
520 msg->cm_fields['R'] = strdup(buf);
522 /* Set the 'List-ID' header */
523 msg->cm_fields['L'] = malloc(1024);
524 snprintf(msg->cm_fields['L'], 1024,
525 "%s <%ld.list-id.%s>",
532 * Go fetch the contents of the digest
534 fseek(sc->digestfp, 0L, SEEK_END);
535 msglen = ftell(sc->digestfp);
537 msg->cm_fields['M'] = malloc(msglen + 1);
538 fseek(sc->digestfp, 0L, SEEK_SET);
539 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
540 msg->cm_fields['M'][msglen] = '\0';
542 fclose(sc->digestfp);
545 /* Now generate the delivery instructions */
548 * Figure out how big a buffer we need to allocate
550 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
551 recps_len = recps_len + strlen(nptr->name) + 2;
554 recps = malloc(recps_len);
557 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
564 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
565 if (nptr != sc->digestrecps) {
568 strcat(recps, nptr->name);
571 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
572 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
574 /* Now submit the message */
575 valid = validate_recipients(recps, NULL, 0);
578 valid->bounce_to = strdup(bounce_to);
579 valid->envelope_from = strdup(bounce_to);
580 CtdlSubmitMsg(msg, valid, NULL, 0);
582 CtdlFreeMessage(msg);
583 free_recipients(valid);
588 * Deliver list messages to everyone on the list ... efficiently
590 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
592 size_t recps_len = SIZ;
593 struct recptypes *valid;
597 /* Don't do this if there were no recipients! */
598 if (sc->listrecps == NULL) return;
600 /* Now generate the delivery instructions */
603 * Figure out how big a buffer we need to allocate
605 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
606 recps_len = recps_len + strlen(nptr->name) + 2;
609 recps = malloc(recps_len);
612 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
619 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
620 if (nptr != sc->listrecps) {
623 strcat(recps, nptr->name);
626 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
627 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
629 /* Now submit the message */
630 valid = validate_recipients(recps, NULL, 0);
633 valid->bounce_to = strdup(bounce_to);
634 valid->envelope_from = strdup(bounce_to);
635 CtdlSubmitMsg(msg, valid, NULL, 0);
636 free_recipients(valid);
638 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
645 * Spools out one message from the list.
647 void network_spool_msg(long msgnum, void *userdata) {
650 char *newpath = NULL;
651 size_t instr_len = SIZ;
652 struct CtdlMessage *msg = NULL;
655 struct ser_ret sermsg;
657 char filename[PATH_MAX];
661 int delete_after_send = 0; /* Set to 1 to delete after spooling */
662 int ok_to_participate = 0;
663 struct recptypes *valid;
665 sc = (SpoolControl *)userdata;
668 * Process mailing list recipients
671 if (sc->listrecps != NULL) {
672 /* Fetch the message. We're going to need to modify it
673 * in order to insert the [list name] in it, etc.
675 msg = CtdlFetchMessage(msgnum, 1);
677 if (msg->cm_fields['V'] == NULL){
678 /* local message, no enVelope */
681 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
682 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
683 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
685 msg->cm_fields['K'] = SmashStrBuf(&Buf);
688 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
690 /* Set the 'List-ID' header */
691 if (msg->cm_fields['L'] != NULL) {
692 free(msg->cm_fields['L']);
694 msg->cm_fields['L'] = malloc(1024);
695 snprintf(msg->cm_fields['L'], 1024,
696 "%s <%ld.list-id.%s>",
702 /* Prepend "[List name]" to the subject */
703 if (msg->cm_fields['U'] == NULL) {
704 msg->cm_fields['U'] = strdup("(no subject)");
706 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
707 free(msg->cm_fields['U']);
708 msg->cm_fields['U'] = strdup(buf);
710 /* Set the recipient of the list message to the
711 * email address of the room itself.
712 * FIXME ... I want to be able to pick any address
714 if (msg->cm_fields['R'] != NULL) {
715 free(msg->cm_fields['R']);
717 msg->cm_fields['R'] = malloc(256);
718 snprintf(msg->cm_fields['R'], 256,
719 "room_%s@%s", CC->room.QRname,
721 for (i=0; msg->cm_fields['R'][i]; ++i) {
722 if (isspace(msg->cm_fields['R'][i])) {
723 msg->cm_fields['R'][i] = '_';
727 /* Handle delivery */
728 network_deliver_list(msg, sc);
729 CtdlFreeMessage(msg);
734 * Process digest recipients
736 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
737 msg = CtdlFetchMessage(msgnum, 1);
739 fprintf(sc->digestfp, " -----------------------------------"
740 "------------------------------------"
742 fprintf(sc->digestfp, "From: ");
743 if (msg->cm_fields['A'] != NULL) {
744 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
746 if (msg->cm_fields['F'] != NULL) {
747 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
749 else if (msg->cm_fields['N'] != NULL) {
750 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
752 fprintf(sc->digestfp, "\n");
753 if (msg->cm_fields['U'] != NULL) {
754 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
757 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
759 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
760 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
762 StrBufTrim(CC->redirect_buffer);
763 fwrite(HKEY("\n"), 1, sc->digestfp);
764 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
765 fwrite(HKEY("\n"), 1, sc->digestfp);
767 FreeStrBuf(&CC->redirect_buffer);
769 sc->num_msgs_spooled += 1;
775 * Process client-side list participations for this room
778 if (sc->participates != NULL) {
779 msg = CtdlFetchMessage(msgnum, 1);
782 /* Only send messages which originated on our own Citadel
783 * network, otherwise we'll end up sending the remote
784 * mailing list's messages back to it, which is rude...
786 ok_to_participate = 0;
787 if (msg->cm_fields['N'] != NULL) {
788 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
789 ok_to_participate = 1;
791 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
792 ok_to_participate = 1;
795 if (ok_to_participate) {
796 if (msg->cm_fields['F'] != NULL) {
797 free(msg->cm_fields['F']);
799 msg->cm_fields['F'] = malloc(SIZ);
800 /* Replace the Internet email address of the actual
801 * author with the email address of the room itself,
802 * so the remote listserv doesn't reject us.
803 * FIXME ... I want to be able to pick any address
805 snprintf(msg->cm_fields['F'], SIZ,
806 "room_%s@%s", CC->room.QRname,
808 for (i=0; msg->cm_fields['F'][i]; ++i) {
809 if (isspace(msg->cm_fields['F'][i])) {
810 msg->cm_fields['F'][i] = '_';
815 * Figure out how big a buffer we need to allocate
817 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
819 if (msg->cm_fields['R'] == NULL) {
820 free(msg->cm_fields['R']);
822 msg->cm_fields['R'] = strdup(nptr->name);
824 valid = validate_recipients(nptr->name, NULL, 0);
825 CtdlSubmitMsg(msg, valid, "", 0);
826 free_recipients(valid);
830 CtdlFreeMessage(msg);
835 * Process IGnet push shares
837 msg = CtdlFetchMessage(msgnum, 1);
841 /* Prepend our node name to the Path field whenever
842 * sending a message to another IGnet node
844 if (msg->cm_fields['P'] == NULL) {
845 msg->cm_fields['P'] = strdup("username");
847 newpath_len = strlen(msg->cm_fields['P']) +
848 strlen(config.c_nodename) + 2;
849 newpath = malloc(newpath_len);
850 snprintf(newpath, newpath_len, "%s!%s",
851 config.c_nodename, msg->cm_fields['P']);
852 free(msg->cm_fields['P']);
853 msg->cm_fields['P'] = newpath;
856 * Determine if this message is set to be deleted
857 * after sending out on the network
859 if (msg->cm_fields['S'] != NULL) {
860 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
861 delete_after_send = 1;
865 /* Now send it to every node */
866 if (sc->ignet_push_shares != NULL)
867 for (mptr = sc->ignet_push_shares; mptr != NULL;
872 /* Check for valid node name */
873 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
874 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
878 /* Check for split horizon */
879 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
880 bang = num_tokens(msg->cm_fields['P'], '!');
881 if (bang > 1) for (i=0; i<(bang-1); ++i) {
882 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
883 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
884 buf, mptr->remote_nodename) ;
885 if (!strcasecmp(buf, mptr->remote_nodename)) {
887 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
888 mptr->remote_nodename);
891 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
895 /* Send the message */
899 * Force the message to appear in the correct room
900 * on the far end by setting the C field correctly
902 if (msg->cm_fields['C'] != NULL) {
903 free(msg->cm_fields['C']);
905 if (!IsEmptyStr(mptr->remote_roomname)) {
906 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
909 msg->cm_fields['C'] = strdup(CC->room.QRname);
912 /* serialize it for transmission */
913 serialize_message(&sermsg, msg);
914 if (sermsg.len > 0) {
916 /* write it to a spool file */
917 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
919 mptr->remote_nodename,
923 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
924 fp = fopen(filename, "ab");
931 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
934 /* free the serialized version */
940 CtdlFreeMessage(msg);
943 /* update lastsent */
944 sc->lastsent = msgnum;
946 /* Delete this message if delete-after-send is set */
947 if (delete_after_send) {
948 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
954 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
960 char roomname[ROOMNAMELEN];
963 int skipthisline = 0;
964 namelist *nptr = NULL;
965 maplist *mptr = NULL;
968 fp = fopen(filename, "r");
972 sc = malloc(sizeof(SpoolControl));
973 memset(sc, 0, sizeof(SpoolControl));
976 while (fgets(buf, sizeof buf, fp) != NULL) {
977 buf[strlen(buf)-1] = 0;
979 extract_token(instr, buf, 0, '|', sizeof instr);
980 if (!strcasecmp(instr, strof(lastsent))) {
981 sc->lastsent = extract_long(buf, 1);
983 else if (!strcasecmp(instr, strof(listrecp))) {
985 malloc(sizeof(namelist));
986 nptr->next = sc->listrecps;
987 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
988 sc->listrecps = nptr;
990 else if (!strcasecmp(instr, strof(participate))) {
992 malloc(sizeof(namelist));
993 nptr->next = sc->participates;
994 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
995 sc->participates = nptr;
997 else if (!strcasecmp(instr, strof(digestrecp))) {
999 malloc(sizeof(namelist));
1000 nptr->next = sc->digestrecps;
1001 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1002 sc->digestrecps = nptr;
1004 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1005 extract_token(nodename, buf, 1, '|', sizeof nodename);
1006 extract_token(roomname, buf, 2, '|', sizeof roomname);
1007 mptr = (maplist *) malloc(sizeof(maplist));
1008 mptr->next = sc->ignet_push_shares;
1009 strcpy(mptr->remote_nodename, nodename);
1010 strcpy(mptr->remote_roomname, roomname);
1011 sc->ignet_push_shares = mptr;
1014 /* Preserve 'other' lines ... *unless* they happen to
1015 * be subscribe/unsubscribe pendings with expired
1019 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1020 if (time(NULL) - extract_long(buf, 4) > EXP) {
1024 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1025 if (time(NULL) - extract_long(buf, 3) > EXP) {
1030 if (skipthisline == 0) {
1031 linesize = strlen(buf);
1032 sc->misc = realloc(sc->misc,
1033 (miscsize + linesize + 2) );
1034 sprintf(&sc->misc[miscsize], "%s\n", buf);
1035 miscsize = miscsize + linesize + 1;
1045 void free_spoolcontrol_struct(SpoolControl **scc)
1048 namelist *nptr = NULL;
1049 maplist *mptr = NULL;
1052 while (sc->listrecps != NULL) {
1053 nptr = sc->listrecps->next;
1054 free(sc->listrecps);
1055 sc->listrecps = nptr;
1057 /* Do the same for digestrecps */
1058 while (sc->digestrecps != NULL) {
1059 nptr = sc->digestrecps->next;
1060 free(sc->digestrecps);
1061 sc->digestrecps = nptr;
1063 /* Do the same for participates */
1064 while (sc->participates != NULL) {
1065 nptr = sc->participates->next;
1066 free(sc->participates);
1067 sc->participates = nptr;
1069 while (sc->ignet_push_shares != NULL) {
1070 mptr = sc->ignet_push_shares->next;
1071 free(sc->ignet_push_shares);
1072 sc->ignet_push_shares = mptr;
1079 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1083 namelist *nptr = NULL;
1084 maplist *mptr = NULL;
1087 fp = fopen(filename, "w");
1089 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1090 filename, strerror(errno));
1091 free_spoolcontrol_struct(scc);
1094 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1096 /* Write out the listrecps while freeing from memory at the
1097 * same time. Am I clever or what? :)
1099 while (sc->listrecps != NULL) {
1100 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1101 nptr = sc->listrecps->next;
1102 free(sc->listrecps);
1103 sc->listrecps = nptr;
1105 /* Do the same for digestrecps */
1106 while (sc->digestrecps != NULL) {
1107 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1108 nptr = sc->digestrecps->next;
1109 free(sc->digestrecps);
1110 sc->digestrecps = nptr;
1112 /* Do the same for participates */
1113 while (sc->participates != NULL) {
1114 fprintf(fp, "participate|%s\n", sc->participates->name);
1115 nptr = sc->participates->next;
1116 free(sc->participates);
1117 sc->participates = nptr;
1119 while (sc->ignet_push_shares != NULL) {
1120 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1121 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1122 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1125 mptr = sc->ignet_push_shares->next;
1126 free(sc->ignet_push_shares);
1127 sc->ignet_push_shares = mptr;
1129 if (sc->misc != NULL) {
1130 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1140 int is_recipient(SpoolControl *sc, const char *Name)
1146 nptr = sc->listrecps;
1147 while (nptr != NULL) {
1148 if (strncmp(Name, nptr->name, len)==0)
1152 /* Do the same for digestrecps */
1153 nptr = sc->digestrecps;
1154 while (nptr != NULL) {
1155 if (strncmp(Name, nptr->name, len)==0)
1159 /* Do the same for participates */
1160 nptr = sc->participates;
1161 while (nptr != NULL) {
1162 if (strncmp(Name, nptr->name, len)==0)
1171 * Batch up and send all outbound traffic from the current room
1173 void network_spoolout_room(char *room_to_spool) {
1175 char filename[PATH_MAX];
1180 * If the room doesn't exist, don't try to perform its networking tasks.
1181 * Normally this should never happen, but once in a while maybe a room gets
1182 * queued for networking and then deleted before it can happen.
1184 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1185 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1189 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1190 begin_critical_section(S_NETCONFIGS);
1192 /* Only do net processing for rooms that have netconfigs */
1193 if (!read_spoolcontrol_file(&sc, filename))
1195 end_critical_section(S_NETCONFIGS);
1198 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1200 /* If there are digest recipients, we have to build a digest */
1201 if (sc->digestrecps != NULL) {
1202 sc->digestfp = tmpfile();
1203 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1206 /* Do something useful */
1207 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1208 network_spool_msg, sc);
1210 /* If we wrote a digest, deliver it and then close it */
1211 snprintf(buf, sizeof buf, "room_%s@%s",
1212 CC->room.QRname, config.c_fqdn);
1213 for (i=0; buf[i]; ++i) {
1214 buf[i] = tolower(buf[i]);
1215 if (isspace(buf[i])) buf[i] = '_';
1217 if (sc->digestfp != NULL) {
1218 fprintf(sc->digestfp, " -----------------------------------"
1219 "------------------------------------"
1221 "You are subscribed to the '%s' "
1223 "To post to the list: %s\n",
1224 CC->room.QRname, buf
1226 network_deliver_digest(sc); /* deliver and close */
1229 /* Now rewrite the config file */
1230 writenfree_spoolcontrol_file (&sc, filename);
1231 end_critical_section(S_NETCONFIGS);
1237 * Send the *entire* contents of the current room to one specific network node,
1238 * ignoring anything we know about which messages have already undergone
1239 * network processing. This can be used to bring a new node into sync.
1241 int network_sync_to(char *target_node) {
1243 int num_spooled = 0;
1249 char filename[PATH_MAX];
1252 /* Grab the configuration line we're looking for */
1253 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1254 begin_critical_section(S_NETCONFIGS);
1255 fp = fopen(filename, "r");
1257 end_critical_section(S_NETCONFIGS);
1260 while (fgets(buf, sizeof buf, fp) != NULL) {
1261 buf[strlen(buf)-1] = 0;
1262 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1263 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1264 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1265 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1266 && (!strcasecmp(sc_node, target_node)) ) {
1269 /* Concise syntax because we don't need a full linked-list */
1270 memset(&sc, 0, sizeof(SpoolControl));
1271 sc.ignet_push_shares = (maplist *)
1272 malloc(sizeof(maplist));
1273 sc.ignet_push_shares->next = NULL;
1274 safestrncpy(sc.ignet_push_shares->remote_nodename,
1276 sizeof sc.ignet_push_shares->remote_nodename);
1277 safestrncpy(sc.ignet_push_shares->remote_roomname,
1279 sizeof sc.ignet_push_shares->remote_roomname);
1283 end_critical_section(S_NETCONFIGS);
1285 if (!found_node) return(-1);
1287 /* Send ALL messages */
1288 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1289 network_spool_msg, &sc);
1291 /* Concise cleanup because we know there's only one node in the sc */
1292 free(sc.ignet_push_shares);
1294 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1295 num_spooled, target_node);
1296 return(num_spooled);
1301 * Implements the NSYN command
1303 void cmd_nsyn(char *argbuf) {
1305 char target_node[256];
1307 if (CtdlAccessCheck(ac_aide)) return;
1309 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1310 num_spooled = network_sync_to(target_node);
1311 if (num_spooled >= 0) {
1312 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1315 cprintf("%d No such room/node share exists.\n",
1316 ERROR + ROOM_NOT_FOUND);
1323 * Batch up and send all outbound traffic from the current room
1325 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1326 struct RoomProcList *ptr;
1328 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1329 if (ptr == NULL) return;
1331 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1332 begin_critical_section(S_RPLIST);
1335 end_critical_section(S_RPLIST);
1338 void destroy_network_queue_room(void)
1340 struct RoomProcList *cur, *p;
1341 NetMap *nmcur, *nmp;
1344 begin_critical_section(S_RPLIST);
1352 end_critical_section(S_RPLIST);
1355 while (nmcur != NULL)
1362 if (working_ignetcfg != NULL)
1363 free (working_ignetcfg);
1364 working_ignetcfg = NULL;
1369 * Learn topology from path fields
1371 void network_learn_topology(char *node, char *path) {
1375 strcpy(nexthop, "");
1377 if (num_tokens(path, '!') < 3) return;
1378 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1379 if (!strcasecmp(nmptr->nodename, node)) {
1380 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1381 nmptr->lastcontact = time(NULL);
1387 /* If we got here then it's not in the map, so add it. */
1388 nmptr = (NetMap *) malloc(sizeof (NetMap));
1389 strcpy(nmptr->nodename, node);
1390 nmptr->lastcontact = time(NULL);
1391 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1392 nmptr->next = the_netmap;
1401 * Bounce a message back to the sender
1403 void network_bounce(struct CtdlMessage *msg, char *reason) {
1404 char *oldpath = NULL;
1406 char bouncesource[SIZ];
1407 char recipient[SIZ];
1408 struct recptypes *valid = NULL;
1409 char force_room[ROOMNAMELEN];
1410 static int serialnum = 0;
1413 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1415 if (msg == NULL) return;
1417 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1420 * Give it a fresh message ID
1422 if (msg->cm_fields['I'] != NULL) {
1423 free(msg->cm_fields['I']);
1425 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1426 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1427 msg->cm_fields['I'] = strdup(buf);
1430 * FIXME ... right now we're just sending a bounce; we really want to
1431 * include the text of the bounced message.
1433 if (msg->cm_fields['M'] != NULL) {
1434 free(msg->cm_fields['M']);
1436 msg->cm_fields['M'] = strdup(reason);
1437 msg->cm_format_type = 0;
1440 * Turn the message around
1442 if (msg->cm_fields['R'] == NULL) {
1443 free(msg->cm_fields['R']);
1446 if (msg->cm_fields['D'] == NULL) {
1447 free(msg->cm_fields['D']);
1450 snprintf(recipient, sizeof recipient, "%s@%s",
1451 msg->cm_fields['A'], msg->cm_fields['N']);
1453 if (msg->cm_fields['A'] == NULL) {
1454 free(msg->cm_fields['A']);
1457 if (msg->cm_fields['N'] == NULL) {
1458 free(msg->cm_fields['N']);
1461 if (msg->cm_fields['U'] == NULL) {
1462 free(msg->cm_fields['U']);
1465 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1466 msg->cm_fields['N'] = strdup(config.c_nodename);
1467 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
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", config.c_nodename, oldpath);
1482 /* Now submit the message */
1483 valid = validate_recipients(recipient, NULL, 0);
1484 if (valid != NULL) if (valid->num_error != 0) {
1485 free_recipients(valid);
1488 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1489 strcpy(force_room, config.c_aideroom);
1492 strcpy(force_room, "");
1494 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1495 strcpy(force_room, config.c_aideroom);
1497 CtdlSubmitMsg(msg, valid, force_room, 0);
1500 if (valid != NULL) free_recipients(valid);
1501 CtdlFreeMessage(msg);
1502 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1509 * Process a buffer containing a single message from a single file
1510 * from the inbound queue
1512 void network_process_buffer(char *buffer, long size) {
1513 struct CtdlMessage *msg = NULL;
1516 struct recptypes *recp = NULL;
1517 char target_room[ROOMNAMELEN];
1518 struct ser_ret sermsg;
1519 char *oldpath = NULL;
1520 char filename[PATH_MAX];
1523 unsigned char firstbyte;
1524 unsigned char lastbyte;
1526 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1528 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1529 firstbyte = buffer[0];
1530 lastbyte = buffer[size-1];
1531 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1532 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1533 size, firstbyte, lastbyte);
1537 /* Set default target room to trash */
1538 strcpy(target_room, TWITROOM);
1540 /* Load the message into memory */
1541 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1542 memset(msg, 0, sizeof(struct CtdlMessage));
1543 msg->cm_magic = CTDLMESSAGE_MAGIC;
1544 msg->cm_anon_type = buffer[1];
1545 msg->cm_format_type = buffer[2];
1547 for (pos = 3; pos < size; ++pos) {
1548 field = buffer[pos];
1549 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1550 pos = pos + strlen(&buffer[(int)pos]);
1553 /* Check for message routing */
1554 if (msg->cm_fields['D'] != NULL) {
1555 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1557 /* route the message */
1558 strcpy(nexthop, "");
1559 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1560 /* prepend our node to the path */
1561 if (msg->cm_fields['P'] != NULL) {
1562 oldpath = msg->cm_fields['P'];
1563 msg->cm_fields['P'] = NULL;
1566 oldpath = strdup("unknown_user");
1568 size = strlen(oldpath) + SIZ;
1569 msg->cm_fields['P'] = malloc(size);
1570 snprintf(msg->cm_fields['P'], size, "%s!%s",
1571 config.c_nodename, oldpath);
1574 /* serialize the message */
1575 serialize_message(&sermsg, msg);
1578 if (IsEmptyStr(nexthop)) {
1579 strcpy(nexthop, msg->cm_fields['D']);
1589 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1590 fp = fopen(filename, "ab");
1592 fwrite(sermsg.ser, sermsg.len, 1, fp);
1596 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1599 CtdlFreeMessage(msg);
1603 else { /* invalid destination node name */
1606 "A message you sent could not be delivered due to an invalid destination node"
1607 " name. Please check the address and try sending the message again.\n");
1616 * Check to see if we already have a copy of this message, and
1617 * abort its processing if so. (We used to post a warning to Aide>
1618 * every time this happened, but the network is now so densely
1619 * connected that it's inevitable.)
1621 if (network_usetable(msg) != 0) {
1622 CtdlFreeMessage(msg);
1626 /* Learn network topology from the path */
1627 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1628 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1631 /* Is the sending node giving us a very persuasive suggestion about
1632 * which room this message should be saved in? If so, go with that.
1634 if (msg->cm_fields['C'] != NULL) {
1635 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1638 /* Otherwise, does it have a recipient? If so, validate it... */
1639 else if (msg->cm_fields['R'] != NULL) {
1640 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1641 if (recp != NULL) if (recp->num_error != 0) {
1643 "A message you sent could not be delivered due to an invalid address.\n"
1644 "Please check the address and try sending the message again.\n");
1646 free_recipients(recp);
1647 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1650 strcpy(target_room, ""); /* no target room if mail */
1653 /* Our last shot at finding a home for this message is to see if
1654 * it has the O field (Originating room) set.
1656 else if (msg->cm_fields['O'] != NULL) {
1657 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1660 /* Strip out fields that are only relevant during transit */
1661 if (msg->cm_fields['D'] != NULL) {
1662 free(msg->cm_fields['D']);
1663 msg->cm_fields['D'] = NULL;
1665 if (msg->cm_fields['C'] != NULL) {
1666 free(msg->cm_fields['C']);
1667 msg->cm_fields['C'] = NULL;
1670 /* save the message into a room */
1671 if (PerformNetprocHooks(msg, target_room) == 0) {
1672 msg->cm_flags = CM_SKIP_HOOKS;
1673 CtdlSubmitMsg(msg, recp, target_room, 0);
1675 CtdlFreeMessage(msg);
1676 free_recipients(recp);
1681 * Process a single message from a single file from the inbound queue
1683 void network_process_message(FILE *fp, long msgstart, long msgend) {
1688 hold_pos = ftell(fp);
1689 size = msgend - msgstart + 1;
1690 buffer = malloc(size);
1691 if (buffer != NULL) {
1692 fseek(fp, msgstart, SEEK_SET);
1693 if (fread(buffer, size, 1, fp) > 0) {
1694 network_process_buffer(buffer, size);
1699 fseek(fp, hold_pos, SEEK_SET);
1704 * Process a single file from the inbound queue
1706 void network_process_file(char *filename) {
1708 long msgstart = (-1L);
1709 long msgend = (-1L);
1714 fp = fopen(filename, "rb");
1716 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1720 fseek(fp, 0L, SEEK_END);
1721 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1724 /* Look for messages in the data stream and break them out */
1725 while (ch = getc(fp), ch >= 0) {
1728 if (msgstart >= 0L) {
1729 msgend = msgcur - 1;
1730 network_process_message(fp, msgstart, msgend);
1738 msgend = msgcur - 1;
1739 if (msgstart >= 0L) {
1740 network_process_message(fp, msgstart, msgend);
1749 * Process anything in the inbound queue
1751 void network_do_spoolin(void) {
1754 struct stat statbuf;
1755 char filename[PATH_MAX];
1756 static time_t last_spoolin_mtime = 0L;
1759 * Check the spoolin directory's modification time. If it hasn't
1760 * been touched, we don't need to scan it.
1762 if (stat(ctdl_netin_dir, &statbuf)) return;
1763 if (statbuf.st_mtime == last_spoolin_mtime) {
1764 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1767 last_spoolin_mtime = statbuf.st_mtime;
1768 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1771 * Ok, there's something interesting in there, so scan it.
1773 dp = opendir(ctdl_netin_dir);
1774 if (dp == NULL) return;
1776 while (d = readdir(dp), d != NULL) {
1777 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1784 network_process_file(filename);
1792 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1793 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1795 void network_consolidate_spoolout(void) {
1798 char filename[PATH_MAX];
1804 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1805 dp = opendir(ctdl_netout_dir);
1806 if (dp == NULL) return;
1807 while (d = readdir(dp), d != NULL) {
1809 (strcmp(d->d_name, "."))
1810 && (strcmp(d->d_name, ".."))
1811 && (strchr(d->d_name, '@') != NULL)
1813 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1814 ptr = strchr(nexthop, '@');
1824 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1825 if (network_talking_to(nexthop, NTT_CHECK)) {
1826 CtdlLogPrintf(CTDL_DEBUG,
1827 "Currently online with %s - skipping for now\n",
1832 network_talking_to(nexthop, NTT_ADD);
1833 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1835 ctdl_netout_dir, nexthop,
1839 network_talking_to(nexthop, NTT_REMOVE);
1845 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1847 dp = opendir(ctdl_netout_dir);
1848 if (dp == NULL) return;
1850 while (d = readdir(dp), d != NULL) {
1851 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1853 ptr = strchr(d->d_name, '@');
1863 strcpy(nexthop, "");
1864 i = is_valid_node(nexthop, NULL, d->d_name);
1866 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1877 * receive network spool from the remote system
1879 void receive_spool(int *sock, char *remote_nodename) {
1880 long download_len = 0L;
1881 long bytes_received = 0L;
1883 static char pbuf[IGNET_PACKET_SIZE];
1884 char tempfilename[PATH_MAX];
1885 char permfilename[PATH_MAX];
1889 snprintf(tempfilename,
1890 sizeof tempfilename,
1898 snprintf(permfilename,
1899 sizeof permfilename,
1907 if (sock_puts(sock, "NDOP") < 0) return;
1908 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1909 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1910 if (buf[0] != '2') {
1913 download_len = extract_long(&buf[4], 0);
1915 if (download_len>0) {
1916 bytes_received = 0L;
1917 fp = fopen(tempfilename, "w");
1919 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1924 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1925 while (bytes_received < download_len) {
1927 * If shutting down we can exit here and unlink the temp file.
1928 * this shouldn't loose us any messages.
1930 if (CtdlThreadCheckStop())
1933 unlink(tempfilename);
1936 snprintf(buf, sizeof buf, "READ %ld|%ld",
1938 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1939 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1941 if (sock_puts(sock, buf) < 0) {
1943 unlink(tempfilename);
1946 if (sock_getln(sock, buf, sizeof buf) < 0) {
1948 unlink(tempfilename);
1952 if (buf[0] == '6') {
1953 plen = extract_long(&buf[4], 0);
1954 if (sock_read(sock, pbuf, plen, 1) < 0) {
1956 unlink(tempfilename);
1959 fwrite((char *) pbuf, plen, 1, fp);
1960 bytes_received = bytes_received + plen;
1966 /* Last chance for shutdown exit */
1967 if (CtdlThreadCheckStop())
1969 unlink(tempfilename);
1973 if (sock_puts(sock, "CLOS") < 0) {
1974 unlink(tempfilename);
1979 * From here on we must complete or messages will get lost
1981 if (sock_getln(sock, buf, sizeof buf) < 0) {
1982 unlink(tempfilename);
1985 if (download_len > 0) {
1986 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1988 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1990 /* Now move the temp file to its permanent location.
1992 if (link(tempfilename, permfilename) != 0) {
1993 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
1994 tempfilename, permfilename, strerror(errno)
1997 unlink(tempfilename);
2003 * transmit network spool to the remote system
2005 void transmit_spool(int *sock, char *remote_nodename)
2010 long bytes_to_write, thisblock, bytes_written;
2014 if (sock_puts(sock, "NUOP") < 0) return;
2015 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2016 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2017 if (buf[0] != '2') {
2021 snprintf(sfname, sizeof sfname,
2026 fd = open(sfname, O_RDONLY);
2028 if (errno != ENOENT) {
2029 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2034 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2035 bytes_to_write = plen;
2036 while (bytes_to_write > 0L) {
2037 /* Exit if shutting down */
2038 if (CtdlThreadCheckStop())
2044 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2045 if (sock_puts(sock, buf) < 0) {
2049 if (sock_getln(sock, buf, sizeof buf) < 0) {
2053 thisblock = atol(&buf[4]);
2054 if (buf[0] == '7') {
2055 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2059 bytes_to_write -= thisblock;
2060 bytes_written += thisblock;
2070 /* Last chance for shutdown exit */
2071 if(CtdlThreadCheckStop())
2074 if (sock_puts(sock, "UCLS 1") < 0) return;
2077 * From here on we must complete or messages will get lost
2079 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2080 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2081 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2082 if (buf[0] == '2') {
2083 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2091 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2093 void network_poll_node(char *node, char *secret, char *host, char *port) {
2097 char connected_to[SIZ];
2100 if (network_talking_to(node, NTT_CHECK)) return;
2101 network_talking_to(node, NTT_ADD);
2102 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2103 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2105 sock = sock_connect(host, port);
2107 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2108 network_talking_to(node, NTT_REMOVE);
2112 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2113 CCC->sReadBuf = NewStrBuf();
2114 CCC->sMigrateBuf = NewStrBuf();
2117 /* Read the server greeting */
2118 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2119 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2121 /* Check that the remote is who we think it is and warn the Aide if not */
2122 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2123 if (strcmp(connected_to, node))
2125 snprintf(err_buf, sizeof(err_buf),
2126 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2129 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2130 CtdlAideMessage(err_buf, "Network error");
2133 /* We're talking to the correct node. Now identify ourselves. */
2134 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2135 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2136 if (sock_puts(&sock, buf) <0) goto bail;
2137 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2138 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2139 if (buf[0] != '2') {
2143 /* At this point we are authenticated. */
2144 if (!CtdlThreadCheckStop())
2145 receive_spool(&sock, node);
2146 if (!CtdlThreadCheckStop())
2147 transmit_spool(&sock, node);
2150 sock_puts(&sock, "QUIT");
2152 FreeStrBuf(&CCC->sReadBuf);
2153 FreeStrBuf(&CCC->sMigrateBuf);
2156 network_talking_to(node, NTT_REMOVE);
2162 * Poll other Citadel nodes and transfer inbound/outbound network data.
2163 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2164 * only nodes to which we have data to send.
2166 void network_poll_other_citadel_nodes(int full_poll) {
2174 char spoolfile[256];
2176 if (working_ignetcfg == NULL) {
2177 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2181 /* Use the string tokenizer to grab one line at a time */
2182 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2183 if(CtdlThreadCheckStop())
2185 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2186 extract_token(node, linebuf, 0, '|', sizeof node);
2187 extract_token(secret, linebuf, 1, '|', sizeof secret);
2188 extract_token(host, linebuf, 2, '|', sizeof host);
2189 extract_token(port, linebuf, 3, '|', sizeof port);
2190 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2191 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2200 if (access(spoolfile, R_OK) == 0) {
2205 network_poll_node(node, secret, host, port);
2216 * It's ok if these directories already exist. Just fail silently.
2218 void create_spool_dirs(void) {
2219 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2220 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2221 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2222 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2223 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2224 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2225 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2226 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2227 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2228 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2229 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2230 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2231 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2232 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2233 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2234 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2242 * network_do_queue()
2244 * Run through the rooms doing various types of network stuff.
2246 void network_do_queue(void) {
2247 static time_t last_run = 0L;
2248 struct RoomProcList *ptr;
2249 int full_processing = 1;
2252 * Run the full set of processing tasks no more frequently
2253 * than once every n seconds
2255 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2256 full_processing = 0;
2257 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2258 config.c_net_freq - (time(NULL)- last_run)
2263 * This is a simple concurrency check to make sure only one queue run
2264 * is done at a time. We could do this with a mutex, but since we
2265 * don't really require extremely fine granularity here, we'll do it
2266 * with a static variable instead.
2273 /* Load the IGnet Configuration into memory */
2274 load_working_ignetcfg();
2277 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2278 * then we poll everyone. Otherwise we only poll nodes we have stuff
2281 network_poll_other_citadel_nodes(full_processing);
2284 * Load the network map and filter list into memory.
2287 filterlist = load_filter_list();
2290 * Go ahead and run the queue
2292 if (full_processing && !CtdlThreadCheckStop()) {
2293 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2294 CtdlForEachRoom(network_queue_room, NULL);
2297 if (rplist != NULL) {
2298 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2299 while (rplist != NULL && !CtdlThreadCheckStop()) {
2300 char spoolroomname[ROOMNAMELEN];
2301 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2302 begin_critical_section(S_RPLIST);
2304 /* pop this record off the list */
2306 rplist = rplist->next;
2309 /* invalidate any duplicate entries to prevent double processing */
2310 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2311 if (!strcasecmp(ptr->name, spoolroomname)) {
2316 end_critical_section(S_RPLIST);
2317 if (spoolroomname[0] != 0) {
2318 network_spoolout_room(spoolroomname);
2323 /* If there is anything in the inbound queue, process it */
2324 if (!CtdlThreadCheckStop()) {
2325 network_do_spoolin();
2328 /* Save the network map back to disk */
2329 write_network_map();
2331 /* Free the filter list in memory */
2332 free_filter_list(filterlist);
2335 network_consolidate_spoolout();
2337 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2339 if (full_processing) {
2340 last_run = time(NULL);
2348 * cmd_netp() - authenticate to the server as another Citadel node polling
2349 * for network traffic
2351 void cmd_netp(char *cmdbuf)
2362 extract_token(node, cmdbuf, 0, '|', sizeof node);
2363 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2365 /* load the IGnet Configuration to check node validity */
2366 load_working_ignetcfg();
2367 v = is_valid_node(nexthop, secret, node);
2370 snprintf(err_buf, sizeof err_buf,
2371 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2372 node, CC->cs_host, CC->cs_addr
2374 CtdlLogPrintf(CTDL_WARNING, err_buf);
2375 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2376 CtdlAideMessage(err_buf, "IGNet Networking.");
2380 if (strcasecmp(pass, secret)) {
2381 snprintf(err_buf, sizeof err_buf,
2382 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2383 CC->cs_host, CC->cs_addr, node
2385 CtdlLogPrintf(CTDL_WARNING, err_buf);
2386 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2387 CtdlAideMessage(err_buf, "IGNet Networking.");
2391 if (network_talking_to(node, NTT_CHECK)) {
2392 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2393 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2397 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2398 network_talking_to(node, NTT_ADD);
2399 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2400 CC->net_node, CC->cs_host, CC->cs_addr
2402 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2406 int network_room_handler (struct ctdlroom *room)
2408 network_queue_room(room, NULL);
2412 void *ignet_thread(void *arg) {
2413 struct CitContext ignet_thread_CC;
2415 CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2416 CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2417 citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2419 while (!CtdlThreadCheckStop()) {
2421 CtdlThreadSleep(60);
2424 CtdlClearSystemContext();
2432 * Module entry point
2434 CTDL_MODULE_INIT(network)
2438 create_spool_dirs();
2439 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2440 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2441 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2442 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2443 CtdlRegisterRoomHook(network_room_handler);
2444 CtdlRegisterCleanupHook(destroy_network_queue_room);
2445 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);