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