58d2094afc13cedaf8de96e4f0f7928c7a7bdd13
[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-2015 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 "citadel_dirs.h"
76 #include "threads.h"
77 #include "context.h"
78 #include "ctdl_module.h"
79 #include "netspool.h"
80 #include "netmail.h"
81
82 int NetQDebugEnabled = 0;
83 struct CitContext networker_spool_CC;
84
85 /* comes from lookup3.c from libcitadel... */
86 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
87
88 typedef struct __roomlists {
89         RoomProcList *rplist;
90 }roomlists;
91 /*
92  * When we do network processing, it's accomplished in two passes; one to
93  * gather a list of rooms and one to actually do them.  It's ok that rplist
94  * is global; we have a mutex that keeps it safe.
95  */
96 struct RoomProcList *rplist = NULL;
97
98
99
100 /*
101  * Check the use table.  This is a list of messages which have recently
102  * arrived on the system.  It is maintained and queried to prevent the same
103  * message from being entered into the database multiple times if it happens
104  * to arrive multiple times by accident.
105  */
106 int network_usetable(struct CtdlMessage *msg)
107 {
108         StrBuf *msgid;
109         struct CitContext *CCC = CC;
110         time_t now;
111
112         /* Bail out if we can't generate a message ID */
113         if ((msg == NULL) || CM_IsEmpty(msg, emessageId))
114         {
115                 return(0);
116         }
117
118         /* Generate the message ID */
119         msgid = NewStrBufPlain(CM_KEY(msg, emessageId));
120         if (haschar(ChrPtr(msgid), '@') == 0) {
121                 StrBufAppendBufPlain(msgid, HKEY("@"), 0);
122                 if (!CM_IsEmpty(msg, eNodeName)) {
123                         StrBufAppendBufPlain(msgid, CM_KEY(msg, eNodeName), 0);
124                 }
125                 else {
126                         FreeStrBuf(&msgid);
127                         return(0);
128                 }
129         }
130         now = time(NULL);
131         if (CheckIfAlreadySeen("Networker Import",
132                                msgid,
133                                now, 0,
134                                eCheckUpdate,
135                                CCC->cs_pid, 0) != 0)
136         {
137                 FreeStrBuf(&msgid);
138                 return(1);
139         }
140         FreeStrBuf(&msgid);
141
142         return(0);
143 }
144
145
146
147 /*
148  * Send the *entire* contents of the current room to one specific network node,
149  * ignoring anything we know about which messages have already undergone
150  * network processing.  This can be used to bring a new node into sync.
151  */
152 int network_sync_to(char *target_node, long len)
153 {
154         struct CitContext *CCC = CC;
155         OneRoomNetCfg OneRNCFG;
156         OneRoomNetCfg *pRNCFG;
157         const RoomNetCfgLine *pCfgLine;
158         SpoolControl sc;
159         int num_spooled = 0;
160
161         /* Grab the configuration line we're looking for */
162         begin_critical_section(S_NETCONFIGS);
163         pRNCFG = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
164         if ((pRNCFG == NULL) ||
165             (pRNCFG->NetConfigs[ignet_push_share] == NULL))
166         {
167                 return -1;
168         }
169
170         pCfgLine = pRNCFG->NetConfigs[ignet_push_share];
171         while (pCfgLine != NULL)
172         {
173                 if (!strcmp(ChrPtr(pCfgLine->Value[0]), target_node))
174                         break;
175                 pCfgLine = pCfgLine->next;
176         }
177         if (pCfgLine == NULL)
178         {
179                 return -1;
180         }
181
182         memset(&sc, 0, sizeof(SpoolControl));
183         memset(&OneRNCFG, 0, sizeof(OneRoomNetCfg));
184         sc.RNCfg = &OneRNCFG;
185         sc.RNCfg->NetConfigs[ignet_push_share] = DuplicateOneGenericCfgLine(pCfgLine);
186         sc.Users[ignet_push_share] = NewStrBufPlain(NULL,
187                                                     StrLength(pCfgLine->Value[0]) +
188                                                     StrLength(pCfgLine->Value[1]) + 10);
189         StrBufAppendBuf(sc.Users[ignet_push_share], 
190                         pCfgLine->Value[0],
191                         0);
192         StrBufAppendBufPlain(sc.Users[ignet_push_share], 
193                              HKEY(","),
194                              0);
195
196         StrBufAppendBuf(sc.Users[ignet_push_share], 
197                         pCfgLine->Value[1],
198                         0);
199         CalcListID(&sc);
200
201         end_critical_section(S_NETCONFIGS);
202
203         sc.working_ignetcfg = CtdlLoadIgNetCfg();
204         sc.the_netmap = CtdlReadNetworkMap();
205
206         /* Send ALL messages */
207         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
208                 network_spool_msg, &sc);
209
210         /* Concise cleanup because we know there's only one node in the sc */
211         DeleteGenericCfgLine(NULL/*TODO*/, &sc.RNCfg->NetConfigs[ignet_push_share]);
212
213         DeleteHash(&sc.working_ignetcfg);
214         DeleteHash(&sc.the_netmap);
215         free_spoolcontrol_struct_members(&sc);
216
217         QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
218                   num_spooled, target_node);
219         return(num_spooled);
220 }
221
222
223 /*
224  * Implements the NSYN command
225  */
226 void cmd_nsyn(char *argbuf) {
227         int num_spooled;
228         long len;
229         char target_node[256];
230
231         if (CtdlAccessCheck(ac_aide)) return;
232
233         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
234         num_spooled = network_sync_to(target_node, len);
235         if (num_spooled >= 0) {
236                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
237         }
238         else {
239                 cprintf("%d No such room/node share exists.\n",
240                         ERROR + ROOM_NOT_FOUND);
241         }
242 }
243
244 RoomProcList *CreateRoomProcListEntry(struct ctdlroom *qrbuf, OneRoomNetCfg *OneRNCFG)
245 {
246         int i;
247         struct RoomProcList *ptr;
248
249         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
250         if (ptr == NULL) return NULL;
251
252         ptr->namelen = strlen(qrbuf->QRname);
253         if (ptr->namelen > ROOMNAMELEN)
254                 ptr->namelen = ROOMNAMELEN - 1;
255
256         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
257         ptr->name[ptr->namelen] = '\0';
258         ptr->QRNum = qrbuf->QRnumber;
259
260         for (i = 0; i < ptr->namelen; i++)
261         {
262                 ptr->lcname[i] = tolower(ptr->name[i]);
263         }
264
265         ptr->lcname[ptr->namelen] = '\0';
266         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
267         ptr->lastsent = OneRNCFG->lastsent;
268         ptr->OneRNCfg = OneRNCFG;
269         return ptr;
270 }
271
272 /*
273  * Batch up and send all outbound traffic from the current room
274  */
275 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCfg)
276 {
277         struct RoomProcList *ptr;
278         roomlists *RP = (roomlists*) data;
279
280         if (!HaveSpoolConfig(OneRNCfg))
281                 return;
282
283         ptr = CreateRoomProcListEntry(qrbuf, OneRNCfg);
284
285         if (ptr != NULL)
286         {
287                 ptr->next = RP->rplist;
288                 RP->rplist = ptr;
289         }
290 }
291
292 /*
293  * Batch up and send all outbound traffic from the current room
294  */
295 int network_room_handler (struct ctdlroom *qrbuf)
296 {
297         struct RoomProcList *ptr;
298         OneRoomNetCfg* RNCfg;
299
300         if (qrbuf->QRdefaultview == VIEW_QUEUE)
301                 return 1;
302
303         RNCfg = CtdlGetNetCfgForRoom(qrbuf->QRnumber);
304         if (RNCfg == NULL)
305                 return 1;
306
307         if (!HaveSpoolConfig(RNCfg))
308                 return 1;
309
310         ptr = CreateRoomProcListEntry(qrbuf, RNCfg);
311         if (ptr == NULL)
312                 return 1;
313
314         ptr->OneRNCfg = NULL;
315         begin_critical_section(S_RPLIST);
316         ptr->next = rplist;
317         rplist = ptr;
318         end_critical_section(S_RPLIST);
319         return 1;
320 }
321
322 void destroy_network_queue_room(RoomProcList *rplist)
323 {
324         struct RoomProcList *cur, *p;
325
326         cur = rplist;
327         while (cur != NULL)
328         {
329                 p = cur->next;
330                 free (cur);
331                 cur = p;                
332         }
333 }
334
335 void destroy_network_queue_room_locked (void)
336 {
337         begin_critical_section(S_RPLIST);
338         destroy_network_queue_room(rplist);
339         end_critical_section(S_RPLIST);
340 }
341
342
343
344 /*
345  * Bounce a message back to the sender
346  */
347 void network_bounce(struct CtdlMessage *msg, char *reason)
348 {
349         struct CitContext *CCC = CC;
350         char buf[SIZ];
351         char bouncesource[SIZ];
352         char recipient[SIZ];
353         recptypes *valid = NULL;
354         char force_room[ROOMNAMELEN];
355         static int serialnum = 0;
356         long len;
357
358         QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
359
360         if (msg == NULL) return;
361
362         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, CtdlGetConfigStr("c_nodename"));
363
364         /* 
365          * Give it a fresh message ID
366          */
367         len = snprintf(buf, sizeof(buf),
368                        "%ld.%04lx.%04x@%s",
369                        (long)time(NULL),
370                        (long)getpid(),
371                        ++serialnum,
372                        CtdlGetConfigStr("c_fqdn")
373         );
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, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("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         {
408                 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
409         }
410         else {
411                 strcpy(force_room, "");
412         }
413         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
414                 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
415         }
416         CtdlSubmitMsg(msg, valid, force_room, 0);
417
418         /* Clean up */
419         if (valid != NULL) free_recipients(valid);
420         CM_Free(msg);
421         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
422 }
423
424
425
426 /*
427  * network_do_queue()
428  * 
429  * Run through the rooms doing various types of network stuff.
430  */
431 void network_do_queue(void)
432 {
433         struct CitContext *CCC = CC;
434         static time_t last_run = 0L;
435         int full_processing = 1;
436         HashList *working_ignetcfg;
437         HashList *the_netmap = NULL;
438         int netmap_changed = 0;
439         roomlists RL;
440         SpoolControl *sc = NULL;
441         SpoolControl *pSC;
442
443         /*
444          * Run the full set of processing tasks no more frequently
445          * than once every n seconds
446          */
447         if ( (time(NULL) - last_run) < CtdlGetConfigLong("c_net_freq") )
448         {
449                 full_processing = 0;
450                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
451                        CtdlGetConfigLong("c_net_freq") - (time(NULL)- last_run)
452                 );
453         }
454
455         become_session(&networker_spool_CC);
456         begin_critical_section(S_RPLIST);
457         RL.rplist = rplist;
458         rplist = NULL;
459         end_critical_section(S_RPLIST);
460 ///TODO hm, check whether we have a config at all here?
461         /* Load the IGnet Configuration into memory */
462         working_ignetcfg = CtdlLoadIgNetCfg();
463
464         /*
465          * Load the network map and filter list into memory.
466          */
467         if (!server_shutting_down)
468                 the_netmap = CtdlReadNetworkMap();
469 #if 0
470         /* filterlist isn't supported anymore
471         if (!server_shutting_down)
472                 load_network_filter_list();
473         */
474 #endif
475
476         /* 
477          * Go ahead and run the queue
478          */
479         if (full_processing && !server_shutting_down) {
480                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
481                 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
482         }
483
484         if ((RL.rplist != NULL) && (!server_shutting_down)) {
485                 RoomProcList *ptr, *cmp;
486                 ptr = RL.rplist;
487                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
488                 while (ptr != NULL && !server_shutting_down) {
489                         
490                         cmp = ptr->next;
491                         /* filter duplicates from the list... */
492                         while (cmp != NULL) {
493                                 if ((cmp->namelen > 0) &&
494                                     (cmp->key == ptr->key) &&
495                                     (cmp->namelen == ptr->namelen) &&
496                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
497                                 {
498                                         cmp->namelen = 0;
499                                 }
500                                 cmp = cmp->next;
501                         }
502
503                         if (ptr->namelen > 0) {
504                                 InspectQueuedRoom(&sc,
505                                                   ptr, 
506                                                   working_ignetcfg,
507                                                   the_netmap);
508                         }
509                         ptr = ptr->next;
510                 }
511         }
512
513
514         pSC = sc;
515         while (pSC != NULL)
516         {
517                 network_spoolout_room(pSC);
518                 pSC = pSC->next;
519         }
520
521         pSC = sc;
522         while (pSC != NULL)
523         {
524                 sc = pSC->next;
525                 free_spoolcontrol_struct(&pSC);
526                 pSC = sc;
527         }
528         /* If there is anything in the inbound queue, process it */
529         if (!server_shutting_down) {
530                 network_do_spoolin(working_ignetcfg, 
531                                    the_netmap,
532                                    &netmap_changed);
533         }
534
535         /* Free the filter list in memory */
536         free_netfilter_list();
537
538         /* Save the network map back to disk */
539         if (netmap_changed) {
540                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
541                 char *pMapStr = SmashStrBuf(&MapStr);
542                 CtdlPutSysConfig(IGNETMAP, pMapStr);
543                 free(pMapStr);
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         destroy_network_queue_room(RL.rplist);
561         SaveChangedConfigs();
562
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 int ignet_aftersave(struct CtdlMessage *msg,
596                     recptypes *recps)   /* recipients (if mail) */
597 {
598         /* For IGnet mail, we have to save a new copy into the spooler for
599          * each recipient, with the R and D fields set to the recipient and
600          * destination-node.  This has two ugly side effects: all other
601          * recipients end up being unlisted in this recipient's copy of the
602          * message, and it has to deliver multiple messages to the same
603          * node.  We'll revisit this again in a year or so when everyone has
604          * a network spool receiver that can handle the new style messages.
605          */
606         if ((recps != NULL) && (recps->num_ignet > 0))
607         {
608                 char *recipient;
609                 int rv = 0;
610                 struct ser_ret smr;
611                 FILE *network_fp = NULL;
612                 char submit_filename[128];
613                 static int seqnum = 1;
614                 int i;
615                 char *hold_R, *hold_D, *RBuf, *DBuf;
616                 long hrlen, hdlen, rblen, dblen, count, rlen;
617                 CitContext *CCC = MyContext();
618
619                 CM_GetAsField(msg, eRecipient, &hold_R, &hrlen);;
620                 CM_GetAsField(msg, eDestination, &hold_D, &hdlen);;
621
622                 count = num_tokens(recps->recp_ignet, '|');
623                 rlen = strlen(recps->recp_ignet);
624                 recipient = malloc(rlen + 1);
625                 RBuf = malloc(rlen + 1);
626                 DBuf = malloc(rlen + 1);
627                 for (i=0; i<count; ++i) {
628                         extract_token(recipient, recps->recp_ignet, i,
629                                       '|', rlen + 1);
630
631                         rblen = extract_token(RBuf, recipient, 0, '@', rlen + 1);
632                         dblen = extract_token(DBuf, recipient, 1, '@', rlen + 1);
633                 
634                         CM_SetAsField(msg, eRecipient, &RBuf, rblen);;
635                         CM_SetAsField(msg, eDestination, &DBuf, dblen);;
636                         CtdlSerializeMessage(&smr, msg);
637                         if (smr.len > 0) {
638                                 snprintf(submit_filename, sizeof submit_filename,
639                                          "%s/netmail.%04lx.%04x.%04x",
640                                          ctdl_netin_dir,
641                                          (long) getpid(),
642                                          CCC->cs_pid,
643                                          ++seqnum);
644
645                                 network_fp = fopen(submit_filename, "wb+");
646                                 if (network_fp != NULL) {
647                                         rv = fwrite(smr.ser, smr.len, 1, network_fp);
648                                         if (rv == -1) {
649                                                 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
650                                                            strerror(errno));
651                                         }
652                                         fclose(network_fp);
653                                 }
654                                 free(smr.ser);
655                         }
656                         CM_GetAsField(msg, eRecipient, &RBuf, &rblen);;
657                         CM_GetAsField(msg, eDestination, &DBuf, &dblen);;
658                 }
659                 free(RBuf);
660                 free(DBuf);
661                 free(recipient);
662                 CM_SetAsField(msg, eRecipient, &hold_R, hrlen);
663                 CM_SetAsField(msg, eDestination, &hold_D, hdlen);
664                 return 1;
665         }
666         return 0;
667 }
668
669 /*
670  * Module entry point
671  */
672
673 void SetNetQDebugEnabled(const int n)
674 {
675         NetQDebugEnabled = n;
676 }
677
678 CTDL_MODULE_INIT(network)
679 {
680         if (!threading)
681         {
682                 CtdlRegisterMessageHook(ignet_aftersave, EVT_AFTERSAVE);
683
684                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
685                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
686                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
687                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
688                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
689                 CtdlRegisterRoomHook(network_room_handler);
690                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
691                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
692         }
693         return "network";
694 }