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