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