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