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 {
91 HashList *RoomsInterestedIn;
94 * When we do network processing, it's accomplished in two passes; one to
95 * gather a list of rooms and one to actually do them. It's ok that rplist
96 * is global; we have a mutex that keeps it safe.
98 struct RoomProcList *rplist = NULL;
100 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
104 struct dirent *filedir_entry;
108 filedir = opendir (DirName);
109 if (filedir == NULL) {
113 d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
118 while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
119 (filedir_entry != NULL))
121 RoomNR = atol(filedir_entry->d_name);
124 Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
136 * Check the use table. This is a list of messages which have recently
137 * arrived on the system. It is maintained and queried to prevent the same
138 * message from being entered into the database multiple times if it happens
139 * to arrive multiple times by accident.
141 int network_usetable(struct CtdlMessage *msg)
143 struct CitContext *CCC = CC;
145 struct cdbdata *cdbut;
148 /* Bail out if we can't generate a message ID */
152 if (msg->cm_fields['I'] == NULL) {
155 if (IsEmptyStr(msg->cm_fields['I'])) {
159 /* Generate the message ID */
160 strcpy(msgid, msg->cm_fields['I']);
161 if (haschar(msgid, '@') == 0) {
163 if (msg->cm_fields['N'] != NULL) {
164 strcat(msgid, msg->cm_fields['N']);
171 cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
174 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
178 /* If we got to this point, it's unique: add it. */
179 strcpy(ut.ut_msgid, msgid);
180 ut.ut_timestamp = time(NULL);
181 cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
195 * Send the *entire* contents of the current room to one specific network node,
196 * ignoring anything we know about which messages have already undergone
197 * network processing. This can be used to bring a new node into sync.
199 int network_sync_to(char *target_node, long len)
201 struct CitContext *CCC = CC;
209 char filename[PATH_MAX];
212 /* Grab the configuration line we're looking for */
213 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
214 begin_critical_section(S_NETCONFIGS);
215 fp = fopen(filename, "r");
217 end_critical_section(S_NETCONFIGS);
220 while (fgets(buf, sizeof buf, fp) != NULL)
222 buf[strlen(buf)-1] = 0;
224 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
225 if (strcasecmp(sc_type, "ignet_push_share"))
228 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
229 if (strcasecmp(sc_node, target_node))
232 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
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);
248 end_critical_section(S_NETCONFIGS);
251 free(sc.ignet_push_shares);
255 sc.working_ignetcfg = load_ignetcfg();
256 sc.the_netmap = CtdlReadNetworkMap();
258 /* Send ALL messages */
259 num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
260 network_spool_msg, &sc);
262 /* Concise cleanup because we know there's only one node in the sc */
263 free(sc.ignet_push_shares);
265 DeleteHash(&sc.working_ignetcfg);
266 DeleteHash(&sc.the_netmap);
268 QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
269 num_spooled, target_node);
277 * Implements the NSYN command
279 void cmd_nsyn(char *argbuf) {
282 char target_node[256];
284 if (CtdlAccessCheck(ac_aide)) return;
286 len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
287 ///// TODO num_spooled = network_sync_to(target_node, len);
288 if (num_spooled >= 0) {
289 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
292 cprintf("%d No such room/node share exists.\n",
293 ERROR + ROOM_NOT_FOUND);
300 * Batch up and send all outbound traffic from the current room
302 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
304 struct RoomProcList *ptr;
305 long QRNum = qrbuf->QRnumber;
307 roomlists *RP = (roomlists*) data;
309 if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
312 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
313 if (ptr == NULL) return;
315 ptr->namelen = strlen(qrbuf->QRname);
316 if (ptr->namelen > ROOMNAMELEN)
317 ptr->namelen = ROOMNAMELEN - 1;
319 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
320 ptr->name[ptr->namelen] = '\0';
321 ptr->QRNum = qrbuf->QRnumber;
323 for (i = 0; i < ptr->namelen; i++)
325 ptr->lcname[i] = tolower(ptr->name[i]);
328 ptr->lcname[ptr->namelen] = '\0';
329 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
330 ptr->next = RP->rplist;
335 * Batch up and send all outbound traffic from the current room
337 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
339 struct RoomProcList *ptr;
341 if (qrbuf->QRdefaultview == VIEW_QUEUE)
343 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
344 if (ptr == NULL) return;
346 ptr->namelen = strlen(qrbuf->QRname);
347 if (ptr->namelen > ROOMNAMELEN)
348 ptr->namelen = ROOMNAMELEN - 1;
350 memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
351 ptr->name[ptr->namelen] = '\0';
352 ptr->QRNum = qrbuf->QRnumber;
354 for (i = 0; i < ptr->namelen; i++)
356 ptr->lcname[i] = tolower(ptr->name[i]);
358 ptr->lcname[ptr->namelen] = '\0';
359 ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
361 begin_critical_section(S_RPLIST);
364 end_critical_section(S_RPLIST);
367 void destroy_network_queue_room(RoomProcList *rplist)
369 struct RoomProcList *cur, *p;
380 void destroy_network_queue_room_locked (void)
382 begin_critical_section(S_RPLIST);
383 destroy_network_queue_room(rplist);
384 end_critical_section(S_RPLIST);
390 * Bounce a message back to the sender
392 void network_bounce(struct CtdlMessage *msg, char *reason)
394 struct CitContext *CCC = CC;
395 char *oldpath = NULL;
397 char bouncesource[SIZ];
399 struct recptypes *valid = NULL;
400 char force_room[ROOMNAMELEN];
401 static int serialnum = 0;
404 QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
406 if (msg == NULL) return;
408 snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
411 * Give it a fresh message ID
413 if (msg->cm_fields['I'] != NULL) {
414 free(msg->cm_fields['I']);
416 snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
417 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
418 msg->cm_fields['I'] = strdup(buf);
421 * FIXME ... right now we're just sending a bounce; we really want to
422 * include the text of the bounced message.
424 if (msg->cm_fields['M'] != NULL) {
425 free(msg->cm_fields['M']);
427 msg->cm_fields['M'] = strdup(reason);
428 msg->cm_format_type = 0;
431 * Turn the message around
433 if (msg->cm_fields['R'] == NULL) {
434 free(msg->cm_fields['R']);
437 if (msg->cm_fields['D'] == NULL) {
438 free(msg->cm_fields['D']);
441 snprintf(recipient, sizeof recipient, "%s@%s",
442 msg->cm_fields['A'], msg->cm_fields['N']);
444 if (msg->cm_fields['A'] == NULL) {
445 free(msg->cm_fields['A']);
448 if (msg->cm_fields['N'] == NULL) {
449 free(msg->cm_fields['N']);
452 if (msg->cm_fields['U'] == NULL) {
453 free(msg->cm_fields['U']);
456 msg->cm_fields['A'] = strdup(BOUNCESOURCE);
457 msg->cm_fields['N'] = strdup(config.c_nodename);
458 msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
460 /* prepend our node to the path */
461 if (msg->cm_fields['P'] != NULL) {
462 oldpath = msg->cm_fields['P'];
463 msg->cm_fields['P'] = NULL;
466 oldpath = strdup("unknown_user");
468 size = strlen(oldpath) + SIZ;
469 msg->cm_fields['P'] = malloc(size);
470 snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
473 /* Now submit the message */
474 valid = validate_recipients(recipient, NULL, 0);
475 if (valid != NULL) if (valid->num_error != 0) {
476 free_recipients(valid);
479 if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
480 strcpy(force_room, config.c_aideroom);
483 strcpy(force_room, "");
485 if ( (valid == NULL) && IsEmptyStr(force_room) ) {
486 strcpy(force_room, config.c_aideroom);
488 CtdlSubmitMsg(msg, valid, force_room, 0);
491 if (valid != NULL) free_recipients(valid);
492 CtdlFreeMessage(msg);
493 QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
505 * Run through the rooms doing various types of network stuff.
507 void network_do_queue(void)
509 struct CitContext *CCC = CC;
510 static int doing_queue = 0;
511 static time_t last_run = 0L;
512 int full_processing = 1;
513 HashList *working_ignetcfg;
514 HashList *the_netmap = NULL;
515 int netmap_changed = 0;
519 * Run the full set of processing tasks no more frequently
520 * than once every n seconds
522 if ( (time(NULL) - last_run) < config.c_net_freq ) {
524 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
525 config.c_net_freq - (time(NULL)- last_run)
530 * This is a simple concurrency check to make sure only one queue run
531 * is done at a time. We could do this with a mutex, but since we
532 * don't really require extremely fine granularity here, we'll do it
533 * with a static variable instead.
540 become_session(&networker_spool_CC);
541 begin_critical_section(S_RPLIST);
544 end_critical_section(S_RPLIST);
546 RL.RoomsInterestedIn = NewHash(1, lFlathash);
547 if (full_processing &&
548 (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
551 DeleteHash(&RL.RoomsInterestedIn);
552 if (RL.rplist == NULL)
555 /* Load the IGnet Configuration into memory */
556 working_ignetcfg = CtdlLoadIgNetCfg();
559 * Load the network map and filter list into memory.
561 if (!server_shutting_down)
562 the_netmap = CtdlReadNetworkMap();
563 if (!server_shutting_down)
564 load_network_filter_list();
567 * Go ahead and run the queue
569 if (full_processing && !server_shutting_down) {
570 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
571 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
574 if ((RL.rplist != NULL) && (!server_shutting_down)) {
575 RoomProcList *ptr, *cmp;
577 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
578 while (ptr != NULL && !server_shutting_down) {
582 while (cmp != NULL) {
583 if ((cmp->namelen > 0) &&
584 (cmp->key == ptr->key) &&
585 (cmp->namelen == ptr->namelen) &&
586 (strcmp(cmp->lcname, ptr->lcname) == 0))
593 if (ptr->namelen > 0) {
594 network_spoolout_room(ptr,
602 /* If there is anything in the inbound queue, process it */
603 if (!server_shutting_down) {
604 network_do_spoolin(working_ignetcfg,
609 /* Free the filter list in memory */
610 free_netfilter_list();
612 /* Save the network map back to disk */
613 if (netmap_changed) {
614 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
615 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
618 /* combine singe message files into one spool entry per remote node. */
619 network_consolidate_spoolout(working_ignetcfg, the_netmap);
623 DeleteHash(&the_netmap);
625 DeleteHash(&working_ignetcfg);
627 QNM_syslog(LOG_DEBUG, "network: queue run completed");
629 if (full_processing) {
630 last_run = time(NULL);
632 DeleteHash(&RL.RoomsInterestedIn);
633 destroy_network_queue_room(RL.rplist);
640 int network_room_handler (struct ctdlroom *room)
642 network_queue_room(room, NULL);
649 void network_logout_hook(void)
651 CitContext *CCC = MyContext();
654 * If we were talking to a network node, we're not anymore...
656 if (!IsEmptyStr(CCC->net_node)) {
657 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
658 CCC->net_node[0] = '\0';
661 void network_cleanup_function(void)
663 struct CitContext *CCC = CC;
665 if (!IsEmptyStr(CCC->net_node)) {
666 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
667 CCC->net_node[0] = '\0';
676 void SetNetQDebugEnabled(const int n)
678 NetQDebugEnabled = n;
681 CTDL_MODULE_INIT(network)
685 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
686 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
687 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
688 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
689 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
690 CtdlRegisterRoomHook(network_room_handler);
691 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
692 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);