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