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