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