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