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>
63 # if HAVE_SYS_SYSCALL_H
64 # include <sys/syscall.h>
71 #include <libcitadel.h>
74 #include "citserver.h"
80 #include "internet_addressing.h"
81 #include "serv_network.h"
82 #include "clientsocket.h"
84 #include "citadel_dirs.h"
93 #include "ctdl_module.h"
97 /* Nonzero while we are doing network processing */
98 static int doing_queue = 0;
101 * When we do network processing, it's accomplished in two passes; one to
102 * gather a list of rooms and one to actually do them. It's ok that rplist
103 * is global; we have a mutex that keeps it safe.
105 struct RoomProcList *rplist = NULL;
108 * We build a map of network nodes during processing.
110 NetMap *the_netmap = NULL;
111 int netmap_changed = 0;
112 char *working_ignetcfg = NULL;
115 * Load or refresh the Citadel network (IGnet) configuration for this node.
117 void load_working_ignetcfg(void) {
121 cfg = CtdlGetSysConfig(IGNETCFG);
126 oldcfg = working_ignetcfg;
127 working_ignetcfg = cfg;
128 if (oldcfg != NULL) {
138 * Keep track of what messages to reject
140 FilterList *load_filter_list(void) {
141 char *serialized_list = NULL;
144 FilterList *newlist = NULL;
147 serialized_list = CtdlGetSysConfig(FILTERLIST);
148 if (serialized_list == NULL) return(NULL); /* if null, no entries */
150 /* Use the string tokenizer to grab one line at a time */
151 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
152 extract_token(buf, serialized_list, i, '\n', sizeof buf);
153 nptr = (FilterList *) malloc(sizeof(FilterList));
154 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
155 striplt(nptr->fl_user);
156 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
157 striplt(nptr->fl_room);
158 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
159 striplt(nptr->fl_node);
161 /* Cowardly refuse to add an any/any/any entry that would
162 * end up filtering every single message.
164 if (IsEmptyStr(nptr->fl_user) &&
165 IsEmptyStr(nptr->fl_room) &&
166 IsEmptyStr(nptr->fl_node)) {
170 nptr->next = newlist;
175 free(serialized_list);
180 void free_filter_list(FilterList *fl) {
181 if (fl == NULL) return;
182 free_filter_list(fl->next);
189 * Check the use table. This is a list of messages which have recently
190 * arrived on the system. It is maintained and queried to prevent the same
191 * message from being entered into the database multiple times if it happens
192 * to arrive multiple times by accident.
194 int network_usetable(struct CtdlMessage *msg) {
197 struct cdbdata *cdbut;
200 /* Bail out if we can't generate a message ID */
204 if (msg->cm_fields['I'] == NULL) {
207 if (IsEmptyStr(msg->cm_fields['I'])) {
211 /* Generate the message ID */
212 strcpy(msgid, msg->cm_fields['I']);
213 if (haschar(msgid, '@') == 0) {
215 if (msg->cm_fields['N'] != NULL) {
216 strcat(msgid, msg->cm_fields['N']);
223 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
226 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
230 /* If we got to this point, it's unique: add it. */
231 strcpy(ut.ut_msgid, msgid);
232 ut.ut_timestamp = time(NULL);
233 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
239 * Read the network map from its configuration file into memory.
241 void read_network_map(void) {
242 char *serialized_map = NULL;
247 serialized_map = CtdlGetSysConfig(IGNETMAP);
248 if (serialized_map == NULL) return; /* if null, no entries */
250 /* Use the string tokenizer to grab one line at a time */
251 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
252 extract_token(buf, serialized_map, i, '\n', sizeof buf);
253 nmptr = (NetMap *) malloc(sizeof(NetMap));
254 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
255 nmptr->lastcontact = extract_long(buf, 1);
256 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
257 nmptr->next = the_netmap;
261 free(serialized_map);
267 * Write the network map from memory back to the configuration file.
269 void write_network_map(void) {
270 char *serialized_map = NULL;
274 if (netmap_changed) {
275 serialized_map = strdup("");
277 if (the_netmap != NULL) {
278 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
279 serialized_map = realloc(serialized_map,
280 (strlen(serialized_map)+SIZ) );
281 if (!IsEmptyStr(nmptr->nodename)) {
282 snprintf(&serialized_map[strlen(serialized_map)],
286 (long)nmptr->lastcontact,
292 CtdlPutSysConfig(IGNETMAP, serialized_map);
293 free(serialized_map);
296 /* Now free the list */
297 while (the_netmap != NULL) {
298 nmptr = the_netmap->next;
308 * Check the network map and determine whether the supplied node name is
309 * valid. If it is not a neighbor node, supply the name of a neighbor node
310 * which is the next hop. If it *is* a neighbor node, we also fill in the
313 int is_valid_node(char *nexthop, char *secret, char *node) {
325 * First try the neighbor nodes
327 if (working_ignetcfg == NULL) {
328 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
329 if (nexthop != NULL) {
336 if (nexthop != NULL) {
340 /* Use the string tokenizer to grab one line at a time */
341 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
342 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
343 extract_token(buf, linebuf, 0, '|', sizeof buf);
344 if (!strcasecmp(buf, node)) {
345 if (nexthop != NULL) {
348 if (secret != NULL) {
349 extract_token(secret, linebuf, 1, '|', 256);
356 return(retval); /* yup, it's a direct neighbor */
360 * If we get to this point we have to see if we know the next hop
362 if (the_netmap != NULL) {
363 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
364 if (!strcasecmp(nmptr->nodename, node)) {
365 if (nexthop != NULL) {
366 strcpy(nexthop, nmptr->nexthop);
374 * If we get to this point, the supplied node name is bogus.
376 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
384 void cmd_gnet(char *argbuf) {
385 char filename[PATH_MAX];
389 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
390 /* users can edit the netconfigs for their own mailbox rooms */
392 else if (CtdlAccessCheck(ac_room_aide)) return;
394 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
395 cprintf("%d Network settings for room #%ld <%s>\n",
397 CC->room.QRnumber, CC->room.QRname);
399 fp = fopen(filename, "r");
401 while (fgets(buf, sizeof buf, fp) != NULL) {
402 buf[strlen(buf)-1] = 0;
403 cprintf("%s\n", buf);
412 void cmd_snet(char *argbuf) {
413 char tempfilename[PATH_MAX];
414 char filename[PATH_MAX];
423 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
424 /* users can edit the netconfigs for their own mailbox rooms */
426 else if (CtdlAccessCheck(ac_room_aide)) return;
428 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
429 memcpy(tempfilename, filename, len + 1);
431 memset(&StatBuf, 0, sizeof(struct stat));
432 if (stat(filename, &StatBuf) == -1)
433 StatBuf.st_size = 80; /* Not there? guess 80 chars line. */
435 sprintf(tempfilename + len, ".%d", CC->cs_pid);
437 TmpFD = open(tempfilename, O_CREAT|O_EXCL);
441 char *tmp = malloc(StatBuf.st_size * 2);
442 memset(tmp, 0, StatBuf.st_size * 2);
443 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
448 cprintf("%d Unable to allocate the space required for %s: %s\n",
449 ERROR + INTERNAL_ERROR,
454 lseek(TmpFD, SEEK_SET, 0);
457 cprintf("%d Unable to allocate the space required for %s: %s\n",
458 ERROR + INTERNAL_ERROR,
466 cprintf("%d %s\n", SEND_LISTING, tempfilename);
469 while (rc = CtdlClientGetLine(Line),
472 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
474 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
475 write(TmpFD, ChrPtr(Line), StrLength(Line));
476 len += StrLength(Line);
479 ftruncate(TmpFD, len + 1);
482 /* Now copy the temp file to its permanent location.
483 * (We copy instead of link because they may be on different filesystems)
485 begin_critical_section(S_NETCONFIGS);
486 rename(filename, tempfilename);
487 end_critical_section(S_NETCONFIGS);
492 * Deliver digest messages
494 void network_deliver_digest(SpoolControl *sc) {
497 struct CtdlMessage *msg = NULL;
500 size_t recps_len = SIZ;
502 struct recptypes *valid;
506 if (sc->num_msgs_spooled < 1) {
507 fclose(sc->digestfp);
512 msg = malloc(sizeof(struct CtdlMessage));
513 memset(msg, 0, sizeof(struct CtdlMessage));
514 msg->cm_magic = CTDLMESSAGE_MAGIC;
515 msg->cm_format_type = FMT_RFC822;
516 msg->cm_anon_type = MES_NORMAL;
518 sprintf(buf, "%ld", time(NULL));
519 msg->cm_fields['T'] = strdup(buf);
520 msg->cm_fields['A'] = strdup(CC->room.QRname);
521 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
522 msg->cm_fields['U'] = strdup(buf);
523 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
524 for (i=0; buf[i]; ++i) {
525 if (isspace(buf[i])) buf[i]='_';
526 buf[i] = tolower(buf[i]);
528 msg->cm_fields['F'] = strdup(buf);
529 msg->cm_fields['R'] = strdup(buf);
531 /* Set the 'List-ID' header */
532 msg->cm_fields['L'] = malloc(1024);
533 snprintf(msg->cm_fields['L'], 1024,
534 "%s <%ld.list-id.%s>",
541 * Go fetch the contents of the digest
543 fseek(sc->digestfp, 0L, SEEK_END);
544 msglen = ftell(sc->digestfp);
546 msg->cm_fields['M'] = malloc(msglen + 1);
547 fseek(sc->digestfp, 0L, SEEK_SET);
548 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
549 msg->cm_fields['M'][msglen] = '\0';
551 fclose(sc->digestfp);
554 /* Now generate the delivery instructions */
557 * Figure out how big a buffer we need to allocate
559 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
560 recps_len = recps_len + strlen(nptr->name) + 2;
563 recps = malloc(recps_len);
566 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
573 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
574 if (nptr != sc->digestrecps) {
577 strcat(recps, nptr->name);
580 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
581 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
583 /* Now submit the message */
584 valid = validate_recipients(recps, NULL, 0);
587 valid->bounce_to = strdup(bounce_to);
588 valid->envelope_from = strdup(bounce_to);
589 CtdlSubmitMsg(msg, valid, NULL, 0);
591 CtdlFreeMessage(msg);
592 free_recipients(valid);
597 * Deliver list messages to everyone on the list ... efficiently
599 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
601 size_t recps_len = SIZ;
602 struct recptypes *valid;
606 /* Don't do this if there were no recipients! */
607 if (sc->listrecps == NULL) return;
609 /* Now generate the delivery instructions */
612 * Figure out how big a buffer we need to allocate
614 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
615 recps_len = recps_len + strlen(nptr->name) + 2;
618 recps = malloc(recps_len);
621 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
628 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
629 if (nptr != sc->listrecps) {
632 strcat(recps, nptr->name);
635 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
636 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
638 /* Now submit the message */
639 valid = validate_recipients(recps, NULL, 0);
642 valid->bounce_to = strdup(bounce_to);
643 valid->envelope_from = strdup(bounce_to);
644 CtdlSubmitMsg(msg, valid, NULL, 0);
645 free_recipients(valid);
647 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
654 * Spools out one message from the list.
656 void network_spool_msg(long msgnum, void *userdata) {
659 char *newpath = NULL;
660 size_t instr_len = SIZ;
661 struct CtdlMessage *msg = NULL;
664 struct ser_ret sermsg;
666 char filename[PATH_MAX];
670 int delete_after_send = 0; /* Set to 1 to delete after spooling */
671 int ok_to_participate = 0;
672 struct recptypes *valid;
674 sc = (SpoolControl *)userdata;
677 * Process mailing list recipients
680 if (sc->listrecps != NULL) {
681 /* Fetch the message. We're going to need to modify it
682 * in order to insert the [list name] in it, etc.
684 msg = CtdlFetchMessage(msgnum, 1);
686 if (msg->cm_fields['V'] == NULL){
687 /* local message, no enVelope */
690 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
691 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
692 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
694 msg->cm_fields['K'] = SmashStrBuf(&Buf);
697 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
699 /* Set the 'List-ID' header */
700 if (msg->cm_fields['L'] != NULL) {
701 free(msg->cm_fields['L']);
703 msg->cm_fields['L'] = malloc(1024);
704 snprintf(msg->cm_fields['L'], 1024,
705 "%s <%ld.list-id.%s>",
711 /* Prepend "[List name]" to the subject */
712 if (msg->cm_fields['U'] == NULL) {
713 msg->cm_fields['U'] = strdup("(no subject)");
715 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
716 free(msg->cm_fields['U']);
717 msg->cm_fields['U'] = strdup(buf);
719 /* Set the recipient of the list message to the
720 * email address of the room itself.
721 * FIXME ... I want to be able to pick any address
723 if (msg->cm_fields['R'] != NULL) {
724 free(msg->cm_fields['R']);
726 msg->cm_fields['R'] = malloc(256);
727 snprintf(msg->cm_fields['R'], 256,
728 "room_%s@%s", CC->room.QRname,
730 for (i=0; msg->cm_fields['R'][i]; ++i) {
731 if (isspace(msg->cm_fields['R'][i])) {
732 msg->cm_fields['R'][i] = '_';
736 /* Handle delivery */
737 network_deliver_list(msg, sc);
738 CtdlFreeMessage(msg);
743 * Process digest recipients
745 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
746 msg = CtdlFetchMessage(msgnum, 1);
748 fprintf(sc->digestfp, " -----------------------------------"
749 "------------------------------------"
751 fprintf(sc->digestfp, "From: ");
752 if (msg->cm_fields['A'] != NULL) {
753 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
755 if (msg->cm_fields['F'] != NULL) {
756 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
758 else if (msg->cm_fields['N'] != NULL) {
759 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
761 fprintf(sc->digestfp, "\n");
762 if (msg->cm_fields['U'] != NULL) {
763 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
766 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
768 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
769 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
771 StrBufTrim(CC->redirect_buffer);
772 fwrite(HKEY("\n"), 1, sc->digestfp);
773 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
774 fwrite(HKEY("\n"), 1, sc->digestfp);
776 FreeStrBuf(&CC->redirect_buffer);
778 sc->num_msgs_spooled += 1;
784 * Process client-side list participations for this room
787 if (sc->participates != NULL) {
788 msg = CtdlFetchMessage(msgnum, 1);
791 /* Only send messages which originated on our own Citadel
792 * network, otherwise we'll end up sending the remote
793 * mailing list's messages back to it, which is rude...
795 ok_to_participate = 0;
796 if (msg->cm_fields['N'] != NULL) {
797 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
798 ok_to_participate = 1;
800 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
801 ok_to_participate = 1;
804 if (ok_to_participate) {
805 if (msg->cm_fields['F'] != NULL) {
806 free(msg->cm_fields['F']);
808 msg->cm_fields['F'] = malloc(SIZ);
809 /* Replace the Internet email address of the actual
810 * author with the email address of the room itself,
811 * so the remote listserv doesn't reject us.
812 * FIXME ... I want to be able to pick any address
814 snprintf(msg->cm_fields['F'], SIZ,
815 "room_%s@%s", CC->room.QRname,
817 for (i=0; msg->cm_fields['F'][i]; ++i) {
818 if (isspace(msg->cm_fields['F'][i])) {
819 msg->cm_fields['F'][i] = '_';
824 * Figure out how big a buffer we need to allocate
826 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
828 if (msg->cm_fields['R'] == NULL) {
829 free(msg->cm_fields['R']);
831 msg->cm_fields['R'] = strdup(nptr->name);
833 valid = validate_recipients(nptr->name, NULL, 0);
834 CtdlSubmitMsg(msg, valid, "", 0);
835 free_recipients(valid);
839 CtdlFreeMessage(msg);
844 * Process IGnet push shares
846 msg = CtdlFetchMessage(msgnum, 1);
850 /* Prepend our node name to the Path field whenever
851 * sending a message to another IGnet node
853 if (msg->cm_fields['P'] == NULL) {
854 msg->cm_fields['P'] = strdup("username");
856 newpath_len = strlen(msg->cm_fields['P']) +
857 strlen(config.c_nodename) + 2;
858 newpath = malloc(newpath_len);
859 snprintf(newpath, newpath_len, "%s!%s",
860 config.c_nodename, msg->cm_fields['P']);
861 free(msg->cm_fields['P']);
862 msg->cm_fields['P'] = newpath;
865 * Determine if this message is set to be deleted
866 * after sending out on the network
868 if (msg->cm_fields['S'] != NULL) {
869 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
870 delete_after_send = 1;
874 /* Now send it to every node */
875 if (sc->ignet_push_shares != NULL)
876 for (mptr = sc->ignet_push_shares; mptr != NULL;
881 /* Check for valid node name */
882 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
883 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
887 /* Check for split horizon */
888 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
889 bang = num_tokens(msg->cm_fields['P'], '!');
890 if (bang > 1) for (i=0; i<(bang-1); ++i) {
891 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
892 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
893 buf, mptr->remote_nodename) ;
894 if (!strcasecmp(buf, mptr->remote_nodename)) {
896 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
897 mptr->remote_nodename);
900 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
904 /* Send the message */
908 * Force the message to appear in the correct room
909 * on the far end by setting the C field correctly
911 if (msg->cm_fields['C'] != NULL) {
912 free(msg->cm_fields['C']);
914 if (!IsEmptyStr(mptr->remote_roomname)) {
915 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
918 msg->cm_fields['C'] = strdup(CC->room.QRname);
921 /* serialize it for transmission */
922 serialize_message(&sermsg, msg);
923 if (sermsg.len > 0) {
925 /* write it to a spool file */
926 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
928 mptr->remote_nodename,
932 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
933 fp = fopen(filename, "ab");
940 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
943 /* free the serialized version */
949 CtdlFreeMessage(msg);
952 /* update lastsent */
953 sc->lastsent = msgnum;
955 /* Delete this message if delete-after-send is set */
956 if (delete_after_send) {
957 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
963 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
969 char roomname[ROOMNAMELEN];
972 int skipthisline = 0;
973 namelist *nptr = NULL;
974 maplist *mptr = NULL;
977 fp = fopen(filename, "r");
981 sc = malloc(sizeof(SpoolControl));
982 memset(sc, 0, sizeof(SpoolControl));
985 while (fgets(buf, sizeof buf, fp) != NULL) {
986 buf[strlen(buf)-1] = 0;
988 extract_token(instr, buf, 0, '|', sizeof instr);
989 if (!strcasecmp(instr, strof(lastsent))) {
990 sc->lastsent = extract_long(buf, 1);
992 else if (!strcasecmp(instr, strof(listrecp))) {
994 malloc(sizeof(namelist));
995 nptr->next = sc->listrecps;
996 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
997 sc->listrecps = nptr;
999 else if (!strcasecmp(instr, strof(participate))) {
1001 malloc(sizeof(namelist));
1002 nptr->next = sc->participates;
1003 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1004 sc->participates = nptr;
1006 else if (!strcasecmp(instr, strof(digestrecp))) {
1008 malloc(sizeof(namelist));
1009 nptr->next = sc->digestrecps;
1010 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1011 sc->digestrecps = nptr;
1013 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1014 extract_token(nodename, buf, 1, '|', sizeof nodename);
1015 extract_token(roomname, buf, 2, '|', sizeof roomname);
1016 mptr = (maplist *) malloc(sizeof(maplist));
1017 mptr->next = sc->ignet_push_shares;
1018 strcpy(mptr->remote_nodename, nodename);
1019 strcpy(mptr->remote_roomname, roomname);
1020 sc->ignet_push_shares = mptr;
1023 /* Preserve 'other' lines ... *unless* they happen to
1024 * be subscribe/unsubscribe pendings with expired
1028 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1029 if (time(NULL) - extract_long(buf, 4) > EXP) {
1033 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1034 if (time(NULL) - extract_long(buf, 3) > EXP) {
1039 if (skipthisline == 0) {
1040 linesize = strlen(buf);
1041 sc->misc = realloc(sc->misc,
1042 (miscsize + linesize + 2) );
1043 sprintf(&sc->misc[miscsize], "%s\n", buf);
1044 miscsize = miscsize + linesize + 1;
1054 void free_spoolcontrol_struct(SpoolControl **scc)
1057 namelist *nptr = NULL;
1058 maplist *mptr = NULL;
1061 while (sc->listrecps != NULL) {
1062 nptr = sc->listrecps->next;
1063 free(sc->listrecps);
1064 sc->listrecps = nptr;
1066 /* Do the same for digestrecps */
1067 while (sc->digestrecps != NULL) {
1068 nptr = sc->digestrecps->next;
1069 free(sc->digestrecps);
1070 sc->digestrecps = nptr;
1072 /* Do the same for participates */
1073 while (sc->participates != NULL) {
1074 nptr = sc->participates->next;
1075 free(sc->participates);
1076 sc->participates = nptr;
1078 while (sc->ignet_push_shares != NULL) {
1079 mptr = sc->ignet_push_shares->next;
1080 free(sc->ignet_push_shares);
1081 sc->ignet_push_shares = mptr;
1088 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1090 char tempfilename[PATH_MAX];
1093 namelist *nptr = NULL;
1094 maplist *mptr = NULL;
1098 long reltid; /* if we don't have SYS_gettid, use "random" value */
1102 len = strlen(filename);
1103 memcpy(tempfilename, filename, len + 1);
1106 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1107 reltid = syscall(SYS_gettid);
1109 gettimeofday(&tv, NULL);
1110 /* Promote to time_t; types differ on some OSes (like darwin) */
1111 unixtime = tv.tv_sec;
1113 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1115 fp = fopen(tempfilename, "w");
1118 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1119 filename, strerror(errno));
1120 free_spoolcontrol_struct(scc);
1123 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1125 /* Write out the listrecps while freeing from memory at the
1126 * same time. Am I clever or what? :)
1128 while (sc->listrecps != NULL) {
1129 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1130 nptr = sc->listrecps->next;
1131 free(sc->listrecps);
1132 sc->listrecps = nptr;
1134 /* Do the same for digestrecps */
1135 while (sc->digestrecps != NULL) {
1136 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1137 nptr = sc->digestrecps->next;
1138 free(sc->digestrecps);
1139 sc->digestrecps = nptr;
1141 /* Do the same for participates */
1142 while (sc->participates != NULL) {
1143 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1144 nptr = sc->participates->next;
1145 free(sc->participates);
1146 sc->participates = nptr;
1148 while (sc->ignet_push_shares != NULL) {
1149 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1150 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1151 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1153 StrBufAppendPrintf(Cfg, "\n");
1154 mptr = sc->ignet_push_shares->next;
1155 free(sc->ignet_push_shares);
1156 sc->ignet_push_shares = mptr;
1158 if (sc->misc != NULL) {
1159 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1163 rc = fwrite(ChrPtr(Cfg), StrLength(Cfg), 1, fp);
1167 rename(filename, tempfilename);
1170 CtdlLogPrintf(CTDL_EMERG,
1171 "unable to write %s; not enough space on the disk?\n",
1181 int is_recipient(SpoolControl *sc, const char *Name)
1187 nptr = sc->listrecps;
1188 while (nptr != NULL) {
1189 if (strncmp(Name, nptr->name, len)==0)
1193 /* Do the same for digestrecps */
1194 nptr = sc->digestrecps;
1195 while (nptr != NULL) {
1196 if (strncmp(Name, nptr->name, len)==0)
1200 /* Do the same for participates */
1201 nptr = sc->participates;
1202 while (nptr != NULL) {
1203 if (strncmp(Name, nptr->name, len)==0)
1212 * Batch up and send all outbound traffic from the current room
1214 void network_spoolout_room(char *room_to_spool) {
1216 char filename[PATH_MAX];
1221 * If the room doesn't exist, don't try to perform its networking tasks.
1222 * Normally this should never happen, but once in a while maybe a room gets
1223 * queued for networking and then deleted before it can happen.
1225 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1226 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1230 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1231 begin_critical_section(S_NETCONFIGS);
1233 /* Only do net processing for rooms that have netconfigs */
1234 if (!read_spoolcontrol_file(&sc, filename))
1236 end_critical_section(S_NETCONFIGS);
1239 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1241 /* If there are digest recipients, we have to build a digest */
1242 if (sc->digestrecps != NULL) {
1243 sc->digestfp = tmpfile();
1244 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1247 /* Do something useful */
1248 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1249 network_spool_msg, sc);
1251 /* If we wrote a digest, deliver it and then close it */
1252 snprintf(buf, sizeof buf, "room_%s@%s",
1253 CC->room.QRname, config.c_fqdn);
1254 for (i=0; buf[i]; ++i) {
1255 buf[i] = tolower(buf[i]);
1256 if (isspace(buf[i])) buf[i] = '_';
1258 if (sc->digestfp != NULL) {
1259 fprintf(sc->digestfp, " -----------------------------------"
1260 "------------------------------------"
1262 "You are subscribed to the '%s' "
1264 "To post to the list: %s\n",
1265 CC->room.QRname, buf
1267 network_deliver_digest(sc); /* deliver and close */
1270 /* Now rewrite the config file */
1271 writenfree_spoolcontrol_file (&sc, filename);
1272 end_critical_section(S_NETCONFIGS);
1278 * Send the *entire* contents of the current room to one specific network node,
1279 * ignoring anything we know about which messages have already undergone
1280 * network processing. This can be used to bring a new node into sync.
1282 int network_sync_to(char *target_node) {
1284 int num_spooled = 0;
1290 char filename[PATH_MAX];
1293 /* Grab the configuration line we're looking for */
1294 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1295 begin_critical_section(S_NETCONFIGS);
1296 fp = fopen(filename, "r");
1298 end_critical_section(S_NETCONFIGS);
1301 while (fgets(buf, sizeof buf, fp) != NULL) {
1302 buf[strlen(buf)-1] = 0;
1303 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1304 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1305 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1306 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1307 && (!strcasecmp(sc_node, target_node)) ) {
1310 /* Concise syntax because we don't need a full linked-list */
1311 memset(&sc, 0, sizeof(SpoolControl));
1312 sc.ignet_push_shares = (maplist *)
1313 malloc(sizeof(maplist));
1314 sc.ignet_push_shares->next = NULL;
1315 safestrncpy(sc.ignet_push_shares->remote_nodename,
1317 sizeof sc.ignet_push_shares->remote_nodename);
1318 safestrncpy(sc.ignet_push_shares->remote_roomname,
1320 sizeof sc.ignet_push_shares->remote_roomname);
1324 end_critical_section(S_NETCONFIGS);
1326 if (!found_node) return(-1);
1328 /* Send ALL messages */
1329 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1330 network_spool_msg, &sc);
1332 /* Concise cleanup because we know there's only one node in the sc */
1333 free(sc.ignet_push_shares);
1335 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1336 num_spooled, target_node);
1337 return(num_spooled);
1342 * Implements the NSYN command
1344 void cmd_nsyn(char *argbuf) {
1346 char target_node[256];
1348 if (CtdlAccessCheck(ac_aide)) return;
1350 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1351 num_spooled = network_sync_to(target_node);
1352 if (num_spooled >= 0) {
1353 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1356 cprintf("%d No such room/node share exists.\n",
1357 ERROR + ROOM_NOT_FOUND);
1364 * Batch up and send all outbound traffic from the current room
1366 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1367 struct RoomProcList *ptr;
1369 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1370 if (ptr == NULL) return;
1372 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1373 begin_critical_section(S_RPLIST);
1376 end_critical_section(S_RPLIST);
1379 void destroy_network_queue_room(void)
1381 struct RoomProcList *cur, *p;
1382 NetMap *nmcur, *nmp;
1385 begin_critical_section(S_RPLIST);
1393 end_critical_section(S_RPLIST);
1396 while (nmcur != NULL)
1403 if (working_ignetcfg != NULL)
1404 free (working_ignetcfg);
1405 working_ignetcfg = NULL;
1410 * Learn topology from path fields
1412 void network_learn_topology(char *node, char *path) {
1416 strcpy(nexthop, "");
1418 if (num_tokens(path, '!') < 3) return;
1419 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1420 if (!strcasecmp(nmptr->nodename, node)) {
1421 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1422 nmptr->lastcontact = time(NULL);
1428 /* If we got here then it's not in the map, so add it. */
1429 nmptr = (NetMap *) malloc(sizeof (NetMap));
1430 strcpy(nmptr->nodename, node);
1431 nmptr->lastcontact = time(NULL);
1432 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1433 nmptr->next = the_netmap;
1442 * Bounce a message back to the sender
1444 void network_bounce(struct CtdlMessage *msg, char *reason) {
1445 char *oldpath = NULL;
1447 char bouncesource[SIZ];
1448 char recipient[SIZ];
1449 struct recptypes *valid = NULL;
1450 char force_room[ROOMNAMELEN];
1451 static int serialnum = 0;
1454 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1456 if (msg == NULL) return;
1458 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1461 * Give it a fresh message ID
1463 if (msg->cm_fields['I'] != NULL) {
1464 free(msg->cm_fields['I']);
1466 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1467 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1468 msg->cm_fields['I'] = strdup(buf);
1471 * FIXME ... right now we're just sending a bounce; we really want to
1472 * include the text of the bounced message.
1474 if (msg->cm_fields['M'] != NULL) {
1475 free(msg->cm_fields['M']);
1477 msg->cm_fields['M'] = strdup(reason);
1478 msg->cm_format_type = 0;
1481 * Turn the message around
1483 if (msg->cm_fields['R'] == NULL) {
1484 free(msg->cm_fields['R']);
1487 if (msg->cm_fields['D'] == NULL) {
1488 free(msg->cm_fields['D']);
1491 snprintf(recipient, sizeof recipient, "%s@%s",
1492 msg->cm_fields['A'], msg->cm_fields['N']);
1494 if (msg->cm_fields['A'] == NULL) {
1495 free(msg->cm_fields['A']);
1498 if (msg->cm_fields['N'] == NULL) {
1499 free(msg->cm_fields['N']);
1502 if (msg->cm_fields['U'] == NULL) {
1503 free(msg->cm_fields['U']);
1506 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1507 msg->cm_fields['N'] = strdup(config.c_nodename);
1508 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1510 /* prepend our node to the path */
1511 if (msg->cm_fields['P'] != NULL) {
1512 oldpath = msg->cm_fields['P'];
1513 msg->cm_fields['P'] = NULL;
1516 oldpath = strdup("unknown_user");
1518 size = strlen(oldpath) + SIZ;
1519 msg->cm_fields['P'] = malloc(size);
1520 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1523 /* Now submit the message */
1524 valid = validate_recipients(recipient, NULL, 0);
1525 if (valid != NULL) if (valid->num_error != 0) {
1526 free_recipients(valid);
1529 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1530 strcpy(force_room, config.c_aideroom);
1533 strcpy(force_room, "");
1535 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1536 strcpy(force_room, config.c_aideroom);
1538 CtdlSubmitMsg(msg, valid, force_room, 0);
1541 if (valid != NULL) free_recipients(valid);
1542 CtdlFreeMessage(msg);
1543 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1550 * Process a buffer containing a single message from a single file
1551 * from the inbound queue
1553 void network_process_buffer(char *buffer, long size) {
1554 struct CtdlMessage *msg = NULL;
1557 struct recptypes *recp = NULL;
1558 char target_room[ROOMNAMELEN];
1559 struct ser_ret sermsg;
1560 char *oldpath = NULL;
1561 char filename[PATH_MAX];
1564 unsigned char firstbyte;
1565 unsigned char lastbyte;
1567 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1569 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1570 firstbyte = buffer[0];
1571 lastbyte = buffer[size-1];
1572 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1573 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1574 size, firstbyte, lastbyte);
1578 /* Set default target room to trash */
1579 strcpy(target_room, TWITROOM);
1581 /* Load the message into memory */
1582 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1583 memset(msg, 0, sizeof(struct CtdlMessage));
1584 msg->cm_magic = CTDLMESSAGE_MAGIC;
1585 msg->cm_anon_type = buffer[1];
1586 msg->cm_format_type = buffer[2];
1588 for (pos = 3; pos < size; ++pos) {
1589 field = buffer[pos];
1590 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1591 pos = pos + strlen(&buffer[(int)pos]);
1594 /* Check for message routing */
1595 if (msg->cm_fields['D'] != NULL) {
1596 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1598 /* route the message */
1599 strcpy(nexthop, "");
1600 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1601 /* prepend our node to the path */
1602 if (msg->cm_fields['P'] != NULL) {
1603 oldpath = msg->cm_fields['P'];
1604 msg->cm_fields['P'] = NULL;
1607 oldpath = strdup("unknown_user");
1609 size = strlen(oldpath) + SIZ;
1610 msg->cm_fields['P'] = malloc(size);
1611 snprintf(msg->cm_fields['P'], size, "%s!%s",
1612 config.c_nodename, oldpath);
1615 /* serialize the message */
1616 serialize_message(&sermsg, msg);
1619 if (IsEmptyStr(nexthop)) {
1620 strcpy(nexthop, msg->cm_fields['D']);
1630 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1631 fp = fopen(filename, "ab");
1633 fwrite(sermsg.ser, sermsg.len, 1, fp);
1637 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1640 CtdlFreeMessage(msg);
1644 else { /* invalid destination node name */
1647 "A message you sent could not be delivered due to an invalid destination node"
1648 " name. Please check the address and try sending the message again.\n");
1657 * Check to see if we already have a copy of this message, and
1658 * abort its processing if so. (We used to post a warning to Aide>
1659 * every time this happened, but the network is now so densely
1660 * connected that it's inevitable.)
1662 if (network_usetable(msg) != 0) {
1663 CtdlFreeMessage(msg);
1667 /* Learn network topology from the path */
1668 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1669 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1672 /* Is the sending node giving us a very persuasive suggestion about
1673 * which room this message should be saved in? If so, go with that.
1675 if (msg->cm_fields['C'] != NULL) {
1676 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1679 /* Otherwise, does it have a recipient? If so, validate it... */
1680 else if (msg->cm_fields['R'] != NULL) {
1681 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1682 if (recp != NULL) if (recp->num_error != 0) {
1684 "A message you sent could not be delivered due to an invalid address.\n"
1685 "Please check the address and try sending the message again.\n");
1687 free_recipients(recp);
1688 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1691 strcpy(target_room, ""); /* no target room if mail */
1694 /* Our last shot at finding a home for this message is to see if
1695 * it has the O field (Originating room) set.
1697 else if (msg->cm_fields['O'] != NULL) {
1698 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1701 /* Strip out fields that are only relevant during transit */
1702 if (msg->cm_fields['D'] != NULL) {
1703 free(msg->cm_fields['D']);
1704 msg->cm_fields['D'] = NULL;
1706 if (msg->cm_fields['C'] != NULL) {
1707 free(msg->cm_fields['C']);
1708 msg->cm_fields['C'] = NULL;
1711 /* save the message into a room */
1712 if (PerformNetprocHooks(msg, target_room) == 0) {
1713 msg->cm_flags = CM_SKIP_HOOKS;
1714 CtdlSubmitMsg(msg, recp, target_room, 0);
1716 CtdlFreeMessage(msg);
1717 free_recipients(recp);
1722 * Process a single message from a single file from the inbound queue
1724 void network_process_message(FILE *fp, long msgstart, long msgend) {
1729 hold_pos = ftell(fp);
1730 size = msgend - msgstart + 1;
1731 buffer = malloc(size);
1732 if (buffer != NULL) {
1733 fseek(fp, msgstart, SEEK_SET);
1734 if (fread(buffer, size, 1, fp) > 0) {
1735 network_process_buffer(buffer, size);
1740 fseek(fp, hold_pos, SEEK_SET);
1745 * Process a single file from the inbound queue
1747 void network_process_file(char *filename) {
1749 long msgstart = (-1L);
1750 long msgend = (-1L);
1755 fp = fopen(filename, "rb");
1757 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1761 fseek(fp, 0L, SEEK_END);
1762 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1765 /* Look for messages in the data stream and break them out */
1766 while (ch = getc(fp), ch >= 0) {
1769 if (msgstart >= 0L) {
1770 msgend = msgcur - 1;
1771 network_process_message(fp, msgstart, msgend);
1779 msgend = msgcur - 1;
1780 if (msgstart >= 0L) {
1781 network_process_message(fp, msgstart, msgend);
1790 * Process anything in the inbound queue
1792 void network_do_spoolin(void) {
1795 struct stat statbuf;
1796 char filename[PATH_MAX];
1797 static time_t last_spoolin_mtime = 0L;
1800 * Check the spoolin directory's modification time. If it hasn't
1801 * been touched, we don't need to scan it.
1803 if (stat(ctdl_netin_dir, &statbuf)) return;
1804 if (statbuf.st_mtime == last_spoolin_mtime) {
1805 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1808 last_spoolin_mtime = statbuf.st_mtime;
1809 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1812 * Ok, there's something interesting in there, so scan it.
1814 dp = opendir(ctdl_netin_dir);
1815 if (dp == NULL) return;
1817 while (d = readdir(dp), d != NULL) {
1818 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1825 network_process_file(filename);
1833 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1834 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1836 void network_consolidate_spoolout(void) {
1839 char filename[PATH_MAX];
1845 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1846 dp = opendir(ctdl_netout_dir);
1847 if (dp == NULL) return;
1848 while (d = readdir(dp), d != NULL) {
1850 (strcmp(d->d_name, "."))
1851 && (strcmp(d->d_name, ".."))
1852 && (strchr(d->d_name, '@') != NULL)
1854 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1855 ptr = strchr(nexthop, '@');
1865 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1866 if (network_talking_to(nexthop, NTT_CHECK)) {
1867 CtdlLogPrintf(CTDL_DEBUG,
1868 "Currently online with %s - skipping for now\n",
1873 network_talking_to(nexthop, NTT_ADD);
1874 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1876 ctdl_netout_dir, nexthop,
1880 network_talking_to(nexthop, NTT_REMOVE);
1886 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1888 dp = opendir(ctdl_netout_dir);
1889 if (dp == NULL) return;
1891 while (d = readdir(dp), d != NULL) {
1892 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1894 ptr = strchr(d->d_name, '@');
1904 strcpy(nexthop, "");
1905 i = is_valid_node(nexthop, NULL, d->d_name);
1907 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1918 * receive network spool from the remote system
1920 void receive_spool(int *sock, char *remote_nodename) {
1921 long download_len = 0L;
1922 long bytes_received = 0L;
1924 static char pbuf[IGNET_PACKET_SIZE];
1925 char tempfilename[PATH_MAX];
1926 char permfilename[PATH_MAX];
1930 snprintf(tempfilename,
1931 sizeof tempfilename,
1939 snprintf(permfilename,
1940 sizeof permfilename,
1948 if (sock_puts(sock, "NDOP") < 0) return;
1949 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1950 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1951 if (buf[0] != '2') {
1954 download_len = extract_long(&buf[4], 0);
1956 if (download_len>0) {
1957 bytes_received = 0L;
1958 fp = fopen(tempfilename, "w");
1960 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1965 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1966 while (bytes_received < download_len) {
1968 * If shutting down we can exit here and unlink the temp file.
1969 * this shouldn't loose us any messages.
1971 if (CtdlThreadCheckStop())
1974 unlink(tempfilename);
1977 snprintf(buf, sizeof buf, "READ %ld|%ld",
1979 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1980 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1982 if (sock_puts(sock, buf) < 0) {
1984 unlink(tempfilename);
1987 if (sock_getln(sock, buf, sizeof buf) < 0) {
1989 unlink(tempfilename);
1993 if (buf[0] == '6') {
1994 plen = extract_long(&buf[4], 0);
1995 if (sock_read(sock, pbuf, plen, 1) < 0) {
1997 unlink(tempfilename);
2000 fwrite((char *) pbuf, plen, 1, fp);
2001 bytes_received = bytes_received + plen;
2007 /* Last chance for shutdown exit */
2008 if (CtdlThreadCheckStop())
2010 unlink(tempfilename);
2014 if (sock_puts(sock, "CLOS") < 0) {
2015 unlink(tempfilename);
2020 * From here on we must complete or messages will get lost
2022 if (sock_getln(sock, buf, sizeof buf) < 0) {
2023 unlink(tempfilename);
2026 if (download_len > 0) {
2027 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
2029 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2031 /* Now move the temp file to its permanent location.
2033 if (link(tempfilename, permfilename) != 0) {
2034 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2035 tempfilename, permfilename, strerror(errno)
2038 unlink(tempfilename);
2044 * transmit network spool to the remote system
2046 void transmit_spool(int *sock, char *remote_nodename)
2051 long bytes_to_write, thisblock, bytes_written;
2055 if (sock_puts(sock, "NUOP") < 0) return;
2056 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2057 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2058 if (buf[0] != '2') {
2062 snprintf(sfname, sizeof sfname,
2067 fd = open(sfname, O_RDONLY);
2069 if (errno != ENOENT) {
2070 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2075 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2076 bytes_to_write = plen;
2077 while (bytes_to_write > 0L) {
2078 /* Exit if shutting down */
2079 if (CtdlThreadCheckStop())
2085 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2086 if (sock_puts(sock, buf) < 0) {
2090 if (sock_getln(sock, buf, sizeof buf) < 0) {
2094 thisblock = atol(&buf[4]);
2095 if (buf[0] == '7') {
2096 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2100 bytes_to_write -= thisblock;
2101 bytes_written += thisblock;
2111 /* Last chance for shutdown exit */
2112 if(CtdlThreadCheckStop())
2115 if (sock_puts(sock, "UCLS 1") < 0) return;
2118 * From here on we must complete or messages will get lost
2120 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2121 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2122 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2123 if (buf[0] == '2') {
2124 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2132 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2134 void network_poll_node(char *node, char *secret, char *host, char *port) {
2138 char connected_to[SIZ];
2141 if (network_talking_to(node, NTT_CHECK)) return;
2142 network_talking_to(node, NTT_ADD);
2143 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2144 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2146 sock = sock_connect(host, port, "tcp");
2148 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2149 network_talking_to(node, NTT_REMOVE);
2153 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2154 CCC->sReadBuf = NewStrBuf();
2155 CCC->sMigrateBuf = NewStrBuf();
2158 /* Read the server greeting */
2159 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2160 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2162 /* Check that the remote is who we think it is and warn the Aide if not */
2163 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2164 if (strcmp(connected_to, node))
2166 snprintf(err_buf, sizeof(err_buf),
2167 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2170 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2171 CtdlAideMessage(err_buf, "Network error");
2174 /* We're talking to the correct node. Now identify ourselves. */
2175 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2176 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2177 if (sock_puts(&sock, buf) <0) goto bail;
2178 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2179 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2180 if (buf[0] != '2') {
2184 /* At this point we are authenticated. */
2185 if (!CtdlThreadCheckStop())
2186 receive_spool(&sock, node);
2187 if (!CtdlThreadCheckStop())
2188 transmit_spool(&sock, node);
2191 sock_puts(&sock, "QUIT");
2193 FreeStrBuf(&CCC->sReadBuf);
2194 FreeStrBuf(&CCC->sMigrateBuf);
2197 network_talking_to(node, NTT_REMOVE);
2203 * Poll other Citadel nodes and transfer inbound/outbound network data.
2204 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2205 * only nodes to which we have data to send.
2207 void network_poll_other_citadel_nodes(int full_poll) {
2215 char spoolfile[256];
2217 if (working_ignetcfg == NULL) {
2218 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2222 /* Use the string tokenizer to grab one line at a time */
2223 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2224 if(CtdlThreadCheckStop())
2226 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2227 extract_token(node, linebuf, 0, '|', sizeof node);
2228 extract_token(secret, linebuf, 1, '|', sizeof secret);
2229 extract_token(host, linebuf, 2, '|', sizeof host);
2230 extract_token(port, linebuf, 3, '|', sizeof port);
2231 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2232 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2241 if (access(spoolfile, R_OK) == 0) {
2246 network_poll_node(node, secret, host, port);
2257 * It's ok if these directories already exist. Just fail silently.
2259 void create_spool_dirs(void) {
2260 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2261 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2262 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2263 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2264 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2265 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2266 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2267 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2268 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2269 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2270 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2271 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2272 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2273 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2274 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2275 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2283 * network_do_queue()
2285 * Run through the rooms doing various types of network stuff.
2287 void *network_do_queue(void *args) {
2288 static time_t last_run = 0L;
2289 struct RoomProcList *ptr;
2290 int full_processing = 1;
2291 struct CitContext networkerCC;
2293 /* Give the networker its own private CitContext */
2294 CtdlFillSystemContext(&networkerCC, "network");
2295 citthread_setspecific(MyConKey, (void *)&networkerCC );
2298 * Run the full set of processing tasks no more frequently
2299 * than once every n seconds
2301 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2302 full_processing = 0;
2303 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2304 config.c_net_freq - (time(NULL)- last_run)
2309 * This is a simple concurrency check to make sure only one queue run
2310 * is done at a time. We could do this with a mutex, but since we
2311 * don't really require extremely fine granularity here, we'll do it
2312 * with a static variable instead.
2315 CtdlClearSystemContext();
2320 /* Load the IGnet Configuration into memory */
2321 load_working_ignetcfg();
2324 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2325 * then we poll everyone. Otherwise we only poll nodes we have stuff
2328 network_poll_other_citadel_nodes(full_processing);
2331 * Load the network map and filter list into memory.
2334 filterlist = load_filter_list();
2337 * Go ahead and run the queue
2339 if (full_processing && !CtdlThreadCheckStop()) {
2340 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2341 CtdlForEachRoom(network_queue_room, NULL);
2344 if (rplist != NULL) {
2345 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2346 while (rplist != NULL && !CtdlThreadCheckStop()) {
2347 char spoolroomname[ROOMNAMELEN];
2348 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2349 begin_critical_section(S_RPLIST);
2351 /* pop this record off the list */
2353 rplist = rplist->next;
2356 /* invalidate any duplicate entries to prevent double processing */
2357 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2358 if (!strcasecmp(ptr->name, spoolroomname)) {
2363 end_critical_section(S_RPLIST);
2364 if (spoolroomname[0] != 0) {
2365 network_spoolout_room(spoolroomname);
2370 /* If there is anything in the inbound queue, process it */
2371 if (!CtdlThreadCheckStop()) {
2372 network_do_spoolin();
2375 /* Save the network map back to disk */
2376 write_network_map();
2378 /* Free the filter list in memory */
2379 free_filter_list(filterlist);
2382 network_consolidate_spoolout();
2384 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2386 if (full_processing) {
2387 last_run = time(NULL);
2392 /* Reschedule this task to happen again periodically, unless the thread system indicates
2393 * that the server is shutting down.
2395 if (!CtdlThreadCheckStop()) {
2396 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK,
2397 network_do_queue, NULL, time(NULL) + 60
2401 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2403 CtdlClearSystemContext();
2409 * cmd_netp() - authenticate to the server as another Citadel node polling
2410 * for network traffic
2412 void cmd_netp(char *cmdbuf)
2423 extract_token(node, cmdbuf, 0, '|', sizeof node);
2424 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2426 /* load the IGnet Configuration to check node validity */
2427 load_working_ignetcfg();
2428 v = is_valid_node(nexthop, secret, node);
2431 snprintf(err_buf, sizeof err_buf,
2432 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2433 node, CC->cs_host, CC->cs_addr
2435 CtdlLogPrintf(CTDL_WARNING, err_buf);
2436 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2437 CtdlAideMessage(err_buf, "IGNet Networking.");
2441 if (strcasecmp(pass, secret)) {
2442 snprintf(err_buf, sizeof err_buf,
2443 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2444 CC->cs_host, CC->cs_addr, node
2446 CtdlLogPrintf(CTDL_WARNING, err_buf);
2447 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2448 CtdlAideMessage(err_buf, "IGNet Networking.");
2452 if (network_talking_to(node, NTT_CHECK)) {
2453 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2454 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2458 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2459 network_talking_to(node, NTT_ADD);
2460 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2461 CC->net_node, CC->cs_host, CC->cs_addr
2463 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2467 int network_room_handler (struct ctdlroom *room)
2469 network_queue_room(room, NULL);
2475 * Module entry point
2477 CTDL_MODULE_INIT(network)
2481 create_spool_dirs();
2482 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2483 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2484 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2485 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2486 CtdlRegisterRoomHook(network_room_handler);
2487 CtdlRegisterCleanupHook(destroy_network_queue_room);
2490 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2491 /* return our Subversion id for the Log */