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