2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2012 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 3.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
16 * This is a fairly high-level type of critical section. It ensures that no
17 * two threads work on the netconfigs files at the same time. Since we do
18 * so many things inside these, here are the rules:
19 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
20 * 2. Do *not* perform any I/O with the client during these sections.
25 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
26 * requests that have not been confirmed will be deleted.
28 #define EXP 259200 /* three days */
40 #include <sys/types.h>
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
47 # include <sys/time.h>
55 # if HAVE_SYS_SYSCALL_H
56 # include <sys/syscall.h>
63 #include <libcitadel.h>
66 #include "citserver.h"
72 #include "internet_addressing.h"
73 #include "serv_network.h"
74 #include "clientsocket.h"
76 #include "citadel_dirs.h"
80 #include "ctdl_module.h"
92 #define IFTODT(mode) (((mode) & 0170000) >> 12)
93 #define DTTOIF(dirtype) ((dirtype) << 12)
97 void ParseLastSent(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
100 nptr = (RoomNetCfgLine *)
101 malloc(sizeof(RoomNetCfgLine));
103 OneRNCFG->lastsent = extract_long(LinePos, 0);
104 OneRNCFG->NetConfigs[ThisOne->C] = nptr;
107 void ParseRoomAlias(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
110 if (rncfg->RNCfg->sender != NULL)
111 continue; / * just one alowed... * /
112 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
113 rncfg->RNCfg->sender = nptr;
117 void ParseSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
119 if (time(NULL) - extract_long(LinePos, 3) > EXP)
120 return; /* expired subscription... */
122 ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
124 void ParseUnSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
126 if (time(NULL) - extract_long(LinePos, 2) > EXP)
127 return; /* expired subscription... */
129 ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
133 void SerializeLastSent(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
135 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
136 StrBufAppendPrintf(OutputBuffer, "|%ld\n", RNCfg->lastsent);
139 void DeleteLastSent(const CfgLineType *ThisOne, RoomNetCfgLine **data)
149 * Batch up and send all outbound traffic from the current room
151 void network_spoolout_room(RoomProcList *room_to_spool,
152 HashList *working_ignetcfg,
153 HashList *the_netmap)
155 struct CitContext *CCC = CC;
160 if ((sc.RNCfg->NetConfigs[listrecp] == NULL) &&
161 (sc.RNCfg->NetConfigs[digestrecp] == NULL) &&
162 (sc.RNCfg->NetConfigs[participate] == NULL) &&
163 (sc.RNCfg->NetConfigs[ignet_push_share] == NULL))
165 /* nothing to do for this room... */
170 * If the room doesn't exist, don't try to perform its networking tasks.
171 * Normally this should never happen, but once in a while maybe a room gets
172 * queued for networking and then deleted before it can happen.
174 if (CtdlGetRoom(&CCC->room, room_to_spool->name) != 0) {
175 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
180 syslog(LOG_INFO, "Networking started for <%s>\n", CCC->room.QRname);
181 sc.RNCfg = room_to_spool->OneRNCfg;
182 sc.lastsent = room_to_spool->OneRNCfg->lastsent;
183 sc.working_ignetcfg = working_ignetcfg;
184 sc.the_netmap = the_netmap;
186 /* If there are digest recipients, we have to build a digest */
187 if (sc.RNCfg->NetConfigs[digestrecp] != NULL) {
188 sc.digestfp = tmpfile();
189 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
192 /* Do something useful */
193 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL, NULL,
194 network_spool_msg, &sc);
196 /* If we wrote a digest, deliver it and then close it */
197 if (StrLength(sc.RNCfg->Sender) > 0)
200 len = StrLength(sc.RNCfg->Sender);
201 if (len + 1 > sizeof(buf))
202 len = sizeof(buf) - 1;
203 memcpy(buf, ChrPtr(sc.RNCfg->Sender), len);
208 snprintf(buf, sizeof buf, "room_%s@%s",
209 CCC->room.QRname, config.c_fqdn);
212 for (i=0; buf[i]; ++i) {
213 buf[i] = tolower(buf[i]);
214 if (isspace(buf[i])) buf[i] = '_';
216 if (sc.digestfp != NULL) {
218 " -----------------------------------"
219 "------------------------------------"
221 "You are subscribed to the '%s' "
223 "To post to the list: %s\n",
224 CCC->room.QRname, buf
226 network_deliver_digest(&sc); /* deliver and close */
229 /* Now rewrite the config file */
230 if (sc.lastsent != room_to_spool->OneRNCfg->lastsent)
232 room_to_spool->OneRNCfg->lastsent = sc.lastsent;
233 room_to_spool->OneRNCfg->changed = 1;
235 end_critical_section(S_NETCONFIGS);
239 * Process a buffer containing a single message from a single file
240 * from the inbound queue
242 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
244 struct CitContext *CCC = CC;
246 struct CtdlMessage *msg = NULL;
249 struct recptypes *recp = NULL;
250 char target_room[ROOMNAMELEN];
251 struct ser_ret sermsg;
252 char *oldpath = NULL;
253 char filename[PATH_MAX];
255 const StrBuf *nexthop = NULL;
256 unsigned char firstbyte;
257 unsigned char lastbyte;
259 QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
261 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
262 firstbyte = buffer[0];
263 lastbyte = buffer[size-1];
264 if ( (firstbyte != 255) || (lastbyte != 0) ) {
265 QN_syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
266 size, firstbyte, lastbyte);
270 /* Set default target room to trash */
271 strcpy(target_room, TWITROOM);
273 /* Load the message into memory */
274 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
275 memset(msg, 0, sizeof(struct CtdlMessage));
276 msg->cm_magic = CTDLMESSAGE_MAGIC;
277 msg->cm_anon_type = buffer[1];
278 msg->cm_format_type = buffer[2];
280 for (pos = 3; pos < size; ++pos) {
282 msg->cm_fields[field] = strdup(&buffer[pos+1]);
283 pos = pos + strlen(&buffer[(int)pos]);
286 /* Check for message routing */
287 if (msg->cm_fields['D'] != NULL) {
288 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
290 /* route the message */
291 Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
292 if (CtdlIsValidNode(&nexthop,
298 /* prepend our node to the path */
299 if (msg->cm_fields['P'] != NULL) {
300 oldpath = msg->cm_fields['P'];
301 msg->cm_fields['P'] = NULL;
304 oldpath = strdup("unknown_user");
306 size = strlen(oldpath) + SIZ;
307 msg->cm_fields['P'] = malloc(size);
308 snprintf(msg->cm_fields['P'], size, "%s!%s",
309 config.c_nodename, oldpath);
312 /* serialize the message */
313 serialize_message(&sermsg, msg);
316 if (StrLength(nexthop) == 0) {
327 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
328 fp = fopen(filename, "ab");
330 fwrite(sermsg.ser, sermsg.len, 1, fp);
334 QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
337 CtdlFreeMessage(msg);
342 else { /* invalid destination node name */
346 "A message you sent could not be delivered due to an invalid destination node"
347 " name. Please check the address and try sending the message again.\n");
356 * Check to see if we already have a copy of this message, and
357 * abort its processing if so. (We used to post a warning to Aide>
358 * every time this happened, but the network is now so densely
359 * connected that it's inevitable.)
361 if (network_usetable(msg) != 0) {
362 CtdlFreeMessage(msg);
366 /* Learn network topology from the path */
367 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
368 NetworkLearnTopology(msg->cm_fields['N'],
374 /* Is the sending node giving us a very persuasive suggestion about
375 * which room this message should be saved in? If so, go with that.
377 if (msg->cm_fields['C'] != NULL) {
378 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
381 /* Otherwise, does it have a recipient? If so, validate it... */
382 else if (msg->cm_fields['R'] != NULL) {
383 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
384 if (recp != NULL) if (recp->num_error != 0) {
386 "A message you sent could not be delivered due to an invalid address.\n"
387 "Please check the address and try sending the message again.\n");
389 free_recipients(recp);
390 QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
393 strcpy(target_room, ""); /* no target room if mail */
396 /* Our last shot at finding a home for this message is to see if
397 * it has the O field (Originating room) set.
399 else if (msg->cm_fields['O'] != NULL) {
400 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
403 /* Strip out fields that are only relevant during transit */
404 if (msg->cm_fields['D'] != NULL) {
405 free(msg->cm_fields['D']);
406 msg->cm_fields['D'] = NULL;
408 if (msg->cm_fields['C'] != NULL) {
409 free(msg->cm_fields['C']);
410 msg->cm_fields['C'] = NULL;
413 /* save the message into a room */
414 if (PerformNetprocHooks(msg, target_room) == 0) {
415 msg->cm_flags = CM_SKIP_HOOKS;
416 CtdlSubmitMsg(msg, recp, target_room, 0);
418 CtdlFreeMessage(msg);
419 free_recipients(recp);
424 * Process a single message from a single file from the inbound queue
426 void network_process_message(FILE *fp,
429 HashList *working_ignetcfg,
430 HashList *the_netmap,
437 hold_pos = ftell(fp);
438 size = msgend - msgstart + 1;
439 buffer = malloc(size);
440 if (buffer != NULL) {
441 fseek(fp, msgstart, SEEK_SET);
442 if (fread(buffer, size, 1, fp) > 0) {
443 network_process_buffer(buffer,
452 fseek(fp, hold_pos, SEEK_SET);
457 * Process a single file from the inbound queue
459 void network_process_file(char *filename,
460 HashList *working_ignetcfg,
461 HashList *the_netmap,
464 struct CitContext *CCC = CC;
466 long msgstart = (-1L);
472 fp = fopen(filename, "rb");
474 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
478 fseek(fp, 0L, SEEK_END);
479 QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
482 /* Look for messages in the data stream and break them out */
483 while (ch = getc(fp), ch >= 0) {
486 if (msgstart >= 0L) {
488 network_process_message(fp,
502 if (msgstart >= 0L) {
503 network_process_message(fp,
517 * Process anything in the inbound queue
519 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
521 struct CitContext *CCC = CC;
524 struct dirent *filedir_entry;
526 char filename[PATH_MAX];
527 static time_t last_spoolin_mtime = 0L;
532 * Check the spoolin directory's modification time. If it hasn't
533 * been touched, we don't need to scan it.
535 if (stat(ctdl_netin_dir, &statbuf)) return;
536 if (statbuf.st_mtime == last_spoolin_mtime) {
537 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
540 last_spoolin_mtime = statbuf.st_mtime;
541 QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
544 * Ok, there's something interesting in there, so scan it.
546 dp = opendir(ctdl_netin_dir);
547 if (dp == NULL) return;
549 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
555 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
556 (filedir_entry != NULL))
558 #ifdef _DIRENT_HAVE_D_NAMLEN
559 d_namelen = filedir_entry->d_namelen;
562 d_namelen = strlen(filedir_entry->d_name);
565 #ifdef _DIRENT_HAVE_D_TYPE
566 d_type = filedir_entry->d_type;
570 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
571 continue; /* Ignore backup files... */
573 if ((d_namelen == 1) &&
574 (filedir_entry->d_name[0] == '.'))
577 if ((d_namelen == 2) &&
578 (filedir_entry->d_name[0] == '.') &&
579 (filedir_entry->d_name[1] == '.'))
582 if (d_type == DT_UNKNOWN) {
590 filedir_entry->d_name);
592 if (lstat(path, &s) == 0) {
593 d_type = IFTODT(s.st_mode);
601 case DT_LNK: /* TODO: check whether its a file or a directory */
609 network_process_file(filename,
621 * Step 1: consolidate files in the outbound queue into one file per neighbor node
622 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
624 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
626 struct CitContext *CCC = CC;
632 struct dirent *filedir_entry;
634 char spooloutfilename[PATH_MAX];
635 char filename[PATH_MAX];
636 const StrBuf *nexthop;
644 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
645 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
646 if (d == NULL) return;
648 dp = opendir(ctdl_netout_dir);
654 NextHop = NewStrBuf();
655 memset(&IOB, 0, sizeof(IOBuffer));
656 memset(&FDIO, 0, sizeof(FDIOBuffer));
659 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
660 (filedir_entry != NULL))
662 #ifdef _DIRENT_HAVE_D_NAMLEN
663 d_namelen = filedir_entry->d_namelen;
666 d_namelen = strlen(filedir_entry->d_name);
669 #ifdef _DIRENT_HAVE_D_TYPE
670 d_type = filedir_entry->d_type;
674 if (d_type == DT_DIR)
677 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
678 continue; /* Ignore backup files... */
680 if ((d_namelen == 1) &&
681 (filedir_entry->d_name[0] == '.'))
684 if ((d_namelen == 2) &&
685 (filedir_entry->d_name[0] == '.') &&
686 (filedir_entry->d_name[1] == '.'))
689 pch = strchr(filedir_entry->d_name, '@');
697 filedir_entry->d_name);
700 filedir_entry->d_name,
701 pch - filedir_entry->d_name);
703 snprintf(spooloutfilename,
704 sizeof spooloutfilename,
709 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
710 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
713 "Currently online with %s - skipping for now\n",
721 const char *err = NULL;
722 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
724 infd = open(filename, O_RDONLY);
728 "failed to open %s for reading due to %s; skipping.\n",
729 filename, strerror(errno)
731 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
735 outfd = open(spooloutfilename,
736 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
740 outfd = open(spooloutfilename,
741 O_EXCL|O_NONBLOCK|O_WRONLY,
747 "failed to open %s for reading due to %s; skipping.\n",
748 spooloutfilename, strerror(errno)
751 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
755 dsize = lseek(outfd, 0, SEEK_END);
756 lseek(outfd, -dsize, SEEK_SET);
758 fstat(infd, &statbuf);
759 fsize = statbuf.st_size;
761 fsize = lseek(infd, 0, SEEK_END);
764 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
765 FDIO.ChunkSendRemain = fsize;
766 FDIO.TotalSentAlready = dsize;
769 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
776 "failed to append to %s [%s]; rolling back..\n",
777 spooloutfilename, strerror(errno)
779 /* whoops partial append?? truncate spooloutfilename again! */
780 ftruncate(outfd, dsize);
782 FDIOBufferDelete(&FDIO);
785 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
791 FreeStrBuf(&NextHop);
793 "skipping Spoolcleanup because of %d files unprocessed.\n",
800 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
801 dp = opendir(ctdl_netout_dir);
803 FreeStrBuf(&NextHop);
808 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
809 (filedir_entry != NULL))
811 #ifdef _DIRENT_HAVE_D_NAMLEN
812 d_namelen = filedir_entry->d_namelen;
815 d_namelen = strlen(filedir_entry->d_name);
818 #ifdef _DIRENT_HAVE_D_TYPE
819 d_type = filedir_entry->d_type;
823 if (d_type == DT_DIR)
826 if ((d_namelen == 1) &&
827 (filedir_entry->d_name[0] == '.'))
830 if ((d_namelen == 2) &&
831 (filedir_entry->d_name[0] == '.') &&
832 (filedir_entry->d_name[1] == '.'))
835 pch = strchr(filedir_entry->d_name, '@');
836 if (pch == NULL) /* no @ in name? consolidated file. */
840 filedir_entry->d_name,
841 pch - filedir_entry->d_name);
847 filedir_entry->d_name
850 i = CtdlIsValidNode(&nexthop,
856 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
860 FreeStrBuf(&NextHop);
869 * It's ok if these directories already exist. Just fail silently.
871 void create_spool_dirs(void) {
872 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
873 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
874 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
875 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
876 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
877 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
878 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
879 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
880 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
881 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
882 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
883 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
884 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
885 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
886 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
887 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
893 CTDL_MODULE_INIT(network_spool)
897 CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, 5, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
898 CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine, 0, 4, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
899 CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, 1, SerializeLastSent, DeleteLastSent);
900 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric, 0, 2, SerializeGeneric, DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
901 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
902 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
903 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
904 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
907 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
909 return "network_spool";