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>
62 #include <libcitadel.h>
65 #include "citserver.h"
71 #include "internet_addressing.h"
72 #include "serv_network.h"
73 #include "clientsocket.h"
75 #include "citadel_dirs.h"
84 #include "ctdl_module.h"
88 /* Nonzero while we are doing network processing */
89 static int doing_queue = 0;
92 * When we do network processing, it's accomplished in two passes; one to
93 * gather a list of rooms and one to actually do them. It's ok that rplist
94 * is global; we have a mutex that keeps it safe.
96 struct RoomProcList *rplist = NULL;
99 * We build a map of network nodes during processing.
101 NetMap *the_netmap = NULL;
102 int netmap_changed = 0;
103 char *working_ignetcfg = NULL;
106 * Load or refresh the Citadel network (IGnet) configuration for this node.
108 void load_working_ignetcfg(void) {
112 cfg = CtdlGetSysConfig(IGNETCFG);
117 oldcfg = working_ignetcfg;
118 working_ignetcfg = cfg;
119 if (oldcfg != NULL) {
129 * Keep track of what messages to reject
131 FilterList *load_filter_list(void) {
132 char *serialized_list = NULL;
135 FilterList *newlist = NULL;
138 serialized_list = CtdlGetSysConfig(FILTERLIST);
139 if (serialized_list == NULL) return(NULL); /* if null, no entries */
141 /* Use the string tokenizer to grab one line at a time */
142 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
143 extract_token(buf, serialized_list, i, '\n', sizeof buf);
144 nptr = (FilterList *) malloc(sizeof(FilterList));
145 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
146 striplt(nptr->fl_user);
147 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
148 striplt(nptr->fl_room);
149 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
150 striplt(nptr->fl_node);
152 /* Cowardly refuse to add an any/any/any entry that would
153 * end up filtering every single message.
155 if (IsEmptyStr(nptr->fl_user) &&
156 IsEmptyStr(nptr->fl_room) &&
157 IsEmptyStr(nptr->fl_node)) {
161 nptr->next = newlist;
166 free(serialized_list);
171 void free_filter_list(FilterList *fl) {
172 if (fl == NULL) return;
173 free_filter_list(fl->next);
180 * Check the use table. This is a list of messages which have recently
181 * arrived on the system. It is maintained and queried to prevent the same
182 * message from being entered into the database multiple times if it happens
183 * to arrive multiple times by accident.
185 int network_usetable(struct CtdlMessage *msg) {
188 struct cdbdata *cdbut;
191 /* Bail out if we can't generate a message ID */
195 if (msg->cm_fields['I'] == NULL) {
198 if (IsEmptyStr(msg->cm_fields['I'])) {
202 /* Generate the message ID */
203 strcpy(msgid, msg->cm_fields['I']);
204 if (haschar(msgid, '@') == 0) {
206 if (msg->cm_fields['N'] != NULL) {
207 strcat(msgid, msg->cm_fields['N']);
214 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
217 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
221 /* If we got to this point, it's unique: add it. */
222 strcpy(ut.ut_msgid, msgid);
223 ut.ut_timestamp = time(NULL);
224 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
230 * Read the network map from its configuration file into memory.
232 void read_network_map(void) {
233 char *serialized_map = NULL;
238 serialized_map = CtdlGetSysConfig(IGNETMAP);
239 if (serialized_map == NULL) return; /* if null, no entries */
241 /* Use the string tokenizer to grab one line at a time */
242 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
243 extract_token(buf, serialized_map, i, '\n', sizeof buf);
244 nmptr = (NetMap *) malloc(sizeof(NetMap));
245 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
246 nmptr->lastcontact = extract_long(buf, 1);
247 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
248 nmptr->next = the_netmap;
252 free(serialized_map);
258 * Write the network map from memory back to the configuration file.
260 void write_network_map(void) {
261 char *serialized_map = NULL;
265 if (netmap_changed) {
266 serialized_map = strdup("");
268 if (the_netmap != NULL) {
269 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
270 serialized_map = realloc(serialized_map,
271 (strlen(serialized_map)+SIZ) );
272 if (!IsEmptyStr(nmptr->nodename)) {
273 snprintf(&serialized_map[strlen(serialized_map)],
277 (long)nmptr->lastcontact,
283 CtdlPutSysConfig(IGNETMAP, serialized_map);
284 free(serialized_map);
287 /* Now free the list */
288 while (the_netmap != NULL) {
289 nmptr = the_netmap->next;
299 * Check the network map and determine whether the supplied node name is
300 * valid. If it is not a neighbor node, supply the name of a neighbor node
301 * which is the next hop. If it *is* a neighbor node, we also fill in the
304 int is_valid_node(char *nexthop, char *secret, char *node) {
316 * First try the neighbor nodes
318 if (working_ignetcfg == NULL) {
319 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
320 if (nexthop != NULL) {
327 if (nexthop != NULL) {
331 /* Use the string tokenizer to grab one line at a time */
332 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
333 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
334 extract_token(buf, linebuf, 0, '|', sizeof buf);
335 if (!strcasecmp(buf, node)) {
336 if (nexthop != NULL) {
339 if (secret != NULL) {
340 extract_token(secret, linebuf, 1, '|', 256);
347 return(retval); /* yup, it's a direct neighbor */
351 * If we get to this point we have to see if we know the next hop
353 if (the_netmap != NULL) {
354 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
355 if (!strcasecmp(nmptr->nodename, node)) {
356 if (nexthop != NULL) {
357 strcpy(nexthop, nmptr->nexthop);
365 * If we get to this point, the supplied node name is bogus.
367 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
375 void cmd_gnet(char *argbuf) {
376 char filename[PATH_MAX];
380 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
381 /* users can edit the netconfigs for their own mailbox rooms */
383 else if (CtdlAccessCheck(ac_room_aide)) return;
385 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
386 cprintf("%d Network settings for room #%ld <%s>\n",
388 CC->room.QRnumber, CC->room.QRname);
390 fp = fopen(filename, "r");
392 while (fgets(buf, sizeof buf, fp) != NULL) {
393 buf[strlen(buf)-1] = 0;
394 cprintf("%s\n", buf);
403 void cmd_snet(char *argbuf) {
404 char tempfilename[PATH_MAX];
405 char filename[PATH_MAX];
411 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
412 /* users can edit the netconfigs for their own mailbox rooms */
414 else if (CtdlAccessCheck(ac_room_aide)) return;
416 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
417 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
419 fp = fopen(tempfilename, "w");
421 cprintf("%d Cannot open %s: %s\n",
422 ERROR + INTERNAL_ERROR,
427 cprintf("%d %s\n", SEND_LISTING, tempfilename);
428 while (client_getln(buf, sizeof buf) >= 0 && strcmp(buf, "000")) {
429 fprintf(fp, "%s\n", buf);
433 /* Now copy the temp file to its permanent location.
434 * (We copy instead of link because they may be on different filesystems)
436 begin_critical_section(S_NETCONFIGS);
437 fp = fopen(tempfilename, "r");
439 newfp = fopen(filename, "w");
441 while (fgets(buf, sizeof buf, fp) != NULL) {
442 fprintf(newfp, "%s", buf);
448 end_critical_section(S_NETCONFIGS);
449 unlink(tempfilename);
454 * Deliver digest messages
456 void network_deliver_digest(SpoolControl *sc) {
459 struct CtdlMessage *msg = NULL;
462 size_t recps_len = SIZ;
464 struct recptypes *valid;
468 if (sc->num_msgs_spooled < 1) {
469 fclose(sc->digestfp);
474 msg = malloc(sizeof(struct CtdlMessage));
475 memset(msg, 0, sizeof(struct CtdlMessage));
476 msg->cm_magic = CTDLMESSAGE_MAGIC;
477 msg->cm_format_type = FMT_RFC822;
478 msg->cm_anon_type = MES_NORMAL;
480 sprintf(buf, "%ld", time(NULL));
481 msg->cm_fields['T'] = strdup(buf);
482 msg->cm_fields['A'] = strdup(CC->room.QRname);
483 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
484 msg->cm_fields['U'] = strdup(buf);
485 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
486 for (i=0; buf[i]; ++i) {
487 if (isspace(buf[i])) buf[i]='_';
488 buf[i] = tolower(buf[i]);
490 msg->cm_fields['F'] = strdup(buf);
491 msg->cm_fields['R'] = strdup(buf);
493 /* Set the 'List-ID' header */
494 msg->cm_fields['L'] = malloc(1024);
495 snprintf(msg->cm_fields['L'], 1024,
496 "%s <%ld.list-id.%s>",
503 * Go fetch the contents of the digest
505 fseek(sc->digestfp, 0L, SEEK_END);
506 msglen = ftell(sc->digestfp);
508 msg->cm_fields['M'] = malloc(msglen + 1);
509 fseek(sc->digestfp, 0L, SEEK_SET);
510 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
511 msg->cm_fields['M'][msglen] = '\0';
513 fclose(sc->digestfp);
516 /* Now generate the delivery instructions */
519 * Figure out how big a buffer we need to allocate
521 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
522 recps_len = recps_len + strlen(nptr->name) + 2;
525 recps = malloc(recps_len);
528 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
535 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
536 if (nptr != sc->digestrecps) {
539 strcat(recps, nptr->name);
542 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
543 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
545 /* Now submit the message */
546 valid = validate_recipients(recps, NULL, 0);
549 valid->bounce_to = strdup(bounce_to);
550 valid->envelope_from = strdup(bounce_to);
551 CtdlSubmitMsg(msg, valid, NULL, 0);
553 CtdlFreeMessage(msg);
554 free_recipients(valid);
559 * Deliver list messages to everyone on the list ... efficiently
561 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
563 size_t recps_len = SIZ;
564 struct recptypes *valid;
568 /* Don't do this if there were no recipients! */
569 if (sc->listrecps == NULL) return;
571 /* Now generate the delivery instructions */
574 * Figure out how big a buffer we need to allocate
576 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
577 recps_len = recps_len + strlen(nptr->name) + 2;
580 recps = malloc(recps_len);
583 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
590 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
591 if (nptr != sc->listrecps) {
594 strcat(recps, nptr->name);
597 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
598 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
600 /* Now submit the message */
601 valid = validate_recipients(recps, NULL, 0);
604 valid->bounce_to = strdup(bounce_to);
605 valid->envelope_from = strdup(bounce_to);
606 CtdlSubmitMsg(msg, valid, NULL, 0);
607 free_recipients(valid);
609 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
616 * Spools out one message from the list.
618 void network_spool_msg(long msgnum, void *userdata) {
621 char *newpath = NULL;
622 size_t instr_len = SIZ;
623 struct CtdlMessage *msg = NULL;
626 struct ser_ret sermsg;
628 char filename[PATH_MAX];
632 int delete_after_send = 0; /* Set to 1 to delete after spooling */
633 int ok_to_participate = 0;
634 struct recptypes *valid;
636 sc = (SpoolControl *)userdata;
639 * Process mailing list recipients
642 if (sc->listrecps != NULL) {
643 /* Fetch the message. We're going to need to modify it
644 * in order to insert the [list name] in it, etc.
646 msg = CtdlFetchMessage(msgnum, 1);
648 if (msg->cm_fields['V'] == NULL){
649 /* local message, no enVelope */
652 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
653 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
654 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
656 msg->cm_fields['K'] = SmashStrBuf(&Buf);
659 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
661 /* Set the 'List-ID' header */
662 if (msg->cm_fields['L'] != NULL) {
663 free(msg->cm_fields['L']);
665 msg->cm_fields['L'] = malloc(1024);
666 snprintf(msg->cm_fields['L'], 1024,
667 "%s <%ld.list-id.%s>",
673 /* Prepend "[List name]" to the subject */
674 if (msg->cm_fields['U'] == NULL) {
675 msg->cm_fields['U'] = strdup("(no subject)");
677 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
678 free(msg->cm_fields['U']);
679 msg->cm_fields['U'] = strdup(buf);
681 /* Set the recipient of the list message to the
682 * email address of the room itself.
683 * FIXME ... I want to be able to pick any address
685 if (msg->cm_fields['R'] != NULL) {
686 free(msg->cm_fields['R']);
688 msg->cm_fields['R'] = malloc(256);
689 snprintf(msg->cm_fields['R'], 256,
690 "room_%s@%s", CC->room.QRname,
692 for (i=0; msg->cm_fields['R'][i]; ++i) {
693 if (isspace(msg->cm_fields['R'][i])) {
694 msg->cm_fields['R'][i] = '_';
698 /* Handle delivery */
699 network_deliver_list(msg, sc);
700 CtdlFreeMessage(msg);
705 * Process digest recipients
707 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
708 msg = CtdlFetchMessage(msgnum, 1);
710 fprintf(sc->digestfp, " -----------------------------------"
711 "------------------------------------"
713 fprintf(sc->digestfp, "From: ");
714 if (msg->cm_fields['A'] != NULL) {
715 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
717 if (msg->cm_fields['F'] != NULL) {
718 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
720 else if (msg->cm_fields['N'] != NULL) {
721 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
723 fprintf(sc->digestfp, "\n");
724 if (msg->cm_fields['U'] != NULL) {
725 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
728 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
730 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
731 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
733 StrBufTrim(CC->redirect_buffer);
734 fwrite(HKEY("\n"), 1, sc->digestfp);
735 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
736 fwrite(HKEY("\n"), 1, sc->digestfp);
738 FreeStrBuf(&CC->redirect_buffer);
740 sc->num_msgs_spooled += 1;
746 * Process client-side list participations for this room
749 if (sc->participates != NULL) {
750 msg = CtdlFetchMessage(msgnum, 1);
753 /* Only send messages which originated on our own Citadel
754 * network, otherwise we'll end up sending the remote
755 * mailing list's messages back to it, which is rude...
757 ok_to_participate = 0;
758 if (msg->cm_fields['N'] != NULL) {
759 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
760 ok_to_participate = 1;
762 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
763 ok_to_participate = 1;
766 if (ok_to_participate) {
767 if (msg->cm_fields['F'] != NULL) {
768 free(msg->cm_fields['F']);
770 msg->cm_fields['F'] = malloc(SIZ);
771 /* Replace the Internet email address of the actual
772 * author with the email address of the room itself,
773 * so the remote listserv doesn't reject us.
774 * FIXME ... I want to be able to pick any address
776 snprintf(msg->cm_fields['F'], SIZ,
777 "room_%s@%s", CC->room.QRname,
779 for (i=0; msg->cm_fields['F'][i]; ++i) {
780 if (isspace(msg->cm_fields['F'][i])) {
781 msg->cm_fields['F'][i] = '_';
786 * Figure out how big a buffer we need to allocate
788 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
790 if (msg->cm_fields['R'] == NULL) {
791 free(msg->cm_fields['R']);
793 msg->cm_fields['R'] = strdup(nptr->name);
795 valid = validate_recipients(nptr->name, NULL, 0);
796 CtdlSubmitMsg(msg, valid, "", 0);
797 free_recipients(valid);
801 CtdlFreeMessage(msg);
806 * Process IGnet push shares
808 msg = CtdlFetchMessage(msgnum, 1);
812 /* Prepend our node name to the Path field whenever
813 * sending a message to another IGnet node
815 if (msg->cm_fields['P'] == NULL) {
816 msg->cm_fields['P'] = strdup("username");
818 newpath_len = strlen(msg->cm_fields['P']) +
819 strlen(config.c_nodename) + 2;
820 newpath = malloc(newpath_len);
821 snprintf(newpath, newpath_len, "%s!%s",
822 config.c_nodename, msg->cm_fields['P']);
823 free(msg->cm_fields['P']);
824 msg->cm_fields['P'] = newpath;
827 * Determine if this message is set to be deleted
828 * after sending out on the network
830 if (msg->cm_fields['S'] != NULL) {
831 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
832 delete_after_send = 1;
836 /* Now send it to every node */
837 if (sc->ignet_push_shares != NULL)
838 for (mptr = sc->ignet_push_shares; mptr != NULL;
843 /* Check for valid node name */
844 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
845 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
849 /* Check for split horizon */
850 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
851 bang = num_tokens(msg->cm_fields['P'], '!');
852 if (bang > 1) for (i=0; i<(bang-1); ++i) {
853 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
854 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
855 buf, mptr->remote_nodename) ;
856 if (!strcasecmp(buf, mptr->remote_nodename)) {
858 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
859 mptr->remote_nodename);
862 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
866 /* Send the message */
870 * Force the message to appear in the correct room
871 * on the far end by setting the C field correctly
873 if (msg->cm_fields['C'] != NULL) {
874 free(msg->cm_fields['C']);
876 if (!IsEmptyStr(mptr->remote_roomname)) {
877 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
880 msg->cm_fields['C'] = strdup(CC->room.QRname);
883 /* serialize it for transmission */
884 serialize_message(&sermsg, msg);
885 if (sermsg.len > 0) {
887 /* write it to a spool file */
888 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
890 mptr->remote_nodename,
894 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
895 fp = fopen(filename, "ab");
902 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
905 /* free the serialized version */
911 CtdlFreeMessage(msg);
914 /* update lastsent */
915 sc->lastsent = msgnum;
917 /* Delete this message if delete-after-send is set */
918 if (delete_after_send) {
919 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
925 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
931 char roomname[ROOMNAMELEN];
934 int skipthisline = 0;
935 namelist *nptr = NULL;
936 maplist *mptr = NULL;
939 fp = fopen(filename, "r");
943 sc = malloc(sizeof(SpoolControl));
944 memset(sc, 0, sizeof(SpoolControl));
947 while (fgets(buf, sizeof buf, fp) != NULL) {
948 buf[strlen(buf)-1] = 0;
950 extract_token(instr, buf, 0, '|', sizeof instr);
951 if (!strcasecmp(instr, strof(lastsent))) {
952 sc->lastsent = extract_long(buf, 1);
954 else if (!strcasecmp(instr, strof(listrecp))) {
956 malloc(sizeof(namelist));
957 nptr->next = sc->listrecps;
958 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
959 sc->listrecps = nptr;
961 else if (!strcasecmp(instr, strof(participate))) {
963 malloc(sizeof(namelist));
964 nptr->next = sc->participates;
965 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
966 sc->participates = nptr;
968 else if (!strcasecmp(instr, strof(digestrecp))) {
970 malloc(sizeof(namelist));
971 nptr->next = sc->digestrecps;
972 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
973 sc->digestrecps = nptr;
975 else if (!strcasecmp(instr, strof(ignet_push_share))) {
976 extract_token(nodename, buf, 1, '|', sizeof nodename);
977 extract_token(roomname, buf, 2, '|', sizeof roomname);
978 mptr = (maplist *) malloc(sizeof(maplist));
979 mptr->next = sc->ignet_push_shares;
980 strcpy(mptr->remote_nodename, nodename);
981 strcpy(mptr->remote_roomname, roomname);
982 sc->ignet_push_shares = mptr;
985 /* Preserve 'other' lines ... *unless* they happen to
986 * be subscribe/unsubscribe pendings with expired
990 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
991 if (time(NULL) - extract_long(buf, 4) > EXP) {
995 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
996 if (time(NULL) - extract_long(buf, 3) > EXP) {
1001 if (skipthisline == 0) {
1002 linesize = strlen(buf);
1003 sc->misc = realloc(sc->misc,
1004 (miscsize + linesize + 2) );
1005 sprintf(&sc->misc[miscsize], "%s\n", buf);
1006 miscsize = miscsize + linesize + 1;
1016 void free_spoolcontrol_struct(SpoolControl **scc)
1019 namelist *nptr = NULL;
1020 maplist *mptr = NULL;
1023 while (sc->listrecps != NULL) {
1024 nptr = sc->listrecps->next;
1025 free(sc->listrecps);
1026 sc->listrecps = nptr;
1028 /* Do the same for digestrecps */
1029 while (sc->digestrecps != NULL) {
1030 nptr = sc->digestrecps->next;
1031 free(sc->digestrecps);
1032 sc->digestrecps = nptr;
1034 /* Do the same for participates */
1035 while (sc->participates != NULL) {
1036 nptr = sc->participates->next;
1037 free(sc->participates);
1038 sc->participates = nptr;
1040 while (sc->ignet_push_shares != NULL) {
1041 mptr = sc->ignet_push_shares->next;
1042 free(sc->ignet_push_shares);
1043 sc->ignet_push_shares = mptr;
1050 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1054 namelist *nptr = NULL;
1055 maplist *mptr = NULL;
1058 fp = fopen(filename, "w");
1060 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1061 filename, strerror(errno));
1062 free_spoolcontrol_struct(scc);
1065 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1067 /* Write out the listrecps while freeing from memory at the
1068 * same time. Am I clever or what? :)
1070 while (sc->listrecps != NULL) {
1071 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1072 nptr = sc->listrecps->next;
1073 free(sc->listrecps);
1074 sc->listrecps = nptr;
1076 /* Do the same for digestrecps */
1077 while (sc->digestrecps != NULL) {
1078 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1079 nptr = sc->digestrecps->next;
1080 free(sc->digestrecps);
1081 sc->digestrecps = nptr;
1083 /* Do the same for participates */
1084 while (sc->participates != NULL) {
1085 fprintf(fp, "participate|%s\n", sc->participates->name);
1086 nptr = sc->participates->next;
1087 free(sc->participates);
1088 sc->participates = nptr;
1090 while (sc->ignet_push_shares != NULL) {
1091 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1092 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1093 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1096 mptr = sc->ignet_push_shares->next;
1097 free(sc->ignet_push_shares);
1098 sc->ignet_push_shares = mptr;
1100 if (sc->misc != NULL) {
1101 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1111 int is_recipient(SpoolControl *sc, const char *Name)
1117 nptr = sc->listrecps;
1118 while (nptr != NULL) {
1119 if (strncmp(Name, nptr->name, len)==0)
1123 /* Do the same for digestrecps */
1124 nptr = sc->digestrecps;
1125 while (nptr != NULL) {
1126 if (strncmp(Name, nptr->name, len)==0)
1130 /* Do the same for participates */
1131 nptr = sc->participates;
1132 while (nptr != NULL) {
1133 if (strncmp(Name, nptr->name, len)==0)
1142 * Batch up and send all outbound traffic from the current room
1144 void network_spoolout_room(char *room_to_spool) {
1146 char filename[PATH_MAX];
1151 * If the room doesn't exist, don't try to perform its networking tasks.
1152 * Normally this should never happen, but once in a while maybe a room gets
1153 * queued for networking and then deleted before it can happen.
1155 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1156 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1160 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1161 begin_critical_section(S_NETCONFIGS);
1163 /* Only do net processing for rooms that have netconfigs */
1164 if (!read_spoolcontrol_file(&sc, filename))
1166 end_critical_section(S_NETCONFIGS);
1169 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1171 /* If there are digest recipients, we have to build a digest */
1172 if (sc->digestrecps != NULL) {
1173 sc->digestfp = tmpfile();
1174 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1177 /* Do something useful */
1178 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1179 network_spool_msg, sc);
1181 /* If we wrote a digest, deliver it and then close it */
1182 snprintf(buf, sizeof buf, "room_%s@%s",
1183 CC->room.QRname, config.c_fqdn);
1184 for (i=0; buf[i]; ++i) {
1185 buf[i] = tolower(buf[i]);
1186 if (isspace(buf[i])) buf[i] = '_';
1188 if (sc->digestfp != NULL) {
1189 fprintf(sc->digestfp, " -----------------------------------"
1190 "------------------------------------"
1192 "You are subscribed to the '%s' "
1194 "To post to the list: %s\n",
1195 CC->room.QRname, buf
1197 network_deliver_digest(sc); /* deliver and close */
1200 /* Now rewrite the config file */
1201 writenfree_spoolcontrol_file (&sc, filename);
1202 end_critical_section(S_NETCONFIGS);
1208 * Send the *entire* contents of the current room to one specific network node,
1209 * ignoring anything we know about which messages have already undergone
1210 * network processing. This can be used to bring a new node into sync.
1212 int network_sync_to(char *target_node) {
1214 int num_spooled = 0;
1220 char filename[PATH_MAX];
1223 /* Grab the configuration line we're looking for */
1224 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1225 begin_critical_section(S_NETCONFIGS);
1226 fp = fopen(filename, "r");
1228 end_critical_section(S_NETCONFIGS);
1231 while (fgets(buf, sizeof buf, fp) != NULL) {
1232 buf[strlen(buf)-1] = 0;
1233 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1234 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1235 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1236 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1237 && (!strcasecmp(sc_node, target_node)) ) {
1240 /* Concise syntax because we don't need a full linked-list */
1241 memset(&sc, 0, sizeof(SpoolControl));
1242 sc.ignet_push_shares = (maplist *)
1243 malloc(sizeof(maplist));
1244 sc.ignet_push_shares->next = NULL;
1245 safestrncpy(sc.ignet_push_shares->remote_nodename,
1247 sizeof sc.ignet_push_shares->remote_nodename);
1248 safestrncpy(sc.ignet_push_shares->remote_roomname,
1250 sizeof sc.ignet_push_shares->remote_roomname);
1254 end_critical_section(S_NETCONFIGS);
1256 if (!found_node) return(-1);
1258 /* Send ALL messages */
1259 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1260 network_spool_msg, &sc);
1262 /* Concise cleanup because we know there's only one node in the sc */
1263 free(sc.ignet_push_shares);
1265 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1266 num_spooled, target_node);
1267 return(num_spooled);
1272 * Implements the NSYN command
1274 void cmd_nsyn(char *argbuf) {
1276 char target_node[256];
1278 if (CtdlAccessCheck(ac_aide)) return;
1280 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1281 num_spooled = network_sync_to(target_node);
1282 if (num_spooled >= 0) {
1283 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1286 cprintf("%d No such room/node share exists.\n",
1287 ERROR + ROOM_NOT_FOUND);
1294 * Batch up and send all outbound traffic from the current room
1296 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1297 struct RoomProcList *ptr;
1299 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1300 if (ptr == NULL) return;
1302 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1303 begin_critical_section(S_RPLIST);
1306 end_critical_section(S_RPLIST);
1309 void destroy_network_queue_room(void)
1311 struct RoomProcList *cur, *p;
1312 NetMap *nmcur, *nmp;
1315 begin_critical_section(S_RPLIST);
1323 end_critical_section(S_RPLIST);
1326 while (nmcur != NULL)
1333 if (working_ignetcfg != NULL)
1334 free (working_ignetcfg);
1335 working_ignetcfg = NULL;
1340 * Learn topology from path fields
1342 void network_learn_topology(char *node, char *path) {
1346 strcpy(nexthop, "");
1348 if (num_tokens(path, '!') < 3) return;
1349 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1350 if (!strcasecmp(nmptr->nodename, node)) {
1351 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1352 nmptr->lastcontact = time(NULL);
1358 /* If we got here then it's not in the map, so add it. */
1359 nmptr = (NetMap *) malloc(sizeof (NetMap));
1360 strcpy(nmptr->nodename, node);
1361 nmptr->lastcontact = time(NULL);
1362 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1363 nmptr->next = the_netmap;
1372 * Bounce a message back to the sender
1374 void network_bounce(struct CtdlMessage *msg, char *reason) {
1375 char *oldpath = NULL;
1377 char bouncesource[SIZ];
1378 char recipient[SIZ];
1379 struct recptypes *valid = NULL;
1380 char force_room[ROOMNAMELEN];
1381 static int serialnum = 0;
1384 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1386 if (msg == NULL) return;
1388 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1391 * Give it a fresh message ID
1393 if (msg->cm_fields['I'] != NULL) {
1394 free(msg->cm_fields['I']);
1396 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1397 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1398 msg->cm_fields['I'] = strdup(buf);
1401 * FIXME ... right now we're just sending a bounce; we really want to
1402 * include the text of the bounced message.
1404 if (msg->cm_fields['M'] != NULL) {
1405 free(msg->cm_fields['M']);
1407 msg->cm_fields['M'] = strdup(reason);
1408 msg->cm_format_type = 0;
1411 * Turn the message around
1413 if (msg->cm_fields['R'] == NULL) {
1414 free(msg->cm_fields['R']);
1417 if (msg->cm_fields['D'] == NULL) {
1418 free(msg->cm_fields['D']);
1421 snprintf(recipient, sizeof recipient, "%s@%s",
1422 msg->cm_fields['A'], msg->cm_fields['N']);
1424 if (msg->cm_fields['A'] == NULL) {
1425 free(msg->cm_fields['A']);
1428 if (msg->cm_fields['N'] == NULL) {
1429 free(msg->cm_fields['N']);
1432 if (msg->cm_fields['U'] == NULL) {
1433 free(msg->cm_fields['U']);
1436 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1437 msg->cm_fields['N'] = strdup(config.c_nodename);
1438 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1440 /* prepend our node to the path */
1441 if (msg->cm_fields['P'] != NULL) {
1442 oldpath = msg->cm_fields['P'];
1443 msg->cm_fields['P'] = NULL;
1446 oldpath = strdup("unknown_user");
1448 size = strlen(oldpath) + SIZ;
1449 msg->cm_fields['P'] = malloc(size);
1450 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1453 /* Now submit the message */
1454 valid = validate_recipients(recipient, NULL, 0);
1455 if (valid != NULL) if (valid->num_error != 0) {
1456 free_recipients(valid);
1459 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1460 strcpy(force_room, config.c_aideroom);
1463 strcpy(force_room, "");
1465 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1466 strcpy(force_room, config.c_aideroom);
1468 CtdlSubmitMsg(msg, valid, force_room, 0);
1471 if (valid != NULL) free_recipients(valid);
1472 CtdlFreeMessage(msg);
1473 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1480 * Process a buffer containing a single message from a single file
1481 * from the inbound queue
1483 void network_process_buffer(char *buffer, long size) {
1484 struct CtdlMessage *msg = NULL;
1487 struct recptypes *recp = NULL;
1488 char target_room[ROOMNAMELEN];
1489 struct ser_ret sermsg;
1490 char *oldpath = NULL;
1491 char filename[PATH_MAX];
1494 unsigned char firstbyte;
1495 unsigned char lastbyte;
1497 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1499 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1500 firstbyte = buffer[0];
1501 lastbyte = buffer[size-1];
1502 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1503 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1504 size, firstbyte, lastbyte);
1508 /* Set default target room to trash */
1509 strcpy(target_room, TWITROOM);
1511 /* Load the message into memory */
1512 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1513 memset(msg, 0, sizeof(struct CtdlMessage));
1514 msg->cm_magic = CTDLMESSAGE_MAGIC;
1515 msg->cm_anon_type = buffer[1];
1516 msg->cm_format_type = buffer[2];
1518 for (pos = 3; pos < size; ++pos) {
1519 field = buffer[pos];
1520 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1521 pos = pos + strlen(&buffer[(int)pos]);
1524 /* Check for message routing */
1525 if (msg->cm_fields['D'] != NULL) {
1526 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1528 /* route the message */
1529 strcpy(nexthop, "");
1530 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1531 /* prepend our node to the path */
1532 if (msg->cm_fields['P'] != NULL) {
1533 oldpath = msg->cm_fields['P'];
1534 msg->cm_fields['P'] = NULL;
1537 oldpath = strdup("unknown_user");
1539 size = strlen(oldpath) + SIZ;
1540 msg->cm_fields['P'] = malloc(size);
1541 snprintf(msg->cm_fields['P'], size, "%s!%s",
1542 config.c_nodename, oldpath);
1545 /* serialize the message */
1546 serialize_message(&sermsg, msg);
1549 if (IsEmptyStr(nexthop)) {
1550 strcpy(nexthop, msg->cm_fields['D']);
1560 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1561 fp = fopen(filename, "ab");
1563 fwrite(sermsg.ser, sermsg.len, 1, fp);
1567 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1570 CtdlFreeMessage(msg);
1574 else { /* invalid destination node name */
1577 "A message you sent could not be delivered due to an invalid destination node"
1578 " name. Please check the address and try sending the message again.\n");
1587 * Check to see if we already have a copy of this message, and
1588 * abort its processing if so. (We used to post a warning to Aide>
1589 * every time this happened, but the network is now so densely
1590 * connected that it's inevitable.)
1592 if (network_usetable(msg) != 0) {
1593 CtdlFreeMessage(msg);
1597 /* Learn network topology from the path */
1598 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1599 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1602 /* Is the sending node giving us a very persuasive suggestion about
1603 * which room this message should be saved in? If so, go with that.
1605 if (msg->cm_fields['C'] != NULL) {
1606 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1609 /* Otherwise, does it have a recipient? If so, validate it... */
1610 else if (msg->cm_fields['R'] != NULL) {
1611 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1612 if (recp != NULL) if (recp->num_error != 0) {
1614 "A message you sent could not be delivered due to an invalid address.\n"
1615 "Please check the address and try sending the message again.\n");
1617 free_recipients(recp);
1618 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1621 strcpy(target_room, ""); /* no target room if mail */
1624 /* Our last shot at finding a home for this message is to see if
1625 * it has the O field (Originating room) set.
1627 else if (msg->cm_fields['O'] != NULL) {
1628 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1631 /* Strip out fields that are only relevant during transit */
1632 if (msg->cm_fields['D'] != NULL) {
1633 free(msg->cm_fields['D']);
1634 msg->cm_fields['D'] = NULL;
1636 if (msg->cm_fields['C'] != NULL) {
1637 free(msg->cm_fields['C']);
1638 msg->cm_fields['C'] = NULL;
1641 /* save the message into a room */
1642 if (PerformNetprocHooks(msg, target_room) == 0) {
1643 msg->cm_flags = CM_SKIP_HOOKS;
1644 CtdlSubmitMsg(msg, recp, target_room, 0);
1646 CtdlFreeMessage(msg);
1647 free_recipients(recp);
1652 * Process a single message from a single file from the inbound queue
1654 void network_process_message(FILE *fp, long msgstart, long msgend) {
1659 hold_pos = ftell(fp);
1660 size = msgend - msgstart + 1;
1661 buffer = malloc(size);
1662 if (buffer != NULL) {
1663 fseek(fp, msgstart, SEEK_SET);
1664 if (fread(buffer, size, 1, fp) > 0) {
1665 network_process_buffer(buffer, size);
1670 fseek(fp, hold_pos, SEEK_SET);
1675 * Process a single file from the inbound queue
1677 void network_process_file(char *filename) {
1679 long msgstart = (-1L);
1680 long msgend = (-1L);
1685 fp = fopen(filename, "rb");
1687 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1691 fseek(fp, 0L, SEEK_END);
1692 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1695 /* Look for messages in the data stream and break them out */
1696 while (ch = getc(fp), ch >= 0) {
1699 if (msgstart >= 0L) {
1700 msgend = msgcur - 1;
1701 network_process_message(fp, msgstart, msgend);
1709 msgend = msgcur - 1;
1710 if (msgstart >= 0L) {
1711 network_process_message(fp, msgstart, msgend);
1720 * Process anything in the inbound queue
1722 void network_do_spoolin(void) {
1725 struct stat statbuf;
1726 char filename[PATH_MAX];
1727 static time_t last_spoolin_mtime = 0L;
1730 * Check the spoolin directory's modification time. If it hasn't
1731 * been touched, we don't need to scan it.
1733 if (stat(ctdl_netin_dir, &statbuf)) return;
1734 if (statbuf.st_mtime == last_spoolin_mtime) {
1735 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1738 last_spoolin_mtime = statbuf.st_mtime;
1739 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1742 * Ok, there's something interesting in there, so scan it.
1744 dp = opendir(ctdl_netin_dir);
1745 if (dp == NULL) return;
1747 while (d = readdir(dp), d != NULL) {
1748 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1755 network_process_file(filename);
1763 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1764 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1766 void network_consolidate_spoolout(void) {
1769 char filename[PATH_MAX];
1775 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1776 dp = opendir(ctdl_netout_dir);
1777 if (dp == NULL) return;
1778 while (d = readdir(dp), d != NULL) {
1780 (strcmp(d->d_name, "."))
1781 && (strcmp(d->d_name, ".."))
1782 && (strchr(d->d_name, '@') != NULL)
1784 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1785 ptr = strchr(nexthop, '@');
1795 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1796 if (network_talking_to(nexthop, NTT_CHECK)) {
1797 CtdlLogPrintf(CTDL_DEBUG,
1798 "Currently online with %s - skipping for now\n",
1803 network_talking_to(nexthop, NTT_ADD);
1804 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1806 ctdl_netout_dir, nexthop,
1810 network_talking_to(nexthop, NTT_REMOVE);
1816 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1818 dp = opendir(ctdl_netout_dir);
1819 if (dp == NULL) return;
1821 while (d = readdir(dp), d != NULL) {
1822 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1824 ptr = strchr(d->d_name, '@');
1834 strcpy(nexthop, "");
1835 i = is_valid_node(nexthop, NULL, d->d_name);
1837 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1848 * receive network spool from the remote system
1850 void receive_spool(int *sock, char *remote_nodename) {
1851 long download_len = 0L;
1852 long bytes_received = 0L;
1854 static char pbuf[IGNET_PACKET_SIZE];
1855 char tempfilename[PATH_MAX];
1856 char permfilename[PATH_MAX];
1860 snprintf(tempfilename,
1861 sizeof tempfilename,
1869 snprintf(permfilename,
1870 sizeof permfilename,
1878 if (sock_puts(sock, "NDOP") < 0) return;
1879 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1880 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1881 if (buf[0] != '2') {
1884 download_len = extract_long(&buf[4], 0);
1886 if (download_len>0) {
1887 bytes_received = 0L;
1888 fp = fopen(tempfilename, "w");
1890 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1895 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1896 while (bytes_received < download_len) {
1898 * If shutting down we can exit here and unlink the temp file.
1899 * this shouldn't loose us any messages.
1901 if (CtdlThreadCheckStop())
1904 unlink(tempfilename);
1907 snprintf(buf, sizeof buf, "READ %ld|%ld",
1909 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1910 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1912 if (sock_puts(sock, buf) < 0) {
1914 unlink(tempfilename);
1917 if (sock_getln(sock, buf, sizeof buf) < 0) {
1919 unlink(tempfilename);
1923 if (buf[0] == '6') {
1924 plen = extract_long(&buf[4], 0);
1925 if (sock_read(sock, pbuf, plen, 1) < 0) {
1927 unlink(tempfilename);
1930 fwrite((char *) pbuf, plen, 1, fp);
1931 bytes_received = bytes_received + plen;
1937 /* Last chance for shutdown exit */
1938 if (CtdlThreadCheckStop())
1940 unlink(tempfilename);
1944 if (sock_puts(sock, "CLOS") < 0) {
1945 unlink(tempfilename);
1950 * From here on we must complete or messages will get lost
1952 if (sock_getln(sock, buf, sizeof buf) < 0) {
1953 unlink(tempfilename);
1956 if (download_len > 0) {
1957 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1959 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1961 /* Now move the temp file to its permanent location.
1963 if (link(tempfilename, permfilename) != 0) {
1964 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
1965 tempfilename, permfilename, strerror(errno)
1968 unlink(tempfilename);
1974 * transmit network spool to the remote system
1976 void transmit_spool(int *sock, char *remote_nodename)
1981 long bytes_to_write, thisblock, bytes_written;
1985 if (sock_puts(sock, "NUOP") < 0) return;
1986 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1987 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1988 if (buf[0] != '2') {
1992 snprintf(sfname, sizeof sfname,
1997 fd = open(sfname, O_RDONLY);
1999 if (errno != ENOENT) {
2000 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2005 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2006 bytes_to_write = plen;
2007 while (bytes_to_write > 0L) {
2008 /* Exit if shutting down */
2009 if (CtdlThreadCheckStop())
2015 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2016 if (sock_puts(sock, buf) < 0) {
2020 if (sock_getln(sock, buf, sizeof buf) < 0) {
2024 thisblock = atol(&buf[4]);
2025 if (buf[0] == '7') {
2026 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2030 bytes_to_write -= thisblock;
2031 bytes_written += thisblock;
2041 /* Last chance for shutdown exit */
2042 if(CtdlThreadCheckStop())
2045 if (sock_puts(sock, "UCLS 1") < 0) return;
2048 * From here on we must complete or messages will get lost
2050 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2051 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2052 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2053 if (buf[0] == '2') {
2054 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2062 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2064 void network_poll_node(char *node, char *secret, char *host, char *port) {
2068 char connected_to[SIZ];
2071 if (network_talking_to(node, NTT_CHECK)) return;
2072 network_talking_to(node, NTT_ADD);
2073 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2074 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2076 sock = sock_connect(host, port);
2078 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2079 network_talking_to(node, NTT_REMOVE);
2083 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2084 CCC->sReadBuf = NewStrBuf();
2085 CCC->sMigrateBuf = NewStrBuf();
2088 /* Read the server greeting */
2089 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2090 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2092 /* Check that the remote is who we think it is and warn the Aide if not */
2093 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2094 if (strcmp(connected_to, node))
2096 snprintf(err_buf, sizeof(err_buf),
2097 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2100 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2101 CtdlAideMessage(err_buf, "Network error");
2104 /* We're talking to the correct node. Now identify ourselves. */
2105 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2106 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2107 if (sock_puts(&sock, buf) <0) goto bail;
2108 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2109 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2110 if (buf[0] != '2') {
2114 /* At this point we are authenticated. */
2115 if (!CtdlThreadCheckStop())
2116 receive_spool(&sock, node);
2117 if (!CtdlThreadCheckStop())
2118 transmit_spool(&sock, node);
2121 sock_puts(&sock, "QUIT");
2123 FreeStrBuf(&CCC->sReadBuf);
2124 FreeStrBuf(&CCC->sMigrateBuf);
2127 network_talking_to(node, NTT_REMOVE);
2133 * Poll other Citadel nodes and transfer inbound/outbound network data.
2134 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2135 * only nodes to which we have data to send.
2137 void network_poll_other_citadel_nodes(int full_poll) {
2145 char spoolfile[256];
2147 if (working_ignetcfg == NULL) {
2148 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2152 /* Use the string tokenizer to grab one line at a time */
2153 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2154 if(CtdlThreadCheckStop())
2156 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2157 extract_token(node, linebuf, 0, '|', sizeof node);
2158 extract_token(secret, linebuf, 1, '|', sizeof secret);
2159 extract_token(host, linebuf, 2, '|', sizeof host);
2160 extract_token(port, linebuf, 3, '|', sizeof port);
2161 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2162 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2171 if (access(spoolfile, R_OK) == 0) {
2176 network_poll_node(node, secret, host, port);
2187 * It's ok if these directories already exist. Just fail silently.
2189 void create_spool_dirs(void) {
2190 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2191 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2192 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2193 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2194 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2195 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2196 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2197 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2198 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2199 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2200 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2201 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2202 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2203 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2204 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2205 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2213 * network_do_queue()
2215 * Run through the rooms doing various types of network stuff.
2217 void *network_do_queue(void *args) {
2218 static time_t last_run = 0L;
2219 struct RoomProcList *ptr;
2220 int full_processing = 1;
2221 struct CitContext networkerCC;
2223 /* Give the networker its own private CitContext */
2224 CtdlFillSystemContext(&networkerCC, "network");
2225 citthread_setspecific(MyConKey, (void *)&networkerCC );
2228 * Run the full set of processing tasks no more frequently
2229 * than once every n seconds
2231 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2232 full_processing = 0;
2233 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2234 config.c_net_freq - (time(NULL)- last_run)
2239 * This is a simple concurrency check to make sure only one queue run
2240 * is done at a time. We could do this with a mutex, but since we
2241 * don't really require extremely fine granularity here, we'll do it
2242 * with a static variable instead.
2245 CtdlClearSystemContext();
2250 /* Load the IGnet Configuration into memory */
2251 load_working_ignetcfg();
2254 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2255 * then we poll everyone. Otherwise we only poll nodes we have stuff
2258 network_poll_other_citadel_nodes(full_processing);
2261 * Load the network map and filter list into memory.
2264 filterlist = load_filter_list();
2267 * Go ahead and run the queue
2269 if (full_processing && !CtdlThreadCheckStop()) {
2270 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2271 CtdlForEachRoom(network_queue_room, NULL);
2274 if (rplist != NULL) {
2275 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2276 while (rplist != NULL && !CtdlThreadCheckStop()) {
2277 char spoolroomname[ROOMNAMELEN];
2278 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2279 begin_critical_section(S_RPLIST);
2281 /* pop this record off the list */
2283 rplist = rplist->next;
2286 /* invalidate any duplicate entries to prevent double processing */
2287 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2288 if (!strcasecmp(ptr->name, spoolroomname)) {
2293 end_critical_section(S_RPLIST);
2294 if (spoolroomname[0] != 0) {
2295 network_spoolout_room(spoolroomname);
2300 /* If there is anything in the inbound queue, process it */
2301 if (!CtdlThreadCheckStop()) {
2302 network_do_spoolin();
2305 /* Save the network map back to disk */
2306 write_network_map();
2308 /* Free the filter list in memory */
2309 free_filter_list(filterlist);
2312 network_consolidate_spoolout();
2314 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2316 if (full_processing) {
2317 last_run = time(NULL);
2322 /* Reschedule this task to happen again periodically, unless the thread system indicates
2323 * that the server is shutting down.
2325 if (!CtdlThreadCheckStop()) {
2326 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK,
2327 network_do_queue, NULL, time(NULL) + 60
2331 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2333 CtdlClearSystemContext();
2339 * cmd_netp() - authenticate to the server as another Citadel node polling
2340 * for network traffic
2342 void cmd_netp(char *cmdbuf)
2353 extract_token(node, cmdbuf, 0, '|', sizeof node);
2354 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2356 /* load the IGnet Configuration to check node validity */
2357 load_working_ignetcfg();
2358 v = is_valid_node(nexthop, secret, node);
2361 snprintf(err_buf, sizeof err_buf,
2362 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2363 node, CC->cs_host, CC->cs_addr
2365 CtdlLogPrintf(CTDL_WARNING, err_buf);
2366 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2367 CtdlAideMessage(err_buf, "IGNet Networking.");
2371 if (strcasecmp(pass, secret)) {
2372 snprintf(err_buf, sizeof err_buf,
2373 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2374 CC->cs_host, CC->cs_addr, node
2376 CtdlLogPrintf(CTDL_WARNING, err_buf);
2377 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2378 CtdlAideMessage(err_buf, "IGNet Networking.");
2382 if (network_talking_to(node, NTT_CHECK)) {
2383 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2384 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2388 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2389 network_talking_to(node, NTT_ADD);
2390 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2391 CC->net_node, CC->cs_host, CC->cs_addr
2393 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2397 int network_room_handler (struct ctdlroom *room)
2399 network_queue_room(room, NULL);
2405 * Module entry point
2407 CTDL_MODULE_INIT(network)
2411 create_spool_dirs();
2412 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2413 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2414 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2415 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2416 CtdlRegisterRoomHook(network_room_handler);
2417 CtdlRegisterCleanupHook(destroy_network_queue_room);
2420 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2421 /* return our Subversion id for the Log */