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