2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2010 by the citadel.org team
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
22 * This is a fairly high-level type of critical section. It ensures that no
23 * two threads work on the netconfigs files at the same time. Since we do
24 * so many things inside these, here are the rules:
25 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26 * 2. Do *not* perform any I/O with the client during these sections.
31 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32 * requests that have not been confirmed will be deleted.
34 #define EXP 259200 /* three days */
46 #include <sys/types.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
53 # include <sys/time.h>
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"
95 /* Nonzero while we are doing network processing */
96 static int doing_queue = 0;
99 * When we do network processing, it's accomplished in two passes; one to
100 * gather a list of rooms and one to actually do them. It's ok that rplist
101 * is global; we have a mutex that keeps it safe.
103 struct RoomProcList *rplist = NULL;
106 * We build a map of network nodes during processing.
108 NetMap *the_netmap = NULL;
109 int netmap_changed = 0;
110 char *working_ignetcfg = NULL;
113 * Load or refresh the Citadel network (IGnet) configuration for this node.
115 void load_working_ignetcfg(void) {
119 cfg = CtdlGetSysConfig(IGNETCFG);
124 oldcfg = working_ignetcfg;
125 working_ignetcfg = cfg;
126 if (oldcfg != NULL) {
136 * Keep track of what messages to reject
138 FilterList *load_filter_list(void) {
139 char *serialized_list = NULL;
142 FilterList *newlist = NULL;
145 serialized_list = CtdlGetSysConfig(FILTERLIST);
146 if (serialized_list == NULL) return(NULL); /* if null, no entries */
148 /* Use the string tokenizer to grab one line at a time */
149 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
150 extract_token(buf, serialized_list, i, '\n', sizeof buf);
151 nptr = (FilterList *) malloc(sizeof(FilterList));
152 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
153 striplt(nptr->fl_user);
154 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
155 striplt(nptr->fl_room);
156 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
157 striplt(nptr->fl_node);
159 /* Cowardly refuse to add an any/any/any entry that would
160 * end up filtering every single message.
162 if (IsEmptyStr(nptr->fl_user) &&
163 IsEmptyStr(nptr->fl_room) &&
164 IsEmptyStr(nptr->fl_node)) {
168 nptr->next = newlist;
173 free(serialized_list);
178 void free_filter_list(FilterList *fl) {
179 if (fl == NULL) return;
180 free_filter_list(fl->next);
187 * Check the use table. This is a list of messages which have recently
188 * arrived on the system. It is maintained and queried to prevent the same
189 * message from being entered into the database multiple times if it happens
190 * to arrive multiple times by accident.
192 int network_usetable(struct CtdlMessage *msg) {
195 struct cdbdata *cdbut;
198 /* Bail out if we can't generate a message ID */
202 if (msg->cm_fields['I'] == NULL) {
205 if (IsEmptyStr(msg->cm_fields['I'])) {
209 /* Generate the message ID */
210 strcpy(msgid, msg->cm_fields['I']);
211 if (haschar(msgid, '@') == 0) {
213 if (msg->cm_fields['N'] != NULL) {
214 strcat(msgid, msg->cm_fields['N']);
221 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
224 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
228 /* If we got to this point, it's unique: add it. */
229 strcpy(ut.ut_msgid, msgid);
230 ut.ut_timestamp = time(NULL);
231 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
237 * Read the network map from its configuration file into memory.
239 void read_network_map(void) {
240 char *serialized_map = NULL;
245 serialized_map = CtdlGetSysConfig(IGNETMAP);
246 if (serialized_map == NULL) return; /* if null, no entries */
248 /* Use the string tokenizer to grab one line at a time */
249 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
250 extract_token(buf, serialized_map, i, '\n', sizeof buf);
251 nmptr = (NetMap *) malloc(sizeof(NetMap));
252 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
253 nmptr->lastcontact = extract_long(buf, 1);
254 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
255 nmptr->next = the_netmap;
259 free(serialized_map);
265 * Write the network map from memory back to the configuration file.
267 void write_network_map(void) {
268 char *serialized_map = NULL;
272 if (netmap_changed) {
273 serialized_map = strdup("");
275 if (the_netmap != NULL) {
276 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
277 serialized_map = realloc(serialized_map,
278 (strlen(serialized_map)+SIZ) );
279 if (!IsEmptyStr(nmptr->nodename)) {
280 snprintf(&serialized_map[strlen(serialized_map)],
284 (long)nmptr->lastcontact,
290 CtdlPutSysConfig(IGNETMAP, serialized_map);
291 free(serialized_map);
294 /* Now free the list */
295 while (the_netmap != NULL) {
296 nmptr = the_netmap->next;
306 * Check the network map and determine whether the supplied node name is
307 * valid. If it is not a neighbor node, supply the name of a neighbor node
308 * which is the next hop. If it *is* a neighbor node, we also fill in the
311 int is_valid_node(char *nexthop, char *secret, char *node) {
323 * First try the neighbor nodes
325 if (working_ignetcfg == NULL) {
326 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
327 if (nexthop != NULL) {
334 if (nexthop != NULL) {
338 /* Use the string tokenizer to grab one line at a time */
339 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
340 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
341 extract_token(buf, linebuf, 0, '|', sizeof buf);
342 if (!strcasecmp(buf, node)) {
343 if (nexthop != NULL) {
346 if (secret != NULL) {
347 extract_token(secret, linebuf, 1, '|', 256);
354 return(retval); /* yup, it's a direct neighbor */
358 * If we get to this point we have to see if we know the next hop
360 if (the_netmap != NULL) {
361 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
362 if (!strcasecmp(nmptr->nodename, node)) {
363 if (nexthop != NULL) {
364 strcpy(nexthop, nmptr->nexthop);
372 * If we get to this point, the supplied node name is bogus.
374 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
382 void cmd_gnet(char *argbuf) {
383 char filename[PATH_MAX];
387 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
388 /* users can edit the netconfigs for their own mailbox rooms */
390 else if (CtdlAccessCheck(ac_room_aide)) return;
392 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
393 cprintf("%d Network settings for room #%ld <%s>\n",
395 CC->room.QRnumber, CC->room.QRname);
397 fp = fopen(filename, "r");
399 while (fgets(buf, sizeof buf, fp) != NULL) {
400 buf[strlen(buf)-1] = 0;
401 cprintf("%s\n", buf);
410 void cmd_snet(char *argbuf) {
411 char tempfilename[PATH_MAX];
412 char filename[PATH_MAX];
421 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
422 /* users can edit the netconfigs for their own mailbox rooms */
424 else if (CtdlAccessCheck(ac_room_aide)) return;
426 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
427 memcpy(tempfilename, filename, len + 1);
429 memset(&StatBuf, 0, sizeof(struct stat));
430 if ((stat(filename, &StatBuf) == -1) || (StatBuf.st_size == 0))
431 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
433 sprintf(tempfilename + len, ".%d", CC->cs_pid);
435 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
437 if ((TmpFD > 0) && (errno == 0))
439 char *tmp = malloc(StatBuf.st_size * 2);
440 memset(tmp, ' ', StatBuf.st_size * 2);
441 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
443 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
446 cprintf("%d Unable to allocate the space required for %s: %s\n",
447 ERROR + INTERNAL_ERROR,
450 unlink(tempfilename);
453 lseek(TmpFD, SEEK_SET, 0);
456 cprintf("%d Unable to allocate the space required for %s: %s\n",
457 ERROR + INTERNAL_ERROR,
460 unlink(tempfilename);
465 cprintf("%d %s\n", SEND_LISTING, tempfilename);
468 while (rc = CtdlClientGetLine(Line),
471 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
473 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
474 write(TmpFD, ChrPtr(Line), StrLength(Line));
475 len += StrLength(Line);
478 ftruncate(TmpFD, len);
481 /* Now copy the temp file to its permanent location.
482 * (We copy instead of link because they may be on different filesystems)
484 begin_critical_section(S_NETCONFIGS);
485 rename(tempfilename, filename);
486 end_critical_section(S_NETCONFIGS);
491 * Deliver digest messages
493 void network_deliver_digest(SpoolControl *sc) {
496 struct CtdlMessage *msg = NULL;
499 size_t recps_len = SIZ;
501 struct recptypes *valid;
505 if (sc->num_msgs_spooled < 1) {
506 fclose(sc->digestfp);
511 msg = malloc(sizeof(struct CtdlMessage));
512 memset(msg, 0, sizeof(struct CtdlMessage));
513 msg->cm_magic = CTDLMESSAGE_MAGIC;
514 msg->cm_format_type = FMT_RFC822;
515 msg->cm_anon_type = MES_NORMAL;
517 sprintf(buf, "%ld", time(NULL));
518 msg->cm_fields['T'] = strdup(buf);
519 msg->cm_fields['A'] = strdup(CC->room.QRname);
520 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
521 msg->cm_fields['U'] = strdup(buf);
522 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
523 for (i=0; buf[i]; ++i) {
524 if (isspace(buf[i])) buf[i]='_';
525 buf[i] = tolower(buf[i]);
527 msg->cm_fields['F'] = strdup(buf);
528 msg->cm_fields['R'] = strdup(buf);
530 /* Set the 'List-ID' header */
531 msg->cm_fields['L'] = malloc(1024);
532 snprintf(msg->cm_fields['L'], 1024,
533 "%s <%ld.list-id.%s>",
540 * Go fetch the contents of the digest
542 fseek(sc->digestfp, 0L, SEEK_END);
543 msglen = ftell(sc->digestfp);
545 msg->cm_fields['M'] = malloc(msglen + 1);
546 fseek(sc->digestfp, 0L, SEEK_SET);
547 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
548 msg->cm_fields['M'][msglen] = '\0';
550 fclose(sc->digestfp);
553 /* Now generate the delivery instructions */
556 * Figure out how big a buffer we need to allocate
558 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
559 recps_len = recps_len + strlen(nptr->name) + 2;
562 recps = malloc(recps_len);
565 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
572 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
573 if (nptr != sc->digestrecps) {
576 strcat(recps, nptr->name);
579 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
580 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
582 /* Now submit the message */
583 valid = validate_recipients(recps, NULL, 0);
586 valid->bounce_to = strdup(bounce_to);
587 valid->envelope_from = strdup(bounce_to);
588 CtdlSubmitMsg(msg, valid, NULL, 0);
590 CtdlFreeMessage(msg);
591 free_recipients(valid);
596 * Deliver list messages to everyone on the list ... efficiently
598 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
600 size_t recps_len = SIZ;
601 struct recptypes *valid;
605 /* Don't do this if there were no recipients! */
606 if (sc->listrecps == NULL) return;
608 /* Now generate the delivery instructions */
611 * Figure out how big a buffer we need to allocate
613 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
614 recps_len = recps_len + strlen(nptr->name) + 2;
617 recps = malloc(recps_len);
620 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
627 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
628 if (nptr != sc->listrecps) {
631 strcat(recps, nptr->name);
634 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
635 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
637 /* Now submit the message */
638 valid = validate_recipients(recps, NULL, 0);
641 valid->bounce_to = strdup(bounce_to);
642 valid->envelope_from = strdup(bounce_to);
643 CtdlSubmitMsg(msg, valid, NULL, 0);
644 free_recipients(valid);
646 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
653 * Spools out one message from the list.
655 void network_spool_msg(long msgnum, void *userdata) {
658 char *newpath = NULL;
659 size_t instr_len = SIZ;
660 struct CtdlMessage *msg = NULL;
663 struct ser_ret sermsg;
665 char filename[PATH_MAX];
669 int delete_after_send = 0; /* Set to 1 to delete after spooling */
670 int ok_to_participate = 0;
671 struct recptypes *valid;
673 sc = (SpoolControl *)userdata;
676 * Process mailing list recipients
679 if (sc->listrecps != NULL) {
680 /* Fetch the message. We're going to need to modify it
681 * in order to insert the [list name] in it, etc.
683 msg = CtdlFetchMessage(msgnum, 1);
688 if (msg->cm_fields['V'] == NULL){
689 /* local message, no enVelope */
692 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
693 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
694 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
696 msg->cm_fields['K'] = SmashStrBuf(&Buf);
699 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
701 /* Set the 'List-ID' header */
702 if (msg->cm_fields['L'] != NULL) {
703 free(msg->cm_fields['L']);
705 msg->cm_fields['L'] = malloc(1024);
706 snprintf(msg->cm_fields['L'], 1024,
707 "%s <%ld.list-id.%s>",
713 /* Prepend "[List name]" to the subject */
714 if (msg->cm_fields['U'] == NULL) {
715 msg->cm_fields['U'] = strdup("(no subject)");
718 len = strlen(msg->cm_fields['U']);
719 rlen = strlen(CC->room.QRname);
720 pCh = strstr(msg->cm_fields['U'], CC->room.QRname);
722 (*(pCh + rlen) != ']') ||
723 (pCh == msg->cm_fields['U']) ||
730 pBuff = malloc (rlen * sizeof(char));
732 snprintf(pBuff, rlen, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
733 free(msg->cm_fields['U']);
734 msg->cm_fields['U'] = pBuff;
736 /* else we won't modify the buffer, since the roomname is already here. */
738 /* if we don't already have a 'reply to' field, put our roomname in. */
739 if (msg->cm_fields['K'] == NULL) {
740 msg->cm_fields['K'] = malloc(256);
741 snprintf(msg->cm_fields['K'], 256,
742 "room_%s@%s", CC->room.QRname,
744 for (i=0; msg->cm_fields['K'][i]; ++i) {
745 if (isspace(msg->cm_fields['K'][i])) {
746 msg->cm_fields['K'][i] = '_';
751 /* Handle delivery */
752 network_deliver_list(msg, sc);
753 CtdlFreeMessage(msg);
758 * Process digest recipients
760 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
761 msg = CtdlFetchMessage(msgnum, 1);
763 fprintf(sc->digestfp, " -----------------------------------"
764 "------------------------------------"
766 fprintf(sc->digestfp, "From: ");
767 if (msg->cm_fields['A'] != NULL) {
768 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
770 if (msg->cm_fields['F'] != NULL) {
771 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
773 else if (msg->cm_fields['N'] != NULL) {
774 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
776 fprintf(sc->digestfp, "\n");
777 if (msg->cm_fields['U'] != NULL) {
778 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
781 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
783 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
784 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
786 StrBufTrim(CC->redirect_buffer);
787 fwrite(HKEY("\n"), 1, sc->digestfp);
788 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
789 fwrite(HKEY("\n"), 1, sc->digestfp);
791 FreeStrBuf(&CC->redirect_buffer);
793 sc->num_msgs_spooled += 1;
799 * Process client-side list participations for this room
802 if (sc->participates != NULL) {
803 msg = CtdlFetchMessage(msgnum, 1);
806 /* Only send messages which originated on our own Citadel
807 * network, otherwise we'll end up sending the remote
808 * mailing list's messages back to it, which is rude...
810 ok_to_participate = 0;
811 if (msg->cm_fields['N'] != NULL) {
812 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
813 ok_to_participate = 1;
815 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
816 ok_to_participate = 1;
819 if (ok_to_participate) {
820 if (msg->cm_fields['F'] != NULL) {
821 free(msg->cm_fields['F']);
823 msg->cm_fields['F'] = malloc(SIZ);
824 /* Replace the Internet email address of the actual
825 * author with the email address of the room itself,
826 * so the remote listserv doesn't reject us.
827 * FIXME ... I want to be able to pick any address
829 snprintf(msg->cm_fields['F'], SIZ,
830 "room_%s@%s", CC->room.QRname,
832 for (i=0; msg->cm_fields['F'][i]; ++i) {
833 if (isspace(msg->cm_fields['F'][i])) {
834 msg->cm_fields['F'][i] = '_';
839 * Figure out how big a buffer we need to allocate
841 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
843 if (msg->cm_fields['R'] == NULL) {
844 free(msg->cm_fields['R']);
846 msg->cm_fields['R'] = strdup(nptr->name);
848 valid = validate_recipients(nptr->name, NULL, 0);
849 CtdlSubmitMsg(msg, valid, "", 0);
850 free_recipients(valid);
854 CtdlFreeMessage(msg);
859 * Process IGnet push shares
861 msg = CtdlFetchMessage(msgnum, 1);
865 /* Prepend our node name to the Path field whenever
866 * sending a message to another IGnet node
868 if (msg->cm_fields['P'] == NULL) {
869 msg->cm_fields['P'] = strdup("username");
871 newpath_len = strlen(msg->cm_fields['P']) +
872 strlen(config.c_nodename) + 2;
873 newpath = malloc(newpath_len);
874 snprintf(newpath, newpath_len, "%s!%s",
875 config.c_nodename, msg->cm_fields['P']);
876 free(msg->cm_fields['P']);
877 msg->cm_fields['P'] = newpath;
880 * Determine if this message is set to be deleted
881 * after sending out on the network
883 if (msg->cm_fields['S'] != NULL) {
884 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
885 delete_after_send = 1;
889 /* Now send it to every node */
890 if (sc->ignet_push_shares != NULL)
891 for (mptr = sc->ignet_push_shares; mptr != NULL;
896 /* Check for valid node name */
897 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
898 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
902 /* Check for split horizon */
903 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
904 bang = num_tokens(msg->cm_fields['P'], '!');
905 if (bang > 1) for (i=0; i<(bang-1); ++i) {
906 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
907 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
908 buf, mptr->remote_nodename) ;
909 if (!strcasecmp(buf, mptr->remote_nodename)) {
911 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
912 mptr->remote_nodename);
915 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
919 /* Send the message */
923 * Force the message to appear in the correct room
924 * on the far end by setting the C field correctly
926 if (msg->cm_fields['C'] != NULL) {
927 free(msg->cm_fields['C']);
929 if (!IsEmptyStr(mptr->remote_roomname)) {
930 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
933 msg->cm_fields['C'] = strdup(CC->room.QRname);
936 /* serialize it for transmission */
937 serialize_message(&sermsg, msg);
938 if (sermsg.len > 0) {
940 /* write it to a spool file */
941 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
943 mptr->remote_nodename,
947 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
948 fp = fopen(filename, "ab");
955 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
958 /* free the serialized version */
964 CtdlFreeMessage(msg);
967 /* update lastsent */
968 sc->lastsent = msgnum;
970 /* Delete this message if delete-after-send is set */
971 if (delete_after_send) {
972 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
978 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
984 char roomname[ROOMNAMELEN];
987 int skipthisline = 0;
988 namelist *nptr = NULL;
989 maplist *mptr = NULL;
992 fp = fopen(filename, "r");
996 sc = malloc(sizeof(SpoolControl));
997 memset(sc, 0, sizeof(SpoolControl));
1000 while (fgets(buf, sizeof buf, fp) != NULL) {
1001 buf[strlen(buf)-1] = 0;
1003 extract_token(instr, buf, 0, '|', sizeof instr);
1004 if (!strcasecmp(instr, strof(lastsent))) {
1005 sc->lastsent = extract_long(buf, 1);
1007 else if (!strcasecmp(instr, strof(listrecp))) {
1009 malloc(sizeof(namelist));
1010 nptr->next = sc->listrecps;
1011 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1012 sc->listrecps = nptr;
1014 else if (!strcasecmp(instr, strof(participate))) {
1016 malloc(sizeof(namelist));
1017 nptr->next = sc->participates;
1018 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1019 sc->participates = nptr;
1021 else if (!strcasecmp(instr, strof(digestrecp))) {
1023 malloc(sizeof(namelist));
1024 nptr->next = sc->digestrecps;
1025 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1026 sc->digestrecps = nptr;
1028 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1029 extract_token(nodename, buf, 1, '|', sizeof nodename);
1030 extract_token(roomname, buf, 2, '|', sizeof roomname);
1031 mptr = (maplist *) malloc(sizeof(maplist));
1032 mptr->next = sc->ignet_push_shares;
1033 strcpy(mptr->remote_nodename, nodename);
1034 strcpy(mptr->remote_roomname, roomname);
1035 sc->ignet_push_shares = mptr;
1038 /* Preserve 'other' lines ... *unless* they happen to
1039 * be subscribe/unsubscribe pendings with expired
1043 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1044 if (time(NULL) - extract_long(buf, 4) > EXP) {
1048 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1049 if (time(NULL) - extract_long(buf, 3) > EXP) {
1054 if (skipthisline == 0) {
1055 linesize = strlen(buf);
1056 sc->misc = realloc(sc->misc,
1057 (miscsize + linesize + 2) );
1058 sprintf(&sc->misc[miscsize], "%s\n", buf);
1059 miscsize = miscsize + linesize + 1;
1069 void free_spoolcontrol_struct(SpoolControl **scc)
1072 namelist *nptr = NULL;
1073 maplist *mptr = NULL;
1076 while (sc->listrecps != NULL) {
1077 nptr = sc->listrecps->next;
1078 free(sc->listrecps);
1079 sc->listrecps = nptr;
1081 /* Do the same for digestrecps */
1082 while (sc->digestrecps != NULL) {
1083 nptr = sc->digestrecps->next;
1084 free(sc->digestrecps);
1085 sc->digestrecps = nptr;
1087 /* Do the same for participates */
1088 while (sc->participates != NULL) {
1089 nptr = sc->participates->next;
1090 free(sc->participates);
1091 sc->participates = nptr;
1093 while (sc->ignet_push_shares != NULL) {
1094 mptr = sc->ignet_push_shares->next;
1095 free(sc->ignet_push_shares);
1096 sc->ignet_push_shares = mptr;
1103 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1105 char tempfilename[PATH_MAX];
1108 namelist *nptr = NULL;
1109 maplist *mptr = NULL;
1113 long reltid; /* if we don't have SYS_gettid, use "random" value */
1117 len = strlen(filename);
1118 memcpy(tempfilename, filename, len + 1);
1121 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1122 reltid = syscall(SYS_gettid);
1124 gettimeofday(&tv, NULL);
1125 /* Promote to time_t; types differ on some OSes (like darwin) */
1126 unixtime = tv.tv_sec;
1128 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1131 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1133 if ((TmpFD < 0) || (errno != 0)) {
1134 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1135 filename, strerror(errno));
1136 free_spoolcontrol_struct(scc);
1137 unlink(tempfilename);
1140 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1142 /* Write out the listrecps while freeing from memory at the
1143 * same time. Am I clever or what? :)
1145 while (sc->listrecps != NULL) {
1146 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1147 nptr = sc->listrecps->next;
1148 free(sc->listrecps);
1149 sc->listrecps = nptr;
1151 /* Do the same for digestrecps */
1152 while (sc->digestrecps != NULL) {
1153 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1154 nptr = sc->digestrecps->next;
1155 free(sc->digestrecps);
1156 sc->digestrecps = nptr;
1158 /* Do the same for participates */
1159 while (sc->participates != NULL) {
1160 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1161 nptr = sc->participates->next;
1162 free(sc->participates);
1163 sc->participates = nptr;
1165 while (sc->ignet_push_shares != NULL) {
1166 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1167 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1168 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1170 StrBufAppendPrintf(Cfg, "\n");
1171 mptr = sc->ignet_push_shares->next;
1172 free(sc->ignet_push_shares);
1173 sc->ignet_push_shares = mptr;
1175 if (sc->misc != NULL) {
1176 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1180 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1181 if ((rc >=0 ) && (rc == StrLength(Cfg)))
1184 rename(tempfilename, filename);
1187 CtdlLogPrintf(CTDL_EMERG,
1188 "unable to write %s; [%s]; not enough space on the disk?\n",
1192 unlink(tempfilename);
1200 int is_recipient(SpoolControl *sc, const char *Name)
1206 nptr = sc->listrecps;
1207 while (nptr != NULL) {
1208 if (strncmp(Name, nptr->name, len)==0)
1212 /* Do the same for digestrecps */
1213 nptr = sc->digestrecps;
1214 while (nptr != NULL) {
1215 if (strncmp(Name, nptr->name, len)==0)
1219 /* Do the same for participates */
1220 nptr = sc->participates;
1221 while (nptr != NULL) {
1222 if (strncmp(Name, nptr->name, len)==0)
1231 * Batch up and send all outbound traffic from the current room
1233 void network_spoolout_room(char *room_to_spool) {
1235 char filename[PATH_MAX];
1240 * If the room doesn't exist, don't try to perform its networking tasks.
1241 * Normally this should never happen, but once in a while maybe a room gets
1242 * queued for networking and then deleted before it can happen.
1244 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1245 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1249 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1250 begin_critical_section(S_NETCONFIGS);
1252 /* Only do net processing for rooms that have netconfigs */
1253 if (!read_spoolcontrol_file(&sc, filename))
1255 end_critical_section(S_NETCONFIGS);
1258 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1260 /* If there are digest recipients, we have to build a digest */
1261 if (sc->digestrecps != NULL) {
1262 sc->digestfp = tmpfile();
1263 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1266 /* Do something useful */
1267 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1268 network_spool_msg, sc);
1270 /* If we wrote a digest, deliver it and then close it */
1271 snprintf(buf, sizeof buf, "room_%s@%s",
1272 CC->room.QRname, config.c_fqdn);
1273 for (i=0; buf[i]; ++i) {
1274 buf[i] = tolower(buf[i]);
1275 if (isspace(buf[i])) buf[i] = '_';
1277 if (sc->digestfp != NULL) {
1278 fprintf(sc->digestfp, " -----------------------------------"
1279 "------------------------------------"
1281 "You are subscribed to the '%s' "
1283 "To post to the list: %s\n",
1284 CC->room.QRname, buf
1286 network_deliver_digest(sc); /* deliver and close */
1289 /* Now rewrite the config file */
1290 writenfree_spoolcontrol_file (&sc, filename);
1291 end_critical_section(S_NETCONFIGS);
1297 * Send the *entire* contents of the current room to one specific network node,
1298 * ignoring anything we know about which messages have already undergone
1299 * network processing. This can be used to bring a new node into sync.
1301 int network_sync_to(char *target_node) {
1303 int num_spooled = 0;
1309 char filename[PATH_MAX];
1312 /* Grab the configuration line we're looking for */
1313 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1314 begin_critical_section(S_NETCONFIGS);
1315 fp = fopen(filename, "r");
1317 end_critical_section(S_NETCONFIGS);
1320 while (fgets(buf, sizeof buf, fp) != NULL) {
1321 buf[strlen(buf)-1] = 0;
1322 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1323 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1324 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1325 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1326 && (!strcasecmp(sc_node, target_node)) ) {
1329 /* Concise syntax because we don't need a full linked-list */
1330 memset(&sc, 0, sizeof(SpoolControl));
1331 sc.ignet_push_shares = (maplist *)
1332 malloc(sizeof(maplist));
1333 sc.ignet_push_shares->next = NULL;
1334 safestrncpy(sc.ignet_push_shares->remote_nodename,
1336 sizeof sc.ignet_push_shares->remote_nodename);
1337 safestrncpy(sc.ignet_push_shares->remote_roomname,
1339 sizeof sc.ignet_push_shares->remote_roomname);
1343 end_critical_section(S_NETCONFIGS);
1345 if (!found_node) return(-1);
1347 /* Send ALL messages */
1348 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1349 network_spool_msg, &sc);
1351 /* Concise cleanup because we know there's only one node in the sc */
1352 free(sc.ignet_push_shares);
1354 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1355 num_spooled, target_node);
1356 return(num_spooled);
1361 * Implements the NSYN command
1363 void cmd_nsyn(char *argbuf) {
1365 char target_node[256];
1367 if (CtdlAccessCheck(ac_aide)) return;
1369 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1370 num_spooled = network_sync_to(target_node);
1371 if (num_spooled >= 0) {
1372 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1375 cprintf("%d No such room/node share exists.\n",
1376 ERROR + ROOM_NOT_FOUND);
1383 * Batch up and send all outbound traffic from the current room
1385 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1386 struct RoomProcList *ptr;
1388 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1389 if (ptr == NULL) return;
1391 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1392 begin_critical_section(S_RPLIST);
1395 end_critical_section(S_RPLIST);
1398 void destroy_network_queue_room(void)
1400 struct RoomProcList *cur, *p;
1401 NetMap *nmcur, *nmp;
1404 begin_critical_section(S_RPLIST);
1412 end_critical_section(S_RPLIST);
1415 while (nmcur != NULL)
1422 if (working_ignetcfg != NULL)
1423 free (working_ignetcfg);
1424 working_ignetcfg = NULL;
1429 * Learn topology from path fields
1431 void network_learn_topology(char *node, char *path) {
1435 strcpy(nexthop, "");
1437 if (num_tokens(path, '!') < 3) return;
1438 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1439 if (!strcasecmp(nmptr->nodename, node)) {
1440 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1441 nmptr->lastcontact = time(NULL);
1447 /* If we got here then it's not in the map, so add it. */
1448 nmptr = (NetMap *) malloc(sizeof (NetMap));
1449 strcpy(nmptr->nodename, node);
1450 nmptr->lastcontact = time(NULL);
1451 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1452 nmptr->next = the_netmap;
1461 * Bounce a message back to the sender
1463 void network_bounce(struct CtdlMessage *msg, char *reason) {
1464 char *oldpath = NULL;
1466 char bouncesource[SIZ];
1467 char recipient[SIZ];
1468 struct recptypes *valid = NULL;
1469 char force_room[ROOMNAMELEN];
1470 static int serialnum = 0;
1473 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1475 if (msg == NULL) return;
1477 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1480 * Give it a fresh message ID
1482 if (msg->cm_fields['I'] != NULL) {
1483 free(msg->cm_fields['I']);
1485 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1486 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1487 msg->cm_fields['I'] = strdup(buf);
1490 * FIXME ... right now we're just sending a bounce; we really want to
1491 * include the text of the bounced message.
1493 if (msg->cm_fields['M'] != NULL) {
1494 free(msg->cm_fields['M']);
1496 msg->cm_fields['M'] = strdup(reason);
1497 msg->cm_format_type = 0;
1500 * Turn the message around
1502 if (msg->cm_fields['R'] == NULL) {
1503 free(msg->cm_fields['R']);
1506 if (msg->cm_fields['D'] == NULL) {
1507 free(msg->cm_fields['D']);
1510 snprintf(recipient, sizeof recipient, "%s@%s",
1511 msg->cm_fields['A'], msg->cm_fields['N']);
1513 if (msg->cm_fields['A'] == NULL) {
1514 free(msg->cm_fields['A']);
1517 if (msg->cm_fields['N'] == NULL) {
1518 free(msg->cm_fields['N']);
1521 if (msg->cm_fields['U'] == NULL) {
1522 free(msg->cm_fields['U']);
1525 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1526 msg->cm_fields['N'] = strdup(config.c_nodename);
1527 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1529 /* prepend our node to the path */
1530 if (msg->cm_fields['P'] != NULL) {
1531 oldpath = msg->cm_fields['P'];
1532 msg->cm_fields['P'] = NULL;
1535 oldpath = strdup("unknown_user");
1537 size = strlen(oldpath) + SIZ;
1538 msg->cm_fields['P'] = malloc(size);
1539 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1542 /* Now submit the message */
1543 valid = validate_recipients(recipient, NULL, 0);
1544 if (valid != NULL) if (valid->num_error != 0) {
1545 free_recipients(valid);
1548 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1549 strcpy(force_room, config.c_aideroom);
1552 strcpy(force_room, "");
1554 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1555 strcpy(force_room, config.c_aideroom);
1557 CtdlSubmitMsg(msg, valid, force_room, 0);
1560 if (valid != NULL) free_recipients(valid);
1561 CtdlFreeMessage(msg);
1562 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1569 * Process a buffer containing a single message from a single file
1570 * from the inbound queue
1572 void network_process_buffer(char *buffer, long size) {
1573 struct CtdlMessage *msg = NULL;
1576 struct recptypes *recp = NULL;
1577 char target_room[ROOMNAMELEN];
1578 struct ser_ret sermsg;
1579 char *oldpath = NULL;
1580 char filename[PATH_MAX];
1583 unsigned char firstbyte;
1584 unsigned char lastbyte;
1586 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1588 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1589 firstbyte = buffer[0];
1590 lastbyte = buffer[size-1];
1591 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1592 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1593 size, firstbyte, lastbyte);
1597 /* Set default target room to trash */
1598 strcpy(target_room, TWITROOM);
1600 /* Load the message into memory */
1601 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1602 memset(msg, 0, sizeof(struct CtdlMessage));
1603 msg->cm_magic = CTDLMESSAGE_MAGIC;
1604 msg->cm_anon_type = buffer[1];
1605 msg->cm_format_type = buffer[2];
1607 for (pos = 3; pos < size; ++pos) {
1608 field = buffer[pos];
1609 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1610 pos = pos + strlen(&buffer[(int)pos]);
1613 /* Check for message routing */
1614 if (msg->cm_fields['D'] != NULL) {
1615 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1617 /* route the message */
1618 strcpy(nexthop, "");
1619 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1620 /* prepend our node to the path */
1621 if (msg->cm_fields['P'] != NULL) {
1622 oldpath = msg->cm_fields['P'];
1623 msg->cm_fields['P'] = NULL;
1626 oldpath = strdup("unknown_user");
1628 size = strlen(oldpath) + SIZ;
1629 msg->cm_fields['P'] = malloc(size);
1630 snprintf(msg->cm_fields['P'], size, "%s!%s",
1631 config.c_nodename, oldpath);
1634 /* serialize the message */
1635 serialize_message(&sermsg, msg);
1638 if (IsEmptyStr(nexthop)) {
1639 strcpy(nexthop, msg->cm_fields['D']);
1649 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1650 fp = fopen(filename, "ab");
1652 fwrite(sermsg.ser, sermsg.len, 1, fp);
1656 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1659 CtdlFreeMessage(msg);
1663 else { /* invalid destination node name */
1666 "A message you sent could not be delivered due to an invalid destination node"
1667 " name. Please check the address and try sending the message again.\n");
1676 * Check to see if we already have a copy of this message, and
1677 * abort its processing if so. (We used to post a warning to Aide>
1678 * every time this happened, but the network is now so densely
1679 * connected that it's inevitable.)
1681 if (network_usetable(msg) != 0) {
1682 CtdlFreeMessage(msg);
1686 /* Learn network topology from the path */
1687 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1688 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1691 /* Is the sending node giving us a very persuasive suggestion about
1692 * which room this message should be saved in? If so, go with that.
1694 if (msg->cm_fields['C'] != NULL) {
1695 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1698 /* Otherwise, does it have a recipient? If so, validate it... */
1699 else if (msg->cm_fields['R'] != NULL) {
1700 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1701 if (recp != NULL) if (recp->num_error != 0) {
1703 "A message you sent could not be delivered due to an invalid address.\n"
1704 "Please check the address and try sending the message again.\n");
1706 free_recipients(recp);
1707 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1710 strcpy(target_room, ""); /* no target room if mail */
1713 /* Our last shot at finding a home for this message is to see if
1714 * it has the O field (Originating room) set.
1716 else if (msg->cm_fields['O'] != NULL) {
1717 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1720 /* Strip out fields that are only relevant during transit */
1721 if (msg->cm_fields['D'] != NULL) {
1722 free(msg->cm_fields['D']);
1723 msg->cm_fields['D'] = NULL;
1725 if (msg->cm_fields['C'] != NULL) {
1726 free(msg->cm_fields['C']);
1727 msg->cm_fields['C'] = NULL;
1730 /* save the message into a room */
1731 if (PerformNetprocHooks(msg, target_room) == 0) {
1732 msg->cm_flags = CM_SKIP_HOOKS;
1733 CtdlSubmitMsg(msg, recp, target_room, 0);
1735 CtdlFreeMessage(msg);
1736 free_recipients(recp);
1741 * Process a single message from a single file from the inbound queue
1743 void network_process_message(FILE *fp, long msgstart, long msgend) {
1748 hold_pos = ftell(fp);
1749 size = msgend - msgstart + 1;
1750 buffer = malloc(size);
1751 if (buffer != NULL) {
1752 fseek(fp, msgstart, SEEK_SET);
1753 if (fread(buffer, size, 1, fp) > 0) {
1754 network_process_buffer(buffer, size);
1759 fseek(fp, hold_pos, SEEK_SET);
1764 * Process a single file from the inbound queue
1766 void network_process_file(char *filename) {
1768 long msgstart = (-1L);
1769 long msgend = (-1L);
1774 fp = fopen(filename, "rb");
1776 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1780 fseek(fp, 0L, SEEK_END);
1781 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1784 /* Look for messages in the data stream and break them out */
1785 while (ch = getc(fp), ch >= 0) {
1788 if (msgstart >= 0L) {
1789 msgend = msgcur - 1;
1790 network_process_message(fp, msgstart, msgend);
1798 msgend = msgcur - 1;
1799 if (msgstart >= 0L) {
1800 network_process_message(fp, msgstart, msgend);
1809 * Process anything in the inbound queue
1811 void network_do_spoolin(void) {
1814 struct stat statbuf;
1815 char filename[PATH_MAX];
1816 static time_t last_spoolin_mtime = 0L;
1819 * Check the spoolin directory's modification time. If it hasn't
1820 * been touched, we don't need to scan it.
1822 if (stat(ctdl_netin_dir, &statbuf)) return;
1823 if (statbuf.st_mtime == last_spoolin_mtime) {
1824 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1827 last_spoolin_mtime = statbuf.st_mtime;
1828 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1831 * Ok, there's something interesting in there, so scan it.
1833 dp = opendir(ctdl_netin_dir);
1834 if (dp == NULL) return;
1836 while (d = readdir(dp), d != NULL) {
1837 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1844 network_process_file(filename);
1852 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1853 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1855 void network_consolidate_spoolout(void) {
1858 char filename[PATH_MAX];
1864 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1865 dp = opendir(ctdl_netout_dir);
1866 if (dp == NULL) return;
1867 while (d = readdir(dp), d != NULL) {
1869 (strcmp(d->d_name, "."))
1870 && (strcmp(d->d_name, ".."))
1871 && (strchr(d->d_name, '@') != NULL)
1873 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1874 ptr = strchr(nexthop, '@');
1884 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1885 if (network_talking_to(nexthop, NTT_CHECK)) {
1886 CtdlLogPrintf(CTDL_DEBUG,
1887 "Currently online with %s - skipping for now\n",
1892 network_talking_to(nexthop, NTT_ADD);
1893 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1895 ctdl_netout_dir, nexthop,
1899 network_talking_to(nexthop, NTT_REMOVE);
1905 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1907 dp = opendir(ctdl_netout_dir);
1908 if (dp == NULL) return;
1910 while (d = readdir(dp), d != NULL) {
1911 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1913 ptr = strchr(d->d_name, '@');
1923 strcpy(nexthop, "");
1924 i = is_valid_node(nexthop, NULL, d->d_name);
1926 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1937 * receive network spool from the remote system
1939 void receive_spool(int *sock, char *remote_nodename) {
1940 int download_len = 0L;
1941 int bytes_received = 0L;
1943 char tempfilename[PATH_MAX];
1944 char permfilename[PATH_MAX];
1948 snprintf(tempfilename,
1949 sizeof tempfilename,
1957 snprintf(permfilename,
1958 sizeof permfilename,
1966 if (sock_puts(sock, "NDOP") < 0) return;
1967 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1968 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1969 if (buf[0] != '2') {
1973 download_len = extract_long(&buf[4], 0);
1974 if (download_len <= 0) {
1978 bytes_received = 0L;
1979 fp = fopen(tempfilename, "w");
1981 CtdlLogPrintf(CTDL_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1985 CtdlLogPrintf(CTDL_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1986 while (bytes_received < download_len) {
1988 * If shutting down we can exit here and unlink the temp file.
1989 * this shouldn't loose us any messages.
1991 if (CtdlThreadCheckStop())
1994 unlink(tempfilename);
1997 snprintf(buf, sizeof buf, "READ %d|%d",
1999 ((download_len - bytes_received > IGNET_PACKET_SIZE)
2000 ? IGNET_PACKET_SIZE : (download_len - bytes_received))
2003 if (sock_puts(sock, buf) < 0) {
2005 unlink(tempfilename);
2008 if (sock_getln(sock, buf, sizeof buf) < 0) {
2010 unlink(tempfilename);
2014 if (buf[0] == '6') {
2015 plen = extract_int(&buf[4], 0);
2016 StrBuf *pbuf = NewStrBuf();
2017 if (socket_read_blob(sock, pbuf, plen, CLIENT_TIMEOUT) != plen) {
2018 CtdlLogPrintf(CTDL_INFO, "Short read from peer; aborting.\n");
2020 unlink(tempfilename);
2024 fwrite(ChrPtr(pbuf), plen, 1, fp);
2025 bytes_received += plen;
2032 /* Last chance for shutdown exit */
2033 if (CtdlThreadCheckStop())
2035 unlink(tempfilename);
2039 if (sock_puts(sock, "CLOS") < 0) {
2040 unlink(tempfilename);
2045 * From here on we must complete or messages will get lost
2047 if (sock_getln(sock, buf, sizeof buf) < 0) {
2048 unlink(tempfilename);
2052 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2055 * Now move the temp file to its permanent location.
2057 if (link(tempfilename, permfilename) != 0) {
2058 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2059 tempfilename, permfilename, strerror(errno)
2063 unlink(tempfilename);
2069 * transmit network spool to the remote system
2071 void transmit_spool(int *sock, char *remote_nodename)
2076 long bytes_to_write, thisblock, bytes_written;
2080 if (sock_puts(sock, "NUOP") < 0) return;
2081 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2082 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2083 if (buf[0] != '2') {
2087 snprintf(sfname, sizeof sfname,
2092 fd = open(sfname, O_RDONLY);
2094 if (errno != ENOENT) {
2095 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2100 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2101 bytes_to_write = plen;
2102 while (bytes_to_write > 0L) {
2103 /* Exit if shutting down */
2104 if (CtdlThreadCheckStop())
2110 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2111 if (sock_puts(sock, buf) < 0) {
2115 if (sock_getln(sock, buf, sizeof buf) < 0) {
2119 thisblock = atol(&buf[4]);
2120 if (buf[0] == '7') {
2121 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2125 bytes_to_write -= thisblock;
2126 bytes_written += thisblock;
2136 /* Last chance for shutdown exit */
2137 if(CtdlThreadCheckStop())
2140 if (sock_puts(sock, "UCLS 1") < 0) return;
2143 * From here on we must complete or messages will get lost
2145 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2146 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2147 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2148 if (buf[0] == '2') {
2149 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2157 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2159 void network_poll_node(char *node, char *secret, char *host, char *port) {
2163 char connected_to[SIZ];
2166 if (network_talking_to(node, NTT_CHECK)) return;
2167 network_talking_to(node, NTT_ADD);
2168 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2169 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2171 sock = sock_connect(host, port);
2173 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2174 network_talking_to(node, NTT_REMOVE);
2178 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2179 CCC->SBuf.Buf = NewStrBuf();
2180 CCC->sMigrateBuf = NewStrBuf();
2181 CCC->SBuf.ReadWritePointer = NULL;
2183 /* Read the server greeting */
2184 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2185 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2187 /* Check that the remote is who we think it is and warn the Aide if not */
2188 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2189 if (strcmp(connected_to, node))
2191 snprintf(err_buf, sizeof(err_buf),
2192 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2195 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2196 CtdlAideMessage(err_buf, "Network error");
2199 /* We're talking to the correct node. Now identify ourselves. */
2200 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2201 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2202 if (sock_puts(&sock, buf) <0) goto bail;
2203 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2204 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2205 if (buf[0] != '2') {
2209 /* At this point we are authenticated. */
2210 if (!CtdlThreadCheckStop())
2211 receive_spool(&sock, node);
2212 if (!CtdlThreadCheckStop())
2213 transmit_spool(&sock, node);
2216 sock_puts(&sock, "QUIT");
2218 FreeStrBuf(&CCC->SBuf.Buf);
2219 FreeStrBuf(&CCC->sMigrateBuf);
2222 network_talking_to(node, NTT_REMOVE);
2228 * Poll other Citadel nodes and transfer inbound/outbound network data.
2229 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2230 * only nodes to which we have data to send.
2232 void network_poll_other_citadel_nodes(int full_poll) {
2240 char spoolfile[256];
2242 if (working_ignetcfg == NULL) {
2243 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2247 /* Use the string tokenizer to grab one line at a time */
2248 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2249 if(CtdlThreadCheckStop())
2251 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2252 extract_token(node, linebuf, 0, '|', sizeof node);
2253 extract_token(secret, linebuf, 1, '|', sizeof secret);
2254 extract_token(host, linebuf, 2, '|', sizeof host);
2255 extract_token(port, linebuf, 3, '|', sizeof port);
2256 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2257 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2266 if (access(spoolfile, R_OK) == 0) {
2271 network_poll_node(node, secret, host, port);
2282 * It's ok if these directories already exist. Just fail silently.
2284 void create_spool_dirs(void) {
2285 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2286 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2287 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2288 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2289 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2290 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2291 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2292 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2293 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2294 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2295 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2296 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2297 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2298 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2299 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2300 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2308 * network_do_queue()
2310 * Run through the rooms doing various types of network stuff.
2312 void network_do_queue(void) {
2313 static time_t last_run = 0L;
2314 struct RoomProcList *ptr;
2315 int full_processing = 1;
2318 * Run the full set of processing tasks no more frequently
2319 * than once every n seconds
2321 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2322 full_processing = 0;
2323 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2324 config.c_net_freq - (time(NULL)- last_run)
2329 * This is a simple concurrency check to make sure only one queue run
2330 * is done at a time. We could do this with a mutex, but since we
2331 * don't really require extremely fine granularity here, we'll do it
2332 * with a static variable instead.
2339 /* Load the IGnet Configuration into memory */
2340 load_working_ignetcfg();
2343 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2344 * then we poll everyone. Otherwise we only poll nodes we have stuff
2347 network_poll_other_citadel_nodes(full_processing);
2350 * Load the network map and filter list into memory.
2353 filterlist = load_filter_list();
2356 * Go ahead and run the queue
2358 if (full_processing && !CtdlThreadCheckStop()) {
2359 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2360 CtdlForEachRoom(network_queue_room, NULL);
2363 if (rplist != NULL) {
2364 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2365 while (rplist != NULL && !CtdlThreadCheckStop()) {
2366 char spoolroomname[ROOMNAMELEN];
2367 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2368 begin_critical_section(S_RPLIST);
2370 /* pop this record off the list */
2372 rplist = rplist->next;
2375 /* invalidate any duplicate entries to prevent double processing */
2376 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2377 if (!strcasecmp(ptr->name, spoolroomname)) {
2382 end_critical_section(S_RPLIST);
2383 if (spoolroomname[0] != 0) {
2384 network_spoolout_room(spoolroomname);
2389 /* If there is anything in the inbound queue, process it */
2390 if (!CtdlThreadCheckStop()) {
2391 network_do_spoolin();
2394 /* Save the network map back to disk */
2395 write_network_map();
2397 /* Free the filter list in memory */
2398 free_filter_list(filterlist);
2401 network_consolidate_spoolout();
2403 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2405 if (full_processing) {
2406 last_run = time(NULL);
2414 * cmd_netp() - authenticate to the server as another Citadel node polling
2415 * for network traffic
2417 void cmd_netp(char *cmdbuf)
2428 extract_token(node, cmdbuf, 0, '|', sizeof node);
2429 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2431 /* load the IGnet Configuration to check node validity */
2432 load_working_ignetcfg();
2433 v = is_valid_node(nexthop, secret, node);
2436 snprintf(err_buf, sizeof err_buf,
2437 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2438 node, CC->cs_host, CC->cs_addr
2440 CtdlLogPrintf(CTDL_WARNING, err_buf);
2441 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2442 CtdlAideMessage(err_buf, "IGNet Networking.");
2446 if (strcasecmp(pass, secret)) {
2447 snprintf(err_buf, sizeof err_buf,
2448 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2449 CC->cs_host, CC->cs_addr, node
2451 CtdlLogPrintf(CTDL_WARNING, err_buf);
2452 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2453 CtdlAideMessage(err_buf, "IGNet Networking.");
2457 if (network_talking_to(node, NTT_CHECK)) {
2458 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2459 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2463 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2464 network_talking_to(node, NTT_ADD);
2465 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2466 CC->net_node, CC->cs_host, CC->cs_addr
2468 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2472 int network_room_handler (struct ctdlroom *room)
2474 network_queue_room(room, NULL);
2478 void *ignet_thread(void *arg) {
2479 struct CitContext ignet_thread_CC;
2481 CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2482 CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2483 citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2485 while (!CtdlThreadCheckStop()) {
2487 CtdlThreadSleep(60);
2490 CtdlClearSystemContext();
2498 * Module entry point
2500 CTDL_MODULE_INIT(network)
2504 create_spool_dirs();
2505 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2506 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2507 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2508 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2509 CtdlRegisterRoomHook(network_room_handler);
2510 CtdlRegisterCleanupHook(destroy_network_queue_room);
2511 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);