2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2017 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>
64 #include <libcitadel.h>
67 #include "citserver.h"
73 #include "internet_addressing.h"
74 #include "serv_network.h"
75 #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)
98 * Bounce a message back to the sender
100 void network_bounce(struct CtdlMessage **pMsg, char *reason)
103 char bouncesource[SIZ];
105 recptypes *valid = NULL;
106 char force_room[ROOMNAMELEN];
107 static int serialnum = 0;
109 struct CtdlMessage *msg = *pMsg;
111 syslog(LOG_DEBUG, "netspool: entering network_bounce()");
113 if (msg == NULL) return;
115 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, CtdlGetConfigStr("c_nodename"));
118 * Give it a fresh message ID
120 len = snprintf(buf, sizeof(buf),
125 CtdlGetConfigStr("c_fqdn"));
127 CM_SetField(msg, emessageId, buf, len);
130 * FIXME ... right now we're just sending a bounce; we really want to
131 * include the text of the bounced message.
133 if (!IsEmptyStr(reason)) {
134 CM_SetField(msg, eMesageText, reason, strlen(reason));
136 msg->cm_format_type = 0;
139 * Turn the message around
141 CM_FlushField(msg, eRecipient);
142 CM_FlushField(msg, eDestination);
144 len = snprintf(recipient, sizeof(recipient), "%s@%s",
145 msg->cm_fields[eAuthor],
146 msg->cm_fields[eNodeName]);
148 CM_SetField(msg, eAuthor, HKEY(BOUNCESOURCE));
149 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
150 CM_SetField(msg, eMsgSubject, HKEY("Delivery Status Notification (Failure)"));
152 Netmap_AddMe(msg, HKEY("unknown_user"));
154 /* Now submit the message */
155 valid = validate_recipients(recipient, NULL, 0);
156 if (valid != NULL) if (valid->num_error != 0) {
157 free_recipients(valid);
160 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
161 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
164 strcpy(force_room, "");
166 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
167 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
169 CtdlSubmitMsg(msg, valid, force_room, 0);
172 if (valid != NULL) free_recipients(valid);
174 syslog(LOG_DEBUG, "netspool: leaving network_bounce()");
178 void ParseLastSent(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
180 RoomNetCfgLine *nptr;
181 nptr = (RoomNetCfgLine *)
182 malloc(sizeof(RoomNetCfgLine));
183 memset(nptr, 0, sizeof(RoomNetCfgLine));
184 OneRNCFG->lastsent = extract_long(LinePos, 0);
185 OneRNCFG->NetConfigs[ThisOne->C] = nptr;
188 void ParseRoomAlias(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
190 if (rncfg->Sender != NULL)
193 ParseGeneric(ThisOne, Line, LinePos, rncfg);
194 rncfg->Sender = NewStrBufDup(rncfg->NetConfigs[roommailalias]->Value[0]);
197 void ParseSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
199 if (time(NULL) - extract_long(LinePos, 3) > EXP)
200 return; /* expired subscription... */
202 ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
204 void ParseUnSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
206 if (time(NULL) - extract_long(LinePos, 2) > EXP)
207 return; /* expired subscription... */
209 ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
213 void SerializeLastSent(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
215 StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
216 StrBufAppendPrintf(OutputBuffer, "|%ld\n", RNCfg->lastsent);
219 void DeleteLastSent(const CfgLineType *ThisOne, RoomNetCfgLine **data)
225 static const RoomNetCfg SpoolCfgs [4] = {
232 static const long SpoolCfgsCopyN [4] = {
236 int HaveSpoolConfig(OneRoomNetCfg* RNCfg)
240 for (i=0; i < 4; i++) if (RNCfg->NetConfigs[SpoolCfgs[i]] == NULL) interested = 1;
244 void Netmap_AddMe(struct CtdlMessage *msg, const char *defl, long defllen)
249 /* prepend our node to the path */
250 if (CM_IsEmpty(msg, eMessagePath)) {
251 CM_SetField(msg, eMessagePath, defl, defllen);
253 node_len = strlen(CtdlGetConfigStr("c_nodename"));
256 memcpy(buf, CtdlGetConfigStr("c_nodename"), node_len);
258 buf[node_len + 1] = '\0';
259 CM_PrependToField(msg, eMessagePath, buf, node_len + 1);
262 void InspectQueuedRoom(SpoolControl **pSC,
263 RoomProcList *room_to_spool,
264 HashList *working_ignetcfg,
265 HashList *the_netmap)
270 syslog(LOG_INFO, "netspool: InspectQueuedRoom(%s)", room_to_spool->name);
272 sc = (SpoolControl*)malloc(sizeof(SpoolControl));
273 memset(sc, 0, sizeof(SpoolControl));
274 sc->working_ignetcfg = working_ignetcfg;
275 sc->the_netmap = the_netmap;
278 * If the room doesn't exist, don't try to perform its networking tasks.
279 * Normally this should never happen, but once in a while maybe a room gets
280 * queued for networking and then deleted before it can happen.
282 if (CtdlGetRoom(&sc->room, room_to_spool->name) != 0) {
283 syslog(LOG_INFO, "netspool: ERROR; cannot load <%s>", room_to_spool->name);
288 assert(sc->RNCfg == NULL); // checking to make sure we cleared it from last time
290 sc->RNCfg = CtdlGetNetCfgForRoom(sc->room.QRnumber);
292 syslog(LOG_DEBUG, "netspool: room <%s> highest=%ld lastsent=%ld", room_to_spool->name, sc->room.QRhighest, sc->RNCfg->lastsent);
293 if ( (!HaveSpoolConfig(sc->RNCfg)) || (sc->room.QRhighest <= sc->RNCfg->lastsent) )
295 // There is nothing to send from this room.
296 syslog(LOG_DEBUG, "netspool: nothing to do for <%s>", room_to_spool->name);
297 FreeRoomNetworkStruct(&sc->RNCfg);
303 sc->lastsent = sc->RNCfg->lastsent;
304 room_to_spool->lastsent = sc->lastsent;
306 /* Now lets remember whats needed for the actual work... */
308 for (i=0; i < 4; i++)
310 aggregate_recipients(&sc->Users[SpoolCfgs[i]], SpoolCfgs[i], sc->RNCfg, SpoolCfgsCopyN[i]);
313 if (StrLength(sc->RNCfg->Sender) > 0) {
314 sc->Users[roommailalias] = NewStrBufDup(sc->RNCfg->Sender);
320 FreeRoomNetworkStruct(&sc->RNCfg); // done with this for now, we'll grab it again next time
325 void CalcListID(SpoolControl *sc)
328 struct CitContext *CCC = CC;
329 #define MAX_LISTIDLENGTH 150
331 // Load the room banner as the list description
332 struct CtdlMessage *msg = CtdlFetchMessage(sc->room.msgnum_info, 1, 1);
334 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
335 CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
337 sc->RoomInfo = CC->redirect_buffer;
338 CC->redirect_buffer = NULL;
341 sc->RoomInfo = NewStrBufPlain(NULL, SIZ);
344 // Calculate the List ID
345 sc->ListID = NewStrBufPlain(NULL, 1024);
346 if (StrLength(sc->RoomInfo) > 0)
348 const char *Pos = NULL;
349 StrBufSipLine(sc->ListID, sc->RoomInfo, &Pos);
351 if (StrLength(sc->ListID) > MAX_LISTIDLENGTH)
353 StrBufCutAt(sc->ListID, MAX_LISTIDLENGTH, NULL);
354 StrBufAppendBufPlain(sc->ListID, HKEY("..."), 0);
356 StrBufAsciify(sc->ListID, ' ');
360 StrBufAppendBufPlain(sc->ListID, CCC->room.QRname, -1, 0);
363 StrBufAppendBufPlain(sc->ListID, HKEY("<"), 0);
364 RoomName = NewStrBufPlain (sc->room.QRname, -1);
365 StrBufAsciify(RoomName, '_');
366 StrBufReplaceChars(RoomName, ' ', '_');
368 if (StrLength(sc->Users[roommailalias]) > 0)
373 Pos = StrLength(sc->ListID);
374 StrBufAppendBuf(sc->ListID, sc->Users[roommailalias], 0);
375 AtPos = strchr(ChrPtr(sc->ListID) + Pos, '@');
379 StrBufPeek(sc->ListID, AtPos, 0, '.');
384 StrBufAppendBufPlain(sc->ListID, HKEY("room_"), 0);
385 StrBufAppendBuf(sc->ListID, RoomName, 0);
386 StrBufAppendBufPlain(sc->ListID, HKEY("."), 0);
387 StrBufAppendBufPlain(sc->ListID, CtdlGetConfigStr("c_fqdn"), -1, 0);
390 * roomname <Room-Number.list-id.fqdn>
391 * according to rfc2919.txt it only has to be a uniq identifier
392 * under the domain of the system;
393 * in general MUAs use it to calculate the reply address nowadays.
396 StrBufAppendBufPlain(sc->ListID, HKEY(">"), 0);
398 if (StrLength(sc->Users[roommailalias]) == 0)
400 sc->Users[roommailalias] = NewStrBuf();
402 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("room_"), 0);
403 StrBufAppendBuf(sc->Users[roommailalias], RoomName, 0);
404 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("@"), 0);
405 StrBufAppendBufPlain(sc->Users[roommailalias], CtdlGetConfigStr("c_fqdn"), -1, 0);
407 StrBufLowerCase(sc->Users[roommailalias]);
410 FreeStrBuf(&RoomName);
415 * Batch up and send all outbound traffic from the current room
417 void network_spoolout_room(SpoolControl *sc)
419 struct CitContext *CCC = CC;
425 * If the room doesn't exist, don't try to perform its networking tasks.
426 * Normally this should never happen, but once in a while maybe a room gets
427 * queued for networking and then deleted before it can happen.
429 memcpy (&CCC->room, &sc->room, sizeof(ctdlroom));
431 syslog(LOG_INFO, "netspool: network_spoolout_room(room=%s, lastsent=%ld)", CCC->room.QRname, sc->lastsent);
435 /* remember where we started... */
436 lastsent = sc->lastsent;
438 /* Fetch the messages we ought to send & prepare them. */
439 CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL, network_spool_msg, sc);
441 if (StrLength(sc->Users[roommailalias]) > 0)
444 len = StrLength(sc->Users[roommailalias]);
445 if (len + 1 > sizeof(buf))
446 len = sizeof(buf) - 1;
447 memcpy(buf, ChrPtr(sc->Users[roommailalias]), len);
452 snprintf(buf, sizeof buf, "room_%s@%s", CCC->room.QRname, CtdlGetConfigStr("c_fqdn"));
455 for (i=0; buf[i]; ++i) {
456 buf[i] = tolower(buf[i]);
457 if (isspace(buf[i])) buf[i] = '_';
461 /* If we wrote a digest, deliver it and then close it */
462 if ( (sc->Users[digestrecp] != NULL) && (sc->digestfp != NULL) )
464 fprintf(sc->digestfp,
465 " ------------------------------------------------------------------------------\n"
466 "You are subscribed to the '%s' list.\n"
467 "To post to the list: %s\n",
468 CCC->room.QRname, buf
470 network_deliver_digest(sc); /* deliver */
471 fclose(sc->digestfp);
473 remove_digest_file(&sc->room);
476 /* Now rewrite the netconfig */
477 syslog(LOG_DEBUG, "netspool: lastsent was %ld , now it is %ld", lastsent, sc->lastsent);
478 if (sc->lastsent != lastsent)
482 begin_critical_section(S_NETCONFIGS);
483 r = CtdlGetNetCfgForRoom(sc->room.QRnumber);
484 r->lastsent = sc->lastsent;
485 SaveRoomNetConfigFile(r, sc->room.QRnumber);
486 FreeRoomNetworkStruct(&r);
487 end_critical_section(S_NETCONFIGS);
493 * Check the use table. This is a list of messages which have recently
494 * arrived on the system. It is maintained and queried to prevent the same
495 * message from being entered into the database multiple times if it happens
496 * to arrive multiple times by accident.
498 int network_usetable(struct CtdlMessage *msg)
502 /* Bail out if we can't generate a message ID */
503 if ((msg == NULL) || CM_IsEmpty(msg, emessageId))
508 /* Generate the message ID */
509 msgid = NewStrBufPlain(CM_KEY(msg, emessageId));
510 if (haschar(ChrPtr(msgid), '@') == 0) {
511 StrBufAppendBufPlain(msgid, HKEY("@"), 0);
512 if (!CM_IsEmpty(msg, eNodeName)) {
513 StrBufAppendBufPlain(msgid, CM_KEY(msg, eNodeName), 0);
520 if (CheckIfAlreadySeen(msgid)) {
531 * Step 1: consolidate files in the outbound queue into one file per neighbor node
532 * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
534 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
540 struct dirent *filedir_entry;
542 char spooloutfilename[PATH_MAX];
543 char filename[PATH_MAX];
544 const StrBuf *nexthop;
551 /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
553 dp = opendir(ctdl_netout_dir);
558 NextHop = NewStrBuf();
559 memset(&IOB, 0, sizeof(IOBuffer));
560 memset(&FDIO, 0, sizeof(FDIOBuffer));
563 while ( (filedir_entry = readdir(dp)) , (filedir_entry != NULL))
565 #ifdef _DIRENT_HAVE_D_NAMLEN
566 d_namelen = filedir_entry->d_namlen;
569 d_namelen = strlen(filedir_entry->d_name);
572 #ifdef _DIRENT_HAVE_D_TYPE
573 d_type = filedir_entry->d_type;
577 if (d_type == DT_DIR)
580 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
581 continue; /* Ignore backup files... */
583 if ((d_namelen == 1) &&
584 (filedir_entry->d_name[0] == '.'))
587 if ((d_namelen == 2) &&
588 (filedir_entry->d_name[0] == '.') &&
589 (filedir_entry->d_name[1] == '.'))
592 pch = strchr(filedir_entry->d_name, '@');
600 filedir_entry->d_name);
603 filedir_entry->d_name,
604 pch - filedir_entry->d_name);
606 snprintf(spooloutfilename,
607 sizeof spooloutfilename,
612 syslog(LOG_DEBUG, "netspool: consolidate %s to %s", filename, ChrPtr(NextHop));
613 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
615 syslog(LOG_DEBUG, "netspool: currently online with %s - skipping for now", ChrPtr(NextHop));
621 const char *err = NULL;
622 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
624 infd = open(filename, O_RDONLY);
627 syslog(LOG_ERR, "%s: %s", filename, strerror(errno));
628 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
632 outfd = open(spooloutfilename,
633 O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY,
637 outfd = open(spooloutfilename,
638 O_EXCL|O_NONBLOCK|O_WRONLY,
643 syslog(LOG_ERR, "%s: %s", spooloutfilename, strerror(errno));
645 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
649 dsize = lseek(outfd, 0, SEEK_END);
650 lseek(outfd, -dsize, SEEK_SET);
652 fstat(infd, &statbuf);
653 fsize = statbuf.st_size;
655 FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
656 FDIO.ChunkSendRemain = fsize;
657 FDIO.TotalSentAlready = dsize;
660 do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
663 syslog(LOG_DEBUG, "netspool: spoolfile %s now "SIZE_T_FMT" KB", spooloutfilename, (dsize + fsize)/1024);
667 syslog(LOG_ERR, "netspool: failed to append to %s [%s]; rolling back..", spooloutfilename, strerror(errno));
668 /* whoops partial append?? truncate spooloutfilename again! */
669 ftruncate(outfd, dsize);
671 FDIOBufferDelete(&FDIO);
674 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
680 FreeStrBuf(&NextHop);
681 syslog(LOG_INFO, "netspool: skipping Spoolcleanup because of %d files unprocessed.", nFailed);
685 /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
686 dp = opendir(ctdl_netout_dir);
688 FreeStrBuf(&NextHop);
692 while ( (filedir_entry = readdir(dp)) , (filedir_entry != NULL))
694 #ifdef _DIRENT_HAVE_D_NAMLEN
695 d_namelen = filedir_entry->d_namlen;
698 d_namelen = strlen(filedir_entry->d_name);
701 #ifdef _DIRENT_HAVE_D_TYPE
702 d_type = filedir_entry->d_type;
706 if (d_type == DT_DIR)
709 if ((d_namelen == 1) &&
710 (filedir_entry->d_name[0] == '.'))
713 if ((d_namelen == 2) &&
714 (filedir_entry->d_name[0] == '.') &&
715 (filedir_entry->d_name[1] == '.'))
718 pch = strchr(filedir_entry->d_name, '@');
719 if (pch == NULL) /* no @ in name? consolidated file. */
723 filedir_entry->d_name,
724 pch - filedir_entry->d_name);
730 filedir_entry->d_name
733 i = CtdlIsValidNode(&nexthop,
739 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
743 FreeStrBuf(&NextHop);
747 void free_spoolcontrol_struct(SpoolControl **sc)
749 free_spoolcontrol_struct_members(*sc);
754 void free_spoolcontrol_struct_members(SpoolControl *sc)
757 FreeStrBuf(&sc->RoomInfo);
758 FreeStrBuf(&sc->ListID);
759 for (i = 0; i < maxRoomNetCfg; i++)
760 FreeStrBuf(&sc->Users[i]);
765 * It's ok if these directories already exist. Just fail silently.
767 void create_spool_dirs(void) {
768 if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
769 syslog(LOG_EMERG, "netspool: unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
770 if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
771 syslog(LOG_EMERG, "netspool: unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
772 if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
773 syslog(LOG_EMERG, "netspool: unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
774 if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
775 syslog(LOG_EMERG, "netspool: unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
776 if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
777 syslog(LOG_EMERG, "netspool: unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
778 if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
779 syslog(LOG_EMERG, "netspool: unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
785 CTDL_MODULE_INIT(network_spool)
789 CtdlREGISTERRoomCfgType(subpending, ParseSubPendingLine, 0, 5, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
790 CtdlREGISTERRoomCfgType(unsubpending, ParseUnSubPendingLine, 0, 4, SerializeGeneric, DeleteGenericCfgLine); /// todo: move this to mailinglist manager
791 CtdlREGISTERRoomCfgType(lastsent, ParseLastSent, 1, 1, SerializeLastSent, DeleteLastSent);
792 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric, 0, 2, SerializeGeneric, DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
793 CtdlREGISTERRoomCfgType(listrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
794 CtdlREGISTERRoomCfgType(digestrecp, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
795 CtdlREGISTERRoomCfgType(participate, ParseGeneric, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
796 CtdlREGISTERRoomCfgType(roommailalias, ParseRoomAlias, 0, 1, SerializeGeneric, DeleteGenericCfgLine);
799 //////todo CtdlRegisterCleanupHook(destroy_network_queue_room);
801 return "network_spool";