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 as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * ** NOTE ** A word on the S_NETCONFIGS semaphore:
22 * This is a fairly high-level type of critical section. It ensures that no
23 * two threads work on the netconfigs files at the same time. Since we do
24 * so many things inside these, here are the rules:
25 * 1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26 * 2. Do *not* perform any I/O with the client during these sections.
31 * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32 * requests that have not been confirmed will be deleted.
34 #define EXP 259200 /* three days */
46 #include <sys/types.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
53 # include <sys/time.h>
61 # if HAVE_SYS_SYSCALL_H
62 # include <sys/syscall.h>
69 #include <libcitadel.h>
72 #include "citserver.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
82 #include "citadel_dirs.h"
90 #include "netconfig.h"
93 #include "ctdl_module.h"
95 int NetQDebugEnabled = 0;
96 struct CitContext networker_spool_CC;
98 /* comes from lookup3.c from libcitadel... */
99 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
101 typedef struct __roomlists {
102 RoomProcList *rplist;
103 HashList *RoomsInterestedIn;
106 * When we do network processing, it's accomplished in two passes; one to
107 * gather a list of rooms and one to actually do them. It's ok that rplist
108 * is global; we have a mutex that keeps it safe.
110 struct RoomProcList *rplist = NULL;
112 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
116 struct dirent *filedir_entry;
120 filedir = opendir (DirName);
121 if (filedir == NULL) {
125 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
130 while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
131 (filedir_entry != NULL))
133 RoomNR = atol(filedir_entry->d_name);
136 Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
148 * Check the use table. This is a list of messages which have recently
149 * arrived on the system. It is maintained and queried to prevent the same
150 * message from being entered into the database multiple times if it happens
151 * to arrive multiple times by accident.
153 int network_usetable(struct CtdlMessage *msg)
155 struct CitContext *CCC = CC;
157 struct cdbdata *cdbut;
160 /* Bail out if we can't generate a message ID */
164 if (msg->cm_fields['I'] == NULL) {
167 if (IsEmptyStr(msg->cm_fields['I'])) {
171 /* Generate the message ID */
172 strcpy(msgid, msg->cm_fields['I']);
173 if (haschar(msgid, '@') == 0) {
175 if (msg->cm_fields['N'] != NULL) {
176 strcat(msgid, msg->cm_fields['N']);
183 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
186 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
190 /* If we got to this point, it's unique: add it. */
191 strcpy(ut.ut_msgid, msgid);
192 ut.ut_timestamp = time(NULL);
193 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
207 * Send the *entire* contents of the current room to one specific network node,
208 * ignoring anything we know about which messages have already undergone
209 * network processing. This can be used to bring a new node into sync.
211 int network_sync_to(char *target_node, long len)
213 struct CitContext *CCC = CC;
221 char filename[PATH_MAX];
224 /* Grab the configuration line we're looking for */
225 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
226 begin_critical_section(S_NETCONFIGS);
227 fp = fopen(filename, "r");
229 end_critical_section(S_NETCONFIGS);
232 while (fgets(buf, sizeof buf, fp) != NULL)
234 buf[strlen(buf)-1] = 0;
236 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
237 if (strcasecmp(sc_type, "ignet_push_share"))
240 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
241 if (strcasecmp(sc_node, target_node))
244 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
247 /* Concise syntax because we don't need a full linked-list */
248 memset(&sc, 0, sizeof(SpoolControl));
249 sc.ignet_push_shares = (maplist *)
250 malloc(sizeof(maplist));
251 sc.ignet_push_shares->next = NULL;
252 safestrncpy(sc.ignet_push_shares->remote_nodename,
254 sizeof sc.ignet_push_shares->remote_nodename);
255 safestrncpy(sc.ignet_push_shares->remote_roomname,
257 sizeof sc.ignet_push_shares->remote_roomname);
260 end_critical_section(S_NETCONFIGS);
262 if (!found_node) return(-1);
264 sc.working_ignetcfg = load_ignetcfg();
265 sc.the_netmap = read_network_map();
267 /* Send ALL messages */
268 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
269 network_spool_msg, &sc);
271 /* Concise cleanup because we know there's only one node in the sc */
272 free(sc.ignet_push_shares);
274 DeleteHash(&sc.working_ignetcfg);
275 DeleteHash(&sc.the_netmap);
277 QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
278 num_spooled, target_node);
284 * Implements the NSYN command
286 void cmd_nsyn(char *argbuf) {
289 char target_node[256];
291 if (CtdlAccessCheck(ac_aide)) return;
293 len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
294 num_spooled = network_sync_to(target_node, len);
295 if (num_spooled >= 0) {
296 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
299 cprintf("%d No such room/node share exists.\n",
300 ERROR + ROOM_NOT_FOUND);
307 * Batch up and send all outbound traffic from the current room
309 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
311 struct RoomProcList *ptr;
312 long QRNum = qrbuf->QRnumber;
314 roomlists *RP = (roomlists*) data;
316 if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
319 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
320 if (ptr == NULL) return;
322 ptr->namelen = strlen(qrbuf->QRname);
323 if (ptr->namelen > ROOMNAMELEN)
324 ptr->namelen = ROOMNAMELEN - 1;
326 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
327 ptr->name[ptr->namelen] = '\0';
328 ptr->QRNum = qrbuf->QRnumber;
330 for (i = 0; i < ptr->namelen; i++)
332 ptr->lcname[i] = tolower(ptr->name[i]);
335 ptr->lcname[ptr->namelen] = '\0';
336 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
337 ptr->next = RP->rplist;
342 * Batch up and send all outbound traffic from the current room
344 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
346 struct RoomProcList *ptr;
348 if (qrbuf->QRdefaultview == VIEW_QUEUE)
350 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
351 if (ptr == NULL) return;
353 ptr->namelen = strlen(qrbuf->QRname);
354 if (ptr->namelen > ROOMNAMELEN)
355 ptr->namelen = ROOMNAMELEN - 1;
357 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
358 ptr->name[ptr->namelen] = '\0';
359 ptr->QRNum = qrbuf->QRnumber;
361 for (i = 0; i < ptr->namelen; i++)
363 ptr->lcname[i] = tolower(ptr->name[i]);
365 ptr->lcname[ptr->namelen] = '\0';
366 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
368 begin_critical_section(S_RPLIST);
371 end_critical_section(S_RPLIST);
374 void destroy_network_queue_room(RoomProcList *rplist)
376 struct RoomProcList *cur, *p;
387 void destroy_network_queue_room_locked (void)
389 begin_critical_section(S_RPLIST);
390 destroy_network_queue_room(rplist);
391 end_critical_section(S_RPLIST);
397 * Bounce a message back to the sender
399 void network_bounce(struct CtdlMessage *msg, char *reason)
401 struct CitContext *CCC = CC;
402 char *oldpath = NULL;
404 char bouncesource[SIZ];
406 struct recptypes *valid = NULL;
407 char force_room[ROOMNAMELEN];
408 static int serialnum = 0;
411 QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
413 if (msg == NULL) return;
415 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
418 * Give it a fresh message ID
420 if (msg->cm_fields['I'] != NULL) {
421 free(msg->cm_fields['I']);
423 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
424 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
425 msg->cm_fields['I'] = strdup(buf);
428 * FIXME ... right now we're just sending a bounce; we really want to
429 * include the text of the bounced message.
431 if (msg->cm_fields['M'] != NULL) {
432 free(msg->cm_fields['M']);
434 msg->cm_fields['M'] = strdup(reason);
435 msg->cm_format_type = 0;
438 * Turn the message around
440 if (msg->cm_fields['R'] == NULL) {
441 free(msg->cm_fields['R']);
444 if (msg->cm_fields['D'] == NULL) {
445 free(msg->cm_fields['D']);
448 snprintf(recipient, sizeof recipient, "%s@%s",
449 msg->cm_fields['A'], msg->cm_fields['N']);
451 if (msg->cm_fields['A'] == NULL) {
452 free(msg->cm_fields['A']);
455 if (msg->cm_fields['N'] == NULL) {
456 free(msg->cm_fields['N']);
459 if (msg->cm_fields['U'] == NULL) {
460 free(msg->cm_fields['U']);
463 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
464 msg->cm_fields['N'] = strdup(config.c_nodename);
465 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
467 /* prepend our node to the path */
468 if (msg->cm_fields['P'] != NULL) {
469 oldpath = msg->cm_fields['P'];
470 msg->cm_fields['P'] = NULL;
473 oldpath = strdup("unknown_user");
475 size = strlen(oldpath) + SIZ;
476 msg->cm_fields['P'] = malloc(size);
477 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
480 /* Now submit the message */
481 valid = validate_recipients(recipient, NULL, 0);
482 if (valid != NULL) if (valid->num_error != 0) {
483 free_recipients(valid);
486 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
487 strcpy(force_room, config.c_aideroom);
490 strcpy(force_room, "");
492 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
493 strcpy(force_room, config.c_aideroom);
495 CtdlSubmitMsg(msg, valid, force_room, 0);
498 if (valid != NULL) free_recipients(valid);
499 CtdlFreeMessage(msg);
500 QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
512 * Run through the rooms doing various types of network stuff.
514 void network_do_queue(void)
516 struct CitContext *CCC = CC;
517 static int doing_queue = 0;
518 static time_t last_run = 0L;
519 int full_processing = 1;
520 HashList *working_ignetcfg;
521 HashList *the_netmap = NULL;
522 int netmap_changed = 0;
526 * Run the full set of processing tasks no more frequently
527 * than once every n seconds
529 if ( (time(NULL) - last_run) < config.c_net_freq ) {
531 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
532 config.c_net_freq - (time(NULL)- last_run)
537 * This is a simple concurrency check to make sure only one queue run
538 * is done at a time. We could do this with a mutex, but since we
539 * don't really require extremely fine granularity here, we'll do it
540 * with a static variable instead.
547 become_session(&networker_spool_CC);
548 begin_critical_section(S_RPLIST);
551 end_critical_section(S_RPLIST);
553 RL.RoomsInterestedIn = NewHash(1, lFlathash);
554 if (full_processing &&
555 (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
558 DeleteHash(&RL.RoomsInterestedIn);
559 if (RL.rplist == NULL)
562 /* Load the IGnet Configuration into memory */
563 working_ignetcfg = load_ignetcfg();
566 * Load the network map and filter list into memory.
568 if (!server_shutting_down)
569 the_netmap = read_network_map();
570 if (!server_shutting_down)
571 load_network_filter_list();
574 * Go ahead and run the queue
576 if (full_processing && !server_shutting_down) {
577 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
578 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
581 if ((RL.rplist != NULL) && (!server_shutting_down)) {
582 RoomProcList *ptr, *cmp;
584 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
585 while (ptr != NULL && !server_shutting_down) {
589 while (cmp != NULL) {
590 if ((cmp->namelen > 0) &&
591 (cmp->key == ptr->key) &&
592 (cmp->namelen == ptr->namelen) &&
593 (strcmp(cmp->lcname, ptr->lcname) == 0))
600 if (ptr->namelen > 0) {
601 network_spoolout_room(ptr,
609 /* If there is anything in the inbound queue, process it */
610 if (!server_shutting_down) {
611 network_do_spoolin(working_ignetcfg,
616 /* Free the filter list in memory */
617 free_netfilter_list();
619 /* Save the network map back to disk */
620 if (netmap_changed) {
621 StrBuf *MapStr = SerializeNetworkMap(the_netmap);
622 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
625 /* combine singe message files into one spool entry per remote node. */
626 network_consolidate_spoolout(working_ignetcfg, the_netmap);
630 DeleteHash(&the_netmap);
632 DeleteHash(&working_ignetcfg);
634 QNM_syslog(LOG_DEBUG, "network: queue run completed");
636 if (full_processing) {
637 last_run = time(NULL);
639 DeleteHash(&RL.RoomsInterestedIn);
640 destroy_network_queue_room(RL.rplist);
647 int network_room_handler (struct ctdlroom *room)
649 network_queue_room(room, NULL);
653 int NTTDebugEnabled = 0;
656 * network_talking_to() -- concurrency checker
658 static HashList *nttlist = NULL;
659 int network_talking_to(const char *nodename, long len, int operation) {
665 begin_critical_section(S_NTTLIST);
671 nttlist = NewHash(1, NULL);
672 Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
673 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
676 if ((nttlist == NULL) ||
677 (GetCount(nttlist) == 0))
679 Pos = GetNewHashPos(nttlist, 1);
680 if (GetHashPosFromKey (nttlist, nodename, len, Pos))
681 DeleteEntryFromHash(nttlist, Pos);
683 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
688 if ((nttlist == NULL) ||
689 (GetCount(nttlist) == 0))
691 if (GetHash(nttlist, nodename, len, &vdata))
693 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
697 end_critical_section(S_NTTLIST);
701 void cleanup_nttlist(void)
703 begin_critical_section(S_NTTLIST);
704 DeleteHash(&nttlist);
705 end_critical_section(S_NTTLIST);
710 void network_logout_hook(void)
712 CitContext *CCC = MyContext();
715 * If we were talking to a network node, we're not anymore...
717 if (!IsEmptyStr(CCC->net_node)) {
718 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
719 CCC->net_node[0] = '\0';
722 void network_cleanup_function(void)
724 struct CitContext *CCC = CC;
726 if (!IsEmptyStr(CCC->net_node)) {
727 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
728 CCC->net_node[0] = '\0';
736 void SetNTTDebugEnabled(const int n)
740 void SetNetQDebugEnabled(const int n)
742 NetQDebugEnabled = n;
745 CTDL_MODULE_INIT(network)
749 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
750 CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
751 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
752 CtdlRegisterCleanupHook(cleanup_nttlist);
753 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
754 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
755 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
756 CtdlRegisterRoomHook(network_room_handler);
757 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
758 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);