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