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