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