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