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 "netconfig.h"
82 #include "ctdl_module.h"
84 int NetQDebugEnabled = 0;
85 struct CitContext networker_spool_CC;
87 /* comes from lookup3.c from libcitadel... */
88 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
90 typedef struct __roomlists {
92 HashList *RoomsInterestedIn;
95 * When we do network processing, it's accomplished in two passes; one to
96 * gather a list of rooms and one to actually do them. It's ok that rplist
97 * is global; we have a mutex that keeps it safe.
99 struct RoomProcList *rplist = NULL;
101 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
105 struct dirent *filedir_entry;
109 filedir = opendir (DirName);
110 if (filedir == NULL) {
114 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
119 while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
120 (filedir_entry != NULL))
122 RoomNR = atol(filedir_entry->d_name);
125 Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
137 * Check the use table. This is a list of messages which have recently
138 * arrived on the system. It is maintained and queried to prevent the same
139 * message from being entered into the database multiple times if it happens
140 * to arrive multiple times by accident.
142 int network_usetable(struct CtdlMessage *msg)
144 struct CitContext *CCC = CC;
146 struct cdbdata *cdbut;
149 /* Bail out if we can't generate a message ID */
153 if (msg->cm_fields['I'] == NULL) {
156 if (IsEmptyStr(msg->cm_fields['I'])) {
160 /* Generate the message ID */
161 strcpy(msgid, msg->cm_fields['I']);
162 if (haschar(msgid, '@') == 0) {
164 if (msg->cm_fields['N'] != NULL) {
165 strcat(msgid, msg->cm_fields['N']);
172 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
175 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
179 /* If we got to this point, it's unique: add it. */
180 strcpy(ut.ut_msgid, msgid);
181 ut.ut_timestamp = time(NULL);
182 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
196 * Send the *entire* contents of the current room to one specific network node,
197 * ignoring anything we know about which messages have already undergone
198 * network processing. This can be used to bring a new node into sync.
200 int network_sync_to(char *target_node, long len)
202 struct CitContext *CCC = CC;
210 char filename[PATH_MAX];
213 /* Grab the configuration line we're looking for */
214 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
215 begin_critical_section(S_NETCONFIGS);
216 fp = fopen(filename, "r");
218 end_critical_section(S_NETCONFIGS);
221 while (fgets(buf, sizeof buf, fp) != NULL)
223 buf[strlen(buf)-1] = 0;
225 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
226 if (strcasecmp(sc_type, "ignet_push_share"))
229 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
230 if (strcasecmp(sc_node, target_node))
233 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
236 /* Concise syntax because we don't need a full linked-list */
237 memset(&sc, 0, sizeof(SpoolControl));
238 sc.ignet_push_shares = (maplist *)
239 malloc(sizeof(maplist));
240 sc.ignet_push_shares->next = NULL;
241 safestrncpy(sc.ignet_push_shares->remote_nodename,
243 sizeof sc.ignet_push_shares->remote_nodename);
244 safestrncpy(sc.ignet_push_shares->remote_roomname,
246 sizeof sc.ignet_push_shares->remote_roomname);
249 end_critical_section(S_NETCONFIGS);
252 free(sc.ignet_push_shares);
256 sc.working_ignetcfg = load_ignetcfg();
257 sc.the_netmap = read_network_map();
259 /* Send ALL messages */
260 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
261 network_spool_msg, &sc);
263 /* Concise cleanup because we know there's only one node in the sc */
264 free(sc.ignet_push_shares);
266 DeleteHash(&sc.working_ignetcfg);
267 DeleteHash(&sc.the_netmap);
269 QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
270 num_spooled, target_node);
276 * Implements the NSYN command
278 void cmd_nsyn(char *argbuf) {
281 char target_node[256];
283 if (CtdlAccessCheck(ac_aide)) return;
285 len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
286 num_spooled = network_sync_to(target_node, len);
287 if (num_spooled >= 0) {
288 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
291 cprintf("%d No such room/node share exists.\n",
292 ERROR + ROOM_NOT_FOUND);
299 * Batch up and send all outbound traffic from the current room
301 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
303 struct RoomProcList *ptr;
304 long QRNum = qrbuf->QRnumber;
306 roomlists *RP = (roomlists*) data;
308 if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
311 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
312 if (ptr == NULL) return;
314 ptr->namelen = strlen(qrbuf->QRname);
315 if (ptr->namelen > ROOMNAMELEN)
316 ptr->namelen = ROOMNAMELEN - 1;
318 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
319 ptr->name[ptr->namelen] = '\0';
320 ptr->QRNum = qrbuf->QRnumber;
322 for (i = 0; i < ptr->namelen; i++)
324 ptr->lcname[i] = tolower(ptr->name[i]);
327 ptr->lcname[ptr->namelen] = '\0';
328 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
329 ptr->next = RP->rplist;
334 * Batch up and send all outbound traffic from the current room
336 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
338 struct RoomProcList *ptr;
340 if (qrbuf->QRdefaultview == VIEW_QUEUE)
342 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
343 if (ptr == NULL) return;
345 ptr->namelen = strlen(qrbuf->QRname);
346 if (ptr->namelen > ROOMNAMELEN)
347 ptr->namelen = ROOMNAMELEN - 1;
349 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
350 ptr->name[ptr->namelen] = '\0';
351 ptr->QRNum = qrbuf->QRnumber;
353 for (i = 0; i < ptr->namelen; i++)
355 ptr->lcname[i] = tolower(ptr->name[i]);
357 ptr->lcname[ptr->namelen] = '\0';
358 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
360 begin_critical_section(S_RPLIST);
363 end_critical_section(S_RPLIST);
366 void destroy_network_queue_room(RoomProcList *rplist)
368 struct RoomProcList *cur, *p;
379 void destroy_network_queue_room_locked (void)
381 begin_critical_section(S_RPLIST);
382 destroy_network_queue_room(rplist);
383 end_critical_section(S_RPLIST);
389 * Bounce a message back to the sender
391 void network_bounce(struct CtdlMessage *msg, char *reason)
393 struct CitContext *CCC = CC;
394 char *oldpath = NULL;
396 char bouncesource[SIZ];
398 struct recptypes *valid = NULL;
399 char force_room[ROOMNAMELEN];
400 static int serialnum = 0;
403 QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
405 if (msg == NULL) return;
407 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
410 * Give it a fresh message ID
412 if (msg->cm_fields['I'] != NULL) {
413 free(msg->cm_fields['I']);
415 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
416 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
417 msg->cm_fields['I'] = strdup(buf);
420 * FIXME ... right now we're just sending a bounce; we really want to
421 * include the text of the bounced message.
423 if (msg->cm_fields['M'] != NULL) {
424 free(msg->cm_fields['M']);
426 msg->cm_fields['M'] = strdup(reason);
427 msg->cm_format_type = 0;
430 * Turn the message around
432 if (msg->cm_fields['R'] == NULL) {
433 free(msg->cm_fields['R']);
436 if (msg->cm_fields['D'] == NULL) {
437 free(msg->cm_fields['D']);
440 snprintf(recipient, sizeof recipient, "%s@%s",
441 msg->cm_fields['A'], msg->cm_fields['N']);
443 if (msg->cm_fields['A'] == NULL) {
444 free(msg->cm_fields['A']);
447 if (msg->cm_fields['N'] == NULL) {
448 free(msg->cm_fields['N']);
451 if (msg->cm_fields['U'] == NULL) {
452 free(msg->cm_fields['U']);
455 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
456 msg->cm_fields['N'] = strdup(config.c_nodename);
457 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
459 /* prepend our node to the path */
460 if (msg->cm_fields['P'] != NULL) {
461 oldpath = msg->cm_fields['P'];
462 msg->cm_fields['P'] = NULL;
465 oldpath = strdup("unknown_user");
467 size = strlen(oldpath) + SIZ;
468 msg->cm_fields['P'] = malloc(size);
469 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
472 /* Now submit the message */
473 valid = validate_recipients(recipient, NULL, 0);
474 if (valid != NULL) if (valid->num_error != 0) {
475 free_recipients(valid);
478 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
479 strcpy(force_room, config.c_aideroom);
482 strcpy(force_room, "");
484 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
485 strcpy(force_room, config.c_aideroom);
487 CtdlSubmitMsg(msg, valid, force_room, 0);
490 if (valid != NULL) free_recipients(valid);
491 CtdlFreeMessage(msg);
492 QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
504 * Run through the rooms doing various types of network stuff.
506 void network_do_queue(void)
508 struct CitContext *CCC = CC;
509 static int doing_queue = 0;
510 static time_t last_run = 0L;
511 int full_processing = 1;
512 HashList *working_ignetcfg;
513 HashList *the_netmap = NULL;
514 int netmap_changed = 0;
518 * Run the full set of processing tasks no more frequently
519 * than once every n seconds
521 if ( (time(NULL) - last_run) < config.c_net_freq ) {
523 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
524 config.c_net_freq - (time(NULL)- last_run)
529 * This is a simple concurrency check to make sure only one queue run
530 * is done at a time. We could do this with a mutex, but since we
531 * don't really require extremely fine granularity here, we'll do it
532 * with a static variable instead.
539 become_session(&networker_spool_CC);
540 begin_critical_section(S_RPLIST);
543 end_critical_section(S_RPLIST);
545 RL.RoomsInterestedIn = NewHash(1, lFlathash);
546 if (full_processing &&
547 (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
550 DeleteHash(&RL.RoomsInterestedIn);
551 if (RL.rplist == NULL)
554 /* Load the IGnet Configuration into memory */
555 working_ignetcfg = load_ignetcfg();
558 * Load the network map and filter list into memory.
560 if (!server_shutting_down)
561 the_netmap = read_network_map();
562 if (!server_shutting_down)
563 load_network_filter_list();
566 * Go ahead and run the queue
568 if (full_processing && !server_shutting_down) {
569 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
570 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
573 if ((RL.rplist != NULL) && (!server_shutting_down)) {
574 RoomProcList *ptr, *cmp;
576 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
577 while (ptr != NULL && !server_shutting_down) {
581 while (cmp != NULL) {
582 if ((cmp->namelen > 0) &&
583 (cmp->key == ptr->key) &&
584 (cmp->namelen == ptr->namelen) &&
585 (strcmp(cmp->lcname, ptr->lcname) == 0))
592 if (ptr->namelen > 0) {
593 network_spoolout_room(ptr,
601 /* If there is anything in the inbound queue, process it */
602 if (!server_shutting_down) {
603 network_do_spoolin(working_ignetcfg,
608 /* Free the filter list in memory */
609 free_netfilter_list();
611 /* Save the network map back to disk */
612 if (netmap_changed) {
613 StrBuf *MapStr = SerializeNetworkMap(the_netmap);
614 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
617 /* combine singe message files into one spool entry per remote node. */
618 network_consolidate_spoolout(working_ignetcfg, the_netmap);
622 DeleteHash(&the_netmap);
624 DeleteHash(&working_ignetcfg);
626 QNM_syslog(LOG_DEBUG, "network: queue run completed");
628 if (full_processing) {
629 last_run = time(NULL);
631 DeleteHash(&RL.RoomsInterestedIn);
632 destroy_network_queue_room(RL.rplist);
639 int network_room_handler (struct ctdlroom *room)
641 network_queue_room(room, NULL);
645 int NTTDebugEnabled = 0;
648 * network_talking_to() -- concurrency checker
650 static HashList *nttlist = NULL;
651 int network_talking_to(const char *nodename, long len, int operation) {
657 begin_critical_section(S_NTTLIST);
663 nttlist = NewHash(1, NULL);
664 Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
665 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
668 if ((nttlist == NULL) ||
669 (GetCount(nttlist) == 0))
671 Pos = GetNewHashPos(nttlist, 1);
672 if (GetHashPosFromKey (nttlist, nodename, len, Pos))
673 DeleteEntryFromHash(nttlist, Pos);
675 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
680 if ((nttlist == NULL) ||
681 (GetCount(nttlist) == 0))
683 if (GetHash(nttlist, nodename, len, &vdata))
685 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
689 end_critical_section(S_NTTLIST);
693 void cleanup_nttlist(void)
695 begin_critical_section(S_NTTLIST);
696 DeleteHash(&nttlist);
697 end_critical_section(S_NTTLIST);
702 void network_logout_hook(void)
704 CitContext *CCC = MyContext();
707 * If we were talking to a network node, we're not anymore...
709 if (!IsEmptyStr(CCC->net_node)) {
710 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
711 CCC->net_node[0] = '\0';
714 void network_cleanup_function(void)
716 struct CitContext *CCC = CC;
718 if (!IsEmptyStr(CCC->net_node)) {
719 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
720 CCC->net_node[0] = '\0';
728 void SetNTTDebugEnabled(const int n)
732 void SetNetQDebugEnabled(const int n)
734 NetQDebugEnabled = n;
737 CTDL_MODULE_INIT(network)
741 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
742 CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
743 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
744 CtdlRegisterCleanupHook(cleanup_nttlist);
745 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
746 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
747 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
748 CtdlRegisterRoomHook(network_room_handler);
749 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
750 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);