6dda5036342adf7330238adee5d4294d6f3d10ec
[citadel.git] / citadel / modules / network / serv_network.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2012 by the citadel.org team
6  *
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.
9  *
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.
14  *
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.
21  *
22  */
23
24 /*
25  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
26  * requests that have not been confirmed will be deleted.
27  */
28 #define EXP     259200  /* three days */
29
30 #include "sysdep.h"
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <pwd.h>
38 #include <errno.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <dirent.h>
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
44 # include <time.h>
45 #else
46 # if HAVE_SYS_TIME_H
47 #  include <sys/time.h>
48 # else
49 #  include <time.h>
50 # endif
51 #endif
52 #ifdef HAVE_SYSCALL_H
53 # include <syscall.h>
54 #else 
55 # if HAVE_SYS_SYSCALL_H
56 #  include <sys/syscall.h>
57 # endif
58 #endif
59
60 #include <sys/wait.h>
61 #include <string.h>
62 #include <limits.h>
63 #include <libcitadel.h>
64 #include "citadel.h"
65 #include "server.h"
66 #include "citserver.h"
67 #include "support.h"
68 #include "config.h"
69 #include "user_ops.h"
70 #include "database.h"
71 #include "msgbase.h"
72 #include "internet_addressing.h"
73 #include "serv_network.h"
74 #include "clientsocket.h"
75 #include "file_ops.h"
76 #include "citadel_dirs.h"
77 #include "threads.h"
78 #include "context.h"
79 #include "ctdl_module.h"
80 #include "netspool.h"
81 #include "netmail.h"
82
83 int NetQDebugEnabled = 0;
84 struct CitContext networker_spool_CC;
85
86 /* comes from lookup3.c from libcitadel... */
87 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
88
89 typedef struct __roomlists {
90         RoomProcList *rplist;
91         HashList *RoomsInterestedIn;
92 }roomlists;
93 /*
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.
97  */
98 struct RoomProcList *rplist = NULL;
99
100
101
102 /*
103  * Check the use table.  This is a list of messages which have recently
104  * arrived on the system.  It is maintained and queried to prevent the same
105  * message from being entered into the database multiple times if it happens
106  * to arrive multiple times by accident.
107  */
108 int network_usetable(struct CtdlMessage *msg)
109 {
110         struct CitContext *CCC = CC;
111         char msgid[SIZ];
112         struct cdbdata *cdbut;
113         struct UseTable ut;
114
115         /* Bail out if we can't generate a message ID */
116         if (msg == NULL) {
117                 return(0);
118         }
119         if (msg->cm_fields['I'] == NULL) {
120                 return(0);
121         }
122         if (IsEmptyStr(msg->cm_fields['I'])) {
123                 return(0);
124         }
125
126         /* Generate the message ID */
127         strcpy(msgid, msg->cm_fields['I']);
128         if (haschar(msgid, '@') == 0) {
129                 strcat(msgid, "@");
130                 if (msg->cm_fields['N'] != NULL) {
131                         strcat(msgid, msg->cm_fields['N']);
132                 }
133                 else {
134                         return(0);
135                 }
136         }
137
138         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
139         if (cdbut != NULL) {
140                 cdb_free(cdbut);
141                 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
142                 return(1);
143         }
144
145         /* If we got to this point, it's unique: add it. */
146         strcpy(ut.ut_msgid, msgid);
147         ut.ut_timestamp = time(NULL);
148         cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
149         return(0);
150 }
151
152
153
154 /*
155  * Send the *entire* contents of the current room to one specific network node,
156  * ignoring anything we know about which messages have already undergone
157  * network processing.  This can be used to bring a new node into sync.
158  */
159 int network_sync_to(char *target_node, long len)
160 {
161         struct CitContext *CCC = CC;
162         const OneRoomNetCfg *OneRNCFG;
163         const RoomNetCfgLine *pCfgLine;
164         SpoolControl sc;
165         int num_spooled = 0;
166
167         /* Grab the configuration line we're looking for */
168         begin_critical_section(S_NETCONFIGS);
169         OneRNCFG = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
170         if ((OneRNCFG == NULL) ||
171             (OneRNCFG->NetConfigs[ignet_push_share] == NULL))
172         {
173                 return -1;
174         }
175
176         pCfgLine = OneRNCFG->NetConfigs[ignet_push_share];
177         while (pCfgLine != NULL)
178         {
179                 if (strcmp(ChrPtr(pCfgLine->Value[0]), target_node))
180                         break;
181                 pCfgLine = pCfgLine->next;
182         }
183         if (pCfgLine == NULL)
184         {
185                 return -1;
186         }
187         memset(&sc, 0, sizeof(SpoolControl));
188
189         sc.NetConfigs[ignet_push_share] = DuplicateOneGenericCfgLine(pCfgLine);
190
191         end_critical_section(S_NETCONFIGS);
192
193         sc.working_ignetcfg = CtdlLoadIgNetCfg();
194         sc.the_netmap = CtdlReadNetworkMap();
195
196         /* Send ALL messages */
197         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
198                 network_spool_msg, &sc);
199
200         /* Concise cleanup because we know there's only one node in the sc */
201         DeleteGenericCfgLine(NULL/*TODO*/, &sc.NetConfigs[ignet_push_share]);
202
203         DeleteHash(&sc.working_ignetcfg);
204         DeleteHash(&sc.the_netmap);
205
206         QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
207                   num_spooled, target_node);
208         return(num_spooled);
209 }
210
211
212 /*
213  * Implements the NSYN command
214  */
215 void cmd_nsyn(char *argbuf) {
216         int num_spooled;
217         long len;
218         char target_node[256];
219
220         if (CtdlAccessCheck(ac_aide)) return;
221
222         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
223         num_spooled = network_sync_to(target_node, len);
224         if (num_spooled >= 0) {
225                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
226         }
227         else {
228                 cprintf("%d No such room/node share exists.\n",
229                         ERROR + ROOM_NOT_FOUND);
230         }
231 }
232
233 RoomProcList *CreateRoomProcListEntry(struct ctdlroom *qrbuf, const OneRoomNetCfg *OneRNCFG)
234 {
235         int i;
236         struct RoomProcList *ptr;
237
238         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
239         if (ptr == NULL) return NULL;
240
241         ptr->namelen = strlen(qrbuf->QRname);
242         if (ptr->namelen > ROOMNAMELEN)
243                 ptr->namelen = ROOMNAMELEN - 1;
244
245         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
246         ptr->name[ptr->namelen] = '\0';
247         ptr->QRNum = qrbuf->QRnumber;
248
249         for (i = 0; i < ptr->namelen; i++)
250         {
251                 ptr->lcname[i] = tolower(ptr->name[i]);
252         }
253
254         ptr->lcname[ptr->namelen] = '\0';
255         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
256         ptr->OneRNCFG = OneRNCFG;
257         return ptr;
258 }
259
260 /*
261  * Batch up and send all outbound traffic from the current room
262  */
263 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data, const OneRoomNetCfg *OneRNCfg)
264 {
265         struct RoomProcList *ptr;
266         roomlists *RP = (roomlists*) data;
267
268         ptr = CreateRoomProcListEntry(qrbuf, OneRNCfg);
269
270         ptr->next = RP->rplist;
271         RP->rplist = ptr;
272 }
273
274 /*
275  * Batch up and send all outbound traffic from the current room
276  */
277 int network_room_handler (struct ctdlroom *qrbuf)
278 {
279         struct RoomProcList *ptr;
280         const OneRoomNetCfg* RNCfg;
281
282         if (qrbuf->QRdefaultview == VIEW_QUEUE)
283                 return 1;
284
285         RNCfg = CtdlGetNetCfgForRoom(qrbuf->QRnumber);
286         if (RNCfg == NULL)
287                 return 1;
288
289         ptr = CreateRoomProcListEntry(qrbuf, RNCfg);
290         if (ptr == NULL)
291                 return 1;
292
293         begin_critical_section(S_RPLIST);
294         ptr->next = rplist;
295         rplist = ptr;
296         end_critical_section(S_RPLIST);
297         return 1;
298 }
299
300 void destroy_network_queue_room(RoomProcList *rplist)
301 {
302         struct RoomProcList *cur, *p;
303
304         cur = rplist;
305         while (cur != NULL)
306         {
307                 p = cur->next;
308                 free (cur);
309                 cur = p;                
310         }
311 }
312
313 void destroy_network_queue_room_locked (void)
314 {
315         begin_critical_section(S_RPLIST);
316         destroy_network_queue_room(rplist);
317         end_critical_section(S_RPLIST);
318 }
319
320
321
322 /*
323  * Bounce a message back to the sender
324  */
325 void network_bounce(struct CtdlMessage *msg, char *reason)
326 {
327         struct CitContext *CCC = CC;
328         char *oldpath = NULL;
329         char buf[SIZ];
330         char bouncesource[SIZ];
331         char recipient[SIZ];
332         struct recptypes *valid = NULL;
333         char force_room[ROOMNAMELEN];
334         static int serialnum = 0;
335         size_t size;
336
337         QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
338
339         if (msg == NULL) return;
340
341         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
342
343         /* 
344          * Give it a fresh message ID
345          */
346         if (msg->cm_fields['I'] != NULL) {
347                 free(msg->cm_fields['I']);
348         }
349         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
350                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
351         msg->cm_fields['I'] = strdup(buf);
352
353         /*
354          * FIXME ... right now we're just sending a bounce; we really want to
355          * include the text of the bounced message.
356          */
357         if (msg->cm_fields['M'] != NULL) {
358                 free(msg->cm_fields['M']);
359         }
360         msg->cm_fields['M'] = strdup(reason);
361         msg->cm_format_type = 0;
362
363         /*
364          * Turn the message around
365          */
366         if (msg->cm_fields['R'] == NULL) {
367                 free(msg->cm_fields['R']);
368         }
369
370         if (msg->cm_fields['D'] == NULL) {
371                 free(msg->cm_fields['D']);
372         }
373
374         snprintf(recipient, sizeof recipient, "%s@%s",
375                 msg->cm_fields['A'], msg->cm_fields['N']);
376
377         if (msg->cm_fields['A'] == NULL) {
378                 free(msg->cm_fields['A']);
379         }
380
381         if (msg->cm_fields['N'] == NULL) {
382                 free(msg->cm_fields['N']);
383         }
384
385         if (msg->cm_fields['U'] == NULL) {
386                 free(msg->cm_fields['U']);
387         }
388
389         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
390         msg->cm_fields['N'] = strdup(config.c_nodename);
391         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
392
393         /* prepend our node to the path */
394         if (msg->cm_fields['P'] != NULL) {
395                 oldpath = msg->cm_fields['P'];
396                 msg->cm_fields['P'] = NULL;
397         }
398         else {
399                 oldpath = strdup("unknown_user");
400         }
401         size = strlen(oldpath) + SIZ;
402         msg->cm_fields['P'] = malloc(size);
403         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
404         free(oldpath);
405
406         /* Now submit the message */
407         valid = validate_recipients(recipient, NULL, 0);
408         if (valid != NULL) if (valid->num_error != 0) {
409                 free_recipients(valid);
410                 valid = NULL;
411         }
412         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
413                 strcpy(force_room, config.c_aideroom);
414         }
415         else {
416                 strcpy(force_room, "");
417         }
418         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
419                 strcpy(force_room, config.c_aideroom);
420         }
421         CtdlSubmitMsg(msg, valid, force_room, 0);
422
423         /* Clean up */
424         if (valid != NULL) free_recipients(valid);
425         CtdlFreeMessage(msg);
426         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
427 }
428
429
430
431
432
433
434
435 /*
436  * network_do_queue()
437  * 
438  * Run through the rooms doing various types of network stuff.
439  */
440 void network_do_queue(void)
441 {
442         struct CitContext *CCC = CC;
443         static int doing_queue = 0;
444         static time_t last_run = 0L;
445         int full_processing = 1;
446         HashList *working_ignetcfg;
447         HashList *the_netmap = NULL;
448         int netmap_changed = 0;
449         roomlists RL;
450
451         /*
452          * Run the full set of processing tasks no more frequently
453          * than once every n seconds
454          */
455         if ( (time(NULL) - last_run) < config.c_net_freq ) {
456                 full_processing = 0;
457                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
458                        config.c_net_freq - (time(NULL)- last_run)
459                 );
460         }
461
462         /*
463          * This is a simple concurrency check to make sure only one queue run
464          * is done at a time.  We could do this with a mutex, but since we
465          * don't really require extremely fine granularity here, we'll do it
466          * with a static variable instead.
467          */
468         if (doing_queue) {
469                 return;
470         }
471         doing_queue = 1;
472
473         become_session(&networker_spool_CC);
474         begin_critical_section(S_RPLIST);
475         RL.rplist = rplist;
476         rplist = NULL;
477         end_critical_section(S_RPLIST);
478 ///TODO hm, check whether we have a config at all here?
479         /* Load the IGnet Configuration into memory */
480         working_ignetcfg = CtdlLoadIgNetCfg();
481
482         /*
483          * Load the network map and filter list into memory.
484          */
485         if (!server_shutting_down)
486                 the_netmap = CtdlReadNetworkMap();
487 #if 0
488         /* filterlist isn't supported anymore
489         if (!server_shutting_down)
490                 load_network_filter_list();
491         */
492 #endif
493
494         /* 
495          * Go ahead and run the queue
496          */
497         if (full_processing && !server_shutting_down) {
498                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
499                 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
500         }
501
502         if ((RL.rplist != NULL) && (!server_shutting_down)) {
503                 RoomProcList *ptr, *cmp;
504                 ptr = RL.rplist;
505                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
506                 while (ptr != NULL && !server_shutting_down) {
507                         
508                         cmp = ptr->next;
509
510                         while (cmp != NULL) {
511                                 if ((cmp->namelen > 0) &&
512                                     (cmp->key == ptr->key) &&
513                                     (cmp->namelen == ptr->namelen) &&
514                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
515                                 {
516                                         cmp->namelen = 0;
517                                 }
518                                 cmp = cmp->next;
519                         }
520
521                         if (ptr->namelen > 0) {
522                                 network_spoolout_room(ptr, 
523                                                       working_ignetcfg,
524                                                       the_netmap);
525                         }
526                         ptr = ptr->next;
527                 }
528         }
529
530         /* If there is anything in the inbound queue, process it */
531         if (!server_shutting_down) {
532                 network_do_spoolin(working_ignetcfg, 
533                                    the_netmap,
534                                    &netmap_changed);
535         }
536
537         /* Free the filter list in memory */
538         free_netfilter_list();
539
540         /* Save the network map back to disk */
541         if (netmap_changed) {
542                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
543                 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
544         }
545
546         /* combine singe message files into one spool entry per remote node. */
547         network_consolidate_spoolout(working_ignetcfg, the_netmap);
548
549         /* shut down. */
550
551         DeleteHash(&the_netmap);
552
553         DeleteHash(&working_ignetcfg);
554
555         QNM_syslog(LOG_DEBUG, "network: queue run completed");
556
557         if (full_processing) {
558                 last_run = time(NULL);
559         }
560         DeleteHash(&RL.RoomsInterestedIn);
561         destroy_network_queue_room(RL.rplist);
562         doing_queue = 0;
563 }
564
565
566
567
568
569
570
571
572 void network_logout_hook(void)
573 {
574         CitContext *CCC = MyContext();
575
576         /*
577          * If we were talking to a network node, we're not anymore...
578          */
579         if (!IsEmptyStr(CCC->net_node)) {
580                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
581                 CCC->net_node[0] = '\0';
582         }
583 }
584 void network_cleanup_function(void)
585 {
586         struct CitContext *CCC = CC;
587
588         if (!IsEmptyStr(CCC->net_node)) {
589                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
590                 CCC->net_node[0] = '\0';
591         }
592 }
593
594
595 /*
596  * Module entry point
597  */
598
599 void SetNetQDebugEnabled(const int n)
600 {
601         NetQDebugEnabled = n;
602 }
603
604 CTDL_MODULE_INIT(network)
605 {
606         if (!threading)
607         {
608                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
609                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
610                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
611                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
612                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
613                 CtdlRegisterRoomHook(network_room_handler);
614                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
615                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
616         }
617         return "network";
618 }