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