Fix possible double free during sending network error messages.
[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['I'] == NULL) || (IsEmptyStr(msg->cm_fields['I'])))
115         {
116                 return(0);
117         }
118
119         /* Generate the message ID */
120         msgid = NewStrBufPlain(msg->cm_fields['I'], -1);
121         if (haschar(ChrPtr(msgid), '@') == 0) {
122                 StrBufAppendBufPlain(msgid, HKEY("@"), 0);
123                 if (msg->cm_fields['N'] != NULL) {
124                         StrBufAppendBufPlain(msgid, msg->cm_fields['N'], -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['I'] != NULL) {
370                 free(msg->cm_fields['I']);
371         }
372         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
373                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
374         msg->cm_fields['I'] = 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['M'] != NULL) {
381                 free(msg->cm_fields['M']);
382         }
383         msg->cm_fields['M'] = strdup(reason);
384         msg->cm_format_type = 0;
385
386         /*
387          * Turn the message around
388          */
389         if (msg->cm_fields['R'] == NULL) {
390                 free(msg->cm_fields['R']);
391                 msg->cm_fields['R'] = NULL;
392         }
393
394         if (msg->cm_fields['D'] == NULL) {
395                 free(msg->cm_fields['D']);
396                 msg->cm_fields['D'] = NULL;
397         }
398
399         snprintf(recipient, sizeof recipient, "%s@%s",
400                 msg->cm_fields['A'], msg->cm_fields['N']);
401
402         if (msg->cm_fields['A'] == NULL) {
403                 free(msg->cm_fields['A']);
404         }
405
406         if (msg->cm_fields['N'] == NULL) {
407                 free(msg->cm_fields['N']);
408         }
409
410         if (msg->cm_fields['U'] == NULL) {
411                 free(msg->cm_fields['U']);
412         }
413
414         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
415         msg->cm_fields['N'] = strdup(config.c_nodename);
416         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
417
418         /* prepend our node to the path */
419         if (msg->cm_fields['P'] != NULL) {
420                 oldpath = msg->cm_fields['P'];
421                 msg->cm_fields['P'] = NULL;
422         }
423         else {
424                 oldpath = strdup("unknown_user");
425         }
426         size = strlen(oldpath) + SIZ;
427         msg->cm_fields['P'] = malloc(size);
428         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
429         free(oldpath);
430
431         /* Now submit the message */
432         valid = validate_recipients(recipient, NULL, 0);
433         if (valid != NULL) if (valid->num_error != 0) {
434                 free_recipients(valid);
435                 valid = NULL;
436         }
437         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
438                 strcpy(force_room, config.c_aideroom);
439         }
440         else {
441                 strcpy(force_room, "");
442         }
443         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
444                 strcpy(force_room, config.c_aideroom);
445         }
446         CtdlSubmitMsg(msg, valid, force_room, 0);
447
448         /* Clean up */
449         if (valid != NULL) free_recipients(valid);
450         CtdlFreeMessage(msg);
451         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
452 }
453
454
455
456 /*
457  * network_do_queue()
458  * 
459  * Run through the rooms doing various types of network stuff.
460  */
461 void network_do_queue(void)
462 {
463         struct CitContext *CCC = CC;
464         static time_t last_run = 0L;
465         int full_processing = 1;
466         HashList *working_ignetcfg;
467         HashList *the_netmap = NULL;
468         int netmap_changed = 0;
469         roomlists RL;
470         SpoolControl *sc = NULL;
471         SpoolControl *pSC;
472
473         /*
474          * Run the full set of processing tasks no more frequently
475          * than once every n seconds
476          */
477         if ( (time(NULL) - last_run) < config.c_net_freq ) {
478                 full_processing = 0;
479                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
480                        config.c_net_freq - (time(NULL)- last_run)
481                 );
482         }
483
484         become_session(&networker_spool_CC);
485         begin_critical_section(S_RPLIST);
486         RL.rplist = rplist;
487         rplist = NULL;
488         end_critical_section(S_RPLIST);
489 ///TODO hm, check whether we have a config at all here?
490         /* Load the IGnet Configuration into memory */
491         working_ignetcfg = CtdlLoadIgNetCfg();
492
493         /*
494          * Load the network map and filter list into memory.
495          */
496         if (!server_shutting_down)
497                 the_netmap = CtdlReadNetworkMap();
498 #if 0
499         /* filterlist isn't supported anymore
500         if (!server_shutting_down)
501                 load_network_filter_list();
502         */
503 #endif
504
505         /* 
506          * Go ahead and run the queue
507          */
508         if (full_processing && !server_shutting_down) {
509                 QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
510                 CtdlForEachNetCfgRoom(network_queue_interesting_rooms, &RL, maxRoomNetCfg);
511         }
512
513         if ((RL.rplist != NULL) && (!server_shutting_down)) {
514                 RoomProcList *ptr, *cmp;
515                 ptr = RL.rplist;
516                 QNM_syslog(LOG_DEBUG, "network: running outbound queue");
517                 while (ptr != NULL && !server_shutting_down) {
518                         
519                         cmp = ptr->next;
520                         /* filter duplicates from the list... */
521                         while (cmp != NULL) {
522                                 if ((cmp->namelen > 0) &&
523                                     (cmp->key == ptr->key) &&
524                                     (cmp->namelen == ptr->namelen) &&
525                                     (strcmp(cmp->lcname, ptr->lcname) == 0))
526                                 {
527                                         cmp->namelen = 0;
528                                 }
529                                 cmp = cmp->next;
530                         }
531
532                         if (ptr->namelen > 0) {
533                                 InspectQueuedRoom(&sc,
534                                                   ptr, 
535                                                   working_ignetcfg,
536                                                   the_netmap);
537                         }
538                         ptr = ptr->next;
539                 }
540         }
541
542
543         pSC = sc;
544         while (pSC != NULL)
545         {
546                 network_spoolout_room(pSC);
547                 pSC = pSC->next;
548         }
549
550         pSC = sc;
551         while (pSC != NULL)
552         {
553                 sc = pSC->next;
554                 free_spoolcontrol_struct(&pSC);
555                 pSC = sc;
556         }
557         /* If there is anything in the inbound queue, process it */
558         if (!server_shutting_down) {
559                 network_do_spoolin(working_ignetcfg, 
560                                    the_netmap,
561                                    &netmap_changed);
562         }
563
564         /* Free the filter list in memory */
565         free_netfilter_list();
566
567         /* Save the network map back to disk */
568         if (netmap_changed) {
569                 StrBuf *MapStr = CtdlSerializeNetworkMap(the_netmap);
570                 char *pMapStr = SmashStrBuf(&MapStr);
571                 CtdlPutSysConfig(IGNETMAP, pMapStr);
572                 free(pMapStr);
573         }
574
575         /* combine singe message files into one spool entry per remote node. */
576         network_consolidate_spoolout(working_ignetcfg, the_netmap);
577
578         /* shut down. */
579
580         DeleteHash(&the_netmap);
581
582         DeleteHash(&working_ignetcfg);
583
584         QNM_syslog(LOG_DEBUG, "network: queue run completed");
585
586         if (full_processing) {
587                 last_run = time(NULL);
588         }
589         destroy_network_queue_room(RL.rplist);
590         SaveChangedConfigs();
591
592 }
593
594
595
596
597
598
599
600
601 void network_logout_hook(void)
602 {
603         CitContext *CCC = MyContext();
604
605         /*
606          * If we were talking to a network node, we're not anymore...
607          */
608         if (!IsEmptyStr(CCC->net_node)) {
609                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
610                 CCC->net_node[0] = '\0';
611         }
612 }
613 void network_cleanup_function(void)
614 {
615         struct CitContext *CCC = CC;
616
617         if (!IsEmptyStr(CCC->net_node)) {
618                 CtdlNetworkTalkingTo(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
619                 CCC->net_node[0] = '\0';
620         }
621 }
622
623
624 /*
625  * Module entry point
626  */
627
628 void SetNetQDebugEnabled(const int n)
629 {
630         NetQDebugEnabled = n;
631 }
632
633 CTDL_MODULE_INIT(network)
634 {
635         if (!threading)
636         {
637                 CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
638                 CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
639                 CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
640                 CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
641                 CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
642                 CtdlRegisterRoomHook(network_room_handler);
643                 CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
644                 CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
645         }
646         return "network";
647 }