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 *rncfg)
99 rncfg->lastsent = extract_long(LinePos, 0);
101 void ParseIgnetPushShare(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
104 extract_token(nodename, LinePos, 0, '|', sizeof nodename);
105 extract_token(roomname, LinePos, 1, '|', sizeof roomname);
106 mptr = (maplist *) malloc(sizeof(maplist));
107 mptr->next = rncfg->RNCfg->ignet_push_shares;
108 strcpy(mptr->remote_nodename, nodename);
109 strcpy(mptr->remote_roomname, roomname);
110 rncfg->RNCfg->ignet_push_shares = mptr;
114 void ParseRoomAlias(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
117 if (rncfg->RNCfg->sender != NULL)
118 continue; / * just one alowed... * /
119 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
120 rncfg->RNCfg->sender = nptr;
124 void ParseSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
127 if (time(NULL) - extract_long(LinePos, 3) > EXP) {
135 void ParseUnSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
137 ///int skipthisline = 0;
138 if (time(NULL) - extract_long(LinePos, 2) > EXP) {
145 void SerializeLastSent(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
147 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
148 StrBufAppendPrintf(OutputBuffer, "|%ld\n", RNCfg->lastsent);
151 void SerializeIgnetPushShare(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
153 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
155 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", RNCfg->ignet_push_shares->remote_nodename);
156 if (!IsEmptyStr(RNCfg->ignet_push_shares->remote_roomname)) {
157 StrBufAppendPrintf(Cfg, "|%s", RNCfg->ignet_push_shares->remote_roomname);
159 StrBufAppendPrintf(Cfg, "\n");
160 mptr = RNCfg->ignet_push_shares->next;
161 free(RNCfg->ignet_push_shares);
162 RNCfg->ignet_push_shares = mptr;
164 StrBufAppendBuf(OutputBuffer, data->Value, 0);
165 StrBufAppendBufPlain(OutputBuffer, HKEY("\n"), 0);
170 * Batch up and send all outbound traffic from the current room
172 void network_spoolout_room(RoomProcList *room_to_spool,
173 HashList *working_ignetcfg,
174 HashList *the_netmap)
177 char filename[PATH_MAX];
182 * If the room doesn't exist, don't try to perform its networking tasks.
183 * Normally this should never happen, but once in a while maybe a room gets
184 * queued for networking and then deleted before it can happen.
186 if (CtdlGetRoom(&CC->room, room_to_spool->name) != 0) {
187 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
191 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
192 begin_critical_section(S_NETCONFIGS);
194 /* Only do net processing for rooms that have netconfigs */
195 if (!read_spoolcontrol_file(&sc, filename))
197 end_critical_section(S_NETCONFIGS);
200 syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
202 sc->working_ignetcfg = working_ignetcfg;
203 sc->the_netmap = the_netmap;
205 /* If there are digest recipients, we have to build a digest */
206 if (sc->RNCfg->NetConfigs[digestrecp] != NULL) {
207 sc->digestfp = tmpfile();
208 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
211 /* Do something useful */
212 CtdlForEachMessage(MSGS_GT, sc->RNCfg->lastsent, NULL, NULL, NULL,
213 network_spool_msg, sc);
215 /* If we wrote a digest, deliver it and then close it */
216 snprintf(buf, sizeof buf, "room_%s@%s",
217 CC->room.QRname, config.c_fqdn);
218 for (i=0; buf[i]; ++i) {
219 buf[i] = tolower(buf[i]);
220 if (isspace(buf[i])) buf[i] = '_';
222 if (sc->digestfp != NULL) {
223 fprintf(sc->digestfp, " -----------------------------------"
224 "------------------------------------"
226 "You are subscribed to the '%s' "
228 "To post to the list: %s\n",
231 network_deliver_digest(sc); /* deliver and close */
234 /* Now rewrite the config file */
235 //// todo writenfree_spoolcontrol_file(&sc, filename);
236 end_critical_section(S_NETCONFIGS);
240 * Process a buffer containing a single message from a single file
241 * from the inbound queue
243 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
245 struct CitContext *CCC = CC;
247 struct CtdlMessage *msg = NULL;
250 struct recptypes *recp = NULL;
251 char target_room[ROOMNAMELEN];
252 struct ser_ret sermsg;
253 char *oldpath = NULL;
254 char filename[PATH_MAX];
256 const StrBuf *nexthop = NULL;
257 unsigned char firstbyte;
258 unsigned char lastbyte;
260 QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
262 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
263 firstbyte = buffer[0];
264 lastbyte = buffer[size-1];
265 if ( (firstbyte != 255) || (lastbyte != 0) ) {
266 QN_syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
267 size, firstbyte, lastbyte);
271 /* Set default target room to trash */
272 strcpy(target_room, TWITROOM);
274 /* Load the message into memory */
275 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
276 memset(msg, 0, sizeof(struct CtdlMessage));
277 msg->cm_magic = CTDLMESSAGE_MAGIC;
278 msg->cm_anon_type = buffer[1];
279 msg->cm_format_type = buffer[2];
281 for (pos = 3; pos < size; ++pos) {
283 msg->cm_fields[field] = strdup(&buffer[pos+1]);
284 pos = pos + strlen(&buffer[(int)pos]);
287 /* Check for message routing */
288 if (msg->cm_fields['D'] != NULL) {
289 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
291 /* route the message */
292 Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
293 if (CtdlIsValidNode(&nexthop,
299 /* prepend our node to the path */
300 if (msg->cm_fields['P'] != NULL) {
301 oldpath = msg->cm_fields['P'];
302 msg->cm_fields['P'] = NULL;
305 oldpath = strdup("unknown_user");
307 size = strlen(oldpath) + SIZ;
308 msg->cm_fields['P'] = malloc(size);
309 snprintf(msg->cm_fields['P'], size, "%s!%s",
310 config.c_nodename, oldpath);
313 /* serialize the message */
314 serialize_message(&sermsg, msg);
317 if (StrLength(nexthop) == 0) {
328 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
329 fp = fopen(filename, "ab");
331 fwrite(sermsg.ser, sermsg.len, 1, fp);
335 QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
338 CtdlFreeMessage(msg);
343 else { /* invalid destination node name */
347 "A message you sent could not be delivered due to an invalid destination node"
348 " name. Please check the address and try sending the message again.\n");
357 * Check to see if we already have a copy of this message, and
358 * abort its processing if so. (We used to post a warning to Aide>
359 * every time this happened, but the network is now so densely
360 * connected that it's inevitable.)
362 if (network_usetable(msg) != 0) {
363 CtdlFreeMessage(msg);
367 /* Learn network topology from the path */
368 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
369 NetworkLearnTopology(msg->cm_fields['N'],
375 /* Is the sending node giving us a very persuasive suggestion about
376 * which room this message should be saved in? If so, go with that.
378 if (msg->cm_fields['C'] != NULL) {
379 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
382 /* Otherwise, does it have a recipient? If so, validate it... */
383 else if (msg->cm_fields['R'] != NULL) {
384 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
385 if (recp != NULL) if (recp->num_error != 0) {
387 "A message you sent could not be delivered due to an invalid address.\n"
388 "Please check the address and try sending the message again.\n");
390 free_recipients(recp);
391 QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
394 strcpy(target_room, ""); /* no target room if mail */
397 /* Our last shot at finding a home for this message is to see if
398 * it has the O field (Originating room) set.
400 else if (msg->cm_fields['O'] != NULL) {
401 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
404 /* Strip out fields that are only relevant during transit */
405 if (msg->cm_fields['D'] != NULL) {
406 free(msg->cm_fields['D']);
407 msg->cm_fields['D'] = NULL;
409 if (msg->cm_fields['C'] != NULL) {
410 free(msg->cm_fields['C']);
411 msg->cm_fields['C'] = NULL;
414 /* save the message into a room */
415 if (PerformNetprocHooks(msg, target_room) == 0) {
416 msg->cm_flags = CM_SKIP_HOOKS;
417 CtdlSubmitMsg(msg, recp, target_room, 0);
419 CtdlFreeMessage(msg);
420 free_recipients(recp);
425 * Process a single message from a single file from the inbound queue
427 void network_process_message(FILE *fp,
430 HashList *working_ignetcfg,
431 HashList *the_netmap,
438 hold_pos = ftell(fp);
439 size = msgend - msgstart + 1;
440 buffer = malloc(size);
441 if (buffer != NULL) {
442 fseek(fp, msgstart, SEEK_SET);
443 if (fread(buffer, size, 1, fp) > 0) {
444 network_process_buffer(buffer,
453 fseek(fp, hold_pos, SEEK_SET);
458 * Process a single file from the inbound queue
460 void network_process_file(char *filename,
461 HashList *working_ignetcfg,
462 HashList *the_netmap,
465 struct CitContext *CCC = CC;
467 long msgstart = (-1L);
473 fp = fopen(filename, "rb");
475 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
479 fseek(fp, 0L, SEEK_END);
480 QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
483 /* Look for messages in the data stream and break them out */
484 while (ch = getc(fp), ch >= 0) {
487 if (msgstart >= 0L) {
489 network_process_message(fp,
503 if (msgstart >= 0L) {
504 network_process_message(fp,
518 * Process anything in the inbound queue
520 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
522 struct CitContext *CCC = CC;
525 struct dirent *filedir_entry;
527 char filename[PATH_MAX];
528 static time_t last_spoolin_mtime = 0L;
533 * Check the spoolin directory's modification time. If it hasn't
534 * been touched, we don't need to scan it.
536 if (stat(ctdl_netin_dir, &statbuf)) return;
537 if (statbuf.st_mtime == last_spoolin_mtime) {
538 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
541 last_spoolin_mtime = statbuf.st_mtime;
542 QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
545 * Ok, there's something interesting in there, so scan it.
547 dp = opendir(ctdl_netin_dir);
548 if (dp == NULL) return;
550 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
556 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
557 (filedir_entry != NULL))
559 #ifdef _DIRENT_HAVE_D_NAMLEN
560 d_namelen = filedir_entry->d_namelen;
563 d_namelen = strlen(filedir_entry->d_name);
566 #ifdef _DIRENT_HAVE_D_TYPE
567 d_type = filedir_entry->d_type;
571 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
572 continue; /* Ignore backup files... */
574 if ((d_namelen == 1) &&
575 (filedir_entry->d_name[0] == '.'))
578 if ((d_namelen == 2) &&
579 (filedir_entry->d_name[0] == '.') &&
580 (filedir_entry->d_name[1] == '.'))
583 if (d_type == DT_UNKNOWN) {
591 filedir_entry->d_name);
593 if (lstat(path, &s) == 0) {
594 d_type = IFTODT(s.st_mode);
602 case DT_LNK: /* TODO: check whether its a file or a directory */
610 network_process_file(filename,
622 * Step 1: consolidate files in the outbound queue into one file per neighbor node
623 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
625 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
627 struct CitContext *CCC = CC;
633 struct dirent *filedir_entry;
635 char spooloutfilename[PATH_MAX];
636 char filename[PATH_MAX];
637 const StrBuf *nexthop;
645 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
646 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
647 if (d == NULL) return;
649 dp = opendir(ctdl_netout_dir);
655 NextHop = NewStrBuf();
656 memset(&IOB, 0, sizeof(IOBuffer));
657 memset(&FDIO, 0, sizeof(FDIOBuffer));
660 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
661 (filedir_entry != NULL))
663 #ifdef _DIRENT_HAVE_D_NAMLEN
664 d_namelen = filedir_entry->d_namelen;
667 d_namelen = strlen(filedir_entry->d_name);
670 #ifdef _DIRENT_HAVE_D_TYPE
671 d_type = filedir_entry->d_type;
675 if (d_type == DT_DIR)
678 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
679 continue; /* Ignore backup files... */
681 if ((d_namelen == 1) &&
682 (filedir_entry->d_name[0] == '.'))
685 if ((d_namelen == 2) &&
686 (filedir_entry->d_name[0] == '.') &&
687 (filedir_entry->d_name[1] == '.'))
690 pch = strchr(filedir_entry->d_name, '@');
698 filedir_entry->d_name);
701 filedir_entry->d_name,
702 pch - filedir_entry->d_name);
704 snprintf(spooloutfilename,
705 sizeof spooloutfilename,
710 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
711 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
714 "Currently online with %s - skipping for now\n",
722 const char *err = NULL;
723 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
725 infd = open(filename, O_RDONLY);
729 "failed to open %s for reading due to %s; skipping.\n",
730 filename, strerror(errno)
732 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
736 outfd = open(spooloutfilename,
737 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
741 outfd = open(spooloutfilename,
742 O_EXCL|O_NONBLOCK|O_WRONLY,
748 "failed to open %s for reading due to %s; skipping.\n",
749 spooloutfilename, strerror(errno)
752 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
756 dsize = lseek(outfd, 0, SEEK_END);
757 lseek(outfd, -dsize, SEEK_SET);
759 fstat(infd, &statbuf);
760 fsize = statbuf.st_size;
762 fsize = lseek(infd, 0, SEEK_END);
765 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
766 FDIO.ChunkSendRemain = fsize;
767 FDIO.TotalSentAlready = dsize;
770 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
777 "failed to append to %s [%s]; rolling back..\n",
778 spooloutfilename, strerror(errno)
780 /* whoops partial append?? truncate spooloutfilename again! */
781 ftruncate(outfd, dsize);
783 FDIOBufferDelete(&FDIO);
786 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
792 FreeStrBuf(&NextHop);
794 "skipping Spoolcleanup because of %d files unprocessed.\n",
801 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
802 dp = opendir(ctdl_netout_dir);
804 FreeStrBuf(&NextHop);
809 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
810 (filedir_entry != NULL))
812 #ifdef _DIRENT_HAVE_D_NAMLEN
813 d_namelen = filedir_entry->d_namelen;
816 d_namelen = strlen(filedir_entry->d_name);
819 #ifdef _DIRENT_HAVE_D_TYPE
820 d_type = filedir_entry->d_type;
824 if (d_type == DT_DIR)
827 if ((d_namelen == 1) &&
828 (filedir_entry->d_name[0] == '.'))
831 if ((d_namelen == 2) &&
832 (filedir_entry->d_name[0] == '.') &&
833 (filedir_entry->d_name[1] == '.'))
836 pch = strchr(filedir_entry->d_name, '@');
837 if (pch == NULL) /* no @ in name? consolidated file. */
841 filedir_entry->d_name,
842 pch - filedir_entry->d_name);
848 filedir_entry->d_name
851 i = CtdlIsValidNode(&nexthop,
857 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
861 FreeStrBuf(&NextHop);
870 * It's ok if these directories already exist. Just fail silently.
872 void create_spool_dirs(void) {
873 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
874 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
875 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
876 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
877 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
878 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
879 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
880 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
881 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
882 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
883 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
884 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
885 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
886 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
887 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
888 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
894 CTDL_MODULE_INIT(network_spool)
898 // CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, SerializeSubPendingLine, DeleteSubPendingLine); /// todo: move this to mailinglist manager
899 // CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine0, SerializeUnSubPendingLine, DeleteUnSubPendingLine); /// todo: move this to mailinglist manager
900 // CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, SerializeLastSent, DeleteLastSent);
901 /// CtdlREGISTERRoomCfgType(ignet_push_share, ParseIgnetPushShare, 0, SerializeIgnetPushShare, DeleteIgnetPushShare); // todo: move this to the ignet client
902 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
903 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
904 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
905 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, SerializeGeneric, DeleteGenericCfgLine);
908 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
910 return "network_spool";