2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2011 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 /* comes from lookup3.c from libcitadel... */
96 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
98 typedef struct __roomlists {
100 HashList *RoomsInterestedIn;
103 * When we do network processing, it's accomplished in two passes; one to
104 * gather a list of rooms and one to actually do them. It's ok that rplist
105 * is global; we have a mutex that keeps it safe.
107 struct RoomProcList *rplist = NULL;
109 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
113 struct dirent *filedir_entry;
117 filedir = opendir (DirName);
118 if (filedir == NULL) {
122 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
127 while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
128 (filedir_entry != NULL))
130 RoomNR = atol(filedir_entry->d_name);
133 Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
145 * Check the use table. This is a list of messages which have recently
146 * arrived on the system. It is maintained and queried to prevent the same
147 * message from being entered into the database multiple times if it happens
148 * to arrive multiple times by accident.
150 int network_usetable(struct CtdlMessage *msg) {
153 struct cdbdata *cdbut;
156 /* Bail out if we can't generate a message ID */
160 if (msg->cm_fields['I'] == NULL) {
163 if (IsEmptyStr(msg->cm_fields['I'])) {
167 /* Generate the message ID */
168 strcpy(msgid, msg->cm_fields['I']);
169 if (haschar(msgid, '@') == 0) {
171 if (msg->cm_fields['N'] != NULL) {
172 strcat(msgid, msg->cm_fields['N']);
179 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
182 syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
186 /* If we got to this point, it's unique: add it. */
187 strcpy(ut.ut_msgid, msgid);
188 ut.ut_timestamp = time(NULL);
189 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
203 * Send the *entire* contents of the current room to one specific network node,
204 * ignoring anything we know about which messages have already undergone
205 * network processing. This can be used to bring a new node into sync.
207 int network_sync_to(char *target_node) {
215 char filename[PATH_MAX];
218 /* Grab the configuration line we're looking for */
219 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
220 begin_critical_section(S_NETCONFIGS);
221 fp = fopen(filename, "r");
223 end_critical_section(S_NETCONFIGS);
226 while (fgets(buf, sizeof buf, fp) != NULL) {
227 buf[strlen(buf)-1] = 0;
228 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
229 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
230 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
231 if ( (!strcasecmp(sc_type, "ignet_push_share"))
232 && (!strcasecmp(sc_node, target_node)) ) {
235 /* Concise syntax because we don't need a full linked-list */
236 memset(&sc, 0, sizeof(SpoolControl));
237 sc.ignet_push_shares = (maplist *)
238 malloc(sizeof(maplist));
239 sc.ignet_push_shares->next = NULL;
240 safestrncpy(sc.ignet_push_shares->remote_nodename,
242 sizeof sc.ignet_push_shares->remote_nodename);
243 safestrncpy(sc.ignet_push_shares->remote_roomname,
245 sizeof sc.ignet_push_shares->remote_roomname);
249 end_critical_section(S_NETCONFIGS);
251 if (!found_node) return(-1);
253 /* Send ALL messages */
254 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
255 network_spool_msg, &sc);
257 /* Concise cleanup because we know there's only one node in the sc */
258 free(sc.ignet_push_shares);
260 syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
261 num_spooled, target_node);
267 * Implements the NSYN command
269 void cmd_nsyn(char *argbuf) {
271 char target_node[256];
273 if (CtdlAccessCheck(ac_aide)) return;
275 extract_token(target_node, argbuf, 0, '|', sizeof target_node);
276 num_spooled = network_sync_to(target_node);
277 if (num_spooled >= 0) {
278 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
281 cprintf("%d No such room/node share exists.\n",
282 ERROR + ROOM_NOT_FOUND);
289 * Batch up and send all outbound traffic from the current room
291 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
293 struct RoomProcList *ptr;
294 long QRNum = qrbuf->QRnumber;
296 roomlists *RP = (roomlists*) data;
298 if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
301 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
302 if (ptr == NULL) return;
304 ptr->namelen = strlen(qrbuf->QRname);
305 if (ptr->namelen > ROOMNAMELEN)
306 ptr->namelen = ROOMNAMELEN - 1;
308 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
309 ptr->name[ptr->namelen] = '\0';
310 ptr->QRNum = qrbuf->QRnumber;
312 for (i = 0; i < ptr->namelen; i++)
314 ptr->lcname[i] = tolower(ptr->name[i]);
317 ptr->lcname[ptr->namelen] = '\0';
318 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
319 ptr->next = RP->rplist;
324 * Batch up and send all outbound traffic from the current room
326 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
328 struct RoomProcList *ptr;
330 if (qrbuf->QRdefaultview == VIEW_QUEUE)
332 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
333 if (ptr == NULL) return;
335 ptr->namelen = strlen(qrbuf->QRname);
336 if (ptr->namelen > ROOMNAMELEN)
337 ptr->namelen = ROOMNAMELEN - 1;
339 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
340 ptr->name[ptr->namelen] = '\0';
341 ptr->QRNum = qrbuf->QRnumber;
343 for (i = 0; i < ptr->namelen; i++)
345 ptr->lcname[i] = tolower(ptr->name[i]);
347 ptr->lcname[ptr->namelen] = '\0';
348 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
350 begin_critical_section(S_RPLIST);
353 end_critical_section(S_RPLIST);
356 void destroy_network_queue_room(RoomProcList *rplist)
358 struct RoomProcList *cur, *p;
369 void destroy_network_queue_room_locked (void)
371 begin_critical_section(S_RPLIST);
372 destroy_network_queue_room(rplist);
373 end_critical_section(S_RPLIST);
379 * Bounce a message back to the sender
381 void network_bounce(struct CtdlMessage *msg, char *reason) {
382 char *oldpath = NULL;
384 char bouncesource[SIZ];
386 struct recptypes *valid = NULL;
387 char force_room[ROOMNAMELEN];
388 static int serialnum = 0;
391 syslog(LOG_DEBUG, "entering network_bounce()\n");
393 if (msg == NULL) return;
395 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
398 * Give it a fresh message ID
400 if (msg->cm_fields['I'] != NULL) {
401 free(msg->cm_fields['I']);
403 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
404 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
405 msg->cm_fields['I'] = strdup(buf);
408 * FIXME ... right now we're just sending a bounce; we really want to
409 * include the text of the bounced message.
411 if (msg->cm_fields['M'] != NULL) {
412 free(msg->cm_fields['M']);
414 msg->cm_fields['M'] = strdup(reason);
415 msg->cm_format_type = 0;
418 * Turn the message around
420 if (msg->cm_fields['R'] == NULL) {
421 free(msg->cm_fields['R']);
424 if (msg->cm_fields['D'] == NULL) {
425 free(msg->cm_fields['D']);
428 snprintf(recipient, sizeof recipient, "%s@%s",
429 msg->cm_fields['A'], msg->cm_fields['N']);
431 if (msg->cm_fields['A'] == NULL) {
432 free(msg->cm_fields['A']);
435 if (msg->cm_fields['N'] == NULL) {
436 free(msg->cm_fields['N']);
439 if (msg->cm_fields['U'] == NULL) {
440 free(msg->cm_fields['U']);
443 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
444 msg->cm_fields['N'] = strdup(config.c_nodename);
445 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
447 /* prepend our node to the path */
448 if (msg->cm_fields['P'] != NULL) {
449 oldpath = msg->cm_fields['P'];
450 msg->cm_fields['P'] = NULL;
453 oldpath = strdup("unknown_user");
455 size = strlen(oldpath) + SIZ;
456 msg->cm_fields['P'] = malloc(size);
457 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
460 /* Now submit the message */
461 valid = validate_recipients(recipient, NULL, 0);
462 if (valid != NULL) if (valid->num_error != 0) {
463 free_recipients(valid);
466 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
467 strcpy(force_room, config.c_aideroom);
470 strcpy(force_room, "");
472 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
473 strcpy(force_room, config.c_aideroom);
475 CtdlSubmitMsg(msg, valid, force_room, 0);
478 if (valid != NULL) free_recipients(valid);
479 CtdlFreeMessage(msg);
480 syslog(LOG_DEBUG, "leaving network_bounce()\n");
492 * Run through the rooms doing various types of network stuff.
494 void network_do_queue(void) {
495 static int doing_queue = 0;
496 static time_t last_run = 0L;
497 int full_processing = 1;
498 char *working_ignetcfg;
499 NetMap *the_netmap = NULL;
500 int netmap_changed = 0;
504 * Run the full set of processing tasks no more frequently
505 * than once every n seconds
507 if ( (time(NULL) - last_run) < config.c_net_freq ) {
509 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
510 config.c_net_freq - (time(NULL)- last_run)
515 * This is a simple concurrency check to make sure only one queue run
516 * is done at a time. We could do this with a mutex, but since we
517 * don't really require extremely fine granularity here, we'll do it
518 * with a static variable instead.
525 begin_critical_section(S_RPLIST);
528 end_critical_section(S_RPLIST);
530 RL.RoomsInterestedIn = NewHash(1, lFlathash);
531 if (full_processing &&
532 (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
535 DeleteHash(&RL.RoomsInterestedIn);
536 if (RL.rplist == NULL)
539 /* Load the IGnet Configuration into memory */
540 working_ignetcfg = load_working_ignetcfg();
543 * Load the network map and filter list into memory.
545 if (!server_shutting_down)
546 the_netmap = read_network_map();
547 if (!server_shutting_down)
548 load_network_filter_list();
551 * Go ahead and run the queue
553 if (full_processing && !server_shutting_down) {
554 syslog(LOG_DEBUG, "network: loading outbound queue\n");
555 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
558 if ((RL.rplist != NULL) && (!server_shutting_down)) {
559 RoomProcList *ptr, *cmp;
561 syslog(LOG_DEBUG, "network: running outbound queue\n");
562 while (ptr != NULL && !server_shutting_down) {
566 while (cmp != NULL) {
567 if ((cmp->namelen > 0) &&
568 (cmp->key == ptr->key) &&
569 (cmp->namelen == ptr->namelen) &&
570 (strcmp(cmp->lcname, ptr->lcname) == 0))
577 if (ptr->namelen > 0) {
578 network_spoolout_room(ptr,
586 /* If there is anything in the inbound queue, process it */
587 if (!server_shutting_down) {
588 network_do_spoolin(working_ignetcfg,
593 /* Save the network map back to disk */
594 write_network_map(the_netmap, netmap_changed);
596 /* Free the filter list in memory */
597 free_netfilter_list();
599 network_consolidate_spoolout(working_ignetcfg, the_netmap);
600 free(working_ignetcfg);
602 syslog(LOG_DEBUG, "network: queue run completed\n");
604 if (full_processing) {
605 last_run = time(NULL);
607 DeleteHash(&RL.RoomsInterestedIn);
608 destroy_network_queue_room(RL.rplist);
615 int network_room_handler (struct ctdlroom *room)
617 network_queue_room(room, NULL);
621 int NTTDebugEnabled = 0;
624 * network_talking_to() -- concurrency checker
626 static HashList *nttlist = NULL;
627 int network_talking_to(const char *nodename, long len, int operation) {
633 begin_critical_section(S_NTTLIST);
639 nttlist = NewHash(1, NULL);
640 Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
641 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
644 if ((nttlist == NULL) ||
645 (GetCount(nttlist) == 0))
647 Pos = GetNewHashPos(nttlist, 1);
648 if (GetHashPosFromKey (nttlist, nodename, len, Pos))
649 DeleteEntryFromHash(nttlist, Pos);
651 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
656 if ((nttlist == NULL) ||
657 (GetCount(nttlist) == 0))
659 if (GetHash(nttlist, nodename, len, &vdata))
661 if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
665 end_critical_section(S_NTTLIST);
669 void cleanup_nttlist(void)
671 begin_critical_section(S_NTTLIST);
672 DeleteHash(&nttlist);
673 end_critical_section(S_NTTLIST);
678 void network_logout_hook(void)
680 CitContext *CCC = MyContext();
683 * If we were talking to a network node, we're not anymore...
685 if (!IsEmptyStr(CCC->net_node)) {
686 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
693 void SetNTTDebugEnabled(const int n)
698 CTDL_MODULE_INIT(network)
702 CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
703 CtdlRegisterCleanupHook(cleanup_nttlist);
704 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT);
705 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
706 CtdlRegisterRoomHook(network_room_handler);
707 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
708 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);