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