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