]> code.citadel.org Git - citadel.git/blob - citadel/server/sysdep.c
Temporarily disable the indexer
[citadel.git] / citadel / server / sysdep.c
1 // This started as a portability layer, but then everything got more standard.
2 // Most of it handles network communication.
3 //
4 // Copyright (c) 1987-2023 by the citadel.org team
5 //
6 // This program is open source software.  Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
8
9 #include "sysdep.h"
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <sys/stat.h>
13 #include <errno.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <syslog.h>
17 #include <sys/syslog.h>
18 #include <execinfo.h>
19 #include <netdb.h>
20 #include <sys/un.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25 #include <netinet/tcp.h>
26 #include <arpa/inet.h>
27 #define SHOW_ME_VAPPEND_PRINTF
28 #include <libcitadel.h>
29 #include "citserver.h"
30 #include "config.h"
31 #include "ctdl_module.h"
32 #include "sysdep_decls.h"
33 #include "modules/crypto/serv_crypto.h" // Needed for init_ssl, client_write_ssl, client_read_ssl
34 #include "housekeeping.h"
35 #include "context.h"
36
37 // Signal handler to shut down the server.
38 volatile int exit_signal = 0;
39 volatile int shutdown_and_halt = 0;
40 volatile int restart_server = 0;
41 volatile int running_as_daemon = 0;
42
43
44 static RETSIGTYPE signal_cleanup(int signum) {
45         syslog(LOG_DEBUG, "sysdep: caught signal %d", signum);
46         signal(SIGINT, SIG_DFL);
47         signal(SIGHUP, SIG_DFL);
48         signal(SIGTERM, SIG_DFL);
49         //signal(SIGSEGV, SIG_DFL);
50         exit_signal = signum;
51         server_shutting_down = 1;
52         master_cleanup(signum);
53 }
54
55
56 // Some initialization stuff...
57 void init_sysdep(void) {
58         sigset_t set;
59
60         // Avoid vulnerabilities related to FD_SETSIZE if we can.
61 #ifdef FD_SETSIZE
62 #ifdef RLIMIT_NOFILE
63         struct rlimit rl;
64         getrlimit(RLIMIT_NOFILE, &rl);
65         rl.rlim_cur = FD_SETSIZE;
66         rl.rlim_max = FD_SETSIZE;
67         setrlimit(RLIMIT_NOFILE, &rl);
68 #endif
69 #endif
70
71         // If we've got OpenSSL, we're going to use it.
72 #ifdef HAVE_OPENSSL
73         init_ssl();
74 #endif
75
76         if (pthread_key_create(&MyConKey, NULL) != 0) {                         // TSD for sessions
77                 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
78                 exit(CTDLEXIT_THREAD);
79         }
80
81         // Interript, hangup, and terminate signals should cause the server to shut down.
82         sigemptyset(&set);
83         sigaddset(&set, SIGINT);
84         sigaddset(&set, SIGHUP);
85         sigaddset(&set, SIGTERM);
86         //sigaddset(&set, SIGSEGV);
87         sigprocmask(SIG_UNBLOCK, &set, NULL);
88
89         signal(SIGINT, signal_cleanup);
90         signal(SIGHUP, signal_cleanup);
91         signal(SIGTERM, signal_cleanup);
92         //signal(SIGSEGV, signal_cleanup);
93
94         // Do not shut down the server on broken pipe signals, otherwise the
95         // whole Citadel service would come down whenever a single client
96         // socket breaks.
97         signal(SIGPIPE, SIG_IGN);
98 }
99
100
101 // This is a generic function to set up a master socket for listening on
102 // a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
103 //
104 // ip_addr      IP address to bind
105 // port_number  port number to bind
106 // queue_len    number of incoming connections to allow in the queue
107 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len) {
108         struct protoent *p;
109         struct sockaddr_in6 sin6;
110         struct sockaddr_in sin4;
111         int s, i, b;
112         int ip_version = 6;
113
114         memset(&sin6, 0, sizeof(sin6));
115         memset(&sin4, 0, sizeof(sin4));
116         sin6.sin6_family = AF_INET6;
117         sin4.sin_family = AF_INET;
118
119         if (    (ip_addr == NULL)                                                       // any IPv6
120                 || (IsEmptyStr(ip_addr))
121                 || (!strcmp(ip_addr, "*"))
122                 || (!strcmp(ip_addr, "::"))
123         ) {
124                 ip_version = 6;
125                 sin6.sin6_addr = in6addr_any;
126         }
127         else if (!strcmp(ip_addr, "0.0.0.0")) {                                         // any IPv4
128                 ip_version = 4;
129                 sin4.sin_addr.s_addr = INADDR_ANY;
130         }
131         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) {                   // specific IPv4
132                 ip_version = 4;
133                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
134                         syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
135                         return (-1);
136                 }
137         }
138         else {                                                                          // specific IPv6
139                 ip_version = 6;
140                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
141                         syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
142                         return (-1);
143                 }
144         }
145
146         if (port_number == 0) {
147                 syslog(LOG_ALERT, "tcpserver: no port number was specified");
148                 return (-1);
149         }
150         sin6.sin6_port = htons((u_short) port_number);
151         sin4.sin_port = htons((u_short) port_number);
152
153         p = getprotobyname("tcp");
154         if (p == NULL) {
155                 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
156                 return (-1);
157         }
158
159         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
160         if (s < 0) {
161                 syslog(LOG_ALERT, "tcpserver: socket: %m");
162                 return (-1);
163         }
164         // Set some socket options that make sense.
165         i = 1;
166         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
167
168         if (ip_version == 6) {
169                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
170         }
171         else {
172                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
173         }
174
175         if (b < 0) {
176                 syslog(LOG_ALERT, "tcpserver: bind: %m");
177                 return (-1);
178         }
179
180         fcntl(s, F_SETFL, O_NONBLOCK);
181
182         if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
183                 syslog(LOG_ALERT, "tcpserver: listen: %m");
184                 return (-1);
185         }
186         return (s);
187 }
188
189
190 // Create a Unix domain socket and listen on it
191 int ctdl_uds_server(char *sockpath, int queue_len) {
192         struct sockaddr_un addr;
193         int s;
194         int i;
195         int actual_queue_len;
196
197         actual_queue_len = queue_len;
198         if (actual_queue_len < 5) actual_queue_len = 5;
199
200         i = unlink(sockpath);
201         if ((i != 0) && (errno != ENOENT)) {
202                 syslog(LOG_ERR, "udsserver: %m");
203                 return(-1);
204         }
205
206         memset(&addr, 0, sizeof(addr));
207         addr.sun_family = AF_UNIX;
208         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
209
210         s = socket(AF_UNIX, SOCK_STREAM, 0);
211         if (s < 0) {
212                 syslog(LOG_ERR, "udsserver: socket: %m");
213                 return(-1);
214         }
215
216         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
217                 syslog(LOG_ERR, "udsserver: bind: %m");
218                 return(-1);
219         }
220
221         // set to nonblock - we need this for some obscure situations
222         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
223                 syslog(LOG_ERR, "udsserver: fcntl: %m");
224                 close(s);
225                 return(-1);
226         }
227
228         if (listen(s, actual_queue_len) < 0) {
229                 syslog(LOG_ERR, "udsserver: listen: %m");
230                 return(-1);
231         }
232
233         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
234         return(s);
235 }
236
237
238 // The following functions implement output buffering on operating systems which
239 // support it (such as Linux and various BSD flavors).
240 #ifndef HAVE_DARWIN
241 #ifdef TCP_CORK
242 #       define HAVE_TCP_BUFFERING
243 #else
244 #       ifdef TCP_NOPUSH
245 #               define HAVE_TCP_BUFFERING
246 #               define TCP_CORK TCP_NOPUSH
247 #       endif
248 #endif // TCP_CORK
249 #endif // HAVE_DARWIN
250
251 static unsigned on = 1, off = 0;
252
253 void buffer_output(void) {
254 #ifdef HAVE_TCP_BUFFERING
255 #ifdef HAVE_OPENSSL
256         if (!CC->redirect_ssl)
257 #endif
258                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
259 #endif
260 }
261
262 void unbuffer_output(void) {
263 #ifdef HAVE_TCP_BUFFERING
264 #ifdef HAVE_OPENSSL
265         if (!CC->redirect_ssl)
266 #endif
267                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
268 #endif
269 }
270
271 void flush_output(void) {
272 #ifdef HAVE_TCP_BUFFERING
273         setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
274         setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
275 #endif
276 }
277
278
279 // close the client socket
280 void client_close(void) {
281         if (!CC) return;
282         if (CC->client_socket <= 0) return;
283         syslog(LOG_DEBUG, "sysdep: closing socket %d", CC->client_socket);
284         close(CC->client_socket);
285         CC->client_socket = -1 ;
286 }
287
288
289 // Send binary data to the client.
290 int client_write(const char *buf, int nbytes) {
291         int bytes_written = 0;
292         int retval;
293 #ifndef HAVE_TCP_BUFFERING
294         int old_buffer_len = 0;
295 #endif
296         fd_set wset;
297         CitContext *Ctx;
298         int fdflags;
299
300         if (nbytes < 1) return(0);
301
302         Ctx = CC;
303         if (Ctx->redirect_buffer != NULL) {
304                 StrBufAppendBufPlain(Ctx->redirect_buffer, buf, nbytes, 0);
305                 return 0;
306         }
307
308 #ifdef HAVE_OPENSSL
309         if (Ctx->redirect_ssl) {
310                 client_write_ssl(buf, nbytes);
311                 return 0;
312         }
313 #endif
314         if (Ctx->client_socket == -1) return -1;
315
316         fdflags = fcntl(Ctx->client_socket, F_GETFL);
317
318         while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
319                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
320                         FD_ZERO(&wset);
321                         FD_SET(Ctx->client_socket, &wset);
322                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
323                                 if (errno == EINTR) {
324                                         syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
325                                         if (server_shutting_down) {
326                                                 CC->kill_me = KILLME_SELECT_INTERRUPTED;
327                                                 return (-1);
328                                         }
329                                         else {
330                                                 // can't trust fd's and stuff so we need to re-create them
331                                                 continue;
332                                         }
333                                 }
334                                 else {
335                                         syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
336                                         client_close();
337                                         Ctx->kill_me = KILLME_SELECT_FAILED;
338                                         return -1;
339                                 }
340                         }
341                 }
342
343                 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
344                 if (retval < 1) {
345                         syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
346                         client_close();
347                         Ctx->kill_me = KILLME_WRITE_FAILED;
348                         return -1;
349                 }
350                 bytes_written = bytes_written + retval;
351         }
352         return 0;
353 }
354
355
356 void cputbuf(const StrBuf *Buf) {   
357         client_write(ChrPtr(Buf), StrLength(Buf)); 
358 }   
359
360
361 // Send formatted printable data to the client.
362 // Implemented in terms of client_write() so it's technically not sysdep...
363 void cprintf(const char *format, ...) {   
364         va_list arg_ptr;   
365         char buf[1024];
366         int rc;
367    
368         va_start(arg_ptr, format);   
369         rc = vsnprintf(buf, sizeof buf, format, arg_ptr);
370         if (rc < 0) {
371                 syslog(LOG_ERR,"Console output error occured. Format: %s",format);
372         } else {
373                 if (rc >= sizeof buf) {
374                         // Output was truncated.
375                         // Chop at the end of the buffer
376                         buf[sizeof buf - 2] = '\n';
377                         buf[sizeof buf - 1] = 0;
378                 }
379                 client_write(buf, strlen(buf)); 
380         }
381         va_end(arg_ptr);
382 }
383
384
385 // Read data from the client socket.
386 //
387 // sock         socket fd to read from
388 // buf          buffer to read into 
389 // bytes        number of bytes to read
390 // timeout      Number of seconds to wait before timing out
391 //
392 // Possible return values:
393 //      1       Requested number of bytes has been read.
394 //      0       Request timed out.
395 //      -1      Connection is broken, or other error.
396 int client_read_blob(StrBuf *Target, int bytes, int timeout) {
397         const char *Error;
398         int retval = 0;
399
400 #ifdef HAVE_OPENSSL
401         if (CC->redirect_ssl) {
402                 retval = client_read_sslblob(Target, bytes, timeout);
403                 if (retval < 0) {
404                         syslog(LOG_ERR, "sysdep: client_read_blob() failed");
405                 }
406         }
407         else 
408 #endif
409         {
410                 retval = StrBufReadBLOBBuffered(Target, 
411                                                 CC->RecvBuf.Buf,
412                                                 &CC->RecvBuf.ReadWritePointer,
413                                                 &CC->client_socket,
414                                                 1, 
415                                                 bytes,
416                                                 O_TERM,
417                                                 &Error
418                 );
419                 if (retval < 0) {
420                         syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
421                         client_close();
422                         return retval;
423                 }
424         }
425         return retval;
426 }
427
428
429 // to make client_read_random_blob() more efficient, increase buffer size.
430 // just use in greeting function, else your buffer may be flushed
431 void client_set_inbound_buf(long N) {
432         FlushStrBuf(CC->RecvBuf.Buf);
433         ReAdjustEmptyBuf(CC->RecvBuf.Buf, N * SIZ, N * SIZ);
434 }
435
436
437 int client_read_random_blob(StrBuf *Target, int timeout) {
438         int rc;
439
440         rc =  client_read_blob(Target, 1, timeout);
441         if (rc > 0) {
442                 long len;
443                 const char *pch;
444                 
445                 len = StrLength(CC->RecvBuf.Buf);
446                 pch = ChrPtr(CC->RecvBuf.Buf);
447
448                 if (len > 0) {
449                         if (CC->RecvBuf.ReadWritePointer != NULL) {
450                                 len -= CC->RecvBuf.ReadWritePointer - pch;
451                                 pch = CC->RecvBuf.ReadWritePointer;
452                         }
453                         StrBufAppendBufPlain(Target, pch, len, 0);
454                         FlushStrBuf(CC->RecvBuf.Buf);
455                         CC->RecvBuf.ReadWritePointer = NULL;
456                         return StrLength(Target);
457                 }
458                 return rc;
459         }
460         else
461                 return rc;
462 }
463
464
465 int client_read_to(char *buf, int bytes, int timeout) {
466         int rc;
467
468         rc = client_read_blob(CC->MigrateBuf, bytes, timeout);
469         if (rc < 0) {
470                 *buf = '\0';
471                 return rc;
472         }
473         else {
474                 memcpy(buf, 
475                        ChrPtr(CC->MigrateBuf),
476                        StrLength(CC->MigrateBuf) + 1);
477                 FlushStrBuf(CC->MigrateBuf);
478                 return rc;
479         }
480 }
481
482
483 int HaveMoreLinesWaiting(CitContext *ctx) {
484         if (    (ctx->kill_me != 0)
485                 || ( (ctx->RecvBuf.ReadWritePointer == NULL)
486                 && (StrLength(ctx->RecvBuf.Buf) == 0)
487                 && (ctx->client_socket != -1))
488         )
489                 return 0;
490         else
491                 return 1;
492 }
493
494
495 // Read data from the client socket with default timeout.
496 // (This is implemented in terms of client_read_to() and could be
497 // justifiably moved out of sysdep.c)
498 INLINE int client_read(char *buf, int bytes) {
499         return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
500 }
501
502
503 int CtdlClientGetLine(StrBuf *Target) {
504         const char *Error;
505         int rc;
506
507         FlushStrBuf(Target);
508 #ifdef HAVE_OPENSSL
509         if (CC->redirect_ssl) {
510                 rc = client_readline_sslbuffer(Target, CC->RecvBuf.Buf, &CC->RecvBuf.ReadWritePointer, 1);
511                 return rc;
512         }
513         else 
514 #endif
515         {
516                 rc = StrBufTCP_read_buffered_line_fast(Target, 
517                                                        CC->RecvBuf.Buf,
518                                                        &CC->RecvBuf.ReadWritePointer,
519                                                        &CC->client_socket,
520                                                        5,
521                                                        1,
522                                                        &Error
523                 );
524                 return rc;
525         }
526 }
527
528
529 // Get a LF-terminated line of text from the client.
530 // (This is implemented in terms of client_read() and could be
531 // justifiably moved out of sysdep.c)
532 int client_getln(char *buf, int bufsize) {
533         int i, retval;
534         const char *pCh;
535
536         retval = CtdlClientGetLine(CC->MigrateBuf);
537         if (retval < 0)
538           return(retval >= 0);
539
540
541         i = StrLength(CC->MigrateBuf);
542         pCh = ChrPtr(CC->MigrateBuf);
543         // Strip the trailing LF, and the trailing CR if present.
544         if (bufsize <= i)
545                 i = bufsize - 1;
546         while ( (i > 0)
547                 && ( (pCh[i - 1]==13)
548                      || ( pCh[i - 1]==10)) ) {
549                 i--;
550         }
551         memcpy(buf, pCh, i);
552         buf[i] = 0;
553
554         FlushStrBuf(CC->MigrateBuf);
555         if (retval < 0) {
556                 safestrncpy(&buf[i], "000", bufsize - i);
557         }
558         return(retval >= 0);
559 }
560
561
562 pid_t current_child;
563 void supervisor_process_shutdown(int signum) {
564         kill(current_child, signum);
565         unlink(file_pid_file);
566         exit(0);
567 }
568
569 int nFireUps = 0;
570 int nFireUpsNonRestart = 0;
571 pid_t ForkedPid = 1;
572
573 // Start running as a daemon.
574 void start_daemon(int unused) {
575         int status = 0;
576         pid_t child = 0;
577         FILE *fp;
578         int do_restart = 0;
579         current_child = 0;
580
581         // Close stdin/stdout/stderr and replace them with /dev/null.
582         // We don't just call close() because we don't want these fd's
583         // to be reused for other files.
584         child = fork();
585         if (child != 0) {
586                 exit(0);
587         }
588         
589         signal(SIGHUP, SIG_IGN);
590         signal(SIGINT, SIG_IGN);
591         signal(SIGQUIT, SIG_IGN);
592
593         setsid();
594         umask(0);
595         if (    (freopen("/dev/null", "r", stdin) != stdin) || 
596                 (freopen("/dev/null", "w", stdout) != stdout) || 
597                 (freopen("/dev/null", "w", stderr) != stderr)
598         ) {
599                 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
600         }
601
602         do {
603                 current_child = fork();
604                 signal(SIGTERM, supervisor_process_shutdown);
605                 if (current_child < 0) {
606                         perror("fork");
607                         exit(errno);
608                 }
609                 else if (current_child == 0) {
610                         return; // continue starting citadel.
611                 }
612                 else {
613                         fp = fopen(file_pid_file, "w");
614                         if (fp != NULL) {
615                                 fprintf(fp, ""F_PID_T"\n", getpid());
616                                 fclose(fp);
617                         }
618                         waitpid(current_child, &status, 0);
619                 }
620                 nFireUpsNonRestart = nFireUps;
621                 
622                 // Exit code 0 means the watcher should exit
623                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
624                         do_restart = 0;
625                 }
626
627                 // Exit code 101-109 means the watcher should exit
628                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
629                         do_restart = 0;
630                 }
631
632                 // Any other exit code, or no exit code, means we should restart.
633                 else {
634                         do_restart = 1;
635                         nFireUps++;
636                         ForkedPid = current_child;
637                 }
638
639         } while (do_restart);
640
641         unlink(file_pid_file);
642         exit(WEXITSTATUS(status));
643 }
644
645
646 void checkcrash(void) {
647         if (nFireUpsNonRestart != nFireUps) {
648                 StrBuf *CrashMail;
649                 CrashMail = NewStrBuf();
650                 syslog(LOG_ALERT, "sysdep: posting crash message");
651                 StrBufPrintf(CrashMail, 
652                         " \n"
653                         " The Citadel server process (citserver) terminated unexpectedly."
654                         "\n \n"
655                         " This could be the result of a bug in the server program, or some external "
656                         "factor.\n \n"
657                         " You can obtain more information about this by enabling core dumps.\n \n"
658                         " For more information, please see:\n \n"
659                         " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
660                         "\n \n"
661
662                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
663                         ,
664                         ctdl_run_dir, ForkedPid);
665                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
666                 FreeStrBuf(&CrashMail);
667         }
668 }
669
670
671 // Generic routine to convert a login name to a full name (gecos)
672 // Returns nonzero if a conversion took place
673 int convert_login(char NameToConvert[]) {
674         struct passwd *pw;
675         unsigned int a;
676
677         pw = getpwnam(NameToConvert);
678         if (pw == NULL) {
679                 return(0);
680         }
681         else {
682                 strcpy(NameToConvert, pw->pw_gecos);
683                 for (a=0; a<strlen(NameToConvert); ++a) {
684                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
685                 }
686                 return(1);
687         }
688 }
689
690
691 void HuntBadSession(void) {
692         int highest;
693         CitContext *ptr;
694         fd_set readfds;
695         struct timeval tv;
696         struct ServiceFunctionHook *serviceptr;
697
698         // Next, add all of the client sockets
699         begin_critical_section(S_SESSION_TABLE);
700         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
701                 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
702                         continue;
703                 // Initialize the fdset.
704                 FD_ZERO(&readfds);
705                 highest = 0;
706                 tv.tv_sec = 0;          // wake up every second if no input
707                 tv.tv_usec = 0;
708
709                 // Don't select on dead sessions, only truly idle ones
710                 if (    (ptr->state == CON_IDLE)
711                         && (ptr->kill_me == 0)
712                         && (ptr->client_socket > 0)
713                 ) {
714                         FD_SET(ptr->client_socket, &readfds);
715                         if (ptr->client_socket > highest)
716                                 highest = ptr->client_socket;
717                         
718                         if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
719                                 // Gotcha!
720                                 syslog(LOG_ERR,
721                                        "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
722                                         ptr->cs_pid,
723                                         ptr->client_socket,
724                                         ptr->curr_user,
725                                         ptr->cs_host,
726                                         ptr->cs_addr
727                                 );
728                                 ptr->kill_me = 1;
729                                 ptr->client_socket = -1;
730                                 break;
731                         }
732                 }
733         }
734         end_critical_section(S_SESSION_TABLE);
735
736         // First, add the various master sockets to the fdset.
737         for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
738
739                 // Initialize the fdset.
740                 highest = 0;
741                 tv.tv_sec = 0;          // wake up every second if no input
742                 tv.tv_usec = 0;
743
744                 FD_SET(serviceptr->msock, &readfds);
745                 if (serviceptr->msock > highest) {
746                         highest = serviceptr->msock;
747                 }
748                 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
749                         // Gotcha! server socket dead? commit suicide!
750                         syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
751                         server_shutting_down = 1;
752                         break;
753                 }
754         }
755 }
756
757
758 // Main server loop
759 // select() can wake up on any of the following conditions:
760 // 1. A new client connection on a master socket
761 // 2. Received data on a client socket
762 // 3. A timer event
763 // That's why we are blocking on select() and not accept().
764 void *worker_thread(void *blah) {
765         int highest;
766         CitContext *ptr;
767         CitContext *bind_me = NULL;
768         fd_set readfds;
769         int retval = 0;
770         struct timeval tv;
771         int force_purge = 0;
772         struct ServiceFunctionHook *serviceptr;
773         int ssock;                      // Descriptor for client socket
774         CitContext *con = NULL;         // Temporary context pointer
775         int i;
776
777         pthread_mutex_lock(&ThreadCountMutex);
778         ++num_workers;
779         pthread_mutex_unlock(&ThreadCountMutex);
780
781         while (!server_shutting_down) {
782
783                 // make doubly sure we're not holding any stale db handles which might cause a deadlock
784                 cdb_check_handles();
785 do_select:      force_purge = 0;
786                 bind_me = NULL;         // Which session shall we handle?
787
788                 // Initialize the fdset
789                 FD_ZERO(&readfds);
790                 highest = 0;
791
792                 // First, add the various master sockets to the fdset.
793                 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
794                         FD_SET(serviceptr->msock, &readfds);
795                         if (serviceptr->msock > highest) {
796                                 highest = serviceptr->msock;
797                         }
798                 }
799
800                 // Next, add all of the client sockets.
801                 begin_critical_section(S_SESSION_TABLE);
802                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
803                         if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
804                             continue;
805
806                         // Don't select on dead sessions, only truly idle ones
807                         if (    (ptr->state == CON_IDLE)
808                                 && (ptr->kill_me == 0)
809                                 && (ptr->client_socket > 0)
810                         ) {
811                                 FD_SET(ptr->client_socket, &readfds);
812                                 if (ptr->client_socket > highest)
813                                         highest = ptr->client_socket;
814                         }
815                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
816                                 bind_me = ptr;
817                                 ptr->state = CON_EXECUTING;
818                                 break;
819                         }
820                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
821                                 bind_me = ptr;
822                                 ptr->state = CON_STARTING;
823                                 break;
824                         }
825                 }
826                 end_critical_section(S_SESSION_TABLE);
827
828                 if (bind_me) {
829                         goto SKIP_SELECT;
830                 }
831
832                 // If we got this far, it means that there are no sessions
833                 // which a previous thread marked for attention, so we go
834                 // ahead and get ready to select().
835
836                 if (!server_shutting_down) {
837                         tv.tv_sec = 1;          // wake up every second if no input
838                         tv.tv_usec = 0;
839                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
840                 }
841                 else {
842                         --num_workers;
843                         return NULL;
844                 }
845
846                 // Now figure out who made this select() unblock.
847                 // First, check for an error or exit condition.
848                 if (retval < 0) {
849                         if (errno == EBADF) {
850                                 syslog(LOG_ERR, "sysdep: select() failed: %m");
851                                 HuntBadSession();
852                                 goto do_select;
853                         }
854                         if (errno != EINTR) {
855                                 syslog(LOG_ERR, "sysdep: exiting: %m");
856                                 server_shutting_down = 1;
857                                 continue;
858                         } else {
859                                 if (server_shutting_down) {
860                                         --num_workers;
861                                         return(NULL);
862                                 }
863                                 goto do_select;
864                         }
865                 }
866                 else if (retval == 0) {
867                         if (server_shutting_down) {
868                                 --num_workers;
869                                 return(NULL);
870                         }
871                 }
872
873                 // Next, check to see if it's a new client connecting on a master socket.
874
875                 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
876
877                         if (FD_ISSET(serviceptr->msock, &readfds)) {
878                                 ssock = accept(serviceptr->msock, NULL, 0);
879                                 if (ssock >= 0) {
880                                         syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
881
882                                         // The master socket is non-blocking but the client
883                                         // sockets need to be blocking, otherwise certain
884                                         // operations barf on FreeBSD.  Not a fatal error.
885                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
886                                                 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
887                                         }
888
889                                         // New context will be created already
890                                         // set up in the CON_EXECUTING state.
891                                         con = CreateNewContext();
892
893                                         // Assign our new socket number to it.
894                                         con->tcp_port = serviceptr->tcp_port;
895                                         con->client_socket = ssock;
896                                         con->h_command_function = serviceptr->h_command_function;
897                                         con->h_async_function = serviceptr->h_async_function;
898                                         con->h_greeting_function = serviceptr->h_greeting_function;
899                                         con->ServiceName = serviceptr->ServiceName;
900                                         
901                                         // Connections on a local client are always from the same host
902                                         if (serviceptr->sockpath != NULL) {
903                                                 con->is_local_client = 1;
904                                         }
905         
906                                         // Set the SO_REUSEADDR socket option
907                                         i = 1;
908                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
909                                         con->state = CON_GREETING;
910                                         retval--;
911                                         if (retval == 0)
912                                                 break;
913                                 }
914                         }
915                 }
916
917                 // It must be a client socket.  Find a context that has data
918                 // waiting on its socket *and* is in the CON_IDLE state.  Any
919                 // active sockets other than our chosen one are marked as
920                 // CON_READY so the next thread that comes around can just bind
921                 // to one without having to select() again.
922                 begin_critical_section(S_SESSION_TABLE);
923                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
924                         int checkfd = ptr->client_socket;
925                         if ((checkfd != -1) && (ptr->state == CON_IDLE)){
926                                 if (FD_ISSET(checkfd, &readfds)) {
927                                         ptr->input_waiting = 1;
928                                         if (!bind_me) {
929                                                 bind_me = ptr;  // I choose you!
930                                                 bind_me->state = CON_EXECUTING;
931                                         }
932                                         else {
933                                                 ptr->state = CON_READY;
934                                         }
935                                 }
936                                 else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
937                                         if (!bind_me) {
938                                                 bind_me = ptr;  // I choose you!
939                                                 bind_me->state = CON_EXECUTING;
940                                         }
941                                         else {
942                                                 ptr->state = CON_READY;
943                                         }
944                                 }
945                         }
946                 }
947                 end_critical_section(S_SESSION_TABLE);
948
949 SKIP_SELECT:
950                 // We're bound to a session
951                 pthread_mutex_lock(&ThreadCountMutex);
952                 ++active_workers;
953                 pthread_mutex_unlock(&ThreadCountMutex);
954
955                 if (bind_me != NULL) {
956                         become_session(bind_me);
957
958                         if (bind_me->state == CON_STARTING) {
959                                 bind_me->state = CON_EXECUTING;
960                                 begin_session(bind_me);
961                                 bind_me->h_greeting_function();
962                         }
963                         // If the client has sent a command, execute it.
964                         if (CC->input_waiting) {
965                                 CC->h_command_function();
966
967                                 while (HaveMoreLinesWaiting(CC))
968                                        CC->h_command_function();
969
970                                 CC->input_waiting = 0;
971                         }
972
973                         // If there are asynchronous messages waiting and the client supports it, do those now
974                         if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
975                                 CC->h_async_function();
976                                 CC->async_waiting = 0;
977                         }
978
979                         force_purge = CC->kill_me;
980                         become_session(NULL);
981                         bind_me->state = CON_IDLE;
982                 }
983
984                 dead_session_purge(force_purge);
985                 do_housekeeping();
986
987                 pthread_mutex_lock(&ThreadCountMutex);
988                 --active_workers;
989                 pthread_mutex_unlock(&ThreadCountMutex);
990         }
991
992         // If control reaches this point, the server is shutting down
993         while(1) {
994                 sleep(1);               // wait to die
995         }
996         //pthread_mutex_lock(&ThreadCountMutex);
997         //--num_workers;
998         //pthread_mutex_unlock(&ThreadCountMutex);
999         //return(NULL);
1000 }
1001
1002
1003 // SyslogFacility()
1004 // Translate text facility name to syslog.h defined value.
1005 int SyslogFacility(char *name) {
1006         int i;
1007         struct {
1008                 int facility;
1009                 char *name;
1010         }   facTbl[] =
1011         {
1012                 {   LOG_KERN,   "kern"          },
1013                 {   LOG_USER,   "user"          },
1014                 {   LOG_MAIL,   "mail"          },
1015                 {   LOG_DAEMON, "daemon"        },
1016                 {   LOG_AUTH,   "auth"          },
1017                 {   LOG_SYSLOG, "syslog"        },
1018                 {   LOG_LPR,    "lpr"           },
1019                 {   LOG_NEWS,   "news"          },
1020                 {   LOG_UUCP,   "uucp"          },
1021                 {   LOG_LOCAL0, "local0"        },
1022                 {   LOG_LOCAL1, "local1"        },
1023                 {   LOG_LOCAL2, "local2"        },
1024                 {   LOG_LOCAL3, "local3"        },
1025                 {   LOG_LOCAL4, "local4"        },
1026                 {   LOG_LOCAL5, "local5"        },
1027                 {   LOG_LOCAL6, "local6"        },
1028                 {   LOG_LOCAL7, "local7"        },
1029                 {   0,            NULL          }
1030         };
1031         for(i = 0; facTbl[i].name != NULL; i++) {
1032                 if(!strcasecmp(name, facTbl[i].name))
1033                         return facTbl[i].facility;
1034         }
1035         return LOG_DAEMON;
1036 }