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