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);
278 * Implements the NSYN command
280 void cmd_nsyn(char *argbuf) {
283 char target_node[256];
285 if (CtdlAccessCheck(ac_aide)) return;
287 len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
288 ///// TODO num_spooled = network_sync_to(target_node, len);
289 if (num_spooled >= 0) {
290 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
293 cprintf("%d No such room/node share exists.\n",
294 ERROR + ROOM_NOT_FOUND);
301 * Batch up and send all outbound traffic from the current room
303 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
305 struct RoomProcList *ptr;
306 long QRNum = qrbuf->QRnumber;
308 roomlists *RP = (roomlists*) data;
310 if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
313 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
314 if (ptr == NULL) return;
316 ptr->namelen = strlen(qrbuf->QRname);
317 if (ptr->namelen > ROOMNAMELEN)
318 ptr->namelen = ROOMNAMELEN - 1;
320 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
321 ptr->name[ptr->namelen] = '\0';
322 ptr->QRNum = qrbuf->QRnumber;
324 for (i = 0; i < ptr->namelen; i++)
326 ptr->lcname[i] = tolower(ptr->name[i]);
329 ptr->lcname[ptr->namelen] = '\0';
330 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
331 ptr->next = RP->rplist;
336 * Batch up and send all outbound traffic from the current room
338 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
340 struct RoomProcList *ptr;
342 if (qrbuf->QRdefaultview == VIEW_QUEUE)
344 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
345 if (ptr == NULL) return;
347 ptr->namelen = strlen(qrbuf->QRname);
348 if (ptr->namelen > ROOMNAMELEN)
349 ptr->namelen = ROOMNAMELEN - 1;
351 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
352 ptr->name[ptr->namelen] = '\0';
353 ptr->QRNum = qrbuf->QRnumber;
355 for (i = 0; i < ptr->namelen; i++)
357 ptr->lcname[i] = tolower(ptr->name[i]);
359 ptr->lcname[ptr->namelen] = '\0';
360 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
362 begin_critical_section(S_RPLIST);
365 end_critical_section(S_RPLIST);
368 void destroy_network_queue_room(RoomProcList *rplist)
370 struct RoomProcList *cur, *p;
381 void destroy_network_queue_room_locked (void)
383 begin_critical_section(S_RPLIST);
384 destroy_network_queue_room(rplist);
385 end_critical_section(S_RPLIST);
391 * Bounce a message back to the sender
393 void network_bounce(struct CtdlMessage *msg, char *reason)
395 struct CitContext *CCC = CC;
396 char *oldpath = NULL;
398 char bouncesource[SIZ];
400 struct recptypes *valid = NULL;
401 char force_room[ROOMNAMELEN];
402 static int serialnum = 0;
405 QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
407 if (msg == NULL) return;
409 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
412 * Give it a fresh message ID
414 if (msg->cm_fields['I'] != NULL) {
415 free(msg->cm_fields['I']);
417 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
418 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
419 msg->cm_fields['I'] = strdup(buf);
422 * FIXME ... right now we're just sending a bounce; we really want to
423 * include the text of the bounced message.
425 if (msg->cm_fields['M'] != NULL) {
426 free(msg->cm_fields['M']);
428 msg->cm_fields['M'] = strdup(reason);
429 msg->cm_format_type = 0;
432 * Turn the message around
434 if (msg->cm_fields['R'] == NULL) {
435 free(msg->cm_fields['R']);
438 if (msg->cm_fields['D'] == NULL) {
439 free(msg->cm_fields['D']);
442 snprintf(recipient, sizeof recipient, "%s@%s",
443 msg->cm_fields['A'], msg->cm_fields['N']);
445 if (msg->cm_fields['A'] == NULL) {
446 free(msg->cm_fields['A']);
449 if (msg->cm_fields['N'] == NULL) {
450 free(msg->cm_fields['N']);
453 if (msg->cm_fields['U'] == NULL) {
454 free(msg->cm_fields['U']);
457 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
458 msg->cm_fields['N'] = strdup(config.c_nodename);
459 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
461 /* prepend our node to the path */
462 if (msg->cm_fields['P'] != NULL) {
463 oldpath = msg->cm_fields['P'];
464 msg->cm_fields['P'] = NULL;
467 oldpath = strdup("unknown_user");
469 size = strlen(oldpath) + SIZ;
470 msg->cm_fields['P'] = malloc(size);
471 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
474 /* Now submit the message */
475 valid = validate_recipients(recipient, NULL, 0);
476 if (valid != NULL) if (valid->num_error != 0) {
477 free_recipients(valid);
480 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
481 strcpy(force_room, config.c_aideroom);
484 strcpy(force_room, "");
486 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
487 strcpy(force_room, config.c_aideroom);
489 CtdlSubmitMsg(msg, valid, force_room, 0);
492 if (valid != NULL) free_recipients(valid);
493 CtdlFreeMessage(msg);
494 QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
506 * Run through the rooms doing various types of network stuff.
508 void network_do_queue(void)
510 struct CitContext *CCC = CC;
511 static int doing_queue = 0;
512 static time_t last_run = 0L;
513 int full_processing = 1;
514 HashList *working_ignetcfg;
515 HashList *the_netmap = NULL;
516 int netmap_changed = 0;
520 * Run the full set of processing tasks no more frequently
521 * than once every n seconds
523 if ( (time(NULL) - last_run) < config.c_net_freq ) {
525 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
526 config.c_net_freq - (time(NULL)- last_run)
531 * This is a simple concurrency check to make sure only one queue run
532 * is done at a time. We could do this with a mutex, but since we
533 * don't really require extremely fine granularity here, we'll do it
534 * with a static variable instead.
541 become_session(&networker_spool_CC);
542 begin_critical_section(S_RPLIST);
545 end_critical_section(S_RPLIST);
547 RL.RoomsInterestedIn = NewHash(1, lFlathash);
548 if (full_processing &&
549 (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
552 DeleteHash(&RL.RoomsInterestedIn);
553 if (RL.rplist == NULL)
556 /* Load the IGnet Configuration into memory */
557 working_ignetcfg = load_ignetcfg();
560 * Load the network map and filter list into memory.
562 if (!server_shutting_down)
563 the_netmap = read_network_map();
564 if (!server_shutting_down)
565 load_network_filter_list();
568 * Go ahead and run the queue
570 if (full_processing && !server_shutting_down) {
571 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
572 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
575 if ((RL.rplist != NULL) && (!server_shutting_down)) {
576 RoomProcList *ptr, *cmp;
578 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
579 while (ptr != NULL && !server_shutting_down) {
583 while (cmp != NULL) {
584 if ((cmp->namelen > 0) &&
585 (cmp->key == ptr->key) &&
586 (cmp->namelen == ptr->namelen) &&
587 (strcmp(cmp->lcname, ptr->lcname) == 0))
594 if (ptr->namelen > 0) {
595 network_spoolout_room(ptr,
603 /* If there is anything in the inbound queue, process it */
604 if (!server_shutting_down) {
605 network_do_spoolin(working_ignetcfg,
610 /* Free the filter list in memory */
611 free_netfilter_list();
613 /* Save the network map back to disk */
614 if (netmap_changed) {
615 StrBuf *MapStr = SerializeNetworkMap(the_netmap);
616 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
619 /* combine singe message files into one spool entry per remote node. */
620 network_consolidate_spoolout(working_ignetcfg, the_netmap);
624 DeleteHash(&the_netmap);
626 DeleteHash(&working_ignetcfg);
628 QNM_syslog(LOG_DEBUG, "network: queue run completed");
630 if (full_processing) {
631 last_run = time(NULL);
633 DeleteHash(&RL.RoomsInterestedIn);
634 destroy_network_queue_room(RL.rplist);
641 int network_room_handler (struct ctdlroom *room)
643 network_queue_room(room, NULL);
647 int NTTDebugEnabled = 0;
650 * network_talking_to() -- concurrency checker
652 static HashList *nttlist = NULL;
653 int network_talking_to(const char *nodename, long len, int operation) {
659 begin_critical_section(S_NTTLIST);
665 nttlist = NewHash(1, NULL);
666 Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
667 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
670 if ((nttlist == NULL) ||
671 (GetCount(nttlist) == 0))
673 Pos = GetNewHashPos(nttlist, 1);
674 if (GetHashPosFromKey (nttlist, nodename, len, Pos))
675 DeleteEntryFromHash(nttlist, Pos);
677 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
682 if ((nttlist == NULL) ||
683 (GetCount(nttlist) == 0))
685 if (GetHash(nttlist, nodename, len, &vdata))
687 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
691 end_critical_section(S_NTTLIST);
695 void cleanup_nttlist(void)
697 begin_critical_section(S_NTTLIST);
698 DeleteHash(&nttlist);
699 end_critical_section(S_NTTLIST);
704 void network_logout_hook(void)
706 CitContext *CCC = MyContext();
709 * If we were talking to a network node, we're not anymore...
711 if (!IsEmptyStr(CCC->net_node)) {
712 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
713 CCC->net_node[0] = '\0';
716 void network_cleanup_function(void)
718 struct CitContext *CCC = CC;
720 if (!IsEmptyStr(CCC->net_node)) {
721 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
722 CCC->net_node[0] = '\0';
730 void SetNTTDebugEnabled(const int n)
734 void SetNetQDebugEnabled(const int n)
736 NetQDebugEnabled = n;
739 CTDL_MODULE_INIT(network)
743 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
744 CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
745 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
746 CtdlRegisterCleanupHook(cleanup_nttlist);
747 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
748 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
749 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
750 CtdlRegisterRoomHook(network_room_handler);
751 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
752 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);