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