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)
431 StatBuf.st_size = 80; /* Not there? guess 80 chars line. */
433 sprintf(tempfilename + len, ".%d", CC->cs_pid);
435 TmpFD = open(tempfilename, O_CREAT|O_EXCL);
439 char *tmp = malloc(StatBuf.st_size * 2);
440 memset(tmp, 0, StatBuf.st_size * 2);
441 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
446 cprintf("%d Unable to allocate the space required for %s: %s\n",
447 ERROR + INTERNAL_ERROR,
452 lseek(TmpFD, SEEK_SET, 0);
455 cprintf("%d Unable to allocate the space required for %s: %s\n",
456 ERROR + INTERNAL_ERROR,
464 cprintf("%d %s\n", SEND_LISTING, tempfilename);
467 while (rc = CtdlClientGetLine(Line),
470 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
472 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
473 write(TmpFD, ChrPtr(Line), StrLength(Line));
474 len += StrLength(Line);
477 ftruncate(TmpFD, len + 1);
480 /* Now copy the temp file to its permanent location.
481 * (We copy instead of link because they may be on different filesystems)
483 begin_critical_section(S_NETCONFIGS);
484 rename(filename, tempfilename);
485 end_critical_section(S_NETCONFIGS);
490 * Deliver digest messages
492 void network_deliver_digest(SpoolControl *sc) {
495 struct CtdlMessage *msg = NULL;
498 size_t recps_len = SIZ;
500 struct recptypes *valid;
504 if (sc->num_msgs_spooled < 1) {
505 fclose(sc->digestfp);
510 msg = malloc(sizeof(struct CtdlMessage));
511 memset(msg, 0, sizeof(struct CtdlMessage));
512 msg->cm_magic = CTDLMESSAGE_MAGIC;
513 msg->cm_format_type = FMT_RFC822;
514 msg->cm_anon_type = MES_NORMAL;
516 sprintf(buf, "%ld", time(NULL));
517 msg->cm_fields['T'] = strdup(buf);
518 msg->cm_fields['A'] = strdup(CC->room.QRname);
519 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
520 msg->cm_fields['U'] = strdup(buf);
521 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
522 for (i=0; buf[i]; ++i) {
523 if (isspace(buf[i])) buf[i]='_';
524 buf[i] = tolower(buf[i]);
526 msg->cm_fields['F'] = strdup(buf);
527 msg->cm_fields['R'] = strdup(buf);
529 /* Set the 'List-ID' header */
530 msg->cm_fields['L'] = malloc(1024);
531 snprintf(msg->cm_fields['L'], 1024,
532 "%s <%ld.list-id.%s>",
539 * Go fetch the contents of the digest
541 fseek(sc->digestfp, 0L, SEEK_END);
542 msglen = ftell(sc->digestfp);
544 msg->cm_fields['M'] = malloc(msglen + 1);
545 fseek(sc->digestfp, 0L, SEEK_SET);
546 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
547 msg->cm_fields['M'][msglen] = '\0';
549 fclose(sc->digestfp);
552 /* Now generate the delivery instructions */
555 * Figure out how big a buffer we need to allocate
557 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
558 recps_len = recps_len + strlen(nptr->name) + 2;
561 recps = malloc(recps_len);
564 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
571 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
572 if (nptr != sc->digestrecps) {
575 strcat(recps, nptr->name);
578 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
579 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
581 /* Now submit the message */
582 valid = validate_recipients(recps, NULL, 0);
585 valid->bounce_to = strdup(bounce_to);
586 valid->envelope_from = strdup(bounce_to);
587 CtdlSubmitMsg(msg, valid, NULL, 0);
589 CtdlFreeMessage(msg);
590 free_recipients(valid);
595 * Deliver list messages to everyone on the list ... efficiently
597 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
599 size_t recps_len = SIZ;
600 struct recptypes *valid;
604 /* Don't do this if there were no recipients! */
605 if (sc->listrecps == NULL) return;
607 /* Now generate the delivery instructions */
610 * Figure out how big a buffer we need to allocate
612 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
613 recps_len = recps_len + strlen(nptr->name) + 2;
616 recps = malloc(recps_len);
619 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
626 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
627 if (nptr != sc->listrecps) {
630 strcat(recps, nptr->name);
633 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
634 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
636 /* Now submit the message */
637 valid = validate_recipients(recps, NULL, 0);
640 valid->bounce_to = strdup(bounce_to);
641 valid->envelope_from = strdup(bounce_to);
642 CtdlSubmitMsg(msg, valid, NULL, 0);
643 free_recipients(valid);
645 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
652 * Spools out one message from the list.
654 void network_spool_msg(long msgnum, void *userdata) {
657 char *newpath = NULL;
658 size_t instr_len = SIZ;
659 struct CtdlMessage *msg = NULL;
662 struct ser_ret sermsg;
664 char filename[PATH_MAX];
668 int delete_after_send = 0; /* Set to 1 to delete after spooling */
669 int ok_to_participate = 0;
670 struct recptypes *valid;
672 sc = (SpoolControl *)userdata;
675 * Process mailing list recipients
678 if (sc->listrecps != NULL) {
679 /* Fetch the message. We're going to need to modify it
680 * in order to insert the [list name] in it, etc.
682 msg = CtdlFetchMessage(msgnum, 1);
684 if (msg->cm_fields['V'] == NULL){
685 /* local message, no enVelope */
688 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
689 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
690 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
692 msg->cm_fields['K'] = SmashStrBuf(&Buf);
695 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
697 /* Set the 'List-ID' header */
698 if (msg->cm_fields['L'] != NULL) {
699 free(msg->cm_fields['L']);
701 msg->cm_fields['L'] = malloc(1024);
702 snprintf(msg->cm_fields['L'], 1024,
703 "%s <%ld.list-id.%s>",
709 /* Prepend "[List name]" to the subject */
710 if (msg->cm_fields['U'] == NULL) {
711 msg->cm_fields['U'] = strdup("(no subject)");
713 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
714 free(msg->cm_fields['U']);
715 msg->cm_fields['U'] = strdup(buf);
717 /* Set the recipient of the list message to the
718 * email address of the room itself.
719 * FIXME ... I want to be able to pick any address
721 if (msg->cm_fields['R'] != NULL) {
722 free(msg->cm_fields['R']);
724 msg->cm_fields['R'] = malloc(256);
725 snprintf(msg->cm_fields['R'], 256,
726 "room_%s@%s", CC->room.QRname,
728 for (i=0; msg->cm_fields['R'][i]; ++i) {
729 if (isspace(msg->cm_fields['R'][i])) {
730 msg->cm_fields['R'][i] = '_';
734 /* Handle delivery */
735 network_deliver_list(msg, sc);
736 CtdlFreeMessage(msg);
741 * Process digest recipients
743 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
744 msg = CtdlFetchMessage(msgnum, 1);
746 fprintf(sc->digestfp, " -----------------------------------"
747 "------------------------------------"
749 fprintf(sc->digestfp, "From: ");
750 if (msg->cm_fields['A'] != NULL) {
751 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
753 if (msg->cm_fields['F'] != NULL) {
754 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
756 else if (msg->cm_fields['N'] != NULL) {
757 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
759 fprintf(sc->digestfp, "\n");
760 if (msg->cm_fields['U'] != NULL) {
761 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
764 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
766 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
767 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
769 StrBufTrim(CC->redirect_buffer);
770 fwrite(HKEY("\n"), 1, sc->digestfp);
771 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
772 fwrite(HKEY("\n"), 1, sc->digestfp);
774 FreeStrBuf(&CC->redirect_buffer);
776 sc->num_msgs_spooled += 1;
782 * Process client-side list participations for this room
785 if (sc->participates != NULL) {
786 msg = CtdlFetchMessage(msgnum, 1);
789 /* Only send messages which originated on our own Citadel
790 * network, otherwise we'll end up sending the remote
791 * mailing list's messages back to it, which is rude...
793 ok_to_participate = 0;
794 if (msg->cm_fields['N'] != NULL) {
795 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
796 ok_to_participate = 1;
798 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
799 ok_to_participate = 1;
802 if (ok_to_participate) {
803 if (msg->cm_fields['F'] != NULL) {
804 free(msg->cm_fields['F']);
806 msg->cm_fields['F'] = malloc(SIZ);
807 /* Replace the Internet email address of the actual
808 * author with the email address of the room itself,
809 * so the remote listserv doesn't reject us.
810 * FIXME ... I want to be able to pick any address
812 snprintf(msg->cm_fields['F'], SIZ,
813 "room_%s@%s", CC->room.QRname,
815 for (i=0; msg->cm_fields['F'][i]; ++i) {
816 if (isspace(msg->cm_fields['F'][i])) {
817 msg->cm_fields['F'][i] = '_';
822 * Figure out how big a buffer we need to allocate
824 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
826 if (msg->cm_fields['R'] == NULL) {
827 free(msg->cm_fields['R']);
829 msg->cm_fields['R'] = strdup(nptr->name);
831 valid = validate_recipients(nptr->name, NULL, 0);
832 CtdlSubmitMsg(msg, valid, "", 0);
833 free_recipients(valid);
837 CtdlFreeMessage(msg);
842 * Process IGnet push shares
844 msg = CtdlFetchMessage(msgnum, 1);
848 /* Prepend our node name to the Path field whenever
849 * sending a message to another IGnet node
851 if (msg->cm_fields['P'] == NULL) {
852 msg->cm_fields['P'] = strdup("username");
854 newpath_len = strlen(msg->cm_fields['P']) +
855 strlen(config.c_nodename) + 2;
856 newpath = malloc(newpath_len);
857 snprintf(newpath, newpath_len, "%s!%s",
858 config.c_nodename, msg->cm_fields['P']);
859 free(msg->cm_fields['P']);
860 msg->cm_fields['P'] = newpath;
863 * Determine if this message is set to be deleted
864 * after sending out on the network
866 if (msg->cm_fields['S'] != NULL) {
867 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
868 delete_after_send = 1;
872 /* Now send it to every node */
873 if (sc->ignet_push_shares != NULL)
874 for (mptr = sc->ignet_push_shares; mptr != NULL;
879 /* Check for valid node name */
880 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
881 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
885 /* Check for split horizon */
886 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
887 bang = num_tokens(msg->cm_fields['P'], '!');
888 if (bang > 1) for (i=0; i<(bang-1); ++i) {
889 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
890 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
891 buf, mptr->remote_nodename) ;
892 if (!strcasecmp(buf, mptr->remote_nodename)) {
894 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
895 mptr->remote_nodename);
898 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
902 /* Send the message */
906 * Force the message to appear in the correct room
907 * on the far end by setting the C field correctly
909 if (msg->cm_fields['C'] != NULL) {
910 free(msg->cm_fields['C']);
912 if (!IsEmptyStr(mptr->remote_roomname)) {
913 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
916 msg->cm_fields['C'] = strdup(CC->room.QRname);
919 /* serialize it for transmission */
920 serialize_message(&sermsg, msg);
921 if (sermsg.len > 0) {
923 /* write it to a spool file */
924 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
926 mptr->remote_nodename,
930 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
931 fp = fopen(filename, "ab");
938 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
941 /* free the serialized version */
947 CtdlFreeMessage(msg);
950 /* update lastsent */
951 sc->lastsent = msgnum;
953 /* Delete this message if delete-after-send is set */
954 if (delete_after_send) {
955 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
961 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
967 char roomname[ROOMNAMELEN];
970 int skipthisline = 0;
971 namelist *nptr = NULL;
972 maplist *mptr = NULL;
975 fp = fopen(filename, "r");
979 sc = malloc(sizeof(SpoolControl));
980 memset(sc, 0, sizeof(SpoolControl));
983 while (fgets(buf, sizeof buf, fp) != NULL) {
984 buf[strlen(buf)-1] = 0;
986 extract_token(instr, buf, 0, '|', sizeof instr);
987 if (!strcasecmp(instr, strof(lastsent))) {
988 sc->lastsent = extract_long(buf, 1);
990 else if (!strcasecmp(instr, strof(listrecp))) {
992 malloc(sizeof(namelist));
993 nptr->next = sc->listrecps;
994 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
995 sc->listrecps = nptr;
997 else if (!strcasecmp(instr, strof(participate))) {
999 malloc(sizeof(namelist));
1000 nptr->next = sc->participates;
1001 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1002 sc->participates = nptr;
1004 else if (!strcasecmp(instr, strof(digestrecp))) {
1006 malloc(sizeof(namelist));
1007 nptr->next = sc->digestrecps;
1008 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1009 sc->digestrecps = nptr;
1011 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1012 extract_token(nodename, buf, 1, '|', sizeof nodename);
1013 extract_token(roomname, buf, 2, '|', sizeof roomname);
1014 mptr = (maplist *) malloc(sizeof(maplist));
1015 mptr->next = sc->ignet_push_shares;
1016 strcpy(mptr->remote_nodename, nodename);
1017 strcpy(mptr->remote_roomname, roomname);
1018 sc->ignet_push_shares = mptr;
1021 /* Preserve 'other' lines ... *unless* they happen to
1022 * be subscribe/unsubscribe pendings with expired
1026 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1027 if (time(NULL) - extract_long(buf, 4) > EXP) {
1031 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1032 if (time(NULL) - extract_long(buf, 3) > EXP) {
1037 if (skipthisline == 0) {
1038 linesize = strlen(buf);
1039 sc->misc = realloc(sc->misc,
1040 (miscsize + linesize + 2) );
1041 sprintf(&sc->misc[miscsize], "%s\n", buf);
1042 miscsize = miscsize + linesize + 1;
1052 void free_spoolcontrol_struct(SpoolControl **scc)
1055 namelist *nptr = NULL;
1056 maplist *mptr = NULL;
1059 while (sc->listrecps != NULL) {
1060 nptr = sc->listrecps->next;
1061 free(sc->listrecps);
1062 sc->listrecps = nptr;
1064 /* Do the same for digestrecps */
1065 while (sc->digestrecps != NULL) {
1066 nptr = sc->digestrecps->next;
1067 free(sc->digestrecps);
1068 sc->digestrecps = nptr;
1070 /* Do the same for participates */
1071 while (sc->participates != NULL) {
1072 nptr = sc->participates->next;
1073 free(sc->participates);
1074 sc->participates = nptr;
1076 while (sc->ignet_push_shares != NULL) {
1077 mptr = sc->ignet_push_shares->next;
1078 free(sc->ignet_push_shares);
1079 sc->ignet_push_shares = mptr;
1086 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1088 char tempfilename[PATH_MAX];
1091 namelist *nptr = NULL;
1092 maplist *mptr = NULL;
1096 long reltid; /* if we don't have SYS_gettid, use "random" value */
1100 len = strlen(filename);
1101 memcpy(tempfilename, filename, len + 1);
1104 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1105 reltid = syscall(SYS_gettid);
1107 gettimeofday(&tv, NULL);
1108 /* Promote to time_t; types differ on some OSes (like darwin) */
1109 unixtime = tv.tv_sec;
1111 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1113 fp = fopen(tempfilename, "w");
1116 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1117 filename, strerror(errno));
1118 free_spoolcontrol_struct(scc);
1121 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1123 /* Write out the listrecps while freeing from memory at the
1124 * same time. Am I clever or what? :)
1126 while (sc->listrecps != NULL) {
1127 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1128 nptr = sc->listrecps->next;
1129 free(sc->listrecps);
1130 sc->listrecps = nptr;
1132 /* Do the same for digestrecps */
1133 while (sc->digestrecps != NULL) {
1134 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1135 nptr = sc->digestrecps->next;
1136 free(sc->digestrecps);
1137 sc->digestrecps = nptr;
1139 /* Do the same for participates */
1140 while (sc->participates != NULL) {
1141 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1142 nptr = sc->participates->next;
1143 free(sc->participates);
1144 sc->participates = nptr;
1146 while (sc->ignet_push_shares != NULL) {
1147 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1148 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1149 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1151 StrBufAppendPrintf(Cfg, "\n");
1152 mptr = sc->ignet_push_shares->next;
1153 free(sc->ignet_push_shares);
1154 sc->ignet_push_shares = mptr;
1156 if (sc->misc != NULL) {
1157 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1161 rc = fwrite(ChrPtr(Cfg), StrLength(Cfg), 1, fp);
1165 rename(filename, tempfilename);
1168 CtdlLogPrintf(CTDL_EMERG,
1169 "unable to write %s; not enough space on the disk?\n",
1179 int is_recipient(SpoolControl *sc, const char *Name)
1185 nptr = sc->listrecps;
1186 while (nptr != NULL) {
1187 if (strncmp(Name, nptr->name, len)==0)
1191 /* Do the same for digestrecps */
1192 nptr = sc->digestrecps;
1193 while (nptr != NULL) {
1194 if (strncmp(Name, nptr->name, len)==0)
1198 /* Do the same for participates */
1199 nptr = sc->participates;
1200 while (nptr != NULL) {
1201 if (strncmp(Name, nptr->name, len)==0)
1210 * Batch up and send all outbound traffic from the current room
1212 void network_spoolout_room(char *room_to_spool) {
1214 char filename[PATH_MAX];
1219 * If the room doesn't exist, don't try to perform its networking tasks.
1220 * Normally this should never happen, but once in a while maybe a room gets
1221 * queued for networking and then deleted before it can happen.
1223 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1224 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1228 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1229 begin_critical_section(S_NETCONFIGS);
1231 /* Only do net processing for rooms that have netconfigs */
1232 if (!read_spoolcontrol_file(&sc, filename))
1234 end_critical_section(S_NETCONFIGS);
1237 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1239 /* If there are digest recipients, we have to build a digest */
1240 if (sc->digestrecps != NULL) {
1241 sc->digestfp = tmpfile();
1242 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1245 /* Do something useful */
1246 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1247 network_spool_msg, sc);
1249 /* If we wrote a digest, deliver it and then close it */
1250 snprintf(buf, sizeof buf, "room_%s@%s",
1251 CC->room.QRname, config.c_fqdn);
1252 for (i=0; buf[i]; ++i) {
1253 buf[i] = tolower(buf[i]);
1254 if (isspace(buf[i])) buf[i] = '_';
1256 if (sc->digestfp != NULL) {
1257 fprintf(sc->digestfp, " -----------------------------------"
1258 "------------------------------------"
1260 "You are subscribed to the '%s' "
1262 "To post to the list: %s\n",
1263 CC->room.QRname, buf
1265 network_deliver_digest(sc); /* deliver and close */
1268 /* Now rewrite the config file */
1269 writenfree_spoolcontrol_file (&sc, filename);
1270 end_critical_section(S_NETCONFIGS);
1276 * Send the *entire* contents of the current room to one specific network node,
1277 * ignoring anything we know about which messages have already undergone
1278 * network processing. This can be used to bring a new node into sync.
1280 int network_sync_to(char *target_node) {
1282 int num_spooled = 0;
1288 char filename[PATH_MAX];
1291 /* Grab the configuration line we're looking for */
1292 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1293 begin_critical_section(S_NETCONFIGS);
1294 fp = fopen(filename, "r");
1296 end_critical_section(S_NETCONFIGS);
1299 while (fgets(buf, sizeof buf, fp) != NULL) {
1300 buf[strlen(buf)-1] = 0;
1301 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1302 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1303 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1304 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1305 && (!strcasecmp(sc_node, target_node)) ) {
1308 /* Concise syntax because we don't need a full linked-list */
1309 memset(&sc, 0, sizeof(SpoolControl));
1310 sc.ignet_push_shares = (maplist *)
1311 malloc(sizeof(maplist));
1312 sc.ignet_push_shares->next = NULL;
1313 safestrncpy(sc.ignet_push_shares->remote_nodename,
1315 sizeof sc.ignet_push_shares->remote_nodename);
1316 safestrncpy(sc.ignet_push_shares->remote_roomname,
1318 sizeof sc.ignet_push_shares->remote_roomname);
1322 end_critical_section(S_NETCONFIGS);
1324 if (!found_node) return(-1);
1326 /* Send ALL messages */
1327 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1328 network_spool_msg, &sc);
1330 /* Concise cleanup because we know there's only one node in the sc */
1331 free(sc.ignet_push_shares);
1333 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1334 num_spooled, target_node);
1335 return(num_spooled);
1340 * Implements the NSYN command
1342 void cmd_nsyn(char *argbuf) {
1344 char target_node[256];
1346 if (CtdlAccessCheck(ac_aide)) return;
1348 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1349 num_spooled = network_sync_to(target_node);
1350 if (num_spooled >= 0) {
1351 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1354 cprintf("%d No such room/node share exists.\n",
1355 ERROR + ROOM_NOT_FOUND);
1362 * Batch up and send all outbound traffic from the current room
1364 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1365 struct RoomProcList *ptr;
1367 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1368 if (ptr == NULL) return;
1370 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1371 begin_critical_section(S_RPLIST);
1374 end_critical_section(S_RPLIST);
1377 void destroy_network_queue_room(void)
1379 struct RoomProcList *cur, *p;
1380 NetMap *nmcur, *nmp;
1383 begin_critical_section(S_RPLIST);
1391 end_critical_section(S_RPLIST);
1394 while (nmcur != NULL)
1401 if (working_ignetcfg != NULL)
1402 free (working_ignetcfg);
1403 working_ignetcfg = NULL;
1408 * Learn topology from path fields
1410 void network_learn_topology(char *node, char *path) {
1414 strcpy(nexthop, "");
1416 if (num_tokens(path, '!') < 3) return;
1417 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1418 if (!strcasecmp(nmptr->nodename, node)) {
1419 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1420 nmptr->lastcontact = time(NULL);
1426 /* If we got here then it's not in the map, so add it. */
1427 nmptr = (NetMap *) malloc(sizeof (NetMap));
1428 strcpy(nmptr->nodename, node);
1429 nmptr->lastcontact = time(NULL);
1430 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1431 nmptr->next = the_netmap;
1440 * Bounce a message back to the sender
1442 void network_bounce(struct CtdlMessage *msg, char *reason) {
1443 char *oldpath = NULL;
1445 char bouncesource[SIZ];
1446 char recipient[SIZ];
1447 struct recptypes *valid = NULL;
1448 char force_room[ROOMNAMELEN];
1449 static int serialnum = 0;
1452 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1454 if (msg == NULL) return;
1456 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1459 * Give it a fresh message ID
1461 if (msg->cm_fields['I'] != NULL) {
1462 free(msg->cm_fields['I']);
1464 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1465 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1466 msg->cm_fields['I'] = strdup(buf);
1469 * FIXME ... right now we're just sending a bounce; we really want to
1470 * include the text of the bounced message.
1472 if (msg->cm_fields['M'] != NULL) {
1473 free(msg->cm_fields['M']);
1475 msg->cm_fields['M'] = strdup(reason);
1476 msg->cm_format_type = 0;
1479 * Turn the message around
1481 if (msg->cm_fields['R'] == NULL) {
1482 free(msg->cm_fields['R']);
1485 if (msg->cm_fields['D'] == NULL) {
1486 free(msg->cm_fields['D']);
1489 snprintf(recipient, sizeof recipient, "%s@%s",
1490 msg->cm_fields['A'], msg->cm_fields['N']);
1492 if (msg->cm_fields['A'] == NULL) {
1493 free(msg->cm_fields['A']);
1496 if (msg->cm_fields['N'] == NULL) {
1497 free(msg->cm_fields['N']);
1500 if (msg->cm_fields['U'] == NULL) {
1501 free(msg->cm_fields['U']);
1504 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1505 msg->cm_fields['N'] = strdup(config.c_nodename);
1506 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1508 /* prepend our node to the path */
1509 if (msg->cm_fields['P'] != NULL) {
1510 oldpath = msg->cm_fields['P'];
1511 msg->cm_fields['P'] = NULL;
1514 oldpath = strdup("unknown_user");
1516 size = strlen(oldpath) + SIZ;
1517 msg->cm_fields['P'] = malloc(size);
1518 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1521 /* Now submit the message */
1522 valid = validate_recipients(recipient, NULL, 0);
1523 if (valid != NULL) if (valid->num_error != 0) {
1524 free_recipients(valid);
1527 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1528 strcpy(force_room, config.c_aideroom);
1531 strcpy(force_room, "");
1533 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1534 strcpy(force_room, config.c_aideroom);
1536 CtdlSubmitMsg(msg, valid, force_room, 0);
1539 if (valid != NULL) free_recipients(valid);
1540 CtdlFreeMessage(msg);
1541 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1548 * Process a buffer containing a single message from a single file
1549 * from the inbound queue
1551 void network_process_buffer(char *buffer, long size) {
1552 struct CtdlMessage *msg = NULL;
1555 struct recptypes *recp = NULL;
1556 char target_room[ROOMNAMELEN];
1557 struct ser_ret sermsg;
1558 char *oldpath = NULL;
1559 char filename[PATH_MAX];
1562 unsigned char firstbyte;
1563 unsigned char lastbyte;
1565 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1567 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1568 firstbyte = buffer[0];
1569 lastbyte = buffer[size-1];
1570 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1571 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1572 size, firstbyte, lastbyte);
1576 /* Set default target room to trash */
1577 strcpy(target_room, TWITROOM);
1579 /* Load the message into memory */
1580 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1581 memset(msg, 0, sizeof(struct CtdlMessage));
1582 msg->cm_magic = CTDLMESSAGE_MAGIC;
1583 msg->cm_anon_type = buffer[1];
1584 msg->cm_format_type = buffer[2];
1586 for (pos = 3; pos < size; ++pos) {
1587 field = buffer[pos];
1588 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1589 pos = pos + strlen(&buffer[(int)pos]);
1592 /* Check for message routing */
1593 if (msg->cm_fields['D'] != NULL) {
1594 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1596 /* route the message */
1597 strcpy(nexthop, "");
1598 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1599 /* prepend our node to the path */
1600 if (msg->cm_fields['P'] != NULL) {
1601 oldpath = msg->cm_fields['P'];
1602 msg->cm_fields['P'] = NULL;
1605 oldpath = strdup("unknown_user");
1607 size = strlen(oldpath) + SIZ;
1608 msg->cm_fields['P'] = malloc(size);
1609 snprintf(msg->cm_fields['P'], size, "%s!%s",
1610 config.c_nodename, oldpath);
1613 /* serialize the message */
1614 serialize_message(&sermsg, msg);
1617 if (IsEmptyStr(nexthop)) {
1618 strcpy(nexthop, msg->cm_fields['D']);
1628 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1629 fp = fopen(filename, "ab");
1631 fwrite(sermsg.ser, sermsg.len, 1, fp);
1635 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1638 CtdlFreeMessage(msg);
1642 else { /* invalid destination node name */
1645 "A message you sent could not be delivered due to an invalid destination node"
1646 " name. Please check the address and try sending the message again.\n");
1655 * Check to see if we already have a copy of this message, and
1656 * abort its processing if so. (We used to post a warning to Aide>
1657 * every time this happened, but the network is now so densely
1658 * connected that it's inevitable.)
1660 if (network_usetable(msg) != 0) {
1661 CtdlFreeMessage(msg);
1665 /* Learn network topology from the path */
1666 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1667 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1670 /* Is the sending node giving us a very persuasive suggestion about
1671 * which room this message should be saved in? If so, go with that.
1673 if (msg->cm_fields['C'] != NULL) {
1674 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1677 /* Otherwise, does it have a recipient? If so, validate it... */
1678 else if (msg->cm_fields['R'] != NULL) {
1679 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1680 if (recp != NULL) if (recp->num_error != 0) {
1682 "A message you sent could not be delivered due to an invalid address.\n"
1683 "Please check the address and try sending the message again.\n");
1685 free_recipients(recp);
1686 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1689 strcpy(target_room, ""); /* no target room if mail */
1692 /* Our last shot at finding a home for this message is to see if
1693 * it has the O field (Originating room) set.
1695 else if (msg->cm_fields['O'] != NULL) {
1696 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1699 /* Strip out fields that are only relevant during transit */
1700 if (msg->cm_fields['D'] != NULL) {
1701 free(msg->cm_fields['D']);
1702 msg->cm_fields['D'] = NULL;
1704 if (msg->cm_fields['C'] != NULL) {
1705 free(msg->cm_fields['C']);
1706 msg->cm_fields['C'] = NULL;
1709 /* save the message into a room */
1710 if (PerformNetprocHooks(msg, target_room) == 0) {
1711 msg->cm_flags = CM_SKIP_HOOKS;
1712 CtdlSubmitMsg(msg, recp, target_room, 0);
1714 CtdlFreeMessage(msg);
1715 free_recipients(recp);
1720 * Process a single message from a single file from the inbound queue
1722 void network_process_message(FILE *fp, long msgstart, long msgend) {
1727 hold_pos = ftell(fp);
1728 size = msgend - msgstart + 1;
1729 buffer = malloc(size);
1730 if (buffer != NULL) {
1731 fseek(fp, msgstart, SEEK_SET);
1732 if (fread(buffer, size, 1, fp) > 0) {
1733 network_process_buffer(buffer, size);
1738 fseek(fp, hold_pos, SEEK_SET);
1743 * Process a single file from the inbound queue
1745 void network_process_file(char *filename) {
1747 long msgstart = (-1L);
1748 long msgend = (-1L);
1753 fp = fopen(filename, "rb");
1755 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1759 fseek(fp, 0L, SEEK_END);
1760 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1763 /* Look for messages in the data stream and break them out */
1764 while (ch = getc(fp), ch >= 0) {
1767 if (msgstart >= 0L) {
1768 msgend = msgcur - 1;
1769 network_process_message(fp, msgstart, msgend);
1777 msgend = msgcur - 1;
1778 if (msgstart >= 0L) {
1779 network_process_message(fp, msgstart, msgend);
1788 * Process anything in the inbound queue
1790 void network_do_spoolin(void) {
1793 struct stat statbuf;
1794 char filename[PATH_MAX];
1795 static time_t last_spoolin_mtime = 0L;
1798 * Check the spoolin directory's modification time. If it hasn't
1799 * been touched, we don't need to scan it.
1801 if (stat(ctdl_netin_dir, &statbuf)) return;
1802 if (statbuf.st_mtime == last_spoolin_mtime) {
1803 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1806 last_spoolin_mtime = statbuf.st_mtime;
1807 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1810 * Ok, there's something interesting in there, so scan it.
1812 dp = opendir(ctdl_netin_dir);
1813 if (dp == NULL) return;
1815 while (d = readdir(dp), d != NULL) {
1816 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1823 network_process_file(filename);
1831 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1832 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1834 void network_consolidate_spoolout(void) {
1837 char filename[PATH_MAX];
1843 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1844 dp = opendir(ctdl_netout_dir);
1845 if (dp == NULL) return;
1846 while (d = readdir(dp), d != NULL) {
1848 (strcmp(d->d_name, "."))
1849 && (strcmp(d->d_name, ".."))
1850 && (strchr(d->d_name, '@') != NULL)
1852 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1853 ptr = strchr(nexthop, '@');
1863 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1864 if (network_talking_to(nexthop, NTT_CHECK)) {
1865 CtdlLogPrintf(CTDL_DEBUG,
1866 "Currently online with %s - skipping for now\n",
1871 network_talking_to(nexthop, NTT_ADD);
1872 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1874 ctdl_netout_dir, nexthop,
1878 network_talking_to(nexthop, NTT_REMOVE);
1884 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1886 dp = opendir(ctdl_netout_dir);
1887 if (dp == NULL) return;
1889 while (d = readdir(dp), d != NULL) {
1890 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1892 ptr = strchr(d->d_name, '@');
1902 strcpy(nexthop, "");
1903 i = is_valid_node(nexthop, NULL, d->d_name);
1905 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1916 * receive network spool from the remote system
1918 void receive_spool(int *sock, char *remote_nodename) {
1919 long download_len = 0L;
1920 long bytes_received = 0L;
1922 static char pbuf[IGNET_PACKET_SIZE];
1923 char tempfilename[PATH_MAX];
1924 char permfilename[PATH_MAX];
1928 snprintf(tempfilename,
1929 sizeof tempfilename,
1937 snprintf(permfilename,
1938 sizeof permfilename,
1946 if (sock_puts(sock, "NDOP") < 0) return;
1947 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1948 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1949 if (buf[0] != '2') {
1952 download_len = extract_long(&buf[4], 0);
1954 if (download_len>0) {
1955 bytes_received = 0L;
1956 fp = fopen(tempfilename, "w");
1958 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1963 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1964 while (bytes_received < download_len) {
1966 * If shutting down we can exit here and unlink the temp file.
1967 * this shouldn't loose us any messages.
1969 if (CtdlThreadCheckStop())
1972 unlink(tempfilename);
1975 snprintf(buf, sizeof buf, "READ %ld|%ld",
1977 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1978 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1980 if (sock_puts(sock, buf) < 0) {
1982 unlink(tempfilename);
1985 if (sock_getln(sock, buf, sizeof buf) < 0) {
1987 unlink(tempfilename);
1991 if (buf[0] == '6') {
1992 plen = extract_long(&buf[4], 0);
1993 if (sock_read(sock, pbuf, plen, 1) < 0) {
1995 unlink(tempfilename);
1998 fwrite((char *) pbuf, plen, 1, fp);
1999 bytes_received = bytes_received + plen;
2005 /* Last chance for shutdown exit */
2006 if (CtdlThreadCheckStop())
2008 unlink(tempfilename);
2012 if (sock_puts(sock, "CLOS") < 0) {
2013 unlink(tempfilename);
2018 * From here on we must complete or messages will get lost
2020 if (sock_getln(sock, buf, sizeof buf) < 0) {
2021 unlink(tempfilename);
2024 if (download_len > 0) {
2025 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
2027 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2029 /* Now move the temp file to its permanent location.
2031 if (link(tempfilename, permfilename) != 0) {
2032 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2033 tempfilename, permfilename, strerror(errno)
2036 unlink(tempfilename);
2042 * transmit network spool to the remote system
2044 void transmit_spool(int *sock, char *remote_nodename)
2049 long bytes_to_write, thisblock, bytes_written;
2053 if (sock_puts(sock, "NUOP") < 0) return;
2054 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2055 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2056 if (buf[0] != '2') {
2060 snprintf(sfname, sizeof sfname,
2065 fd = open(sfname, O_RDONLY);
2067 if (errno != ENOENT) {
2068 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2073 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2074 bytes_to_write = plen;
2075 while (bytes_to_write > 0L) {
2076 /* Exit if shutting down */
2077 if (CtdlThreadCheckStop())
2083 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2084 if (sock_puts(sock, buf) < 0) {
2088 if (sock_getln(sock, buf, sizeof buf) < 0) {
2092 thisblock = atol(&buf[4]);
2093 if (buf[0] == '7') {
2094 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2098 bytes_to_write -= thisblock;
2099 bytes_written += thisblock;
2109 /* Last chance for shutdown exit */
2110 if(CtdlThreadCheckStop())
2113 if (sock_puts(sock, "UCLS 1") < 0) return;
2116 * From here on we must complete or messages will get lost
2118 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2119 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2120 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2121 if (buf[0] == '2') {
2122 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2130 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2132 void network_poll_node(char *node, char *secret, char *host, char *port) {
2136 char connected_to[SIZ];
2139 if (network_talking_to(node, NTT_CHECK)) return;
2140 network_talking_to(node, NTT_ADD);
2141 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2142 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2144 sock = sock_connect(host, port);
2146 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2147 network_talking_to(node, NTT_REMOVE);
2151 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2152 CCC->sReadBuf = NewStrBuf();
2153 CCC->sMigrateBuf = NewStrBuf();
2156 /* Read the server greeting */
2157 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2158 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2160 /* Check that the remote is who we think it is and warn the Aide if not */
2161 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2162 if (strcmp(connected_to, node))
2164 snprintf(err_buf, sizeof(err_buf),
2165 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2168 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2169 CtdlAideMessage(err_buf, "Network error");
2172 /* We're talking to the correct node. Now identify ourselves. */
2173 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2174 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2175 if (sock_puts(&sock, buf) <0) goto bail;
2176 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2177 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2178 if (buf[0] != '2') {
2182 /* At this point we are authenticated. */
2183 if (!CtdlThreadCheckStop())
2184 receive_spool(&sock, node);
2185 if (!CtdlThreadCheckStop())
2186 transmit_spool(&sock, node);
2189 sock_puts(&sock, "QUIT");
2191 FreeStrBuf(&CCC->sReadBuf);
2192 FreeStrBuf(&CCC->sMigrateBuf);
2195 network_talking_to(node, NTT_REMOVE);
2201 * Poll other Citadel nodes and transfer inbound/outbound network data.
2202 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2203 * only nodes to which we have data to send.
2205 void network_poll_other_citadel_nodes(int full_poll) {
2213 char spoolfile[256];
2215 if (working_ignetcfg == NULL) {
2216 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2220 /* Use the string tokenizer to grab one line at a time */
2221 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2222 if(CtdlThreadCheckStop())
2224 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2225 extract_token(node, linebuf, 0, '|', sizeof node);
2226 extract_token(secret, linebuf, 1, '|', sizeof secret);
2227 extract_token(host, linebuf, 2, '|', sizeof host);
2228 extract_token(port, linebuf, 3, '|', sizeof port);
2229 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2230 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2239 if (access(spoolfile, R_OK) == 0) {
2244 network_poll_node(node, secret, host, port);
2255 * It's ok if these directories already exist. Just fail silently.
2257 void create_spool_dirs(void) {
2258 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2259 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2260 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2261 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2262 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2263 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2264 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2265 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2266 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2267 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2268 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2269 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2270 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2271 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2272 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2273 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2281 * network_do_queue()
2283 * Run through the rooms doing various types of network stuff.
2285 void network_do_queue(void) {
2286 static time_t last_run = 0L;
2287 struct RoomProcList *ptr;
2288 int full_processing = 1;
2291 * Run the full set of processing tasks no more frequently
2292 * than once every n seconds
2294 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2295 full_processing = 0;
2296 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2297 config.c_net_freq - (time(NULL)- last_run)
2302 * This is a simple concurrency check to make sure only one queue run
2303 * is done at a time. We could do this with a mutex, but since we
2304 * don't really require extremely fine granularity here, we'll do it
2305 * with a static variable instead.
2312 /* Load the IGnet Configuration into memory */
2313 load_working_ignetcfg();
2316 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2317 * then we poll everyone. Otherwise we only poll nodes we have stuff
2320 network_poll_other_citadel_nodes(full_processing);
2323 * Load the network map and filter list into memory.
2326 filterlist = load_filter_list();
2329 * Go ahead and run the queue
2331 if (full_processing && !CtdlThreadCheckStop()) {
2332 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2333 CtdlForEachRoom(network_queue_room, NULL);
2336 if (rplist != NULL) {
2337 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2338 while (rplist != NULL && !CtdlThreadCheckStop()) {
2339 char spoolroomname[ROOMNAMELEN];
2340 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2341 begin_critical_section(S_RPLIST);
2343 /* pop this record off the list */
2345 rplist = rplist->next;
2348 /* invalidate any duplicate entries to prevent double processing */
2349 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2350 if (!strcasecmp(ptr->name, spoolroomname)) {
2355 end_critical_section(S_RPLIST);
2356 if (spoolroomname[0] != 0) {
2357 network_spoolout_room(spoolroomname);
2362 /* If there is anything in the inbound queue, process it */
2363 if (!CtdlThreadCheckStop()) {
2364 network_do_spoolin();
2367 /* Save the network map back to disk */
2368 write_network_map();
2370 /* Free the filter list in memory */
2371 free_filter_list(filterlist);
2374 network_consolidate_spoolout();
2376 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2378 if (full_processing) {
2379 last_run = time(NULL);
2387 * cmd_netp() - authenticate to the server as another Citadel node polling
2388 * for network traffic
2390 void cmd_netp(char *cmdbuf)
2401 extract_token(node, cmdbuf, 0, '|', sizeof node);
2402 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2404 /* load the IGnet Configuration to check node validity */
2405 load_working_ignetcfg();
2406 v = is_valid_node(nexthop, secret, node);
2409 snprintf(err_buf, sizeof err_buf,
2410 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2411 node, CC->cs_host, CC->cs_addr
2413 CtdlLogPrintf(CTDL_WARNING, err_buf);
2414 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2415 CtdlAideMessage(err_buf, "IGNet Networking.");
2419 if (strcasecmp(pass, secret)) {
2420 snprintf(err_buf, sizeof err_buf,
2421 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2422 CC->cs_host, CC->cs_addr, node
2424 CtdlLogPrintf(CTDL_WARNING, err_buf);
2425 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2426 CtdlAideMessage(err_buf, "IGNet Networking.");
2430 if (network_talking_to(node, NTT_CHECK)) {
2431 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2432 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2436 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2437 network_talking_to(node, NTT_ADD);
2438 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2439 CC->net_node, CC->cs_host, CC->cs_addr
2441 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2445 int network_room_handler (struct ctdlroom *room)
2447 network_queue_room(room, NULL);
2451 void *ignet_thread(void *arg) {
2452 struct CitContext ignet_thread_CC;
2454 CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2455 CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2456 citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2458 while (!CtdlThreadCheckStop()) {
2460 CtdlThreadSleep(60);
2463 CtdlClearSystemContext();
2471 * Module entry point
2473 CTDL_MODULE_INIT(network)
2477 create_spool_dirs();
2478 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2479 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2480 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2481 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2482 CtdlRegisterRoomHook(network_room_handler);
2483 CtdlRegisterCleanupHook(destroy_network_queue_room);
2484 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);