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