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