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