* Fixed a bug where sysdep.c fails to build if OpenSSL is not present
[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
379         actual_queue_len = queue_len;
380         if (actual_queue_len < 5) actual_queue_len = 5;
381
382         i = unlink(sockpath);
383         if ((i != 0) && (errno != ENOENT)) {
384                 *errormessage = (char*) malloc(SIZ + 1);
385                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
386                         sockpath, strerror(errno));
387                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
388                 return(-1);
389         }
390
391         memset(&addr, 0, sizeof(addr));
392         addr.sun_family = AF_UNIX;
393         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
394
395         s = socket(AF_UNIX, SOCK_STREAM, 0);
396         if (s < 0) {
397                 *errormessage = (char*) malloc(SIZ + 1);
398                 snprintf(*errormessage, SIZ, 
399                          "citserver: Can't create a socket: %s",
400                          strerror(errno));
401                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
402                 return(-1);
403         }
404
405         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
406                 *errormessage = (char*) malloc(SIZ + 1);
407                 snprintf(*errormessage, SIZ, 
408                          "citserver: Can't bind: %s",
409                          strerror(errno));
410                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
411                 return(-1);
412         }
413
414         /* set to nonblock - we need this for some obscure situations */
415         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
416                 *errormessage = (char*) malloc(SIZ + 1);
417                 snprintf(*errormessage, SIZ, 
418                          "citserver: Can't set socket to non-blocking: %s",
419                          strerror(errno));
420                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
421                 close(s);
422                 return(-1);
423         }
424
425         if (listen(s, actual_queue_len) < 0) {
426                 *errormessage = (char*) malloc(SIZ + 1);
427                 snprintf(*errormessage, SIZ, 
428                          "citserver: Can't listen: %s",
429                          strerror(errno));
430                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
431                 return(-1);
432         }
433
434         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
435         return(s);
436 }
437
438
439
440 /*
441  * Return a pointer to the CitContext structure bound to the thread which
442  * called this function.  If there's no such binding (for example, if it's
443  * called by the housekeeper thread) then a generic 'master' CC is returned.
444  *
445  * This function is used *VERY* frequently and must be kept small.
446  */
447 struct CitContext *MyContext(void) {
448
449         register struct CitContext *c;
450
451         return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
452                 c == NULL) ? &masterCC : c
453         );
454 }
455
456
457 /*
458  * Initialize a new context and place it in the list.  The session number
459  * used to be the PID (which is why it's called cs_pid), but that was when we
460  * had one process per session.  Now we just assign them sequentially, starting
461  * at 1 (don't change it to 0 because masterCC uses 0).
462  */
463 struct CitContext *CreateNewContext(void) {
464         struct CitContext *me;
465         static int next_pid = 0;
466
467         me = (struct CitContext *) malloc(sizeof(struct CitContext));
468         if (me == NULL) {
469                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
470                 return NULL;
471         }
472
473         memset(me, 0, sizeof(struct CitContext));
474         
475         /* Give the contaxt a name. Hopefully makes it easier to track */
476         strcpy (me->user.fullname, "SYS_notauth");
477         
478         /* The new context will be created already in the CON_EXECUTING state
479          * in order to prevent another thread from grabbing it while it's
480          * being set up.
481          */
482         me->state = CON_EXECUTING;
483         /*
484          * Generate a unique session number and insert this context into
485          * the list.
486          */
487         begin_critical_section(S_SESSION_TABLE);
488         me->cs_pid = ++next_pid;
489         me->prev = NULL;
490         me->next = ContextList;
491         ContextList = me;
492         if (me->next != NULL) {
493                 me->next->prev = me;
494         }
495         ++num_sessions;
496         end_critical_section(S_SESSION_TABLE);
497         return (me);
498 }
499
500
501 struct CitContext *CtdlGetContextArray(int *count)
502 {
503         int nContexts, i;
504         struct CitContext *nptr, *cptr;
505         
506         nContexts = num_sessions;
507         nptr = malloc(sizeof(struct CitContext) * nContexts);
508         if (!nptr)
509                 return NULL;
510         begin_critical_section(S_SESSION_TABLE);
511         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
512                 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
513         end_critical_section (S_SESSION_TABLE);
514         
515         *count = i;
516         return nptr;
517 }
518
519
520
521 /**
522  * This function fills in a context and its user field correctly
523  * Then creates/loads that user
524  */
525 void CtdlFillSystemContext(struct CitContext *context, char *name)
526 {
527         char sysname[USERNAME_SIZE];
528
529         memset(context, 0, sizeof(struct CitContext));
530         context->internal_pgm = 1;
531         context->cs_pid = 0;
532         strcpy (sysname, "SYS_");
533         strcat (sysname, name);
534         /* internal_create_user has the side effect of loading the user regardless of wether they
535          * already existed or needed to be created
536          */
537         internal_create_user (sysname, &(context->user), -1) ;
538         
539         /* Check to see if the system user needs upgrading */
540         if (context->user.usernum == 0)
541         {       /* old system user with number 0, upgrade it */
542                 context->user.usernum = get_new_user_number();
543                 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
544                 /* add user to the database */
545                 putuser(&(context->user));
546                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
547         }
548 }
549
550 /*
551  * The following functions implement output buffering on operating systems which
552  * support it (such as Linux and various BSD flavors).
553  */
554 #ifndef HAVE_DARWIN
555 #ifdef TCP_CORK
556 #       define HAVE_TCP_BUFFERING
557 #else
558 #       ifdef TCP_NOPUSH
559 #               define HAVE_TCP_BUFFERING
560 #               define TCP_CORK TCP_NOPUSH
561 #       endif
562 #endif /* TCP_CORK */
563 #endif /* HAVE_DARWIN */
564
565 static unsigned on = 1, off = 0;
566
567 void buffer_output(void) {
568 #ifdef HAVE_TCP_BUFFERING
569 #ifdef HAVE_OPENSSL
570         if (!CC->redirect_ssl)
571 #endif
572                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
573 #endif
574 }
575
576 void unbuffer_output(void) {
577 #ifdef HAVE_TCP_BUFFERING
578 #ifdef HAVE_OPENSSL
579         if (!CC->redirect_ssl)
580 #endif
581                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
582 #endif
583 }
584
585 void flush_output(void) {
586 #ifdef HAVE_TCP_BUFFERING
587         struct CitContext *CCC = CC;
588         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
589         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
590 #endif
591 }
592
593
594
595 /*
596  * client_write()   ...    Send binary data to the client.
597  */
598 int client_write(char *buf, int nbytes)
599 {
600         int bytes_written = 0;
601         int retval;
602 #ifndef HAVE_TCP_BUFFERING
603         int old_buffer_len = 0;
604 #endif
605         fd_set wset;
606         t_context *Ctx;
607         int fdflags;
608
609         Ctx = CC;
610         if (Ctx->redirect_buffer != NULL) {
611                 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
612                         Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
613                         Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
614                                                 Ctx->redirect_alloc);
615                 }
616                 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
617                 Ctx->redirect_len += nbytes;
618                 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
619                 return 0;
620         }
621
622 #ifdef HAVE_OPENSSL
623         if (Ctx->redirect_ssl) {
624                 client_write_ssl(buf, nbytes);
625                 return 0;
626         }
627 #endif
628
629         fdflags = fcntl(Ctx->client_socket, F_GETFL);
630
631         while (bytes_written < nbytes) {
632                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
633                         FD_ZERO(&wset);
634                         FD_SET(Ctx->client_socket, &wset);
635                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
636                                 CtdlLogPrintf(CTDL_ERR,
637                                         "client_write(%d bytes) select failed: %s (%d)\n",
638                                         nbytes - bytes_written,
639                                         strerror(errno), errno);
640                                 cit_backtrace();
641                                 Ctx->kill_me = 1;
642                                 return -1;
643                         }
644                 }
645
646                 retval = write(Ctx->client_socket, &buf[bytes_written],
647                         nbytes - bytes_written);
648                 if (retval < 1) {
649                         CtdlLogPrintf(CTDL_ERR,
650                                 "client_write(%d bytes) failed: %s (%d)\n",
651                                 nbytes - bytes_written,
652                                 strerror(errno), errno);
653                         cit_backtrace();
654                         // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
655                         Ctx->kill_me = 1;
656                         return -1;
657                 }
658                 bytes_written = bytes_written + retval;
659         }
660         return 0;
661 }
662
663
664 /*
665  * cprintf()    Send formatted printable data to the client.
666  *              Implemented in terms of client_write() so it's technically not sysdep...
667  */
668 void cprintf(const char *format, ...) {   
669         va_list arg_ptr;   
670         char buf[1024];
671    
672         va_start(arg_ptr, format);   
673         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
674                 buf[sizeof buf - 2] = '\n';
675         client_write(buf, strlen(buf)); 
676         va_end(arg_ptr);
677 }   
678
679
680 /*
681  * Read data from the client socket.
682  * Return values are:
683  *      1       Requested number of bytes has been read.
684  *      0       Request timed out.
685  *      -1      The socket is broken.
686  * If the socket breaks, the session will be terminated.
687  */
688 int client_read_to(char *buf, int bytes, int timeout)
689 {
690         int len,rlen;
691         fd_set rfds;
692         int fd;
693         struct timeval tv;
694         int retval;
695
696 #ifdef HAVE_OPENSSL
697         if (CC->redirect_ssl) {
698                 return (client_read_ssl(buf, bytes, timeout));
699         }
700 #endif
701         len = 0;
702         fd = CC->client_socket;
703         while(len<bytes) {
704                 FD_ZERO(&rfds);
705                 FD_SET(fd, &rfds);
706                 tv.tv_sec = timeout;
707                 tv.tv_usec = 0;
708
709                 retval = select( (fd)+1, 
710                                  &rfds, NULL, NULL, &tv);
711                 if (retval < 0)
712                 {
713                         if (errno == EINTR)
714                         {
715                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
716                                 CC->kill_me = 1;
717                                 return (-1);
718                         }
719                 }
720
721                 if (FD_ISSET(fd, &rfds) == 0) {
722                         return(0);
723                 }
724
725                 rlen = read(fd, &buf[len], bytes-len);
726                 if (rlen<1) {
727                         /* The socket has been disconnected! */
728                         CC->kill_me = 1;
729                         return(-1);
730                 }
731                 len = len + rlen;
732         }
733         return(1);
734 }
735
736 /*
737  * Read data from the client socket with default timeout.
738  * (This is implemented in terms of client_read_to() and could be
739  * justifiably moved out of sysdep.c)
740  */
741 INLINE int client_read(char *buf, int bytes)
742 {
743         return(client_read_to(buf, bytes, config.c_sleeping));
744 }
745
746
747 /*
748  * client_getln()   ...   Get a LF-terminated line of text from the client.
749  * (This is implemented in terms of client_read() and could be
750  * justifiably moved out of sysdep.c)
751  */
752 int client_getln(char *buf, int bufsize)
753 {
754         int i, retval;
755
756         /* Read one character at a time.
757          */
758         for (i = 0;;i++) {
759                 retval = client_read(&buf[i], 1);
760                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
761                         break;
762         }
763
764         /* If we got a long line, discard characters until the newline.
765          */
766         if (i == (bufsize-1))
767                 while (buf[i] != '\n' && retval == 1)
768                         retval = client_read(&buf[i], 1);
769
770         /* Strip the trailing LF, and the trailing CR if present.
771          */
772         buf[i] = 0;
773         while ( (i > 0)
774                 && ( (buf[i - 1]==13)
775                      || ( buf[i - 1]==10)) ) {
776                 i--;
777                 buf[i] = 0;
778         }
779         if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
780         return(retval);
781 }
782
783
784 /*
785  * Cleanup any contexts that are left lying around
786  */
787 void context_cleanup(void)
788 {
789         struct CitContext *ptr = NULL;
790         struct CitContext *rem = NULL;
791
792         /*
793          * Clean up the contexts.
794          * There are no threads so no critical_section stuff is needed.
795          */
796         ptr = ContextList;
797         
798         /* We need to update the ContextList because some modules may want to itterate it
799          * Question is should we NULL it before iterating here or should we just keep updating it
800          * as we remove items?
801          *
802          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
803          */
804         ContextList=NULL;
805         while (ptr != NULL){
806                 /* Remove the session from the active list */
807                 rem = ptr->next;
808                 --num_sessions;
809                 
810                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
811                 RemoveContext(ptr);
812                 free (ptr);
813                 ptr = rem;
814         }
815 }
816
817
818
819 void close_masters (void)
820 {
821         struct ServiceFunctionHook *serviceptr;
822         
823         /*
824          * close all protocol master sockets
825          */
826         for (serviceptr = ServiceHookTable; serviceptr != NULL;
827             serviceptr = serviceptr->next ) {
828
829                 if (serviceptr->tcp_port > 0)
830                 {
831                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
832                                 serviceptr->tcp_port);
833                         serviceptr->tcp_port = 0;
834                 }
835                 
836                 if (serviceptr->sockpath != NULL)
837                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
838                                 serviceptr->sockpath);
839
840                 close(serviceptr->msock);
841                 /* If it's a Unix domain socket, remove the file. */
842                 if (serviceptr->sockpath != NULL) {
843                         unlink(serviceptr->sockpath);
844                         serviceptr->sockpath = NULL;
845                 }
846         }
847 }
848
849
850 /*
851  * The system-dependent part of master_cleanup() - close the master socket.
852  */
853 void sysdep_master_cleanup(void) {
854         
855         close_masters();
856         
857         context_cleanup();
858         
859 #ifdef HAVE_OPENSSL
860         destruct_ssl();
861 #endif
862         CtdlDestroyProtoHooks();
863         CtdlDestroyDeleteHooks();
864         CtdlDestroyXmsgHooks();
865         CtdlDestroyNetprocHooks();
866         CtdlDestroyUserHooks();
867         CtdlDestroyMessageHook();
868         CtdlDestroyCleanupHooks();
869         CtdlDestroyFixedOutputHooks();  
870         CtdlDestroySessionHooks();
871         CtdlDestroyServiceHook();
872         CtdlDestroyRoomHooks();
873         CtdlDestroyDirectoryServiceFuncs();
874         #ifdef HAVE_BACKTRACE
875         eCrash_Uninit();
876         #endif
877 }
878
879
880
881 /*
882  * Terminate another session.
883  * (This could justifiably be moved out of sysdep.c because it
884  * no longer does anything that is system-dependent.)
885  */
886 void kill_session(int session_to_kill) {
887         struct CitContext *ptr;
888
889         begin_critical_section(S_SESSION_TABLE);
890         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
891                 if (ptr->cs_pid == session_to_kill) {
892                         ptr->kill_me = 1;
893                 }
894         }
895         end_critical_section(S_SESSION_TABLE);
896 }
897
898 pid_t current_child;
899 void graceful_shutdown(int signum) {
900         kill(current_child, signum);
901         unlink(file_pid_file);
902         exit(0);
903 }
904
905 int nFireUps = 0;
906 int nFireUpsNonRestart = 0;
907 pid_t ForkedPid = 1;
908
909 /*
910  * Start running as a daemon.
911  */
912 void start_daemon(int unused) {
913         int status = 0;
914         pid_t child = 0;
915         FILE *fp;
916         int do_restart = 0;
917
918         current_child = 0;
919
920         /* Close stdin/stdout/stderr and replace them with /dev/null.
921          * We don't just call close() because we don't want these fd's
922          * to be reused for other files.
923          */
924         chdir(ctdl_run_dir);
925
926         child = fork();
927         if (child != 0) {
928                 exit(0);
929         }
930         
931         signal(SIGHUP, SIG_IGN);
932         signal(SIGINT, SIG_IGN);
933         signal(SIGQUIT, SIG_IGN);
934
935         setsid();
936         umask(0);
937         freopen("/dev/null", "r", stdin);
938         freopen("/dev/null", "w", stdout);
939         freopen("/dev/null", "w", stderr);
940
941         do {
942                 current_child = fork();
943
944                 signal(SIGTERM, graceful_shutdown);
945         
946                 if (current_child < 0) {
947                         perror("fork");
948                         exit(errno);
949                 }
950         
951                 else if (current_child == 0) {
952                         return; /* continue starting citadel. */
953                 }
954         
955                 else {
956                         fp = fopen(file_pid_file, "w");
957                         if (fp != NULL) {
958                                 fprintf(fp, ""F_PID_T"\n", getpid());
959                                 fclose(fp);
960                         }
961                         waitpid(current_child, &status, 0);
962                 }
963                 do_restart = 0;
964                 nFireUpsNonRestart = nFireUps;
965                 
966                 /* Exit code 0 means the watcher should exit */
967                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
968                         do_restart = 0;
969                 }
970
971                 /* Exit code 101-109 means the watcher should exit */
972                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
973                         do_restart = 0;
974                 }
975
976                 /* Any other exit code, or no exit code, means we should restart. */
977                 else {
978                         do_restart = 1;
979                         nFireUps++;
980                         ForkedPid = current_child;
981                 }
982
983         } while (do_restart);
984
985         unlink(file_pid_file);
986         exit(WEXITSTATUS(status));
987 }
988
989
990
991 void checkcrash(void)
992 {
993         if (nFireUpsNonRestart != nFireUps)
994         {
995                 StrBuf *CrashMail;
996
997                 CrashMail = NewStrBuf();
998                 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
999                 StrBufPrintf(CrashMail, 
1000                         " \n"
1001                         " The Citadel server process (citserver) terminated unexpectedly."
1002                         "\n \n"
1003                         " This could be the result of a bug in the server program, or some external "
1004                         "factor.  You can obtain more information about this by enabling core dumps. "
1005                         "For more information, please see: "
1006                         "http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1007                         "\n \n"
1008                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
1009                         ,
1010                         ctdl_run_dir, ForkedPid);
1011                 aide_message(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1012                 FreeStrBuf(&CrashMail);
1013         }
1014 }
1015
1016
1017 /*
1018  * Generic routine to convert a login name to a full name (gecos)
1019  * Returns nonzero if a conversion took place
1020  */
1021 int convert_login(char NameToConvert[]) {
1022         struct passwd *pw;
1023         int a;
1024
1025         pw = getpwnam(NameToConvert);
1026         if (pw == NULL) {
1027                 return(0);
1028         }
1029         else {
1030                 strcpy(NameToConvert, pw->pw_gecos);
1031                 for (a=0; a<strlen(NameToConvert); ++a) {
1032                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1033                 }
1034                 return(1);
1035         }
1036 }
1037
1038 /*
1039  * Purge all sessions which have the 'kill_me' flag set.
1040  * This function has code to prevent it from running more than once every
1041  * few seconds, because running it after every single unbind would waste a lot
1042  * of CPU time and keep the context list locked too much.  To force it to run
1043  * anyway, set "force" to nonzero.
1044  */
1045 void dead_session_purge(int force) {
1046         struct CitContext *ptr, *ptr2;          /* general-purpose utility pointer */
1047         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1048         
1049         if (force == 0) {
1050                 if ( (time(NULL) - last_purge) < 5 ) {
1051                         return; /* Too soon, go away */
1052                 }
1053         }
1054         time(&last_purge);
1055
1056         if (try_critical_section(S_SESSION_TABLE))
1057                 return;
1058                 
1059         ptr = ContextList;
1060         while (ptr) {
1061                 ptr2 = ptr;
1062                 ptr = ptr->next;
1063                 
1064                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1065                         /* Remove the session from the active list */
1066                         if (ptr2->prev) {
1067                                 ptr2->prev->next = ptr2->next;
1068                         }
1069                         else {
1070                                 ContextList = ptr2->next;
1071                         }
1072                         if (ptr2->next) {
1073                                 ptr2->next->prev = ptr2->prev;
1074                         }
1075
1076                         --num_sessions;
1077                         /* And put it on our to-be-destroyed list */
1078                         ptr2->next = rem;
1079                         rem = ptr2;
1080                 }
1081         }
1082         end_critical_section(S_SESSION_TABLE);
1083
1084         /* Now that we no longer have the session list locked, we can take
1085          * our time and destroy any sessions on the to-be-killed list, which
1086          * is allocated privately on this thread's stack.
1087          */
1088         while (rem != NULL) {
1089                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1090                 RemoveContext(rem);
1091                 ptr = rem;
1092                 rem = rem->next;
1093                 free(ptr);
1094         }
1095 }
1096
1097
1098
1099
1100
1101 /*
1102  * masterCC is the context we use when not attached to a session.  This
1103  * function initializes it.
1104  */
1105 void InitializeMasterCC(void) {
1106         memset(&masterCC, 0, sizeof(struct CitContext));
1107         masterCC.internal_pgm = 1;
1108         masterCC.cs_pid = 0;
1109 }
1110
1111
1112
1113
1114 /*
1115  * Bind a thread to a context.  (It's inline merely to speed things up.)
1116  */
1117 INLINE void become_session(struct CitContext *which_con) {
1118         citthread_setspecific(MyConKey, (void *)which_con );
1119 }
1120
1121
1122
1123 /* 
1124  * This loop just keeps going and going and going...
1125  */
1126 /*
1127  * FIXME:
1128  * This current implimentation of worker_thread creates a bottle neck in several situations
1129  * The first thing to remember is that a single thread can handle more than one connection at a time.
1130  * More threads mean less memory for the system to run in.
1131  * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1132  * something to happen anywhere.
1133  * This current implimentation requires worker threads to wait in other locations, after it has
1134  * been committed to a single connection which is very wasteful.
1135  * As an extreme case consider this:
1136  * A slow client connects and this slow client sends only one character each second.
1137  * With this current implimentation a single worker thread is dispatched to handle that connection
1138  * until such times as the client timeout expires, an error occurs on the socket or the client
1139  * completes its transmission.
1140  * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1141  * second interval between chars.
1142  *
1143  * It is my intention to re-write this code and the associated client_getln, client_read functions
1144  * to allow any thread to read data on behalf of any connection (context).
1145  * To do this I intend to have this main loop read chars into a buffer stored in the context.
1146  * Once the correct criteria for a full buffer is met then we will dispatch a thread to 
1147  * process it.
1148  * This worker thread loop also needs to be able to handle binary data.
1149  */
1150  
1151 void *worker_thread(void *arg) {
1152         int i;
1153         int highest;
1154         struct CitContext *ptr;
1155         struct CitContext *bind_me = NULL;
1156         fd_set readfds;
1157         int retval = 0;
1158         struct CitContext *con= NULL;   /* Temporary context pointer */
1159         struct ServiceFunctionHook *serviceptr;
1160         int ssock;                      /* Descriptor for client socket */
1161         struct timeval tv;
1162         int force_purge = 0;
1163         int m;
1164         
1165
1166         while (!CtdlThreadCheckStop()) {
1167
1168                 /* make doubly sure we're not holding any stale db handles
1169                  * which might cause a deadlock.
1170                  */
1171                 cdb_check_handles();
1172 do_select:      force_purge = 0;
1173                 bind_me = NULL;         /* Which session shall we handle? */
1174
1175                 /* Initialize the fdset. */
1176                 FD_ZERO(&readfds);
1177                 highest = 0;
1178
1179                 begin_critical_section(S_SESSION_TABLE);
1180                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1181                         if (ptr->state == CON_IDLE) {
1182                                 FD_SET(ptr->client_socket, &readfds);
1183                                 if (ptr->client_socket > highest)
1184                                         highest = ptr->client_socket;
1185                         }
1186                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1187                                 bind_me = ptr;
1188                                 ptr->state = CON_EXECUTING;
1189                         }
1190                 }
1191                 end_critical_section(S_SESSION_TABLE);
1192
1193                 if (bind_me) {
1194                         goto SKIP_SELECT;
1195                 }
1196
1197                 /* If we got this far, it means that there are no sessions
1198                  * which a previous thread marked for attention, so we go
1199                  * ahead and get ready to select().
1200                  */
1201
1202                 /* First, add the various master sockets to the fdset. */
1203                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1204                 serviceptr = serviceptr->next ) {
1205                         m = serviceptr->msock;
1206                         FD_SET(m, &readfds);
1207                         if (m > highest) {
1208                                 highest = m;
1209                         }
1210                 }
1211
1212                 if (!CtdlThreadCheckStop()) {
1213                         tv.tv_sec = 1;          /* wake up every second if no input */
1214                         tv.tv_usec = 0;
1215                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1216                 }
1217                 else
1218                         return NULL;
1219
1220                 /* Now figure out who made this select() unblock.
1221                  * First, check for an error or exit condition.
1222                  */
1223                 if (retval < 0) {
1224                         if (errno == EBADF) {
1225                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1226                                         strerror(errno));
1227                                 goto do_select;
1228                         }
1229                         if (errno != EINTR) {
1230                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1231                                 CtdlThreadStopAll();
1232                         } else {
1233                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1234                                 if (CtdlThreadCheckStop()) return(NULL);
1235                                 goto do_select;
1236                         }
1237                 }
1238                 else if(retval == 0) {
1239                         if (CtdlThreadCheckStop()) return(NULL);
1240                         goto SKIP_SELECT;
1241                 }
1242                 /* Next, check to see if it's a new client connecting
1243                  * on a master socket.
1244                  */
1245                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1246                      serviceptr = serviceptr->next ) {
1247
1248                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1249                                 ssock = accept(serviceptr->msock, NULL, 0);
1250                                 if (ssock >= 0) {
1251                                         CtdlLogPrintf(CTDL_DEBUG,
1252                                                 "New client socket %d\n",
1253                                                 ssock);
1254
1255                                         /* The master socket is non-blocking but the client
1256                                          * sockets need to be blocking, otherwise certain
1257                                          * operations barf on FreeBSD.  Not a fatal error.
1258                                          */
1259                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1260                                                 CtdlLogPrintf(CTDL_EMERG,
1261                                                         "citserver: Can't set socket to blocking: %s\n",
1262                                                         strerror(errno));
1263                                         }
1264
1265                                         /* New context will be created already
1266                                          * set up in the CON_EXECUTING state.
1267                                          */
1268                                         con = CreateNewContext();
1269
1270                                         /* Assign our new socket number to it. */
1271                                         con->client_socket = ssock;
1272                                         con->h_command_function =
1273                                                 serviceptr->h_command_function;
1274                                         con->h_async_function =
1275                                                 serviceptr->h_async_function;
1276                                         con->ServiceName =
1277                                                 serviceptr->ServiceName;
1278                                         
1279                                         /* Determine whether it's a local socket */
1280                                         if (serviceptr->sockpath != NULL)
1281                                                 con->is_local_socket = 1;
1282         
1283                                         /* Set the SO_REUSEADDR socket option */
1284                                         i = 1;
1285                                         setsockopt(ssock, SOL_SOCKET,
1286                                                 SO_REUSEADDR,
1287                                                 &i, sizeof(i));
1288
1289                                         become_session(con);
1290                                         begin_session(con);
1291                                         serviceptr->h_greeting_function();
1292                                         become_session(NULL);
1293                                         con->state = CON_IDLE;
1294                                         goto do_select;
1295                                 }
1296                         }
1297                 }
1298
1299                 /* It must be a client socket.  Find a context that has data
1300                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1301                  * active sockets other than our chosen one are marked as
1302                  * CON_READY so the next thread that comes around can just bind
1303                  * to one without having to select() again.
1304                  */
1305                 begin_critical_section(S_SESSION_TABLE);
1306                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1307                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1308                            && (ptr->state != CON_EXECUTING) ) {
1309                                 ptr->input_waiting = 1;
1310                                 if (!bind_me) {
1311                                         bind_me = ptr;  /* I choose you! */
1312                                         bind_me->state = CON_EXECUTING;
1313                                 }
1314                                 else {
1315                                         ptr->state = CON_READY;
1316                                 }
1317                         }
1318                 }
1319                 end_critical_section(S_SESSION_TABLE);
1320
1321 SKIP_SELECT:
1322                 /* We're bound to a session */
1323                 if (bind_me != NULL) {
1324                         become_session(bind_me);
1325
1326                         /* If the client has sent a command, execute it. */
1327                         if (CC->input_waiting) {
1328                                 CC->h_command_function();
1329                                 CC->input_waiting = 0;
1330                         }
1331
1332                         /* If there are asynchronous messages waiting and the
1333                          * client supports it, do those now */
1334                         if ((CC->is_async) && (CC->async_waiting)
1335                            && (CC->h_async_function != NULL)) {
1336                                 CC->h_async_function();
1337                                 CC->async_waiting = 0;
1338                         }
1339                         
1340                         force_purge = CC->kill_me;
1341                         become_session(NULL);
1342                         bind_me->state = CON_IDLE;
1343                 }
1344
1345                 dead_session_purge(force_purge);
1346                 do_housekeeping();
1347         }
1348         /* If control reaches this point, the server is shutting down */        
1349         return(NULL);
1350 }
1351
1352
1353
1354
1355 /*
1356  * SyslogFacility()
1357  * Translate text facility name to syslog.h defined value.
1358  */
1359 int SyslogFacility(char *name)
1360 {
1361         int i;
1362         struct
1363         {
1364                 int facility;
1365                 char *name;
1366         }   facTbl[] =
1367         {
1368                 {   LOG_KERN,   "kern"          },
1369                 {   LOG_USER,   "user"          },
1370                 {   LOG_MAIL,   "mail"          },
1371                 {   LOG_DAEMON, "daemon"        },
1372                 {   LOG_AUTH,   "auth"          },
1373                 {   LOG_SYSLOG, "syslog"        },
1374                 {   LOG_LPR,    "lpr"           },
1375                 {   LOG_NEWS,   "news"          },
1376                 {   LOG_UUCP,   "uucp"          },
1377                 {   LOG_LOCAL0, "local0"        },
1378                 {   LOG_LOCAL1, "local1"        },
1379                 {   LOG_LOCAL2, "local2"        },
1380                 {   LOG_LOCAL3, "local3"        },
1381                 {   LOG_LOCAL4, "local4"        },
1382                 {   LOG_LOCAL5, "local5"        },
1383                 {   LOG_LOCAL6, "local6"        },
1384                 {   LOG_LOCAL7, "local7"        },
1385                 {   0,            NULL          }
1386         };
1387         for(i = 0; facTbl[i].name != NULL; i++) {
1388                 if(!strcasecmp(name, facTbl[i].name))
1389                         return facTbl[i].facility;
1390         }
1391         enable_syslog = 0;
1392         return LOG_DAEMON;
1393 }
1394
1395
1396 /********** MEM CHEQQER ***********/
1397
1398 #ifdef DEBUG_MEMORY_LEAKS
1399
1400 #undef malloc
1401 #undef realloc
1402 #undef strdup
1403 #undef free
1404
1405 void *tracked_malloc(size_t size, char *file, int line) {
1406         struct igheap *thisheap;
1407         void *block;
1408
1409         block = malloc(size);
1410         if (block == NULL) return(block);
1411
1412         thisheap = malloc(sizeof(struct igheap));
1413         if (thisheap == NULL) {
1414                 free(block);
1415                 return(NULL);
1416         }
1417
1418         thisheap->block = block;
1419         strcpy(thisheap->file, file);
1420         thisheap->line = line;
1421         
1422         begin_critical_section(S_DEBUGMEMLEAKS);
1423         thisheap->next = igheap;
1424         igheap = thisheap;
1425         end_critical_section(S_DEBUGMEMLEAKS);
1426
1427         return(block);
1428 }
1429
1430
1431 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1432         struct igheap *thisheap;
1433         void *block;
1434
1435         block = realloc(ptr, size);
1436         if (block == NULL) return(block);
1437
1438         thisheap = malloc(sizeof(struct igheap));
1439         if (thisheap == NULL) {
1440                 free(block);
1441                 return(NULL);
1442         }
1443
1444         thisheap->block = block;
1445         strcpy(thisheap->file, file);
1446         thisheap->line = line;
1447         
1448         begin_critical_section(S_DEBUGMEMLEAKS);
1449         thisheap->next = igheap;
1450         igheap = thisheap;
1451         end_critical_section(S_DEBUGMEMLEAKS);
1452
1453         return(block);
1454 }
1455
1456
1457
1458 void tracked_free(void *ptr) {
1459         struct igheap *thisheap;
1460         struct igheap *trash;
1461
1462         free(ptr);
1463
1464         if (igheap == NULL) return;
1465         begin_critical_section(S_DEBUGMEMLEAKS);
1466         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1467                 if (thisheap->next != NULL) {
1468                         if (thisheap->next->block == ptr) {
1469                                 trash = thisheap->next;
1470                                 thisheap->next = thisheap->next->next;
1471                                 free(trash);
1472                         }
1473                 }
1474         }
1475         if (igheap->block == ptr) {
1476                 trash = igheap;
1477                 igheap = igheap->next;
1478                 free(trash);
1479         }
1480         end_critical_section(S_DEBUGMEMLEAKS);
1481 }
1482
1483 char *tracked_strdup(const char *s, char *file, int line) {
1484         char *ptr;
1485
1486         if (s == NULL) return(NULL);
1487         ptr = tracked_malloc(strlen(s) + 1, file, line);
1488         if (ptr == NULL) return(NULL);
1489         strncpy(ptr, s, strlen(s));
1490         return(ptr);
1491 }
1492
1493 void dump_heap(void) {
1494         struct igheap *thisheap;
1495
1496         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1497                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1498                         thisheap->file, thisheap->line);
1499         }
1500 }
1501
1502 #endif /*  DEBUG_MEMORY_LEAKS */