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