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