1d24919c7ac02c042629948a5701b2ffb664f3a5
[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
575         if (CC->redirect_buffer != NULL) {
576                 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
577                         CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
578                         CC->redirect_buffer = realloc(CC->redirect_buffer,
579                                                 CC->redirect_alloc);
580                 }
581                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
582                 CC->redirect_len += nbytes;
583                 CC->redirect_buffer[CC->redirect_len] = 0;
584                 return;
585         }
586
587 #ifndef HAVE_TCP_BUFFERING
588         /* If we're buffering for later, do that now. */
589         if (CC->buffering) {
590                 old_buffer_len = CC->buffer_len;
591                 CC->buffer_len += nbytes;
592                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
593                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
594                 return;
595         }
596 #endif
597
598         /* Ok, at this point we're not buffering.  Go ahead and write. */
599
600 #ifdef HAVE_OPENSSL
601         if (CC->redirect_ssl) {
602                 client_write_ssl(buf, nbytes);
603                 return;
604         }
605 #endif
606
607         while (bytes_written < nbytes) {
608                 retval = write(CC->client_socket, &buf[bytes_written],
609                         nbytes - bytes_written);
610                 if (retval < 1) {
611                         lprintf(CTDL_ERR,
612                                 "client_write(%d bytes) failed: %s (%d)\n",
613                                 nbytes - bytes_written,
614                                 strerror(errno), errno);
615                         cit_backtrace();
616                         lprintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
617                         CC->kill_me = 1;
618                         return;
619                 }
620                 bytes_written = bytes_written + retval;
621         }
622 }
623
624
625 /*
626  * cprintf()  ...   Send formatted printable data to the client.   It is
627  *                implemented in terms of client_write() but remains in
628  *                sysdep.c in case we port to somewhere without va_args...
629  */
630 void cprintf(const char *format, ...) {   
631         va_list arg_ptr;   
632         char buf[1024];   
633    
634         va_start(arg_ptr, format);   
635         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
636                 buf[sizeof buf - 2] = '\n';
637         client_write(buf, strlen(buf)); 
638         va_end(arg_ptr);
639 }   
640
641
642 /*
643  * Read data from the client socket.
644  * Return values are:
645  *      1       Requested number of bytes has been read.
646  *      0       Request timed out.
647  *      -1      The socket is broken.
648  * If the socket breaks, the session will be terminated.
649  */
650 int client_read_to(char *buf, int bytes, int timeout)
651 {
652         int len,rlen;
653         fd_set rfds;
654         struct timeval tv;
655         int retval;
656
657 #ifdef HAVE_OPENSSL
658         if (CC->redirect_ssl) {
659                 return (client_read_ssl(buf, bytes, timeout));
660         }
661 #endif
662         len = 0;
663         while(len<bytes) {
664                 FD_ZERO(&rfds);
665                 FD_SET(CC->client_socket, &rfds);
666                 tv.tv_sec = timeout;
667                 tv.tv_usec = 0;
668
669                 retval = select( (CC->client_socket)+1, 
670                                         &rfds, NULL, NULL, &tv);
671
672                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
673                         return(0);
674                 }
675
676                 rlen = read(CC->client_socket, &buf[len], bytes-len);
677                 if (rlen<1) {
678                         /* The socket has been disconnected! */
679                         CC->kill_me = 1;
680                         return(-1);
681                 }
682                 len = len + rlen;
683         }
684         return(1);
685 }
686
687 /*
688  * Read data from the client socket with default timeout.
689  * (This is implemented in terms of client_read_to() and could be
690  * justifiably moved out of sysdep.c)
691  */
692 INLINE int client_read(char *buf, int bytes)
693 {
694         return(client_read_to(buf, bytes, config.c_sleeping));
695 }
696
697
698 /*
699  * client_getln()   ...   Get a LF-terminated line of text from the client.
700  * (This is implemented in terms of client_read() and could be
701  * justifiably moved out of sysdep.c)
702  */
703 int client_getln(char *buf, int bufsize)
704 {
705         int i, retval;
706
707         /* Read one character at a time.
708          */
709         for (i = 0;;i++) {
710                 retval = client_read(&buf[i], 1);
711                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
712                         break;
713         }
714
715         /* If we got a long line, discard characters until the newline.
716          */
717         if (i == (bufsize-1))
718                 while (buf[i] != '\n' && retval == 1)
719                         retval = client_read(&buf[i], 1);
720
721         /* Strip the trailing LF, and the trailing CR if present.
722          */
723         buf[i] = 0;
724         while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
725                 buf[strlen(buf)-1] = 0;
726         }
727         if (retval < 0) safestrncpy(buf, "000", bufsize);
728         return(retval);
729 }
730
731
732
733 /*
734  * The system-dependent part of master_cleanup() - close the master socket.
735  */
736 void sysdep_master_cleanup(void) {
737         struct ServiceFunctionHook *serviceptr;
738
739 /////   DestroyWorkerList();
740         /*
741          * close all protocol master sockets
742          */
743         for (serviceptr = ServiceHookTable; serviceptr != NULL;
744             serviceptr = serviceptr->next ) {
745
746                 if (serviceptr->tcp_port > 0)
747                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
748                                 serviceptr->tcp_port);
749
750                 if (serviceptr->sockpath != NULL)
751                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
752                                 serviceptr->sockpath);
753
754                 close(serviceptr->msock);
755
756                 /* If it's a Unix domain socket, remove the file. */
757                 if (serviceptr->sockpath != NULL) {
758                         unlink(serviceptr->sockpath);
759                 }
760         }
761 #ifdef HAVE_OPENSSL
762         destruct_ssl();
763 #endif
764         serv_calendar_destroy();
765         CtdlDestroyProtoHooks();
766         CtdlDestroyDeleteHooks();
767         CtdlDestroyXmsgHooks();
768         CtdlDestroyNetprocHooks();
769         CtdlDestroyUserHooks();
770         CtdlDestroyMessageHook();
771         CtdlDestroyCleanupHooks();
772         CtdlDestroyFixedOutputHooks();  
773         CtdlDestroySessionHooks();
774         CtdlDestroyServiceHook();
775         #ifdef HAVE_BACKTRACE
776         eCrash_Uninit();
777         #endif
778 }
779
780
781
782
783 /*
784  * Terminate another session.
785  * (This could justifiably be moved out of sysdep.c because it
786  * no longer does anything that is system-dependent.)
787  */
788 void kill_session(int session_to_kill) {
789         struct CitContext *ptr;
790
791         begin_critical_section(S_SESSION_TABLE);
792         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
793                 if (ptr->cs_pid == session_to_kill) {
794                         ptr->kill_me = 1;
795                 }
796         }
797         end_critical_section(S_SESSION_TABLE);
798 }
799
800 pid_t current_child;
801 void graceful_shutdown(int signum) {
802         kill(current_child, signum);
803         unlink(file_pid_file);
804         exit(0);
805 }
806
807
808 /*
809  * Start running as a daemon.
810  */
811 void start_daemon(int unused) {
812         int status = 0;
813         pid_t child = 0;
814         FILE *fp;
815         int do_restart = 0;
816
817         current_child = 0;
818
819         /* Close stdin/stdout/stderr and replace them with /dev/null.
820          * We don't just call close() because we don't want these fd's
821          * to be reused for other files.
822          */
823         chdir(ctdl_run_dir);
824
825         child = fork();
826         if (child != 0) {
827                 exit(0);
828         }
829         
830         signal(SIGHUP, SIG_IGN);
831         signal(SIGINT, SIG_IGN);
832         signal(SIGQUIT, SIG_IGN);
833
834         setsid();
835         umask(0);
836         freopen("/dev/null", "r", stdin);
837         freopen("/dev/null", "w", stdout);
838         freopen("/dev/null", "w", stderr);
839
840         do {
841                 current_child = fork();
842
843                 signal(SIGTERM, graceful_shutdown);
844         
845                 if (current_child < 0) {
846                         perror("fork");
847                         exit(errno);
848                 }
849         
850                 else if (current_child == 0) {
851                         return; /* continue starting citadel. */
852                 }
853         
854                 else {
855                         fp = fopen(file_pid_file, "w");
856                         if (fp != NULL) {
857                                 fprintf(fp, ""F_PID_T"\n", child);
858                                 fclose(fp);
859                         }
860                         waitpid(current_child, &status, 0);
861                 }
862
863                 do_restart = 0;
864
865                 /* Did the main process exit with an actual exit code? */
866                 if (WIFEXITED(status)) {
867
868                         /* Exit code 0 means the watcher should exit */
869                         if (WEXITSTATUS(status) == 0) {
870                                 do_restart = 0;
871                         }
872
873                         /* Exit code 101-109 means the watcher should exit */
874                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
875                                 do_restart = 0;
876                         }
877
878                         /* Any other exit code means we should restart. */
879                         else {
880                                 do_restart = 1;
881                         }
882                 }
883
884                 /* Any other type of termination (signals, etc.) should also restart. */
885                 else {
886                         do_restart = 1;
887                 }
888
889         } while (do_restart);
890
891         unlink(file_pid_file);
892         exit(WEXITSTATUS(status));
893 }
894
895
896
897 /*
898  * Generic routine to convert a login name to a full name (gecos)
899  * Returns nonzero if a conversion took place
900  */
901 int convert_login(char NameToConvert[]) {
902         struct passwd *pw;
903         int a;
904
905         pw = getpwnam(NameToConvert);
906         if (pw == NULL) {
907                 return(0);
908         }
909         else {
910                 strcpy(NameToConvert, pw->pw_gecos);
911                 for (a=0; a<strlen(NameToConvert); ++a) {
912                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
913                 }
914                 return(1);
915         }
916 }
917
918 struct worker_node *worker_list = NULL;
919
920
921 /*
922  * create a worker thread. this function must always be called from within
923  * an S_WORKER_LIST critical section!
924  */
925 void create_worker(void) {
926         int ret;
927         struct worker_node *n;
928         pthread_attr_t attr;
929
930         n = malloc(sizeof(struct worker_node));
931         if (n == NULL) {
932                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
933                 time_to_die = -1;
934                 return;
935         }
936
937         if ((ret = pthread_attr_init(&attr))) {
938                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
939                 time_to_die = -1;
940                 return;
941         }
942
943         /* Our per-thread stacks need to be bigger than the default size,
944          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
945          * crashes on 64-bit Linux.
946          */
947         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
948                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
949                         strerror(ret));
950                 time_to_die = -1;
951                 pthread_attr_destroy(&attr);
952                 return;
953         }
954
955         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
956         {
957
958                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
959                         strerror(ret));
960         }
961
962         n->next = worker_list;
963         worker_list = n;
964         pthread_attr_destroy(&attr);
965 }
966
967 void DestroyWorkerList(void)
968 {
969         struct CitContext *ptr;         /* general-purpose utility pointer */
970         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
971
972         begin_critical_section(S_SESSION_TABLE);
973         ptr = ContextList;
974         while (ptr != NULL){
975                 /* Remove the session from the active list */
976                 rem = ptr->next;
977                 --num_sessions;
978                 
979                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
980                 end_critical_section(S_SESSION_TABLE);
981                 RemoveContext(ptr);
982                 begin_critical_section(S_SESSION_TABLE);
983                 free (ptr);
984                 ptr = rem;
985         }
986         end_critical_section(S_SESSION_TABLE);
987
988         struct worker_node *cur, *p;
989         cur = worker_list;
990         while (cur != NULL)
991         {
992                 p = cur->next;
993                 free (cur);
994                 cur = p;
995         }
996         worker_list = NULL;
997 }
998
999 /*
1000  * Create the maintenance threads and begin their operation.
1001  */
1002 void create_maintenance_threads(void) {
1003         int ret;
1004         pthread_attr_t attr;
1005
1006         if ((ret = pthread_attr_init(&attr))) {
1007                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1008                 time_to_die = -1;
1009                 return;
1010         }
1011
1012         /* Our per-thread stacks need to be bigger than the default size,
1013          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1014          * crashes on 64-bit Linux.
1015          */
1016         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1017                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1018                         strerror(ret));
1019                 time_to_die = -1;
1020                 pthread_attr_destroy(&attr);
1021                 return;
1022         }
1023         
1024         struct MaintenanceThreadHook *fcn;
1025
1026         lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1027
1028         for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1029                 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1030                         lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1031                 }
1032                 else
1033                 {
1034                         lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1035                                 fcn->MaintenanceThread_tid);
1036                 }
1037         }
1038
1039
1040         pthread_attr_destroy(&attr);
1041 }
1042
1043
1044
1045 /*
1046  * Purge all sessions which have the 'kill_me' flag set.
1047  * This function has code to prevent it from running more than once every
1048  * few seconds, because running it after every single unbind would waste a lot
1049  * of CPU time and keep the context list locked too much.  To force it to run
1050  * anyway, set "force" to nonzero.
1051  *
1052  *
1053  * After that's done, we raise the size of the worker thread pool
1054  * if such an action is appropriate.
1055  */
1056 void dead_session_purge(int force) {
1057         struct CitContext *ptr;         /* general-purpose utility pointer */
1058         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1059
1060         if (force == 0) {
1061                 if ( (time(NULL) - last_purge) < 5 ) {
1062                         return; /* Too soon, go away */
1063                 }
1064         }
1065         time(&last_purge);
1066
1067         begin_critical_section(S_SESSION_TABLE);
1068         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1069                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1070
1071                         /* Remove the session from the active list */
1072                         if (ptr->prev) {
1073                                 ptr->prev->next = ptr->next;
1074                         }
1075                         else {
1076                                 ContextList = ptr->next;
1077                         }
1078                         if (ptr->next) {
1079                                 ptr->next->prev = ptr->prev;
1080                         }
1081
1082                         --num_sessions;
1083
1084                         /* And put it on our to-be-destroyed list */
1085                         ptr->next = rem;
1086                         rem = ptr;
1087
1088                 }
1089         }
1090         end_critical_section(S_SESSION_TABLE);
1091
1092         /* Now that we no longer have the session list locked, we can take
1093          * our time and destroy any sessions on the to-be-killed list, which
1094          * is allocated privately on this thread's stack.
1095          */
1096         while (rem != NULL) {
1097                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1098                 RemoveContext(rem);
1099                 ptr = rem;
1100                 rem = rem->next;
1101                 free(ptr);
1102         }
1103
1104         /* Raise the size of the worker thread pool if necessary. */
1105         if ( (num_sessions > num_threads)
1106            && (num_threads < config.c_max_workers) ) {
1107                 begin_critical_section(S_WORKER_LIST);
1108                 create_worker();
1109                 end_critical_section(S_WORKER_LIST);
1110         }
1111 }
1112
1113
1114
1115
1116
1117 /*
1118  * masterCC is the context we use when not attached to a session.  This
1119  * function initializes it.
1120  */
1121 void InitializeMasterCC(void) {
1122         memset(&masterCC, 0, sizeof(struct CitContext));
1123         masterCC.internal_pgm = 1;
1124         masterCC.cs_pid = 0;
1125 }
1126
1127
1128
1129
1130
1131
1132 /*
1133  * Bind a thread to a context.  (It's inline merely to speed things up.)
1134  */
1135 INLINE void become_session(struct CitContext *which_con) {
1136         pthread_setspecific(MyConKey, (void *)which_con );
1137 }
1138
1139
1140
1141 /* 
1142  * This loop just keeps going and going and going...
1143  */     
1144 void *worker_thread(void *arg) {
1145         int i;
1146         int highest;
1147         struct CitContext *ptr;
1148         struct CitContext *bind_me = NULL;
1149         fd_set readfds;
1150         int retval = 0;
1151         struct CitContext *con= NULL;   /* Temporary context pointer */
1152         struct ServiceFunctionHook *serviceptr;
1153         int ssock;                      /* Descriptor for client socket */
1154         struct timeval tv;
1155         int force_purge = 0;
1156         int m;
1157
1158         num_threads++;
1159
1160         cdb_allocate_tsd();
1161
1162         // Register for tracing
1163         #ifdef HAVE_BACKTRACE
1164         eCrash_RegisterThread("WorkerThread", 0);
1165         #endif
1166         while (!time_to_die) {
1167
1168                 /* make doubly sure we're not holding any stale db handles
1169                  * which might cause a deadlock.
1170                  */
1171                 cdb_check_handles();
1172 do_select:      force_purge = 0;
1173                 bind_me = NULL;         /* Which session shall we handle? */
1174
1175                 /* Initialize the fdset. */
1176                 FD_ZERO(&readfds);
1177                 highest = 0;
1178
1179                 begin_critical_section(S_SESSION_TABLE);
1180                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1181                         if (ptr->state == CON_IDLE) {
1182                                 FD_SET(ptr->client_socket, &readfds);
1183                                 if (ptr->client_socket > highest)
1184                                         highest = ptr->client_socket;
1185                         }
1186                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1187                                 bind_me = ptr;
1188                                 ptr->state = CON_EXECUTING;
1189                         }
1190                 }
1191                 end_critical_section(S_SESSION_TABLE);
1192
1193                 if (bind_me) {
1194                         goto SKIP_SELECT;
1195                 }
1196
1197                 /* If we got this far, it means that there are no sessions
1198                  * which a previous thread marked for attention, so we go
1199                  * ahead and get ready to select().
1200                  */
1201
1202                 /* First, add the various master sockets to the fdset. */
1203                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1204                 serviceptr = serviceptr->next ) {
1205                         m = serviceptr->msock;
1206                         FD_SET(m, &readfds);
1207                         if (m > highest) {
1208                                 highest = m;
1209                         }
1210                 }
1211
1212                 if (!time_to_die) {
1213                         tv.tv_sec = 1;          /* wake up every second if no input */
1214                         tv.tv_usec = 0;
1215                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1216                 }
1217
1218                 if (time_to_die) return(NULL);
1219
1220                 /* Now figure out who made this select() unblock.
1221                  * First, check for an error or exit condition.
1222                  */
1223                 if (retval < 0) {
1224                         if (errno == EBADF) {
1225                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1226                                         strerror(errno));
1227                                 goto do_select;
1228                         }
1229                         if (errno != EINTR) {
1230                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1231                                 time_to_die = 1;
1232                         } else if (!time_to_die)
1233                                 goto do_select;
1234                 }
1235
1236                 /* Next, check to see if it's a new client connecting
1237                  * on a master socket.
1238                  */
1239                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1240                      serviceptr = serviceptr->next ) {
1241
1242                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1243                                 ssock = accept(serviceptr->msock, NULL, 0);
1244                                 if (ssock >= 0) {
1245                                         lprintf(CTDL_DEBUG,
1246                                                 "New client socket %d\n",
1247                                                 ssock);
1248
1249                                         /* The master socket is non-blocking but the client
1250                                          * sockets need to be blocking, otherwise certain
1251                                          * operations barf on FreeBSD.  Not a fatal error.
1252                                          */
1253                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1254                                                 lprintf(CTDL_EMERG,
1255                                                         "citserver: Can't set socket to blocking: %s\n",
1256                                                         strerror(errno));
1257                                         }
1258
1259                                         /* New context will be created already
1260                                          * set up in the CON_EXECUTING state.
1261                                          */
1262                                         con = CreateNewContext();
1263
1264                                         /* Assign our new socket number to it. */
1265                                         con->client_socket = ssock;
1266                                         con->h_command_function =
1267                                                 serviceptr->h_command_function;
1268                                         con->h_async_function =
1269                                                 serviceptr->h_async_function;
1270                                         con->ServiceName =
1271                                                 serviceptr->ServiceName;
1272                                         
1273                                         /* Determine whether it's a local socket */
1274                                         if (serviceptr->sockpath != NULL)
1275                                                 con->is_local_socket = 1;
1276         
1277                                         /* Set the SO_REUSEADDR socket option */
1278                                         i = 1;
1279                                         setsockopt(ssock, SOL_SOCKET,
1280                                                 SO_REUSEADDR,
1281                                                 &i, sizeof(i));
1282
1283                                         become_session(con);
1284                                         begin_session(con);
1285                                         serviceptr->h_greeting_function();
1286                                         become_session(NULL);
1287                                         con->state = CON_IDLE;
1288                                         goto do_select;
1289                                 }
1290                         }
1291                 }
1292
1293                 /* It must be a client socket.  Find a context that has data
1294                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1295                  * active sockets other than our chosen one are marked as
1296                  * CON_READY so the next thread that comes around can just bind
1297                  * to one without having to select() again.
1298                  */
1299                 begin_critical_section(S_SESSION_TABLE);
1300                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1301                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1302                            && (ptr->state != CON_EXECUTING) ) {
1303                                 ptr->input_waiting = 1;
1304                                 if (!bind_me) {
1305                                         bind_me = ptr;  /* I choose you! */
1306                                         bind_me->state = CON_EXECUTING;
1307                                 }
1308                                 else {
1309                                         ptr->state = CON_READY;
1310                                 }
1311                         }
1312                 }
1313                 end_critical_section(S_SESSION_TABLE);
1314
1315 SKIP_SELECT:
1316                 /* We're bound to a session */
1317                 if (bind_me != NULL) {
1318                         become_session(bind_me);
1319
1320                         /* If the client has sent a command, execute it. */
1321                         if (CC->input_waiting) {
1322                                 CC->h_command_function();
1323                                 CC->input_waiting = 0;
1324                         }
1325
1326                         /* If there are asynchronous messages waiting and the
1327                          * client supports it, do those now */
1328                         if ((CC->is_async) && (CC->async_waiting)
1329                            && (CC->h_async_function != NULL)) {
1330                                 CC->h_async_function();
1331                                 CC->async_waiting = 0;
1332                         }
1333                         
1334                         force_purge = CC->kill_me;
1335                         become_session(NULL);
1336                         bind_me->state = CON_IDLE;
1337                 }
1338
1339                 dead_session_purge(force_purge);
1340                 do_housekeeping();
1341                 check_sched_shutdown();
1342         }
1343         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1344         /* If control reaches this point, the server is shutting down */        
1345         #ifdef HAVE_BACKTRACE
1346         eCrash_UnregisterThread();
1347         #endif
1348         return(NULL);
1349 }
1350
1351
1352
1353
1354 /*
1355  * SyslogFacility()
1356  * Translate text facility name to syslog.h defined value.
1357  */
1358 int SyslogFacility(char *name)
1359 {
1360         int i;
1361         struct
1362         {
1363                 int facility;
1364                 char *name;
1365         }   facTbl[] =
1366         {
1367                 {   LOG_KERN,   "kern"          },
1368                 {   LOG_USER,   "user"          },
1369                 {   LOG_MAIL,   "mail"          },
1370                 {   LOG_DAEMON, "daemon"        },
1371                 {   LOG_AUTH,   "auth"          },
1372                 {   LOG_SYSLOG, "syslog"        },
1373                 {   LOG_LPR,    "lpr"           },
1374                 {   LOG_NEWS,   "news"          },
1375                 {   LOG_UUCP,   "uucp"          },
1376                 {   LOG_LOCAL0, "local0"        },
1377                 {   LOG_LOCAL1, "local1"        },
1378                 {   LOG_LOCAL2, "local2"        },
1379                 {   LOG_LOCAL3, "local3"        },
1380                 {   LOG_LOCAL4, "local4"        },
1381                 {   LOG_LOCAL5, "local5"        },
1382                 {   LOG_LOCAL6, "local6"        },
1383                 {   LOG_LOCAL7, "local7"        },
1384                 {   0,            NULL          }
1385         };
1386         for(i = 0; facTbl[i].name != NULL; i++) {
1387                 if(!strcasecmp(name, facTbl[i].name))
1388                         return facTbl[i].facility;
1389         }
1390         enable_syslog = 0;
1391         return LOG_DAEMON;
1392 }
1393
1394
1395 /********** MEM CHEQQER ***********/
1396
1397 #ifdef DEBUG_MEMORY_LEAKS
1398
1399 #undef malloc
1400 #undef realloc
1401 #undef strdup
1402 #undef free
1403
1404 void *tracked_malloc(size_t size, char *file, int line) {
1405         struct igheap *thisheap;
1406         void *block;
1407
1408         block = malloc(size);
1409         if (block == NULL) return(block);
1410
1411         thisheap = malloc(sizeof(struct igheap));
1412         if (thisheap == NULL) {
1413                 free(block);
1414                 return(NULL);
1415         }
1416
1417         thisheap->block = block;
1418         strcpy(thisheap->file, file);
1419         thisheap->line = line;
1420         
1421         begin_critical_section(S_DEBUGMEMLEAKS);
1422         thisheap->next = igheap;
1423         igheap = thisheap;
1424         end_critical_section(S_DEBUGMEMLEAKS);
1425
1426         return(block);
1427 }
1428
1429
1430 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1431         struct igheap *thisheap;
1432         void *block;
1433
1434         block = realloc(ptr, size);
1435         if (block == NULL) return(block);
1436
1437         thisheap = malloc(sizeof(struct igheap));
1438         if (thisheap == NULL) {
1439                 free(block);
1440                 return(NULL);
1441         }
1442
1443         thisheap->block = block;
1444         strcpy(thisheap->file, file);
1445         thisheap->line = line;
1446         
1447         begin_critical_section(S_DEBUGMEMLEAKS);
1448         thisheap->next = igheap;
1449         igheap = thisheap;
1450         end_critical_section(S_DEBUGMEMLEAKS);
1451
1452         return(block);
1453 }
1454
1455
1456
1457 void tracked_free(void *ptr) {
1458         struct igheap *thisheap;
1459         struct igheap *trash;
1460
1461         free(ptr);
1462
1463         if (igheap == NULL) return;
1464         begin_critical_section(S_DEBUGMEMLEAKS);
1465         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1466                 if (thisheap->next != NULL) {
1467                         if (thisheap->next->block == ptr) {
1468                                 trash = thisheap->next;
1469                                 thisheap->next = thisheap->next->next;
1470                                 free(trash);
1471                         }
1472                 }
1473         }
1474         if (igheap->block == ptr) {
1475                 trash = igheap;
1476                 igheap = igheap->next;
1477                 free(trash);
1478         }
1479         end_critical_section(S_DEBUGMEMLEAKS);
1480 }
1481
1482 char *tracked_strdup(const char *s, char *file, int line) {
1483         char *ptr;
1484
1485         if (s == NULL) return(NULL);
1486         ptr = tracked_malloc(strlen(s) + 1, file, line);
1487         if (ptr == NULL) return(NULL);
1488         strncpy(ptr, s, strlen(s));
1489         return(ptr);
1490 }
1491
1492 void dump_heap(void) {
1493         struct igheap *thisheap;
1494
1495         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1496                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1497                         thisheap->file, thisheap->line);
1498         }
1499 }
1500
1501 #endif /*  DEBUG_MEMORY_LEAKS */