4 * This module handles shared rooms, inter-Citadel mail, and outbound
5 * mailing list processing.
7 * Copyright (c) 2000-2010 by the citadel.org team
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
24 * This is a fairly high-level type of critical section. It ensures that no
25 * two threads work on the netconfigs files at the same time. Since we do
26 * so many things inside these, here are the rules:
27 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
28 * 2. Do *not* perform any I/O with the client during these sections.
33 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
34 * requests that have not been confirmed will be deleted.
36 #define EXP 259200 /* three days */
48 #include <sys/types.h>
50 #if TIME_WITH_SYS_TIME
51 # include <sys/time.h>
55 # include <sys/time.h>
64 #include <libcitadel.h>
67 #include "citserver.h"
73 #include "internet_addressing.h"
74 #include "serv_network.h"
75 #include "clientsocket.h"
77 #include "citadel_dirs.h"
86 #include "ctdl_module.h"
90 /* Nonzero while we are doing network processing */
91 static int doing_queue = 0;
94 * When we do network processing, it's accomplished in two passes; one to
95 * gather a list of rooms and one to actually do them. It's ok that rplist
96 * is global; we have a mutex that keeps it safe.
98 struct RoomProcList *rplist = NULL;
101 * We build a map of network nodes during processing.
103 NetMap *the_netmap = NULL;
104 int netmap_changed = 0;
105 char *working_ignetcfg = NULL;
108 * Load or refresh the Citadel network (IGnet) configuration for this node.
110 void load_working_ignetcfg(void) {
114 cfg = CtdlGetSysConfig(IGNETCFG);
119 oldcfg = working_ignetcfg;
120 working_ignetcfg = cfg;
121 if (oldcfg != NULL) {
131 * Keep track of what messages to reject
133 FilterList *load_filter_list(void) {
134 char *serialized_list = NULL;
137 FilterList *newlist = NULL;
140 serialized_list = CtdlGetSysConfig(FILTERLIST);
141 if (serialized_list == NULL) return(NULL); /* if null, no entries */
143 /* Use the string tokenizer to grab one line at a time */
144 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
145 extract_token(buf, serialized_list, i, '\n', sizeof buf);
146 nptr = (FilterList *) malloc(sizeof(FilterList));
147 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
148 striplt(nptr->fl_user);
149 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
150 striplt(nptr->fl_room);
151 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
152 striplt(nptr->fl_node);
154 /* Cowardly refuse to add an any/any/any entry that would
155 * end up filtering every single message.
157 if (IsEmptyStr(nptr->fl_user) &&
158 IsEmptyStr(nptr->fl_room) &&
159 IsEmptyStr(nptr->fl_node)) {
163 nptr->next = newlist;
168 free(serialized_list);
173 void free_filter_list(FilterList *fl) {
174 if (fl == NULL) return;
175 free_filter_list(fl->next);
182 * Check the use table. This is a list of messages which have recently
183 * arrived on the system. It is maintained and queried to prevent the same
184 * message from being entered into the database multiple times if it happens
185 * to arrive multiple times by accident.
187 int network_usetable(struct CtdlMessage *msg) {
190 struct cdbdata *cdbut;
193 /* Bail out if we can't generate a message ID */
197 if (msg->cm_fields['I'] == NULL) {
200 if (IsEmptyStr(msg->cm_fields['I'])) {
204 /* Generate the message ID */
205 strcpy(msgid, msg->cm_fields['I']);
206 if (haschar(msgid, '@') == 0) {
208 if (msg->cm_fields['N'] != NULL) {
209 strcat(msgid, msg->cm_fields['N']);
216 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
219 CtdlLogPrintf(CTDL_DEBUG, "network_usetable() : we already have %s\n", msgid);
223 /* If we got to this point, it's unique: add it. */
224 strcpy(ut.ut_msgid, msgid);
225 ut.ut_timestamp = time(NULL);
226 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
232 * Read the network map from its configuration file into memory.
234 void read_network_map(void) {
235 char *serialized_map = NULL;
240 serialized_map = CtdlGetSysConfig(IGNETMAP);
241 if (serialized_map == NULL) return; /* if null, no entries */
243 /* Use the string tokenizer to grab one line at a time */
244 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
245 extract_token(buf, serialized_map, i, '\n', sizeof buf);
246 nmptr = (NetMap *) malloc(sizeof(NetMap));
247 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
248 nmptr->lastcontact = extract_long(buf, 1);
249 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
250 nmptr->next = the_netmap;
254 free(serialized_map);
260 * Write the network map from memory back to the configuration file.
262 void write_network_map(void) {
263 char *serialized_map = NULL;
267 if (netmap_changed) {
268 serialized_map = strdup("");
270 if (the_netmap != NULL) {
271 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
272 serialized_map = realloc(serialized_map,
273 (strlen(serialized_map)+SIZ) );
274 if (!IsEmptyStr(nmptr->nodename)) {
275 snprintf(&serialized_map[strlen(serialized_map)],
279 (long)nmptr->lastcontact,
285 CtdlPutSysConfig(IGNETMAP, serialized_map);
286 free(serialized_map);
289 /* Now free the list */
290 while (the_netmap != NULL) {
291 nmptr = the_netmap->next;
301 * Check the network map and determine whether the supplied node name is
302 * valid. If it is not a neighbor node, supply the name of a neighbor node
303 * which is the next hop. If it *is* a neighbor node, we also fill in the
306 int is_valid_node(char *nexthop, char *secret, char *node) {
318 * First try the neighbor nodes
320 if (working_ignetcfg == NULL) {
321 CtdlLogPrintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
322 if (nexthop != NULL) {
329 if (nexthop != NULL) {
333 /* Use the string tokenizer to grab one line at a time */
334 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
335 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
336 extract_token(buf, linebuf, 0, '|', sizeof buf);
337 if (!strcasecmp(buf, node)) {
338 if (nexthop != NULL) {
341 if (secret != NULL) {
342 extract_token(secret, linebuf, 1, '|', 256);
349 return(retval); /* yup, it's a direct neighbor */
353 * If we get to this point we have to see if we know the next hop
355 if (the_netmap != NULL) {
356 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
357 if (!strcasecmp(nmptr->nodename, node)) {
358 if (nexthop != NULL) {
359 strcpy(nexthop, nmptr->nexthop);
367 * If we get to this point, the supplied node name is bogus.
369 CtdlLogPrintf(CTDL_ERR, "Invalid node name <%s>\n", node);
377 void cmd_gnet(char *argbuf) {
378 char filename[PATH_MAX];
382 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
383 /* users can edit the netconfigs for their own mailbox rooms */
385 else if (CtdlAccessCheck(ac_room_aide)) return;
387 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
388 cprintf("%d Network settings for room #%ld <%s>\n",
390 CC->room.QRnumber, CC->room.QRname);
392 fp = fopen(filename, "r");
394 while (fgets(buf, sizeof buf, fp) != NULL) {
395 buf[strlen(buf)-1] = 0;
396 cprintf("%s\n", buf);
405 void cmd_snet(char *argbuf) {
406 char tempfilename[PATH_MAX];
407 char filename[PATH_MAX];
413 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
414 /* users can edit the netconfigs for their own mailbox rooms */
416 else if (CtdlAccessCheck(ac_room_aide)) return;
418 CtdlMakeTempFileName(tempfilename, sizeof tempfilename);
419 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
421 fp = fopen(tempfilename, "w");
423 cprintf("%d Cannot open %s: %s\n",
424 ERROR + INTERNAL_ERROR,
429 cprintf("%d %s\n", SEND_LISTING, tempfilename);
430 while (client_getln(buf, sizeof buf) >= 0 && strcmp(buf, "000")) {
431 fprintf(fp, "%s\n", buf);
435 /* Now copy the temp file to its permanent location.
436 * (We copy instead of link because they may be on different filesystems)
438 begin_critical_section(S_NETCONFIGS);
439 fp = fopen(tempfilename, "r");
441 newfp = fopen(filename, "w");
443 while (fgets(buf, sizeof buf, fp) != NULL) {
444 fprintf(newfp, "%s", buf);
450 end_critical_section(S_NETCONFIGS);
451 unlink(tempfilename);
456 * Deliver digest messages
458 void network_deliver_digest(SpoolControl *sc) {
461 struct CtdlMessage *msg = NULL;
464 size_t recps_len = SIZ;
466 struct recptypes *valid;
470 if (sc->num_msgs_spooled < 1) {
471 fclose(sc->digestfp);
476 msg = malloc(sizeof(struct CtdlMessage));
477 memset(msg, 0, sizeof(struct CtdlMessage));
478 msg->cm_magic = CTDLMESSAGE_MAGIC;
479 msg->cm_format_type = FMT_RFC822;
480 msg->cm_anon_type = MES_NORMAL;
482 sprintf(buf, "%ld", time(NULL));
483 msg->cm_fields['T'] = strdup(buf);
484 msg->cm_fields['A'] = strdup(CC->room.QRname);
485 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
486 msg->cm_fields['U'] = strdup(buf);
487 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
488 for (i=0; buf[i]; ++i) {
489 if (isspace(buf[i])) buf[i]='_';
490 buf[i] = tolower(buf[i]);
492 msg->cm_fields['F'] = strdup(buf);
493 msg->cm_fields['R'] = strdup(buf);
495 /* Set the 'List-ID' header */
496 msg->cm_fields['L'] = malloc(1024);
497 snprintf(msg->cm_fields['L'], 1024,
498 "%s <%ld.list-id.%s>",
505 * Go fetch the contents of the digest
507 fseek(sc->digestfp, 0L, SEEK_END);
508 msglen = ftell(sc->digestfp);
510 msg->cm_fields['M'] = malloc(msglen + 1);
511 fseek(sc->digestfp, 0L, SEEK_SET);
512 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
513 msg->cm_fields['M'][msglen] = '\0';
515 fclose(sc->digestfp);
518 /* Now generate the delivery instructions */
521 * Figure out how big a buffer we need to allocate
523 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
524 recps_len = recps_len + strlen(nptr->name) + 2;
527 recps = malloc(recps_len);
530 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
537 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
538 if (nptr != sc->digestrecps) {
541 strcat(recps, nptr->name);
544 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
545 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
547 /* Now submit the message */
548 valid = validate_recipients(recps, NULL, 0);
551 valid->bounce_to = strdup(bounce_to);
552 valid->envelope_from = strdup(bounce_to);
553 CtdlSubmitMsg(msg, valid, NULL, 0);
555 CtdlFreeMessage(msg);
556 free_recipients(valid);
561 * Deliver list messages to everyone on the list ... efficiently
563 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
565 size_t recps_len = SIZ;
566 struct recptypes *valid;
570 /* Don't do this if there were no recipients! */
571 if (sc->listrecps == NULL) return;
573 /* Now generate the delivery instructions */
576 * Figure out how big a buffer we need to allocate
578 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
579 recps_len = recps_len + strlen(nptr->name) + 2;
582 recps = malloc(recps_len);
585 CtdlLogPrintf(CTDL_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
592 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
593 if (nptr != sc->listrecps) {
596 strcat(recps, nptr->name);
599 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
600 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
602 /* Now submit the message */
603 valid = validate_recipients(recps, NULL, 0);
606 valid->bounce_to = strdup(bounce_to);
607 valid->envelope_from = strdup(bounce_to);
608 CtdlSubmitMsg(msg, valid, NULL, 0);
609 free_recipients(valid);
611 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
618 * Spools out one message from the list.
620 void network_spool_msg(long msgnum, void *userdata) {
623 char *newpath = NULL;
624 size_t instr_len = SIZ;
625 struct CtdlMessage *msg = NULL;
628 struct ser_ret sermsg;
630 char filename[PATH_MAX];
634 int delete_after_send = 0; /* Set to 1 to delete after spooling */
635 int ok_to_participate = 0;
636 struct recptypes *valid;
638 sc = (SpoolControl *)userdata;
641 * Process mailing list recipients
644 if (sc->listrecps != NULL) {
645 /* Fetch the message. We're going to need to modify it
646 * in order to insert the [list name] in it, etc.
648 msg = CtdlFetchMessage(msgnum, 1);
650 if (msg->cm_fields['V'] == NULL){
651 /* local message, no enVelope */
654 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
655 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
656 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
658 msg->cm_fields['K'] = SmashStrBuf(&Buf);
661 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
663 /* Set the 'List-ID' header */
664 if (msg->cm_fields['L'] != NULL) {
665 free(msg->cm_fields['L']);
667 msg->cm_fields['L'] = malloc(1024);
668 snprintf(msg->cm_fields['L'], 1024,
669 "%s <%ld.list-id.%s>",
675 /* Prepend "[List name]" to the subject */
676 if (msg->cm_fields['U'] == NULL) {
677 msg->cm_fields['U'] = strdup("(no subject)");
679 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
680 free(msg->cm_fields['U']);
681 msg->cm_fields['U'] = strdup(buf);
683 /* Set the recipient of the list message to the
684 * email address of the room itself.
685 * FIXME ... I want to be able to pick any address
687 if (msg->cm_fields['R'] != NULL) {
688 free(msg->cm_fields['R']);
690 msg->cm_fields['R'] = malloc(256);
691 snprintf(msg->cm_fields['R'], 256,
692 "room_%s@%s", CC->room.QRname,
694 for (i=0; msg->cm_fields['R'][i]; ++i) {
695 if (isspace(msg->cm_fields['R'][i])) {
696 msg->cm_fields['R'][i] = '_';
700 /* Handle delivery */
701 network_deliver_list(msg, sc);
702 CtdlFreeMessage(msg);
707 * Process digest recipients
709 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
710 msg = CtdlFetchMessage(msgnum, 1);
712 fprintf(sc->digestfp, " -----------------------------------"
713 "------------------------------------"
715 fprintf(sc->digestfp, "From: ");
716 if (msg->cm_fields['A'] != NULL) {
717 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
719 if (msg->cm_fields['F'] != NULL) {
720 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
722 else if (msg->cm_fields['N'] != NULL) {
723 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
725 fprintf(sc->digestfp, "\n");
726 if (msg->cm_fields['U'] != NULL) {
727 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
730 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
732 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
733 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
735 StrBufTrim(CC->redirect_buffer);
736 fwrite(HKEY("\n"), 1, sc->digestfp);
737 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
738 fwrite(HKEY("\n"), 1, sc->digestfp);
740 FreeStrBuf(&CC->redirect_buffer);
742 sc->num_msgs_spooled += 1;
748 * Process client-side list participations for this room
751 if (sc->participates != NULL) {
752 msg = CtdlFetchMessage(msgnum, 1);
755 /* Only send messages which originated on our own Citadel
756 * network, otherwise we'll end up sending the remote
757 * mailing list's messages back to it, which is rude...
759 ok_to_participate = 0;
760 if (msg->cm_fields['N'] != NULL) {
761 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
762 ok_to_participate = 1;
764 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
765 ok_to_participate = 1;
768 if (ok_to_participate) {
769 if (msg->cm_fields['F'] != NULL) {
770 free(msg->cm_fields['F']);
772 msg->cm_fields['F'] = malloc(SIZ);
773 /* Replace the Internet email address of the actual
774 * author with the email address of the room itself,
775 * so the remote listserv doesn't reject us.
776 * FIXME ... I want to be able to pick any address
778 snprintf(msg->cm_fields['F'], SIZ,
779 "room_%s@%s", CC->room.QRname,
781 for (i=0; msg->cm_fields['F'][i]; ++i) {
782 if (isspace(msg->cm_fields['F'][i])) {
783 msg->cm_fields['F'][i] = '_';
788 * Figure out how big a buffer we need to allocate
790 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
792 if (msg->cm_fields['R'] == NULL) {
793 free(msg->cm_fields['R']);
795 msg->cm_fields['R'] = strdup(nptr->name);
797 valid = validate_recipients(nptr->name, NULL, 0);
798 CtdlSubmitMsg(msg, valid, "", 0);
799 free_recipients(valid);
803 CtdlFreeMessage(msg);
808 * Process IGnet push shares
810 msg = CtdlFetchMessage(msgnum, 1);
814 /* Prepend our node name to the Path field whenever
815 * sending a message to another IGnet node
817 if (msg->cm_fields['P'] == NULL) {
818 msg->cm_fields['P'] = strdup("username");
820 newpath_len = strlen(msg->cm_fields['P']) +
821 strlen(config.c_nodename) + 2;
822 newpath = malloc(newpath_len);
823 snprintf(newpath, newpath_len, "%s!%s",
824 config.c_nodename, msg->cm_fields['P']);
825 free(msg->cm_fields['P']);
826 msg->cm_fields['P'] = newpath;
829 * Determine if this message is set to be deleted
830 * after sending out on the network
832 if (msg->cm_fields['S'] != NULL) {
833 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
834 delete_after_send = 1;
838 /* Now send it to every node */
839 if (sc->ignet_push_shares != NULL)
840 for (mptr = sc->ignet_push_shares; mptr != NULL;
845 /* Check for valid node name */
846 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
847 CtdlLogPrintf(CTDL_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
851 /* Check for split horizon */
852 CtdlLogPrintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
853 bang = num_tokens(msg->cm_fields['P'], '!');
854 if (bang > 1) for (i=0; i<(bang-1); ++i) {
855 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
856 CtdlLogPrintf(CTDL_DEBUG, "Compare <%s> to <%s>\n",
857 buf, mptr->remote_nodename) ;
858 if (!strcasecmp(buf, mptr->remote_nodename)) {
860 CtdlLogPrintf(CTDL_DEBUG, "Not sending to %s\n",
861 mptr->remote_nodename);
864 CtdlLogPrintf(CTDL_DEBUG, "Sending to %s\n", mptr->remote_nodename);
868 /* Send the message */
872 * Force the message to appear in the correct room
873 * on the far end by setting the C field correctly
875 if (msg->cm_fields['C'] != NULL) {
876 free(msg->cm_fields['C']);
878 if (!IsEmptyStr(mptr->remote_roomname)) {
879 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
882 msg->cm_fields['C'] = strdup(CC->room.QRname);
885 /* serialize it for transmission */
886 serialize_message(&sermsg, msg);
887 if (sermsg.len > 0) {
889 /* write it to a spool file */
890 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
892 mptr->remote_nodename,
896 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
897 fp = fopen(filename, "ab");
904 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
907 /* free the serialized version */
913 CtdlFreeMessage(msg);
916 /* update lastsent */
917 sc->lastsent = msgnum;
919 /* Delete this message if delete-after-send is set */
920 if (delete_after_send) {
921 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
927 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
933 char roomname[ROOMNAMELEN];
936 int skipthisline = 0;
937 namelist *nptr = NULL;
938 maplist *mptr = NULL;
941 fp = fopen(filename, "r");
945 sc = malloc(sizeof(SpoolControl));
946 memset(sc, 0, sizeof(SpoolControl));
949 while (fgets(buf, sizeof buf, fp) != NULL) {
950 buf[strlen(buf)-1] = 0;
952 extract_token(instr, buf, 0, '|', sizeof instr);
953 if (!strcasecmp(instr, strof(lastsent))) {
954 sc->lastsent = extract_long(buf, 1);
956 else if (!strcasecmp(instr, strof(listrecp))) {
958 malloc(sizeof(namelist));
959 nptr->next = sc->listrecps;
960 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
961 sc->listrecps = nptr;
963 else if (!strcasecmp(instr, strof(participate))) {
965 malloc(sizeof(namelist));
966 nptr->next = sc->participates;
967 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
968 sc->participates = nptr;
970 else if (!strcasecmp(instr, strof(digestrecp))) {
972 malloc(sizeof(namelist));
973 nptr->next = sc->digestrecps;
974 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
975 sc->digestrecps = nptr;
977 else if (!strcasecmp(instr, strof(ignet_push_share))) {
978 extract_token(nodename, buf, 1, '|', sizeof nodename);
979 extract_token(roomname, buf, 2, '|', sizeof roomname);
980 mptr = (maplist *) malloc(sizeof(maplist));
981 mptr->next = sc->ignet_push_shares;
982 strcpy(mptr->remote_nodename, nodename);
983 strcpy(mptr->remote_roomname, roomname);
984 sc->ignet_push_shares = mptr;
987 /* Preserve 'other' lines ... *unless* they happen to
988 * be subscribe/unsubscribe pendings with expired
992 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
993 if (time(NULL) - extract_long(buf, 4) > EXP) {
997 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
998 if (time(NULL) - extract_long(buf, 3) > EXP) {
1003 if (skipthisline == 0) {
1004 linesize = strlen(buf);
1005 sc->misc = realloc(sc->misc,
1006 (miscsize + linesize + 2) );
1007 sprintf(&sc->misc[miscsize], "%s\n", buf);
1008 miscsize = miscsize + linesize + 1;
1018 void free_spoolcontrol_struct(SpoolControl **scc)
1021 namelist *nptr = NULL;
1022 maplist *mptr = NULL;
1025 while (sc->listrecps != NULL) {
1026 nptr = sc->listrecps->next;
1027 free(sc->listrecps);
1028 sc->listrecps = nptr;
1030 /* Do the same for digestrecps */
1031 while (sc->digestrecps != NULL) {
1032 nptr = sc->digestrecps->next;
1033 free(sc->digestrecps);
1034 sc->digestrecps = nptr;
1036 /* Do the same for participates */
1037 while (sc->participates != NULL) {
1038 nptr = sc->participates->next;
1039 free(sc->participates);
1040 sc->participates = nptr;
1042 while (sc->ignet_push_shares != NULL) {
1043 mptr = sc->ignet_push_shares->next;
1044 free(sc->ignet_push_shares);
1045 sc->ignet_push_shares = mptr;
1052 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1056 namelist *nptr = NULL;
1057 maplist *mptr = NULL;
1060 fp = fopen(filename, "w");
1062 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1063 filename, strerror(errno));
1064 free_spoolcontrol_struct(scc);
1067 fprintf(fp, "lastsent|%ld\n", sc->lastsent);
1069 /* Write out the listrecps while freeing from memory at the
1070 * same time. Am I clever or what? :)
1072 while (sc->listrecps != NULL) {
1073 fprintf(fp, "listrecp|%s\n", sc->listrecps->name);
1074 nptr = sc->listrecps->next;
1075 free(sc->listrecps);
1076 sc->listrecps = nptr;
1078 /* Do the same for digestrecps */
1079 while (sc->digestrecps != NULL) {
1080 fprintf(fp, "digestrecp|%s\n", sc->digestrecps->name);
1081 nptr = sc->digestrecps->next;
1082 free(sc->digestrecps);
1083 sc->digestrecps = nptr;
1085 /* Do the same for participates */
1086 while (sc->participates != NULL) {
1087 fprintf(fp, "participate|%s\n", sc->participates->name);
1088 nptr = sc->participates->next;
1089 free(sc->participates);
1090 sc->participates = nptr;
1092 while (sc->ignet_push_shares != NULL) {
1093 fprintf(fp, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1094 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1095 fprintf(fp, "|%s", sc->ignet_push_shares->remote_roomname);
1098 mptr = sc->ignet_push_shares->next;
1099 free(sc->ignet_push_shares);
1100 sc->ignet_push_shares = mptr;
1102 if (sc->misc != NULL) {
1103 fwrite(sc->misc, strlen(sc->misc), 1, fp);
1113 int is_recipient(SpoolControl *sc, const char *Name)
1119 nptr = sc->listrecps;
1120 while (nptr != NULL) {
1121 if (strncmp(Name, nptr->name, len)==0)
1125 /* Do the same for digestrecps */
1126 nptr = sc->digestrecps;
1127 while (nptr != NULL) {
1128 if (strncmp(Name, nptr->name, len)==0)
1132 /* Do the same for participates */
1133 nptr = sc->participates;
1134 while (nptr != NULL) {
1135 if (strncmp(Name, nptr->name, len)==0)
1144 * Batch up and send all outbound traffic from the current room
1146 void network_spoolout_room(char *room_to_spool) {
1148 char filename[PATH_MAX];
1153 * If the room doesn't exist, don't try to perform its networking tasks.
1154 * Normally this should never happen, but once in a while maybe a room gets
1155 * queued for networking and then deleted before it can happen.
1157 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1158 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1162 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1163 begin_critical_section(S_NETCONFIGS);
1165 /* Only do net processing for rooms that have netconfigs */
1166 if (!read_spoolcontrol_file(&sc, filename))
1168 end_critical_section(S_NETCONFIGS);
1171 CtdlLogPrintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
1173 /* If there are digest recipients, we have to build a digest */
1174 if (sc->digestrecps != NULL) {
1175 sc->digestfp = tmpfile();
1176 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1179 /* Do something useful */
1180 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1181 network_spool_msg, sc);
1183 /* If we wrote a digest, deliver it and then close it */
1184 snprintf(buf, sizeof buf, "room_%s@%s",
1185 CC->room.QRname, config.c_fqdn);
1186 for (i=0; buf[i]; ++i) {
1187 buf[i] = tolower(buf[i]);
1188 if (isspace(buf[i])) buf[i] = '_';
1190 if (sc->digestfp != NULL) {
1191 fprintf(sc->digestfp, " -----------------------------------"
1192 "------------------------------------"
1194 "You are subscribed to the '%s' "
1196 "To post to the list: %s\n",
1197 CC->room.QRname, buf
1199 network_deliver_digest(sc); /* deliver and close */
1202 /* Now rewrite the config file */
1203 writenfree_spoolcontrol_file (&sc, filename);
1204 end_critical_section(S_NETCONFIGS);
1210 * Send the *entire* contents of the current room to one specific network node,
1211 * ignoring anything we know about which messages have already undergone
1212 * network processing. This can be used to bring a new node into sync.
1214 int network_sync_to(char *target_node) {
1216 int num_spooled = 0;
1222 char filename[PATH_MAX];
1225 /* Grab the configuration line we're looking for */
1226 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1227 begin_critical_section(S_NETCONFIGS);
1228 fp = fopen(filename, "r");
1230 end_critical_section(S_NETCONFIGS);
1233 while (fgets(buf, sizeof buf, fp) != NULL) {
1234 buf[strlen(buf)-1] = 0;
1235 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1236 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1237 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1238 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1239 && (!strcasecmp(sc_node, target_node)) ) {
1242 /* Concise syntax because we don't need a full linked-list */
1243 memset(&sc, 0, sizeof(SpoolControl));
1244 sc.ignet_push_shares = (maplist *)
1245 malloc(sizeof(maplist));
1246 sc.ignet_push_shares->next = NULL;
1247 safestrncpy(sc.ignet_push_shares->remote_nodename,
1249 sizeof sc.ignet_push_shares->remote_nodename);
1250 safestrncpy(sc.ignet_push_shares->remote_roomname,
1252 sizeof sc.ignet_push_shares->remote_roomname);
1256 end_critical_section(S_NETCONFIGS);
1258 if (!found_node) return(-1);
1260 /* Send ALL messages */
1261 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1262 network_spool_msg, &sc);
1264 /* Concise cleanup because we know there's only one node in the sc */
1265 free(sc.ignet_push_shares);
1267 CtdlLogPrintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1268 num_spooled, target_node);
1269 return(num_spooled);
1274 * Implements the NSYN command
1276 void cmd_nsyn(char *argbuf) {
1278 char target_node[256];
1280 if (CtdlAccessCheck(ac_aide)) return;
1282 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1283 num_spooled = network_sync_to(target_node);
1284 if (num_spooled >= 0) {
1285 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1288 cprintf("%d No such room/node share exists.\n",
1289 ERROR + ROOM_NOT_FOUND);
1296 * Batch up and send all outbound traffic from the current room
1298 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1299 struct RoomProcList *ptr;
1301 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1302 if (ptr == NULL) return;
1304 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1305 begin_critical_section(S_RPLIST);
1308 end_critical_section(S_RPLIST);
1311 void destroy_network_queue_room(void)
1313 struct RoomProcList *cur, *p;
1314 NetMap *nmcur, *nmp;
1317 begin_critical_section(S_RPLIST);
1325 end_critical_section(S_RPLIST);
1328 while (nmcur != NULL)
1335 if (working_ignetcfg != NULL)
1336 free (working_ignetcfg);
1337 working_ignetcfg = NULL;
1342 * Learn topology from path fields
1344 void network_learn_topology(char *node, char *path) {
1348 strcpy(nexthop, "");
1350 if (num_tokens(path, '!') < 3) return;
1351 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1352 if (!strcasecmp(nmptr->nodename, node)) {
1353 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1354 nmptr->lastcontact = time(NULL);
1360 /* If we got here then it's not in the map, so add it. */
1361 nmptr = (NetMap *) malloc(sizeof (NetMap));
1362 strcpy(nmptr->nodename, node);
1363 nmptr->lastcontact = time(NULL);
1364 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1365 nmptr->next = the_netmap;
1374 * Bounce a message back to the sender
1376 void network_bounce(struct CtdlMessage *msg, char *reason) {
1377 char *oldpath = NULL;
1379 char bouncesource[SIZ];
1380 char recipient[SIZ];
1381 struct recptypes *valid = NULL;
1382 char force_room[ROOMNAMELEN];
1383 static int serialnum = 0;
1386 CtdlLogPrintf(CTDL_DEBUG, "entering network_bounce()\n");
1388 if (msg == NULL) return;
1390 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1393 * Give it a fresh message ID
1395 if (msg->cm_fields['I'] != NULL) {
1396 free(msg->cm_fields['I']);
1398 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1399 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1400 msg->cm_fields['I'] = strdup(buf);
1403 * FIXME ... right now we're just sending a bounce; we really want to
1404 * include the text of the bounced message.
1406 if (msg->cm_fields['M'] != NULL) {
1407 free(msg->cm_fields['M']);
1409 msg->cm_fields['M'] = strdup(reason);
1410 msg->cm_format_type = 0;
1413 * Turn the message around
1415 if (msg->cm_fields['R'] == NULL) {
1416 free(msg->cm_fields['R']);
1419 if (msg->cm_fields['D'] == NULL) {
1420 free(msg->cm_fields['D']);
1423 snprintf(recipient, sizeof recipient, "%s@%s",
1424 msg->cm_fields['A'], msg->cm_fields['N']);
1426 if (msg->cm_fields['A'] == NULL) {
1427 free(msg->cm_fields['A']);
1430 if (msg->cm_fields['N'] == NULL) {
1431 free(msg->cm_fields['N']);
1434 if (msg->cm_fields['U'] == NULL) {
1435 free(msg->cm_fields['U']);
1438 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1439 msg->cm_fields['N'] = strdup(config.c_nodename);
1440 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1442 /* prepend our node to the path */
1443 if (msg->cm_fields['P'] != NULL) {
1444 oldpath = msg->cm_fields['P'];
1445 msg->cm_fields['P'] = NULL;
1448 oldpath = strdup("unknown_user");
1450 size = strlen(oldpath) + SIZ;
1451 msg->cm_fields['P'] = malloc(size);
1452 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1455 /* Now submit the message */
1456 valid = validate_recipients(recipient, NULL, 0);
1457 if (valid != NULL) if (valid->num_error != 0) {
1458 free_recipients(valid);
1461 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1462 strcpy(force_room, config.c_aideroom);
1465 strcpy(force_room, "");
1467 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1468 strcpy(force_room, config.c_aideroom);
1470 CtdlSubmitMsg(msg, valid, force_room, 0);
1473 if (valid != NULL) free_recipients(valid);
1474 CtdlFreeMessage(msg);
1475 CtdlLogPrintf(CTDL_DEBUG, "leaving network_bounce()\n");
1482 * Process a buffer containing a single message from a single file
1483 * from the inbound queue
1485 void network_process_buffer(char *buffer, long size) {
1486 struct CtdlMessage *msg = NULL;
1489 struct recptypes *recp = NULL;
1490 char target_room[ROOMNAMELEN];
1491 struct ser_ret sermsg;
1492 char *oldpath = NULL;
1493 char filename[PATH_MAX];
1496 unsigned char firstbyte;
1497 unsigned char lastbyte;
1499 CtdlLogPrintf(CTDL_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1501 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1502 firstbyte = buffer[0];
1503 lastbyte = buffer[size-1];
1504 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1505 CtdlLogPrintf(CTDL_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1506 size, firstbyte, lastbyte);
1510 /* Set default target room to trash */
1511 strcpy(target_room, TWITROOM);
1513 /* Load the message into memory */
1514 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1515 memset(msg, 0, sizeof(struct CtdlMessage));
1516 msg->cm_magic = CTDLMESSAGE_MAGIC;
1517 msg->cm_anon_type = buffer[1];
1518 msg->cm_format_type = buffer[2];
1520 for (pos = 3; pos < size; ++pos) {
1521 field = buffer[pos];
1522 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1523 pos = pos + strlen(&buffer[(int)pos]);
1526 /* Check for message routing */
1527 if (msg->cm_fields['D'] != NULL) {
1528 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1530 /* route the message */
1531 strcpy(nexthop, "");
1532 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1533 /* prepend our node to the path */
1534 if (msg->cm_fields['P'] != NULL) {
1535 oldpath = msg->cm_fields['P'];
1536 msg->cm_fields['P'] = NULL;
1539 oldpath = strdup("unknown_user");
1541 size = strlen(oldpath) + SIZ;
1542 msg->cm_fields['P'] = malloc(size);
1543 snprintf(msg->cm_fields['P'], size, "%s!%s",
1544 config.c_nodename, oldpath);
1547 /* serialize the message */
1548 serialize_message(&sermsg, msg);
1551 if (IsEmptyStr(nexthop)) {
1552 strcpy(nexthop, msg->cm_fields['D']);
1562 CtdlLogPrintf(CTDL_DEBUG, "Appending to %s\n", filename);
1563 fp = fopen(filename, "ab");
1565 fwrite(sermsg.ser, sermsg.len, 1, fp);
1569 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1572 CtdlFreeMessage(msg);
1576 else { /* invalid destination node name */
1579 "A message you sent could not be delivered due to an invalid destination node"
1580 " name. Please check the address and try sending the message again.\n");
1589 * Check to see if we already have a copy of this message, and
1590 * abort its processing if so. (We used to post a warning to Aide>
1591 * every time this happened, but the network is now so densely
1592 * connected that it's inevitable.)
1594 if (network_usetable(msg) != 0) {
1595 CtdlFreeMessage(msg);
1599 /* Learn network topology from the path */
1600 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1601 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1604 /* Is the sending node giving us a very persuasive suggestion about
1605 * which room this message should be saved in? If so, go with that.
1607 if (msg->cm_fields['C'] != NULL) {
1608 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1611 /* Otherwise, does it have a recipient? If so, validate it... */
1612 else if (msg->cm_fields['R'] != NULL) {
1613 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1614 if (recp != NULL) if (recp->num_error != 0) {
1616 "A message you sent could not be delivered due to an invalid address.\n"
1617 "Please check the address and try sending the message again.\n");
1619 free_recipients(recp);
1620 CtdlLogPrintf(CTDL_DEBUG, "Bouncing message due to invalid recipient address.\n");
1623 strcpy(target_room, ""); /* no target room if mail */
1626 /* Our last shot at finding a home for this message is to see if
1627 * it has the O field (Originating room) set.
1629 else if (msg->cm_fields['O'] != NULL) {
1630 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1633 /* Strip out fields that are only relevant during transit */
1634 if (msg->cm_fields['D'] != NULL) {
1635 free(msg->cm_fields['D']);
1636 msg->cm_fields['D'] = NULL;
1638 if (msg->cm_fields['C'] != NULL) {
1639 free(msg->cm_fields['C']);
1640 msg->cm_fields['C'] = NULL;
1643 /* save the message into a room */
1644 if (PerformNetprocHooks(msg, target_room) == 0) {
1645 msg->cm_flags = CM_SKIP_HOOKS;
1646 CtdlSubmitMsg(msg, recp, target_room, 0);
1648 CtdlFreeMessage(msg);
1649 free_recipients(recp);
1654 * Process a single message from a single file from the inbound queue
1656 void network_process_message(FILE *fp, long msgstart, long msgend) {
1661 hold_pos = ftell(fp);
1662 size = msgend - msgstart + 1;
1663 buffer = malloc(size);
1664 if (buffer != NULL) {
1665 fseek(fp, msgstart, SEEK_SET);
1666 if (fread(buffer, size, 1, fp) > 0) {
1667 network_process_buffer(buffer, size);
1672 fseek(fp, hold_pos, SEEK_SET);
1677 * Process a single file from the inbound queue
1679 void network_process_file(char *filename) {
1681 long msgstart = (-1L);
1682 long msgend = (-1L);
1687 fp = fopen(filename, "rb");
1689 CtdlLogPrintf(CTDL_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1693 fseek(fp, 0L, SEEK_END);
1694 CtdlLogPrintf(CTDL_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1697 /* Look for messages in the data stream and break them out */
1698 while (ch = getc(fp), ch >= 0) {
1701 if (msgstart >= 0L) {
1702 msgend = msgcur - 1;
1703 network_process_message(fp, msgstart, msgend);
1711 msgend = msgcur - 1;
1712 if (msgstart >= 0L) {
1713 network_process_message(fp, msgstart, msgend);
1722 * Process anything in the inbound queue
1724 void network_do_spoolin(void) {
1727 struct stat statbuf;
1728 char filename[PATH_MAX];
1729 static time_t last_spoolin_mtime = 0L;
1732 * Check the spoolin directory's modification time. If it hasn't
1733 * been touched, we don't need to scan it.
1735 if (stat(ctdl_netin_dir, &statbuf)) return;
1736 if (statbuf.st_mtime == last_spoolin_mtime) {
1737 CtdlLogPrintf(CTDL_DEBUG, "network: nothing in inbound queue\n");
1740 last_spoolin_mtime = statbuf.st_mtime;
1741 CtdlLogPrintf(CTDL_DEBUG, "network: processing inbound queue\n");
1744 * Ok, there's something interesting in there, so scan it.
1746 dp = opendir(ctdl_netin_dir);
1747 if (dp == NULL) return;
1749 while (d = readdir(dp), d != NULL) {
1750 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1757 network_process_file(filename);
1765 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1766 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1768 void network_consolidate_spoolout(void) {
1771 char filename[PATH_MAX];
1777 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1778 dp = opendir(ctdl_netout_dir);
1779 if (dp == NULL) return;
1780 while (d = readdir(dp), d != NULL) {
1782 (strcmp(d->d_name, "."))
1783 && (strcmp(d->d_name, ".."))
1784 && (strchr(d->d_name, '@') != NULL)
1786 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1787 ptr = strchr(nexthop, '@');
1797 CtdlLogPrintf(CTDL_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1798 if (network_talking_to(nexthop, NTT_CHECK)) {
1799 CtdlLogPrintf(CTDL_DEBUG,
1800 "Currently online with %s - skipping for now\n",
1805 network_talking_to(nexthop, NTT_ADD);
1806 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1808 ctdl_netout_dir, nexthop,
1812 network_talking_to(nexthop, NTT_REMOVE);
1818 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1820 dp = opendir(ctdl_netout_dir);
1821 if (dp == NULL) return;
1823 while (d = readdir(dp), d != NULL) {
1824 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1826 ptr = strchr(d->d_name, '@');
1836 strcpy(nexthop, "");
1837 i = is_valid_node(nexthop, NULL, d->d_name);
1839 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1850 * receive network spool from the remote system
1852 void receive_spool(int *sock, char *remote_nodename) {
1853 long download_len = 0L;
1854 long bytes_received = 0L;
1856 static char pbuf[IGNET_PACKET_SIZE];
1857 char tempfilename[PATH_MAX];
1858 char permfilename[PATH_MAX];
1862 snprintf(tempfilename,
1863 sizeof tempfilename,
1871 snprintf(permfilename,
1872 sizeof permfilename,
1880 if (sock_puts(sock, "NDOP") < 0) return;
1881 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1882 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1883 if (buf[0] != '2') {
1886 download_len = extract_long(&buf[4], 0);
1888 if (download_len>0) {
1889 bytes_received = 0L;
1890 fp = fopen(tempfilename, "w");
1892 CtdlLogPrintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1897 CtdlLogPrintf(CTDL_DEBUG, "For this download we are expecting %d bytes\n", download_len);
1898 while (bytes_received < download_len) {
1900 * If shutting down we can exit here and unlink the temp file.
1901 * this shouldn't loose us any messages.
1903 if (CtdlThreadCheckStop())
1906 unlink(tempfilename);
1909 snprintf(buf, sizeof buf, "READ %ld|%ld",
1911 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1912 ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1914 if (sock_puts(sock, buf) < 0) {
1916 unlink(tempfilename);
1919 if (sock_getln(sock, buf, sizeof buf) < 0) {
1921 unlink(tempfilename);
1925 if (buf[0] == '6') {
1926 plen = extract_long(&buf[4], 0);
1927 if (sock_read(sock, pbuf, plen, 1) < 0) {
1929 unlink(tempfilename);
1932 fwrite((char *) pbuf, plen, 1, fp);
1933 bytes_received = bytes_received + plen;
1939 /* Last chance for shutdown exit */
1940 if (CtdlThreadCheckStop())
1942 unlink(tempfilename);
1946 if (sock_puts(sock, "CLOS") < 0) {
1947 unlink(tempfilename);
1952 * From here on we must complete or messages will get lost
1954 if (sock_getln(sock, buf, sizeof buf) < 0) {
1955 unlink(tempfilename);
1958 if (download_len > 0) {
1959 CtdlLogPrintf(CTDL_NOTICE, "Received %ld octets from <%s>\n", download_len, remote_nodename);
1961 CtdlLogPrintf(CTDL_DEBUG, "%s\n", buf);
1963 /* Now move the temp file to its permanent location.
1965 if (link(tempfilename, permfilename) != 0) {
1966 CtdlLogPrintf(CTDL_ALERT, "Could not link %s to %s: %s\n",
1967 tempfilename, permfilename, strerror(errno)
1970 unlink(tempfilename);
1976 * transmit network spool to the remote system
1978 void transmit_spool(int *sock, char *remote_nodename)
1983 long bytes_to_write, thisblock, bytes_written;
1987 if (sock_puts(sock, "NUOP") < 0) return;
1988 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1989 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
1990 if (buf[0] != '2') {
1994 snprintf(sfname, sizeof sfname,
1999 fd = open(sfname, O_RDONLY);
2001 if (errno != ENOENT) {
2002 CtdlLogPrintf(CTDL_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2007 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2008 bytes_to_write = plen;
2009 while (bytes_to_write > 0L) {
2010 /* Exit if shutting down */
2011 if (CtdlThreadCheckStop())
2017 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2018 if (sock_puts(sock, buf) < 0) {
2022 if (sock_getln(sock, buf, sizeof buf) < 0) {
2026 thisblock = atol(&buf[4]);
2027 if (buf[0] == '7') {
2028 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2032 bytes_to_write -= thisblock;
2033 bytes_written += thisblock;
2043 /* Last chance for shutdown exit */
2044 if(CtdlThreadCheckStop())
2047 if (sock_puts(sock, "UCLS 1") < 0) return;
2050 * From here on we must complete or messages will get lost
2052 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2053 CtdlLogPrintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2054 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2055 if (buf[0] == '2') {
2056 CtdlLogPrintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
2064 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2066 void network_poll_node(char *node, char *secret, char *host, char *port) {
2070 char connected_to[SIZ];
2073 if (network_talking_to(node, NTT_CHECK)) return;
2074 network_talking_to(node, NTT_ADD);
2075 CtdlLogPrintf(CTDL_DEBUG, "network: polling <%s>\n", node);
2076 CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2078 sock = sock_connect(host, port);
2080 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
2081 network_talking_to(node, NTT_REMOVE);
2085 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
2086 CCC->sReadBuf = NewStrBuf();
2087 CCC->sMigrateBuf = NewStrBuf();
2090 /* Read the server greeting */
2091 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2092 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2094 /* Check that the remote is who we think it is and warn the Aide if not */
2095 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2096 if (strcmp(connected_to, node))
2098 snprintf(err_buf, sizeof(err_buf),
2099 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2102 CtdlLogPrintf(CTDL_ERR, "%s\n", err_buf);
2103 CtdlAideMessage(err_buf, "Network error");
2106 /* We're talking to the correct node. Now identify ourselves. */
2107 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2108 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
2109 if (sock_puts(&sock, buf) <0) goto bail;
2110 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2111 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
2112 if (buf[0] != '2') {
2116 /* At this point we are authenticated. */
2117 if (!CtdlThreadCheckStop())
2118 receive_spool(&sock, node);
2119 if (!CtdlThreadCheckStop())
2120 transmit_spool(&sock, node);
2123 sock_puts(&sock, "QUIT");
2125 FreeStrBuf(&CCC->sReadBuf);
2126 FreeStrBuf(&CCC->sMigrateBuf);
2129 network_talking_to(node, NTT_REMOVE);
2135 * Poll other Citadel nodes and transfer inbound/outbound network data.
2136 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2137 * only nodes to which we have data to send.
2139 void network_poll_other_citadel_nodes(int full_poll) {
2147 char spoolfile[256];
2149 if (working_ignetcfg == NULL) {
2150 CtdlLogPrintf(CTDL_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2154 /* Use the string tokenizer to grab one line at a time */
2155 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2156 if(CtdlThreadCheckStop())
2158 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2159 extract_token(node, linebuf, 0, '|', sizeof node);
2160 extract_token(secret, linebuf, 1, '|', sizeof secret);
2161 extract_token(host, linebuf, 2, '|', sizeof host);
2162 extract_token(port, linebuf, 3, '|', sizeof port);
2163 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2164 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2173 if (access(spoolfile, R_OK) == 0) {
2178 network_poll_node(node, secret, host, port);
2189 * It's ok if these directories already exist. Just fail silently.
2191 void create_spool_dirs(void) {
2192 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2193 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2194 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2195 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2196 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2197 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2198 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2199 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2200 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2201 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2202 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2203 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2204 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2205 CtdlLogPrintf(CTDL_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2206 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2207 CtdlLogPrintf(CTDL_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2215 * network_do_queue()
2217 * Run through the rooms doing various types of network stuff.
2219 void *network_do_queue(void *args) {
2220 static time_t last_run = 0L;
2221 struct RoomProcList *ptr;
2222 int full_processing = 1;
2223 struct CitContext networkerCC;
2225 /* Give the networker its own private CitContext */
2226 CtdlFillSystemContext(&networkerCC, "network");
2227 citthread_setspecific(MyConKey, (void *)&networkerCC );
2230 * Run the full set of processing tasks no more frequently
2231 * than once every n seconds
2233 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2234 full_processing = 0;
2235 CtdlLogPrintf(CTDL_DEBUG, "Network full processing in %ld seconds.\n",
2236 config.c_net_freq - (time(NULL)- last_run)
2241 * This is a simple concurrency check to make sure only one queue run
2242 * is done at a time. We could do this with a mutex, but since we
2243 * don't really require extremely fine granularity here, we'll do it
2244 * with a static variable instead.
2247 CtdlClearSystemContext();
2252 /* Load the IGnet Configuration into memory */
2253 load_working_ignetcfg();
2256 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2257 * then we poll everyone. Otherwise we only poll nodes we have stuff
2260 network_poll_other_citadel_nodes(full_processing);
2263 * Load the network map and filter list into memory.
2266 filterlist = load_filter_list();
2269 * Go ahead and run the queue
2271 if (full_processing && !CtdlThreadCheckStop()) {
2272 CtdlLogPrintf(CTDL_DEBUG, "network: loading outbound queue\n");
2273 CtdlForEachRoom(network_queue_room, NULL);
2276 if (rplist != NULL) {
2277 CtdlLogPrintf(CTDL_DEBUG, "network: running outbound queue\n");
2278 while (rplist != NULL && !CtdlThreadCheckStop()) {
2279 char spoolroomname[ROOMNAMELEN];
2280 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2281 begin_critical_section(S_RPLIST);
2283 /* pop this record off the list */
2285 rplist = rplist->next;
2288 /* invalidate any duplicate entries to prevent double processing */
2289 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2290 if (!strcasecmp(ptr->name, spoolroomname)) {
2295 end_critical_section(S_RPLIST);
2296 if (spoolroomname[0] != 0) {
2297 network_spoolout_room(spoolroomname);
2302 /* If there is anything in the inbound queue, process it */
2303 if (!CtdlThreadCheckStop()) {
2304 network_do_spoolin();
2307 /* Save the network map back to disk */
2308 write_network_map();
2310 /* Free the filter list in memory */
2311 free_filter_list(filterlist);
2314 network_consolidate_spoolout();
2316 CtdlLogPrintf(CTDL_DEBUG, "network: queue run completed\n");
2318 if (full_processing) {
2319 last_run = time(NULL);
2324 /* Reschedule this task to happen again periodically, unless the thread system indicates
2325 * that the server is shutting down.
2327 if (!CtdlThreadCheckStop()) {
2328 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK,
2329 network_do_queue, NULL, time(NULL) + 60
2333 CtdlLogPrintf(CTDL_DEBUG, "network: Task STOPPED.\n");
2335 CtdlClearSystemContext();
2341 * cmd_netp() - authenticate to the server as another Citadel node polling
2342 * for network traffic
2344 void cmd_netp(char *cmdbuf)
2355 extract_token(node, cmdbuf, 0, '|', sizeof node);
2356 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2358 /* load the IGnet Configuration to check node validity */
2359 load_working_ignetcfg();
2360 v = is_valid_node(nexthop, secret, node);
2363 snprintf(err_buf, sizeof err_buf,
2364 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2365 node, CC->cs_host, CC->cs_addr
2367 CtdlLogPrintf(CTDL_WARNING, err_buf);
2368 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2369 CtdlAideMessage(err_buf, "IGNet Networking.");
2373 if (strcasecmp(pass, secret)) {
2374 snprintf(err_buf, sizeof err_buf,
2375 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2376 CC->cs_host, CC->cs_addr, node
2378 CtdlLogPrintf(CTDL_WARNING, err_buf);
2379 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2380 CtdlAideMessage(err_buf, "IGNet Networking.");
2384 if (network_talking_to(node, NTT_CHECK)) {
2385 CtdlLogPrintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2386 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2390 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2391 network_talking_to(node, NTT_ADD);
2392 CtdlLogPrintf(CTDL_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2393 CC->net_node, CC->cs_host, CC->cs_addr
2395 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2399 int network_room_handler (struct ctdlroom *room)
2401 network_queue_room(room, NULL);
2407 * Module entry point
2409 CTDL_MODULE_INIT(network)
2413 create_spool_dirs();
2414 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2415 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2416 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2417 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2418 CtdlRegisterRoomHook(network_room_handler);
2419 CtdlRegisterCleanupHook(destroy_network_queue_room);
2422 CtdlThreadSchedule("IGnet Network", CTDLTHREAD_BIGSTACK, network_do_queue, NULL, 0);
2423 /* return our Subversion id for the Log */