c81f016ab7a66eeb827016668cf1c4f4dc56bdf7
[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-2016 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  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
25  * requests that have not been confirmed will be deleted.
26  */
27 #define EXP     259200  /* three days */
28
29 #include "sysdep.h"
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <ctype.h>
35 #include <signal.h>
36 #include <pwd.h>
37 #include <errno.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <dirent.h>
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
43 # include <time.h>
44 #else
45 # if HAVE_SYS_TIME_H
46 #  include <sys/time.h>
47 # else
48 #  include <time.h>
49 # endif
50 #endif
51 #ifdef HAVE_SYSCALL_H
52 # include <syscall.h>
53 #else 
54 # if HAVE_SYS_SYSCALL_H
55 #  include <sys/syscall.h>
56 # endif
57 #endif
58
59 #include <sys/wait.h>
60 #include <string.h>
61 #include <limits.h>
62 #include <libcitadel.h>
63 #include "citadel.h"
64 #include "server.h"
65 #include "citserver.h"
66 #include "support.h"
67 #include "config.h"
68 #include "user_ops.h"
69 #include "database.h"
70 #include "msgbase.h"
71 #include "internet_addressing.h"
72 #include "serv_network.h"
73 #include "clientsocket.h"
74 #include "citadel_dirs.h"
75 #include "threads.h"
76 #include "context.h"
77 #include "ctdl_module.h"
78 #include "netspool.h"
79 #include "netmail.h"
80
81 int NetQDebugEnabled = 0;
82 struct CitContext networker_spool_CC;
83
84 /* comes from lookup3.c from libcitadel... */
85 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
86
87 typedef struct __roomlists {
88         RoomProcList *rplist;
89 } roomlists;
90
91
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  * Send the *entire* contents of the current room to one specific network node,
102  * ignoring anything we know about which messages have already undergone
103  * network processing.  This can be used to bring a new node into sync.
104  */
105 int network_sync_to(char *target_node, long len)
106 {
107         struct CitContext *CCC = CC;
108         OneRoomNetCfg OneRNCFG;
109         OneRoomNetCfg *pRNCFG;
110         const RoomNetCfgLine *pCfgLine;
111         SpoolControl sc;
112         int num_spooled = 0;
113
114         /* Load the netconfig for this room */
115         pRNCFG = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
116         if (pRNCFG == NULL) {                                   // no netconfig at all?
117                 return -1;
118         }
119         if (pRNCFG->NetConfigs[ignet_push_share] == NULL)       // no ignet push shares?
120         {
121                 FreeRoomNetworkStruct(&pRNCFG);
122                 return -1;
123         }
124
125         /* Search for an ignet_oush_share configuration bearing the target node's name */
126         for (pCfgLine = pRNCFG->NetConfigs[ignet_push_share]; pCfgLine != NULL; pCfgLine = pCfgLine->next)
127         {
128                 if (!strcmp(ChrPtr(pCfgLine->Value[0]), target_node))
129                         break;
130         }
131
132         /* If we aren't sharing with that node, bail out */
133         if (pCfgLine == NULL)
134         {
135                 FreeRoomNetworkStruct(&pRNCFG);
136                 return -1;
137         }
138
139         /* If we got here, we're good to go ... make up a dummy spoolconfig and roll with it */
140
141         begin_critical_section(S_NETCONFIGS);
142         memset(&sc, 0, sizeof(SpoolControl));
143         memset(&OneRNCFG, 0, sizeof(OneRoomNetCfg));
144         sc.RNCfg = &OneRNCFG;
145         sc.RNCfg->NetConfigs[ignet_push_share] = DuplicateOneGenericCfgLine(pCfgLine);
146         sc.Users[ignet_push_share] = NewStrBufPlain(NULL, (StrLength(pCfgLine->Value[0]) + StrLength(pCfgLine->Value[1]) + 10) );
147         StrBufAppendBuf(sc.Users[ignet_push_share], pCfgLine->Value[0], 0);
148         StrBufAppendBufPlain(sc.Users[ignet_push_share], HKEY(","), 0);
149         StrBufAppendBuf(sc.Users[ignet_push_share], pCfgLine->Value[1], 0);
150         CalcListID(&sc);
151         end_critical_section(S_NETCONFIGS);
152
153         sc.working_ignetcfg = CtdlLoadIgNetCfg();
154         sc.the_netmap = CtdlReadNetworkMap();
155
156         /* Send ALL messages */
157         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, network_spool_msg, &sc);
158
159         /* Concise cleanup because we know there's only one node in the sc */
160         DeleteGenericCfgLine(NULL, &sc.RNCfg->NetConfigs[ignet_push_share]);
161
162         DeleteHash(&sc.working_ignetcfg);
163         DeleteHash(&sc.the_netmap);
164         free_spoolcontrol_struct_members(&sc);
165
166         QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>", num_spooled, target_node);
167         return(num_spooled);
168 }
169
170
171 /*
172  * Implements the NSYN command
173  */
174 void cmd_nsyn(char *argbuf) {
175         int num_spooled;
176         long len;
177         char target_node[256];
178
179         if (CtdlAccessCheck(ac_aide)) return;
180
181         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
182         num_spooled = network_sync_to(target_node, len);
183         if (num_spooled >= 0) {
184                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
185         }
186         else {
187                 cprintf("%d No such room/node share exists.\n", ERROR + ROOM_NOT_FOUND);
188         }
189 }
190
191 RoomProcList *CreateRoomProcListEntry(struct ctdlroom *qrbuf, OneRoomNetCfg *OneRNCFG)
192 {
193         int i;
194         struct RoomProcList *ptr;
195
196         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
197         if (ptr == NULL) {
198                 return NULL;
199         }
200
201         ptr->namelen = strlen(qrbuf->QRname);
202         if (ptr->namelen > ROOMNAMELEN) {
203                 ptr->namelen = ROOMNAMELEN - 1;
204         }
205
206         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
207         ptr->name[ptr->namelen] = '\0';
208         ptr->QRNum = qrbuf->QRnumber;
209
210         for (i = 0; i < ptr->namelen; i++)
211         {
212                 ptr->lcname[i] = tolower(ptr->name[i]);
213         }
214
215         ptr->lcname[ptr->namelen] = '\0';
216         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
217         ptr->lastsent = OneRNCFG->lastsent;
218         ptr->OneRNCfg = OneRNCFG;
219         return ptr;
220 }
221
222 /*
223  * Batch up and send all outbound traffic from the current room
224  */
225 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCfg)
226 {
227         struct RoomProcList *ptr;
228         roomlists *RP = (roomlists*) data;
229
230         if (!HaveSpoolConfig(OneRNCfg)) {
231                 return;
232         }
233
234         ptr = CreateRoomProcListEntry(qrbuf, OneRNCfg);
235
236         if (ptr != NULL)
237         {
238                 ptr->next = RP->rplist;
239                 RP->rplist = ptr;
240         }
241 }
242
243 /*
244  * Batch up and send all outbound traffic from the current room
245  */
246 int network_room_handler(struct ctdlroom *qrbuf)
247 {
248         struct RoomProcList *ptr;
249         OneRoomNetCfg *RNCfg;
250
251         if (qrbuf->QRdefaultview == VIEW_QUEUE) {
252                 return 1;
253         }
254
255         RNCfg = CtdlGetNetCfgForRoom(qrbuf->QRnumber);
256         if (RNCfg == NULL) {
257                 return 1;
258         }
259
260         if (!HaveSpoolConfig(RNCfg)) {
261                 FreeRoomNetworkStruct(&RNCfg);
262                 return 1;
263         }
264
265         ptr = CreateRoomProcListEntry(qrbuf, RNCfg);
266         if (ptr == NULL) {
267                 FreeRoomNetworkStruct(&RNCfg);
268                 return 1;
269         }
270
271         ptr->OneRNCfg = NULL;
272         begin_critical_section(S_RPLIST);
273         ptr->next = rplist;
274         rplist = ptr;
275         end_critical_section(S_RPLIST);
276         FreeRoomNetworkStruct(&RNCfg);
277         return 1;
278 }
279
280 void destroy_network_queue_room(RoomProcList *rplist)
281 {
282         struct RoomProcList *cur, *p;
283
284         cur = rplist;
285         while (cur != NULL)
286         {
287                 p = cur->next;
288                 free (cur);
289                 cur = p;                
290         }
291 }
292
293 void destroy_network_queue_room_locked (void)
294 {
295         begin_critical_section(S_RPLIST);
296         destroy_network_queue_room(rplist);
297         end_critical_section(S_RPLIST);
298 }
299
300
301 /*
302  * network_do_queue()
303  * 
304  * Run through the rooms doing various types of network stuff.
305  */
306 void network_do_queue(void)
307 {
308         struct CitContext *CCC = CC;
309         static time_t last_run = 0L;
310         int full_processing = 1;
311         HashList *working_ignetcfg;
312         HashList *the_netmap = NULL;
313         int netmap_changed = 0;
314         roomlists RL;
315         SpoolControl *sc = NULL;
316         SpoolControl *pSC;
317
318         /*
319          * Run the full set of processing tasks no more frequently
320          * than once every n seconds
321          */
322         if ( (time(NULL) - last_run) < CtdlGetConfigLong("c_net_freq") )
323         {
324                 full_processing = 0;
325                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.",
326                        CtdlGetConfigLong("c_net_freq") - (time(NULL)- last_run)
327                 );
328         }
329
330         become_session(&networker_spool_CC);
331         begin_critical_section(S_RPLIST);
332         RL.rplist = rplist;
333         rplist = NULL;
334         end_critical_section(S_RPLIST);
335
336         // TODO hm, check whether we have a config at all here?
337         /* Load the IGnet Configuration into memory */
338         working_ignetcfg = CtdlLoadIgNetCfg();
339
340         /*
341          * Load the network map and filter list into memory.
342          */
343         if (!server_shutting_down) {
344                 the_netmap = CtdlReadNetworkMap();
345         }
346
347         /* 
348          * Go ahead and run the queue
349          */
350         if (full_processing && !server_shutting_down) {
351                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
352                 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
353         }
354
355         if ((RL.rplist != NULL) && (!server_shutting_down)) {
356                 RoomProcList *ptr, *cmp;
357                 ptr = RL.rplist;
358                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
359                 while (ptr != NULL && !server_shutting_down) {
360                         
361                         cmp = ptr->next;
362                         /* filter duplicates from the list... */
363                         while (cmp != NULL) {
364                                 if ((cmp->namelen > 0) &&
365                                     (cmp->key == ptr->key) &&
366                                     (cmp->namelen == ptr->namelen) &&
367                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
368                                 {
369                                         cmp->namelen = 0;
370                                 }
371                                 cmp = cmp->next;
372                         }
373
374                         if (ptr->namelen > 0) {
375                                 InspectQueuedRoom(&sc,
376                                                   ptr, 
377                                                   working_ignetcfg,
378                                                   the_netmap);
379                         }
380                         ptr = ptr->next;
381                 }
382         }
383
384
385         pSC = sc;
386         while (pSC != NULL)
387         {
388                 network_spoolout_room(pSC);
389                 pSC = pSC->next;
390         }
391
392         pSC = sc;
393         while (pSC != NULL)
394         {
395                 sc = pSC->next;
396                 free_spoolcontrol_struct(&pSC);
397                 pSC = sc;
398         }
399         /* If there is anything in the inbound queue, process it */
400         if (!server_shutting_down) {
401                 network_do_spoolin(working_ignetcfg, 
402                                    the_netmap,
403                                    &netmap_changed);
404         }
405
406         /* Free the filter list in memory */
407         free_netfilter_list();
408
409         /* Save the network map back to disk */
410         if (netmap_changed) {
411                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
412                 char *pMapStr = SmashStrBuf(&MapStr);
413                 CtdlPutSysConfig(IGNETMAP, pMapStr);
414                 free(pMapStr);
415         }
416
417         /* combine single message files into one spool entry per remote node. */
418         network_consolidate_spoolout(working_ignetcfg, the_netmap);
419
420         /* shut down. */
421
422         DeleteHash(&the_netmap);
423
424         DeleteHash(&working_ignetcfg);
425
426         QNM_syslog(LOG_DEBUG, "network: queue run completed");
427
428         if (full_processing) {
429                 last_run = time(NULL);
430         }
431         destroy_network_queue_room(RL.rplist);
432 }
433
434
435 void network_logout_hook(void)
436 {
437         CitContext *CCC = MyContext();
438
439         /*
440          * If we were talking to a network node, we're not anymore...
441          */
442         if (!IsEmptyStr(CCC->net_node)) {
443                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
444                 CCC->net_node[0] = '\0';
445         }
446 }
447
448
449 void network_cleanup_function(void)
450 {
451         struct CitContext *CCC = CC;
452
453         if (!IsEmptyStr(CCC->net_node)) {
454                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
455                 CCC->net_node[0] = '\0';
456         }
457 }
458
459
460 int ignet_aftersave(struct CtdlMessage *msg, recptypes *recps)
461 {
462         /* For IGnet mail, we have to save a new copy into the spooler for
463          * each recipient, with the R and D fields set to the recipient and
464          * destination-node.  This has two ugly side effects: all other
465          * recipients end up being unlisted in this recipient's copy of the
466          * message, and it has to deliver multiple messages to the same
467          * node.  We'll revisit this again in a year or so when everyone has
468          * a network spool receiver that can handle the new style messages.
469          */
470         if ((recps != NULL) && (recps->num_ignet > 0))
471         {
472                 char *recipient;
473                 int rv = 0;
474                 struct ser_ret smr;
475                 FILE *network_fp = NULL;
476                 char submit_filename[128];
477                 static int seqnum = 1;
478                 int i;
479                 char *hold_R, *hold_D, *RBuf, *DBuf;
480                 long hrlen, hdlen, rblen, dblen, count, rlen;
481                 CitContext *CCC = MyContext();
482
483                 CM_GetAsField(msg, eRecipient, &hold_R, &hrlen);;
484                 CM_GetAsField(msg, eDestination, &hold_D, &hdlen);;
485
486                 count = num_tokens(recps->recp_ignet, '|');
487                 rlen = strlen(recps->recp_ignet);
488                 recipient = malloc(rlen + 1);
489                 RBuf = malloc(rlen + 1);
490                 DBuf = malloc(rlen + 1);
491                 for (i=0; i<count; ++i) {
492                         extract_token(recipient, recps->recp_ignet, i, '|', rlen + 1);
493
494                         rblen = extract_token(RBuf, recipient, 0, '@', rlen + 1);
495                         dblen = extract_token(DBuf, recipient, 1, '@', rlen + 1);
496                 
497                         CM_SetAsField(msg, eRecipient, &RBuf, rblen);;
498                         CM_SetAsField(msg, eDestination, &DBuf, dblen);;
499                         CtdlSerializeMessage(&smr, msg);
500                         if (smr.len > 0) {
501                                 snprintf(submit_filename, sizeof submit_filename,
502                                          "%s/netmail.%04lx.%04x.%04x",
503                                          ctdl_netin_dir,
504                                          (long) getpid(),
505                                          CCC->cs_pid,
506                                          ++seqnum);
507
508                                 network_fp = fopen(submit_filename, "wb+");
509                                 if (network_fp != NULL) {
510                                         rv = fwrite(smr.ser, smr.len, 1, network_fp);
511                                         if (rv == -1) {
512                                                 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s",
513                                                            strerror(errno));
514                                         }
515                                         fclose(network_fp);
516                                 }
517                                 free(smr.ser);
518                         }
519                         CM_GetAsField(msg, eRecipient, &RBuf, &rblen);;
520                         CM_GetAsField(msg, eDestination, &DBuf, &dblen);;
521                 }
522                 free(RBuf);
523                 free(DBuf);
524                 free(recipient);
525                 CM_SetAsField(msg, eRecipient, &hold_R, hrlen);
526                 CM_SetAsField(msg, eDestination, &hold_D, hdlen);
527                 return 1;
528         }
529         return 0;
530 }
531
532
533 /*
534  * Module entry point
535  */
536
537 void SetNetQDebugEnabled(const int n)
538 {
539         NetQDebugEnabled = n;
540 }
541
542
543 CTDL_MODULE_INIT(network)
544 {
545         if (!threading)
546         {
547                 CtdlRegisterMessageHook(ignet_aftersave, EVT_AFTERSAVE);
548
549                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
550                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
551                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
552                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
553                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
554                 CtdlRegisterRoomHook(network_room_handler);
555                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
556                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
557         }
558         return "network";
559 }