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)
156 char filename[PATH_MAX];
161 * If the room doesn't exist, don't try to perform its networking tasks.
162 * Normally this should never happen, but once in a while maybe a room gets
163 * queued for networking and then deleted before it can happen.
165 if (CtdlGetRoom(&CC->room, room_to_spool->name) != 0) {
166 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
170 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
171 begin_critical_section(S_NETCONFIGS);
173 /* Only do net processing for rooms that have netconfigs */
174 if (!ReadRoomNetConfigFile(&sc, filename))
176 end_critical_section(S_NETCONFIGS);
179 syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
181 sc->working_ignetcfg = working_ignetcfg;
182 sc->the_netmap = the_netmap;
184 /* If there are digest recipients, we have to build a digest */
185 if (sc->NetConfigs[digestrecp] != NULL) {
186 sc->digestfp = tmpfile();
187 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
190 /* Do something useful */
191 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
192 network_spool_msg, sc);
194 /* If we wrote a digest, deliver it and then close it */
195 snprintf(buf, sizeof buf, "room_%s@%s",
196 CC->room.QRname, config.c_fqdn);
197 for (i=0; buf[i]; ++i) {
198 buf[i] = tolower(buf[i]);
199 if (isspace(buf[i])) buf[i] = '_';
201 if (sc->digestfp != NULL) {
202 fprintf(sc->digestfp, " -----------------------------------"
203 "------------------------------------"
205 "You are subscribed to the '%s' "
207 "To post to the list: %s\n",
210 network_deliver_digest(sc); /* deliver and close */
213 /* Now rewrite the config file */
214 //// todo writenfree_spoolcontrol_file(&sc, filename);
215 end_critical_section(S_NETCONFIGS);
219 * Process a buffer containing a single message from a single file
220 * from the inbound queue
222 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
224 struct CitContext *CCC = CC;
226 struct CtdlMessage *msg = NULL;
229 struct recptypes *recp = NULL;
230 char target_room[ROOMNAMELEN];
231 struct ser_ret sermsg;
232 char *oldpath = NULL;
233 char filename[PATH_MAX];
235 const StrBuf *nexthop = NULL;
236 unsigned char firstbyte;
237 unsigned char lastbyte;
239 QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
241 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
242 firstbyte = buffer[0];
243 lastbyte = buffer[size-1];
244 if ( (firstbyte != 255) || (lastbyte != 0) ) {
245 QN_syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
246 size, firstbyte, lastbyte);
250 /* Set default target room to trash */
251 strcpy(target_room, TWITROOM);
253 /* Load the message into memory */
254 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
255 memset(msg, 0, sizeof(struct CtdlMessage));
256 msg->cm_magic = CTDLMESSAGE_MAGIC;
257 msg->cm_anon_type = buffer[1];
258 msg->cm_format_type = buffer[2];
260 for (pos = 3; pos < size; ++pos) {
262 msg->cm_fields[field] = strdup(&buffer[pos+1]);
263 pos = pos + strlen(&buffer[(int)pos]);
266 /* Check for message routing */
267 if (msg->cm_fields['D'] != NULL) {
268 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
270 /* route the message */
271 Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
272 if (CtdlIsValidNode(&nexthop,
278 /* prepend our node to the path */
279 if (msg->cm_fields['P'] != NULL) {
280 oldpath = msg->cm_fields['P'];
281 msg->cm_fields['P'] = NULL;
284 oldpath = strdup("unknown_user");
286 size = strlen(oldpath) + SIZ;
287 msg->cm_fields['P'] = malloc(size);
288 snprintf(msg->cm_fields['P'], size, "%s!%s",
289 config.c_nodename, oldpath);
292 /* serialize the message */
293 serialize_message(&sermsg, msg);
296 if (StrLength(nexthop) == 0) {
307 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
308 fp = fopen(filename, "ab");
310 fwrite(sermsg.ser, sermsg.len, 1, fp);
314 QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
317 CtdlFreeMessage(msg);
322 else { /* invalid destination node name */
326 "A message you sent could not be delivered due to an invalid destination node"
327 " name. Please check the address and try sending the message again.\n");
336 * Check to see if we already have a copy of this message, and
337 * abort its processing if so. (We used to post a warning to Aide>
338 * every time this happened, but the network is now so densely
339 * connected that it's inevitable.)
341 if (network_usetable(msg) != 0) {
342 CtdlFreeMessage(msg);
346 /* Learn network topology from the path */
347 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
348 NetworkLearnTopology(msg->cm_fields['N'],
354 /* Is the sending node giving us a very persuasive suggestion about
355 * which room this message should be saved in? If so, go with that.
357 if (msg->cm_fields['C'] != NULL) {
358 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
361 /* Otherwise, does it have a recipient? If so, validate it... */
362 else if (msg->cm_fields['R'] != NULL) {
363 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
364 if (recp != NULL) if (recp->num_error != 0) {
366 "A message you sent could not be delivered due to an invalid address.\n"
367 "Please check the address and try sending the message again.\n");
369 free_recipients(recp);
370 QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
373 strcpy(target_room, ""); /* no target room if mail */
376 /* Our last shot at finding a home for this message is to see if
377 * it has the O field (Originating room) set.
379 else if (msg->cm_fields['O'] != NULL) {
380 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
383 /* Strip out fields that are only relevant during transit */
384 if (msg->cm_fields['D'] != NULL) {
385 free(msg->cm_fields['D']);
386 msg->cm_fields['D'] = NULL;
388 if (msg->cm_fields['C'] != NULL) {
389 free(msg->cm_fields['C']);
390 msg->cm_fields['C'] = NULL;
393 /* save the message into a room */
394 if (PerformNetprocHooks(msg, target_room) == 0) {
395 msg->cm_flags = CM_SKIP_HOOKS;
396 CtdlSubmitMsg(msg, recp, target_room, 0);
398 CtdlFreeMessage(msg);
399 free_recipients(recp);
404 * Process a single message from a single file from the inbound queue
406 void network_process_message(FILE *fp,
409 HashList *working_ignetcfg,
410 HashList *the_netmap,
417 hold_pos = ftell(fp);
418 size = msgend - msgstart + 1;
419 buffer = malloc(size);
420 if (buffer != NULL) {
421 fseek(fp, msgstart, SEEK_SET);
422 if (fread(buffer, size, 1, fp) > 0) {
423 network_process_buffer(buffer,
432 fseek(fp, hold_pos, SEEK_SET);
437 * Process a single file from the inbound queue
439 void network_process_file(char *filename,
440 HashList *working_ignetcfg,
441 HashList *the_netmap,
444 struct CitContext *CCC = CC;
446 long msgstart = (-1L);
452 fp = fopen(filename, "rb");
454 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
458 fseek(fp, 0L, SEEK_END);
459 QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
462 /* Look for messages in the data stream and break them out */
463 while (ch = getc(fp), ch >= 0) {
466 if (msgstart >= 0L) {
468 network_process_message(fp,
482 if (msgstart >= 0L) {
483 network_process_message(fp,
497 * Process anything in the inbound queue
499 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
501 struct CitContext *CCC = CC;
504 struct dirent *filedir_entry;
506 char filename[PATH_MAX];
507 static time_t last_spoolin_mtime = 0L;
512 * Check the spoolin directory's modification time. If it hasn't
513 * been touched, we don't need to scan it.
515 if (stat(ctdl_netin_dir, &statbuf)) return;
516 if (statbuf.st_mtime == last_spoolin_mtime) {
517 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
520 last_spoolin_mtime = statbuf.st_mtime;
521 QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
524 * Ok, there's something interesting in there, so scan it.
526 dp = opendir(ctdl_netin_dir);
527 if (dp == NULL) return;
529 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
535 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
536 (filedir_entry != NULL))
538 #ifdef _DIRENT_HAVE_D_NAMLEN
539 d_namelen = filedir_entry->d_namelen;
542 d_namelen = strlen(filedir_entry->d_name);
545 #ifdef _DIRENT_HAVE_D_TYPE
546 d_type = filedir_entry->d_type;
550 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
551 continue; /* Ignore backup files... */
553 if ((d_namelen == 1) &&
554 (filedir_entry->d_name[0] == '.'))
557 if ((d_namelen == 2) &&
558 (filedir_entry->d_name[0] == '.') &&
559 (filedir_entry->d_name[1] == '.'))
562 if (d_type == DT_UNKNOWN) {
570 filedir_entry->d_name);
572 if (lstat(path, &s) == 0) {
573 d_type = IFTODT(s.st_mode);
581 case DT_LNK: /* TODO: check whether its a file or a directory */
589 network_process_file(filename,
601 * Step 1: consolidate files in the outbound queue into one file per neighbor node
602 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
604 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
606 struct CitContext *CCC = CC;
612 struct dirent *filedir_entry;
614 char spooloutfilename[PATH_MAX];
615 char filename[PATH_MAX];
616 const StrBuf *nexthop;
624 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
625 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
626 if (d == NULL) return;
628 dp = opendir(ctdl_netout_dir);
634 NextHop = NewStrBuf();
635 memset(&IOB, 0, sizeof(IOBuffer));
636 memset(&FDIO, 0, sizeof(FDIOBuffer));
639 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
640 (filedir_entry != NULL))
642 #ifdef _DIRENT_HAVE_D_NAMLEN
643 d_namelen = filedir_entry->d_namelen;
646 d_namelen = strlen(filedir_entry->d_name);
649 #ifdef _DIRENT_HAVE_D_TYPE
650 d_type = filedir_entry->d_type;
654 if (d_type == DT_DIR)
657 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
658 continue; /* Ignore backup files... */
660 if ((d_namelen == 1) &&
661 (filedir_entry->d_name[0] == '.'))
664 if ((d_namelen == 2) &&
665 (filedir_entry->d_name[0] == '.') &&
666 (filedir_entry->d_name[1] == '.'))
669 pch = strchr(filedir_entry->d_name, '@');
677 filedir_entry->d_name);
680 filedir_entry->d_name,
681 pch - filedir_entry->d_name);
683 snprintf(spooloutfilename,
684 sizeof spooloutfilename,
689 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
690 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
693 "Currently online with %s - skipping for now\n",
701 const char *err = NULL;
702 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
704 infd = open(filename, O_RDONLY);
708 "failed to open %s for reading due to %s; skipping.\n",
709 filename, strerror(errno)
711 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
715 outfd = open(spooloutfilename,
716 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
720 outfd = open(spooloutfilename,
721 O_EXCL|O_NONBLOCK|O_WRONLY,
727 "failed to open %s for reading due to %s; skipping.\n",
728 spooloutfilename, strerror(errno)
731 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
735 dsize = lseek(outfd, 0, SEEK_END);
736 lseek(outfd, -dsize, SEEK_SET);
738 fstat(infd, &statbuf);
739 fsize = statbuf.st_size;
741 fsize = lseek(infd, 0, SEEK_END);
744 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
745 FDIO.ChunkSendRemain = fsize;
746 FDIO.TotalSentAlready = dsize;
749 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
756 "failed to append to %s [%s]; rolling back..\n",
757 spooloutfilename, strerror(errno)
759 /* whoops partial append?? truncate spooloutfilename again! */
760 ftruncate(outfd, dsize);
762 FDIOBufferDelete(&FDIO);
765 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
771 FreeStrBuf(&NextHop);
773 "skipping Spoolcleanup because of %d files unprocessed.\n",
780 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
781 dp = opendir(ctdl_netout_dir);
783 FreeStrBuf(&NextHop);
788 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
789 (filedir_entry != NULL))
791 #ifdef _DIRENT_HAVE_D_NAMLEN
792 d_namelen = filedir_entry->d_namelen;
795 d_namelen = strlen(filedir_entry->d_name);
798 #ifdef _DIRENT_HAVE_D_TYPE
799 d_type = filedir_entry->d_type;
803 if (d_type == DT_DIR)
806 if ((d_namelen == 1) &&
807 (filedir_entry->d_name[0] == '.'))
810 if ((d_namelen == 2) &&
811 (filedir_entry->d_name[0] == '.') &&
812 (filedir_entry->d_name[1] == '.'))
815 pch = strchr(filedir_entry->d_name, '@');
816 if (pch == NULL) /* no @ in name? consolidated file. */
820 filedir_entry->d_name,
821 pch - filedir_entry->d_name);
827 filedir_entry->d_name
830 i = CtdlIsValidNode(&nexthop,
836 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
840 FreeStrBuf(&NextHop);
849 * It's ok if these directories already exist. Just fail silently.
851 void create_spool_dirs(void) {
852 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
853 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
854 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
855 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
856 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
857 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
858 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
859 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
860 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
861 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
862 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
863 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
864 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
865 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
866 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
867 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
873 CTDL_MODULE_INIT(network_spool)
877 CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, 5, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
878 CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine, 0, 4, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
879 CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, 1, SerializeLastSent, DeleteLastSent);
880 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric, 0, 2, SerializeGeneric, DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
881 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
882 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
883 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
884 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
887 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
889 return "network_spool";