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"
88 void ParseLastSent(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
90 rncfg->lastsent = extract_long(LinePos, 0);
92 void ParseIgnetPushShare(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
95 extract_token(nodename, LinePos, 0, '|', sizeof nodename);
96 extract_token(roomname, LinePos, 1, '|', sizeof roomname);
97 mptr = (maplist *) malloc(sizeof(maplist));
98 mptr->next = rncfg->RNCfg->ignet_push_shares;
99 strcpy(mptr->remote_nodename, nodename);
100 strcpy(mptr->remote_roomname, roomname);
101 rncfg->RNCfg->ignet_push_shares = mptr;
105 void ParseRoomAlias(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
108 if (rncfg->RNCfg->sender != NULL)
109 continue; / * just one alowed... * /
110 extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
111 rncfg->RNCfg->sender = nptr;
115 void ParseSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
118 if (time(NULL) - extract_long(LinePos, 3) > EXP) {
126 void ParseUnSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
128 ///int skipthisline = 0;
129 if (time(NULL) - extract_long(LinePos, 2) > EXP) {
136 void SerializeLastSent(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
138 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
139 StrBufAppendPrintf(OutputBuffer, "|%ld\n", RNCfg->lastsent);
142 void SerializeIgnetPushShare(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
144 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
146 StrBufAppendPrintf(Cfg, "ignet_push_share|%s", RNCfg->ignet_push_shares->remote_nodename);
147 if (!IsEmptyStr(RNCfg->ignet_push_shares->remote_roomname)) {
148 StrBufAppendPrintf(Cfg, "|%s", RNCfg->ignet_push_shares->remote_roomname);
150 StrBufAppendPrintf(Cfg, "\n");
151 mptr = RNCfg->ignet_push_shares->next;
152 free(RNCfg->ignet_push_shares);
153 RNCfg->ignet_push_shares = mptr;
155 StrBufAppendBuf(OutputBuffer, data->Value, 0);
156 StrBufAppendBufPlain(OutputBuffer, HKEY("\n"), 0);
161 * Batch up and send all outbound traffic from the current room
163 void network_spoolout_room(RoomProcList *room_to_spool,
164 HashList *working_ignetcfg,
165 HashList *the_netmap)
168 char filename[PATH_MAX];
173 * If the room doesn't exist, don't try to perform its networking tasks.
174 * Normally this should never happen, but once in a while maybe a room gets
175 * queued for networking and then deleted before it can happen.
177 if (CtdlGetRoom(&CC->room, room_to_spool->name) != 0) {
178 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
182 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
183 begin_critical_section(S_NETCONFIGS);
185 /* Only do net processing for rooms that have netconfigs */
186 if (!read_spoolcontrol_file(&sc, filename))
188 end_critical_section(S_NETCONFIGS);
191 syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
193 sc->working_ignetcfg = working_ignetcfg;
194 sc->the_netmap = the_netmap;
196 /* If there are digest recipients, we have to build a digest */
197 if (sc->RNCfg->NetConfigs[digestrecp] != NULL) {
198 sc->digestfp = tmpfile();
199 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
202 /* Do something useful */
203 CtdlForEachMessage(MSGS_GT, sc->RNCfg->lastsent, NULL, NULL, NULL,
204 network_spool_msg, sc);
206 /* If we wrote a digest, deliver it and then close it */
207 snprintf(buf, sizeof buf, "room_%s@%s",
208 CC->room.QRname, config.c_fqdn);
209 for (i=0; buf[i]; ++i) {
210 buf[i] = tolower(buf[i]);
211 if (isspace(buf[i])) buf[i] = '_';
213 if (sc->digestfp != NULL) {
214 fprintf(sc->digestfp, " -----------------------------------"
215 "------------------------------------"
217 "You are subscribed to the '%s' "
219 "To post to the list: %s\n",
222 network_deliver_digest(sc); /* deliver and close */
225 /* Now rewrite the config file */
226 //// todo writenfree_spoolcontrol_file(&sc, filename);
227 end_critical_section(S_NETCONFIGS);
231 * Process a buffer containing a single message from a single file
232 * from the inbound queue
234 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
236 struct CitContext *CCC = CC;
238 struct CtdlMessage *msg = NULL;
241 struct recptypes *recp = NULL;
242 char target_room[ROOMNAMELEN];
243 struct ser_ret sermsg;
244 char *oldpath = NULL;
245 char filename[PATH_MAX];
247 const StrBuf *nexthop = NULL;
248 unsigned char firstbyte;
249 unsigned char lastbyte;
251 QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
253 /* Validate just a little bit. First byte should be FF and * last byte should be 00. */
254 firstbyte = buffer[0];
255 lastbyte = buffer[size-1];
256 if ( (firstbyte != 255) || (lastbyte != 0) ) {
257 QN_syslog(LOG_ERR, "Corrupt message ignored. Length=%ld, firstbyte = %d, lastbyte = %d\n",
258 size, firstbyte, lastbyte);
262 /* Set default target room to trash */
263 strcpy(target_room, TWITROOM);
265 /* Load the message into memory */
266 msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
267 memset(msg, 0, sizeof(struct CtdlMessage));
268 msg->cm_magic = CTDLMESSAGE_MAGIC;
269 msg->cm_anon_type = buffer[1];
270 msg->cm_format_type = buffer[2];
272 for (pos = 3; pos < size; ++pos) {
274 msg->cm_fields[field] = strdup(&buffer[pos+1]);
275 pos = pos + strlen(&buffer[(int)pos]);
278 /* Check for message routing */
279 if (msg->cm_fields['D'] != NULL) {
280 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
282 /* route the message */
283 Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
284 if (CtdlIsValidNode(&nexthop,
290 /* prepend our node to the path */
291 if (msg->cm_fields['P'] != NULL) {
292 oldpath = msg->cm_fields['P'];
293 msg->cm_fields['P'] = NULL;
296 oldpath = strdup("unknown_user");
298 size = strlen(oldpath) + SIZ;
299 msg->cm_fields['P'] = malloc(size);
300 snprintf(msg->cm_fields['P'], size, "%s!%s",
301 config.c_nodename, oldpath);
304 /* serialize the message */
305 serialize_message(&sermsg, msg);
308 if (StrLength(nexthop) == 0) {
319 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
320 fp = fopen(filename, "ab");
322 fwrite(sermsg.ser, sermsg.len, 1, fp);
326 QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
329 CtdlFreeMessage(msg);
334 else { /* invalid destination node name */
338 "A message you sent could not be delivered due to an invalid destination node"
339 " name. Please check the address and try sending the message again.\n");
348 * Check to see if we already have a copy of this message, and
349 * abort its processing if so. (We used to post a warning to Aide>
350 * every time this happened, but the network is now so densely
351 * connected that it's inevitable.)
353 if (network_usetable(msg) != 0) {
354 CtdlFreeMessage(msg);
358 /* Learn network topology from the path */
359 if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
360 NetworkLearnTopology(msg->cm_fields['N'],
366 /* Is the sending node giving us a very persuasive suggestion about
367 * which room this message should be saved in? If so, go with that.
369 if (msg->cm_fields['C'] != NULL) {
370 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
373 /* Otherwise, does it have a recipient? If so, validate it... */
374 else if (msg->cm_fields['R'] != NULL) {
375 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
376 if (recp != NULL) if (recp->num_error != 0) {
378 "A message you sent could not be delivered due to an invalid address.\n"
379 "Please check the address and try sending the message again.\n");
381 free_recipients(recp);
382 QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
385 strcpy(target_room, ""); /* no target room if mail */
388 /* Our last shot at finding a home for this message is to see if
389 * it has the O field (Originating room) set.
391 else if (msg->cm_fields['O'] != NULL) {
392 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
395 /* Strip out fields that are only relevant during transit */
396 if (msg->cm_fields['D'] != NULL) {
397 free(msg->cm_fields['D']);
398 msg->cm_fields['D'] = NULL;
400 if (msg->cm_fields['C'] != NULL) {
401 free(msg->cm_fields['C']);
402 msg->cm_fields['C'] = NULL;
405 /* save the message into a room */
406 if (PerformNetprocHooks(msg, target_room) == 0) {
407 msg->cm_flags = CM_SKIP_HOOKS;
408 CtdlSubmitMsg(msg, recp, target_room, 0);
410 CtdlFreeMessage(msg);
411 free_recipients(recp);
416 * Process a single message from a single file from the inbound queue
418 void network_process_message(FILE *fp,
421 HashList *working_ignetcfg,
422 HashList *the_netmap,
429 hold_pos = ftell(fp);
430 size = msgend - msgstart + 1;
431 buffer = malloc(size);
432 if (buffer != NULL) {
433 fseek(fp, msgstart, SEEK_SET);
434 if (fread(buffer, size, 1, fp) > 0) {
435 network_process_buffer(buffer,
444 fseek(fp, hold_pos, SEEK_SET);
449 * Process a single file from the inbound queue
451 void network_process_file(char *filename,
452 HashList *working_ignetcfg,
453 HashList *the_netmap,
456 struct CitContext *CCC = CC;
458 long msgstart = (-1L);
464 fp = fopen(filename, "rb");
466 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
470 fseek(fp, 0L, SEEK_END);
471 QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
474 /* Look for messages in the data stream and break them out */
475 while (ch = getc(fp), ch >= 0) {
478 if (msgstart >= 0L) {
480 network_process_message(fp,
494 if (msgstart >= 0L) {
495 network_process_message(fp,
509 * Process anything in the inbound queue
511 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
513 struct CitContext *CCC = CC;
517 char filename[PATH_MAX];
518 static time_t last_spoolin_mtime = 0L;
521 * Check the spoolin directory's modification time. If it hasn't
522 * been touched, we don't need to scan it.
524 if (stat(ctdl_netin_dir, &statbuf)) return;
525 if (statbuf.st_mtime == last_spoolin_mtime) {
526 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
529 last_spoolin_mtime = statbuf.st_mtime;
530 QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
533 * Ok, there's something interesting in there, so scan it.
535 dp = opendir(ctdl_netin_dir);
536 if (dp == NULL) return;
538 while (d = readdir(dp), d != NULL) {
539 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
546 network_process_file(filename,
557 * Step 1: consolidate files in the outbound queue into one file per neighbor node
558 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
560 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
562 struct CitContext *CCC = CC;
568 struct dirent *filedir_entry;
570 char spooloutfilename[PATH_MAX];
571 char filename[PATH_MAX];
572 const StrBuf *nexthop;
578 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
579 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
580 if (d == NULL) return;
582 dp = opendir(ctdl_netout_dir);
588 NextHop = NewStrBuf();
589 memset(&IOB, 0, sizeof(IOBuffer));
590 memset(&FDIO, 0, sizeof(FDIOBuffer));
593 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
594 (filedir_entry != NULL))
596 #ifdef _DIRENT_HAVE_D_NAMELEN
597 d_namelen = filedir_entry->d_namelen;
606 #define IFTODT(mode) (((mode) & 0170000) >> 12)
607 #define DTTOIF(dirtype) ((dirtype) << 12)
609 d_namelen = strlen(filedir_entry->d_name);
611 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
612 continue; /* Ignore backup files... */
614 if ((d_namelen == 1) &&
615 (filedir_entry->d_name[0] == '.'))
618 if ((d_namelen == 2) &&
619 (filedir_entry->d_name[0] == '.') &&
620 (filedir_entry->d_name[1] == '.'))
623 pch = strchr(filedir_entry->d_name, '@');
631 filedir_entry->d_name);
634 filedir_entry->d_name,
635 pch - filedir_entry->d_name);
637 snprintf(spooloutfilename,
638 sizeof spooloutfilename,
643 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
644 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
647 "Currently online with %s - skipping for now\n",
655 const char *err = NULL;
656 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
658 infd = open(filename, O_RDONLY);
662 "failed to open %s for reading due to %s; skipping.\n",
663 filename, strerror(errno)
665 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
669 outfd = open(spooloutfilename,
670 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
674 outfd = open(spooloutfilename,
675 O_EXCL|O_NONBLOCK|O_WRONLY,
681 "failed to open %s for reading due to %s; skipping.\n",
682 spooloutfilename, strerror(errno)
685 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
689 dsize = lseek(outfd, 0, SEEK_END);
690 lseek(outfd, -dsize, SEEK_SET);
692 fstat(infd, &statbuf);
693 fsize = statbuf.st_size;
695 fsize = lseek(infd, 0, SEEK_END);
698 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
699 FDIO.ChunkSendRemain = fsize;
700 FDIO.TotalSentAlready = dsize;
703 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
710 "failed to append to %s [%s]; rolling back..\n",
711 spooloutfilename, strerror(errno)
713 /* whoops partial append?? truncate spooloutfilename again! */
714 ftruncate(outfd, dsize);
716 FDIOBufferDelete(&FDIO);
719 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
725 FreeStrBuf(&NextHop);
727 "skipping Spoolcleanup because of %d files unprocessed.\n",
734 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
735 dp = opendir(ctdl_netout_dir);
737 FreeStrBuf(&NextHop);
742 while ((readdir_r(dp, d, &filedir_entry) == 0) &&
743 (filedir_entry != NULL))
745 #ifdef _DIRENT_HAVE_D_NAMELEN
746 d_namelen = filedir_entry->d_namelen;
747 d_type = filedir_entry->d_type;
756 #define IFTODT(mode) (((mode) & 0170000) >> 12)
757 #define DTTOIF(dirtype) ((dirtype) << 12)
759 d_namelen = strlen(filedir_entry->d_name);
761 if ((d_namelen == 1) &&
762 (filedir_entry->d_name[0] == '.'))
765 if ((d_namelen == 2) &&
766 (filedir_entry->d_name[0] == '.') &&
767 (filedir_entry->d_name[1] == '.'))
770 pch = strchr(filedir_entry->d_name, '@');
771 if (pch == NULL) /* no @ in name? consolidated file. */
775 filedir_entry->d_name,
776 pch - filedir_entry->d_name);
782 filedir_entry->d_name
785 i = CtdlIsValidNode(&nexthop,
791 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
795 FreeStrBuf(&NextHop);
804 * It's ok if these directories already exist. Just fail silently.
806 void create_spool_dirs(void) {
807 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
808 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
809 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
810 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
811 if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
812 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
813 if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
814 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
815 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
816 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
817 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
818 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
819 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
820 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
821 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
822 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
828 CTDL_MODULE_INIT(network_spool)
832 // CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, SerializeSubPendingLine, DeleteSubPendingLine); /// todo: move this to mailinglist manager
833 // CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine0, SerializeUnSubPendingLine, DeleteUnSubPendingLine); /// todo: move this to mailinglist manager
834 // CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, SerializeLastSent, DeleteLastSent);
835 /// CtdlREGISTERRoomCfgType(ignet_push_share, ParseIgnetPushShare, 0, SerializeIgnetPushShare, DeleteIgnetPushShare); // todo: move this to the ignet client
836 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
837 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
838 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, SerializeGeneric, DeleteGenericCfgLine);
839 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, SerializeGeneric, DeleteGenericCfgLine);
842 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
844 return "network_spool";