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