]> code.citadel.org Git - citadel.git/blob - citadel/server/sysdep.c
validate_recipients() - completed removal of unused param
[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 // Generic routine to convert a login name to a full name (gecos)
563 // Returns nonzero if a conversion took place
564 int convert_login(char NameToConvert[]) {
565         struct passwd *pw;
566         unsigned int a;
567
568         pw = getpwnam(NameToConvert);
569         if (pw == NULL) {
570                 return(0);
571         }
572         else {
573                 strcpy(NameToConvert, pw->pw_gecos);
574                 for (a=0; a<strlen(NameToConvert); ++a) {
575                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
576                 }
577                 return(1);
578         }
579 }
580
581
582 void HuntBadSession(void) {
583         int highest;
584         CitContext *ptr;
585         fd_set readfds;
586         struct timeval tv;
587         struct ServiceFunctionHook *serviceptr;
588
589         // Next, add all of the client sockets
590         begin_critical_section(S_SESSION_TABLE);
591         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
592                 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
593                         continue;
594                 // Initialize the fdset.
595                 FD_ZERO(&readfds);
596                 highest = 0;
597                 tv.tv_sec = 0;          // wake up every second if no input
598                 tv.tv_usec = 0;
599
600                 // Don't select on dead sessions, only truly idle ones
601                 if (    (ptr->state == CON_IDLE)
602                         && (ptr->kill_me == 0)
603                         && (ptr->client_socket > 0)
604                 ) {
605                         FD_SET(ptr->client_socket, &readfds);
606                         if (ptr->client_socket > highest)
607                                 highest = ptr->client_socket;
608                         
609                         if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
610                                 // Gotcha!
611                                 syslog(LOG_ERR,
612                                        "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
613                                         ptr->cs_pid,
614                                         ptr->client_socket,
615                                         ptr->curr_user,
616                                         ptr->cs_host,
617                                         ptr->cs_addr
618                                 );
619                                 ptr->kill_me = 1;
620                                 ptr->client_socket = -1;
621                                 break;
622                         }
623                 }
624         }
625         end_critical_section(S_SESSION_TABLE);
626
627         // First, add the various master sockets to the fdset.
628         for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
629
630                 // Initialize the fdset.
631                 highest = 0;
632                 tv.tv_sec = 0;          // wake up every second if no input
633                 tv.tv_usec = 0;
634
635                 FD_SET(serviceptr->msock, &readfds);
636                 if (serviceptr->msock > highest) {
637                         highest = serviceptr->msock;
638                 }
639                 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
640                         // Gotcha! server socket dead? commit suicide!
641                         syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
642                         server_shutting_down = 1;
643                         break;
644                 }
645         }
646 }
647
648
649 // Main server loop
650 // select() can wake up on any of the following conditions:
651 // 1. A new client connection on a master socket
652 // 2. Received data on a client socket
653 // 3. A timer event
654 // That's why we are blocking on select() and not accept().
655 void *worker_thread(void *blah) {
656         int highest;
657         CitContext *ptr;
658         CitContext *bind_me = NULL;
659         fd_set readfds;
660         int retval = 0;
661         struct timeval tv;
662         int force_purge = 0;
663         struct ServiceFunctionHook *serviceptr;
664         int ssock;                      // Descriptor for client socket
665         CitContext *con = NULL;         // Temporary context pointer
666         int i;
667
668         pthread_mutex_lock(&ThreadCountMutex);
669         ++num_workers;
670         pthread_mutex_unlock(&ThreadCountMutex);
671
672         while (!server_shutting_down) {
673
674                 // make doubly sure we're not holding any stale db handles which might cause a deadlock
675                 cdb_check_handles();
676 do_select:      force_purge = 0;
677                 bind_me = NULL;         // Which session shall we handle?
678
679                 // Initialize the fdset
680                 FD_ZERO(&readfds);
681                 highest = 0;
682
683                 // First, add the various master sockets to the fdset.
684                 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
685                         FD_SET(serviceptr->msock, &readfds);
686                         if (serviceptr->msock > highest) {
687                                 highest = serviceptr->msock;
688                         }
689                 }
690
691                 // Next, add all of the client sockets.
692                 begin_critical_section(S_SESSION_TABLE);
693                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
694                         if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
695                             continue;
696
697                         // Don't select on dead sessions, only truly idle ones
698                         if (    (ptr->state == CON_IDLE)
699                                 && (ptr->kill_me == 0)
700                                 && (ptr->client_socket > 0)
701                         ) {
702                                 FD_SET(ptr->client_socket, &readfds);
703                                 if (ptr->client_socket > highest)
704                                         highest = ptr->client_socket;
705                         }
706                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
707                                 bind_me = ptr;
708                                 ptr->state = CON_EXECUTING;
709                                 break;
710                         }
711                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
712                                 bind_me = ptr;
713                                 ptr->state = CON_STARTING;
714                                 break;
715                         }
716                 }
717                 end_critical_section(S_SESSION_TABLE);
718
719                 if (bind_me) {                  // don't search for a session to bind to.
720                         goto SKIP_SELECT;       // we already found one.
721                 }
722
723                 // If we got this far, it means that there are no sessions
724                 // which a previous thread marked for attention, so we go
725                 // ahead and get ready to select().
726
727                 if (!server_shutting_down) {
728                         tv.tv_sec = 1;          // wake up every second if no input
729                         tv.tv_usec = 0;
730                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
731                 }
732                 else {
733                         --num_workers;
734                         return NULL;
735                 }
736
737                 // Now figure out who made this select() unblock.
738                 // First, check for an error or exit condition.
739                 if (retval < 0) {
740                         if (errno == EBADF) {
741                                 syslog(LOG_ERR, "sysdep: select() failed: %m");
742                                 HuntBadSession();
743                                 goto do_select;
744                         }
745                         if (errno != EINTR) {
746                                 syslog(LOG_ERR, "sysdep: exiting: %m");
747                                 server_shutting_down = 1;
748                                 continue;
749                         } else {
750                                 if (server_shutting_down) {
751                                         --num_workers;
752                                         return(NULL);
753                                 }
754                                 goto do_select;
755                         }
756                 }
757                 else if (retval == 0) {
758                         if (server_shutting_down) {
759                                 --num_workers;
760                                 return(NULL);
761                         }
762                 }
763
764                 // Next, check to see if it's a new client connecting on a master socket.
765
766                 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
767
768                         if (FD_ISSET(serviceptr->msock, &readfds)) {
769                                 ssock = accept(serviceptr->msock, NULL, 0);
770                                 if (ssock >= 0) {
771                                         syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
772
773                                         // The master socket is non-blocking but the client
774                                         // sockets need to be blocking, otherwise certain
775                                         // operations barf on FreeBSD.  Not a fatal error.
776                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
777                                                 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
778                                         }
779
780                                         // New context will be created already
781                                         // set up in the CON_EXECUTING state.
782                                         con = CreateNewContext();
783
784                                         // Assign our new socket number to it.
785                                         con->tcp_port = serviceptr->tcp_port;
786                                         con->client_socket = ssock;
787                                         con->h_command_function = serviceptr->h_command_function;
788                                         con->h_async_function = serviceptr->h_async_function;
789                                         con->h_greeting_function = serviceptr->h_greeting_function;
790                                         con->ServiceName = serviceptr->ServiceName;
791                                         
792                                         // Connections on a local client are always from the same host
793                                         if (serviceptr->sockpath != NULL) {
794                                                 con->is_local_client = 1;
795                                         }
796         
797                                         // Set the SO_REUSEADDR socket option
798                                         i = 1;
799                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
800                                         con->state = CON_GREETING;
801                                         retval--;
802                                         if (retval == 0)
803                                                 break;
804                                 }
805                         }
806                 }
807
808                 // It must be a client socket.  Find a context that has data
809                 // waiting on its socket *and* is in the CON_IDLE state.  Any
810                 // active sockets other than our chosen one are marked as
811                 // CON_READY so the next thread that comes around can just bind
812                 // to one without having to select() again.
813                 begin_critical_section(S_SESSION_TABLE);
814                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
815                         int checkfd = ptr->client_socket;
816                         if ((checkfd != -1) && (ptr->state == CON_IDLE)){
817                                 if (FD_ISSET(checkfd, &readfds)) {
818                                         ptr->input_waiting = 1;
819                                         if (!bind_me) {
820                                                 bind_me = ptr;  // I choose you!
821                                                 bind_me->state = CON_EXECUTING;
822                                         }
823                                         else {
824                                                 ptr->state = CON_READY;
825                                         }
826                                 }
827                                 else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
828                                         if (!bind_me) {
829                                                 bind_me = ptr;  // I choose you!
830                                                 bind_me->state = CON_EXECUTING;
831                                         }
832                                         else {
833                                                 ptr->state = CON_READY;
834                                         }
835                                 }
836                         }
837                 }
838                 end_critical_section(S_SESSION_TABLE);
839
840 SKIP_SELECT:
841                 // We're bound to a session
842                 pthread_mutex_lock(&ThreadCountMutex);
843                 ++active_workers;
844                 pthread_mutex_unlock(&ThreadCountMutex);
845
846                 if (bind_me != NULL) {
847                         become_session(bind_me);
848
849                         if (bind_me->state == CON_STARTING) {
850                                 bind_me->state = CON_EXECUTING;
851                                 begin_session(bind_me);
852                                 bind_me->h_greeting_function();
853                         }
854                         // If the client has sent a command, execute it.
855                         if (CC->input_waiting) {
856                                 CC->h_command_function();
857
858                                 while (HaveMoreLinesWaiting(CC))
859                                        CC->h_command_function();
860
861                                 CC->input_waiting = 0;
862                         }
863
864                         // If there are asynchronous messages waiting and the client supports it, do those now
865                         if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
866                                 CC->h_async_function();
867                                 CC->async_waiting = 0;
868                         }
869
870                         force_purge = CC->kill_me;
871                         become_session(NULL);
872                         bind_me->state = CON_IDLE;
873                 }
874
875                 dead_session_purge(force_purge);
876                 do_housekeeping();
877
878                 pthread_mutex_lock(&ThreadCountMutex);
879                 --active_workers;
880                 pthread_mutex_unlock(&ThreadCountMutex);
881         }
882
883         // If control reaches this point, the server is shutting down
884         return(NULL);
885 }
886
887
888 // SyslogFacility()
889 // Translate text facility name to syslog.h defined value.
890 int SyslogFacility(char *name) {
891         int i;
892         struct {
893                 int facility;
894                 char *name;
895         }   facTbl[] =
896         {
897                 {   LOG_KERN,   "kern"          },
898                 {   LOG_USER,   "user"          },
899                 {   LOG_MAIL,   "mail"          },
900                 {   LOG_DAEMON, "daemon"        },
901                 {   LOG_AUTH,   "auth"          },
902                 {   LOG_SYSLOG, "syslog"        },
903                 {   LOG_LPR,    "lpr"           },
904                 {   LOG_NEWS,   "news"          },
905                 {   LOG_UUCP,   "uucp"          },
906                 {   LOG_LOCAL0, "local0"        },
907                 {   LOG_LOCAL1, "local1"        },
908                 {   LOG_LOCAL2, "local2"        },
909                 {   LOG_LOCAL3, "local3"        },
910                 {   LOG_LOCAL4, "local4"        },
911                 {   LOG_LOCAL5, "local5"        },
912                 {   LOG_LOCAL6, "local6"        },
913                 {   LOG_LOCAL7, "local7"        },
914                 {   0,            NULL          }
915         };
916         for(i = 0; facTbl[i].name != NULL; i++) {
917                 if(!strcasecmp(name, facTbl[i].name))
918                         return facTbl[i].facility;
919         }
920         return LOG_DAEMON;
921 }