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