a6d1b844f93953c11065adc481cf72514d0e169e
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <syslog.h>
27 #include <sys/syslog.h>
28
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <limits.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <sys/un.h>
47 #include <string.h>
48 #include <pwd.h>
49 #include <errno.h>
50 #include <stdarg.h>
51 #include <grp.h>
52 #ifdef HAVE_PTHREAD_H
53 #include <pthread.h>
54 #endif
55 #include "citadel.h"
56 #include "server.h"
57 #include "sysdep_decls.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "database.h"
62 #include "housekeeping.h"
63 #include "tools.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
65
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
68 #endif
69
70 #ifndef HAVE_SNPRINTF
71 #include "snprintf.h"
72 #endif
73
74
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct igheap {
77         struct igheap *next;
78         char file[32];
79         int line;
80         void *block;
81 };
82
83 struct igheap *igheap = NULL;
84 #endif
85
86
87 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
88 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
89
90 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
91
92 struct CitContext masterCC;
93 time_t last_purge = 0;                          /* Last dead session purge */
94 static int num_threads = 0;                     /* Current number of threads */
95 int num_sessions = 0;                           /* Current number of sessions */
96
97 int syslog_facility = LOG_DAEMON;
98 int enable_syslog = 0;
99
100 void DestroyWorkerList(void);
101
102 /*
103  * lprintf()  ...   Write logging information
104  */
105 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
106         char *buf;
107         va_list arg_ptr;
108
109         if (enable_syslog) {
110                 va_start(arg_ptr, format);
111                         vsyslog((syslog_facility | loglevel), format, arg_ptr);
112                 va_end(arg_ptr);
113         }
114
115         /* stderr output code */
116         if (enable_syslog || running_as_daemon) {
117                 return;
118         }
119
120         /* if we run in forground and syslog is disabled, log to terminal */
121         if (loglevel <= verbosity) { 
122                 struct timeval tv;
123                 struct tm tim;
124                 time_t unixtime;
125
126                 gettimeofday(&tv, NULL);
127                 /* Promote to time_t; types differ on some OSes (like darwin) */
128                 unixtime = tv.tv_sec;
129                 localtime_r(&unixtime, &tim);
130 //      begin_critical_section(S_LOG);
131
132                 buf = malloc(SIZ+strlen(format));
133
134                 if (CC->cs_pid != 0) {
135                         sprintf(buf,
136                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
137                                 tim.tm_year + 1900, tim.tm_mon + 1,
138                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
139                                 tim.tm_sec, (long)tv.tv_usec,
140                                 CC->cs_pid);
141                 } else {
142                         sprintf(buf,
143                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
144                                 tim.tm_year + 1900, tim.tm_mon + 1,
145                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
146                                 tim.tm_sec, (long)tv.tv_usec);
147                 }
148                 strcat(buf, format);
149                 va_start(arg_ptr, buf);   
150                 vfprintf(stderr, buf, arg_ptr);   
151                 va_end(arg_ptr);   
152                 fflush(stderr);
153                 free (buf);
154 //      end_critical_section(S_LOG);
155         }
156 }   
157
158
159
160 /*
161  * Signal handler to shut down the server.
162  */
163
164 volatile int time_to_die = 0;
165 volatile int shutdown_and_halt = 0;
166 volatile int restart_server = 0;
167 volatile int running_as_daemon = 0;
168
169 static RETSIGTYPE signal_cleanup(int signum) {
170         lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
171         time_to_die = 1;
172         master_cleanup(signum);
173 }
174
175
176
177
178 void InitialiseSemaphores(void)
179 {
180         int i;
181
182         /* Set up a bunch of semaphores to be used for critical sections */
183         for (i=0; i<MAX_SEMAPHORES; ++i) {
184                 pthread_mutex_init(&Critters[i], NULL);
185         }
186 }
187
188
189
190 /*
191  * Some initialization stuff...
192  */
193 void init_sysdep(void) {
194         sigset_t set;
195
196         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
197 #ifdef FD_SETSIZE
198 #ifdef RLIMIT_NOFILE
199         struct rlimit rl;
200         getrlimit(RLIMIT_NOFILE, &rl);
201         rl.rlim_cur = FD_SETSIZE;
202         rl.rlim_max = FD_SETSIZE;
203         setrlimit(RLIMIT_NOFILE, &rl);
204 #endif
205 #endif
206
207         /* If we've got OpenSSL, we're going to use it. */
208 #ifdef HAVE_OPENSSL
209         init_ssl();
210 #endif
211
212         /*
213          * Set up a place to put thread-specific data.
214          * We only need a single pointer per thread - it points to the
215          * CitContext structure (in the ContextList linked list) of the
216          * session to which the calling thread is currently bound.
217          */
218         if (pthread_key_create(&MyConKey, NULL) != 0) {
219                 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
220                         strerror(errno));
221         }
222
223         /*
224          * The action for unexpected signals and exceptions should be to
225          * call signal_cleanup() to gracefully shut down the server.
226          */
227         sigemptyset(&set);
228         sigaddset(&set, SIGINT);
229         sigaddset(&set, SIGQUIT);
230         sigaddset(&set, SIGHUP);
231         sigaddset(&set, SIGTERM);
232         // sigaddset(&set, SIGSEGV);    commented out because
233         // sigaddset(&set, SIGILL);     we want core dumps
234         // sigaddset(&set, SIGBUS);
235         sigprocmask(SIG_UNBLOCK, &set, NULL);
236
237         signal(SIGINT, signal_cleanup);
238         signal(SIGQUIT, signal_cleanup);
239         signal(SIGHUP, signal_cleanup);
240         signal(SIGTERM, signal_cleanup);
241         // signal(SIGSEGV, signal_cleanup);     commented out because
242         // signal(SIGILL, signal_cleanup);      we want core dumps
243         // signal(SIGBUS, signal_cleanup);
244
245         /*
246          * Do not shut down the server on broken pipe signals, otherwise the
247          * whole Citadel service would come down whenever a single client
248          * socket breaks.
249          */
250         signal(SIGPIPE, SIG_IGN);
251 }
252
253
254 /*
255  * Obtain a semaphore lock to begin a critical section.
256  */
257 void begin_critical_section(int which_one)
258 {
259         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
260
261         /* For all types of critical sections except those listed here,
262          * ensure nobody ever tries to do a critical section within a
263          * transaction; this could lead to deadlock.
264          */
265         if (    (which_one != S_FLOORCACHE)
266 #ifdef DEBUG_MEMORY_LEAKS
267                 && (which_one != S_DEBUGMEMLEAKS)
268 #endif
269                 && (which_one != S_RPLIST)
270         ) {
271                 cdb_check_handles();
272         }
273         pthread_mutex_lock(&Critters[which_one]);
274 }
275
276 /*
277  * Release a semaphore lock to end a critical section.
278  */
279 void end_critical_section(int which_one)
280 {
281         pthread_mutex_unlock(&Critters[which_one]);
282 }
283
284
285
286 /*
287  * This is a generic function to set up a master socket for listening on
288  * a TCP port.  The server shuts down if the bind fails.
289  *
290  */
291 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
292 {
293         struct sockaddr_in sin;
294         int s, i;
295         int actual_queue_len;
296
297         actual_queue_len = queue_len;
298         if (actual_queue_len < 5) actual_queue_len = 5;
299
300         memset(&sin, 0, sizeof(sin));
301         sin.sin_family = AF_INET;
302         sin.sin_port = htons((u_short)port_number);
303         if (ip_addr == NULL) {
304                 sin.sin_addr.s_addr = INADDR_ANY;
305         }
306         else {
307                 sin.sin_addr.s_addr = inet_addr(ip_addr);
308         }
309                                                                                 
310         if (sin.sin_addr.s_addr == !INADDR_ANY) {
311                 sin.sin_addr.s_addr = INADDR_ANY;
312         }
313
314         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
315
316         if (s < 0) {
317                 *errormessage = (char*) malloc(SIZ + 1);
318                 snprintf(*errormessage, SIZ, 
319                                  "citserver: Can't create a socket: %s",
320                                  strerror(errno));
321                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
322                 return(-1);
323         }
324
325         i = 1;
326         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
327
328         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
329                 *errormessage = (char*) malloc(SIZ + 1);
330                 snprintf(*errormessage, SIZ, 
331                                  "citserver: Can't bind: %s",
332                                  strerror(errno));
333                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
334                 close(s);
335                 return(-1);
336         }
337
338         /* set to nonblock - we need this for some obscure situations */
339         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
340                 *errormessage = (char*) malloc(SIZ + 1);
341                 snprintf(*errormessage, SIZ, 
342                                  "citserver: Can't set socket to non-blocking: %s",
343                                  strerror(errno));
344                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
345                 close(s);
346                 return(-1);
347         }
348
349         if (listen(s, actual_queue_len) < 0) {
350                 *errormessage = (char*) malloc(SIZ + 1);
351                 snprintf(*errormessage, SIZ, 
352                                  "citserver: Can't listen: %s",
353                                  strerror(errno));
354                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
355                 close(s);
356                 return(-1);
357         }
358
359         return(s);
360 }
361
362
363
364 /*
365  * Create a Unix domain socket and listen on it
366  */
367 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
368 {
369         struct sockaddr_un addr;
370         int s;
371         int i;
372         int actual_queue_len;
373         long ret, ret2;
374         actual_queue_len = queue_len;
375         if (actual_queue_len < 5) actual_queue_len = 5;
376
377         i = unlink(sockpath);
378         if (i != 0) if (errno != ENOENT) {
379                 *errormessage = (char*) malloc(SIZ + 1);
380                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
381                         sockpath, strerror(errno));
382                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
383                 return(-1);
384         }
385
386         memset(&addr, 0, sizeof(addr));
387         addr.sun_family = AF_UNIX;
388         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
389
390         s = socket(AF_UNIX, SOCK_STREAM, 0);
391         if (s < 0) {
392                 *errormessage = (char*) malloc(SIZ + 1);
393                 snprintf(*errormessage, SIZ, 
394                          "citserver: Can't create a socket: %s",
395                          strerror(errno));
396                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
397                 return(-1);
398         }
399
400         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
401                 *errormessage = (char*) malloc(SIZ + 1);
402                 snprintf(*errormessage, SIZ, 
403                          "citserver: Can't bind: %s",
404                          strerror(errno));
405                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
406                 return(-1);
407         }
408
409         /* set to nonblock - we need this for some obscure situations */
410         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
411                 *errormessage = (char*) malloc(SIZ + 1);
412                 snprintf(*errormessage, SIZ, 
413                          "citserver: Can't set socket to non-blocking: %s",
414                          strerror(errno));
415                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
416                 close(s);
417                 return(-1);
418         }
419
420         if (listen(s, actual_queue_len) < 0) {
421                 *errormessage = (char*) malloc(SIZ + 1);
422                 snprintf(*errormessage, SIZ, 
423                          "citserver: Can't listen: %s",
424                          strerror(errno));
425                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
426                 return(-1);
427         }
428
429         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
430         return(s);
431 }
432
433
434
435 /*
436  * Return a pointer to the CitContext structure bound to the thread which
437  * called this function.  If there's no such binding (for example, if it's
438  * called by the housekeeper thread) then a generic 'master' CC is returned.
439  *
440  * This function is used *VERY* frequently and must be kept small.
441  */
442 struct CitContext *MyContext(void) {
443
444         register struct CitContext *c;
445
446         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
447                 c == NULL) ? &masterCC : c
448         );
449 }
450
451
452 /*
453  * Initialize a new context and place it in the list.  The session number
454  * used to be the PID (which is why it's called cs_pid), but that was when we
455  * had one process per session.  Now we just assign them sequentially, starting
456  * at 1 (don't change it to 0 because masterCC uses 0).
457  */
458 struct CitContext *CreateNewContext(void) {
459         struct CitContext *me;
460         static int next_pid = 0;
461
462         me = (struct CitContext *) malloc(sizeof(struct CitContext));
463         if (me == NULL) {
464                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
465                 return NULL;
466         }
467         memset(me, 0, sizeof(struct CitContext));
468
469         /* The new context will be created already in the CON_EXECUTING state
470          * in order to prevent another thread from grabbing it while it's
471          * being set up.
472          */
473         me->state = CON_EXECUTING;
474
475         /*
476          * Generate a unique session number and insert this context into
477          * the list.
478          */
479         begin_critical_section(S_SESSION_TABLE);
480         me->cs_pid = ++next_pid;
481         me->prev = NULL;
482         me->next = ContextList;
483         ContextList = me;
484         if (me->next != NULL) {
485                 me->next->prev = me;
486         }
487         ++num_sessions;
488         end_critical_section(S_SESSION_TABLE);
489         return(me);
490 }
491
492
493 /*
494  * The following functions implement output buffering. If the kernel supplies
495  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
496  * user-space buffering.
497  */
498 #ifndef HAVE_DARWIN
499 #ifdef TCP_CORK
500 #       define HAVE_TCP_BUFFERING
501 #else
502 #       ifdef TCP_NOPUSH
503 #               define HAVE_TCP_BUFFERING
504 #               define TCP_CORK TCP_NOPUSH
505 #       endif
506 #endif /* TCP_CORK */
507 #endif /* HAVE_DARWIN */
508
509 #ifdef HAVE_TCP_BUFFERING
510 static unsigned on = 1, off = 0;
511 void buffer_output(void) {
512         struct CitContext *ctx = MyContext();
513         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
514         ctx->buffering = 1;
515 }
516
517 void unbuffer_output(void) {
518         struct CitContext *ctx = MyContext();
519         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
520         ctx->buffering = 0;
521 }
522
523 void flush_output(void) {
524         struct CitContext *ctx = MyContext();
525         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
526         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
527 }
528 #else 
529 #ifdef HAVE_DARWIN
530 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
531 void buffer_output(void) {
532         CC->buffering = 0;
533 }
534 void unbuffer_output(void) {
535         CC->buffering = 0;
536 }
537 void flush_output(void) {
538 }
539 #else
540 void buffer_output(void) {
541         if (CC->buffering == 0) {
542                 CC->buffering = 1;
543                 CC->buffer_len = 0;
544                 CC->output_buffer = malloc(SIZ);
545         }
546 }
547
548 void flush_output(void) {
549         if (CC->buffering == 1) {
550                 client_write(CC->output_buffer, CC->buffer_len);
551                 CC->buffer_len = 0;
552         }
553 }
554
555 void unbuffer_output(void) {
556         if (CC->buffering == 1) {
557                 CC->buffering = 0;
558                 /* We don't call flush_output because we can't. */
559                 client_write(CC->output_buffer, CC->buffer_len);
560                 CC->buffer_len = 0;
561                 free(CC->output_buffer);
562                 CC->output_buffer = NULL;
563         }
564 }
565 #endif /* HAVE_DARWIN */
566 #endif /* HAVE_TCP_BUFFERING */
567
568
569
570 /*
571  * client_write()   ...    Send binary data to the client.
572  */
573 void client_write(char *buf, int nbytes)
574 {
575         int bytes_written = 0;
576         int retval;
577 #ifndef HAVE_TCP_BUFFERING
578         int old_buffer_len = 0;
579 #endif
580
581         if (CC->redirect_buffer != NULL) {
582                 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
583                         CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
584                         CC->redirect_buffer = realloc(CC->redirect_buffer,
585                                                 CC->redirect_alloc);
586                 }
587                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
588                 CC->redirect_len += nbytes;
589                 CC->redirect_buffer[CC->redirect_len] = 0;
590                 return;
591         }
592
593 #ifndef HAVE_TCP_BUFFERING
594         /* If we're buffering for later, do that now. */
595         if (CC->buffering) {
596                 old_buffer_len = CC->buffer_len;
597                 CC->buffer_len += nbytes;
598                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
599                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
600                 return;
601         }
602 #endif
603
604         /* Ok, at this point we're not buffering.  Go ahead and write. */
605
606 #ifdef HAVE_OPENSSL
607         if (CC->redirect_ssl) {
608                 client_write_ssl(buf, nbytes);
609                 return;
610         }
611 #endif
612
613         while (bytes_written < nbytes) {
614                 retval = write(CC->client_socket, &buf[bytes_written],
615                         nbytes - bytes_written);
616                 if (retval < 1) {
617                         lprintf(CTDL_ERR,
618                                 "client_write(%d bytes) failed: %s (%d)\n",
619                                 nbytes - bytes_written,
620                                 strerror(errno), errno);
621                         cit_backtrace();
622                         CC->kill_me = 1;
623                         return;
624                 }
625                 bytes_written = bytes_written + retval;
626         }
627 }
628
629
630 /*
631  * cprintf()  ...   Send formatted printable data to the client.   It is
632  *                implemented in terms of client_write() but remains in
633  *                sysdep.c in case we port to somewhere without va_args...
634  */
635 void cprintf(const char *format, ...) {   
636         va_list arg_ptr;   
637         char buf[1024];   
638    
639         va_start(arg_ptr, format);   
640         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
641                 buf[sizeof buf - 2] = '\n';
642         client_write(buf, strlen(buf)); 
643         va_end(arg_ptr);
644 }   
645
646
647 /*
648  * Read data from the client socket.
649  * Return values are:
650  *      1       Requested number of bytes has been read.
651  *      0       Request timed out.
652  *      -1      The socket is broken.
653  * If the socket breaks, the session will be terminated.
654  */
655 int client_read_to(char *buf, int bytes, int timeout)
656 {
657         int len,rlen;
658         fd_set rfds;
659         struct timeval tv;
660         int retval;
661
662 #ifdef HAVE_OPENSSL
663         if (CC->redirect_ssl) {
664                 return (client_read_ssl(buf, bytes, timeout));
665         }
666 #endif
667         len = 0;
668         while(len<bytes) {
669                 FD_ZERO(&rfds);
670                 FD_SET(CC->client_socket, &rfds);
671                 tv.tv_sec = timeout;
672                 tv.tv_usec = 0;
673
674                 retval = select( (CC->client_socket)+1, 
675                                         &rfds, NULL, NULL, &tv);
676
677                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
678                         return(0);
679                 }
680
681                 rlen = read(CC->client_socket, &buf[len], bytes-len);
682                 if (rlen<1) {
683                         /* The socket has been disconnected! */
684                         CC->kill_me = 1;
685                         return(-1);
686                 }
687                 len = len + rlen;
688         }
689         return(1);
690 }
691
692 /*
693  * Read data from the client socket with default timeout.
694  * (This is implemented in terms of client_read_to() and could be
695  * justifiably moved out of sysdep.c)
696  */
697 INLINE int client_read(char *buf, int bytes)
698 {
699         return(client_read_to(buf, bytes, config.c_sleeping));
700 }
701
702
703 /*
704  * client_getln()   ...   Get a LF-terminated line of text from the client.
705  * (This is implemented in terms of client_read() and could be
706  * justifiably moved out of sysdep.c)
707  */
708 int client_getln(char *buf, int bufsize)
709 {
710         int i, retval;
711
712         /* Read one character at a time.
713          */
714         for (i = 0;;i++) {
715                 retval = client_read(&buf[i], 1);
716                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
717                         break;
718         }
719
720         /* If we got a long line, discard characters until the newline.
721          */
722         if (i == (bufsize-1))
723                 while (buf[i] != '\n' && retval == 1)
724                         retval = client_read(&buf[i], 1);
725
726         /* Strip the trailing LF, and the trailing CR if present.
727          */
728         buf[i] = 0;
729         while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
730                 buf[strlen(buf)-1] = 0;
731         }
732         if (retval < 0) safestrncpy(buf, "000", bufsize);
733         return(retval);
734 }
735
736
737
738 /*
739  * The system-dependent part of master_cleanup() - close the master socket.
740  */
741 void sysdep_master_cleanup(void) {
742         struct ServiceFunctionHook *serviceptr;
743
744 /////   DestroyWorkerList();
745         /*
746          * close all protocol master sockets
747          */
748         for (serviceptr = ServiceHookTable; serviceptr != NULL;
749             serviceptr = serviceptr->next ) {
750
751                 if (serviceptr->tcp_port > 0)
752                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
753                                 serviceptr->tcp_port);
754
755                 if (serviceptr->sockpath != NULL)
756                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
757                                 serviceptr->sockpath);
758
759                 close(serviceptr->msock);
760
761                 /* If it's a Unix domain socket, remove the file. */
762                 if (serviceptr->sockpath != NULL) {
763                         unlink(serviceptr->sockpath);
764                 }
765         }
766 #ifdef HAVE_OPENSSL
767         destruct_ssl();
768 #endif
769         serv_calendar_destroy();
770         CtdlDestroyProtoHooks();
771         CtdlDestroyDeleteHooks();
772         CtdlDestroyXmsgHooks();
773         CtdlDestroyNetprocHooks();
774         CtdlDestroyUserHooks();
775         CtdlDestroyMessageHook();
776         CtdlDestroyCleanupHooks();
777         CtdlDestroyFixedOutputHooks();  
778         CtdlDestroySessionHooks();
779         CtdlDestroyServiceHook();
780 }
781
782
783
784
785 /*
786  * Terminate another session.
787  * (This could justifiably be moved out of sysdep.c because it
788  * no longer does anything that is system-dependent.)
789  */
790 void kill_session(int session_to_kill) {
791         struct CitContext *ptr;
792
793         begin_critical_section(S_SESSION_TABLE);
794         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
795                 if (ptr->cs_pid == session_to_kill) {
796                         ptr->kill_me = 1;
797                 }
798         }
799         end_critical_section(S_SESSION_TABLE);
800 }
801
802 pid_t current_child;
803 void graceful_shutdown(int signum) {
804         kill(current_child, signum);
805         unlink(file_pid_file);
806         exit(0);
807 }
808
809
810 /*
811  * Start running as a daemon.
812  */
813 void start_daemon(int unused) {
814         int status = 0;
815         pid_t child = 0;
816         FILE *fp;
817         int do_restart = 0;
818
819         current_child = 0;
820
821         /* Close stdin/stdout/stderr and replace them with /dev/null.
822          * We don't just call close() because we don't want these fd's
823          * to be reused for other files.
824          */
825         chdir(ctdl_run_dir);
826
827         child = fork();
828         if (child != 0) {
829                 exit(0);
830         }
831         
832         signal(SIGHUP, SIG_IGN);
833         signal(SIGINT, SIG_IGN);
834         signal(SIGQUIT, SIG_IGN);
835
836         setsid();
837         umask(0);
838         freopen("/dev/null", "r", stdin);
839         freopen("/dev/null", "w", stdout);
840         freopen("/dev/null", "w", stderr);
841
842         do {
843                 current_child = fork();
844
845                 signal(SIGTERM, graceful_shutdown);
846         
847                 if (current_child < 0) {
848                         perror("fork");
849                         exit(errno);
850                 }
851         
852                 else if (current_child == 0) {
853                         return; /* continue starting citadel. */
854                 }
855         
856                 else {
857                         fp = fopen(file_pid_file, "w");
858                         if (fp != NULL) {
859                                 fprintf(fp, ""F_PID_T"\n", child);
860                                 fclose(fp);
861                         }
862                         waitpid(current_child, &status, 0);
863                 }
864
865                 do_restart = 0;
866
867                 /* Did the main process exit with an actual exit code? */
868                 if (WIFEXITED(status)) {
869
870                         /* Exit code 0 means the watcher should exit */
871                         if (WEXITSTATUS(status) == 0) {
872                                 do_restart = 0;
873                         }
874
875                         /* Exit code 101-109 means the watcher should exit */
876                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
877                                 do_restart = 0;
878                         }
879
880                         /* Any other exit code means we should restart. */
881                         else {
882                                 do_restart = 1;
883                         }
884                 }
885
886                 /* Any other type of termination (signals, etc.) should also restart. */
887                 else {
888                         do_restart = 1;
889                 }
890
891         } while (do_restart);
892
893         unlink(file_pid_file);
894         exit(WEXITSTATUS(status));
895 }
896
897
898
899 /*
900  * Generic routine to convert a login name to a full name (gecos)
901  * Returns nonzero if a conversion took place
902  */
903 int convert_login(char NameToConvert[]) {
904         struct passwd *pw;
905         int a;
906
907         pw = getpwnam(NameToConvert);
908         if (pw == NULL) {
909                 return(0);
910         }
911         else {
912                 strcpy(NameToConvert, pw->pw_gecos);
913                 for (a=0; a<strlen(NameToConvert); ++a) {
914                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
915                 }
916                 return(1);
917         }
918 }
919
920 struct worker_node *worker_list = NULL;
921
922
923 /*
924  * create a worker thread. this function must always be called from within
925  * an S_WORKER_LIST critical section!
926  */
927 void create_worker(void) {
928         int ret;
929         struct worker_node *n;
930         pthread_attr_t attr;
931
932         n = malloc(sizeof(struct worker_node));
933         if (n == NULL) {
934                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
935                 time_to_die = -1;
936                 return;
937         }
938
939         if ((ret = pthread_attr_init(&attr))) {
940                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
941                 time_to_die = -1;
942                 return;
943         }
944
945         /* Our per-thread stacks need to be bigger than the default size,
946          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
947          * crashes on 64-bit Linux.
948          */
949         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
950                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
951                         strerror(ret));
952                 time_to_die = -1;
953                 pthread_attr_destroy(&attr);
954                 return;
955         }
956
957         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
958         {
959
960                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
961                         strerror(ret));
962         }
963
964         n->next = worker_list;
965         worker_list = n;
966         pthread_attr_destroy(&attr);
967 }
968
969 void DestroyWorkerList(void)
970 {
971         struct CitContext *ptr;         /* general-purpose utility pointer */
972         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
973
974         begin_critical_section(S_SESSION_TABLE);
975         ptr = ContextList;
976         while (ptr != NULL){
977                 /* Remove the session from the active list */
978                 rem = ptr->next;
979                 --num_sessions;
980                 
981                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
982                 end_critical_section(S_SESSION_TABLE);
983                 RemoveContext(ptr);
984                 begin_critical_section(S_SESSION_TABLE);
985                 free (ptr);
986                 ptr = rem;
987         }
988         end_critical_section(S_SESSION_TABLE);
989
990         struct worker_node *cur, *p;
991         cur = worker_list;
992         while (cur != NULL)
993         {
994                 p = cur->next;
995                 free (cur);
996                 cur = p;
997         }
998         worker_list = NULL;
999 }
1000
1001 /*
1002  * Create the maintenance threads and begin their operation.
1003  */
1004 void create_maintenance_threads(void) {
1005         int ret;
1006         pthread_attr_t attr;
1007
1008         if ((ret = pthread_attr_init(&attr))) {
1009                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1010                 time_to_die = -1;
1011                 return;
1012         }
1013
1014         /* Our per-thread stacks need to be bigger than the default size,
1015          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1016          * crashes on 64-bit Linux.
1017          */
1018         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1019                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1020                         strerror(ret));
1021                 time_to_die = -1;
1022                 pthread_attr_destroy(&attr);
1023                 return;
1024         }
1025         
1026         struct MaintenanceThreadHook *fcn;
1027
1028         lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1029
1030         for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1031                 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1032                         lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1033                 }
1034                 else
1035                 {
1036                         lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1037                                 fcn->MaintenanceThread_tid);
1038                 }
1039         }
1040
1041
1042         pthread_attr_destroy(&attr);
1043 }
1044
1045
1046
1047 /*
1048  * Purge all sessions which have the 'kill_me' flag set.
1049  * This function has code to prevent it from running more than once every
1050  * few seconds, because running it after every single unbind would waste a lot
1051  * of CPU time and keep the context list locked too much.  To force it to run
1052  * anyway, set "force" to nonzero.
1053  *
1054  *
1055  * After that's done, we raise the size of the worker thread pool
1056  * if such an action is appropriate.
1057  */
1058 void dead_session_purge(int force) {
1059         struct CitContext *ptr;         /* general-purpose utility pointer */
1060         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1061
1062         if (force == 0) {
1063                 if ( (time(NULL) - last_purge) < 5 ) {
1064                         return; /* Too soon, go away */
1065                 }
1066         }
1067         time(&last_purge);
1068
1069         begin_critical_section(S_SESSION_TABLE);
1070         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1071                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1072
1073                         /* Remove the session from the active list */
1074                         if (ptr->prev) {
1075                                 ptr->prev->next = ptr->next;
1076                         }
1077                         else {
1078                                 ContextList = ptr->next;
1079                         }
1080                         if (ptr->next) {
1081                                 ptr->next->prev = ptr->prev;
1082                         }
1083
1084                         --num_sessions;
1085
1086                         /* And put it on our to-be-destroyed list */
1087                         ptr->next = rem;
1088                         rem = ptr;
1089
1090                 }
1091         }
1092         end_critical_section(S_SESSION_TABLE);
1093
1094         /* Now that we no longer have the session list locked, we can take
1095          * our time and destroy any sessions on the to-be-killed list, which
1096          * is allocated privately on this thread's stack.
1097          */
1098         while (rem != NULL) {
1099                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1100                 RemoveContext(rem);
1101                 ptr = rem;
1102                 rem = rem->next;
1103                 free(ptr);
1104         }
1105
1106         /* Raise the size of the worker thread pool if necessary. */
1107         if ( (num_sessions > num_threads)
1108            && (num_threads < config.c_max_workers) ) {
1109                 begin_critical_section(S_WORKER_LIST);
1110                 create_worker();
1111                 end_critical_section(S_WORKER_LIST);
1112         }
1113 }
1114
1115
1116
1117
1118
1119 /*
1120  * masterCC is the context we use when not attached to a session.  This
1121  * function initializes it.
1122  */
1123 void InitializeMasterCC(void) {
1124         memset(&masterCC, 0, sizeof(struct CitContext));
1125         masterCC.internal_pgm = 1;
1126         masterCC.cs_pid = 0;
1127 }
1128
1129
1130
1131
1132
1133
1134 /*
1135  * Bind a thread to a context.  (It's inline merely to speed things up.)
1136  */
1137 INLINE void become_session(struct CitContext *which_con) {
1138         pthread_setspecific(MyConKey, (void *)which_con );
1139 }
1140
1141
1142
1143 /* 
1144  * This loop just keeps going and going and going...
1145  */     
1146 void *worker_thread(void *arg) {
1147         int i;
1148         int highest;
1149         struct CitContext *ptr;
1150         struct CitContext *bind_me = NULL;
1151         fd_set readfds;
1152         int retval = 0;
1153         struct CitContext *con= NULL;   /* Temporary context pointer */
1154         struct ServiceFunctionHook *serviceptr;
1155         int ssock;                      /* Descriptor for client socket */
1156         struct timeval tv;
1157         int force_purge = 0;
1158         int m;
1159
1160         num_threads++;
1161
1162         cdb_allocate_tsd();
1163
1164         while (!time_to_die) {
1165
1166                 /* make doubly sure we're not holding any stale db handles
1167                  * which might cause a deadlock.
1168                  */
1169                 cdb_check_handles();
1170 do_select:      force_purge = 0;
1171                 bind_me = NULL;         /* Which session shall we handle? */
1172
1173                 /* Initialize the fdset. */
1174                 FD_ZERO(&readfds);
1175                 highest = 0;
1176
1177                 begin_critical_section(S_SESSION_TABLE);
1178                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1179                         if (ptr->state == CON_IDLE) {
1180                                 FD_SET(ptr->client_socket, &readfds);
1181                                 if (ptr->client_socket > highest)
1182                                         highest = ptr->client_socket;
1183                         }
1184                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1185                                 bind_me = ptr;
1186                                 ptr->state = CON_EXECUTING;
1187                         }
1188                 }
1189                 end_critical_section(S_SESSION_TABLE);
1190
1191                 if (bind_me) {
1192                         goto SKIP_SELECT;
1193                 }
1194
1195                 /* If we got this far, it means that there are no sessions
1196                  * which a previous thread marked for attention, so we go
1197                  * ahead and get ready to select().
1198                  */
1199
1200                 /* First, add the various master sockets to the fdset. */
1201                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1202                 serviceptr = serviceptr->next ) {
1203                         m = serviceptr->msock;
1204                         FD_SET(m, &readfds);
1205                         if (m > highest) {
1206                                 highest = m;
1207                         }
1208                 }
1209
1210                 if (!time_to_die) {
1211                         tv.tv_sec = 1;          /* wake up every second if no input */
1212                         tv.tv_usec = 0;
1213                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1214                 }
1215
1216                 if (time_to_die) return(NULL);
1217
1218                 /* Now figure out who made this select() unblock.
1219                  * First, check for an error or exit condition.
1220                  */
1221                 if (retval < 0) {
1222                         if (errno == EBADF) {
1223                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1224                                         strerror(errno));
1225                                 goto do_select;
1226                         }
1227                         if (errno != EINTR) {
1228                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1229                                 time_to_die = 1;
1230                         } else if (!time_to_die)
1231                                 goto do_select;
1232                 }
1233
1234                 /* Next, check to see if it's a new client connecting
1235                  * on a master socket.
1236                  */
1237                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1238                      serviceptr = serviceptr->next ) {
1239
1240                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1241                                 ssock = accept(serviceptr->msock, NULL, 0);
1242                                 if (ssock >= 0) {
1243                                         lprintf(CTDL_DEBUG,
1244                                                 "New client socket %d\n",
1245                                                 ssock);
1246
1247                                         /* The master socket is non-blocking but the client
1248                                          * sockets need to be blocking, otherwise certain
1249                                          * operations barf on FreeBSD.  Not a fatal error.
1250                                          */
1251                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1252                                                 lprintf(CTDL_EMERG,
1253                                                         "citserver: Can't set socket to blocking: %s\n",
1254                                                         strerror(errno));
1255                                         }
1256
1257                                         /* New context will be created already
1258                                          * set up in the CON_EXECUTING state.
1259                                          */
1260                                         con = CreateNewContext();
1261
1262                                         /* Assign our new socket number to it. */
1263                                         con->client_socket = ssock;
1264                                         con->h_command_function =
1265                                                 serviceptr->h_command_function;
1266                                         con->h_async_function =
1267                                                 serviceptr->h_async_function;
1268
1269                                         /* Determine whether it's a local socket */
1270                                         if (serviceptr->sockpath != NULL)
1271                                                 con->is_local_socket = 1;
1272         
1273                                         /* Set the SO_REUSEADDR socket option */
1274                                         i = 1;
1275                                         setsockopt(ssock, SOL_SOCKET,
1276                                                 SO_REUSEADDR,
1277                                                 &i, sizeof(i));
1278
1279                                         become_session(con);
1280                                         begin_session(con);
1281                                         serviceptr->h_greeting_function();
1282                                         become_session(NULL);
1283                                         con->state = CON_IDLE;
1284                                         goto do_select;
1285                                 }
1286                         }
1287                 }
1288
1289                 /* It must be a client socket.  Find a context that has data
1290                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1291                  * active sockets other than our chosen one are marked as
1292                  * CON_READY so the next thread that comes around can just bind
1293                  * to one without having to select() again.
1294                  */
1295                 begin_critical_section(S_SESSION_TABLE);
1296                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1297                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1298                            && (ptr->state != CON_EXECUTING) ) {
1299                                 ptr->input_waiting = 1;
1300                                 if (!bind_me) {
1301                                         bind_me = ptr;  /* I choose you! */
1302                                         bind_me->state = CON_EXECUTING;
1303                                 }
1304                                 else {
1305                                         ptr->state = CON_READY;
1306                                 }
1307                         }
1308                 }
1309                 end_critical_section(S_SESSION_TABLE);
1310
1311 SKIP_SELECT:
1312                 /* We're bound to a session */
1313                 if (bind_me != NULL) {
1314                         become_session(bind_me);
1315
1316                         /* If the client has sent a command, execute it. */
1317                         if (CC->input_waiting) {
1318                                 CC->h_command_function();
1319                                 CC->input_waiting = 0;
1320                         }
1321
1322                         /* If there are asynchronous messages waiting and the
1323                          * client supports it, do those now */
1324                         if ((CC->is_async) && (CC->async_waiting)
1325                            && (CC->h_async_function != NULL)) {
1326                                 CC->h_async_function();
1327                                 CC->async_waiting = 0;
1328                         }
1329                         
1330                         force_purge = CC->kill_me;
1331                         become_session(NULL);
1332                         bind_me->state = CON_IDLE;
1333                 }
1334
1335                 dead_session_purge(force_purge);
1336                 do_housekeeping();
1337                 check_sched_shutdown();
1338         }
1339         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1340         /* If control reaches this point, the server is shutting down */        
1341         return(NULL);
1342 }
1343
1344
1345
1346
1347 /*
1348  * SyslogFacility()
1349  * Translate text facility name to syslog.h defined value.
1350  */
1351 int SyslogFacility(char *name)
1352 {
1353         int i;
1354         struct
1355         {
1356                 int facility;
1357                 char *name;
1358         }   facTbl[] =
1359         {
1360                 {   LOG_KERN,   "kern"          },
1361                 {   LOG_USER,   "user"          },
1362                 {   LOG_MAIL,   "mail"          },
1363                 {   LOG_DAEMON, "daemon"        },
1364                 {   LOG_AUTH,   "auth"          },
1365                 {   LOG_SYSLOG, "syslog"        },
1366                 {   LOG_LPR,    "lpr"           },
1367                 {   LOG_NEWS,   "news"          },
1368                 {   LOG_UUCP,   "uucp"          },
1369                 {   LOG_LOCAL0, "local0"        },
1370                 {   LOG_LOCAL1, "local1"        },
1371                 {   LOG_LOCAL2, "local2"        },
1372                 {   LOG_LOCAL3, "local3"        },
1373                 {   LOG_LOCAL4, "local4"        },
1374                 {   LOG_LOCAL5, "local5"        },
1375                 {   LOG_LOCAL6, "local6"        },
1376                 {   LOG_LOCAL7, "local7"        },
1377                 {   0,            NULL          }
1378         };
1379         for(i = 0; facTbl[i].name != NULL; i++) {
1380                 if(!strcasecmp(name, facTbl[i].name))
1381                         return facTbl[i].facility;
1382         }
1383         enable_syslog = 0;
1384         return LOG_DAEMON;
1385 }
1386
1387
1388 /********** MEM CHEQQER ***********/
1389
1390 #ifdef DEBUG_MEMORY_LEAKS
1391
1392 #undef malloc
1393 #undef realloc
1394 #undef strdup
1395 #undef free
1396
1397 void *tracked_malloc(size_t size, char *file, int line) {
1398         struct igheap *thisheap;
1399         void *block;
1400
1401         block = malloc(size);
1402         if (block == NULL) return(block);
1403
1404         thisheap = malloc(sizeof(struct igheap));
1405         if (thisheap == NULL) {
1406                 free(block);
1407                 return(NULL);
1408         }
1409
1410         thisheap->block = block;
1411         strcpy(thisheap->file, file);
1412         thisheap->line = line;
1413         
1414         begin_critical_section(S_DEBUGMEMLEAKS);
1415         thisheap->next = igheap;
1416         igheap = thisheap;
1417         end_critical_section(S_DEBUGMEMLEAKS);
1418
1419         return(block);
1420 }
1421
1422
1423 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1424         struct igheap *thisheap;
1425         void *block;
1426
1427         block = realloc(ptr, size);
1428         if (block == NULL) return(block);
1429
1430         thisheap = malloc(sizeof(struct igheap));
1431         if (thisheap == NULL) {
1432                 free(block);
1433                 return(NULL);
1434         }
1435
1436         thisheap->block = block;
1437         strcpy(thisheap->file, file);
1438         thisheap->line = line;
1439         
1440         begin_critical_section(S_DEBUGMEMLEAKS);
1441         thisheap->next = igheap;
1442         igheap = thisheap;
1443         end_critical_section(S_DEBUGMEMLEAKS);
1444
1445         return(block);
1446 }
1447
1448
1449
1450 void tracked_free(void *ptr) {
1451         struct igheap *thisheap;
1452         struct igheap *trash;
1453
1454         free(ptr);
1455
1456         if (igheap == NULL) return;
1457         begin_critical_section(S_DEBUGMEMLEAKS);
1458         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1459                 if (thisheap->next != NULL) {
1460                         if (thisheap->next->block == ptr) {
1461                                 trash = thisheap->next;
1462                                 thisheap->next = thisheap->next->next;
1463                                 free(trash);
1464                         }
1465                 }
1466         }
1467         if (igheap->block == ptr) {
1468                 trash = igheap;
1469                 igheap = igheap->next;
1470                 free(trash);
1471         }
1472         end_critical_section(S_DEBUGMEMLEAKS);
1473 }
1474
1475 char *tracked_strdup(const char *s, char *file, int line) {
1476         char *ptr;
1477
1478         if (s == NULL) return(NULL);
1479         ptr = tracked_malloc(strlen(s) + 1, file, line);
1480         if (ptr == NULL) return(NULL);
1481         strncpy(ptr, s, strlen(s));
1482         return(ptr);
1483 }
1484
1485 void dump_heap(void) {
1486         struct igheap *thisheap;
1487
1488         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1489                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1490                         thisheap->file, thisheap->line);
1491         }
1492 }
1493
1494 #endif /*  DEBUG_MEMORY_LEAKS */