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) || (StatBuf.st_size == 0))
433 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
435 sprintf(tempfilename + len, ".%d", CC->cs_pid);
437 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
439 if ((TmpFD > 0) && (errno == 0))
441 char *tmp = malloc(StatBuf.st_size * 2);
442 memset(tmp, ' ', StatBuf.st_size * 2);
443 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
445 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
448 cprintf("%d Unable to allocate the space required for %s: %s\n",
449 ERROR + INTERNAL_ERROR,
452 unlink(tempfilename);
455 lseek(TmpFD, SEEK_SET, 0);
458 cprintf("%d Unable to allocate the space required for %s: %s\n",
459 ERROR + INTERNAL_ERROR,
462 unlink(tempfilename);
467 cprintf("%d %s\n", SEND_LISTING, tempfilename);
470 while (rc = CtdlClientGetLine(Line),
473 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
475 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
476 write(TmpFD, ChrPtr(Line), StrLength(Line));
477 len += StrLength(Line);
480 ftruncate(TmpFD, len);
483 /* Now copy the temp file to its permanent location.
484 * (We copy instead of link because they may be on different filesystems)
486 begin_critical_section(S_NETCONFIGS);
487 rename(tempfilename, filename);
488 end_critical_section(S_NETCONFIGS);
493 * Deliver digest messages
495 void network_deliver_digest(SpoolControl *sc) {
498 struct CtdlMessage *msg = NULL;
501 size_t recps_len = SIZ;
503 struct recptypes *valid;
507 if (sc->num_msgs_spooled < 1) {
508 fclose(sc->digestfp);
513 msg = malloc(sizeof(struct CtdlMessage));
514 memset(msg, 0, sizeof(struct CtdlMessage));
515 msg->cm_magic = CTDLMESSAGE_MAGIC;
516 msg->cm_format_type = FMT_RFC822;
517 msg->cm_anon_type = MES_NORMAL;
519 sprintf(buf, "%ld", time(NULL));
520 msg->cm_fields['T'] = strdup(buf);
521 msg->cm_fields['A'] = strdup(CC->room.QRname);
522 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
523 msg->cm_fields['U'] = strdup(buf);
524 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
525 for (i=0; buf[i]; ++i) {
526 if (isspace(buf[i])) buf[i]='_';
527 buf[i] = tolower(buf[i]);
529 msg->cm_fields['F'] = strdup(buf);
530 msg->cm_fields['R'] = strdup(buf);
532 /* Set the 'List-ID' header */
533 msg->cm_fields['L'] = malloc(1024);
534 snprintf(msg->cm_fields['L'], 1024,
535 "%s <%ld.list-id.%s>",
542 * Go fetch the contents of the digest
544 fseek(sc->digestfp, 0L, SEEK_END);
545 msglen = ftell(sc->digestfp);
547 msg->cm_fields['M'] = malloc(msglen + 1);
548 fseek(sc->digestfp, 0L, SEEK_SET);
549 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
550 msg->cm_fields['M'][msglen] = '\0';
552 fclose(sc->digestfp);
555 /* Now generate the delivery instructions */
558 * Figure out how big a buffer we need to allocate
560 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
561 recps_len = recps_len + strlen(nptr->name) + 2;
564 recps = malloc(recps_len);
567 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
574 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
575 if (nptr != sc->digestrecps) {
578 strcat(recps, nptr->name);
581 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
582 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
584 /* Now submit the message */
585 valid = validate_recipients(recps, NULL, 0);
588 valid->bounce_to = strdup(bounce_to);
589 valid->envelope_from = strdup(bounce_to);
590 CtdlSubmitMsg(msg, valid, NULL, 0);
592 CtdlFreeMessage(msg);
593 free_recipients(valid);
598 * Deliver list messages to everyone on the list ... efficiently
600 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
602 size_t recps_len = SIZ;
603 struct recptypes *valid;
607 /* Don't do this if there were no recipients! */
608 if (sc->listrecps == NULL) return;
610 /* Now generate the delivery instructions */
613 * Figure out how big a buffer we need to allocate
615 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
616 recps_len = recps_len + strlen(nptr->name) + 2;
619 recps = malloc(recps_len);
622 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
629 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
630 if (nptr != sc->listrecps) {
633 strcat(recps, nptr->name);
636 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
637 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
639 /* Now submit the message */
640 valid = validate_recipients(recps, NULL, 0);
643 valid->bounce_to = strdup(bounce_to);
644 valid->envelope_from = strdup(bounce_to);
645 CtdlSubmitMsg(msg, valid, NULL, 0);
646 free_recipients(valid);
648 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
655 * Spools out one message from the list.
657 void network_spool_msg(long msgnum, void *userdata) {
660 char *newpath = NULL;
661 size_t instr_len = SIZ;
662 struct CtdlMessage *msg = NULL;
665 struct ser_ret sermsg;
667 char filename[PATH_MAX];
671 int delete_after_send = 0; /* Set to 1 to delete after spooling */
672 int ok_to_participate = 0;
673 struct recptypes *valid;
675 sc = (SpoolControl *)userdata;
678 * Process mailing list recipients
681 if (sc->listrecps != NULL) {
682 /* Fetch the message. We're going to need to modify it
683 * in order to insert the [list name] in it, etc.
685 msg = CtdlFetchMessage(msgnum, 1);
687 if (msg->cm_fields['V'] == NULL){
688 /* local message, no enVelope */
691 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
692 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
693 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
695 msg->cm_fields['K'] = SmashStrBuf(&Buf);
698 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
700 /* Set the 'List-ID' header */
701 if (msg->cm_fields['L'] != NULL) {
702 free(msg->cm_fields['L']);
704 msg->cm_fields['L'] = malloc(1024);
705 snprintf(msg->cm_fields['L'], 1024,
706 "%s <%ld.list-id.%s>",
712 /* Prepend "[List name]" to the subject */
713 if (msg->cm_fields['U'] == NULL) {
714 msg->cm_fields['U'] = strdup("(no subject)");
716 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
717 free(msg->cm_fields['U']);
718 msg->cm_fields['U'] = strdup(buf);
720 /* Set the recipient of the list message to the
721 * email address of the room itself.
722 * FIXME ... I want to be able to pick any address
724 if (msg->cm_fields['R'] != NULL) {
725 free(msg->cm_fields['R']);
727 msg->cm_fields['R'] = malloc(256);
728 snprintf(msg->cm_fields['R'], 256,
729 "room_%s@%s", CC->room.QRname,
731 for (i=0; msg->cm_fields['R'][i]; ++i) {
732 if (isspace(msg->cm_fields['R'][i])) {
733 msg->cm_fields['R'][i] = '_';
737 /* Handle delivery */
738 network_deliver_list(msg, sc);
739 CtdlFreeMessage(msg);
744 * Process digest recipients
746 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
747 msg = CtdlFetchMessage(msgnum, 1);
749 fprintf(sc->digestfp, " -----------------------------------"
750 "------------------------------------"
752 fprintf(sc->digestfp, "From: ");
753 if (msg->cm_fields['A'] != NULL) {
754 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
756 if (msg->cm_fields['F'] != NULL) {
757 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
759 else if (msg->cm_fields['N'] != NULL) {
760 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
762 fprintf(sc->digestfp, "\n");
763 if (msg->cm_fields['U'] != NULL) {
764 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
767 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
769 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
770 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
772 StrBufTrim(CC->redirect_buffer);
773 fwrite(HKEY("\n"), 1, sc->digestfp);
774 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
775 fwrite(HKEY("\n"), 1, sc->digestfp);
777 FreeStrBuf(&CC->redirect_buffer);
779 sc->num_msgs_spooled += 1;
785 * Process client-side list participations for this room
788 if (sc->participates != NULL) {
789 msg = CtdlFetchMessage(msgnum, 1);
792 /* Only send messages which originated on our own Citadel
793 * network, otherwise we'll end up sending the remote
794 * mailing list's messages back to it, which is rude...
796 ok_to_participate = 0;
797 if (msg->cm_fields['N'] != NULL) {
798 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
799 ok_to_participate = 1;
801 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
802 ok_to_participate = 1;
805 if (ok_to_participate) {
806 if (msg->cm_fields['F'] != NULL) {
807 free(msg->cm_fields['F']);
809 msg->cm_fields['F'] = malloc(SIZ);
810 /* Replace the Internet email address of the actual
811 * author with the email address of the room itself,
812 * so the remote listserv doesn't reject us.
813 * FIXME ... I want to be able to pick any address
815 snprintf(msg->cm_fields['F'], SIZ,
816 "room_%s@%s", CC->room.QRname,
818 for (i=0; msg->cm_fields['F'][i]; ++i) {
819 if (isspace(msg->cm_fields['F'][i])) {
820 msg->cm_fields['F'][i] = '_';
825 * Figure out how big a buffer we need to allocate
827 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
829 if (msg->cm_fields['R'] == NULL) {
830 free(msg->cm_fields['R']);
832 msg->cm_fields['R'] = strdup(nptr->name);
834 valid = validate_recipients(nptr->name, NULL, 0);
835 CtdlSubmitMsg(msg, valid, "", 0);
836 free_recipients(valid);
840 CtdlFreeMessage(msg);
845 * Process IGnet push shares
847 msg = CtdlFetchMessage(msgnum, 1);
851 /* Prepend our node name to the Path field whenever
852 * sending a message to another IGnet node
854 if (msg->cm_fields['P'] == NULL) {
855 msg->cm_fields['P'] = strdup("username");
857 newpath_len = strlen(msg->cm_fields['P']) +
858 strlen(config.c_nodename) + 2;
859 newpath = malloc(newpath_len);
860 snprintf(newpath, newpath_len, "%s!%s",
861 config.c_nodename, msg->cm_fields['P']);
862 free(msg->cm_fields['P']);
863 msg->cm_fields['P'] = newpath;
866 * Determine if this message is set to be deleted
867 * after sending out on the network
869 if (msg->cm_fields['S'] != NULL) {
870 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
871 delete_after_send = 1;
875 /* Now send it to every node */
876 if (sc->ignet_push_shares != NULL)
877 for (mptr = sc->ignet_push_shares; mptr != NULL;
882 /* Check for valid node name */
883 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
884 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
888 /* Check for split horizon */
889 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
890 bang = num_tokens(msg->cm_fields['P'], '!');
891 if (bang > 1) for (i=0; i<(bang-1); ++i) {
892 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
893 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
894 buf, mptr->remote_nodename) ;
895 if (!strcasecmp(buf, mptr->remote_nodename)) {
897 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
898 mptr->remote_nodename);
901 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
905 /* Send the message */
909 * Force the message to appear in the correct room
910 * on the far end by setting the C field correctly
912 if (msg->cm_fields['C'] != NULL) {
913 free(msg->cm_fields['C']);
915 if (!IsEmptyStr(mptr->remote_roomname)) {
916 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
919 msg->cm_fields['C'] = strdup(CC->room.QRname);
922 /* serialize it for transmission */
923 serialize_message(&sermsg, msg);
924 if (sermsg.len > 0) {
926 /* write it to a spool file */
927 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
929 mptr->remote_nodename,
933 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
934 fp = fopen(filename, "ab");
941 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
944 /* free the serialized version */
950 CtdlFreeMessage(msg);
953 /* update lastsent */
954 sc->lastsent = msgnum;
956 /* Delete this message if delete-after-send is set */
957 if (delete_after_send) {
958 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
964 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
970 char roomname[ROOMNAMELEN];
973 int skipthisline = 0;
974 namelist *nptr = NULL;
975 maplist *mptr = NULL;
978 fp = fopen(filename, "r");
982 sc = malloc(sizeof(SpoolControl));
983 memset(sc, 0, sizeof(SpoolControl));
986 while (fgets(buf, sizeof buf, fp) != NULL) {
987 buf[strlen(buf)-1] = 0;
989 extract_token(instr, buf, 0, '|', sizeof instr);
990 if (!strcasecmp(instr, strof(lastsent))) {
991 sc->lastsent = extract_long(buf, 1);
993 else if (!strcasecmp(instr, strof(listrecp))) {
995 malloc(sizeof(namelist));
996 nptr->next = sc->listrecps;
997 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
998 sc->listrecps = nptr;
1000 else if (!strcasecmp(instr, strof(participate))) {
1002 malloc(sizeof(namelist));
1003 nptr->next = sc->participates;
1004 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1005 sc->participates = nptr;
1007 else if (!strcasecmp(instr, strof(digestrecp))) {
1009 malloc(sizeof(namelist));
1010 nptr->next = sc->digestrecps;
1011 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1012 sc->digestrecps = nptr;
1014 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1015 extract_token(nodename, buf, 1, '|', sizeof nodename);
1016 extract_token(roomname, buf, 2, '|', sizeof roomname);
1017 mptr = (maplist *) malloc(sizeof(maplist));
1018 mptr->next = sc->ignet_push_shares;
1019 strcpy(mptr->remote_nodename, nodename);
1020 strcpy(mptr->remote_roomname, roomname);
1021 sc->ignet_push_shares = mptr;
1024 /* Preserve 'other' lines ... *unless* they happen to
1025 * be subscribe/unsubscribe pendings with expired
1029 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1030 if (time(NULL) - extract_long(buf, 4) > EXP) {
1034 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1035 if (time(NULL) - extract_long(buf, 3) > EXP) {
1040 if (skipthisline == 0) {
1041 linesize = strlen(buf);
1042 sc->misc = realloc(sc->misc,
1043 (miscsize + linesize + 2) );
1044 sprintf(&sc->misc[miscsize], "%s\n", buf);
1045 miscsize = miscsize + linesize + 1;
1055 void free_spoolcontrol_struct(SpoolControl **scc)
1058 namelist *nptr = NULL;
1059 maplist *mptr = NULL;
1062 while (sc->listrecps != NULL) {
1063 nptr = sc->listrecps->next;
1064 free(sc->listrecps);
1065 sc->listrecps = nptr;
1067 /* Do the same for digestrecps */
1068 while (sc->digestrecps != NULL) {
1069 nptr = sc->digestrecps->next;
1070 free(sc->digestrecps);
1071 sc->digestrecps = nptr;
1073 /* Do the same for participates */
1074 while (sc->participates != NULL) {
1075 nptr = sc->participates->next;
1076 free(sc->participates);
1077 sc->participates = nptr;
1079 while (sc->ignet_push_shares != NULL) {
1080 mptr = sc->ignet_push_shares->next;
1081 free(sc->ignet_push_shares);
1082 sc->ignet_push_shares = mptr;
1089 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1091 char tempfilename[PATH_MAX];
1094 namelist *nptr = NULL;
1095 maplist *mptr = NULL;
1099 long reltid; /* if we don't have SYS_gettid, use "random" value */
1103 len = strlen(filename);
1104 memcpy(tempfilename, filename, len + 1);
1107 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1108 reltid = syscall(SYS_gettid);
1110 gettimeofday(&tv, NULL);
1111 /* Promote to time_t; types differ on some OSes (like darwin) */
1112 unixtime = tv.tv_sec;
1114 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1117 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1119 if ((TmpFD < 0) || (errno != 0)) {
1120 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1121 filename, strerror(errno));
1122 free_spoolcontrol_struct(scc);
1123 unlink(tempfilename);
1126 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1128 /* Write out the listrecps while freeing from memory at the
1129 * same time. Am I clever or what? :)
1131 while (sc->listrecps != NULL) {
1132 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1133 nptr = sc->listrecps->next;
1134 free(sc->listrecps);
1135 sc->listrecps = nptr;
1137 /* Do the same for digestrecps */
1138 while (sc->digestrecps != NULL) {
1139 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1140 nptr = sc->digestrecps->next;
1141 free(sc->digestrecps);
1142 sc->digestrecps = nptr;
1144 /* Do the same for participates */
1145 while (sc->participates != NULL) {
1146 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1147 nptr = sc->participates->next;
1148 free(sc->participates);
1149 sc->participates = nptr;
1151 while (sc->ignet_push_shares != NULL) {
1152 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1153 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1154 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1156 StrBufAppendPrintf(Cfg, "\n");
1157 mptr = sc->ignet_push_shares->next;
1158 free(sc->ignet_push_shares);
1159 sc->ignet_push_shares = mptr;
1161 if (sc->misc != NULL) {
1162 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1166 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1167 if ((rc >=0 ) && (rc == StrLength(Cfg)))
1170 rename(tempfilename, filename);
1173 CtdlLogPrintf(CTDL_EMERG,
1174 "unable to write %s; [%s]; not enough space on the disk?\n",
1178 unlink(tempfilename);
1186 int is_recipient(SpoolControl *sc, const char *Name)
1192 nptr = sc->listrecps;
1193 while (nptr != NULL) {
1194 if (strncmp(Name, nptr->name, len)==0)
1198 /* Do the same for digestrecps */
1199 nptr = sc->digestrecps;
1200 while (nptr != NULL) {
1201 if (strncmp(Name, nptr->name, len)==0)
1205 /* Do the same for participates */
1206 nptr = sc->participates;
1207 while (nptr != NULL) {
1208 if (strncmp(Name, nptr->name, len)==0)
1217 * Batch up and send all outbound traffic from the current room
1219 void network_spoolout_room(char *room_to_spool) {
1221 char filename[PATH_MAX];
1226 * If the room doesn't exist, don't try to perform its networking tasks.
1227 * Normally this should never happen, but once in a while maybe a room gets
1228 * queued for networking and then deleted before it can happen.
1230 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1231 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1235 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1236 begin_critical_section(S_NETCONFIGS);
1238 /* Only do net processing for rooms that have netconfigs */
1239 if (!read_spoolcontrol_file(&sc, filename))
1241 end_critical_section(S_NETCONFIGS);
1244 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1246 /* If there are digest recipients, we have to build a digest */
1247 if (sc->digestrecps != NULL) {
1248 sc->digestfp = tmpfile();
1249 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1252 /* Do something useful */
1253 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1254 network_spool_msg, sc);
1256 /* If we wrote a digest, deliver it and then close it */
1257 snprintf(buf, sizeof buf, "room_%s@%s",
1258 CC->room.QRname, config.c_fqdn);
1259 for (i=0; buf[i]; ++i) {
1260 buf[i] = tolower(buf[i]);
1261 if (isspace(buf[i])) buf[i] = '_';
1263 if (sc->digestfp != NULL) {
1264 fprintf(sc->digestfp, " -----------------------------------"
1265 "------------------------------------"
1267 "You are subscribed to the '%s' "
1269 "To post to the list: %s\n",
1270 CC->room.QRname, buf
1272 network_deliver_digest(sc); /* deliver and close */
1275 /* Now rewrite the config file */
1276 writenfree_spoolcontrol_file (&sc, filename);
1277 end_critical_section(S_NETCONFIGS);
1283 * Send the *entire* contents of the current room to one specific network node,
1284 * ignoring anything we know about which messages have already undergone
1285 * network processing. This can be used to bring a new node into sync.
1287 int network_sync_to(char *target_node) {
1289 int num_spooled = 0;
1295 char filename[PATH_MAX];
1298 /* Grab the configuration line we're looking for */
1299 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1300 begin_critical_section(S_NETCONFIGS);
1301 fp = fopen(filename, "r");
1303 end_critical_section(S_NETCONFIGS);
1306 while (fgets(buf, sizeof buf, fp) != NULL) {
1307 buf[strlen(buf)-1] = 0;
1308 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1309 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1310 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1311 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1312 && (!strcasecmp(sc_node, target_node)) ) {
1315 /* Concise syntax because we don't need a full linked-list */
1316 memset(&sc, 0, sizeof(SpoolControl));
1317 sc.ignet_push_shares = (maplist *)
1318 malloc(sizeof(maplist));
1319 sc.ignet_push_shares->next = NULL;
1320 safestrncpy(sc.ignet_push_shares->remote_nodename,
1322 sizeof sc.ignet_push_shares->remote_nodename);
1323 safestrncpy(sc.ignet_push_shares->remote_roomname,
1325 sizeof sc.ignet_push_shares->remote_roomname);
1329 end_critical_section(S_NETCONFIGS);
1331 if (!found_node) return(-1);
1333 /* Send ALL messages */
1334 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1335 network_spool_msg, &sc);
1337 /* Concise cleanup because we know there's only one node in the sc */
1338 free(sc.ignet_push_shares);
1340 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1341 num_spooled, target_node);
1342 return(num_spooled);
1347 * Implements the NSYN command
1349 void cmd_nsyn(char *argbuf) {
1351 char target_node[256];
1353 if (CtdlAccessCheck(ac_aide)) return;
1355 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1356 num_spooled = network_sync_to(target_node);
1357 if (num_spooled >= 0) {
1358 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1361 cprintf("%d No such room/node share exists.\n",
1362 ERROR + ROOM_NOT_FOUND);
1369 * Batch up and send all outbound traffic from the current room
1371 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1372 struct RoomProcList *ptr;
1374 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1375 if (ptr == NULL) return;
1377 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1378 begin_critical_section(S_RPLIST);
1381 end_critical_section(S_RPLIST);
1384 void destroy_network_queue_room(void)
1386 struct RoomProcList *cur, *p;
1387 NetMap *nmcur, *nmp;
1390 begin_critical_section(S_RPLIST);
1398 end_critical_section(S_RPLIST);
1401 while (nmcur != NULL)
1408 if (working_ignetcfg != NULL)
1409 free (working_ignetcfg);
1410 working_ignetcfg = NULL;
1415 * Learn topology from path fields
1417 void network_learn_topology(char *node, char *path) {
1421 strcpy(nexthop, "");
1423 if (num_tokens(path, '!') < 3) return;
1424 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1425 if (!strcasecmp(nmptr->nodename, node)) {
1426 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1427 nmptr->lastcontact = time(NULL);
1433 /* If we got here then it's not in the map, so add it. */
1434 nmptr = (NetMap *) malloc(sizeof (NetMap));
1435 strcpy(nmptr->nodename, node);
1436 nmptr->lastcontact = time(NULL);
1437 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1438 nmptr->next = the_netmap;
1447 * Bounce a message back to the sender
1449 void network_bounce(struct CtdlMessage *msg, char *reason) {
1450 char *oldpath = NULL;
1452 char bouncesource[SIZ];
1453 char recipient[SIZ];
1454 struct recptypes *valid = NULL;
1455 char force_room[ROOMNAMELEN];
1456 static int serialnum = 0;
1459 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1461 if (msg == NULL) return;
1463 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1466 * Give it a fresh message ID
1468 if (msg->cm_fields['I'] != NULL) {
1469 free(msg->cm_fields['I']);
1471 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1472 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1473 msg->cm_fields['I'] = strdup(buf);
1476 * FIXME ... right now we're just sending a bounce; we really want to
1477 * include the text of the bounced message.
1479 if (msg->cm_fields['M'] != NULL) {
1480 free(msg->cm_fields['M']);
1482 msg->cm_fields['M'] = strdup(reason);
1483 msg->cm_format_type = 0;
1486 * Turn the message around
1488 if (msg->cm_fields['R'] == NULL) {
1489 free(msg->cm_fields['R']);
1492 if (msg->cm_fields['D'] == NULL) {
1493 free(msg->cm_fields['D']);
1496 snprintf(recipient, sizeof recipient, "%s@%s",
1497 msg->cm_fields['A'], msg->cm_fields['N']);
1499 if (msg->cm_fields['A'] == NULL) {
1500 free(msg->cm_fields['A']);
1503 if (msg->cm_fields['N'] == NULL) {
1504 free(msg->cm_fields['N']);
1507 if (msg->cm_fields['U'] == NULL) {
1508 free(msg->cm_fields['U']);
1511 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1512 msg->cm_fields['N'] = strdup(config.c_nodename);
1513 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1515 /* prepend our node to the path */
1516 if (msg->cm_fields['P'] != NULL) {
1517 oldpath = msg->cm_fields['P'];
1518 msg->cm_fields['P'] = NULL;
1521 oldpath = strdup("unknown_user");
1523 size = strlen(oldpath) + SIZ;
1524 msg->cm_fields['P'] = malloc(size);
1525 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1528 /* Now submit the message */
1529 valid = validate_recipients(recipient, NULL, 0);
1530 if (valid != NULL) if (valid->num_error != 0) {
1531 free_recipients(valid);
1534 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1535 strcpy(force_room, config.c_aideroom);
1538 strcpy(force_room, "");
1540 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1541 strcpy(force_room, config.c_aideroom);
1543 CtdlSubmitMsg(msg, valid, force_room, 0);
1546 if (valid != NULL) free_recipients(valid);
1547 CtdlFreeMessage(msg);
1548 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1555 * Process a buffer containing a single message from a single file
1556 * from the inbound queue
1558 void network_process_buffer(char *buffer, long size) {
1559 struct CtdlMessage *msg = NULL;
1562 struct recptypes *recp = NULL;
1563 char target_room[ROOMNAMELEN];
1564 struct ser_ret sermsg;
1565 char *oldpath = NULL;
1566 char filename[PATH_MAX];
1569 unsigned char firstbyte;
1570 unsigned char lastbyte;
1572 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1574 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1575 firstbyte = buffer[0];
1576 lastbyte = buffer[size-1];
1577 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1578 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1579 size, firstbyte, lastbyte);
1583 /* Set default target room to trash */
1584 strcpy(target_room, TWITROOM);
1586 /* Load the message into memory */
1587 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1588 memset(msg, 0, sizeof(struct CtdlMessage));
1589 msg->cm_magic = CTDLMESSAGE_MAGIC;
1590 msg->cm_anon_type = buffer[1];
1591 msg->cm_format_type = buffer[2];
1593 for (pos = 3; pos < size; ++pos) {
1594 field = buffer[pos];
1595 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1596 pos = pos + strlen(&buffer[(int)pos]);
1599 /* Check for message routing */
1600 if (msg->cm_fields['D'] != NULL) {
1601 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1603 /* route the message */
1604 strcpy(nexthop, "");
1605 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1606 /* prepend our node to the path */
1607 if (msg->cm_fields['P'] != NULL) {
1608 oldpath = msg->cm_fields['P'];
1609 msg->cm_fields['P'] = NULL;
1612 oldpath = strdup("unknown_user");
1614 size = strlen(oldpath) + SIZ;
1615 msg->cm_fields['P'] = malloc(size);
1616 snprintf(msg->cm_fields['P'], size, "%s!%s",
1617 config.c_nodename, oldpath);
1620 /* serialize the message */
1621 serialize_message(&sermsg, msg);
1624 if (IsEmptyStr(nexthop)) {
1625 strcpy(nexthop, msg->cm_fields['D']);
1635 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1636 fp = fopen(filename, "ab");
1638 fwrite(sermsg.ser, sermsg.len, 1, fp);
1642 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1645 CtdlFreeMessage(msg);
1649 else { /* invalid destination node name */
1652 "A message you sent could not be delivered due to an invalid destination node"
1653 " name. Please check the address and try sending the message again.\n");
1662 * Check to see if we already have a copy of this message, and
1663 * abort its processing if so. (We used to post a warning to Aide>
1664 * every time this happened, but the network is now so densely
1665 * connected that it's inevitable.)
1667 if (network_usetable(msg) != 0) {
1668 CtdlFreeMessage(msg);
1672 /* Learn network topology from the path */
1673 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1674 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1677 /* Is the sending node giving us a very persuasive suggestion about
1678 * which room this message should be saved in? If so, go with that.
1680 if (msg->cm_fields['C'] != NULL) {
1681 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1684 /* Otherwise, does it have a recipient? If so, validate it... */
1685 else if (msg->cm_fields['R'] != NULL) {
1686 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1687 if (recp != NULL) if (recp->num_error != 0) {
1689 "A message you sent could not be delivered due to an invalid address.\n"
1690 "Please check the address and try sending the message again.\n");
1692 free_recipients(recp);
1693 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1696 strcpy(target_room, ""); /* no target room if mail */
1699 /* Our last shot at finding a home for this message is to see if
1700 * it has the O field (Originating room) set.
1702 else if (msg->cm_fields['O'] != NULL) {
1703 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1706 /* Strip out fields that are only relevant during transit */
1707 if (msg->cm_fields['D'] != NULL) {
1708 free(msg->cm_fields['D']);
1709 msg->cm_fields['D'] = NULL;
1711 if (msg->cm_fields['C'] != NULL) {
1712 free(msg->cm_fields['C']);
1713 msg->cm_fields['C'] = NULL;
1716 /* save the message into a room */
1717 if (PerformNetprocHooks(msg, target_room) == 0) {
1718 msg->cm_flags = CM_SKIP_HOOKS;
1719 CtdlSubmitMsg(msg, recp, target_room, 0);
1721 CtdlFreeMessage(msg);
1722 free_recipients(recp);
1727 * Process a single message from a single file from the inbound queue
1729 void network_process_message(FILE *fp, long msgstart, long msgend) {
1734 hold_pos = ftell(fp);
1735 size = msgend - msgstart + 1;
1736 buffer = malloc(size);
1737 if (buffer != NULL) {
1738 fseek(fp, msgstart, SEEK_SET);
1739 if (fread(buffer, size, 1, fp) > 0) {
1740 network_process_buffer(buffer, size);
1745 fseek(fp, hold_pos, SEEK_SET);
1750 * Process a single file from the inbound queue
1752 void network_process_file(char *filename) {
1754 long msgstart = (-1L);
1755 long msgend = (-1L);
1760 fp = fopen(filename, "rb");
1762 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1766 fseek(fp, 0L, SEEK_END);
1767 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1770 /* Look for messages in the data stream and break them out */
1771 while (ch = getc(fp), ch >= 0) {
1774 if (msgstart >= 0L) {
1775 msgend = msgcur - 1;
1776 network_process_message(fp, msgstart, msgend);
1784 msgend = msgcur - 1;
1785 if (msgstart >= 0L) {
1786 network_process_message(fp, msgstart, msgend);
1795 * Process anything in the inbound queue
1797 void network_do_spoolin(void) {
1800 struct stat statbuf;
1801 char filename[PATH_MAX];
1802 static time_t last_spoolin_mtime = 0L;
1805 * Check the spoolin directory's modification time. If it hasn't
1806 * been touched, we don't need to scan it.
1808 if (stat(ctdl_netin_dir, &statbuf)) return;
1809 if (statbuf.st_mtime == last_spoolin_mtime) {
1810 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1813 last_spoolin_mtime = statbuf.st_mtime;
1814 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1817 * Ok, there's something interesting in there, so scan it.
1819 dp = opendir(ctdl_netin_dir);
1820 if (dp == NULL) return;
1822 while (d = readdir(dp), d != NULL) {
1823 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1830 network_process_file(filename);
1838 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1839 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1841 void network_consolidate_spoolout(void) {
1844 char filename[PATH_MAX];
1850 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1851 dp = opendir(ctdl_netout_dir);
1852 if (dp == NULL) return;
1853 while (d = readdir(dp), d != NULL) {
1855 (strcmp(d->d_name, "."))
1856 && (strcmp(d->d_name, ".."))
1857 && (strchr(d->d_name, '@') != NULL)
1859 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1860 ptr = strchr(nexthop, '@');
1870 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1871 if (network_talking_to(nexthop, NTT_CHECK)) {
1872 CtdlLogPrintf(CTDL_DEBUG,
1873 "Currently online with %s - skipping for now\n",
1878 network_talking_to(nexthop, NTT_ADD);
1879 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1881 ctdl_netout_dir, nexthop,
1885 network_talking_to(nexthop, NTT_REMOVE);
1891 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1893 dp = opendir(ctdl_netout_dir);
1894 if (dp == NULL) return;
1896 while (d = readdir(dp), d != NULL) {
1897 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1899 ptr = strchr(d->d_name, '@');
1909 strcpy(nexthop, "");
1910 i = is_valid_node(nexthop, NULL, d->d_name);
1912 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1923 * receive network spool from the remote system
1925 void receive_spool(int *sock, char *remote_nodename) {
1926 int download_len = 0L;
1927 int bytes_received = 0L;
1929 char tempfilename[PATH_MAX];
1930 char permfilename[PATH_MAX];
1934 snprintf(tempfilename,
1935 sizeof tempfilename,
1943 snprintf(permfilename,
1944 sizeof permfilename,
1952 if (sock_puts(sock, "NDOP") < 0) return;
1953 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1954 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1955 if (buf[0] != '2') {
1959 download_len = extract_long(&buf[4], 0);
1960 if (download_len <= 0) {
1964 bytes_received = 0L;
1965 fp = fopen(tempfilename, "w");
1967 CtdlLogPrintf(CTDL_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1971 CtdlLogPrintf(CTDL_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1972 while (bytes_received < download_len) {
1974 * If shutting down we can exit here and unlink the temp file.
1975 * this shouldn't loose us any messages.
1977 if (CtdlThreadCheckStop())
1980 unlink(tempfilename);
1983 snprintf(buf, sizeof buf, "READ %d|%d",
1985 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1986 ? IGNET_PACKET_SIZE : (download_len - bytes_received))
1989 if (sock_puts(sock, buf) < 0) {
1991 unlink(tempfilename);
1994 if (sock_getln(sock, buf, sizeof buf) < 0) {
1996 unlink(tempfilename);
2000 if (buf[0] == '6') {
2001 plen = extract_int(&buf[4], 0);
2002 StrBuf *pbuf = NewStrBuf();
2003 if (socket_read_blob(sock, pbuf, plen, CLIENT_TIMEOUT) != plen) {
2004 CtdlLogPrintf(CTDL_INFO, "Short read from peer; aborting.\n");
2006 unlink(tempfilename);
2010 fwrite(ChrPtr(pbuf), plen, 1, fp);
2011 bytes_received += plen;
2018 /* Last chance for shutdown exit */
2019 if (CtdlThreadCheckStop())
2021 unlink(tempfilename);
2025 if (sock_puts(sock, "CLOS") < 0) {
2026 unlink(tempfilename);
2031 * From here on we must complete or messages will get lost
2033 if (sock_getln(sock, buf, sizeof buf) < 0) {
2034 unlink(tempfilename);
2038 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2041 * Now move the temp file to its permanent location.
2043 if (link(tempfilename, permfilename) != 0) {
2044 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2045 tempfilename, permfilename, strerror(errno)
2049 unlink(tempfilename);
2055 * transmit network spool to the remote system
2057 void transmit_spool(int *sock, char *remote_nodename)
2062 long bytes_to_write, thisblock, bytes_written;
2066 if (sock_puts(sock, "NUOP") < 0) return;
2067 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2068 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2069 if (buf[0] != '2') {
2073 snprintf(sfname, sizeof sfname,
2078 fd = open(sfname, O_RDONLY);
2080 if (errno != ENOENT) {
2081 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2086 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2087 bytes_to_write = plen;
2088 while (bytes_to_write > 0L) {
2089 /* Exit if shutting down */
2090 if (CtdlThreadCheckStop())
2096 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2097 if (sock_puts(sock, buf) < 0) {
2101 if (sock_getln(sock, buf, sizeof buf) < 0) {
2105 thisblock = atol(&buf[4]);
2106 if (buf[0] == '7') {
2107 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2111 bytes_to_write -= thisblock;
2112 bytes_written += thisblock;
2122 /* Last chance for shutdown exit */
2123 if(CtdlThreadCheckStop())
2126 if (sock_puts(sock, "UCLS 1") < 0) return;
2129 * From here on we must complete or messages will get lost
2131 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2132 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2133 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2134 if (buf[0] == '2') {
2135 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2143 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2145 void network_poll_node(char *node, char *secret, char *host, char *port) {
2149 char connected_to[SIZ];
2152 if (network_talking_to(node, NTT_CHECK)) return;
2153 network_talking_to(node, NTT_ADD);
2154 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2155 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2157 sock = sock_connect(host, port, "tcp");
2159 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2160 network_talking_to(node, NTT_REMOVE);
2164 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2165 CCC->sReadBuf = NewStrBuf();
2166 CCC->sMigrateBuf = NewStrBuf();
2169 /* Read the server greeting */
2170 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2171 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2173 /* Check that the remote is who we think it is and warn the Aide if not */
2174 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2175 if (strcmp(connected_to, node))
2177 snprintf(err_buf, sizeof(err_buf),
2178 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2181 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2182 CtdlAideMessage(err_buf, "Network error");
2185 /* We're talking to the correct node. Now identify ourselves. */
2186 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2187 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2188 if (sock_puts(&sock, buf) <0) goto bail;
2189 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2190 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2191 if (buf[0] != '2') {
2195 /* At this point we are authenticated. */
2196 if (!CtdlThreadCheckStop())
2197 receive_spool(&sock, node);
2198 if (!CtdlThreadCheckStop())
2199 transmit_spool(&sock, node);
2202 sock_puts(&sock, "QUIT");
2204 FreeStrBuf(&CCC->sReadBuf);
2205 FreeStrBuf(&CCC->sMigrateBuf);
2208 network_talking_to(node, NTT_REMOVE);
2214 * Poll other Citadel nodes and transfer inbound/outbound network data.
2215 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2216 * only nodes to which we have data to send.
2218 void network_poll_other_citadel_nodes(int full_poll) {
2226 char spoolfile[256];
2228 if (working_ignetcfg == NULL) {
2229 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2233 /* Use the string tokenizer to grab one line at a time */
2234 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2235 if(CtdlThreadCheckStop())
2237 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2238 extract_token(node, linebuf, 0, '|', sizeof node);
2239 extract_token(secret, linebuf, 1, '|', sizeof secret);
2240 extract_token(host, linebuf, 2, '|', sizeof host);
2241 extract_token(port, linebuf, 3, '|', sizeof port);
2242 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2243 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2252 if (access(spoolfile, R_OK) == 0) {
2257 network_poll_node(node, secret, host, port);
2268 * It's ok if these directories already exist. Just fail silently.
2270 void create_spool_dirs(void) {
2271 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2272 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2273 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2274 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2275 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2276 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2277 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2278 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2279 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2280 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2281 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2282 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2283 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2284 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2285 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2286 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2294 * network_do_queue()
2296 * Run through the rooms doing various types of network stuff.
2298 void *network_do_queue(void *args) {
2299 static time_t last_run = 0L;
2300 struct RoomProcList *ptr;
2301 int full_processing = 1;
2302 struct CitContext networkerCC;
2304 /* Give the networker its own private CitContext */
2305 CtdlFillSystemContext(&networkerCC, "network");
2306 citthread_setspecific(MyConKey, (void *)&networkerCC );
2309 * Run the full set of processing tasks no more frequently
2310 * than once every n seconds
2312 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2313 full_processing = 0;
2314 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2315 config.c_net_freq - (time(NULL)- last_run)
2320 * This is a simple concurrency check to make sure only one queue run
2321 * is done at a time. We could do this with a mutex, but since we
2322 * don't really require extremely fine granularity here, we'll do it
2323 * with a static variable instead.
2326 CtdlClearSystemContext();
2331 /* Load the IGnet Configuration into memory */
2332 load_working_ignetcfg();
2335 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2336 * then we poll everyone. Otherwise we only poll nodes we have stuff
2339 network_poll_other_citadel_nodes(full_processing);
2342 * Load the network map and filter list into memory.
2345 filterlist = load_filter_list();
2348 * Go ahead and run the queue
2350 if (full_processing && !CtdlThreadCheckStop()) {
2351 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2352 CtdlForEachRoom(network_queue_room, NULL);
2355 if (rplist != NULL) {
2356 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2357 while (rplist != NULL && !CtdlThreadCheckStop()) {
2358 char spoolroomname[ROOMNAMELEN];
2359 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2360 begin_critical_section(S_RPLIST);
2362 /* pop this record off the list */
2364 rplist = rplist->next;
2367 /* invalidate any duplicate entries to prevent double processing */
2368 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2369 if (!strcasecmp(ptr->name, spoolroomname)) {
2374 end_critical_section(S_RPLIST);
2375 if (spoolroomname[0] != 0) {
2376 network_spoolout_room(spoolroomname);
2381 /* If there is anything in the inbound queue, process it */
2382 if (!CtdlThreadCheckStop()) {
2383 network_do_spoolin();
2386 /* Save the network map back to disk */
2387 write_network_map();
2389 /* Free the filter list in memory */
2390 free_filter_list(filterlist);
2393 network_consolidate_spoolout();
2395 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2397 if (full_processing) {
2398 last_run = time(NULL);
2403 /* Reschedule this task to happen again periodically, unless the thread system indicates
2404 * that the server is shutting down.
2406 if (!CtdlThreadCheckStop()) {
2407 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK,
2408 network_do_queue, NULL, time(NULL) + 60
2412 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2414 CtdlClearSystemContext();
2420 * cmd_netp() - authenticate to the server as another Citadel node polling
2421 * for network traffic
2423 void cmd_netp(char *cmdbuf)
2434 extract_token(node, cmdbuf, 0, '|', sizeof node);
2435 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2437 /* load the IGnet Configuration to check node validity */
2438 load_working_ignetcfg();
2439 v = is_valid_node(nexthop, secret, node);
2442 snprintf(err_buf, sizeof err_buf,
2443 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2444 node, CC->cs_host, CC->cs_addr
2446 CtdlLogPrintf(CTDL_WARNING, err_buf);
2447 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2448 CtdlAideMessage(err_buf, "IGNet Networking.");
2452 if (strcasecmp(pass, secret)) {
2453 snprintf(err_buf, sizeof err_buf,
2454 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2455 CC->cs_host, CC->cs_addr, node
2457 CtdlLogPrintf(CTDL_WARNING, err_buf);
2458 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2459 CtdlAideMessage(err_buf, "IGNet Networking.");
2463 if (network_talking_to(node, NTT_CHECK)) {
2464 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2465 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2469 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2470 network_talking_to(node, NTT_ADD);
2471 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2472 CC->net_node, CC->cs_host, CC->cs_addr
2474 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2478 int network_room_handler (struct ctdlroom *room)
2480 network_queue_room(room, NULL);
2486 * Module entry point
2488 CTDL_MODULE_INIT(network)
2492 create_spool_dirs();
2493 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2494 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2495 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2496 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2497 CtdlRegisterRoomHook(network_room_handler);
2498 CtdlRegisterCleanupHook(destroy_network_queue_room);
2501 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2502 /* return our Subversion id for the Log */