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