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