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);
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);
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(tempfilename, filename);
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);
1114 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1116 if ((TmpFD < 0) || (errno != 0)) {
1117 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1118 filename, strerror(errno));
1119 free_spoolcontrol_struct(scc);
1120 unlink(tempfilename);
1123 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1125 /* Write out the listrecps while freeing from memory at the
1126 * same time. Am I clever or what? :)
1128 while (sc->listrecps != NULL) {
1129 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1130 nptr = sc->listrecps->next;
1131 free(sc->listrecps);
1132 sc->listrecps = nptr;
1134 /* Do the same for digestrecps */
1135 while (sc->digestrecps != NULL) {
1136 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1137 nptr = sc->digestrecps->next;
1138 free(sc->digestrecps);
1139 sc->digestrecps = nptr;
1141 /* Do the same for participates */
1142 while (sc->participates != NULL) {
1143 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1144 nptr = sc->participates->next;
1145 free(sc->participates);
1146 sc->participates = nptr;
1148 while (sc->ignet_push_shares != NULL) {
1149 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1150 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1151 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1153 StrBufAppendPrintf(Cfg, "\n");
1154 mptr = sc->ignet_push_shares->next;
1155 free(sc->ignet_push_shares);
1156 sc->ignet_push_shares = mptr;
1158 if (sc->misc != NULL) {
1159 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1163 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1164 if ((rc >=0 ) && (rc == StrLength(Cfg)))
1167 rename(tempfilename, filename);
1170 CtdlLogPrintf(CTDL_EMERG,
1171 "unable to write %s; [%s]; not enough space on the disk?\n",
1175 unlink(tempfilename);
1183 int is_recipient(SpoolControl *sc, const char *Name)
1189 nptr = sc->listrecps;
1190 while (nptr != NULL) {
1191 if (strncmp(Name, nptr->name, len)==0)
1195 /* Do the same for digestrecps */
1196 nptr = sc->digestrecps;
1197 while (nptr != NULL) {
1198 if (strncmp(Name, nptr->name, len)==0)
1202 /* Do the same for participates */
1203 nptr = sc->participates;
1204 while (nptr != NULL) {
1205 if (strncmp(Name, nptr->name, len)==0)
1214 * Batch up and send all outbound traffic from the current room
1216 void network_spoolout_room(char *room_to_spool) {
1218 char filename[PATH_MAX];
1223 * If the room doesn't exist, don't try to perform its networking tasks.
1224 * Normally this should never happen, but once in a while maybe a room gets
1225 * queued for networking and then deleted before it can happen.
1227 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1228 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1232 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1233 begin_critical_section(S_NETCONFIGS);
1235 /* Only do net processing for rooms that have netconfigs */
1236 if (!read_spoolcontrol_file(&sc, filename))
1238 end_critical_section(S_NETCONFIGS);
1241 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1243 /* If there are digest recipients, we have to build a digest */
1244 if (sc->digestrecps != NULL) {
1245 sc->digestfp = tmpfile();
1246 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1249 /* Do something useful */
1250 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1251 network_spool_msg, sc);
1253 /* If we wrote a digest, deliver it and then close it */
1254 snprintf(buf, sizeof buf, "room_%s@%s",
1255 CC->room.QRname, config.c_fqdn);
1256 for (i=0; buf[i]; ++i) {
1257 buf[i] = tolower(buf[i]);
1258 if (isspace(buf[i])) buf[i] = '_';
1260 if (sc->digestfp != NULL) {
1261 fprintf(sc->digestfp, " -----------------------------------"
1262 "------------------------------------"
1264 "You are subscribed to the '%s' "
1266 "To post to the list: %s\n",
1267 CC->room.QRname, buf
1269 network_deliver_digest(sc); /* deliver and close */
1272 /* Now rewrite the config file */
1273 writenfree_spoolcontrol_file (&sc, filename);
1274 end_critical_section(S_NETCONFIGS);
1280 * Send the *entire* contents of the current room to one specific network node,
1281 * ignoring anything we know about which messages have already undergone
1282 * network processing. This can be used to bring a new node into sync.
1284 int network_sync_to(char *target_node) {
1286 int num_spooled = 0;
1292 char filename[PATH_MAX];
1295 /* Grab the configuration line we're looking for */
1296 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1297 begin_critical_section(S_NETCONFIGS);
1298 fp = fopen(filename, "r");
1300 end_critical_section(S_NETCONFIGS);
1303 while (fgets(buf, sizeof buf, fp) != NULL) {
1304 buf[strlen(buf)-1] = 0;
1305 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1306 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1307 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1308 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1309 && (!strcasecmp(sc_node, target_node)) ) {
1312 /* Concise syntax because we don't need a full linked-list */
1313 memset(&sc, 0, sizeof(SpoolControl));
1314 sc.ignet_push_shares = (maplist *)
1315 malloc(sizeof(maplist));
1316 sc.ignet_push_shares->next = NULL;
1317 safestrncpy(sc.ignet_push_shares->remote_nodename,
1319 sizeof sc.ignet_push_shares->remote_nodename);
1320 safestrncpy(sc.ignet_push_shares->remote_roomname,
1322 sizeof sc.ignet_push_shares->remote_roomname);
1326 end_critical_section(S_NETCONFIGS);
1328 if (!found_node) return(-1);
1330 /* Send ALL messages */
1331 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1332 network_spool_msg, &sc);
1334 /* Concise cleanup because we know there's only one node in the sc */
1335 free(sc.ignet_push_shares);
1337 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1338 num_spooled, target_node);
1339 return(num_spooled);
1344 * Implements the NSYN command
1346 void cmd_nsyn(char *argbuf) {
1348 char target_node[256];
1350 if (CtdlAccessCheck(ac_aide)) return;
1352 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1353 num_spooled = network_sync_to(target_node);
1354 if (num_spooled >= 0) {
1355 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1358 cprintf("%d No such room/node share exists.\n",
1359 ERROR + ROOM_NOT_FOUND);
1366 * Batch up and send all outbound traffic from the current room
1368 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1369 struct RoomProcList *ptr;
1371 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1372 if (ptr == NULL) return;
1374 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1375 begin_critical_section(S_RPLIST);
1378 end_critical_section(S_RPLIST);
1381 void destroy_network_queue_room(void)
1383 struct RoomProcList *cur, *p;
1384 NetMap *nmcur, *nmp;
1387 begin_critical_section(S_RPLIST);
1395 end_critical_section(S_RPLIST);
1398 while (nmcur != NULL)
1405 if (working_ignetcfg != NULL)
1406 free (working_ignetcfg);
1407 working_ignetcfg = NULL;
1412 * Learn topology from path fields
1414 void network_learn_topology(char *node, char *path) {
1418 strcpy(nexthop, "");
1420 if (num_tokens(path, '!') < 3) return;
1421 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1422 if (!strcasecmp(nmptr->nodename, node)) {
1423 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1424 nmptr->lastcontact = time(NULL);
1430 /* If we got here then it's not in the map, so add it. */
1431 nmptr = (NetMap *) malloc(sizeof (NetMap));
1432 strcpy(nmptr->nodename, node);
1433 nmptr->lastcontact = time(NULL);
1434 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1435 nmptr->next = the_netmap;
1444 * Bounce a message back to the sender
1446 void network_bounce(struct CtdlMessage *msg, char *reason) {
1447 char *oldpath = NULL;
1449 char bouncesource[SIZ];
1450 char recipient[SIZ];
1451 struct recptypes *valid = NULL;
1452 char force_room[ROOMNAMELEN];
1453 static int serialnum = 0;
1456 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1458 if (msg == NULL) return;
1460 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1463 * Give it a fresh message ID
1465 if (msg->cm_fields['I'] != NULL) {
1466 free(msg->cm_fields['I']);
1468 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1469 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1470 msg->cm_fields['I'] = strdup(buf);
1473 * FIXME ... right now we're just sending a bounce; we really want to
1474 * include the text of the bounced message.
1476 if (msg->cm_fields['M'] != NULL) {
1477 free(msg->cm_fields['M']);
1479 msg->cm_fields['M'] = strdup(reason);
1480 msg->cm_format_type = 0;
1483 * Turn the message around
1485 if (msg->cm_fields['R'] == NULL) {
1486 free(msg->cm_fields['R']);
1489 if (msg->cm_fields['D'] == NULL) {
1490 free(msg->cm_fields['D']);
1493 snprintf(recipient, sizeof recipient, "%s@%s",
1494 msg->cm_fields['A'], msg->cm_fields['N']);
1496 if (msg->cm_fields['A'] == NULL) {
1497 free(msg->cm_fields['A']);
1500 if (msg->cm_fields['N'] == NULL) {
1501 free(msg->cm_fields['N']);
1504 if (msg->cm_fields['U'] == NULL) {
1505 free(msg->cm_fields['U']);
1508 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1509 msg->cm_fields['N'] = strdup(config.c_nodename);
1510 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1512 /* prepend our node to the path */
1513 if (msg->cm_fields['P'] != NULL) {
1514 oldpath = msg->cm_fields['P'];
1515 msg->cm_fields['P'] = NULL;
1518 oldpath = strdup("unknown_user");
1520 size = strlen(oldpath) + SIZ;
1521 msg->cm_fields['P'] = malloc(size);
1522 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1525 /* Now submit the message */
1526 valid = validate_recipients(recipient, NULL, 0);
1527 if (valid != NULL) if (valid->num_error != 0) {
1528 free_recipients(valid);
1531 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1532 strcpy(force_room, config.c_aideroom);
1535 strcpy(force_room, "");
1537 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1538 strcpy(force_room, config.c_aideroom);
1540 CtdlSubmitMsg(msg, valid, force_room, 0);
1543 if (valid != NULL) free_recipients(valid);
1544 CtdlFreeMessage(msg);
1545 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1552 * Process a buffer containing a single message from a single file
1553 * from the inbound queue
1555 void network_process_buffer(char *buffer, long size) {
1556 struct CtdlMessage *msg = NULL;
1559 struct recptypes *recp = NULL;
1560 char target_room[ROOMNAMELEN];
1561 struct ser_ret sermsg;
1562 char *oldpath = NULL;
1563 char filename[PATH_MAX];
1566 unsigned char firstbyte;
1567 unsigned char lastbyte;
1569 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1571 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1572 firstbyte = buffer[0];
1573 lastbyte = buffer[size-1];
1574 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1575 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1576 size, firstbyte, lastbyte);
1580 /* Set default target room to trash */
1581 strcpy(target_room, TWITROOM);
1583 /* Load the message into memory */
1584 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1585 memset(msg, 0, sizeof(struct CtdlMessage));
1586 msg->cm_magic = CTDLMESSAGE_MAGIC;
1587 msg->cm_anon_type = buffer[1];
1588 msg->cm_format_type = buffer[2];
1590 for (pos = 3; pos < size; ++pos) {
1591 field = buffer[pos];
1592 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1593 pos = pos + strlen(&buffer[(int)pos]);
1596 /* Check for message routing */
1597 if (msg->cm_fields['D'] != NULL) {
1598 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1600 /* route the message */
1601 strcpy(nexthop, "");
1602 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1603 /* prepend our node to the path */
1604 if (msg->cm_fields['P'] != NULL) {
1605 oldpath = msg->cm_fields['P'];
1606 msg->cm_fields['P'] = NULL;
1609 oldpath = strdup("unknown_user");
1611 size = strlen(oldpath) + SIZ;
1612 msg->cm_fields['P'] = malloc(size);
1613 snprintf(msg->cm_fields['P'], size, "%s!%s",
1614 config.c_nodename, oldpath);
1617 /* serialize the message */
1618 serialize_message(&sermsg, msg);
1621 if (IsEmptyStr(nexthop)) {
1622 strcpy(nexthop, msg->cm_fields['D']);
1632 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1633 fp = fopen(filename, "ab");
1635 fwrite(sermsg.ser, sermsg.len, 1, fp);
1639 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1642 CtdlFreeMessage(msg);
1646 else { /* invalid destination node name */
1649 "A message you sent could not be delivered due to an invalid destination node"
1650 " name. Please check the address and try sending the message again.\n");
1659 * Check to see if we already have a copy of this message, and
1660 * abort its processing if so. (We used to post a warning to Aide>
1661 * every time this happened, but the network is now so densely
1662 * connected that it's inevitable.)
1664 if (network_usetable(msg) != 0) {
1665 CtdlFreeMessage(msg);
1669 /* Learn network topology from the path */
1670 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1671 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1674 /* Is the sending node giving us a very persuasive suggestion about
1675 * which room this message should be saved in? If so, go with that.
1677 if (msg->cm_fields['C'] != NULL) {
1678 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1681 /* Otherwise, does it have a recipient? If so, validate it... */
1682 else if (msg->cm_fields['R'] != NULL) {
1683 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1684 if (recp != NULL) if (recp->num_error != 0) {
1686 "A message you sent could not be delivered due to an invalid address.\n"
1687 "Please check the address and try sending the message again.\n");
1689 free_recipients(recp);
1690 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1693 strcpy(target_room, ""); /* no target room if mail */
1696 /* Our last shot at finding a home for this message is to see if
1697 * it has the O field (Originating room) set.
1699 else if (msg->cm_fields['O'] != NULL) {
1700 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1703 /* Strip out fields that are only relevant during transit */
1704 if (msg->cm_fields['D'] != NULL) {
1705 free(msg->cm_fields['D']);
1706 msg->cm_fields['D'] = NULL;
1708 if (msg->cm_fields['C'] != NULL) {
1709 free(msg->cm_fields['C']);
1710 msg->cm_fields['C'] = NULL;
1713 /* save the message into a room */
1714 if (PerformNetprocHooks(msg, target_room) == 0) {
1715 msg->cm_flags = CM_SKIP_HOOKS;
1716 CtdlSubmitMsg(msg, recp, target_room, 0);
1718 CtdlFreeMessage(msg);
1719 free_recipients(recp);
1724 * Process a single message from a single file from the inbound queue
1726 void network_process_message(FILE *fp, long msgstart, long msgend) {
1731 hold_pos = ftell(fp);
1732 size = msgend - msgstart + 1;
1733 buffer = malloc(size);
1734 if (buffer != NULL) {
1735 fseek(fp, msgstart, SEEK_SET);
1736 if (fread(buffer, size, 1, fp) > 0) {
1737 network_process_buffer(buffer, size);
1742 fseek(fp, hold_pos, SEEK_SET);
1747 * Process a single file from the inbound queue
1749 void network_process_file(char *filename) {
1751 long msgstart = (-1L);
1752 long msgend = (-1L);
1757 fp = fopen(filename, "rb");
1759 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1763 fseek(fp, 0L, SEEK_END);
1764 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1767 /* Look for messages in the data stream and break them out */
1768 while (ch = getc(fp), ch >= 0) {
1771 if (msgstart >= 0L) {
1772 msgend = msgcur - 1;
1773 network_process_message(fp, msgstart, msgend);
1781 msgend = msgcur - 1;
1782 if (msgstart >= 0L) {
1783 network_process_message(fp, msgstart, msgend);
1792 * Process anything in the inbound queue
1794 void network_do_spoolin(void) {
1797 struct stat statbuf;
1798 char filename[PATH_MAX];
1799 static time_t last_spoolin_mtime = 0L;
1802 * Check the spoolin directory's modification time. If it hasn't
1803 * been touched, we don't need to scan it.
1805 if (stat(ctdl_netin_dir, &statbuf)) return;
1806 if (statbuf.st_mtime == last_spoolin_mtime) {
1807 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1810 last_spoolin_mtime = statbuf.st_mtime;
1811 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1814 * Ok, there's something interesting in there, so scan it.
1816 dp = opendir(ctdl_netin_dir);
1817 if (dp == NULL) return;
1819 while (d = readdir(dp), d != NULL) {
1820 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1827 network_process_file(filename);
1835 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1836 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1838 void network_consolidate_spoolout(void) {
1841 char filename[PATH_MAX];
1847 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1848 dp = opendir(ctdl_netout_dir);
1849 if (dp == NULL) return;
1850 while (d = readdir(dp), d != NULL) {
1852 (strcmp(d->d_name, "."))
1853 && (strcmp(d->d_name, ".."))
1854 && (strchr(d->d_name, '@') != NULL)
1856 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1857 ptr = strchr(nexthop, '@');
1867 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1868 if (network_talking_to(nexthop, NTT_CHECK)) {
1869 CtdlLogPrintf(CTDL_DEBUG,
1870 "Currently online with %s - skipping for now\n",
1875 network_talking_to(nexthop, NTT_ADD);
1876 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1878 ctdl_netout_dir, nexthop,
1882 network_talking_to(nexthop, NTT_REMOVE);
1888 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1890 dp = opendir(ctdl_netout_dir);
1891 if (dp == NULL) return;
1893 while (d = readdir(dp), d != NULL) {
1894 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1896 ptr = strchr(d->d_name, '@');
1906 strcpy(nexthop, "");
1907 i = is_valid_node(nexthop, NULL, d->d_name);
1909 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1920 * receive network spool from the remote system
1922 void receive_spool(int *sock, char *remote_nodename) {
1923 long download_len = 0L;
1924 long bytes_received = 0L;
1926 static char pbuf[IGNET_PACKET_SIZE];
1927 char tempfilename[PATH_MAX];
1928 char permfilename[PATH_MAX];
1932 snprintf(tempfilename,
1933 sizeof tempfilename,
1941 snprintf(permfilename,
1942 sizeof permfilename,
1950 if (sock_puts(sock, "NDOP") < 0) return;
1951 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1952 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1953 if (buf[0] != '2') {
1956 download_len = extract_long(&buf[4], 0);
1958 if (download_len>0) {
1959 bytes_received = 0L;
1960 fp = fopen(tempfilename, "w");
1962 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1967 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1968 while (bytes_received < download_len) {
1970 * If shutting down we can exit here and unlink the temp file.
1971 * this shouldn't loose us any messages.
1973 if (CtdlThreadCheckStop())
1976 unlink(tempfilename);
1979 snprintf(buf, sizeof buf, "READ %ld|%ld",
1981 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1982 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1984 if (sock_puts(sock, buf) < 0) {
1986 unlink(tempfilename);
1989 if (sock_getln(sock, buf, sizeof buf) < 0) {
1991 unlink(tempfilename);
1995 if (buf[0] == '6') {
1996 plen = extract_long(&buf[4], 0);
1997 if (sock_read(sock, pbuf, plen, 1) < 0) {
1999 unlink(tempfilename);
2002 fwrite((char *) pbuf, plen, 1, fp);
2003 bytes_received = bytes_received + plen;
2009 /* Last chance for shutdown exit */
2010 if (CtdlThreadCheckStop())
2012 unlink(tempfilename);
2016 if (sock_puts(sock, "CLOS") < 0) {
2017 unlink(tempfilename);
2022 * From here on we must complete or messages will get lost
2024 if (sock_getln(sock, buf, sizeof buf) < 0) {
2025 unlink(tempfilename);
2028 if (download_len > 0) {
2029 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
2031 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
2033 /* Now move the temp file to its permanent location.
2035 if (link(tempfilename, permfilename) != 0) {
2036 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
2037 tempfilename, permfilename, strerror(errno)
2040 unlink(tempfilename);
2046 * transmit network spool to the remote system
2048 void transmit_spool(int *sock, char *remote_nodename)
2053 long bytes_to_write, thisblock, bytes_written;
2057 if (sock_puts(sock, "NUOP") < 0) return;
2058 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2059 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2060 if (buf[0] != '2') {
2064 snprintf(sfname, sizeof sfname,
2069 fd = open(sfname, O_RDONLY);
2071 if (errno != ENOENT) {
2072 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2077 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2078 bytes_to_write = plen;
2079 while (bytes_to_write > 0L) {
2080 /* Exit if shutting down */
2081 if (CtdlThreadCheckStop())
2087 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2088 if (sock_puts(sock, buf) < 0) {
2092 if (sock_getln(sock, buf, sizeof buf) < 0) {
2096 thisblock = atol(&buf[4]);
2097 if (buf[0] == '7') {
2098 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2102 bytes_to_write -= thisblock;
2103 bytes_written += thisblock;
2113 /* Last chance for shutdown exit */
2114 if(CtdlThreadCheckStop())
2117 if (sock_puts(sock, "UCLS 1") < 0) return;
2120 * From here on we must complete or messages will get lost
2122 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2123 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2124 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2125 if (buf[0] == '2') {
2126 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2134 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2136 void network_poll_node(char *node, char *secret, char *host, char *port) {
2140 char connected_to[SIZ];
2143 if (network_talking_to(node, NTT_CHECK)) return;
2144 network_talking_to(node, NTT_ADD);
2145 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2146 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2148 sock = sock_connect(host, port);
2150 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2151 network_talking_to(node, NTT_REMOVE);
2155 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2156 CCC->sReadBuf = NewStrBuf();
2157 CCC->sMigrateBuf = NewStrBuf();
2160 /* Read the server greeting */
2161 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2162 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2164 /* Check that the remote is who we think it is and warn the Aide if not */
2165 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2166 if (strcmp(connected_to, node))
2168 snprintf(err_buf, sizeof(err_buf),
2169 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2172 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2173 CtdlAideMessage(err_buf, "Network error");
2176 /* We're talking to the correct node. Now identify ourselves. */
2177 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2178 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2179 if (sock_puts(&sock, buf) <0) goto bail;
2180 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2181 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2182 if (buf[0] != '2') {
2186 /* At this point we are authenticated. */
2187 if (!CtdlThreadCheckStop())
2188 receive_spool(&sock, node);
2189 if (!CtdlThreadCheckStop())
2190 transmit_spool(&sock, node);
2193 sock_puts(&sock, "QUIT");
2195 FreeStrBuf(&CCC->sReadBuf);
2196 FreeStrBuf(&CCC->sMigrateBuf);
2199 network_talking_to(node, NTT_REMOVE);
2205 * Poll other Citadel nodes and transfer inbound/outbound network data.
2206 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2207 * only nodes to which we have data to send.
2209 void network_poll_other_citadel_nodes(int full_poll) {
2217 char spoolfile[256];
2219 if (working_ignetcfg == NULL) {
2220 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2224 /* Use the string tokenizer to grab one line at a time */
2225 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2226 if(CtdlThreadCheckStop())
2228 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2229 extract_token(node, linebuf, 0, '|', sizeof node);
2230 extract_token(secret, linebuf, 1, '|', sizeof secret);
2231 extract_token(host, linebuf, 2, '|', sizeof host);
2232 extract_token(port, linebuf, 3, '|', sizeof port);
2233 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2234 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2243 if (access(spoolfile, R_OK) == 0) {
2248 network_poll_node(node, secret, host, port);
2259 * It's ok if these directories already exist. Just fail silently.
2261 void create_spool_dirs(void) {
2262 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2263 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2264 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2265 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2266 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2267 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2268 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2269 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2270 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2271 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2272 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2273 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2274 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2275 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2276 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2277 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2285 * network_do_queue()
2287 * Run through the rooms doing various types of network stuff.
2289 void network_do_queue(void) {
2290 static time_t last_run = 0L;
2291 struct RoomProcList *ptr;
2292 int full_processing = 1;
2295 * Run the full set of processing tasks no more frequently
2296 * than once every n seconds
2298 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2299 full_processing = 0;
2300 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2301 config.c_net_freq - (time(NULL)- last_run)
2306 * This is a simple concurrency check to make sure only one queue run
2307 * is done at a time. We could do this with a mutex, but since we
2308 * don't really require extremely fine granularity here, we'll do it
2309 * with a static variable instead.
2316 /* Load the IGnet Configuration into memory */
2317 load_working_ignetcfg();
2320 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2321 * then we poll everyone. Otherwise we only poll nodes we have stuff
2324 network_poll_other_citadel_nodes(full_processing);
2327 * Load the network map and filter list into memory.
2330 filterlist = load_filter_list();
2333 * Go ahead and run the queue
2335 if (full_processing && !CtdlThreadCheckStop()) {
2336 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2337 CtdlForEachRoom(network_queue_room, NULL);
2340 if (rplist != NULL) {
2341 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2342 while (rplist != NULL && !CtdlThreadCheckStop()) {
2343 char spoolroomname[ROOMNAMELEN];
2344 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2345 begin_critical_section(S_RPLIST);
2347 /* pop this record off the list */
2349 rplist = rplist->next;
2352 /* invalidate any duplicate entries to prevent double processing */
2353 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2354 if (!strcasecmp(ptr->name, spoolroomname)) {
2359 end_critical_section(S_RPLIST);
2360 if (spoolroomname[0] != 0) {
2361 network_spoolout_room(spoolroomname);
2366 /* If there is anything in the inbound queue, process it */
2367 if (!CtdlThreadCheckStop()) {
2368 network_do_spoolin();
2371 /* Save the network map back to disk */
2372 write_network_map();
2374 /* Free the filter list in memory */
2375 free_filter_list(filterlist);
2378 network_consolidate_spoolout();
2380 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2382 if (full_processing) {
2383 last_run = time(NULL);
2391 * cmd_netp() - authenticate to the server as another Citadel node polling
2392 * for network traffic
2394 void cmd_netp(char *cmdbuf)
2405 extract_token(node, cmdbuf, 0, '|', sizeof node);
2406 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2408 /* load the IGnet Configuration to check node validity */
2409 load_working_ignetcfg();
2410 v = is_valid_node(nexthop, secret, node);
2413 snprintf(err_buf, sizeof err_buf,
2414 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2415 node, CC->cs_host, CC->cs_addr
2417 CtdlLogPrintf(CTDL_WARNING, err_buf);
2418 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2419 CtdlAideMessage(err_buf, "IGNet Networking.");
2423 if (strcasecmp(pass, secret)) {
2424 snprintf(err_buf, sizeof err_buf,
2425 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2426 CC->cs_host, CC->cs_addr, node
2428 CtdlLogPrintf(CTDL_WARNING, err_buf);
2429 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2430 CtdlAideMessage(err_buf, "IGNet Networking.");
2434 if (network_talking_to(node, NTT_CHECK)) {
2435 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2436 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2440 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2441 network_talking_to(node, NTT_ADD);
2442 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2443 CC->net_node, CC->cs_host, CC->cs_addr
2445 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2449 int network_room_handler (struct ctdlroom *room)
2451 network_queue_room(room, NULL);
2455 void *ignet_thread(void *arg) {
2456 struct CitContext ignet_thread_CC;
2458 CtdlLogPrintf(CTDL_DEBUG, "ignet_thread() initializing\n");
2459 CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2460 citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2462 while (!CtdlThreadCheckStop()) {
2464 CtdlThreadSleep(60);
2467 CtdlClearSystemContext();
2475 * Module entry point
2477 CTDL_MODULE_INIT(network)
2481 create_spool_dirs();
2482 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2483 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2484 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2485 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2486 CtdlRegisterRoomHook(network_room_handler);
2487 CtdlRegisterCleanupHook(destroy_network_queue_room);
2488 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);