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