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"
79 #include "ctdl_module.h"
83 int NetQDebugEnabled = 0;
84 struct CitContext networker_spool_CC;
86 /* comes from lookup3.c from libcitadel... */
87 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
89 typedef struct __roomlists {
93 * When we do network processing, it's accomplished in two passes; one to
94 * gather a list of rooms and one to actually do them. It's ok that rplist
95 * is global; we have a mutex that keeps it safe.
97 struct RoomProcList *rplist = NULL;
102 * Check the use table. This is a list of messages which have recently
103 * arrived on the system. It is maintained and queried to prevent the same
104 * message from being entered into the database multiple times if it happens
105 * to arrive multiple times by accident.
107 int network_usetable(struct CtdlMessage *msg)
109 struct CitContext *CCC = CC;
111 struct cdbdata *cdbut;
114 /* Bail out if we can't generate a message ID */
118 if (msg->cm_fields['I'] == NULL) {
121 if (IsEmptyStr(msg->cm_fields['I'])) {
125 /* Generate the message ID */
126 strcpy(msgid, msg->cm_fields['I']);
127 if (haschar(msgid, '@') == 0) {
129 if (msg->cm_fields['N'] != NULL) {
130 strcat(msgid, msg->cm_fields['N']);
137 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
140 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
144 /* If we got to this point, it's unique: add it. */
145 strcpy(ut.ut_msgid, msgid);
146 ut.ut_timestamp = time(NULL);
147 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
152 void CalcListID(SpoolControl *sc)
156 struct CitContext *CCC = CC;
157 char filename[PATH_MAX];
158 #define MAX_LISTIDLENGTH 150
160 assoc_file_name(filename, sizeof filename, &sc->room, ctdl_info_dir);
161 fd = open(filename, 0);
167 if (stbuf.st_size > 0)
169 sc->RoomInfo = NewStrBufPlain(NULL, stbuf.st_size + 1);
170 StrBufReadBLOB(sc->RoomInfo, &fd, 0, stbuf.st_size, &err);
175 sc->ListID = NewStrBufPlain(NULL, 1024);
176 if (StrLength(sc->RoomInfo) > 0)
178 const char *Pos = NULL;
179 StrBufSipLine(sc->ListID, sc->RoomInfo, &Pos);
181 if (StrLength(sc->ListID) > MAX_LISTIDLENGTH)
183 StrBufCutAt(sc->ListID, MAX_LISTIDLENGTH, NULL);
184 StrBufAppendBufPlain(sc->ListID, HKEY("..."), 0);
186 StrBufAsciify(sc->ListID, ' ');
190 StrBufAppendBufPlain(sc->ListID, CCC->room.QRname, -1, 0);
193 StrBufAppendBufPlain(sc->ListID, HKEY("<"), 0);
195 if (StrLength(sc->Users[roommailalias]) > 0)
200 Pos = StrLength(sc->ListID);
201 StrBufAppendBuf(sc->ListID, sc->Users[roommailalias], 0);
202 AtPos = strchr(ChrPtr(sc->ListID) + Pos, '@');
206 StrBufPeek(sc->ListID, AtPos, 0, '.');
211 StrBufAppendBufPlain(sc->ListID, HKEY("room_"), 0);
212 StrBufAppendBufPlain(sc->ListID, sc->room.QRname, -1, 0);
213 StrBufAppendBufPlain(sc->ListID, HKEY("."), 0);
214 StrBufAppendBufPlain(sc->ListID, config.c_fqdn, -1, 0);
217 * roomname <Room-Number.list-id.fqdn>
218 * according to rfc2919.txt it only has to be a uniq identifier
219 * under the domain of the system;
220 * in general MUAs use it to calculate the reply address nowadays.
223 StrBufAppendBufPlain(sc->ListID, HKEY(">"), 0);
225 if (StrLength(sc->Users[roommailalias]) == 0)
227 sc->Users[roommailalias] = NewStrBuf();
229 StrBufPrintf(sc->Users[roommailalias],
234 StrBufAsciify(sc->Users[roommailalias], '_');
235 StrBufLowerCase(sc->Users[roommailalias]);
241 * Send the *entire* contents of the current room to one specific network node,
242 * ignoring anything we know about which messages have already undergone
243 * network processing. This can be used to bring a new node into sync.
245 int network_sync_to(char *target_node, long len)
247 struct CitContext *CCC = CC;
248 OneRoomNetCfg OneRNCFG;
249 OneRoomNetCfg *pRNCFG;
250 const RoomNetCfgLine *pCfgLine;
254 /* Grab the configuration line we're looking for */
255 begin_critical_section(S_NETCONFIGS);
256 pRNCFG = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
257 if ((pRNCFG == NULL) ||
258 (pRNCFG->NetConfigs[ignet_push_share] == NULL))
263 pCfgLine = pRNCFG->NetConfigs[ignet_push_share];
264 while (pCfgLine != NULL)
266 if (strcmp(ChrPtr(pCfgLine->Value[0]), target_node))
268 pCfgLine = pCfgLine->next;
270 if (pCfgLine == NULL)
274 memset(&sc, 0, sizeof(SpoolControl));
275 memset(&OneRNCFG, 0, sizeof(OneRoomNetCfg));
276 sc.RNCfg = &OneRNCFG;
277 sc.RNCfg->NetConfigs[ignet_push_share] = DuplicateOneGenericCfgLine(pCfgLine);
279 end_critical_section(S_NETCONFIGS);
281 sc.working_ignetcfg = CtdlLoadIgNetCfg();
282 sc.the_netmap = CtdlReadNetworkMap();
285 /* Send ALL messages */
286 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
287 network_spool_msg, &sc);
289 /* Concise cleanup because we know there's only one node in the sc */
290 DeleteGenericCfgLine(NULL/*TODO*/, &sc.RNCfg->NetConfigs[ignet_push_share]);
292 DeleteHash(&sc.working_ignetcfg);
293 DeleteHash(&sc.the_netmap);
295 QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
296 num_spooled, target_node);
302 * Implements the NSYN command
304 void cmd_nsyn(char *argbuf) {
307 char target_node[256];
309 if (CtdlAccessCheck(ac_aide)) return;
311 len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
312 num_spooled = network_sync_to(target_node, len);
313 if (num_spooled >= 0) {
314 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
317 cprintf("%d No such room/node share exists.\n",
318 ERROR + ROOM_NOT_FOUND);
322 RoomProcList *CreateRoomProcListEntry(struct ctdlroom *qrbuf, OneRoomNetCfg *OneRNCFG)
325 struct RoomProcList *ptr;
327 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
328 if (ptr == NULL) return NULL;
330 ptr->namelen = strlen(qrbuf->QRname);
331 if (ptr->namelen > ROOMNAMELEN)
332 ptr->namelen = ROOMNAMELEN - 1;
334 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
335 ptr->name[ptr->namelen] = '\0';
336 ptr->QRNum = qrbuf->QRnumber;
338 for (i = 0; i < ptr->namelen; i++)
340 ptr->lcname[i] = tolower(ptr->name[i]);
343 ptr->lcname[ptr->namelen] = '\0';
344 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
345 ptr->lastsent = OneRNCFG->lastsent;
346 ptr->OneRNCfg = OneRNCFG;
351 * Batch up and send all outbound traffic from the current room
353 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCfg)
355 struct RoomProcList *ptr;
356 roomlists *RP = (roomlists*) data;
358 if (!HaveSpoolConfig(OneRNCfg))
361 ptr = CreateRoomProcListEntry(qrbuf, OneRNCfg);
365 ptr->next = RP->rplist;
371 * Batch up and send all outbound traffic from the current room
373 int network_room_handler (struct ctdlroom *qrbuf)
375 struct RoomProcList *ptr;
376 OneRoomNetCfg* RNCfg;
378 if (qrbuf->QRdefaultview == VIEW_QUEUE)
381 RNCfg = CtdlGetNetCfgForRoom(qrbuf->QRnumber);
385 if (!HaveSpoolConfig(RNCfg))
388 ptr = CreateRoomProcListEntry(qrbuf, RNCfg);
392 ptr->OneRNCfg = NULL;
393 begin_critical_section(S_RPLIST);
396 end_critical_section(S_RPLIST);
400 void destroy_network_queue_room(RoomProcList *rplist)
402 struct RoomProcList *cur, *p;
413 void destroy_network_queue_room_locked (void)
415 begin_critical_section(S_RPLIST);
416 destroy_network_queue_room(rplist);
417 end_critical_section(S_RPLIST);
423 * Bounce a message back to the sender
425 void network_bounce(struct CtdlMessage *msg, char *reason)
427 struct CitContext *CCC = CC;
428 char *oldpath = NULL;
430 char bouncesource[SIZ];
432 struct recptypes *valid = NULL;
433 char force_room[ROOMNAMELEN];
434 static int serialnum = 0;
437 QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
439 if (msg == NULL) return;
441 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
444 * Give it a fresh message ID
446 if (msg->cm_fields['I'] != NULL) {
447 free(msg->cm_fields['I']);
449 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
450 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
451 msg->cm_fields['I'] = strdup(buf);
454 * FIXME ... right now we're just sending a bounce; we really want to
455 * include the text of the bounced message.
457 if (msg->cm_fields['M'] != NULL) {
458 free(msg->cm_fields['M']);
460 msg->cm_fields['M'] = strdup(reason);
461 msg->cm_format_type = 0;
464 * Turn the message around
466 if (msg->cm_fields['R'] == NULL) {
467 free(msg->cm_fields['R']);
470 if (msg->cm_fields['D'] == NULL) {
471 free(msg->cm_fields['D']);
474 snprintf(recipient, sizeof recipient, "%s@%s",
475 msg->cm_fields['A'], msg->cm_fields['N']);
477 if (msg->cm_fields['A'] == NULL) {
478 free(msg->cm_fields['A']);
481 if (msg->cm_fields['N'] == NULL) {
482 free(msg->cm_fields['N']);
485 if (msg->cm_fields['U'] == NULL) {
486 free(msg->cm_fields['U']);
489 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
490 msg->cm_fields['N'] = strdup(config.c_nodename);
491 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
493 /* prepend our node to the path */
494 if (msg->cm_fields['P'] != NULL) {
495 oldpath = msg->cm_fields['P'];
496 msg->cm_fields['P'] = NULL;
499 oldpath = strdup("unknown_user");
501 size = strlen(oldpath) + SIZ;
502 msg->cm_fields['P'] = malloc(size);
503 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
506 /* Now submit the message */
507 valid = validate_recipients(recipient, NULL, 0);
508 if (valid != NULL) if (valid->num_error != 0) {
509 free_recipients(valid);
512 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
513 strcpy(force_room, config.c_aideroom);
516 strcpy(force_room, "");
518 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
519 strcpy(force_room, config.c_aideroom);
521 CtdlSubmitMsg(msg, valid, force_room, 0);
524 if (valid != NULL) free_recipients(valid);
525 CtdlFreeMessage(msg);
526 QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
530 void free_network_spoolout_room(SpoolControl *sc)
535 for (i = subpending; i < maxRoomNetCfg; i++)
536 FreeStrBuf(&sc->Users[i]);
547 * Run through the rooms doing various types of network stuff.
549 void network_do_queue(void)
551 struct CitContext *CCC = CC;
552 static time_t last_run = 0L;
553 int full_processing = 1;
554 HashList *working_ignetcfg;
555 HashList *the_netmap = NULL;
556 int netmap_changed = 0;
558 SpoolControl *sc = NULL;
562 * Run the full set of processing tasks no more frequently
563 * than once every n seconds
565 if ( (time(NULL) - last_run) < config.c_net_freq ) {
567 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
568 config.c_net_freq - (time(NULL)- last_run)
572 become_session(&networker_spool_CC);
573 begin_critical_section(S_RPLIST);
576 end_critical_section(S_RPLIST);
577 ///TODO hm, check whether we have a config at all here?
578 /* Load the IGnet Configuration into memory */
579 working_ignetcfg = CtdlLoadIgNetCfg();
582 * Load the network map and filter list into memory.
584 if (!server_shutting_down)
585 the_netmap = CtdlReadNetworkMap();
587 /* filterlist isn't supported anymore
588 if (!server_shutting_down)
589 load_network_filter_list();
594 * Go ahead and run the queue
596 if (full_processing && !server_shutting_down) {
597 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
598 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
601 if ((RL.rplist != NULL) && (!server_shutting_down)) {
602 RoomProcList *ptr, *cmp;
604 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
605 while (ptr != NULL && !server_shutting_down) {
608 /* filter duplicates from the list... */
609 while (cmp != NULL) {
610 if ((cmp->namelen > 0) &&
611 (cmp->key == ptr->key) &&
612 (cmp->namelen == ptr->namelen) &&
613 (strcmp(cmp->lcname, ptr->lcname) == 0))
620 if (ptr->namelen > 0) {
621 InspectQueuedRoom(&sc,
634 network_spoolout_room(pSC);
642 free_network_spoolout_room(pSC);
645 /* If there is anything in the inbound queue, process it */
646 if (!server_shutting_down) {
647 network_do_spoolin(working_ignetcfg,
652 /* Free the filter list in memory */
653 free_netfilter_list();
655 /* Save the network map back to disk */
656 if (netmap_changed) {
657 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
658 char *pMapStr = SmashStrBuf(&MapStr);
659 CtdlPutSysConfig(IGNETMAP, pMapStr);
663 /* combine singe message files into one spool entry per remote node. */
664 network_consolidate_spoolout(working_ignetcfg, the_netmap);
668 DeleteHash(&the_netmap);
670 DeleteHash(&working_ignetcfg);
672 QNM_syslog(LOG_DEBUG, "network: queue run completed");
674 if (full_processing) {
675 last_run = time(NULL);
677 destroy_network_queue_room(RL.rplist);
678 SaveChangedConfigs();
689 void network_logout_hook(void)
691 CitContext *CCC = MyContext();
694 * If we were talking to a network node, we're not anymore...
696 if (!IsEmptyStr(CCC->net_node)) {
697 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
698 CCC->net_node[0] = '\0';
701 void network_cleanup_function(void)
703 struct CitContext *CCC = CC;
705 if (!IsEmptyStr(CCC->net_node)) {
706 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
707 CCC->net_node[0] = '\0';
716 void SetNetQDebugEnabled(const int n)
718 NetQDebugEnabled = n;
721 CTDL_MODULE_INIT(network)
725 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
726 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
727 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
728 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
729 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
730 CtdlRegisterRoomHook(network_room_handler);
731 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
732 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);