beec9b4f7754a365449820981bc605d34e02aa55
[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         HashList *RoomsInterestedIn;
92 }roomlists;
93 /*
94  * When we do network processing, it's accomplished in two passes; one to
95  * gather a list of rooms and one to actually do them.  It's ok that rplist
96  * is global; we have a mutex that keeps it safe.
97  */
98 struct RoomProcList *rplist = NULL;
99
100 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
101 {
102         DIR *filedir = NULL;
103         struct dirent *d;
104         struct dirent *filedir_entry;
105         long RoomNR;
106         long Count = 0;
107                 
108         filedir = opendir (DirName);
109         if (filedir == NULL) {
110                 return 0;
111         }
112
113         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
114         if (d == NULL) {
115                 return 0;
116         }
117
118         while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
119                (filedir_entry != NULL))
120         {
121                 RoomNR = atol(filedir_entry->d_name);
122                 if (RoomNR != 0) {
123                         Count++;
124                         Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
125                 }
126         }
127         free(d);
128         closedir(filedir);
129         return Count;
130 }
131
132
133
134
135 /*
136  * Check the use table.  This is a list of messages which have recently
137  * arrived on the system.  It is maintained and queried to prevent the same
138  * message from being entered into the database multiple times if it happens
139  * to arrive multiple times by accident.
140  */
141 int network_usetable(struct CtdlMessage *msg)
142 {
143         struct CitContext *CCC = CC;
144         char msgid[SIZ];
145         struct cdbdata *cdbut;
146         struct UseTable ut;
147
148         /* Bail out if we can't generate a message ID */
149         if (msg == NULL) {
150                 return(0);
151         }
152         if (msg->cm_fields['I'] == NULL) {
153                 return(0);
154         }
155         if (IsEmptyStr(msg->cm_fields['I'])) {
156                 return(0);
157         }
158
159         /* Generate the message ID */
160         strcpy(msgid, msg->cm_fields['I']);
161         if (haschar(msgid, '@') == 0) {
162                 strcat(msgid, "@");
163                 if (msg->cm_fields['N'] != NULL) {
164                         strcat(msgid, msg->cm_fields['N']);
165                 }
166                 else {
167                         return(0);
168                 }
169         }
170
171         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
172         if (cdbut != NULL) {
173                 cdb_free(cdbut);
174                 QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
175                 return(1);
176         }
177
178         /* If we got to this point, it's unique: add it. */
179         strcpy(ut.ut_msgid, msgid);
180         ut.ut_timestamp = time(NULL);
181         cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
182         return(0);
183 }
184
185
186
187
188
189
190
191 #if 0
192
193
194 /*
195  * Send the *entire* contents of the current room to one specific network node,
196  * ignoring anything we know about which messages have already undergone
197  * network processing.  This can be used to bring a new node into sync.
198  */
199 int network_sync_to(char *target_node, long len)
200 {
201         struct CitContext *CCC = CC;
202         SpoolControl sc;
203         int num_spooled = 0;
204         int found_node = 0;
205         char buf[256];
206         char sc_type[256];
207         char sc_node[256];
208         char sc_room[256];
209         char filename[PATH_MAX];
210         FILE *fp;
211
212         /* Grab the configuration line we're looking for */
213         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
214         begin_critical_section(S_NETCONFIGS);
215         fp = fopen(filename, "r");
216         if (fp == NULL) {
217                 end_critical_section(S_NETCONFIGS);
218                 return(-1);
219         }
220         while (fgets(buf, sizeof buf, fp) != NULL)
221         {
222                 buf[strlen(buf)-1] = 0;
223
224                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
225                 if (strcasecmp(sc_type, "ignet_push_share"))
226                         continue;
227
228                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
229                 if (strcasecmp(sc_node, target_node))
230                         continue;
231
232                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
233                 found_node = 1;
234                         
235                 /* Concise syntax because we don't need a full linked-list */
236                 memset(&sc, 0, sizeof(SpoolControl));
237                 sc.ignet_push_shares = (maplist *)
238                         malloc(sizeof(maplist));
239                 sc.ignet_push_shares->next = NULL;
240                 safestrncpy(sc.ignet_push_shares->remote_nodename,
241                             sc_node,
242                             sizeof sc.ignet_push_shares->remote_nodename);
243                 safestrncpy(sc.ignet_push_shares->remote_roomname,
244                             sc_room,
245                             sizeof sc.ignet_push_shares->remote_roomname);
246         }
247         fclose(fp);
248         end_critical_section(S_NETCONFIGS);
249
250         if (!found_node) {
251                 free(sc.ignet_push_shares);
252                 return(-1);
253         }
254
255         sc.working_ignetcfg = load_ignetcfg();
256         sc.the_netmap = CtdlReadNetworkMap();
257
258         /* Send ALL messages */
259         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
260                 network_spool_msg, &sc);
261
262         /* Concise cleanup because we know there's only one node in the sc */
263         free(sc.ignet_push_shares);
264
265         DeleteHash(&sc.working_ignetcfg);
266         DeleteHash(&sc.the_netmap);
267
268         QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
269                   num_spooled, target_node);
270         return(num_spooled);
271 }
272
273 #endif
274
275
276 /*
277  * Implements the NSYN command
278  */
279 void cmd_nsyn(char *argbuf) {
280         int num_spooled;
281         long len;
282         char target_node[256];
283
284         if (CtdlAccessCheck(ac_aide)) return;
285
286         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
287         ///// TODO num_spooled = network_sync_to(target_node, len);
288         if (num_spooled >= 0) {
289                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
290         }
291         else {
292                 cprintf("%d No such room/node share exists.\n",
293                         ERROR + ROOM_NOT_FOUND);
294         }
295 }
296
297
298
299 /*
300  * Batch up and send all outbound traffic from the current room
301  */
302 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
303         int i;
304         struct RoomProcList *ptr;
305         long QRNum = qrbuf->QRnumber;
306         void *v;
307         roomlists *RP = (roomlists*) data;
308
309         if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
310                 return;
311
312         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
313         if (ptr == NULL) return;
314
315         ptr->namelen = strlen(qrbuf->QRname);
316         if (ptr->namelen > ROOMNAMELEN)
317                 ptr->namelen = ROOMNAMELEN - 1;
318
319         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
320         ptr->name[ptr->namelen] = '\0';
321         ptr->QRNum = qrbuf->QRnumber;
322
323         for (i = 0; i < ptr->namelen; i++)
324         {
325                 ptr->lcname[i] = tolower(ptr->name[i]);
326         }
327
328         ptr->lcname[ptr->namelen] = '\0';
329         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
330         ptr->next = RP->rplist;
331         RP->rplist = ptr;
332 }
333
334 /*
335  * Batch up and send all outbound traffic from the current room
336  */
337 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
338         int i;
339         struct RoomProcList *ptr;
340
341         if (qrbuf->QRdefaultview == VIEW_QUEUE)
342                 return;
343         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
344         if (ptr == NULL) return;
345
346         ptr->namelen = strlen(qrbuf->QRname);
347         if (ptr->namelen > ROOMNAMELEN)
348                 ptr->namelen = ROOMNAMELEN - 1;
349
350         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
351         ptr->name[ptr->namelen] = '\0';
352         ptr->QRNum = qrbuf->QRnumber;
353
354         for (i = 0; i < ptr->namelen; i++)
355         {
356                 ptr->lcname[i] = tolower(ptr->name[i]);
357         }
358         ptr->lcname[ptr->namelen] = '\0';
359         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
360
361         begin_critical_section(S_RPLIST);
362         ptr->next = rplist;
363         rplist = ptr;
364         end_critical_section(S_RPLIST);
365 }
366
367 void destroy_network_queue_room(RoomProcList *rplist)
368 {
369         struct RoomProcList *cur, *p;
370
371         cur = rplist;
372         while (cur != NULL)
373         {
374                 p = cur->next;
375                 free (cur);
376                 cur = p;                
377         }
378 }
379
380 void destroy_network_queue_room_locked (void)
381 {
382         begin_critical_section(S_RPLIST);
383         destroy_network_queue_room(rplist);
384         end_critical_section(S_RPLIST);
385 }
386
387
388
389 /*
390  * Bounce a message back to the sender
391  */
392 void network_bounce(struct CtdlMessage *msg, char *reason)
393 {
394         struct CitContext *CCC = CC;
395         char *oldpath = NULL;
396         char buf[SIZ];
397         char bouncesource[SIZ];
398         char recipient[SIZ];
399         struct recptypes *valid = NULL;
400         char force_room[ROOMNAMELEN];
401         static int serialnum = 0;
402         size_t size;
403
404         QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
405
406         if (msg == NULL) return;
407
408         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
409
410         /* 
411          * Give it a fresh message ID
412          */
413         if (msg->cm_fields['I'] != NULL) {
414                 free(msg->cm_fields['I']);
415         }
416         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
417                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
418         msg->cm_fields['I'] = strdup(buf);
419
420         /*
421          * FIXME ... right now we're just sending a bounce; we really want to
422          * include the text of the bounced message.
423          */
424         if (msg->cm_fields['M'] != NULL) {
425                 free(msg->cm_fields['M']);
426         }
427         msg->cm_fields['M'] = strdup(reason);
428         msg->cm_format_type = 0;
429
430         /*
431          * Turn the message around
432          */
433         if (msg->cm_fields['R'] == NULL) {
434                 free(msg->cm_fields['R']);
435         }
436
437         if (msg->cm_fields['D'] == NULL) {
438                 free(msg->cm_fields['D']);
439         }
440
441         snprintf(recipient, sizeof recipient, "%s@%s",
442                 msg->cm_fields['A'], msg->cm_fields['N']);
443
444         if (msg->cm_fields['A'] == NULL) {
445                 free(msg->cm_fields['A']);
446         }
447
448         if (msg->cm_fields['N'] == NULL) {
449                 free(msg->cm_fields['N']);
450         }
451
452         if (msg->cm_fields['U'] == NULL) {
453                 free(msg->cm_fields['U']);
454         }
455
456         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
457         msg->cm_fields['N'] = strdup(config.c_nodename);
458         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
459
460         /* prepend our node to the path */
461         if (msg->cm_fields['P'] != NULL) {
462                 oldpath = msg->cm_fields['P'];
463                 msg->cm_fields['P'] = NULL;
464         }
465         else {
466                 oldpath = strdup("unknown_user");
467         }
468         size = strlen(oldpath) + SIZ;
469         msg->cm_fields['P'] = malloc(size);
470         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
471         free(oldpath);
472
473         /* Now submit the message */
474         valid = validate_recipients(recipient, NULL, 0);
475         if (valid != NULL) if (valid->num_error != 0) {
476                 free_recipients(valid);
477                 valid = NULL;
478         }
479         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
480                 strcpy(force_room, config.c_aideroom);
481         }
482         else {
483                 strcpy(force_room, "");
484         }
485         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
486                 strcpy(force_room, config.c_aideroom);
487         }
488         CtdlSubmitMsg(msg, valid, force_room, 0);
489
490         /* Clean up */
491         if (valid != NULL) free_recipients(valid);
492         CtdlFreeMessage(msg);
493         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
494 }
495
496
497
498
499
500
501
502 /*
503  * network_do_queue()
504  * 
505  * Run through the rooms doing various types of network stuff.
506  */
507 void network_do_queue(void)
508 {
509         struct CitContext *CCC = CC;
510         static int doing_queue = 0;
511         static time_t last_run = 0L;
512         int full_processing = 1;
513         HashList *working_ignetcfg;
514         HashList *the_netmap = NULL;
515         int netmap_changed = 0;
516         roomlists RL;
517
518         /*
519          * Run the full set of processing tasks no more frequently
520          * than once every n seconds
521          */
522         if ( (time(NULL) - last_run) < config.c_net_freq ) {
523                 full_processing = 0;
524                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
525                        config.c_net_freq - (time(NULL)- last_run)
526                 );
527         }
528
529         /*
530          * This is a simple concurrency check to make sure only one queue run
531          * is done at a time.  We could do this with a mutex, but since we
532          * don't really require extremely fine granularity here, we'll do it
533          * with a static variable instead.
534          */
535         if (doing_queue) {
536                 return;
537         }
538         doing_queue = 1;
539
540         become_session(&networker_spool_CC);
541         begin_critical_section(S_RPLIST);
542         RL.rplist = rplist;
543         rplist = NULL;
544         end_critical_section(S_RPLIST);
545
546         RL.RoomsInterestedIn = NewHash(1, lFlathash);
547         if (full_processing &&
548             (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
549         {
550                 doing_queue = 0;
551                 DeleteHash(&RL.RoomsInterestedIn);
552                 if (RL.rplist == NULL)
553                         return;
554         }
555         /* Load the IGnet Configuration into memory */
556         working_ignetcfg = CtdlLoadIgNetCfg();
557
558         /*
559          * Load the network map and filter list into memory.
560          */
561         if (!server_shutting_down)
562                 the_netmap = CtdlReadNetworkMap();
563         if (!server_shutting_down)
564                 load_network_filter_list();
565
566         /* 
567          * Go ahead and run the queue
568          */
569         if (full_processing && !server_shutting_down) {
570                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
571                 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
572         }
573
574         if ((RL.rplist != NULL) && (!server_shutting_down)) {
575                 RoomProcList *ptr, *cmp;
576                 ptr = RL.rplist;
577                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
578                 while (ptr != NULL && !server_shutting_down) {
579                         
580                         cmp = ptr->next;
581
582                         while (cmp != NULL) {
583                                 if ((cmp->namelen > 0) &&
584                                     (cmp->key == ptr->key) &&
585                                     (cmp->namelen == ptr->namelen) &&
586                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
587                                 {
588                                         cmp->namelen = 0;
589                                 }
590                                 cmp = cmp->next;
591                         }
592
593                         if (ptr->namelen > 0) {
594                                 network_spoolout_room(ptr, 
595                                                       working_ignetcfg,
596                                                       the_netmap);
597                         }
598                         ptr = ptr->next;
599                 }
600         }
601
602         /* If there is anything in the inbound queue, process it */
603         if (!server_shutting_down) {
604                 network_do_spoolin(working_ignetcfg, 
605                                    the_netmap,
606                                    &netmap_changed);
607         }
608
609         /* Free the filter list in memory */
610         free_netfilter_list();
611
612         /* Save the network map back to disk */
613         if (netmap_changed) {
614                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
615                 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
616         }
617
618         /* combine singe message files into one spool entry per remote node. */
619         network_consolidate_spoolout(working_ignetcfg, the_netmap);
620
621         /* shut down. */
622
623         DeleteHash(&the_netmap);
624
625         DeleteHash(&working_ignetcfg);
626
627         QNM_syslog(LOG_DEBUG, "network: queue run completed");
628
629         if (full_processing) {
630                 last_run = time(NULL);
631         }
632         DeleteHash(&RL.RoomsInterestedIn);
633         destroy_network_queue_room(RL.rplist);
634         doing_queue = 0;
635 }
636
637
638
639
640 int network_room_handler (struct ctdlroom *room)
641 {
642         network_queue_room(room, NULL);
643         return 0;
644 }
645
646
647
648
649 void network_logout_hook(void)
650 {
651         CitContext *CCC = MyContext();
652
653         /*
654          * If we were talking to a network node, we're not anymore...
655          */
656         if (!IsEmptyStr(CCC->net_node)) {
657                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
658                 CCC->net_node[0] = '\0';
659         }
660 }
661 void network_cleanup_function(void)
662 {
663         struct CitContext *CCC = CC;
664
665         if (!IsEmptyStr(CCC->net_node)) {
666                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
667                 CCC->net_node[0] = '\0';
668         }
669 }
670
671
672 /*
673  * Module entry point
674  */
675
676 void SetNetQDebugEnabled(const int n)
677 {
678         NetQDebugEnabled = n;
679 }
680
681 CTDL_MODULE_INIT(network)
682 {
683         if (!threading)
684         {
685                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
686                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
687                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
688                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
689                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
690                 CtdlRegisterRoomHook(network_room_handler);
691                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
692                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
693         }
694         return "network";
695 }