2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2011 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
22 * This is a fairly high-level type of critical section. It ensures that no
23 * two threads work on the netconfigs files at the same time. Since we do
24 * so many things inside these, here are the rules:
25 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26 * 2. Do *not* perform any I/O with the client during these sections.
31 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32 * requests that have not been confirmed will be deleted.
34 #define EXP 259200 /* three days */
46 #include <sys/types.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
53 # include <sys/time.h>
61 # if HAVE_SYS_SYSCALL_H
62 # include <sys/syscall.h>
69 #include <libcitadel.h>
72 #include "citserver.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
82 #include "citadel_dirs.h"
91 #include "ctdl_module.h"
96 * When we do network processing, it's accomplished in two passes; one to
97 * gather a list of rooms and one to actually do them. It's ok that rplist
98 * is global; we have a mutex that keeps it safe.
100 struct RoomProcList *rplist = NULL;
103 * We build a map of network nodes during processing.
105 NetMap *the_netmap = NULL;
106 int netmap_changed = 0;
107 char *working_ignetcfg = NULL;
110 * Load or refresh the Citadel network (IGnet) configuration for this node.
112 void load_working_ignetcfg(void) {
116 cfg = CtdlGetSysConfig(IGNETCFG);
121 oldcfg = working_ignetcfg;
122 working_ignetcfg = cfg;
123 if (oldcfg != NULL) {
133 * Keep track of what messages to reject
135 FilterList *load_filter_list(void) {
136 char *serialized_list = NULL;
139 FilterList *newlist = NULL;
142 serialized_list = CtdlGetSysConfig(FILTERLIST);
143 if (serialized_list == NULL) return(NULL); /* if null, no entries */
145 /* Use the string tokenizer to grab one line at a time */
146 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
147 extract_token(buf, serialized_list, i, '\n', sizeof buf);
148 nptr = (FilterList *) malloc(sizeof(FilterList));
149 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
150 striplt(nptr->fl_user);
151 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
152 striplt(nptr->fl_room);
153 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
154 striplt(nptr->fl_node);
156 /* Cowardly refuse to add an any/any/any entry that would
157 * end up filtering every single message.
159 if (IsEmptyStr(nptr->fl_user) &&
160 IsEmptyStr(nptr->fl_room) &&
161 IsEmptyStr(nptr->fl_node)) {
165 nptr->next = newlist;
170 free(serialized_list);
175 void free_filter_list(FilterList *fl) {
176 if (fl == NULL) return;
177 free_filter_list(fl->next);
184 * Check the use table. This is a list of messages which have recently
185 * arrived on the system. It is maintained and queried to prevent the same
186 * message from being entered into the database multiple times if it happens
187 * to arrive multiple times by accident.
189 int network_usetable(struct CtdlMessage *msg) {
192 struct cdbdata *cdbut;
195 /* Bail out if we can't generate a message ID */
199 if (msg->cm_fields['I'] == NULL) {
202 if (IsEmptyStr(msg->cm_fields['I'])) {
206 /* Generate the message ID */
207 strcpy(msgid, msg->cm_fields['I']);
208 if (haschar(msgid, '@') == 0) {
210 if (msg->cm_fields['N'] != NULL) {
211 strcat(msgid, msg->cm_fields['N']);
218 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
221 syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
225 /* If we got to this point, it's unique: add it. */
226 strcpy(ut.ut_msgid, msgid);
227 ut.ut_timestamp = time(NULL);
228 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
234 * Read the network map from its configuration file into memory.
236 void read_network_map(void) {
237 char *serialized_map = NULL;
242 serialized_map = CtdlGetSysConfig(IGNETMAP);
243 if (serialized_map == NULL) return; /* if null, no entries */
245 /* Use the string tokenizer to grab one line at a time */
246 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
247 extract_token(buf, serialized_map, i, '\n', sizeof buf);
248 nmptr = (NetMap *) malloc(sizeof(NetMap));
249 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
250 nmptr->lastcontact = extract_long(buf, 1);
251 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
252 nmptr->next = the_netmap;
256 free(serialized_map);
262 * Write the network map from memory back to the configuration file.
264 void write_network_map(void) {
265 char *serialized_map = NULL;
269 if (netmap_changed) {
270 serialized_map = strdup("");
272 if (the_netmap != NULL) {
273 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
274 serialized_map = realloc(serialized_map,
275 (strlen(serialized_map)+SIZ) );
276 if (!IsEmptyStr(nmptr->nodename)) {
277 snprintf(&serialized_map[strlen(serialized_map)],
281 (long)nmptr->lastcontact,
287 CtdlPutSysConfig(IGNETMAP, serialized_map);
288 free(serialized_map);
291 /* Now free the list */
292 while (the_netmap != NULL) {
293 nmptr = the_netmap->next;
303 * Check the network map and determine whether the supplied node name is
304 * valid. If it is not a neighbor node, supply the name of a neighbor node
305 * which is the next hop. If it *is* a neighbor node, we also fill in the
308 int is_valid_node(char *nexthop, char *secret, char *node) {
320 * First try the neighbor nodes
322 if (working_ignetcfg == NULL) {
323 syslog(LOG_ERR, "working_ignetcfg is NULL!\n");
324 if (nexthop != NULL) {
331 if (nexthop != NULL) {
335 /* Use the string tokenizer to grab one line at a time */
336 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
337 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
338 extract_token(buf, linebuf, 0, '|', sizeof buf);
339 if (!strcasecmp(buf, node)) {
340 if (nexthop != NULL) {
343 if (secret != NULL) {
344 extract_token(secret, linebuf, 1, '|', 256);
351 return(retval); /* yup, it's a direct neighbor */
355 * If we get to this point we have to see if we know the next hop
357 if (the_netmap != NULL) {
358 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
359 if (!strcasecmp(nmptr->nodename, node)) {
360 if (nexthop != NULL) {
361 strcpy(nexthop, nmptr->nexthop);
369 * If we get to this point, the supplied node name is bogus.
371 syslog(LOG_ERR, "Invalid node name <%s>\n", node);
379 void cmd_gnet(char *argbuf) {
380 char filename[PATH_MAX];
384 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
385 /* users can edit the netconfigs for their own mailbox rooms */
387 else if (CtdlAccessCheck(ac_room_aide)) return;
389 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
390 cprintf("%d Network settings for room #%ld <%s>\n",
392 CC->room.QRnumber, CC->room.QRname);
394 fp = fopen(filename, "r");
396 while (fgets(buf, sizeof buf, fp) != NULL) {
397 buf[strlen(buf)-1] = 0;
398 cprintf("%s\n", buf);
407 void cmd_snet(char *argbuf) {
408 char tempfilename[PATH_MAX];
409 char filename[PATH_MAX];
418 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
419 /* users can edit the netconfigs for their own mailbox rooms */
421 else if (CtdlAccessCheck(ac_room_aide)) return;
423 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
424 memcpy(tempfilename, filename, len + 1);
426 memset(&StatBuf, 0, sizeof(struct stat));
427 if ((stat(filename, &StatBuf) == -1) || (StatBuf.st_size == 0))
428 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
430 sprintf(tempfilename + len, ".%d", CC->cs_pid);
432 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
434 if ((TmpFD > 0) && (errno == 0))
436 char *tmp = malloc(StatBuf.st_size * 2);
437 memset(tmp, ' ', StatBuf.st_size * 2);
438 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
440 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
443 cprintf("%d Unable to allocate the space required for %s: %s\n",
444 ERROR + INTERNAL_ERROR,
447 unlink(tempfilename);
450 lseek(TmpFD, SEEK_SET, 0);
453 cprintf("%d Unable to allocate the space required for %s: %s\n",
454 ERROR + INTERNAL_ERROR,
457 unlink(tempfilename);
462 cprintf("%d %s\n", SEND_LISTING, tempfilename);
465 while (rc = CtdlClientGetLine(Line),
468 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
470 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
471 write(TmpFD, ChrPtr(Line), StrLength(Line));
472 len += StrLength(Line);
475 ftruncate(TmpFD, len);
478 /* Now copy the temp file to its permanent location.
479 * (We copy instead of link because they may be on different filesystems)
481 begin_critical_section(S_NETCONFIGS);
482 rename(tempfilename, filename);
483 end_critical_section(S_NETCONFIGS);
488 * Deliver digest messages
490 void network_deliver_digest(SpoolControl *sc) {
493 struct CtdlMessage *msg = NULL;
496 size_t recps_len = SIZ;
498 struct recptypes *valid;
502 if (sc->num_msgs_spooled < 1) {
503 fclose(sc->digestfp);
508 msg = malloc(sizeof(struct CtdlMessage));
509 memset(msg, 0, sizeof(struct CtdlMessage));
510 msg->cm_magic = CTDLMESSAGE_MAGIC;
511 msg->cm_format_type = FMT_RFC822;
512 msg->cm_anon_type = MES_NORMAL;
514 sprintf(buf, "%ld", time(NULL));
515 msg->cm_fields['T'] = strdup(buf);
516 msg->cm_fields['A'] = strdup(CC->room.QRname);
517 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
518 msg->cm_fields['U'] = strdup(buf);
519 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
520 for (i=0; buf[i]; ++i) {
521 if (isspace(buf[i])) buf[i]='_';
522 buf[i] = tolower(buf[i]);
524 msg->cm_fields['F'] = strdup(buf);
525 msg->cm_fields['R'] = strdup(buf);
527 /* Set the 'List-ID' header */
528 msg->cm_fields['L'] = malloc(1024);
529 snprintf(msg->cm_fields['L'], 1024,
530 "%s <%ld.list-id.%s>",
537 * Go fetch the contents of the digest
539 fseek(sc->digestfp, 0L, SEEK_END);
540 msglen = ftell(sc->digestfp);
542 msg->cm_fields['M'] = malloc(msglen + 1);
543 fseek(sc->digestfp, 0L, SEEK_SET);
544 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
545 msg->cm_fields['M'][msglen] = '\0';
547 fclose(sc->digestfp);
550 /* Now generate the delivery instructions */
553 * Figure out how big a buffer we need to allocate
555 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
556 recps_len = recps_len + strlen(nptr->name) + 2;
559 recps = malloc(recps_len);
562 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
569 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
570 if (nptr != sc->digestrecps) {
573 strcat(recps, nptr->name);
576 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
577 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
579 /* Now submit the message */
580 valid = validate_recipients(recps, NULL, 0);
583 valid->bounce_to = strdup(bounce_to);
584 valid->envelope_from = strdup(bounce_to);
585 CtdlSubmitMsg(msg, valid, NULL, 0);
587 CtdlFreeMessage(msg);
588 free_recipients(valid);
593 * Deliver list messages to everyone on the list ... efficiently
595 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
597 size_t recps_len = SIZ;
598 struct recptypes *valid;
602 /* Don't do this if there were no recipients! */
603 if (sc->listrecps == NULL) return;
605 /* Now generate the delivery instructions */
608 * Figure out how big a buffer we need to allocate
610 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
611 recps_len = recps_len + strlen(nptr->name) + 2;
614 recps = malloc(recps_len);
617 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
624 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
625 if (nptr != sc->listrecps) {
628 strcat(recps, nptr->name);
631 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
632 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
634 /* Now submit the message */
635 valid = validate_recipients(recps, NULL, 0);
638 valid->bounce_to = strdup(bounce_to);
639 valid->envelope_from = strdup(bounce_to);
640 CtdlSubmitMsg(msg, valid, NULL, 0);
641 free_recipients(valid);
643 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
650 * Spools out one message from the list.
652 void network_spool_msg(long msgnum, void *userdata) {
655 char *newpath = NULL;
656 size_t instr_len = SIZ;
657 struct CtdlMessage *msg = NULL;
660 struct ser_ret sermsg;
662 char filename[PATH_MAX];
666 int delete_after_send = 0; /* Set to 1 to delete after spooling */
667 int ok_to_participate = 0;
668 struct recptypes *valid;
670 sc = (SpoolControl *)userdata;
673 * Process mailing list recipients
676 if (sc->listrecps != NULL) {
677 /* Fetch the message. We're going to need to modify it
678 * in order to insert the [list name] in it, etc.
680 msg = CtdlFetchMessage(msgnum, 1);
684 StrBuf *Subject, *FlatSubject;
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 Subject = NewStrBufPlain(HKEY("(no subject)"));
716 Subject = NewStrBufPlain(msg->cm_fields['U'], -1);
718 FlatSubject = NewStrBufPlain(NULL, StrLength(Subject));
719 StrBuf_RFC822_to_Utf8(FlatSubject, Subject, NULL, NULL);
721 rlen = strlen(CC->room.QRname);
722 pCh = strstr(ChrPtr(FlatSubject), CC->room.QRname);
724 (*(pCh + rlen) != ']') ||
725 (pCh == ChrPtr(FlatSubject)) ||
730 StrBufPlain(Subject, HKEY("["));
731 StrBufAppendBufPlain(Subject, CC->room.QRname, rlen, 0);
732 StrBufAppendBufPlain(Subject, HKEY("] "), 0);
733 StrBufAppendBuf(Subject, FlatSubject, 0);
734 tmp = Subject; Subject = FlatSubject; FlatSubject = tmp; /* so we can free the right one... */
735 StrBufRFC2047encode(&Subject, FlatSubject);
738 if (msg->cm_fields['U'] != NULL)
739 free (msg->cm_fields['U']);
740 msg->cm_fields['U'] = SmashStrBuf(&Subject);
742 FreeStrBuf(&FlatSubject);
744 /* else we won't modify the buffer, since the roomname is already here. */
746 /* Set the recipient of the list message to the
747 * email address of the room itself.
748 * FIXME ... I want to be able to pick any address
750 if (msg->cm_fields['R'] != NULL) {
751 free(msg->cm_fields['R']);
753 msg->cm_fields['R'] = malloc(256);
754 snprintf(msg->cm_fields['R'], 256,
755 "room_%s@%s", CC->room.QRname,
757 for (i=0; msg->cm_fields['R'][i]; ++i) {
758 if (isspace(msg->cm_fields['R'][i])) {
759 msg->cm_fields['R'][i] = '_';
763 /* Handle delivery */
764 network_deliver_list(msg, sc);
765 CtdlFreeMessage(msg);
770 * Process digest recipients
772 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
773 msg = CtdlFetchMessage(msgnum, 1);
775 fprintf(sc->digestfp, " -----------------------------------"
776 "------------------------------------"
778 fprintf(sc->digestfp, "From: ");
779 if (msg->cm_fields['A'] != NULL) {
780 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
782 if (msg->cm_fields['F'] != NULL) {
783 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
785 else if (msg->cm_fields['N'] != NULL) {
786 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
788 fprintf(sc->digestfp, "\n");
789 if (msg->cm_fields['U'] != NULL) {
790 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
793 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
795 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
796 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
798 StrBufTrim(CC->redirect_buffer);
799 fwrite(HKEY("\n"), 1, sc->digestfp);
800 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
801 fwrite(HKEY("\n"), 1, sc->digestfp);
803 FreeStrBuf(&CC->redirect_buffer);
805 sc->num_msgs_spooled += 1;
811 * Process client-side list participations for this room
814 if (sc->participates != NULL) {
815 msg = CtdlFetchMessage(msgnum, 1);
818 /* Only send messages which originated on our own Citadel
819 * network, otherwise we'll end up sending the remote
820 * mailing list's messages back to it, which is rude...
822 ok_to_participate = 0;
823 if (msg->cm_fields['N'] != NULL) {
824 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
825 ok_to_participate = 1;
827 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
828 ok_to_participate = 1;
831 if (ok_to_participate) {
832 if (msg->cm_fields['F'] != NULL) {
833 free(msg->cm_fields['F']);
835 msg->cm_fields['F'] = malloc(SIZ);
836 /* Replace the Internet email address of the actual
837 * author with the email address of the room itself,
838 * so the remote listserv doesn't reject us.
839 * FIXME ... I want to be able to pick any address
841 snprintf(msg->cm_fields['F'], SIZ,
842 "room_%s@%s", CC->room.QRname,
844 for (i=0; msg->cm_fields['F'][i]; ++i) {
845 if (isspace(msg->cm_fields['F'][i])) {
846 msg->cm_fields['F'][i] = '_';
851 * Figure out how big a buffer we need to allocate
853 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
855 if (msg->cm_fields['R'] == NULL) {
856 free(msg->cm_fields['R']);
858 msg->cm_fields['R'] = strdup(nptr->name);
860 valid = validate_recipients(nptr->name, NULL, 0);
861 CtdlSubmitMsg(msg, valid, "", 0);
862 free_recipients(valid);
866 CtdlFreeMessage(msg);
871 * Process IGnet push shares
873 msg = CtdlFetchMessage(msgnum, 1);
877 /* Prepend our node name to the Path field whenever
878 * sending a message to another IGnet node
880 if (msg->cm_fields['P'] == NULL) {
881 msg->cm_fields['P'] = strdup("username");
883 newpath_len = strlen(msg->cm_fields['P']) +
884 strlen(config.c_nodename) + 2;
885 newpath = malloc(newpath_len);
886 snprintf(newpath, newpath_len, "%s!%s",
887 config.c_nodename, msg->cm_fields['P']);
888 free(msg->cm_fields['P']);
889 msg->cm_fields['P'] = newpath;
892 * Determine if this message is set to be deleted
893 * after sending out on the network
895 if (msg->cm_fields['S'] != NULL) {
896 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
897 delete_after_send = 1;
901 /* Now send it to every node */
902 if (sc->ignet_push_shares != NULL)
903 for (mptr = sc->ignet_push_shares; mptr != NULL;
908 /* Check for valid node name */
909 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
910 syslog(LOG_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
914 /* Check for split horizon */
915 syslog(LOG_DEBUG, "Path is %s\n", msg->cm_fields['P']);
916 bang = num_tokens(msg->cm_fields['P'], '!');
917 if (bang > 1) for (i=0; i<(bang-1); ++i) {
918 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
919 syslog(LOG_DEBUG, "Compare <%s> to <%s>\n",
920 buf, mptr->remote_nodename) ;
921 if (!strcasecmp(buf, mptr->remote_nodename)) {
923 syslog(LOG_DEBUG, "Not sending to %s\n",
924 mptr->remote_nodename);
927 syslog(LOG_DEBUG, "Sending to %s\n", mptr->remote_nodename);
931 /* Send the message */
935 * Force the message to appear in the correct room
936 * on the far end by setting the C field correctly
938 if (msg->cm_fields['C'] != NULL) {
939 free(msg->cm_fields['C']);
941 if (!IsEmptyStr(mptr->remote_roomname)) {
942 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
945 msg->cm_fields['C'] = strdup(CC->room.QRname);
948 /* serialize it for transmission */
949 serialize_message(&sermsg, msg);
950 if (sermsg.len > 0) {
952 /* write it to a spool file */
953 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
955 mptr->remote_nodename,
959 syslog(LOG_DEBUG, "Appending to %s\n", filename);
960 fp = fopen(filename, "ab");
967 syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
970 /* free the serialized version */
976 CtdlFreeMessage(msg);
979 /* update lastsent */
980 sc->lastsent = msgnum;
982 /* Delete this message if delete-after-send is set */
983 if (delete_after_send) {
984 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
990 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
996 char roomname[ROOMNAMELEN];
999 int skipthisline = 0;
1000 namelist *nptr = NULL;
1001 maplist *mptr = NULL;
1004 fp = fopen(filename, "r");
1008 sc = malloc(sizeof(SpoolControl));
1009 memset(sc, 0, sizeof(SpoolControl));
1012 while (fgets(buf, sizeof buf, fp) != NULL) {
1013 buf[strlen(buf)-1] = 0;
1015 extract_token(instr, buf, 0, '|', sizeof instr);
1016 if (!strcasecmp(instr, strof(lastsent))) {
1017 sc->lastsent = extract_long(buf, 1);
1019 else if (!strcasecmp(instr, strof(listrecp))) {
1021 malloc(sizeof(namelist));
1022 nptr->next = sc->listrecps;
1023 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1024 sc->listrecps = nptr;
1026 else if (!strcasecmp(instr, strof(participate))) {
1028 malloc(sizeof(namelist));
1029 nptr->next = sc->participates;
1030 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1031 sc->participates = nptr;
1033 else if (!strcasecmp(instr, strof(digestrecp))) {
1035 malloc(sizeof(namelist));
1036 nptr->next = sc->digestrecps;
1037 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1038 sc->digestrecps = nptr;
1040 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1041 extract_token(nodename, buf, 1, '|', sizeof nodename);
1042 extract_token(roomname, buf, 2, '|', sizeof roomname);
1043 mptr = (maplist *) malloc(sizeof(maplist));
1044 mptr->next = sc->ignet_push_shares;
1045 strcpy(mptr->remote_nodename, nodename);
1046 strcpy(mptr->remote_roomname, roomname);
1047 sc->ignet_push_shares = mptr;
1050 /* Preserve 'other' lines ... *unless* they happen to
1051 * be subscribe/unsubscribe pendings with expired
1055 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1056 if (time(NULL) - extract_long(buf, 4) > EXP) {
1060 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1061 if (time(NULL) - extract_long(buf, 3) > EXP) {
1066 if (skipthisline == 0) {
1067 linesize = strlen(buf);
1068 sc->misc = realloc(sc->misc,
1069 (miscsize + linesize + 2) );
1070 sprintf(&sc->misc[miscsize], "%s\n", buf);
1071 miscsize = miscsize + linesize + 1;
1081 void free_spoolcontrol_struct(SpoolControl **scc)
1084 namelist *nptr = NULL;
1085 maplist *mptr = NULL;
1088 while (sc->listrecps != NULL) {
1089 nptr = sc->listrecps->next;
1090 free(sc->listrecps);
1091 sc->listrecps = nptr;
1093 /* Do the same for digestrecps */
1094 while (sc->digestrecps != NULL) {
1095 nptr = sc->digestrecps->next;
1096 free(sc->digestrecps);
1097 sc->digestrecps = nptr;
1099 /* Do the same for participates */
1100 while (sc->participates != NULL) {
1101 nptr = sc->participates->next;
1102 free(sc->participates);
1103 sc->participates = nptr;
1105 while (sc->ignet_push_shares != NULL) {
1106 mptr = sc->ignet_push_shares->next;
1107 free(sc->ignet_push_shares);
1108 sc->ignet_push_shares = mptr;
1115 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1117 char tempfilename[PATH_MAX];
1120 namelist *nptr = NULL;
1121 maplist *mptr = NULL;
1125 long reltid; /* if we don't have SYS_gettid, use "random" value */
1129 len = strlen(filename);
1130 memcpy(tempfilename, filename, len + 1);
1133 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1134 reltid = syscall(SYS_gettid);
1136 gettimeofday(&tv, NULL);
1137 /* Promote to time_t; types differ on some OSes (like darwin) */
1138 unixtime = tv.tv_sec;
1140 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1143 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1145 if ((TmpFD < 0) || (errno != 0)) {
1146 syslog(LOG_CRIT, "ERROR: cannot open %s: %s\n",
1147 filename, strerror(errno));
1148 free_spoolcontrol_struct(scc);
1149 unlink(tempfilename);
1152 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1154 /* Write out the listrecps while freeing from memory at the
1155 * same time. Am I clever or what? :)
1157 while (sc->listrecps != NULL) {
1158 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1159 nptr = sc->listrecps->next;
1160 free(sc->listrecps);
1161 sc->listrecps = nptr;
1163 /* Do the same for digestrecps */
1164 while (sc->digestrecps != NULL) {
1165 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1166 nptr = sc->digestrecps->next;
1167 free(sc->digestrecps);
1168 sc->digestrecps = nptr;
1170 /* Do the same for participates */
1171 while (sc->participates != NULL) {
1172 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1173 nptr = sc->participates->next;
1174 free(sc->participates);
1175 sc->participates = nptr;
1177 while (sc->ignet_push_shares != NULL) {
1178 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1179 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1180 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1182 StrBufAppendPrintf(Cfg, "\n");
1183 mptr = sc->ignet_push_shares->next;
1184 free(sc->ignet_push_shares);
1185 sc->ignet_push_shares = mptr;
1187 if (sc->misc != NULL) {
1188 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1192 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1193 if ((rc >=0 ) && (rc == StrLength(Cfg)))
1196 rename(tempfilename, filename);
1200 "unable to write %s; [%s]; not enough space on the disk?\n",
1204 unlink(tempfilename);
1212 int is_recipient(SpoolControl *sc, const char *Name)
1218 nptr = sc->listrecps;
1219 while (nptr != NULL) {
1220 if (strncmp(Name, nptr->name, len)==0)
1224 /* Do the same for digestrecps */
1225 nptr = sc->digestrecps;
1226 while (nptr != NULL) {
1227 if (strncmp(Name, nptr->name, len)==0)
1231 /* Do the same for participates */
1232 nptr = sc->participates;
1233 while (nptr != NULL) {
1234 if (strncmp(Name, nptr->name, len)==0)
1243 * Batch up and send all outbound traffic from the current room
1245 void network_spoolout_room(char *room_to_spool) {
1247 char filename[PATH_MAX];
1252 * If the room doesn't exist, don't try to perform its networking tasks.
1253 * Normally this should never happen, but once in a while maybe a room gets
1254 * queued for networking and then deleted before it can happen.
1256 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1257 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1261 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1262 begin_critical_section(S_NETCONFIGS);
1264 /* Only do net processing for rooms that have netconfigs */
1265 if (!read_spoolcontrol_file(&sc, filename))
1267 end_critical_section(S_NETCONFIGS);
1270 syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
1272 /* If there are digest recipients, we have to build a digest */
1273 if (sc->digestrecps != NULL) {
1274 sc->digestfp = tmpfile();
1275 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1278 /* Do something useful */
1279 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1280 network_spool_msg, sc);
1282 /* If we wrote a digest, deliver it and then close it */
1283 snprintf(buf, sizeof buf, "room_%s@%s",
1284 CC->room.QRname, config.c_fqdn);
1285 for (i=0; buf[i]; ++i) {
1286 buf[i] = tolower(buf[i]);
1287 if (isspace(buf[i])) buf[i] = '_';
1289 if (sc->digestfp != NULL) {
1290 fprintf(sc->digestfp, " -----------------------------------"
1291 "------------------------------------"
1293 "You are subscribed to the '%s' "
1295 "To post to the list: %s\n",
1296 CC->room.QRname, buf
1298 network_deliver_digest(sc); /* deliver and close */
1301 /* Now rewrite the config file */
1302 writenfree_spoolcontrol_file (&sc, filename);
1303 end_critical_section(S_NETCONFIGS);
1309 * Send the *entire* contents of the current room to one specific network node,
1310 * ignoring anything we know about which messages have already undergone
1311 * network processing. This can be used to bring a new node into sync.
1313 int network_sync_to(char *target_node) {
1315 int num_spooled = 0;
1321 char filename[PATH_MAX];
1324 /* Grab the configuration line we're looking for */
1325 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1326 begin_critical_section(S_NETCONFIGS);
1327 fp = fopen(filename, "r");
1329 end_critical_section(S_NETCONFIGS);
1332 while (fgets(buf, sizeof buf, fp) != NULL) {
1333 buf[strlen(buf)-1] = 0;
1334 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1335 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1336 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1337 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1338 && (!strcasecmp(sc_node, target_node)) ) {
1341 /* Concise syntax because we don't need a full linked-list */
1342 memset(&sc, 0, sizeof(SpoolControl));
1343 sc.ignet_push_shares = (maplist *)
1344 malloc(sizeof(maplist));
1345 sc.ignet_push_shares->next = NULL;
1346 safestrncpy(sc.ignet_push_shares->remote_nodename,
1348 sizeof sc.ignet_push_shares->remote_nodename);
1349 safestrncpy(sc.ignet_push_shares->remote_roomname,
1351 sizeof sc.ignet_push_shares->remote_roomname);
1355 end_critical_section(S_NETCONFIGS);
1357 if (!found_node) return(-1);
1359 /* Send ALL messages */
1360 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1361 network_spool_msg, &sc);
1363 /* Concise cleanup because we know there's only one node in the sc */
1364 free(sc.ignet_push_shares);
1366 syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
1367 num_spooled, target_node);
1368 return(num_spooled);
1373 * Implements the NSYN command
1375 void cmd_nsyn(char *argbuf) {
1377 char target_node[256];
1379 if (CtdlAccessCheck(ac_aide)) return;
1381 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1382 num_spooled = network_sync_to(target_node);
1383 if (num_spooled >= 0) {
1384 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1387 cprintf("%d No such room/node share exists.\n",
1388 ERROR + ROOM_NOT_FOUND);
1395 * Batch up and send all outbound traffic from the current room
1397 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1398 struct RoomProcList *ptr;
1400 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1401 if (ptr == NULL) return;
1403 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1404 begin_critical_section(S_RPLIST);
1407 end_critical_section(S_RPLIST);
1410 void destroy_network_queue_room(void)
1412 struct RoomProcList *cur, *p;
1413 NetMap *nmcur, *nmp;
1416 begin_critical_section(S_RPLIST);
1424 end_critical_section(S_RPLIST);
1427 while (nmcur != NULL)
1434 if (working_ignetcfg != NULL)
1435 free (working_ignetcfg);
1436 working_ignetcfg = NULL;
1441 * Learn topology from path fields
1443 void network_learn_topology(char *node, char *path) {
1447 strcpy(nexthop, "");
1449 if (num_tokens(path, '!') < 3) return;
1450 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1451 if (!strcasecmp(nmptr->nodename, node)) {
1452 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1453 nmptr->lastcontact = time(NULL);
1459 /* If we got here then it's not in the map, so add it. */
1460 nmptr = (NetMap *) malloc(sizeof (NetMap));
1461 strcpy(nmptr->nodename, node);
1462 nmptr->lastcontact = time(NULL);
1463 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1464 nmptr->next = the_netmap;
1473 * Bounce a message back to the sender
1475 void network_bounce(struct CtdlMessage *msg, char *reason) {
1476 char *oldpath = NULL;
1478 char bouncesource[SIZ];
1479 char recipient[SIZ];
1480 struct recptypes *valid = NULL;
1481 char force_room[ROOMNAMELEN];
1482 static int serialnum = 0;
1485 syslog(LOG_DEBUG, "entering network_bounce()\n");
1487 if (msg == NULL) return;
1489 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1492 * Give it a fresh message ID
1494 if (msg->cm_fields['I'] != NULL) {
1495 free(msg->cm_fields['I']);
1497 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1498 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1499 msg->cm_fields['I'] = strdup(buf);
1502 * FIXME ... right now we're just sending a bounce; we really want to
1503 * include the text of the bounced message.
1505 if (msg->cm_fields['M'] != NULL) {
1506 free(msg->cm_fields['M']);
1508 msg->cm_fields['M'] = strdup(reason);
1509 msg->cm_format_type = 0;
1512 * Turn the message around
1514 if (msg->cm_fields['R'] == NULL) {
1515 free(msg->cm_fields['R']);
1518 if (msg->cm_fields['D'] == NULL) {
1519 free(msg->cm_fields['D']);
1522 snprintf(recipient, sizeof recipient, "%s@%s",
1523 msg->cm_fields['A'], msg->cm_fields['N']);
1525 if (msg->cm_fields['A'] == NULL) {
1526 free(msg->cm_fields['A']);
1529 if (msg->cm_fields['N'] == NULL) {
1530 free(msg->cm_fields['N']);
1533 if (msg->cm_fields['U'] == NULL) {
1534 free(msg->cm_fields['U']);
1537 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1538 msg->cm_fields['N'] = strdup(config.c_nodename);
1539 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1541 /* prepend our node to the path */
1542 if (msg->cm_fields['P'] != NULL) {
1543 oldpath = msg->cm_fields['P'];
1544 msg->cm_fields['P'] = NULL;
1547 oldpath = strdup("unknown_user");
1549 size = strlen(oldpath) + SIZ;
1550 msg->cm_fields['P'] = malloc(size);
1551 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1554 /* Now submit the message */
1555 valid = validate_recipients(recipient, NULL, 0);
1556 if (valid != NULL) if (valid->num_error != 0) {
1557 free_recipients(valid);
1560 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1561 strcpy(force_room, config.c_aideroom);
1564 strcpy(force_room, "");
1566 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1567 strcpy(force_room, config.c_aideroom);
1569 CtdlSubmitMsg(msg, valid, force_room, 0);
1572 if (valid != NULL) free_recipients(valid);
1573 CtdlFreeMessage(msg);
1574 syslog(LOG_DEBUG, "leaving network_bounce()\n");
1581 * Process a buffer containing a single message from a single file
1582 * from the inbound queue
1584 void network_process_buffer(char *buffer, long size) {
1585 struct CtdlMessage *msg = NULL;
1588 struct recptypes *recp = NULL;
1589 char target_room[ROOMNAMELEN];
1590 struct ser_ret sermsg;
1591 char *oldpath = NULL;
1592 char filename[PATH_MAX];
1595 unsigned char firstbyte;
1596 unsigned char lastbyte;
1598 syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1600 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1601 firstbyte = buffer[0];
1602 lastbyte = buffer[size-1];
1603 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1604 syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1605 size, firstbyte, lastbyte);
1609 /* Set default target room to trash */
1610 strcpy(target_room, TWITROOM);
1612 /* Load the message into memory */
1613 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1614 memset(msg, 0, sizeof(struct CtdlMessage));
1615 msg->cm_magic = CTDLMESSAGE_MAGIC;
1616 msg->cm_anon_type = buffer[1];
1617 msg->cm_format_type = buffer[2];
1619 for (pos = 3; pos < size; ++pos) {
1620 field = buffer[pos];
1621 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1622 pos = pos + strlen(&buffer[(int)pos]);
1625 /* Check for message routing */
1626 if (msg->cm_fields['D'] != NULL) {
1627 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1629 /* route the message */
1630 strcpy(nexthop, "");
1631 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1632 /* prepend our node to the path */
1633 if (msg->cm_fields['P'] != NULL) {
1634 oldpath = msg->cm_fields['P'];
1635 msg->cm_fields['P'] = NULL;
1638 oldpath = strdup("unknown_user");
1640 size = strlen(oldpath) + SIZ;
1641 msg->cm_fields['P'] = malloc(size);
1642 snprintf(msg->cm_fields['P'], size, "%s!%s",
1643 config.c_nodename, oldpath);
1646 /* serialize the message */
1647 serialize_message(&sermsg, msg);
1650 if (IsEmptyStr(nexthop)) {
1651 strcpy(nexthop, msg->cm_fields['D']);
1661 syslog(LOG_DEBUG, "Appending to %s\n", filename);
1662 fp = fopen(filename, "ab");
1664 fwrite(sermsg.ser, sermsg.len, 1, fp);
1668 syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
1671 CtdlFreeMessage(msg);
1675 else { /* invalid destination node name */
1678 "A message you sent could not be delivered due to an invalid destination node"
1679 " name. Please check the address and try sending the message again.\n");
1688 * Check to see if we already have a copy of this message, and
1689 * abort its processing if so. (We used to post a warning to Aide>
1690 * every time this happened, but the network is now so densely
1691 * connected that it's inevitable.)
1693 if (network_usetable(msg) != 0) {
1694 CtdlFreeMessage(msg);
1698 /* Learn network topology from the path */
1699 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1700 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1703 /* Is the sending node giving us a very persuasive suggestion about
1704 * which room this message should be saved in? If so, go with that.
1706 if (msg->cm_fields['C'] != NULL) {
1707 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1710 /* Otherwise, does it have a recipient? If so, validate it... */
1711 else if (msg->cm_fields['R'] != NULL) {
1712 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1713 if (recp != NULL) if (recp->num_error != 0) {
1715 "A message you sent could not be delivered due to an invalid address.\n"
1716 "Please check the address and try sending the message again.\n");
1718 free_recipients(recp);
1719 syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
1722 strcpy(target_room, ""); /* no target room if mail */
1725 /* Our last shot at finding a home for this message is to see if
1726 * it has the O field (Originating room) set.
1728 else if (msg->cm_fields['O'] != NULL) {
1729 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1732 /* Strip out fields that are only relevant during transit */
1733 if (msg->cm_fields['D'] != NULL) {
1734 free(msg->cm_fields['D']);
1735 msg->cm_fields['D'] = NULL;
1737 if (msg->cm_fields['C'] != NULL) {
1738 free(msg->cm_fields['C']);
1739 msg->cm_fields['C'] = NULL;
1742 /* save the message into a room */
1743 if (PerformNetprocHooks(msg, target_room) == 0) {
1744 msg->cm_flags = CM_SKIP_HOOKS;
1745 CtdlSubmitMsg(msg, recp, target_room, 0);
1747 CtdlFreeMessage(msg);
1748 free_recipients(recp);
1753 * Process a single message from a single file from the inbound queue
1755 void network_process_message(FILE *fp, long msgstart, long msgend) {
1760 hold_pos = ftell(fp);
1761 size = msgend - msgstart + 1;
1762 buffer = malloc(size);
1763 if (buffer != NULL) {
1764 fseek(fp, msgstart, SEEK_SET);
1765 if (fread(buffer, size, 1, fp) > 0) {
1766 network_process_buffer(buffer, size);
1771 fseek(fp, hold_pos, SEEK_SET);
1776 * Process a single file from the inbound queue
1778 void network_process_file(char *filename) {
1780 long msgstart = (-1L);
1781 long msgend = (-1L);
1786 fp = fopen(filename, "rb");
1788 syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1792 fseek(fp, 0L, SEEK_END);
1793 syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1796 /* Look for messages in the data stream and break them out */
1797 while (ch = getc(fp), ch >= 0) {
1800 if (msgstart >= 0L) {
1801 msgend = msgcur - 1;
1802 network_process_message(fp, msgstart, msgend);
1810 msgend = msgcur - 1;
1811 if (msgstart >= 0L) {
1812 network_process_message(fp, msgstart, msgend);
1821 * Process anything in the inbound queue
1823 void network_do_spoolin(void) {
1826 struct stat statbuf;
1827 char filename[PATH_MAX];
1828 static time_t last_spoolin_mtime = 0L;
1831 * Check the spoolin directory's modification time. If it hasn't
1832 * been touched, we don't need to scan it.
1834 if (stat(ctdl_netin_dir, &statbuf)) return;
1835 if (statbuf.st_mtime == last_spoolin_mtime) {
1836 syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
1839 last_spoolin_mtime = statbuf.st_mtime;
1840 syslog(LOG_DEBUG, "network: processing inbound queue\n");
1843 * Ok, there's something interesting in there, so scan it.
1845 dp = opendir(ctdl_netin_dir);
1846 if (dp == NULL) return;
1848 while (d = readdir(dp), d != NULL) {
1849 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1856 network_process_file(filename);
1864 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1865 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1867 void network_consolidate_spoolout(void) {
1870 char filename[PATH_MAX];
1876 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1877 dp = opendir(ctdl_netout_dir);
1878 if (dp == NULL) return;
1879 while (d = readdir(dp), d != NULL) {
1881 (strcmp(d->d_name, "."))
1882 && (strcmp(d->d_name, ".."))
1883 && (strchr(d->d_name, '@') != NULL)
1885 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1886 ptr = strchr(nexthop, '@');
1896 syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1897 if (network_talking_to(nexthop, NTT_CHECK)) {
1899 "Currently online with %s - skipping for now\n",
1904 network_talking_to(nexthop, NTT_ADD);
1905 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1907 ctdl_netout_dir, nexthop,
1911 network_talking_to(nexthop, NTT_REMOVE);
1917 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1919 dp = opendir(ctdl_netout_dir);
1920 if (dp == NULL) return;
1922 while (d = readdir(dp), d != NULL) {
1923 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1925 ptr = strchr(d->d_name, '@');
1935 strcpy(nexthop, "");
1936 i = is_valid_node(nexthop, NULL, d->d_name);
1938 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1949 * receive network spool from the remote system
1951 void receive_spool(int *sock, char *remote_nodename) {
1952 int download_len = 0L;
1953 int bytes_received = 0L;
1955 char tempfilename[PATH_MAX];
1956 char permfilename[PATH_MAX];
1960 snprintf(tempfilename,
1961 sizeof tempfilename,
1969 snprintf(permfilename,
1970 sizeof permfilename,
1978 if (sock_puts(sock, "NDOP") < 0) return;
1979 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1980 syslog(LOG_DEBUG, "<%s\n", buf);
1981 if (buf[0] != '2') {
1985 download_len = extract_long(&buf[4], 0);
1986 if (download_len <= 0) {
1990 bytes_received = 0L;
1991 fp = fopen(tempfilename, "w");
1993 syslog(LOG_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1997 syslog(LOG_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1998 while (bytes_received < download_len) {
2000 * If shutting down we can exit here and unlink the temp file.
2001 * this shouldn't loose us any messages.
2003 if (server_shutting_down)
2006 unlink(tempfilename);
2009 snprintf(buf, sizeof buf, "READ %d|%d",
2011 ((download_len - bytes_received > IGNET_PACKET_SIZE)
2012 ? IGNET_PACKET_SIZE : (download_len - bytes_received))
2015 if (sock_puts(sock, buf) < 0) {
2017 unlink(tempfilename);
2020 if (sock_getln(sock, buf, sizeof buf) < 0) {
2022 unlink(tempfilename);
2026 if (buf[0] == '6') {
2027 plen = extract_int(&buf[4], 0);
2028 StrBuf *pbuf = NewStrBuf();
2029 if (socket_read_blob(sock, pbuf, plen, CLIENT_TIMEOUT) != plen) {
2030 syslog(LOG_INFO, "Short read from peer; aborting.\n");
2032 unlink(tempfilename);
2036 fwrite(ChrPtr(pbuf), plen, 1, fp);
2037 bytes_received += plen;
2044 /* Last chance for shutdown exit */
2045 if (server_shutting_down)
2047 unlink(tempfilename);
2051 if (sock_puts(sock, "CLOS") < 0) {
2052 unlink(tempfilename);
2057 * From here on we must complete or messages will get lost
2059 if (sock_getln(sock, buf, sizeof buf) < 0) {
2060 unlink(tempfilename);
2064 syslog(LOG_DEBUG, "%s\n", buf);
2067 * Now move the temp file to its permanent location.
2069 if (link(tempfilename, permfilename) != 0) {
2070 syslog(LOG_ALERT, "Could not link %s to %s: %s\n",
2071 tempfilename, permfilename, strerror(errno)
2075 unlink(tempfilename);
2081 * transmit network spool to the remote system
2083 void transmit_spool(int *sock, char *remote_nodename)
2088 long bytes_to_write, thisblock, bytes_written;
2092 if (sock_puts(sock, "NUOP") < 0) return;
2093 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2094 syslog(LOG_DEBUG, "<%s\n", buf);
2095 if (buf[0] != '2') {
2099 snprintf(sfname, sizeof sfname,
2104 fd = open(sfname, O_RDONLY);
2106 if (errno != ENOENT) {
2107 syslog(LOG_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2112 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2113 bytes_to_write = plen;
2114 while (bytes_to_write > 0L) {
2115 /* Exit if shutting down */
2116 if (server_shutting_down)
2122 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2123 if (sock_puts(sock, buf) < 0) {
2127 if (sock_getln(sock, buf, sizeof buf) < 0) {
2131 thisblock = atol(&buf[4]);
2132 if (buf[0] == '7') {
2133 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2137 bytes_to_write -= thisblock;
2138 bytes_written += thisblock;
2148 /* Last chance for shutdown exit */
2149 if(server_shutting_down)
2152 if (sock_puts(sock, "UCLS 1") < 0) return;
2155 * From here on we must complete or messages will get lost
2157 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2158 syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2159 syslog(LOG_DEBUG, "<%s\n", buf);
2160 if (buf[0] == '2') {
2161 syslog(LOG_DEBUG, "Removing <%s>\n", sfname);
2169 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2171 void network_poll_node(char *node, char *secret, char *host, char *port) {
2175 char connected_to[SIZ];
2178 if (network_talking_to(node, NTT_CHECK)) return;
2179 network_talking_to(node, NTT_ADD);
2180 syslog(LOG_DEBUG, "network: polling <%s>\n", node);
2181 syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2183 sock = sock_connect(host, port);
2185 syslog(LOG_ERR, "Could not connect: %s\n", strerror(errno));
2186 network_talking_to(node, NTT_REMOVE);
2190 syslog(LOG_DEBUG, "Connected!\n");
2191 CCC->sReadBuf = NewStrBuf();
2192 CCC->sMigrateBuf = NewStrBuf();
2195 /* Read the server greeting */
2196 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2197 syslog(LOG_DEBUG, ">%s\n", buf);
2199 /* Check that the remote is who we think it is and warn the Aide if not */
2200 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2201 if (strcmp(connected_to, node))
2203 snprintf(err_buf, sizeof(err_buf),
2204 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2207 syslog(LOG_ERR, "%s\n", err_buf);
2208 CtdlAideMessage(err_buf, "Network error");
2211 /* We're talking to the correct node. Now identify ourselves. */
2212 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2213 syslog(LOG_DEBUG, "<%s\n", buf);
2214 if (sock_puts(&sock, buf) <0) goto bail;
2215 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2216 syslog(LOG_DEBUG, ">%s\n", buf);
2217 if (buf[0] != '2') {
2221 /* At this point we are authenticated. */
2222 if (!server_shutting_down)
2223 receive_spool(&sock, node);
2224 if (!server_shutting_down)
2225 transmit_spool(&sock, node);
2228 sock_puts(&sock, "QUIT");
2230 FreeStrBuf(&CCC->sReadBuf);
2231 FreeStrBuf(&CCC->sMigrateBuf);
2234 network_talking_to(node, NTT_REMOVE);
2240 * Poll other Citadel nodes and transfer inbound/outbound network data.
2241 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2242 * only nodes to which we have data to send.
2244 void network_poll_other_citadel_nodes(int full_poll) {
2252 char spoolfile[256];
2254 if (working_ignetcfg == NULL) {
2255 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2259 /* Use the string tokenizer to grab one line at a time */
2260 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2261 if(server_shutting_down)
2263 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2264 extract_token(node, linebuf, 0, '|', sizeof node);
2265 extract_token(secret, linebuf, 1, '|', sizeof secret);
2266 extract_token(host, linebuf, 2, '|', sizeof host);
2267 extract_token(port, linebuf, 3, '|', sizeof port);
2268 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2269 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2278 if (access(spoolfile, R_OK) == 0) {
2283 network_poll_node(node, secret, host, port);
2294 * It's ok if these directories already exist. Just fail silently.
2296 void create_spool_dirs(void) {
2297 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2298 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2299 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2300 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2301 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2302 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2303 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2304 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2305 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2306 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2307 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2308 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2309 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2310 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2311 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2312 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2320 * network_do_queue()
2322 * Run through the rooms doing various types of network stuff.
2324 void network_do_queue(void) {
2325 static int doing_queue = 0;
2326 static time_t last_run = 0L;
2327 struct RoomProcList *ptr;
2328 int full_processing = 1;
2331 * Run the full set of processing tasks no more frequently
2332 * than once every n seconds
2334 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2335 full_processing = 0;
2336 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
2337 config.c_net_freq - (time(NULL)- last_run)
2342 * This is a simple concurrency check to make sure only one queue run
2343 * is done at a time. We could do this with a mutex, but since we
2344 * don't really require extremely fine granularity here, we'll do it
2345 * with a static variable instead.
2352 /* Load the IGnet Configuration into memory */
2353 load_working_ignetcfg();
2356 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2357 * then we poll everyone. Otherwise we only poll nodes we have stuff
2360 network_poll_other_citadel_nodes(full_processing);
2363 * Load the network map and filter list into memory.
2366 filterlist = load_filter_list();
2369 * Go ahead and run the queue
2371 if (full_processing && !server_shutting_down) {
2372 syslog(LOG_DEBUG, "network: loading outbound queue\n");
2373 CtdlForEachRoom(network_queue_room, NULL);
2376 if (rplist != NULL) {
2377 syslog(LOG_DEBUG, "network: running outbound queue\n");
2378 while (rplist != NULL && !server_shutting_down) {
2379 char spoolroomname[ROOMNAMELEN];
2380 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2381 begin_critical_section(S_RPLIST);
2383 /* pop this record off the list */
2385 rplist = rplist->next;
2388 /* invalidate any duplicate entries to prevent double processing */
2389 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2390 if (!strcasecmp(ptr->name, spoolroomname)) {
2395 end_critical_section(S_RPLIST);
2396 if (spoolroomname[0] != 0) {
2397 network_spoolout_room(spoolroomname);
2402 /* If there is anything in the inbound queue, process it */
2403 if (!server_shutting_down) {
2404 network_do_spoolin();
2407 /* Save the network map back to disk */
2408 write_network_map();
2410 /* Free the filter list in memory */
2411 free_filter_list(filterlist);
2414 network_consolidate_spoolout();
2416 syslog(LOG_DEBUG, "network: queue run completed\n");
2418 if (full_processing) {
2419 last_run = time(NULL);
2427 * cmd_netp() - authenticate to the server as another Citadel node polling
2428 * for network traffic
2430 void cmd_netp(char *cmdbuf)
2441 extract_token(node, cmdbuf, 0, '|', sizeof node);
2442 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2444 /* load the IGnet Configuration to check node validity */
2445 load_working_ignetcfg();
2446 v = is_valid_node(nexthop, secret, node);
2449 snprintf(err_buf, sizeof err_buf,
2450 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2451 node, CC->cs_host, CC->cs_addr
2453 syslog(LOG_WARNING, "%s", err_buf);
2454 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2455 CtdlAideMessage(err_buf, "IGNet Networking.");
2459 if (strcasecmp(pass, secret)) {
2460 snprintf(err_buf, sizeof err_buf,
2461 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2462 CC->cs_host, CC->cs_addr, node
2464 syslog(LOG_WARNING, "%s", err_buf);
2465 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2466 CtdlAideMessage(err_buf, "IGNet Networking.");
2470 if (network_talking_to(node, NTT_CHECK)) {
2471 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
2472 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2476 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2477 network_talking_to(node, NTT_ADD);
2478 syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2479 CC->net_node, CC->cs_host, CC->cs_addr
2481 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2485 int network_room_handler (struct ctdlroom *room)
2487 network_queue_room(room, NULL);
2493 * Module entry point
2495 CTDL_MODULE_INIT(network)
2499 create_spool_dirs();
2500 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2501 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2502 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2503 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2504 CtdlRegisterRoomHook(network_room_handler);
2505 CtdlRegisterCleanupHook(destroy_network_queue_room);
2506 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);