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