NSYN: adjust to new semantics
[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 as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
22  * This is a fairly high-level type of critical section.  It ensures that no
23  * two threads work on the netconfigs files at the same time.  Since we do
24  * so many things inside these, here are the rules:
25  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26  *  2. Do *not* perform any I/O with the client during these sections.
27  *
28  */
29
30 /*
31  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32  * requests that have not been confirmed will be deleted.
33  */
34 #define EXP     259200  /* three days */
35
36 #include "sysdep.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <stdio.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <signal.h>
43 #include <pwd.h>
44 #include <errno.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <dirent.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58 #ifdef HAVE_SYSCALL_H
59 # include <syscall.h>
60 #else 
61 # if HAVE_SYS_SYSCALL_H
62 #  include <sys/syscall.h>
63 # endif
64 #endif
65
66 #include <sys/wait.h>
67 #include <string.h>
68 #include <limits.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "user_ops.h"
76 #include "database.h"
77 #include "msgbase.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
81 #include "file_ops.h"
82 #include "citadel_dirs.h"
83 #include "threads.h"
84
85 #ifndef HAVE_SNPRINTF
86 #include "snprintf.h"
87 #endif
88
89 #include "context.h"
90 #include "netconfig.h"
91 #include "netspool.h"
92 #include "netmail.h"
93 #include "ctdl_module.h"
94
95 /* comes from lookup3.c from libcitadel... */
96 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
97
98 typedef struct __roomlists {
99         RoomProcList *rplist;
100         HashList *RoomsInterestedIn;
101 }roomlists;
102 /*
103  * When we do network processing, it's accomplished in two passes; one to
104  * gather a list of rooms and one to actually do them.  It's ok that rplist
105  * is global; we have a mutex that keeps it safe.
106  */
107 struct RoomProcList *rplist = NULL;
108
109 int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
110 {
111         DIR *filedir = NULL;
112         struct dirent *d;
113         struct dirent *filedir_entry;
114         long RoomNR;
115         long Count = 0;
116                 
117         filedir = opendir (DirName);
118         if (filedir == NULL) {
119                 return 0;
120         }
121
122         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
123         if (d == NULL) {
124                 return 0;
125         }
126
127         while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
128                (filedir_entry != NULL))
129         {
130                 RoomNR = atol(filedir_entry->d_name);
131                 if (RoomNR != 0) {
132                         Count++;
133                         Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
134                 }
135         }
136         free(d);
137         closedir(filedir);
138         return Count;
139 }
140
141
142
143
144 /*
145  * Check the use table.  This is a list of messages which have recently
146  * arrived on the system.  It is maintained and queried to prevent the same
147  * message from being entered into the database multiple times if it happens
148  * to arrive multiple times by accident.
149  */
150 int network_usetable(struct CtdlMessage *msg) {
151
152         char msgid[SIZ];
153         struct cdbdata *cdbut;
154         struct UseTable ut;
155
156         /* Bail out if we can't generate a message ID */
157         if (msg == NULL) {
158                 return(0);
159         }
160         if (msg->cm_fields['I'] == NULL) {
161                 return(0);
162         }
163         if (IsEmptyStr(msg->cm_fields['I'])) {
164                 return(0);
165         }
166
167         /* Generate the message ID */
168         strcpy(msgid, msg->cm_fields['I']);
169         if (haschar(msgid, '@') == 0) {
170                 strcat(msgid, "@");
171                 if (msg->cm_fields['N'] != NULL) {
172                         strcat(msgid, msg->cm_fields['N']);
173                 }
174                 else {
175                         return(0);
176                 }
177         }
178
179         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
180         if (cdbut != NULL) {
181                 cdb_free(cdbut);
182                 syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
183                 return(1);
184         }
185
186         /* If we got to this point, it's unique: add it. */
187         strcpy(ut.ut_msgid, msgid);
188         ut.ut_timestamp = time(NULL);
189         cdb_store(CDB_USETABLE, msgid, strlen(msgid), &ut, sizeof(struct UseTable) );
190         return(0);
191 }
192
193
194
195
196
197
198
199
200
201
202 /*
203  * Send the *entire* contents of the current room to one specific network node,
204  * ignoring anything we know about which messages have already undergone
205  * network processing.  This can be used to bring a new node into sync.
206  */
207 int network_sync_to(char *target_node, long len)
208 {
209         SpoolControl sc;
210         int num_spooled = 0;
211         int found_node = 0;
212         char buf[256];
213         char sc_type[256];
214         char sc_node[256];
215         char sc_room[256];
216         char filename[PATH_MAX];
217         FILE *fp;
218
219         /* Grab the configuration line we're looking for */
220         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
221         begin_critical_section(S_NETCONFIGS);
222         fp = fopen(filename, "r");
223         if (fp == NULL) {
224                 end_critical_section(S_NETCONFIGS);
225                 return(-1);
226         }
227         while (fgets(buf, sizeof buf, fp) != NULL)
228         {
229                 buf[strlen(buf)-1] = 0;
230
231                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
232                 if (strcasecmp(sc_type, "ignet_push_share"))
233                         continue;
234
235                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
236                 if (!strcasecmp(sc_node, target_node))
237                         continue;
238
239                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
240                 found_node = 1;
241                         
242                 /* Concise syntax because we don't need a full linked-list */
243                 memset(&sc, 0, sizeof(SpoolControl));
244                 sc.ignet_push_shares = (maplist *)
245                         malloc(sizeof(maplist));
246                 sc.ignet_push_shares->next = NULL;
247                 safestrncpy(sc.ignet_push_shares->remote_nodename,
248                             sc_node,
249                             sizeof sc.ignet_push_shares->remote_nodename);
250                 safestrncpy(sc.ignet_push_shares->remote_roomname,
251                             sc_room,
252                             sizeof sc.ignet_push_shares->remote_roomname);
253         }
254         fclose(fp);
255         end_critical_section(S_NETCONFIGS);
256
257         if (!found_node) return(-1);
258
259         sc.working_ignetcfg = load_ignetcfg();
260         sc.the_netmap = read_network_map();
261
262         /* Send ALL messages */
263         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
264                 network_spool_msg, &sc);
265
266         /* Concise cleanup because we know there's only one node in the sc */
267         free(sc.ignet_push_shares);
268
269         DeleteHash(&sc.working_ignetcfg);
270         DeleteHash(&sc.the_netmap);
271
272         syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
273                 num_spooled, target_node);
274         return(num_spooled);
275 }
276
277
278 /*
279  * Implements the NSYN command
280  */
281 void cmd_nsyn(char *argbuf) {
282         int num_spooled;
283         long len;
284         char target_node[256];
285
286         if (CtdlAccessCheck(ac_aide)) return;
287
288         len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
289         num_spooled = network_sync_to(target_node, len);
290         if (num_spooled >= 0) {
291                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
292         }
293         else {
294                 cprintf("%d No such room/node share exists.\n",
295                         ERROR + ROOM_NOT_FOUND);
296         }
297 }
298
299
300
301 /*
302  * Batch up and send all outbound traffic from the current room
303  */
304 void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
305         int i;
306         struct RoomProcList *ptr;
307         long QRNum = qrbuf->QRnumber;
308         void *v;
309         roomlists *RP = (roomlists*) data;
310
311         if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
312                 return;
313
314         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
315         if (ptr == NULL) return;
316
317         ptr->namelen = strlen(qrbuf->QRname);
318         if (ptr->namelen > ROOMNAMELEN)
319                 ptr->namelen = ROOMNAMELEN - 1;
320
321         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
322         ptr->name[ptr->namelen] = '\0';
323         ptr->QRNum = qrbuf->QRnumber;
324
325         for (i = 0; i < ptr->namelen; i++)
326         {
327                 ptr->lcname[i] = tolower(ptr->name[i]);
328         }
329
330         ptr->lcname[ptr->namelen] = '\0';
331         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
332         ptr->next = RP->rplist;
333         RP->rplist = ptr;
334 }
335
336 /*
337  * Batch up and send all outbound traffic from the current room
338  */
339 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
340         int i;
341         struct RoomProcList *ptr;
342
343         if (qrbuf->QRdefaultview == VIEW_QUEUE)
344                 return;
345         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
346         if (ptr == NULL) return;
347
348         ptr->namelen = strlen(qrbuf->QRname);
349         if (ptr->namelen > ROOMNAMELEN)
350                 ptr->namelen = ROOMNAMELEN - 1;
351
352         memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
353         ptr->name[ptr->namelen] = '\0';
354         ptr->QRNum = qrbuf->QRnumber;
355
356         for (i = 0; i < ptr->namelen; i++)
357         {
358                 ptr->lcname[i] = tolower(ptr->name[i]);
359         }
360         ptr->lcname[ptr->namelen] = '\0';
361         ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
362
363         begin_critical_section(S_RPLIST);
364         ptr->next = rplist;
365         rplist = ptr;
366         end_critical_section(S_RPLIST);
367 }
368
369 void destroy_network_queue_room(RoomProcList *rplist)
370 {
371         struct RoomProcList *cur, *p;
372
373         cur = rplist;
374         while (cur != NULL)
375         {
376                 p = cur->next;
377                 free (cur);
378                 cur = p;                
379         }
380 }
381
382 void destroy_network_queue_room_locked (void)
383 {
384         begin_critical_section(S_RPLIST);
385         destroy_network_queue_room(rplist);
386         end_critical_section(S_RPLIST);
387 }
388
389
390
391 /*
392  * Bounce a message back to the sender
393  */
394 void network_bounce(struct CtdlMessage *msg, char *reason) {
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         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         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         static int doing_queue = 0;
509         static time_t last_run = 0L;
510         int full_processing = 1;
511         HashList *working_ignetcfg;
512         HashList *the_netmap = NULL;
513         int netmap_changed = 0;
514         roomlists RL;
515
516         /*
517          * Run the full set of processing tasks no more frequently
518          * than once every n seconds
519          */
520         if ( (time(NULL) - last_run) < config.c_net_freq ) {
521                 full_processing = 0;
522                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
523                         config.c_net_freq - (time(NULL)- last_run)
524                 );
525         }
526
527         /*
528          * This is a simple concurrency check to make sure only one queue run
529          * is done at a time.  We could do this with a mutex, but since we
530          * don't really require extremely fine granularity here, we'll do it
531          * with a static variable instead.
532          */
533         if (doing_queue) {
534                 return;
535         }
536         doing_queue = 1;
537
538         begin_critical_section(S_RPLIST);
539         RL.rplist = rplist;
540         rplist = NULL;
541         end_critical_section(S_RPLIST);
542
543         RL.RoomsInterestedIn = NewHash(1, lFlathash);
544         if (full_processing &&
545             (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
546         {
547                 doing_queue = 0;
548                 DeleteHash(&RL.RoomsInterestedIn);
549                 if (RL.rplist == NULL)
550                         return;
551         }
552         /* Load the IGnet Configuration into memory */
553         working_ignetcfg = load_ignetcfg();
554
555         /*
556          * Load the network map and filter list into memory.
557          */
558         if (!server_shutting_down)
559                 the_netmap = read_network_map();
560         if (!server_shutting_down)
561                 load_network_filter_list();
562
563         /* 
564          * Go ahead and run the queue
565          */
566         if (full_processing && !server_shutting_down) {
567                 syslog(LOG_DEBUG, "network: loading outbound queue\n");
568                 CtdlForEachRoom(network_queue_interesting_rooms, &RL);
569         }
570
571         if ((RL.rplist != NULL) && (!server_shutting_down)) {
572                 RoomProcList *ptr, *cmp;
573                 ptr = RL.rplist;
574                 syslog(LOG_DEBUG, "network: running outbound queue\n");
575                 while (ptr != NULL && !server_shutting_down) {
576                         
577                         cmp = ptr->next;
578
579                         while (cmp != NULL) {
580                                 if ((cmp->namelen > 0) &&
581                                     (cmp->key == ptr->key) &&
582                                     (cmp->namelen == ptr->namelen) &&
583                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
584                                 {
585                                         cmp->namelen = 0;
586                                 }
587                                 cmp = cmp->next;
588                         }
589
590                         if (ptr->namelen > 0) {
591                                 network_spoolout_room(ptr, 
592                                                       working_ignetcfg,
593                                                       the_netmap);
594                         }
595                         ptr = ptr->next;
596                 }
597         }
598
599         /* If there is anything in the inbound queue, process it */
600         if (!server_shutting_down) {
601                 network_do_spoolin(working_ignetcfg, 
602                                    the_netmap,
603                                    &netmap_changed);
604         }
605
606         /* Free the filter list in memory */
607         free_netfilter_list();
608
609         /* Save the network map back to disk */
610         if (netmap_changed) {
611                 StrBuf *MapStr = SerializeNetworkMap(the_netmap);
612                 CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
613         }
614
615         /* combine singe message files into one spool entry per remote node. */
616         network_consolidate_spoolout(working_ignetcfg, the_netmap);
617
618         /* shut down. */
619
620         DeleteHash(&the_netmap);
621
622         DeleteHash(&working_ignetcfg);
623
624         syslog(LOG_DEBUG, "network: queue run completed\n");
625
626         if (full_processing) {
627                 last_run = time(NULL);
628         }
629         DeleteHash(&RL.RoomsInterestedIn);
630         destroy_network_queue_room(RL.rplist);
631         doing_queue = 0;
632 }
633
634
635
636
637 int network_room_handler (struct ctdlroom *room)
638 {
639         network_queue_room(room, NULL);
640         return 0;
641 }
642
643 int NTTDebugEnabled = 0;
644
645 /*
646  * network_talking_to()  --  concurrency checker
647  */
648 static HashList *nttlist = NULL;
649 int network_talking_to(const char *nodename, long len, int operation) {
650
651         int retval = 0;
652         HashPos *Pos = NULL;
653         void *vdata;
654
655         begin_critical_section(S_NTTLIST);
656
657         switch(operation) {
658
659                 case NTT_ADD:
660                         if (nttlist == NULL) 
661                                 nttlist = NewHash(1, NULL);
662                         Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
663                         if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
664                         break;
665                 case NTT_REMOVE:
666                         if ((nttlist == NULL) ||
667                             (GetCount(nttlist) == 0))
668                                 break;
669                         Pos = GetNewHashPos(nttlist, 1);
670                         if (GetHashPosFromKey (nttlist, nodename, len, Pos))
671                                 DeleteEntryFromHash(nttlist, Pos);
672                         DeleteHashPos(&Pos);
673                         if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
674
675                         break;
676
677                 case NTT_CHECK:
678                         if ((nttlist == NULL) ||
679                             (GetCount(nttlist) == 0))
680                                 break;
681                         if (GetHash(nttlist, nodename, len, &vdata))
682                                 retval ++;
683                         if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
684                         break;
685         }
686
687         end_critical_section(S_NTTLIST);
688         return(retval);
689 }
690
691 void cleanup_nttlist(void)
692 {
693         begin_critical_section(S_NTTLIST);
694         DeleteHash(&nttlist);
695         end_critical_section(S_NTTLIST);
696 }
697
698
699
700 void network_logout_hook(void)
701 {
702         CitContext *CCC = MyContext();
703
704         /*
705          * If we were talking to a network node, we're not anymore...
706          */
707         if (!IsEmptyStr(CCC->net_node)) {
708                 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
709                 CCC->net_node[0] = '\0';
710         }
711 }
712 void network_cleanup_function(void)
713 {
714         struct CitContext *CCC = CC;
715
716         if (!IsEmptyStr(CCC->net_node)) {
717                 network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
718                 CCC->net_node[0] = '\0';
719         }
720 }
721
722
723 /*
724  * Module entry point
725  */
726 void SetNTTDebugEnabled(const int n)
727 {
728         NTTDebugEnabled = n;
729 }
730
731 CTDL_MODULE_INIT(network)
732 {
733         if (!threading)
734         {
735                 CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
736                 CtdlRegisterCleanupHook(cleanup_nttlist);
737                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP);
738                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT);
739                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
740                 CtdlRegisterRoomHook(network_room_handler);
741                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
742                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
743         }
744         return "network";
745 }