2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2010 by the citadel.org team
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
22 * This is a fairly high-level type of critical section. It ensures that no
23 * two threads work on the netconfigs files at the same time. Since we do
24 * so many things inside these, here are the rules:
25 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26 * 2. Do *not* perform any I/O with the client during these sections.
31 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32 * requests that have not been confirmed will be deleted.
34 #define EXP 259200 /* three days */
46 #include <sys/types.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
53 # include <sys/time.h>
61 # if HAVE_SYS_SYSCALL_H
62 # include <sys/syscall.h>
69 #include <libcitadel.h>
72 #include "citserver.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
82 #include "citadel_dirs.h"
91 #include "ctdl_module.h"
95 /* Nonzero while we are doing network processing */
96 static int doing_queue = 0;
99 * When we do network processing, it's accomplished in two passes; one to
100 * gather a list of rooms and one to actually do them. It's ok that rplist
101 * is global; we have a mutex that keeps it safe.
103 struct RoomProcList *rplist = NULL;
106 * We build a map of network nodes during processing.
108 NetMap *the_netmap = NULL;
109 int netmap_changed = 0;
110 char *working_ignetcfg = NULL;
113 * Load or refresh the Citadel network (IGnet) configuration for this node.
115 void load_working_ignetcfg(void) {
119 cfg = CtdlGetSysConfig(IGNETCFG);
124 oldcfg = working_ignetcfg;
125 working_ignetcfg = cfg;
126 if (oldcfg != NULL) {
136 * Keep track of what messages to reject
138 FilterList *load_filter_list(void) {
139 char *serialized_list = NULL;
142 FilterList *newlist = NULL;
145 serialized_list = CtdlGetSysConfig(FILTERLIST);
146 if (serialized_list == NULL) return(NULL); /* if null, no entries */
148 /* Use the string tokenizer to grab one line at a time */
149 for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
150 extract_token(buf, serialized_list, i, '\n', sizeof buf);
151 nptr = (FilterList *) malloc(sizeof(FilterList));
152 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
153 striplt(nptr->fl_user);
154 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
155 striplt(nptr->fl_room);
156 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
157 striplt(nptr->fl_node);
159 /* Cowardly refuse to add an any/any/any entry that would
160 * end up filtering every single message.
162 if (IsEmptyStr(nptr->fl_user) &&
163 IsEmptyStr(nptr->fl_room) &&
164 IsEmptyStr(nptr->fl_node)) {
168 nptr->next = newlist;
173 free(serialized_list);
178 void free_filter_list(FilterList *fl) {
179 if (fl == NULL) return;
180 free_filter_list(fl->next);
187 * Check the use table. This is a list of messages which have recently
188 * arrived on the system. It is maintained and queried to prevent the same
189 * message from being entered into the database multiple times if it happens
190 * to arrive multiple times by accident.
192 int network_usetable(struct CtdlMessage *msg) {
195 struct cdbdata *cdbut;
198 /* Bail out if we can't generate a message ID */
202 if (msg->cm_fields['I'] == NULL) {
205 if (IsEmptyStr(msg->cm_fields['I'])) {
209 /* Generate the message ID */
210 strcpy(msgid, msg->cm_fields['I']);
211 if (haschar(msgid, '@') == 0) {
213 if (msg->cm_fields['N'] != NULL) {
214 strcat(msgid, msg->cm_fields['N']);
221 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
224 syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
228 /* If we got to this point, it's unique: add it. */
229 strcpy(ut.ut_msgid, msgid);
230 ut.ut_timestamp = time(NULL);
231 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
237 * Read the network map from its configuration file into memory.
239 void read_network_map(void) {
240 char *serialized_map = NULL;
245 serialized_map = CtdlGetSysConfig(IGNETMAP);
246 if (serialized_map == NULL) return; /* if null, no entries */
248 /* Use the string tokenizer to grab one line at a time */
249 for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
250 extract_token(buf, serialized_map, i, '\n', sizeof buf);
251 nmptr = (NetMap *) malloc(sizeof(NetMap));
252 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
253 nmptr->lastcontact = extract_long(buf, 1);
254 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
255 nmptr->next = the_netmap;
259 free(serialized_map);
265 * Write the network map from memory back to the configuration file.
267 void write_network_map(void) {
268 char *serialized_map = NULL;
272 if (netmap_changed) {
273 serialized_map = strdup("");
275 if (the_netmap != NULL) {
276 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
277 serialized_map = realloc(serialized_map,
278 (strlen(serialized_map)+SIZ) );
279 if (!IsEmptyStr(nmptr->nodename)) {
280 snprintf(&serialized_map[strlen(serialized_map)],
284 (long)nmptr->lastcontact,
290 CtdlPutSysConfig(IGNETMAP, serialized_map);
291 free(serialized_map);
294 /* Now free the list */
295 while (the_netmap != NULL) {
296 nmptr = the_netmap->next;
306 * Check the network map and determine whether the supplied node name is
307 * valid. If it is not a neighbor node, supply the name of a neighbor node
308 * which is the next hop. If it *is* a neighbor node, we also fill in the
311 int is_valid_node(char *nexthop, char *secret, char *node) {
323 * First try the neighbor nodes
325 if (working_ignetcfg == NULL) {
326 syslog(LOG_ERR, "working_ignetcfg is NULL!\n");
327 if (nexthop != NULL) {
334 if (nexthop != NULL) {
338 /* Use the string tokenizer to grab one line at a time */
339 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
340 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
341 extract_token(buf, linebuf, 0, '|', sizeof buf);
342 if (!strcasecmp(buf, node)) {
343 if (nexthop != NULL) {
346 if (secret != NULL) {
347 extract_token(secret, linebuf, 1, '|', 256);
354 return(retval); /* yup, it's a direct neighbor */
358 * If we get to this point we have to see if we know the next hop
360 if (the_netmap != NULL) {
361 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
362 if (!strcasecmp(nmptr->nodename, node)) {
363 if (nexthop != NULL) {
364 strcpy(nexthop, nmptr->nexthop);
372 * If we get to this point, the supplied node name is bogus.
374 syslog(LOG_ERR, "Invalid node name <%s>\n", node);
382 void cmd_gnet(char *argbuf) {
383 char filename[PATH_MAX];
387 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
388 /* users can edit the netconfigs for their own mailbox rooms */
390 else if (CtdlAccessCheck(ac_room_aide)) return;
392 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
393 cprintf("%d Network settings for room #%ld <%s>\n",
395 CC->room.QRnumber, CC->room.QRname);
397 fp = fopen(filename, "r");
399 while (fgets(buf, sizeof buf, fp) != NULL) {
400 buf[strlen(buf)-1] = 0;
401 cprintf("%s\n", buf);
410 void cmd_snet(char *argbuf) {
411 char tempfilename[PATH_MAX];
412 char filename[PATH_MAX];
421 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
422 /* users can edit the netconfigs for their own mailbox rooms */
424 else if (CtdlAccessCheck(ac_room_aide)) return;
426 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
427 memcpy(tempfilename, filename, len + 1);
429 memset(&StatBuf, 0, sizeof(struct stat));
430 if ((stat(filename, &StatBuf) == -1) || (StatBuf.st_size == 0))
431 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
433 sprintf(tempfilename + len, ".%d", CC->cs_pid);
435 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
437 if ((TmpFD > 0) && (errno == 0))
439 char *tmp = malloc(StatBuf.st_size * 2);
440 memset(tmp, ' ', StatBuf.st_size * 2);
441 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
443 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
446 cprintf("%d Unable to allocate the space required for %s: %s\n",
447 ERROR + INTERNAL_ERROR,
450 unlink(tempfilename);
453 lseek(TmpFD, SEEK_SET, 0);
456 cprintf("%d Unable to allocate the space required for %s: %s\n",
457 ERROR + INTERNAL_ERROR,
460 unlink(tempfilename);
465 cprintf("%d %s\n", SEND_LISTING, tempfilename);
468 while (rc = CtdlClientGetLine(Line),
471 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
473 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
474 write(TmpFD, ChrPtr(Line), StrLength(Line));
475 len += StrLength(Line);
478 ftruncate(TmpFD, len);
481 /* Now copy the temp file to its permanent location.
482 * (We copy instead of link because they may be on different filesystems)
484 begin_critical_section(S_NETCONFIGS);
485 rename(tempfilename, filename);
486 end_critical_section(S_NETCONFIGS);
491 * Deliver digest messages
493 void network_deliver_digest(SpoolControl *sc) {
496 struct CtdlMessage *msg = NULL;
499 size_t recps_len = SIZ;
501 struct recptypes *valid;
505 if (sc->num_msgs_spooled < 1) {
506 fclose(sc->digestfp);
511 msg = malloc(sizeof(struct CtdlMessage));
512 memset(msg, 0, sizeof(struct CtdlMessage));
513 msg->cm_magic = CTDLMESSAGE_MAGIC;
514 msg->cm_format_type = FMT_RFC822;
515 msg->cm_anon_type = MES_NORMAL;
517 sprintf(buf, "%ld", time(NULL));
518 msg->cm_fields['T'] = strdup(buf);
519 msg->cm_fields['A'] = strdup(CC->room.QRname);
520 snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
521 msg->cm_fields['U'] = strdup(buf);
522 sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
523 for (i=0; buf[i]; ++i) {
524 if (isspace(buf[i])) buf[i]='_';
525 buf[i] = tolower(buf[i]);
527 msg->cm_fields['F'] = strdup(buf);
528 msg->cm_fields['R'] = strdup(buf);
530 /* Set the 'List-ID' header */
531 msg->cm_fields['L'] = malloc(1024);
532 snprintf(msg->cm_fields['L'], 1024,
533 "%s <%ld.list-id.%s>",
540 * Go fetch the contents of the digest
542 fseek(sc->digestfp, 0L, SEEK_END);
543 msglen = ftell(sc->digestfp);
545 msg->cm_fields['M'] = malloc(msglen + 1);
546 fseek(sc->digestfp, 0L, SEEK_SET);
547 siz = fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
548 msg->cm_fields['M'][msglen] = '\0';
550 fclose(sc->digestfp);
553 /* Now generate the delivery instructions */
556 * Figure out how big a buffer we need to allocate
558 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
559 recps_len = recps_len + strlen(nptr->name) + 2;
562 recps = malloc(recps_len);
565 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
572 for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
573 if (nptr != sc->digestrecps) {
576 strcat(recps, nptr->name);
579 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
580 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
582 /* Now submit the message */
583 valid = validate_recipients(recps, NULL, 0);
586 valid->bounce_to = strdup(bounce_to);
587 valid->envelope_from = strdup(bounce_to);
588 CtdlSubmitMsg(msg, valid, NULL, 0);
590 CtdlFreeMessage(msg);
591 free_recipients(valid);
596 * Deliver list messages to everyone on the list ... efficiently
598 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
600 size_t recps_len = SIZ;
601 struct recptypes *valid;
605 /* Don't do this if there were no recipients! */
606 if (sc->listrecps == NULL) return;
608 /* Now generate the delivery instructions */
611 * Figure out how big a buffer we need to allocate
613 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
614 recps_len = recps_len + strlen(nptr->name) + 2;
617 recps = malloc(recps_len);
620 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
627 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
628 if (nptr != sc->listrecps) {
631 strcat(recps, nptr->name);
634 /* Where do we want bounces and other noise to be heard? Surely not the list members! */
635 snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
637 /* Now submit the message */
638 valid = validate_recipients(recps, NULL, 0);
641 valid->bounce_to = strdup(bounce_to);
642 valid->envelope_from = strdup(bounce_to);
643 CtdlSubmitMsg(msg, valid, NULL, 0);
644 free_recipients(valid);
646 /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
653 * Spools out one message from the list.
655 void network_spool_msg(long msgnum, void *userdata) {
658 char *newpath = NULL;
659 size_t instr_len = SIZ;
660 struct CtdlMessage *msg = NULL;
663 struct ser_ret sermsg;
665 char filename[PATH_MAX];
669 int delete_after_send = 0; /* Set to 1 to delete after spooling */
670 int ok_to_participate = 0;
671 struct recptypes *valid;
673 sc = (SpoolControl *)userdata;
676 * Process mailing list recipients
679 if (sc->listrecps != NULL) {
680 /* Fetch the message. We're going to need to modify it
681 * in order to insert the [list name] in it, etc.
683 msg = CtdlFetchMessage(msgnum, 1);
685 if (msg->cm_fields['V'] == NULL){
686 /* local message, no enVelope */
689 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
690 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
691 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
693 msg->cm_fields['K'] = SmashStrBuf(&Buf);
696 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
698 /* Set the 'List-ID' header */
699 if (msg->cm_fields['L'] != NULL) {
700 free(msg->cm_fields['L']);
702 msg->cm_fields['L'] = malloc(1024);
703 snprintf(msg->cm_fields['L'], 1024,
704 "%s <%ld.list-id.%s>",
710 /* Prepend "[List name]" to the subject */
711 if (msg->cm_fields['U'] == NULL) {
712 msg->cm_fields['U'] = strdup("(no subject)");
714 snprintf(buf, sizeof buf, "[%s] %s", CC->room.QRname, msg->cm_fields['U']);
715 free(msg->cm_fields['U']);
716 msg->cm_fields['U'] = strdup(buf);
718 /* Set the recipient of the list message to the
719 * email address of the room itself.
720 * FIXME ... I want to be able to pick any address
722 if (msg->cm_fields['R'] != NULL) {
723 free(msg->cm_fields['R']);
725 msg->cm_fields['R'] = malloc(256);
726 snprintf(msg->cm_fields['R'], 256,
727 "room_%s@%s", CC->room.QRname,
729 for (i=0; msg->cm_fields['R'][i]; ++i) {
730 if (isspace(msg->cm_fields['R'][i])) {
731 msg->cm_fields['R'][i] = '_';
735 /* Handle delivery */
736 network_deliver_list(msg, sc);
737 CtdlFreeMessage(msg);
742 * Process digest recipients
744 if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
745 msg = CtdlFetchMessage(msgnum, 1);
747 fprintf(sc->digestfp, " -----------------------------------"
748 "------------------------------------"
750 fprintf(sc->digestfp, "From: ");
751 if (msg->cm_fields['A'] != NULL) {
752 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
754 if (msg->cm_fields['F'] != NULL) {
755 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
757 else if (msg->cm_fields['N'] != NULL) {
758 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
760 fprintf(sc->digestfp, "\n");
761 if (msg->cm_fields['U'] != NULL) {
762 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
765 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
767 safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
768 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
770 StrBufTrim(CC->redirect_buffer);
771 fwrite(HKEY("\n"), 1, sc->digestfp);
772 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
773 fwrite(HKEY("\n"), 1, sc->digestfp);
775 FreeStrBuf(&CC->redirect_buffer);
777 sc->num_msgs_spooled += 1;
783 * Process client-side list participations for this room
786 if (sc->participates != NULL) {
787 msg = CtdlFetchMessage(msgnum, 1);
790 /* Only send messages which originated on our own Citadel
791 * network, otherwise we'll end up sending the remote
792 * mailing list's messages back to it, which is rude...
794 ok_to_participate = 0;
795 if (msg->cm_fields['N'] != NULL) {
796 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
797 ok_to_participate = 1;
799 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
800 ok_to_participate = 1;
803 if (ok_to_participate) {
804 if (msg->cm_fields['F'] != NULL) {
805 free(msg->cm_fields['F']);
807 msg->cm_fields['F'] = malloc(SIZ);
808 /* Replace the Internet email address of the actual
809 * author with the email address of the room itself,
810 * so the remote listserv doesn't reject us.
811 * FIXME ... I want to be able to pick any address
813 snprintf(msg->cm_fields['F'], SIZ,
814 "room_%s@%s", CC->room.QRname,
816 for (i=0; msg->cm_fields['F'][i]; ++i) {
817 if (isspace(msg->cm_fields['F'][i])) {
818 msg->cm_fields['F'][i] = '_';
823 * Figure out how big a buffer we need to allocate
825 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
827 if (msg->cm_fields['R'] == NULL) {
828 free(msg->cm_fields['R']);
830 msg->cm_fields['R'] = strdup(nptr->name);
832 valid = validate_recipients(nptr->name, NULL, 0);
833 CtdlSubmitMsg(msg, valid, "", 0);
834 free_recipients(valid);
838 CtdlFreeMessage(msg);
843 * Process IGnet push shares
845 msg = CtdlFetchMessage(msgnum, 1);
849 /* Prepend our node name to the Path field whenever
850 * sending a message to another IGnet node
852 if (msg->cm_fields['P'] == NULL) {
853 msg->cm_fields['P'] = strdup("username");
855 newpath_len = strlen(msg->cm_fields['P']) +
856 strlen(config.c_nodename) + 2;
857 newpath = malloc(newpath_len);
858 snprintf(newpath, newpath_len, "%s!%s",
859 config.c_nodename, msg->cm_fields['P']);
860 free(msg->cm_fields['P']);
861 msg->cm_fields['P'] = newpath;
864 * Determine if this message is set to be deleted
865 * after sending out on the network
867 if (msg->cm_fields['S'] != NULL) {
868 if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
869 delete_after_send = 1;
873 /* Now send it to every node */
874 if (sc->ignet_push_shares != NULL)
875 for (mptr = sc->ignet_push_shares; mptr != NULL;
880 /* Check for valid node name */
881 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
882 syslog(LOG_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
886 /* Check for split horizon */
887 syslog(LOG_DEBUG, "Path is %s\n", msg->cm_fields['P']);
888 bang = num_tokens(msg->cm_fields['P'], '!');
889 if (bang > 1) for (i=0; i<(bang-1); ++i) {
890 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
891 syslog(LOG_DEBUG, "Compare <%s> to <%s>\n",
892 buf, mptr->remote_nodename) ;
893 if (!strcasecmp(buf, mptr->remote_nodename)) {
895 syslog(LOG_DEBUG, "Not sending to %s\n",
896 mptr->remote_nodename);
899 syslog(LOG_DEBUG, "Sending to %s\n", mptr->remote_nodename);
903 /* Send the message */
907 * Force the message to appear in the correct room
908 * on the far end by setting the C field correctly
910 if (msg->cm_fields['C'] != NULL) {
911 free(msg->cm_fields['C']);
913 if (!IsEmptyStr(mptr->remote_roomname)) {
914 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
917 msg->cm_fields['C'] = strdup(CC->room.QRname);
920 /* serialize it for transmission */
921 serialize_message(&sermsg, msg);
922 if (sermsg.len > 0) {
924 /* write it to a spool file */
925 snprintf(filename, sizeof filename,"%s/%s@%lx%x",
927 mptr->remote_nodename,
931 syslog(LOG_DEBUG, "Appending to %s\n", filename);
932 fp = fopen(filename, "ab");
939 syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
942 /* free the serialized version */
948 CtdlFreeMessage(msg);
951 /* update lastsent */
952 sc->lastsent = msgnum;
954 /* Delete this message if delete-after-send is set */
955 if (delete_after_send) {
956 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
962 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
968 char roomname[ROOMNAMELEN];
971 int skipthisline = 0;
972 namelist *nptr = NULL;
973 maplist *mptr = NULL;
976 fp = fopen(filename, "r");
980 sc = malloc(sizeof(SpoolControl));
981 memset(sc, 0, sizeof(SpoolControl));
984 while (fgets(buf, sizeof buf, fp) != NULL) {
985 buf[strlen(buf)-1] = 0;
987 extract_token(instr, buf, 0, '|', sizeof instr);
988 if (!strcasecmp(instr, strof(lastsent))) {
989 sc->lastsent = extract_long(buf, 1);
991 else if (!strcasecmp(instr, strof(listrecp))) {
993 malloc(sizeof(namelist));
994 nptr->next = sc->listrecps;
995 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
996 sc->listrecps = nptr;
998 else if (!strcasecmp(instr, strof(participate))) {
1000 malloc(sizeof(namelist));
1001 nptr->next = sc->participates;
1002 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1003 sc->participates = nptr;
1005 else if (!strcasecmp(instr, strof(digestrecp))) {
1007 malloc(sizeof(namelist));
1008 nptr->next = sc->digestrecps;
1009 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
1010 sc->digestrecps = nptr;
1012 else if (!strcasecmp(instr, strof(ignet_push_share))) {
1013 extract_token(nodename, buf, 1, '|', sizeof nodename);
1014 extract_token(roomname, buf, 2, '|', sizeof roomname);
1015 mptr = (maplist *) malloc(sizeof(maplist));
1016 mptr->next = sc->ignet_push_shares;
1017 strcpy(mptr->remote_nodename, nodename);
1018 strcpy(mptr->remote_roomname, roomname);
1019 sc->ignet_push_shares = mptr;
1022 /* Preserve 'other' lines ... *unless* they happen to
1023 * be subscribe/unsubscribe pendings with expired
1027 if (!strncasecmp(buf, strof(subpending)"|", 11)) {
1028 if (time(NULL) - extract_long(buf, 4) > EXP) {
1032 if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
1033 if (time(NULL) - extract_long(buf, 3) > EXP) {
1038 if (skipthisline == 0) {
1039 linesize = strlen(buf);
1040 sc->misc = realloc(sc->misc,
1041 (miscsize + linesize + 2) );
1042 sprintf(&sc->misc[miscsize], "%s\n", buf);
1043 miscsize = miscsize + linesize + 1;
1053 void free_spoolcontrol_struct(SpoolControl **scc)
1056 namelist *nptr = NULL;
1057 maplist *mptr = NULL;
1060 while (sc->listrecps != NULL) {
1061 nptr = sc->listrecps->next;
1062 free(sc->listrecps);
1063 sc->listrecps = nptr;
1065 /* Do the same for digestrecps */
1066 while (sc->digestrecps != NULL) {
1067 nptr = sc->digestrecps->next;
1068 free(sc->digestrecps);
1069 sc->digestrecps = nptr;
1071 /* Do the same for participates */
1072 while (sc->participates != NULL) {
1073 nptr = sc->participates->next;
1074 free(sc->participates);
1075 sc->participates = nptr;
1077 while (sc->ignet_push_shares != NULL) {
1078 mptr = sc->ignet_push_shares->next;
1079 free(sc->ignet_push_shares);
1080 sc->ignet_push_shares = mptr;
1087 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
1089 char tempfilename[PATH_MAX];
1092 namelist *nptr = NULL;
1093 maplist *mptr = NULL;
1097 long reltid; /* if we don't have SYS_gettid, use "random" value */
1101 len = strlen(filename);
1102 memcpy(tempfilename, filename, len + 1);
1105 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
1106 reltid = syscall(SYS_gettid);
1108 gettimeofday(&tv, NULL);
1109 /* Promote to time_t; types differ on some OSes (like darwin) */
1110 unixtime = tv.tv_sec;
1112 sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
1115 TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
1117 if ((TmpFD < 0) || (errno != 0)) {
1118 syslog(LOG_CRIT, "ERROR: cannot open %s: %s\n",
1119 filename, strerror(errno));
1120 free_spoolcontrol_struct(scc);
1121 unlink(tempfilename);
1124 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
1126 /* Write out the listrecps while freeing from memory at the
1127 * same time. Am I clever or what? :)
1129 while (sc->listrecps != NULL) {
1130 StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
1131 nptr = sc->listrecps->next;
1132 free(sc->listrecps);
1133 sc->listrecps = nptr;
1135 /* Do the same for digestrecps */
1136 while (sc->digestrecps != NULL) {
1137 StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
1138 nptr = sc->digestrecps->next;
1139 free(sc->digestrecps);
1140 sc->digestrecps = nptr;
1142 /* Do the same for participates */
1143 while (sc->participates != NULL) {
1144 StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
1145 nptr = sc->participates->next;
1146 free(sc->participates);
1147 sc->participates = nptr;
1149 while (sc->ignet_push_shares != NULL) {
1150 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
1151 if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
1152 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
1154 StrBufAppendPrintf(Cfg, "\n");
1155 mptr = sc->ignet_push_shares->next;
1156 free(sc->ignet_push_shares);
1157 sc->ignet_push_shares = mptr;
1159 if (sc->misc != NULL) {
1160 StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
1164 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
1165 if ((rc >=0 ) && (rc == StrLength(Cfg)))
1168 rename(tempfilename, filename);
1172 "unable to write %s; [%s]; not enough space on the disk?\n",
1176 unlink(tempfilename);
1184 int is_recipient(SpoolControl *sc, const char *Name)
1190 nptr = sc->listrecps;
1191 while (nptr != NULL) {
1192 if (strncmp(Name, nptr->name, len)==0)
1196 /* Do the same for digestrecps */
1197 nptr = sc->digestrecps;
1198 while (nptr != NULL) {
1199 if (strncmp(Name, nptr->name, len)==0)
1203 /* Do the same for participates */
1204 nptr = sc->participates;
1205 while (nptr != NULL) {
1206 if (strncmp(Name, nptr->name, len)==0)
1215 * Batch up and send all outbound traffic from the current room
1217 void network_spoolout_room(char *room_to_spool) {
1219 char filename[PATH_MAX];
1224 * If the room doesn't exist, don't try to perform its networking tasks.
1225 * Normally this should never happen, but once in a while maybe a room gets
1226 * queued for networking and then deleted before it can happen.
1228 if (CtdlGetRoom(&CC->room, room_to_spool) != 0) {
1229 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
1233 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1234 begin_critical_section(S_NETCONFIGS);
1236 /* Only do net processing for rooms that have netconfigs */
1237 if (!read_spoolcontrol_file(&sc, filename))
1239 end_critical_section(S_NETCONFIGS);
1242 syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
1244 /* If there are digest recipients, we have to build a digest */
1245 if (sc->digestrecps != NULL) {
1246 sc->digestfp = tmpfile();
1247 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
1250 /* Do something useful */
1251 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
1252 network_spool_msg, sc);
1254 /* If we wrote a digest, deliver it and then close it */
1255 snprintf(buf, sizeof buf, "room_%s@%s",
1256 CC->room.QRname, config.c_fqdn);
1257 for (i=0; buf[i]; ++i) {
1258 buf[i] = tolower(buf[i]);
1259 if (isspace(buf[i])) buf[i] = '_';
1261 if (sc->digestfp != NULL) {
1262 fprintf(sc->digestfp, " -----------------------------------"
1263 "------------------------------------"
1265 "You are subscribed to the '%s' "
1267 "To post to the list: %s\n",
1268 CC->room.QRname, buf
1270 network_deliver_digest(sc); /* deliver and close */
1273 /* Now rewrite the config file */
1274 writenfree_spoolcontrol_file (&sc, filename);
1275 end_critical_section(S_NETCONFIGS);
1281 * Send the *entire* contents of the current room to one specific network node,
1282 * ignoring anything we know about which messages have already undergone
1283 * network processing. This can be used to bring a new node into sync.
1285 int network_sync_to(char *target_node) {
1287 int num_spooled = 0;
1293 char filename[PATH_MAX];
1296 /* Grab the configuration line we're looking for */
1297 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
1298 begin_critical_section(S_NETCONFIGS);
1299 fp = fopen(filename, "r");
1301 end_critical_section(S_NETCONFIGS);
1304 while (fgets(buf, sizeof buf, fp) != NULL) {
1305 buf[strlen(buf)-1] = 0;
1306 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1307 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1308 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1309 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1310 && (!strcasecmp(sc_node, target_node)) ) {
1313 /* Concise syntax because we don't need a full linked-list */
1314 memset(&sc, 0, sizeof(SpoolControl));
1315 sc.ignet_push_shares = (maplist *)
1316 malloc(sizeof(maplist));
1317 sc.ignet_push_shares->next = NULL;
1318 safestrncpy(sc.ignet_push_shares->remote_nodename,
1320 sizeof sc.ignet_push_shares->remote_nodename);
1321 safestrncpy(sc.ignet_push_shares->remote_roomname,
1323 sizeof sc.ignet_push_shares->remote_roomname);
1327 end_critical_section(S_NETCONFIGS);
1329 if (!found_node) return(-1);
1331 /* Send ALL messages */
1332 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
1333 network_spool_msg, &sc);
1335 /* Concise cleanup because we know there's only one node in the sc */
1336 free(sc.ignet_push_shares);
1338 syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
1339 num_spooled, target_node);
1340 return(num_spooled);
1345 * Implements the NSYN command
1347 void cmd_nsyn(char *argbuf) {
1349 char target_node[256];
1351 if (CtdlAccessCheck(ac_aide)) return;
1353 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1354 num_spooled = network_sync_to(target_node);
1355 if (num_spooled >= 0) {
1356 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1359 cprintf("%d No such room/node share exists.\n",
1360 ERROR + ROOM_NOT_FOUND);
1367 * Batch up and send all outbound traffic from the current room
1369 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1370 struct RoomProcList *ptr;
1372 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1373 if (ptr == NULL) return;
1375 safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1376 begin_critical_section(S_RPLIST);
1379 end_critical_section(S_RPLIST);
1382 void destroy_network_queue_room(void)
1384 struct RoomProcList *cur, *p;
1385 NetMap *nmcur, *nmp;
1388 begin_critical_section(S_RPLIST);
1396 end_critical_section(S_RPLIST);
1399 while (nmcur != NULL)
1406 if (working_ignetcfg != NULL)
1407 free (working_ignetcfg);
1408 working_ignetcfg = NULL;
1413 * Learn topology from path fields
1415 void network_learn_topology(char *node, char *path) {
1419 strcpy(nexthop, "");
1421 if (num_tokens(path, '!') < 3) return;
1422 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1423 if (!strcasecmp(nmptr->nodename, node)) {
1424 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1425 nmptr->lastcontact = time(NULL);
1431 /* If we got here then it's not in the map, so add it. */
1432 nmptr = (NetMap *) malloc(sizeof (NetMap));
1433 strcpy(nmptr->nodename, node);
1434 nmptr->lastcontact = time(NULL);
1435 extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1436 nmptr->next = the_netmap;
1445 * Bounce a message back to the sender
1447 void network_bounce(struct CtdlMessage *msg, char *reason) {
1448 char *oldpath = NULL;
1450 char bouncesource[SIZ];
1451 char recipient[SIZ];
1452 struct recptypes *valid = NULL;
1453 char force_room[ROOMNAMELEN];
1454 static int serialnum = 0;
1457 syslog(LOG_DEBUG, "entering network_bounce()\n");
1459 if (msg == NULL) return;
1461 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1464 * Give it a fresh message ID
1466 if (msg->cm_fields['I'] != NULL) {
1467 free(msg->cm_fields['I']);
1469 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1470 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1471 msg->cm_fields['I'] = strdup(buf);
1474 * FIXME ... right now we're just sending a bounce; we really want to
1475 * include the text of the bounced message.
1477 if (msg->cm_fields['M'] != NULL) {
1478 free(msg->cm_fields['M']);
1480 msg->cm_fields['M'] = strdup(reason);
1481 msg->cm_format_type = 0;
1484 * Turn the message around
1486 if (msg->cm_fields['R'] == NULL) {
1487 free(msg->cm_fields['R']);
1490 if (msg->cm_fields['D'] == NULL) {
1491 free(msg->cm_fields['D']);
1494 snprintf(recipient, sizeof recipient, "%s@%s",
1495 msg->cm_fields['A'], msg->cm_fields['N']);
1497 if (msg->cm_fields['A'] == NULL) {
1498 free(msg->cm_fields['A']);
1501 if (msg->cm_fields['N'] == NULL) {
1502 free(msg->cm_fields['N']);
1505 if (msg->cm_fields['U'] == NULL) {
1506 free(msg->cm_fields['U']);
1509 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1510 msg->cm_fields['N'] = strdup(config.c_nodename);
1511 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1513 /* prepend our node to the path */
1514 if (msg->cm_fields['P'] != NULL) {
1515 oldpath = msg->cm_fields['P'];
1516 msg->cm_fields['P'] = NULL;
1519 oldpath = strdup("unknown_user");
1521 size = strlen(oldpath) + SIZ;
1522 msg->cm_fields['P'] = malloc(size);
1523 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1526 /* Now submit the message */
1527 valid = validate_recipients(recipient, NULL, 0);
1528 if (valid != NULL) if (valid->num_error != 0) {
1529 free_recipients(valid);
1532 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1533 strcpy(force_room, config.c_aideroom);
1536 strcpy(force_room, "");
1538 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
1539 strcpy(force_room, config.c_aideroom);
1541 CtdlSubmitMsg(msg, valid, force_room, 0);
1544 if (valid != NULL) free_recipients(valid);
1545 CtdlFreeMessage(msg);
1546 syslog(LOG_DEBUG, "leaving network_bounce()\n");
1553 * Process a buffer containing a single message from a single file
1554 * from the inbound queue
1556 void network_process_buffer(char *buffer, long size) {
1557 struct CtdlMessage *msg = NULL;
1560 struct recptypes *recp = NULL;
1561 char target_room[ROOMNAMELEN];
1562 struct ser_ret sermsg;
1563 char *oldpath = NULL;
1564 char filename[PATH_MAX];
1567 unsigned char firstbyte;
1568 unsigned char lastbyte;
1570 syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
1572 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
1573 firstbyte = buffer[0];
1574 lastbyte = buffer[size-1];
1575 if ( (firstbyte != 255) || (lastbyte != 0) ) {
1576 syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
1577 size, firstbyte, lastbyte);
1581 /* Set default target room to trash */
1582 strcpy(target_room, TWITROOM);
1584 /* Load the message into memory */
1585 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1586 memset(msg, 0, sizeof(struct CtdlMessage));
1587 msg->cm_magic = CTDLMESSAGE_MAGIC;
1588 msg->cm_anon_type = buffer[1];
1589 msg->cm_format_type = buffer[2];
1591 for (pos = 3; pos < size; ++pos) {
1592 field = buffer[pos];
1593 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1594 pos = pos + strlen(&buffer[(int)pos]);
1597 /* Check for message routing */
1598 if (msg->cm_fields['D'] != NULL) {
1599 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1601 /* route the message */
1602 strcpy(nexthop, "");
1603 if (is_valid_node(nexthop, NULL, msg->cm_fields['D']) == 0) {
1604 /* prepend our node to the path */
1605 if (msg->cm_fields['P'] != NULL) {
1606 oldpath = msg->cm_fields['P'];
1607 msg->cm_fields['P'] = NULL;
1610 oldpath = strdup("unknown_user");
1612 size = strlen(oldpath) + SIZ;
1613 msg->cm_fields['P'] = malloc(size);
1614 snprintf(msg->cm_fields['P'], size, "%s!%s",
1615 config.c_nodename, oldpath);
1618 /* serialize the message */
1619 serialize_message(&sermsg, msg);
1622 if (IsEmptyStr(nexthop)) {
1623 strcpy(nexthop, msg->cm_fields['D']);
1633 syslog(LOG_DEBUG, "Appending to %s\n", filename);
1634 fp = fopen(filename, "ab");
1636 fwrite(sermsg.ser, sermsg.len, 1, fp);
1640 syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
1643 CtdlFreeMessage(msg);
1647 else { /* invalid destination node name */
1650 "A message you sent could not be delivered due to an invalid destination node"
1651 " name. Please check the address and try sending the message again.\n");
1660 * Check to see if we already have a copy of this message, and
1661 * abort its processing if so. (We used to post a warning to Aide>
1662 * every time this happened, but the network is now so densely
1663 * connected that it's inevitable.)
1665 if (network_usetable(msg) != 0) {
1666 CtdlFreeMessage(msg);
1670 /* Learn network topology from the path */
1671 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1672 network_learn_topology(msg->cm_fields['N'], msg->cm_fields['P']);
1675 /* Is the sending node giving us a very persuasive suggestion about
1676 * which room this message should be saved in? If so, go with that.
1678 if (msg->cm_fields['C'] != NULL) {
1679 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
1682 /* Otherwise, does it have a recipient? If so, validate it... */
1683 else if (msg->cm_fields['R'] != NULL) {
1684 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
1685 if (recp != NULL) if (recp->num_error != 0) {
1687 "A message you sent could not be delivered due to an invalid address.\n"
1688 "Please check the address and try sending the message again.\n");
1690 free_recipients(recp);
1691 syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
1694 strcpy(target_room, ""); /* no target room if mail */
1697 /* Our last shot at finding a home for this message is to see if
1698 * it has the O field (Originating room) set.
1700 else if (msg->cm_fields['O'] != NULL) {
1701 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
1704 /* Strip out fields that are only relevant during transit */
1705 if (msg->cm_fields['D'] != NULL) {
1706 free(msg->cm_fields['D']);
1707 msg->cm_fields['D'] = NULL;
1709 if (msg->cm_fields['C'] != NULL) {
1710 free(msg->cm_fields['C']);
1711 msg->cm_fields['C'] = NULL;
1714 /* save the message into a room */
1715 if (PerformNetprocHooks(msg, target_room) == 0) {
1716 msg->cm_flags = CM_SKIP_HOOKS;
1717 CtdlSubmitMsg(msg, recp, target_room, 0);
1719 CtdlFreeMessage(msg);
1720 free_recipients(recp);
1725 * Process a single message from a single file from the inbound queue
1727 void network_process_message(FILE *fp, long msgstart, long msgend) {
1732 hold_pos = ftell(fp);
1733 size = msgend - msgstart + 1;
1734 buffer = malloc(size);
1735 if (buffer != NULL) {
1736 fseek(fp, msgstart, SEEK_SET);
1737 if (fread(buffer, size, 1, fp) > 0) {
1738 network_process_buffer(buffer, size);
1743 fseek(fp, hold_pos, SEEK_SET);
1748 * Process a single file from the inbound queue
1750 void network_process_file(char *filename) {
1752 long msgstart = (-1L);
1753 long msgend = (-1L);
1758 fp = fopen(filename, "rb");
1760 syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
1764 fseek(fp, 0L, SEEK_END);
1765 syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
1768 /* Look for messages in the data stream and break them out */
1769 while (ch = getc(fp), ch >= 0) {
1772 if (msgstart >= 0L) {
1773 msgend = msgcur - 1;
1774 network_process_message(fp, msgstart, msgend);
1782 msgend = msgcur - 1;
1783 if (msgstart >= 0L) {
1784 network_process_message(fp, msgstart, msgend);
1793 * Process anything in the inbound queue
1795 void network_do_spoolin(void) {
1798 struct stat statbuf;
1799 char filename[PATH_MAX];
1800 static time_t last_spoolin_mtime = 0L;
1803 * Check the spoolin directory's modification time. If it hasn't
1804 * been touched, we don't need to scan it.
1806 if (stat(ctdl_netin_dir, &statbuf)) return;
1807 if (statbuf.st_mtime == last_spoolin_mtime) {
1808 syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
1811 last_spoolin_mtime = statbuf.st_mtime;
1812 syslog(LOG_DEBUG, "network: processing inbound queue\n");
1815 * Ok, there's something interesting in there, so scan it.
1817 dp = opendir(ctdl_netin_dir);
1818 if (dp == NULL) return;
1820 while (d = readdir(dp), d != NULL) {
1821 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1828 network_process_file(filename);
1836 * Step 1: consolidate files in the outbound queue into one file per neighbor node
1837 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
1839 void network_consolidate_spoolout(void) {
1842 char filename[PATH_MAX];
1848 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
1849 dp = opendir(ctdl_netout_dir);
1850 if (dp == NULL) return;
1851 while (d = readdir(dp), d != NULL) {
1853 (strcmp(d->d_name, "."))
1854 && (strcmp(d->d_name, ".."))
1855 && (strchr(d->d_name, '@') != NULL)
1857 safestrncpy(nexthop, d->d_name, sizeof nexthop);
1858 ptr = strchr(nexthop, '@');
1868 syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, nexthop);
1869 if (network_talking_to(nexthop, NTT_CHECK)) {
1871 "Currently online with %s - skipping for now\n",
1876 network_talking_to(nexthop, NTT_ADD);
1877 snprintf(cmd, sizeof cmd, "/bin/cat %s >>%s/%s && /bin/rm -f %s",
1879 ctdl_netout_dir, nexthop,
1883 network_talking_to(nexthop, NTT_REMOVE);
1889 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1891 dp = opendir(ctdl_netout_dir);
1892 if (dp == NULL) return;
1894 while (d = readdir(dp), d != NULL) {
1895 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1897 ptr = strchr(d->d_name, '@');
1907 strcpy(nexthop, "");
1908 i = is_valid_node(nexthop, NULL, d->d_name);
1910 if ( (i != 0) || !IsEmptyStr(nexthop) ) {
1921 * receive network spool from the remote system
1923 void receive_spool(int *sock, char *remote_nodename) {
1924 int download_len = 0L;
1925 int bytes_received = 0L;
1927 char tempfilename[PATH_MAX];
1928 char permfilename[PATH_MAX];
1932 snprintf(tempfilename,
1933 sizeof tempfilename,
1941 snprintf(permfilename,
1942 sizeof permfilename,
1950 if (sock_puts(sock, "NDOP") < 0) return;
1951 if (sock_getln(sock, buf, sizeof buf) < 0) return;
1952 syslog(LOG_DEBUG, "<%s\n", buf);
1953 if (buf[0] != '2') {
1957 download_len = extract_long(&buf[4], 0);
1958 if (download_len <= 0) {
1962 bytes_received = 0L;
1963 fp = fopen(tempfilename, "w");
1965 syslog(LOG_CRIT, "Cannot create %s: %s\n", tempfilename, strerror(errno));
1969 syslog(LOG_DEBUG, "Expecting to transfer %d bytes\n", download_len);
1970 while (bytes_received < download_len) {
1972 * If shutting down we can exit here and unlink the temp file.
1973 * this shouldn't loose us any messages.
1975 if (CtdlThreadCheckStop())
1978 unlink(tempfilename);
1981 snprintf(buf, sizeof buf, "READ %d|%d",
1983 ((download_len - bytes_received > IGNET_PACKET_SIZE)
1984 ? IGNET_PACKET_SIZE : (download_len - bytes_received))
1987 if (sock_puts(sock, buf) < 0) {
1989 unlink(tempfilename);
1992 if (sock_getln(sock, buf, sizeof buf) < 0) {
1994 unlink(tempfilename);
1998 if (buf[0] == '6') {
1999 plen = extract_int(&buf[4], 0);
2000 StrBuf *pbuf = NewStrBuf();
2001 if (socket_read_blob(sock, pbuf, plen, CLIENT_TIMEOUT) != plen) {
2002 syslog(LOG_INFO, "Short read from peer; aborting.\n");
2004 unlink(tempfilename);
2008 fwrite(ChrPtr(pbuf), plen, 1, fp);
2009 bytes_received += plen;
2016 /* Last chance for shutdown exit */
2017 if (CtdlThreadCheckStop())
2019 unlink(tempfilename);
2023 if (sock_puts(sock, "CLOS") < 0) {
2024 unlink(tempfilename);
2029 * From here on we must complete or messages will get lost
2031 if (sock_getln(sock, buf, sizeof buf) < 0) {
2032 unlink(tempfilename);
2036 syslog(LOG_DEBUG, "%s\n", buf);
2039 * Now move the temp file to its permanent location.
2041 if (link(tempfilename, permfilename) != 0) {
2042 syslog(LOG_ALERT, "Could not link %s to %s: %s\n",
2043 tempfilename, permfilename, strerror(errno)
2047 unlink(tempfilename);
2053 * transmit network spool to the remote system
2055 void transmit_spool(int *sock, char *remote_nodename)
2060 long bytes_to_write, thisblock, bytes_written;
2064 if (sock_puts(sock, "NUOP") < 0) return;
2065 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2066 syslog(LOG_DEBUG, "<%s\n", buf);
2067 if (buf[0] != '2') {
2071 snprintf(sfname, sizeof sfname,
2076 fd = open(sfname, O_RDONLY);
2078 if (errno != ENOENT) {
2079 syslog(LOG_CRIT, "cannot open %s: %s\n", sfname, strerror(errno));
2084 while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
2085 bytes_to_write = plen;
2086 while (bytes_to_write > 0L) {
2087 /* Exit if shutting down */
2088 if (CtdlThreadCheckStop())
2094 snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
2095 if (sock_puts(sock, buf) < 0) {
2099 if (sock_getln(sock, buf, sizeof buf) < 0) {
2103 thisblock = atol(&buf[4]);
2104 if (buf[0] == '7') {
2105 if (sock_write(sock, pbuf, (int) thisblock) < 0) {
2109 bytes_to_write -= thisblock;
2110 bytes_written += thisblock;
2120 /* Last chance for shutdown exit */
2121 if(CtdlThreadCheckStop())
2124 if (sock_puts(sock, "UCLS 1") < 0) return;
2127 * From here on we must complete or messages will get lost
2129 if (sock_getln(sock, buf, sizeof buf) < 0) return;
2130 syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", bytes_written, remote_nodename);
2131 syslog(LOG_DEBUG, "<%s\n", buf);
2132 if (buf[0] == '2') {
2133 syslog(LOG_DEBUG, "Removing <%s>\n", sfname);
2141 * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
2143 void network_poll_node(char *node, char *secret, char *host, char *port) {
2147 char connected_to[SIZ];
2150 if (network_talking_to(node, NTT_CHECK)) return;
2151 network_talking_to(node, NTT_ADD);
2152 syslog(LOG_DEBUG, "network: polling <%s>\n", node);
2153 syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
2155 sock = sock_connect(host, port);
2157 syslog(LOG_ERR, "Could not connect: %s\n", strerror(errno));
2158 network_talking_to(node, NTT_REMOVE);
2162 syslog(LOG_DEBUG, "Connected!\n");
2163 CCC->sReadBuf = NewStrBuf();
2164 CCC->sMigrateBuf = NewStrBuf();
2167 /* Read the server greeting */
2168 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2169 syslog(LOG_DEBUG, ">%s\n", buf);
2171 /* Check that the remote is who we think it is and warn the Aide if not */
2172 extract_token (connected_to, buf, 1, ' ', sizeof connected_to);
2173 if (strcmp(connected_to, node))
2175 snprintf(err_buf, sizeof(err_buf),
2176 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
2179 syslog(LOG_ERR, "%s\n", err_buf);
2180 CtdlAideMessage(err_buf, "Network error");
2183 /* We're talking to the correct node. Now identify ourselves. */
2184 snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
2185 syslog(LOG_DEBUG, "<%s\n", buf);
2186 if (sock_puts(&sock, buf) <0) goto bail;
2187 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
2188 syslog(LOG_DEBUG, ">%s\n", buf);
2189 if (buf[0] != '2') {
2193 /* At this point we are authenticated. */
2194 if (!CtdlThreadCheckStop())
2195 receive_spool(&sock, node);
2196 if (!CtdlThreadCheckStop())
2197 transmit_spool(&sock, node);
2200 sock_puts(&sock, "QUIT");
2202 FreeStrBuf(&CCC->sReadBuf);
2203 FreeStrBuf(&CCC->sMigrateBuf);
2206 network_talking_to(node, NTT_REMOVE);
2212 * Poll other Citadel nodes and transfer inbound/outbound network data.
2213 * Set "full" to nonzero to force a poll of every node, or to zero to poll
2214 * only nodes to which we have data to send.
2216 void network_poll_other_citadel_nodes(int full_poll) {
2224 char spoolfile[256];
2226 if (working_ignetcfg == NULL) {
2227 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
2231 /* Use the string tokenizer to grab one line at a time */
2232 for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
2233 if(CtdlThreadCheckStop())
2235 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
2236 extract_token(node, linebuf, 0, '|', sizeof node);
2237 extract_token(secret, linebuf, 1, '|', sizeof secret);
2238 extract_token(host, linebuf, 2, '|', sizeof host);
2239 extract_token(port, linebuf, 3, '|', sizeof port);
2240 if ( !IsEmptyStr(node) && !IsEmptyStr(secret)
2241 && !IsEmptyStr(host) && !IsEmptyStr(port)) {
2250 if (access(spoolfile, R_OK) == 0) {
2255 network_poll_node(node, secret, host, port);
2266 * It's ok if these directories already exist. Just fail silently.
2268 void create_spool_dirs(void) {
2269 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
2270 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
2271 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
2272 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
2273 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
2274 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
2275 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
2276 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
2277 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
2278 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2279 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
2280 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
2281 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
2282 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
2283 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
2284 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
2292 * network_do_queue()
2294 * Run through the rooms doing various types of network stuff.
2296 void network_do_queue(void) {
2297 static time_t last_run = 0L;
2298 struct RoomProcList *ptr;
2299 int full_processing = 1;
2302 * Run the full set of processing tasks no more frequently
2303 * than once every n seconds
2305 if ( (time(NULL) - last_run) < config.c_net_freq ) {
2306 full_processing = 0;
2307 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
2308 config.c_net_freq - (time(NULL)- last_run)
2313 * This is a simple concurrency check to make sure only one queue run
2314 * is done at a time. We could do this with a mutex, but since we
2315 * don't really require extremely fine granularity here, we'll do it
2316 * with a static variable instead.
2323 /* Load the IGnet Configuration into memory */
2324 load_working_ignetcfg();
2327 * Poll other Citadel nodes. Maybe. If "full_processing" is set
2328 * then we poll everyone. Otherwise we only poll nodes we have stuff
2331 network_poll_other_citadel_nodes(full_processing);
2334 * Load the network map and filter list into memory.
2337 filterlist = load_filter_list();
2340 * Go ahead and run the queue
2342 if (full_processing && !CtdlThreadCheckStop()) {
2343 syslog(LOG_DEBUG, "network: loading outbound queue\n");
2344 CtdlForEachRoom(network_queue_room, NULL);
2347 if (rplist != NULL) {
2348 syslog(LOG_DEBUG, "network: running outbound queue\n");
2349 while (rplist != NULL && !CtdlThreadCheckStop()) {
2350 char spoolroomname[ROOMNAMELEN];
2351 safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
2352 begin_critical_section(S_RPLIST);
2354 /* pop this record off the list */
2356 rplist = rplist->next;
2359 /* invalidate any duplicate entries to prevent double processing */
2360 for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
2361 if (!strcasecmp(ptr->name, spoolroomname)) {
2366 end_critical_section(S_RPLIST);
2367 if (spoolroomname[0] != 0) {
2368 network_spoolout_room(spoolroomname);
2373 /* If there is anything in the inbound queue, process it */
2374 if (!CtdlThreadCheckStop()) {
2375 network_do_spoolin();
2378 /* Save the network map back to disk */
2379 write_network_map();
2381 /* Free the filter list in memory */
2382 free_filter_list(filterlist);
2385 network_consolidate_spoolout();
2387 syslog(LOG_DEBUG, "network: queue run completed\n");
2389 if (full_processing) {
2390 last_run = time(NULL);
2398 * cmd_netp() - authenticate to the server as another Citadel node polling
2399 * for network traffic
2401 void cmd_netp(char *cmdbuf)
2412 extract_token(node, cmdbuf, 0, '|', sizeof node);
2413 extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2415 /* load the IGnet Configuration to check node validity */
2416 load_working_ignetcfg();
2417 v = is_valid_node(nexthop, secret, node);
2420 snprintf(err_buf, sizeof err_buf,
2421 "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
2422 node, CC->cs_host, CC->cs_addr
2424 syslog(LOG_WARNING, err_buf);
2425 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2426 CtdlAideMessage(err_buf, "IGNet Networking.");
2430 if (strcasecmp(pass, secret)) {
2431 snprintf(err_buf, sizeof err_buf,
2432 "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
2433 CC->cs_host, CC->cs_addr, node
2435 syslog(LOG_WARNING, err_buf);
2436 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2437 CtdlAideMessage(err_buf, "IGNet Networking.");
2441 if (network_talking_to(node, NTT_CHECK)) {
2442 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
2443 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2447 safestrncpy(CC->net_node, node, sizeof CC->net_node);
2448 network_talking_to(node, NTT_ADD);
2449 syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]\n",
2450 CC->net_node, CC->cs_host, CC->cs_addr
2452 cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
2456 int network_room_handler (struct ctdlroom *room)
2458 network_queue_room(room, NULL);
2462 void *ignet_thread(void *arg) {
2463 struct CitContext ignet_thread_CC;
2465 syslog(LOG_DEBUG, "ignet_thread() initializing\n");
2466 CtdlFillSystemContext(&ignet_thread_CC, "IGnet Queue");
2467 citthread_setspecific(MyConKey, (void *)&ignet_thread_CC);
2469 while (!CtdlThreadCheckStop()) {
2471 CtdlThreadSleep(60);
2474 CtdlClearSystemContext();
2482 * Module entry point
2484 CTDL_MODULE_INIT(network)
2488 create_spool_dirs();
2489 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2490 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2491 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2492 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2493 CtdlRegisterRoomHook(network_room_handler);
2494 CtdlRegisterCleanupHook(destroy_network_queue_room);
2495 CtdlThreadCreate("SMTP Send", CTDLTHREAD_BIGSTACK, ignet_thread, NULL);