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));
102 memset(nptr, 0, 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 memset(&sc, 0, sizeof(SpoolControl));
161 sc.RNCfg = room_to_spool->OneRNCfg;
162 sc.lastsent = room_to_spool->OneRNCfg->lastsent;
163 sc.working_ignetcfg = working_ignetcfg;
164 sc.the_netmap = the_netmap;
166 if ((sc.RNCfg->NetConfigs[listrecp] == NULL) &&
167 (sc.RNCfg->NetConfigs[digestrecp] == NULL) &&
168 (sc.RNCfg->NetConfigs[participate] == NULL) &&
169 (sc.RNCfg->NetConfigs[ignet_push_share] == NULL))
171 /* nothing to do for this room... */
176 * If the room doesn't exist, don't try to perform its networking tasks.
177 * Normally this should never happen, but once in a while maybe a room gets
178 * queued for networking and then deleted before it can happen.
180 if (CtdlGetRoom(&CCC->room, room_to_spool->name) != 0) {
181 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
186 syslog(LOG_INFO, "Networking started for <%s>\n", CCC->room.QRname);
188 /* If there are digest recipients, we have to build a digest */
189 if (sc.RNCfg->NetConfigs[digestrecp] != NULL) {
190 sc.digestfp = tmpfile();
191 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
194 /* Do something useful */
195 CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL, NULL,
196 network_spool_msg, &sc);
198 /* If we wrote a digest, deliver it and then close it */
199 if (StrLength(sc.RNCfg->Sender) > 0)
202 len = StrLength(sc.RNCfg->Sender);
203 if (len + 1 > sizeof(buf))
204 len = sizeof(buf) - 1;
205 memcpy(buf, ChrPtr(sc.RNCfg->Sender), len);
210 snprintf(buf, sizeof buf, "room_%s@%s",
211 CCC->room.QRname, config.c_fqdn);
214 for (i=0; buf[i]; ++i) {
215 buf[i] = tolower(buf[i]);
216 if (isspace(buf[i])) buf[i] = '_';
218 if (sc.digestfp != NULL) {
220 " -----------------------------------"
221 "------------------------------------"
223 "You are subscribed to the '%s' "
225 "To post to the list: %s\n",
226 CCC->room.QRname, buf
228 network_deliver_digest(&sc); /* deliver and close */
231 /* Now rewrite the config file */
232 if (sc.lastsent != room_to_spool->OneRNCfg->lastsent)
234 room_to_spool->OneRNCfg->lastsent = sc.lastsent;
235 room_to_spool->OneRNCfg->changed = 1;
237 end_critical_section(S_NETCONFIGS);
241 * Process a buffer containing a single message from a single file
242 * from the inbound queue
244 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
246 struct CitContext *CCC = CC;
248 struct CtdlMessage *msg = NULL;
251 struct recptypes *recp = NULL;
252 char target_room[ROOMNAMELEN];
253 struct ser_ret sermsg;
254 char *oldpath = NULL;
255 char filename[PATH_MAX];
257 const StrBuf *nexthop = NULL;
258 unsigned char firstbyte;
259 unsigned char lastbyte;
261 QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
263 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
264 firstbyte = buffer[0];
265 lastbyte = buffer[size-1];
266 if ( (firstbyte != 255) || (lastbyte != 0) ) {
267 QN_syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
268 size, firstbyte, lastbyte);
272 /* Set default target room to trash */
273 strcpy(target_room, TWITROOM);
275 /* Load the message into memory */
276 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
277 memset(msg, 0, sizeof(struct CtdlMessage));
278 msg->cm_magic = CTDLMESSAGE_MAGIC;
279 msg->cm_anon_type = buffer[1];
280 msg->cm_format_type = buffer[2];
282 for (pos = 3; pos < size; ++pos) {
284 msg->cm_fields[field] = strdup(&buffer[pos+1]);
285 pos = pos + strlen(&buffer[(int)pos]);
288 /* Check for message routing */
289 if (msg->cm_fields['D'] != NULL) {
290 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
292 /* route the message */
293 Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
294 if (CtdlIsValidNode(&nexthop,
300 /* prepend our node to the path */
301 if (msg->cm_fields['P'] != NULL) {
302 oldpath = msg->cm_fields['P'];
303 msg->cm_fields['P'] = NULL;
306 oldpath = strdup("unknown_user");
308 size = strlen(oldpath) + SIZ;
309 msg->cm_fields['P'] = malloc(size);
310 snprintf(msg->cm_fields['P'], size, "%s!%s",
311 config.c_nodename, oldpath);
314 /* serialize the message */
315 serialize_message(&sermsg, msg);
318 if (StrLength(nexthop) == 0) {
329 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
330 fp = fopen(filename, "ab");
332 fwrite(sermsg.ser, sermsg.len, 1, fp);
336 QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
339 CtdlFreeMessage(msg);
344 else { /* invalid destination node name */
348 "A message you sent could not be delivered due to an invalid destination node"
349 " name. Please check the address and try sending the message again.\n");
358 * Check to see if we already have a copy of this message, and
359 * abort its processing if so. (We used to post a warning to Aide>
360 * every time this happened, but the network is now so densely
361 * connected that it's inevitable.)
363 if (network_usetable(msg) != 0) {
364 CtdlFreeMessage(msg);
368 /* Learn network topology from the path */
369 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
370 NetworkLearnTopology(msg->cm_fields['N'],
376 /* Is the sending node giving us a very persuasive suggestion about
377 * which room this message should be saved in? If so, go with that.
379 if (msg->cm_fields['C'] != NULL) {
380 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
383 /* Otherwise, does it have a recipient? If so, validate it... */
384 else if (msg->cm_fields['R'] != NULL) {
385 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
386 if (recp != NULL) if (recp->num_error != 0) {
388 "A message you sent could not be delivered due to an invalid address.\n"
389 "Please check the address and try sending the message again.\n");
391 free_recipients(recp);
392 QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
395 strcpy(target_room, ""); /* no target room if mail */
398 /* Our last shot at finding a home for this message is to see if
399 * it has the O field (Originating room) set.
401 else if (msg->cm_fields['O'] != NULL) {
402 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
405 /* Strip out fields that are only relevant during transit */
406 if (msg->cm_fields['D'] != NULL) {
407 free(msg->cm_fields['D']);
408 msg->cm_fields['D'] = NULL;
410 if (msg->cm_fields['C'] != NULL) {
411 free(msg->cm_fields['C']);
412 msg->cm_fields['C'] = NULL;
415 /* save the message into a room */
416 if (PerformNetprocHooks(msg, target_room) == 0) {
417 msg->cm_flags = CM_SKIP_HOOKS;
418 CtdlSubmitMsg(msg, recp, target_room, 0);
420 CtdlFreeMessage(msg);
421 free_recipients(recp);
426 * Process a single message from a single file from the inbound queue
428 void network_process_message(FILE *fp,
431 HashList *working_ignetcfg,
432 HashList *the_netmap,
439 hold_pos = ftell(fp);
440 size = msgend - msgstart + 1;
441 buffer = malloc(size);
442 if (buffer != NULL) {
443 fseek(fp, msgstart, SEEK_SET);
444 if (fread(buffer, size, 1, fp) > 0) {
445 network_process_buffer(buffer,
454 fseek(fp, hold_pos, SEEK_SET);
459 * Process a single file from the inbound queue
461 void network_process_file(char *filename,
462 HashList *working_ignetcfg,
463 HashList *the_netmap,
466 struct CitContext *CCC = CC;
468 long msgstart = (-1L);
474 fp = fopen(filename, "rb");
476 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
480 fseek(fp, 0L, SEEK_END);
481 QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
484 /* Look for messages in the data stream and break them out */
485 while (ch = getc(fp), ch >= 0) {
488 if (msgstart >= 0L) {
490 network_process_message(fp,
504 if (msgstart >= 0L) {
505 network_process_message(fp,
519 * Process anything in the inbound queue
521 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
523 struct CitContext *CCC = CC;
526 struct dirent *filedir_entry;
528 char filename[PATH_MAX];
529 static time_t last_spoolin_mtime = 0L;
534 * Check the spoolin directory's modification time. If it hasn't
535 * been touched, we don't need to scan it.
537 if (stat(ctdl_netin_dir, &statbuf)) return;
538 if (statbuf.st_mtime == last_spoolin_mtime) {
539 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
542 last_spoolin_mtime = statbuf.st_mtime;
543 QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
546 * Ok, there's something interesting in there, so scan it.
548 dp = opendir(ctdl_netin_dir);
549 if (dp == NULL) return;
551 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
557 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
558 (filedir_entry != NULL))
560 #ifdef _DIRENT_HAVE_D_NAMLEN
561 d_namelen = filedir_entry->d_namelen;
564 d_namelen = strlen(filedir_entry->d_name);
567 #ifdef _DIRENT_HAVE_D_TYPE
568 d_type = filedir_entry->d_type;
572 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
573 continue; /* Ignore backup files... */
575 if ((d_namelen == 1) &&
576 (filedir_entry->d_name[0] == '.'))
579 if ((d_namelen == 2) &&
580 (filedir_entry->d_name[0] == '.') &&
581 (filedir_entry->d_name[1] == '.'))
584 if (d_type == DT_UNKNOWN) {
592 filedir_entry->d_name);
594 if (lstat(path, &s) == 0) {
595 d_type = IFTODT(s.st_mode);
603 case DT_LNK: /* TODO: check whether its a file or a directory */
611 network_process_file(filename,
623 * Step 1: consolidate files in the outbound queue into one file per neighbor node
624 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
626 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
628 struct CitContext *CCC = CC;
634 struct dirent *filedir_entry;
636 char spooloutfilename[PATH_MAX];
637 char filename[PATH_MAX];
638 const StrBuf *nexthop;
646 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
647 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
648 if (d == NULL) return;
650 dp = opendir(ctdl_netout_dir);
656 NextHop = NewStrBuf();
657 memset(&IOB, 0, sizeof(IOBuffer));
658 memset(&FDIO, 0, sizeof(FDIOBuffer));
661 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
662 (filedir_entry != NULL))
664 #ifdef _DIRENT_HAVE_D_NAMLEN
665 d_namelen = filedir_entry->d_namelen;
668 d_namelen = strlen(filedir_entry->d_name);
671 #ifdef _DIRENT_HAVE_D_TYPE
672 d_type = filedir_entry->d_type;
676 if (d_type == DT_DIR)
679 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
680 continue; /* Ignore backup files... */
682 if ((d_namelen == 1) &&
683 (filedir_entry->d_name[0] == '.'))
686 if ((d_namelen == 2) &&
687 (filedir_entry->d_name[0] == '.') &&
688 (filedir_entry->d_name[1] == '.'))
691 pch = strchr(filedir_entry->d_name, '@');
699 filedir_entry->d_name);
702 filedir_entry->d_name,
703 pch - filedir_entry->d_name);
705 snprintf(spooloutfilename,
706 sizeof spooloutfilename,
711 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
712 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
715 "Currently online with %s - skipping for now\n",
723 const char *err = NULL;
724 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
726 infd = open(filename, O_RDONLY);
730 "failed to open %s for reading due to %s; skipping.\n",
731 filename, strerror(errno)
733 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
737 outfd = open(spooloutfilename,
738 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
742 outfd = open(spooloutfilename,
743 O_EXCL|O_NONBLOCK|O_WRONLY,
749 "failed to open %s for reading due to %s; skipping.\n",
750 spooloutfilename, strerror(errno)
753 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
757 dsize = lseek(outfd, 0, SEEK_END);
758 lseek(outfd, -dsize, SEEK_SET);
760 fstat(infd, &statbuf);
761 fsize = statbuf.st_size;
763 fsize = lseek(infd, 0, SEEK_END);
766 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
767 FDIO.ChunkSendRemain = fsize;
768 FDIO.TotalSentAlready = dsize;
771 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
778 "failed to append to %s [%s]; rolling back..\n",
779 spooloutfilename, strerror(errno)
781 /* whoops partial append?? truncate spooloutfilename again! */
782 ftruncate(outfd, dsize);
784 FDIOBufferDelete(&FDIO);
787 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
793 FreeStrBuf(&NextHop);
795 "skipping Spoolcleanup because of %d files unprocessed.\n",
802 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
803 dp = opendir(ctdl_netout_dir);
805 FreeStrBuf(&NextHop);
810 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
811 (filedir_entry != NULL))
813 #ifdef _DIRENT_HAVE_D_NAMLEN
814 d_namelen = filedir_entry->d_namelen;
817 d_namelen = strlen(filedir_entry->d_name);
820 #ifdef _DIRENT_HAVE_D_TYPE
821 d_type = filedir_entry->d_type;
825 if (d_type == DT_DIR)
828 if ((d_namelen == 1) &&
829 (filedir_entry->d_name[0] == '.'))
832 if ((d_namelen == 2) &&
833 (filedir_entry->d_name[0] == '.') &&
834 (filedir_entry->d_name[1] == '.'))
837 pch = strchr(filedir_entry->d_name, '@');
838 if (pch == NULL) /* no @ in name? consolidated file. */
842 filedir_entry->d_name,
843 pch - filedir_entry->d_name);
849 filedir_entry->d_name
852 i = CtdlIsValidNode(&nexthop,
858 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
862 FreeStrBuf(&NextHop);
871 * It's ok if these directories already exist. Just fail silently.
873 void create_spool_dirs(void) {
874 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
875 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
876 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
877 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
878 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
879 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
880 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
881 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
882 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
883 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
884 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
885 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
886 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
887 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
888 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
889 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
895 CTDL_MODULE_INIT(network_spool)
899 CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, 5, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
900 CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine, 0, 4, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
901 CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, 1, SerializeLastSent, DeleteLastSent);
902 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric, 0, 2, SerializeGeneric, DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
903 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
904 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
905 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
906 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
909 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
911 return "network_spool";