* add possibility to specify the inbound buffer size
[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);                // intr = shutdown
217         // sigaddset(&set, SIGQUIT);            // quit = force quit
218         sigaddset(&set, SIGHUP);
219         sigaddset(&set, SIGTERM);
220         // sigaddset(&set, SIGSEGV);            // we want core dumps
221         // sigaddset(&set, SIGILL);             // we want core dumps
222         // sigaddset(&set, SIGBUS);
223         sigprocmask(SIG_UNBLOCK, &set, NULL);
224
225         signal(SIGINT, signal_cleanup);         // intr = shutdown
226         // signal(SIGQUIT, signal_cleanup);     // quit = force quit
227         signal(SIGHUP, signal_cleanup);
228         signal(SIGTERM, signal_cleanup);
229         signal(SIGUSR2, signal_exit);
230         // signal(SIGSEGV, signal_cleanup);     // we want coredumps
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                 if (retval < 0) {
577                         CtdlLogPrintf(CTDL_CRIT, 
578                                       "%s failed\n",
579                                       __FUNCTION__);
580                 }
581         }
582         else 
583 #endif
584         {
585                 retval = StrBufReadBLOBBuffered(Target, 
586                                                 CCC->ReadBuf,
587                                                 &CCC->Pos,
588                                                 &CCC->client_socket,
589                                                 1, 
590                                                 bytes,
591                                                 O_TERM,
592                                                 &Error);
593                 if (retval < 0) {
594                         CtdlLogPrintf(CTDL_CRIT, 
595                                       "%s failed: %s\n",
596                                       __FUNCTION__, 
597                                       Error);
598                         return retval;
599                 }
600                 else
601                 {
602 #ifdef BIGBAD_IODBG
603                         int rv = 0;
604                         char fn [SIZ];
605                         FILE *fd;
606                         
607                         snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
608                         
609                         fd = fopen(fn, "a+");
610                         fprintf(fd, "Read: BufSize: %d BufContent: [",
611                                 StrLength(Target));
612                         rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
613                         fprintf(fd, "]\n");
614                         
615                         
616                         fclose(fd);
617 #endif
618
619                 }
620         }
621         return retval;
622 }
623
624
625 /*
626  * to make client_read_random_blob() more efficient, increase buffer size.
627  * just use in greeting function, else your buffer may be flushed
628  */
629 void client_set_inbound_buf(long N)
630 {
631         FlushStrBuf(CC->ReadBuf);
632         ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
633 }
634
635 int client_read_random_blob(StrBuf *Target, int timeout)
636 {
637         CitContext *CCC=CC;
638         int rc;
639
640         rc =  client_read_blob(Target, 1, timeout);
641         if (rc > 0)
642         {
643                 long len;
644                 const char *pch;
645                 
646                 len = StrLength(CCC->ReadBuf);
647                 pch = ChrPtr(CCC->ReadBuf);
648
649                 if (len > 0)
650                 {
651                         if (CCC->Pos != NULL) {
652                                 len -= CCC->Pos - pch;
653                                 pch = CCC->Pos;
654                         }
655                         StrBufAppendBufPlain(Target, pch, len, 0);
656                         FlushStrBuf(CCC->ReadBuf);
657                         CCC->Pos = NULL;
658 #ifdef BIGBAD_IODBG
659                         {
660                                 int rv = 0;
661                                 char fn [SIZ];
662                                 FILE *fd;
663                         
664                                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
665                         
666                                 fd = fopen(fn, "a+");
667                                 fprintf(fd, "Read: BufSize: %d BufContent: [",
668                                         StrLength(Target));
669                                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
670                                 fprintf(fd, "]\n");
671                         
672                         
673                                 fclose(fd);
674                         }
675 #endif
676         
677                         return StrLength(Target);
678                 }
679                 return rc;
680         }
681         else
682                 return rc;
683 }
684
685 int client_read_to(char *buf, int bytes, int timeout)
686 {
687         CitContext *CCC=CC;
688         int rc;
689
690         rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
691         if (rc < 0)
692         {
693                 *buf = '\0';
694                 return rc;
695         }
696         else
697         {
698                 memcpy(buf, 
699                        ChrPtr(CCC->MigrateBuf),
700                        StrLength(CCC->MigrateBuf) + 1);
701                 FlushStrBuf(CCC->MigrateBuf);
702                 return rc;
703         }
704 }
705
706
707 int HaveMoreLinesWaiting(CitContext *CCC)
708 {
709         if ((CCC->kill_me == 1) || (
710             (CCC->Pos == NULL) && 
711             (StrLength(CCC->ReadBuf) == 0) && 
712             (CCC->client_socket != -1)) )
713                 return 0;
714         else
715                 return 1;
716 }
717
718
719 /*
720  * Read data from the client socket with default timeout.
721  * (This is implemented in terms of client_read_to() and could be
722  * justifiably moved out of sysdep.c)
723  */
724 INLINE int client_read(char *buf, int bytes)
725 {
726         return(client_read_to(buf, bytes, config.c_sleeping));
727 }
728
729 int CtdlClientGetLine(StrBuf *Target)
730 {
731         CitContext *CCC=CC;
732         const char *Error;
733         int rc;
734
735         FlushStrBuf(Target);
736 #ifdef HAVE_OPENSSL
737         if (CCC->redirect_ssl) {
738 #ifdef BIGBAD_IODBG
739                 char fn [SIZ];
740                 FILE *fd;
741                 int len = 0;
742                 int rlen = 0;
743                 int  nlen = 0;
744                 int nrlen = 0;
745                 const char *pch;
746
747                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
748
749                 fd = fopen(fn, "a+");
750                 pch = ChrPtr(CCC->ReadBuf);
751                 len = StrLength(CCC->ReadBuf);
752                 if (CCC->Pos != NULL)
753                         rlen = CC->Pos - pch;
754                 else
755                         rlen = 0;
756
757 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
758                         len, rlen, pch);
759 */
760                 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
761                         len, rlen);
762 #endif
763                 rc = client_readline_sslbuffer(Target,
764                                                CCC->ReadBuf,
765                                                &CCC->Pos,
766                                                1);
767 #ifdef BIGBAD_IODBG
768                 pch = ChrPtr(CCC->ReadBuf);
769                 nlen = StrLength(CCC->ReadBuf);
770                 if (CCC->Pos != NULL)
771                         nrlen = CC->Pos - pch;
772                 else
773                         nrlen = 0;
774 /*
775                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
776                         len, nlen, rlen, nrlen, pch);
777 */
778                 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
779                         len, nlen, rlen, nrlen);
780
781                 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
782                         StrLength(Target), ChrPtr(Target));
783                 fclose(fd);
784
785                 if (rc < 0)
786                         CtdlLogPrintf(CTDL_CRIT, 
787                                       "%s failed\n",
788                                       __FUNCTION__);
789 #endif
790                 return rc;
791         }
792         else 
793 #endif
794         {
795 #ifdef BIGBAD_IODBG
796                 char fn [SIZ];
797                 FILE *fd;
798                 int len, rlen, nlen, nrlen;
799                 const char *pch;
800
801                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
802
803                 fd = fopen(fn, "a+");
804                 pch = ChrPtr(CCC->ReadBuf);
805                 len = StrLength(CCC->ReadBuf);
806                 if (CCC->Pos != NULL)
807                         rlen = CC->Pos - pch;
808                 else
809                         rlen = 0;
810
811 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
812                         len, rlen, pch);
813 */
814                 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
815                         len, rlen);
816 #endif
817                 rc = StrBufTCP_read_buffered_line_fast(Target, 
818                                                        CCC->ReadBuf,
819                                                        &CCC->Pos,
820                                                        &CCC->client_socket,
821                                                        5,
822                                                        1,
823                                                        &Error);
824
825 #ifdef BIGBAD_IODBG
826                 pch = ChrPtr(CCC->ReadBuf);
827                 nlen = StrLength(CCC->ReadBuf);
828                 if (CCC->Pos != NULL)
829                         nrlen = CC->Pos - pch;
830                 else
831                         nrlen = 0;
832 /*
833                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
834                         len, nlen, rlen, nrlen, pch);
835 */
836                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
837                         len, nlen, rlen, nrlen);
838
839                 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
840                         StrLength(Target), ChrPtr(Target));
841                 fclose(fd);
842
843                 if ((rc < 0) && (Error != NULL))
844                         CtdlLogPrintf(CTDL_CRIT, 
845                                       "%s failed: %s\n",
846                                       __FUNCTION__,
847                                       Error);
848 #endif
849                 return rc;
850         }
851 }
852
853
854 /*
855  * client_getln()   ...   Get a LF-terminated line of text from the client.
856  * (This is implemented in terms of client_read() and could be
857  * justifiably moved out of sysdep.c)
858  */
859 int client_getln(char *buf, int bufsize)
860 {
861         int i, retval;
862         CitContext *CCC=CC;
863         const char *pCh;
864
865         retval = CtdlClientGetLine(CCC->MigrateBuf);
866         if (retval < 0)
867           return(retval >= 0);
868
869
870         i = StrLength(CCC->MigrateBuf);
871         pCh = ChrPtr(CCC->MigrateBuf);
872         /* Strip the trailing LF, and the trailing CR if present.
873          */
874         if (bufsize <= i)
875                 i = bufsize - 1;
876         while ( (i > 0)
877                 && ( (pCh[i - 1]==13)
878                      || ( pCh[i - 1]==10)) ) {
879                 i--;
880         }
881         memcpy(buf, pCh, i);
882         buf[i] = 0;
883
884         FlushStrBuf(CCC->MigrateBuf);
885         if (retval < 0) {
886                 safestrncpy(&buf[i], "000", bufsize - i);
887         }
888         return(retval >= 0);
889 }
890
891
892 /*
893  * Cleanup any contexts that are left lying around
894  */
895
896
897 void close_masters (void)
898 {
899         struct ServiceFunctionHook *serviceptr;
900         
901         /*
902          * close all protocol master sockets
903          */
904         for (serviceptr = ServiceHookTable; serviceptr != NULL;
905             serviceptr = serviceptr->next ) {
906
907                 if (serviceptr->tcp_port > 0)
908                 {
909                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
910                                 serviceptr->tcp_port);
911                         serviceptr->tcp_port = 0;
912                 }
913                 
914                 if (serviceptr->sockpath != NULL)
915                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
916                                 serviceptr->sockpath);
917
918                 close(serviceptr->msock);
919                 /* If it's a Unix domain socket, remove the file. */
920                 if (serviceptr->sockpath != NULL) {
921                         unlink(serviceptr->sockpath);
922                         serviceptr->sockpath = NULL;
923                 }
924         }
925 }
926
927
928 /*
929  * The system-dependent part of master_cleanup() - close the master socket.
930  */
931 void sysdep_master_cleanup(void) {
932         
933         close_masters();
934         
935         context_cleanup();
936         
937 #ifdef HAVE_OPENSSL
938         destruct_ssl();
939 #endif
940         CtdlDestroyProtoHooks();
941         CtdlDestroyDeleteHooks();
942         CtdlDestroyXmsgHooks();
943         CtdlDestroyNetprocHooks();
944         CtdlDestroyUserHooks();
945         CtdlDestroyMessageHook();
946         CtdlDestroyCleanupHooks();
947         CtdlDestroyFixedOutputHooks();  
948         CtdlDestroySessionHooks();
949         CtdlDestroyServiceHook();
950         CtdlDestroyRoomHooks();
951         #ifdef HAVE_BACKTRACE
952 ///     eCrash_Uninit();
953         #endif
954 }
955
956
957
958 pid_t current_child;
959 void graceful_shutdown(int signum) {
960         kill(current_child, signum);
961         unlink(file_pid_file);
962         exit(0);
963 }
964
965 int nFireUps = 0;
966 int nFireUpsNonRestart = 0;
967 pid_t ForkedPid = 1;
968
969 /*
970  * Start running as a daemon.
971  */
972 void start_daemon(int unused) {
973         int status = 0;
974         pid_t child = 0;
975         FILE *fp;
976         int do_restart = 0;
977
978         current_child = 0;
979
980         /* Close stdin/stdout/stderr and replace them with /dev/null.
981          * We don't just call close() because we don't want these fd's
982          * to be reused for other files.
983          */
984         if (chdir(ctdl_run_dir) != 0)
985                 CtdlLogPrintf(CTDL_EMERG, 
986                               "unable to change into directory [%s]: %s", 
987                               ctdl_run_dir, strerror(errno));
988
989         child = fork();
990         if (child != 0) {
991                 exit(0);
992         }
993         
994         signal(SIGHUP, SIG_IGN);
995         signal(SIGINT, SIG_IGN);
996         signal(SIGQUIT, SIG_IGN);
997
998         setsid();
999         umask(0);
1000         if ((freopen("/dev/null", "r", stdin) != stdin) || 
1001             (freopen("/dev/null", "w", stdout) != stdout) || 
1002             (freopen("/dev/null", "w", stderr) != stderr))
1003                 CtdlLogPrintf(CTDL_EMERG, 
1004                               "unable to reopen stdin/out/err %s", 
1005                               strerror(errno));
1006                 
1007
1008         do {
1009                 current_child = fork();
1010
1011                 signal(SIGTERM, graceful_shutdown);
1012         
1013                 if (current_child < 0) {
1014                         perror("fork");
1015                         exit(errno);
1016                 }
1017         
1018                 else if (current_child == 0) {
1019                         return; /* continue starting citadel. */
1020                 }
1021         
1022                 else {
1023                         fp = fopen(file_pid_file, "w");
1024                         if (fp != NULL) {
1025                                 fprintf(fp, ""F_PID_T"\n", getpid());
1026                                 fclose(fp);
1027                         }
1028                         waitpid(current_child, &status, 0);
1029                 }
1030                 do_restart = 0;
1031                 nFireUpsNonRestart = nFireUps;
1032                 
1033                 /* Exit code 0 means the watcher should exit */
1034                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1035                         do_restart = 0;
1036                 }
1037
1038                 /* Exit code 101-109 means the watcher should exit */
1039                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1040                         do_restart = 0;
1041                 }
1042
1043                 /* Any other exit code, or no exit code, means we should restart. */
1044                 else {
1045                         do_restart = 1;
1046                         nFireUps++;
1047                         ForkedPid = current_child;
1048                 }
1049
1050         } while (do_restart);
1051
1052         unlink(file_pid_file);
1053         exit(WEXITSTATUS(status));
1054 }
1055
1056
1057
1058 void checkcrash(void)
1059 {
1060         if (nFireUpsNonRestart != nFireUps)
1061         {
1062                 StrBuf *CrashMail;
1063
1064                 CrashMail = NewStrBuf();
1065                 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1066                 StrBufPrintf(CrashMail, 
1067                         " \n"
1068                         " The Citadel server process (citserver) terminated unexpectedly."
1069                         "\n \n"
1070                         " This could be the result of a bug in the server program, or some external "
1071                         "factor.\n \n"
1072                         " You can obtain more information about this by enabling core dumps.\n \n"
1073                         " For more information, please see:\n \n"
1074                         " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1075                         "\n \n"
1076
1077                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
1078                         ,
1079                         ctdl_run_dir, ForkedPid);
1080                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1081                 FreeStrBuf(&CrashMail);
1082         }
1083 }
1084
1085
1086 /*
1087  * Generic routine to convert a login name to a full name (gecos)
1088  * Returns nonzero if a conversion took place
1089  */
1090 int convert_login(char NameToConvert[]) {
1091         struct passwd *pw;
1092         int a;
1093
1094         pw = getpwnam(NameToConvert);
1095         if (pw == NULL) {
1096                 return(0);
1097         }
1098         else {
1099                 strcpy(NameToConvert, pw->pw_gecos);
1100                 for (a=0; a<strlen(NameToConvert); ++a) {
1101                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1102                 }
1103                 return(1);
1104         }
1105 }
1106
1107
1108
1109 /* 
1110  * This loop just keeps going and going and going...
1111  */
1112 /*
1113  * FIXME:
1114  * This current implimentation of worker_thread creates a bottle neck in several situations
1115  * The first thing to remember is that a single thread can handle more than one connection at a time.
1116  * More threads mean less memory for the system to run in.
1117  * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1118  * something to happen anywhere.
1119  * This current implimentation requires worker threads to wait in other locations, after it has
1120  * been committed to a single connection which is very wasteful.
1121  * As an extreme case consider this:
1122  * A slow client connects and this slow client sends only one character each second.
1123  * With this current implimentation a single worker thread is dispatched to handle that connection
1124  * until such times as the client timeout expires, an error occurs on the socket or the client
1125  * completes its transmission.
1126  * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1127  * second interval between chars.
1128  *
1129  * It is my intention to re-write this code and the associated client_getln, client_read functions
1130  * to allow any thread to read data on behalf of any connection (context).
1131  * To do this I intend to have this main loop read chars into a buffer stored in the context.
1132  * Once the correct criteria for a full buffer is met then we will dispatch a thread to 
1133  * process it.
1134  * This worker thread loop also needs to be able to handle binary data.
1135  */
1136  
1137 void *worker_thread(void *arg) {
1138         int highest;
1139         CitContext *ptr;
1140         CitContext *bind_me = NULL;
1141         fd_set readfds;
1142         int retval = 0;
1143         struct timeval tv;
1144         int force_purge = 0;
1145         
1146
1147         while (!CtdlThreadCheckStop()) {
1148
1149                 /* make doubly sure we're not holding any stale db handles
1150                  * which might cause a deadlock.
1151                  */
1152                 cdb_check_handles();
1153 do_select:      force_purge = 0;
1154                 bind_me = NULL;         /* Which session shall we handle? */
1155
1156                 /* Initialize the fdset. */
1157                 FD_ZERO(&readfds);
1158                 highest = 0;
1159
1160                 begin_critical_section(S_SESSION_TABLE);
1161                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1162                         int client_socket;
1163                         client_socket = ptr->client_socket;
1164                         /* Dont select on dead sessions only truly idle ones */
1165                         if ((ptr->state == CON_IDLE) && 
1166                             (CC->kill_me == 0) &&
1167                             (client_socket != -1))
1168                         {
1169                                 FD_SET(client_socket, &readfds);
1170                                 if (client_socket > highest)
1171                                         highest = client_socket;
1172                         }
1173                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1174                                 bind_me = ptr;
1175                                 ptr->state = CON_EXECUTING;
1176                                 break;
1177                         }
1178                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1179                                 bind_me = ptr;
1180                                 ptr->state = CON_STARTING;
1181                                 break;
1182                         }
1183                 }
1184                 end_critical_section(S_SESSION_TABLE);
1185
1186                 if (bind_me) {
1187                         goto SKIP_SELECT;
1188                 }
1189
1190                 /* If we got this far, it means that there are no sessions
1191                  * which a previous thread marked for attention, so we go
1192                  * ahead and get ready to select().
1193                  */
1194
1195                 if (!CtdlThreadCheckStop()) {
1196                         tv.tv_sec = 1;          /* wake up every second if no input */
1197                         tv.tv_usec = 0;
1198                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1199                 }
1200                 else
1201                         return NULL;
1202
1203                 /* Now figure out who made this select() unblock.
1204                  * First, check for an error or exit condition.
1205                  */
1206                 if (retval < 0) {
1207                         if (errno == EBADF) {
1208                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1209                                         strerror(errno));
1210                                 goto do_select;
1211                         }
1212                         if (errno != EINTR) {
1213                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1214                                 CtdlThreadStopAll();
1215                                 continue;
1216                         } else {
1217                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1218                                 if (CtdlThreadCheckStop()) return(NULL);
1219                                 goto do_select;
1220                         }
1221                 }
1222                 else if(retval == 0) {
1223                         if (CtdlThreadCheckStop()) return(NULL);
1224                 }
1225
1226                 /* It must be a client socket.  Find a context that has data
1227                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1228                  * active sockets other than our chosen one are marked as
1229                  * CON_READY so the next thread that comes around can just bind
1230                  * to one without having to select() again.
1231                  */
1232                 begin_critical_section(S_SESSION_TABLE);
1233                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1234                         int checkfd = ptr->client_socket;
1235                         if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1236                                 if (FD_ISSET(checkfd, &readfds)) {
1237                                         ptr->input_waiting = 1;
1238                                         if (!bind_me) {
1239                                                 bind_me = ptr;  /* I choose you! */
1240                                                 bind_me->state = CON_EXECUTING;
1241                                         }
1242                                         else {
1243                                                 ptr->state = CON_READY;
1244                                         }
1245                                 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1246                                         if (!bind_me) {
1247                                                 bind_me = ptr;  /* I choose you! */
1248                                                 bind_me->state = CON_EXECUTING;
1249                                         }
1250                                         else {
1251                                                 ptr->state = CON_READY;
1252                                         }
1253                                 }
1254                         }
1255                 }
1256                 end_critical_section(S_SESSION_TABLE);
1257
1258 SKIP_SELECT:
1259                 /* We're bound to a session */
1260                 if (bind_me != NULL) {
1261                         become_session(bind_me);
1262
1263                         if (bind_me->state == CON_STARTING) {
1264                                 bind_me->state = CON_EXECUTING;
1265                                 begin_session(bind_me);
1266                                 bind_me->h_greeting_function();
1267                         }
1268                         /* If the client has sent a command, execute it. */
1269                         if (CC->input_waiting) {
1270                                 CC->h_command_function();
1271
1272                                 while (HaveMoreLinesWaiting(CC))
1273                                        CC->h_command_function();
1274
1275                                 CC->input_waiting = 0;
1276                         }
1277
1278                         /* If there are asynchronous messages waiting and the
1279                          * client supports it, do those now */
1280                         if ((CC->is_async) && (CC->async_waiting)
1281                            && (CC->h_async_function != NULL)) {
1282                                 CC->h_async_function();
1283                                 CC->async_waiting = 0;
1284                         }
1285                         
1286                         force_purge = CC->kill_me;
1287                         become_session(NULL);
1288                         bind_me->state = CON_IDLE;
1289                 }
1290
1291                 dead_session_purge(force_purge);
1292                 do_housekeeping();
1293         }
1294         /* If control reaches this point, the server is shutting down */        
1295         return(NULL);
1296 }
1297
1298
1299
1300
1301 /*
1302  * A function to handle selecting on master sockets.
1303  * In other words it handles new connections.
1304  * It is a thread.
1305  */
1306 void *select_on_master (void *arg)
1307 {
1308         struct ServiceFunctionHook *serviceptr;
1309         fd_set master_fds;
1310         int highest;
1311         struct timeval tv;
1312         int ssock;                      /* Descriptor for client socket */
1313         CitContext *con= NULL;  /* Temporary context pointer */
1314         int m;
1315         int i;
1316         int retval;
1317
1318         while (!CtdlThreadCheckStop()) {
1319                 /* Initialize the fdset. */
1320                 FD_ZERO(&master_fds);
1321                 highest = 0;
1322
1323                 /* First, add the various master sockets to the fdset. */
1324                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1325                 serviceptr = serviceptr->next ) {
1326                         m = serviceptr->msock;
1327                         FD_SET(m, &master_fds);
1328                         if (m > highest) {
1329                                 highest = m;
1330                         }
1331                 }
1332
1333                 if (!CtdlThreadCheckStop()) {
1334                         tv.tv_sec = 60;         /* wake up every second if no input */
1335                         tv.tv_usec = 0;
1336                         retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1337                 }
1338                 else
1339                         return NULL;
1340
1341                 /* Now figure out who made this select() unblock.
1342                  * First, check for an error or exit condition.
1343                  */
1344                 if (retval < 0) {
1345                         if (errno == EBADF) {
1346                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1347                                         strerror(errno));
1348                                 continue;
1349                         }
1350                         if (errno != EINTR) {
1351                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1352                                 CtdlThreadStopAll();
1353                         } else {
1354                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1355                                 if (CtdlThreadCheckStop()) return(NULL);
1356                                 continue;
1357                         }
1358                 }
1359                 else if(retval == 0) {
1360                         if (CtdlThreadCheckStop()) return(NULL);
1361                         continue;
1362                 }
1363                 /* Next, check to see if it's a new client connecting
1364                  * on a master socket.
1365                  */
1366                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1367                      serviceptr = serviceptr->next ) {
1368
1369                         if (FD_ISSET(serviceptr->msock, &master_fds)) {
1370                                 ssock = accept(serviceptr->msock, NULL, 0);
1371                                 if (ssock >= 0) {
1372                                         CtdlLogPrintf(CTDL_DEBUG,
1373                                                 "New client socket %d\n",
1374                                                 ssock);
1375
1376                                         /* The master socket is non-blocking but the client
1377                                          * sockets need to be blocking, otherwise certain
1378                                          * operations barf on FreeBSD.  Not a fatal error.
1379                                          */
1380                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1381                                                 CtdlLogPrintf(CTDL_EMERG,
1382                                                         "citserver: Can't set socket to blocking: %s\n",
1383                                                         strerror(errno));
1384                                         }
1385
1386                                         /* New context will be created already
1387                                          * set up in the CON_EXECUTING state.
1388                                          */
1389                                         con = CreateNewContext();
1390
1391                                         /* Assign our new socket number to it. */
1392                                         con->client_socket = ssock;
1393                                         con->h_command_function =
1394                                                 serviceptr->h_command_function;
1395                                         con->h_async_function =
1396                                                 serviceptr->h_async_function;
1397                                         con->h_greeting_function = serviceptr->h_greeting_function;
1398                                         con->ServiceName =
1399                                                 serviceptr->ServiceName;
1400                                         
1401                                         /* Determine whether it's a local socket */
1402                                         if (serviceptr->sockpath != NULL)
1403                                                 con->is_local_socket = 1;
1404         
1405                                         /* Set the SO_REUSEADDR socket option */
1406                                         i = 1;
1407                                         setsockopt(ssock, SOL_SOCKET,
1408                                                 SO_REUSEADDR,
1409                                                 &i, sizeof(i));
1410
1411                                         con->state = CON_GREETING;
1412
1413                                         retval--;
1414                                         if (retval == 0)
1415                                                 break;
1416                                 }
1417                         }
1418                 }
1419         }
1420         return NULL;
1421 }
1422
1423
1424
1425 /*
1426  * SyslogFacility()
1427  * Translate text facility name to syslog.h defined value.
1428  */
1429 int SyslogFacility(char *name)
1430 {
1431         int i;
1432         struct
1433         {
1434                 int facility;
1435                 char *name;
1436         }   facTbl[] =
1437         {
1438                 {   LOG_KERN,   "kern"          },
1439                 {   LOG_USER,   "user"          },
1440                 {   LOG_MAIL,   "mail"          },
1441                 {   LOG_DAEMON, "daemon"        },
1442                 {   LOG_AUTH,   "auth"          },
1443                 {   LOG_SYSLOG, "syslog"        },
1444                 {   LOG_LPR,    "lpr"           },
1445                 {   LOG_NEWS,   "news"          },
1446                 {   LOG_UUCP,   "uucp"          },
1447                 {   LOG_LOCAL0, "local0"        },
1448                 {   LOG_LOCAL1, "local1"        },
1449                 {   LOG_LOCAL2, "local2"        },
1450                 {   LOG_LOCAL3, "local3"        },
1451                 {   LOG_LOCAL4, "local4"        },
1452                 {   LOG_LOCAL5, "local5"        },
1453                 {   LOG_LOCAL6, "local6"        },
1454                 {   LOG_LOCAL7, "local7"        },
1455                 {   0,            NULL          }
1456         };
1457         for(i = 0; facTbl[i].name != NULL; i++) {
1458                 if(!strcasecmp(name, facTbl[i].name))
1459                         return facTbl[i].facility;
1460         }
1461         enable_syslog = 0;
1462         return LOG_DAEMON;
1463 }
1464
1465
1466 /********** MEM CHEQQER ***********/
1467
1468 #ifdef DEBUG_MEMORY_LEAKS
1469
1470 #undef malloc
1471 #undef realloc
1472 #undef strdup
1473 #undef free
1474
1475 void *tracked_malloc(size_t size, char *file, int line) {
1476         struct igheap *thisheap;
1477         void *block;
1478
1479         block = malloc(size);
1480         if (block == NULL) return(block);
1481
1482         thisheap = malloc(sizeof(struct igheap));
1483         if (thisheap == NULL) {
1484                 free(block);
1485                 return(NULL);
1486         }
1487
1488         thisheap->block = block;
1489         strcpy(thisheap->file, file);
1490         thisheap->line = line;
1491         
1492         begin_critical_section(S_DEBUGMEMLEAKS);
1493         thisheap->next = igheap;
1494         igheap = thisheap;
1495         end_critical_section(S_DEBUGMEMLEAKS);
1496
1497         return(block);
1498 }
1499
1500
1501 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1502         struct igheap *thisheap;
1503         void *block;
1504
1505         block = realloc(ptr, size);
1506         if (block == NULL) return(block);
1507
1508         thisheap = malloc(sizeof(struct igheap));
1509         if (thisheap == NULL) {
1510                 free(block);
1511                 return(NULL);
1512         }
1513
1514         thisheap->block = block;
1515         strcpy(thisheap->file, file);
1516         thisheap->line = line;
1517         
1518         begin_critical_section(S_DEBUGMEMLEAKS);
1519         thisheap->next = igheap;
1520         igheap = thisheap;
1521         end_critical_section(S_DEBUGMEMLEAKS);
1522
1523         return(block);
1524 }
1525
1526
1527
1528 void tracked_free(void *ptr) {
1529         struct igheap *thisheap;
1530         struct igheap *trash;
1531
1532         free(ptr);
1533
1534         if (igheap == NULL) return;
1535         begin_critical_section(S_DEBUGMEMLEAKS);
1536         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1537                 if (thisheap->next != NULL) {
1538                         if (thisheap->next->block == ptr) {
1539                                 trash = thisheap->next;
1540                                 thisheap->next = thisheap->next->next;
1541                                 free(trash);
1542                         }
1543                 }
1544         }
1545         if (igheap->block == ptr) {
1546                 trash = igheap;
1547                 igheap = igheap->next;
1548                 free(trash);
1549         }
1550         end_critical_section(S_DEBUGMEMLEAKS);
1551 }
1552
1553 char *tracked_strdup(const char *s, char *file, int line) {
1554         char *ptr;
1555
1556         if (s == NULL) return(NULL);
1557         ptr = tracked_malloc(strlen(s) + 1, file, line);
1558         if (ptr == NULL) return(NULL);
1559         strncpy(ptr, s, strlen(s));
1560         return(ptr);
1561 }
1562
1563 void dump_heap(void) {
1564         struct igheap *thisheap;
1565
1566         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1567                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1568                         thisheap->file, thisheap->line);
1569         }
1570 }
1571
1572 #endif /*  DEBUG_MEMORY_LEAKS */