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