65645d9abe89b8b2e3ca50ad6ec0788de74276b4
[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 }roomlists;
92 /*
93  * When we do network processing, it's accomplished in two passes; one to
94  * gather a list of rooms and one to actually do them.  It's ok that rplist
95  * is global; we have a mutex that keeps it safe.
96  */
97 struct RoomProcList *rplist = NULL;
98
99
100
101 /*
102  * Check the use table.  This is a list of messages which have recently
103  * arrived on the system.  It is maintained and queried to prevent the same
104  * message from being entered into the database multiple times if it happens
105  * to arrive multiple times by accident.
106  */
107 int network_usetable(struct CtdlMessage *msg)
108 {
109         struct CitContext *CCC = CC;
110         char msgid[SIZ];
111         struct cdbdata *cdbut;
112         struct UseTable ut;
113
114         /* Bail out if we can't generate a message ID */
115         if (msg == NULL) {
116                 return(0);
117         }
118         if (msg->cm_fields['I'] == NULL) {
119                 return(0);
120         }
121         if (IsEmptyStr(msg->cm_fields['I'])) {
122                 return(0);
123         }
124
125         /* Generate the message ID */
126         strcpy(msgid, msg->cm_fields['I']);
127         if (haschar(msgid, '@') == 0) {
128                 strcat(msgid, "@");
129                 if (msg->cm_fields['N'] != NULL) {
130                         strcat(msgid, msg->cm_fields['N']);
131                 }
132                 else {
133                         return(0);
134                 }
135         }
136
137         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
138         if (cdbut != NULL) {
139                 cdb_free(cdbut);
140                 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
141                 return(1);
142         }
143
144         /* If we got to this point, it's unique: add it. */
145         strcpy(ut.ut_msgid, msgid);
146         ut.ut_timestamp = time(NULL);
147         cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
148         return(0);
149 }
150
151
152
153 /*
154  * Send the *entire* contents of the current room to one specific network node,
155  * ignoring anything we know about which messages have already undergone
156  * network processing.  This can be used to bring a new node into sync.
157  */
158 int network_sync_to(char *target_node, long len)
159 {
160         struct CitContext *CCC = CC;
161         OneRoomNetCfg OneRNCFG;
162         OneRoomNetCfg *pRNCFG;
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         pRNCFG = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
170         if ((pRNCFG == NULL) ||
171             (pRNCFG->NetConfigs[ignet_push_share] == NULL))
172         {
173                 return -1;
174         }
175
176         pCfgLine = pRNCFG->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         memset(&OneRNCFG, 0, sizeof(OneRoomNetCfg));
189         sc.RNCfg = &OneRNCFG;
190         sc.RNCfg->NetConfigs[ignet_push_share] = DuplicateOneGenericCfgLine(pCfgLine);
191
192         end_critical_section(S_NETCONFIGS);
193
194         sc.working_ignetcfg = CtdlLoadIgNetCfg();
195         sc.the_netmap = CtdlReadNetworkMap();
196
197         /* Send ALL messages */
198         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
199                 network_spool_msg, &sc);
200
201         /* Concise cleanup because we know there's only one node in the sc */
202         DeleteGenericCfgLine(NULL/*TODO*/, &sc.RNCfg->NetConfigs[ignet_push_share]);
203
204         DeleteHash(&sc.working_ignetcfg);
205         DeleteHash(&sc.the_netmap);
206
207         QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
208                   num_spooled, target_node);
209         return(num_spooled);
210 }
211
212
213 /*
214  * Implements the NSYN command
215  */
216 void cmd_nsyn(char *argbuf) {
217         int num_spooled;
218         long len;
219         char target_node[256];
220
221         if (CtdlAccessCheck(ac_aide)) return;
222
223         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
224         num_spooled = network_sync_to(target_node, len);
225         if (num_spooled >= 0) {
226                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
227         }
228         else {
229                 cprintf("%d No such room/node share exists.\n",
230                         ERROR + ROOM_NOT_FOUND);
231         }
232 }
233
234 RoomProcList *CreateRoomProcListEntry(struct ctdlroom *qrbuf, const OneRoomNetCfg *OneRNCFG)
235 {
236         int i;
237         struct RoomProcList *ptr;
238
239         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
240         if (ptr == NULL) return NULL;
241
242         ptr->namelen = strlen(qrbuf->QRname);
243         if (ptr->namelen > ROOMNAMELEN)
244                 ptr->namelen = ROOMNAMELEN - 1;
245
246         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
247         ptr->name[ptr->namelen] = '\0';
248         ptr->QRNum = qrbuf->QRnumber;
249
250         for (i = 0; i < ptr->namelen; i++)
251         {
252                 ptr->lcname[i] = tolower(ptr->name[i]);
253         }
254
255         ptr->lcname[ptr->namelen] = '\0';
256         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
257         ptr->OneRNCfg = OneRNCFG;
258         return ptr;
259 }
260
261 /*
262  * Batch up and send all outbound traffic from the current room
263  */
264 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data, const OneRoomNetCfg *OneRNCfg)
265 {
266         struct RoomProcList *ptr;
267         roomlists *RP = (roomlists*) data;
268
269         ptr = CreateRoomProcListEntry(qrbuf, OneRNCfg);
270
271         ptr->next = RP->rplist;
272         RP->rplist = ptr;
273 }
274
275 /*
276  * Batch up and send all outbound traffic from the current room
277  */
278 int network_room_handler (struct ctdlroom *qrbuf)
279 {
280         struct RoomProcList *ptr;
281         const OneRoomNetCfg* RNCfg;
282
283         if (qrbuf->QRdefaultview == VIEW_QUEUE)
284                 return 1;
285
286         RNCfg = CtdlGetNetCfgForRoom(qrbuf->QRnumber);
287         if (RNCfg == NULL)
288                 return 1;
289
290         ptr = CreateRoomProcListEntry(qrbuf, RNCfg);
291         if (ptr == NULL)
292                 return 1;
293
294         begin_critical_section(S_RPLIST);
295         ptr->next = rplist;
296         rplist = ptr;
297         end_critical_section(S_RPLIST);
298         return 1;
299 }
300
301 void destroy_network_queue_room(RoomProcList *rplist)
302 {
303         struct RoomProcList *cur, *p;
304
305         cur = rplist;
306         while (cur != NULL)
307         {
308                 p = cur->next;
309                 free (cur);
310                 cur = p;                
311         }
312 }
313
314 void destroy_network_queue_room_locked (void)
315 {
316         begin_critical_section(S_RPLIST);
317         destroy_network_queue_room(rplist);
318         end_critical_section(S_RPLIST);
319 }
320
321
322
323 /*
324  * Bounce a message back to the sender
325  */
326 void network_bounce(struct CtdlMessage *msg, char *reason)
327 {
328         struct CitContext *CCC = CC;
329         char *oldpath = NULL;
330         char buf[SIZ];
331         char bouncesource[SIZ];
332         char recipient[SIZ];
333         struct recptypes *valid = NULL;
334         char force_room[ROOMNAMELEN];
335         static int serialnum = 0;
336         size_t size;
337
338         QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
339
340         if (msg == NULL) return;
341
342         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
343
344         /* 
345          * Give it a fresh message ID
346          */
347         if (msg->cm_fields['I'] != NULL) {
348                 free(msg->cm_fields['I']);
349         }
350         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
351                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
352         msg->cm_fields['I'] = strdup(buf);
353
354         /*
355          * FIXME ... right now we're just sending a bounce; we really want to
356          * include the text of the bounced message.
357          */
358         if (msg->cm_fields['M'] != NULL) {
359                 free(msg->cm_fields['M']);
360         }
361         msg->cm_fields['M'] = strdup(reason);
362         msg->cm_format_type = 0;
363
364         /*
365          * Turn the message around
366          */
367         if (msg->cm_fields['R'] == NULL) {
368                 free(msg->cm_fields['R']);
369         }
370
371         if (msg->cm_fields['D'] == NULL) {
372                 free(msg->cm_fields['D']);
373         }
374
375         snprintf(recipient, sizeof recipient, "%s@%s",
376                 msg->cm_fields['A'], msg->cm_fields['N']);
377
378         if (msg->cm_fields['A'] == NULL) {
379                 free(msg->cm_fields['A']);
380         }
381
382         if (msg->cm_fields['N'] == NULL) {
383                 free(msg->cm_fields['N']);
384         }
385
386         if (msg->cm_fields['U'] == NULL) {
387                 free(msg->cm_fields['U']);
388         }
389
390         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
391         msg->cm_fields['N'] = strdup(config.c_nodename);
392         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
393
394         /* prepend our node to the path */
395         if (msg->cm_fields['P'] != NULL) {
396                 oldpath = msg->cm_fields['P'];
397                 msg->cm_fields['P'] = NULL;
398         }
399         else {
400                 oldpath = strdup("unknown_user");
401         }
402         size = strlen(oldpath) + SIZ;
403         msg->cm_fields['P'] = malloc(size);
404         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
405         free(oldpath);
406
407         /* Now submit the message */
408         valid = validate_recipients(recipient, NULL, 0);
409         if (valid != NULL) if (valid->num_error != 0) {
410                 free_recipients(valid);
411                 valid = NULL;
412         }
413         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
414                 strcpy(force_room, config.c_aideroom);
415         }
416         else {
417                 strcpy(force_room, "");
418         }
419         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
420                 strcpy(force_room, config.c_aideroom);
421         }
422         CtdlSubmitMsg(msg, valid, force_room, 0);
423
424         /* Clean up */
425         if (valid != NULL) free_recipients(valid);
426         CtdlFreeMessage(msg);
427         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
428 }
429
430
431
432
433
434
435
436 /*
437  * network_do_queue()
438  * 
439  * Run through the rooms doing various types of network stuff.
440  */
441 void network_do_queue(void)
442 {
443         struct CitContext *CCC = CC;
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         become_session(&networker_spool_CC);
463         begin_critical_section(S_RPLIST);
464         RL.rplist = rplist;
465         rplist = NULL;
466         end_critical_section(S_RPLIST);
467 ///TODO hm, check whether we have a config at all here?
468         /* Load the IGnet Configuration into memory */
469         working_ignetcfg = CtdlLoadIgNetCfg();
470
471         /*
472          * Load the network map and filter list into memory.
473          */
474         if (!server_shutting_down)
475                 the_netmap = CtdlReadNetworkMap();
476 #if 0
477         /* filterlist isn't supported anymore
478         if (!server_shutting_down)
479                 load_network_filter_list();
480         */
481 #endif
482
483         /* 
484          * Go ahead and run the queue
485          */
486         if (full_processing && !server_shutting_down) {
487                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
488                 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
489         }
490
491         if ((RL.rplist != NULL) && (!server_shutting_down)) {
492                 RoomProcList *ptr, *cmp;
493                 ptr = RL.rplist;
494                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
495                 while (ptr != NULL && !server_shutting_down) {
496                         
497                         cmp = ptr->next;
498                         /* filter duplicates from the list... */
499                         while (cmp != NULL) {
500                                 if ((cmp->namelen > 0) &&
501                                     (cmp->key == ptr->key) &&
502                                     (cmp->namelen == ptr->namelen) &&
503                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
504                                 {
505                                         cmp->namelen = 0;
506                                 }
507                                 cmp = cmp->next;
508                         }
509
510                         if (ptr->namelen > 0) {
511                                 network_spoolout_room(ptr, 
512                                                       working_ignetcfg,
513                                                       the_netmap);
514                         }
515                         ptr = ptr->next;
516                 }
517         }
518
519         /* If there is anything in the inbound queue, process it */
520         if (!server_shutting_down) {
521                 network_do_spoolin(working_ignetcfg, 
522                                    the_netmap,
523                                    &netmap_changed);
524         }
525
526         /* Free the filter list in memory */
527         free_netfilter_list();
528
529         /* Save the network map back to disk */
530         if (netmap_changed) {
531                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
532                 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
533         }
534
535         /* combine singe message files into one spool entry per remote node. */
536         network_consolidate_spoolout(working_ignetcfg, the_netmap);
537
538         /* shut down. */
539
540         DeleteHash(&the_netmap);
541
542         DeleteHash(&working_ignetcfg);
543
544         QNM_syslog(LOG_DEBUG, "network: queue run completed");
545
546         if (full_processing) {
547                 last_run = time(NULL);
548         }
549         destroy_network_queue_room(RL.rplist);
550 }
551
552
553
554
555
556
557
558
559 void network_logout_hook(void)
560 {
561         CitContext *CCC = MyContext();
562
563         /*
564          * If we were talking to a network node, we're not anymore...
565          */
566         if (!IsEmptyStr(CCC->net_node)) {
567                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
568                 CCC->net_node[0] = '\0';
569         }
570 }
571 void network_cleanup_function(void)
572 {
573         struct CitContext *CCC = CC;
574
575         if (!IsEmptyStr(CCC->net_node)) {
576                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
577                 CCC->net_node[0] = '\0';
578         }
579 }
580
581
582 /*
583  * Module entry point
584  */
585
586 void SetNetQDebugEnabled(const int n)
587 {
588         NetQDebugEnabled = n;
589 }
590
591 CTDL_MODULE_INIT(network)
592 {
593         if (!threading)
594         {
595                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
596                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
597                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
598                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
599                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
600                 CtdlRegisterRoomHook(network_room_handler);
601                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
602                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
603         }
604         return "network";
605 }