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