1 // Citadel "system dependent" stuff.
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.
6 // Copyright (c) 1987-2022 by the citadel.org team
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.
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.
24 #include <sys/syslog.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"
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"
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;
51 static RETSIGTYPE signal_cleanup(int signum) {
52 syslog(LOG_DEBUG, "sysdep: caught signal %d", signum);
54 server_shutting_down = 1;
58 // Some initialization stuff...
59 void init_sysdep(void) {
62 // Avoid vulnerabilities related to FD_SETSIZE if we can.
66 getrlimit(RLIMIT_NOFILE, &rl);
67 rl.rlim_cur = FD_SETSIZE;
68 rl.rlim_max = FD_SETSIZE;
69 setrlimit(RLIMIT_NOFILE, &rl);
73 // If we've got OpenSSL, we're going to use it.
78 if (pthread_key_create(&ThreadKey, NULL) != 0) { // TSD for threads
79 syslog(LOG_ERR, "pthread_key_create() : %m");
83 if (pthread_key_create(&MyConKey, NULL) != 0) { // TSD for sessions
84 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
88 // Interript, hangup, and terminate signals should cause the server to shut down.
90 sigaddset(&set, SIGINT);
91 sigaddset(&set, SIGHUP);
92 sigaddset(&set, SIGTERM);
93 sigprocmask(SIG_UNBLOCK, &set, NULL);
95 signal(SIGINT, signal_cleanup);
96 signal(SIGHUP, signal_cleanup);
97 signal(SIGTERM, signal_cleanup);
99 // Do not shut down the server on broken pipe signals, otherwise the
100 // whole Citadel service would come down whenever a single client
102 signal(SIGPIPE, SIG_IGN);
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)
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) {
114 struct sockaddr_in6 sin6;
115 struct sockaddr_in sin4;
119 memset(&sin6, 0, sizeof(sin6));
120 memset(&sin4, 0, sizeof(sin4));
121 sin6.sin6_family = AF_INET6;
122 sin4.sin_family = AF_INET;
124 if ( (ip_addr == NULL) // any IPv6
125 || (IsEmptyStr(ip_addr))
126 || (!strcmp(ip_addr, "*"))
129 sin6.sin6_addr = in6addr_any;
131 else if (!strcmp(ip_addr, "0.0.0.0")) { // any IPv4
133 sin4.sin_addr.s_addr = INADDR_ANY;
135 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) { // specific IPv4
137 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
138 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
142 else { // specific IPv6
144 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
145 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
150 if (port_number == 0) {
151 syslog(LOG_ALERT, "tcpserver: no port number was specified");
154 sin6.sin6_port = htons((u_short) port_number);
155 sin4.sin_port = htons((u_short) port_number);
157 p = getprotobyname("tcp");
159 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
163 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
165 syslog(LOG_ALERT, "tcpserver: socket: %m");
168 // Set some socket options that make sense.
170 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
172 if (ip_version == 6) {
173 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
176 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
180 syslog(LOG_ALERT, "tcpserver: bind: %m");
184 fcntl(s, F_SETFL, O_NONBLOCK);
186 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
187 syslog(LOG_ALERT, "tcpserver: listen: %m");
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;
199 int actual_queue_len;
200 #ifdef HAVE_STRUCT_UCRED
204 actual_queue_len = queue_len;
205 if (actual_queue_len < 5) actual_queue_len = 5;
207 i = unlink(sockpath);
208 if ((i != 0) && (errno != ENOENT)) {
209 syslog(LOG_ERR, "udsserver: %m");
213 memset(&addr, 0, sizeof(addr));
214 addr.sun_family = AF_UNIX;
215 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
217 s = socket(AF_UNIX, SOCK_STREAM, 0);
219 syslog(LOG_ERR, "udsserver: socket: %m");
223 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
224 syslog(LOG_ERR, "udsserver: bind: %m");
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");
235 if (listen(s, actual_queue_len) < 0) {
236 syslog(LOG_ERR, "udsserver: listen: %m");
240 #ifdef HAVE_STRUCT_UCRED
241 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
244 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
249 // The following functions implement output buffering on operating systems which
250 // support it (such as Linux and various BSD flavors).
253 # define HAVE_TCP_BUFFERING
256 # define HAVE_TCP_BUFFERING
257 # define TCP_CORK TCP_NOPUSH
260 #endif // HAVE_DARWIN
262 static unsigned on = 1, off = 0;
264 void buffer_output(void) {
265 #ifdef HAVE_TCP_BUFFERING
267 if (!CC->redirect_ssl)
269 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
273 void unbuffer_output(void) {
274 #ifdef HAVE_TCP_BUFFERING
276 if (!CC->redirect_ssl)
278 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
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);
290 // close the client socket
291 void client_close(void) {
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 ;
300 // Send binary data to the client.
301 int client_write(const char *buf, int nbytes) {
302 int bytes_written = 0;
304 #ifndef HAVE_TCP_BUFFERING
305 int old_buffer_len = 0;
311 if (nbytes < 1) return(0);
314 if (Ctx->redirect_buffer != NULL) {
315 StrBufAppendBufPlain(Ctx->redirect_buffer, buf, nbytes, 0);
320 if (Ctx->redirect_ssl) {
321 client_write_ssl(buf, nbytes);
325 if (Ctx->client_socket == -1) return -1;
327 fdflags = fcntl(Ctx->client_socket, F_GETFL);
329 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
330 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
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;
341 // can't trust fd's and stuff so we need to re-create them
346 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
348 Ctx->kill_me = KILLME_SELECT_FAILED;
354 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
356 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
358 Ctx->kill_me = KILLME_WRITE_FAILED;
361 bytes_written = bytes_written + retval;
367 void cputbuf(const StrBuf *Buf) {
368 client_write(ChrPtr(Buf), StrLength(Buf));
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, ...) {
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));
386 // Read data from the client socket.
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
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) {
402 if (CC->redirect_ssl) {
403 retval = client_read_sslblob(Target, bytes, timeout);
405 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
411 retval = StrBufReadBLOBBuffered(Target,
413 &CC->RecvBuf.ReadWritePointer,
421 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
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);
438 int client_read_random_blob(StrBuf *Target, int timeout) {
441 rc = client_read_blob(Target, 1, timeout);
446 len = StrLength(CC->RecvBuf.Buf);
447 pch = ChrPtr(CC->RecvBuf.Buf);
450 if (CC->RecvBuf.ReadWritePointer != NULL) {
451 len -= CC->RecvBuf.ReadWritePointer - pch;
452 pch = CC->RecvBuf.ReadWritePointer;
454 StrBufAppendBufPlain(Target, pch, len, 0);
455 FlushStrBuf(CC->RecvBuf.Buf);
456 CC->RecvBuf.ReadWritePointer = NULL;
457 return StrLength(Target);
466 int client_read_to(char *buf, int bytes, int timeout) {
469 rc = client_read_blob(CC->MigrateBuf, bytes, timeout);
476 ChrPtr(CC->MigrateBuf),
477 StrLength(CC->MigrateBuf) + 1);
478 FlushStrBuf(CC->MigrateBuf);
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))
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")));
504 int CtdlClientGetLine(StrBuf *Target) {
510 if (CC->redirect_ssl) {
511 rc = client_readline_sslbuffer(Target, CC->RecvBuf.Buf, &CC->RecvBuf.ReadWritePointer, 1);
517 rc = StrBufTCP_read_buffered_line_fast(Target,
519 &CC->RecvBuf.ReadWritePointer,
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) {
537 retval = CtdlClientGetLine(CC->MigrateBuf);
542 i = StrLength(CC->MigrateBuf);
543 pCh = ChrPtr(CC->MigrateBuf);
544 // Strip the trailing LF, and the trailing CR if present.
548 && ( (pCh[i - 1]==13)
549 || ( pCh[i - 1]==10)) ) {
555 FlushStrBuf(CC->MigrateBuf);
557 safestrncpy(&buf[i], "000", bufsize - i);
563 // Cleanup any contexts that are left lying around
564 void close_masters(void) {
565 struct ServiceFunctionHook *serviceptr;
568 // close all protocol master sockets
569 for (serviceptr = ServiceHookTable; serviceptr != NULL;
570 serviceptr = serviceptr->next ) {
572 if (serviceptr->tcp_port > 0) {
573 if (serviceptr->msock == -1) {
574 Text = "not closing again";
579 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
584 serviceptr->tcp_port = 0;
587 if (serviceptr->sockpath != NULL) {
588 if (serviceptr->msock == -1) {
589 Text = "not closing again";
594 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
601 if (serviceptr->msock != -1) {
602 close(serviceptr->msock);
603 serviceptr->msock = -1;
606 // If it's a Unix domain socket, remove the file.
607 if (serviceptr->sockpath != NULL) {
608 unlink(serviceptr->sockpath);
609 serviceptr->sockpath = NULL;
615 // The system-dependent part of master_cleanup() - close the master socket.
616 void sysdep_master_cleanup(void) {
624 void graceful_shutdown(int signum) {
625 kill(current_child, signum);
626 unlink(file_pid_file);
631 int nFireUpsNonRestart = 0;
634 // Start running as a daemon.
635 void start_daemon(int unused) {
642 // Close stdin/stdout/stderr and replace them with /dev/null.
643 // We don't just call close() because we don't want these fd's
644 // to be reused for other files.
650 signal(SIGHUP, SIG_IGN);
651 signal(SIGINT, SIG_IGN);
652 signal(SIGQUIT, SIG_IGN);
656 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
657 (freopen("/dev/null", "w", stdout) != stdout) ||
658 (freopen("/dev/null", "w", stderr) != stderr)
660 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
664 current_child = fork();
665 signal(SIGTERM, graceful_shutdown);
666 if (current_child < 0) {
670 else if (current_child == 0) {
671 return; // continue starting citadel.
674 fp = fopen(file_pid_file, "w");
676 fprintf(fp, ""F_PID_T"\n", getpid());
679 waitpid(current_child, &status, 0);
681 nFireUpsNonRestart = nFireUps;
683 // Exit code 0 means the watcher should exit
684 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
688 // Exit code 101-109 means the watcher should exit
689 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
693 // Any other exit code, or no exit code, means we should restart.
697 ForkedPid = current_child;
700 } while (do_restart);
702 unlink(file_pid_file);
703 exit(WEXITSTATUS(status));
707 void checkcrash(void) {
708 if (nFireUpsNonRestart != nFireUps) {
710 CrashMail = NewStrBuf();
711 syslog(LOG_ALERT, "sysdep: posting crash message");
712 StrBufPrintf(CrashMail,
714 " The Citadel server process (citserver) terminated unexpectedly."
716 " This could be the result of a bug in the server program, or some external "
718 " You can obtain more information about this by enabling core dumps.\n \n"
719 " For more information, please see:\n \n"
720 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
723 " If you have already done this, the core dump is likely to be found at %score.%d\n"
725 ctdl_run_dir, ForkedPid);
726 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
727 FreeStrBuf(&CrashMail);
732 // Generic routine to convert a login name to a full name (gecos)
733 // Returns nonzero if a conversion took place
734 int convert_login(char NameToConvert[]) {
738 pw = getpwnam(NameToConvert);
743 strcpy(NameToConvert, pw->pw_gecos);
744 for (a=0; a<strlen(NameToConvert); ++a) {
745 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
752 void HuntBadSession(void) {
757 struct ServiceFunctionHook *serviceptr;
759 // Next, add all of the client sockets
760 begin_critical_section(S_SESSION_TABLE);
761 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
762 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
764 // Initialize the fdset.
767 tv.tv_sec = 0; // wake up every second if no input
770 // Don't select on dead sessions, only truly idle ones
771 if ( (ptr->state == CON_IDLE)
772 && (ptr->kill_me == 0)
773 && (ptr->client_socket > 0)
775 FD_SET(ptr->client_socket, &readfds);
776 if (ptr->client_socket > highest)
777 highest = ptr->client_socket;
779 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
782 "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
790 ptr->client_socket = -1;
795 end_critical_section(S_SESSION_TABLE);
797 // First, add the various master sockets to the fdset.
798 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
800 // Initialize the fdset.
802 tv.tv_sec = 0; // wake up every second if no input
805 FD_SET(serviceptr->msock, &readfds);
806 if (serviceptr->msock > highest) {
807 highest = serviceptr->msock;
809 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF)) {
810 // Gotcha! server socket dead? commit suicide!
811 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
812 server_shutting_down = 1;
819 // This loop just keeps going and going and going...
821 // TECHNICAL NOTE -- AJC 2022-JUN-20
822 // This loop was designed in the 20th Century when accept() was susceptible to the "thundering herd" problem.
823 // Today we can simplify it by having all worker threads block on accept() and the OS will do the right thing when a
824 // connection arrives and only unblock one thread. This will require a separate execution path for non-client activity
825 // such as housekeeping but maybe we can move those to a "supervisor thread".
827 // This implementation works and is not broken in any way, but if we can simplify it we should.
829 void *worker_thread(void *blah) {
832 CitContext *bind_me = NULL;
837 struct ServiceFunctionHook *serviceptr;
838 int ssock; // Descriptor for client socket
839 CitContext *con = NULL; // Temporary context pointer
842 pthread_mutex_lock(&ThreadCountMutex);
844 pthread_mutex_unlock(&ThreadCountMutex);
846 while (!server_shutting_down) {
848 // make doubly sure we're not holding any stale db handles which might cause a deadlock
850 do_select: force_purge = 0;
851 bind_me = NULL; // Which session shall we handle?
853 // Initialize the fdset
857 // First, add the various master sockets to the fdset.
858 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
859 FD_SET(serviceptr->msock, &readfds);
860 if (serviceptr->msock > highest) {
861 highest = serviceptr->msock;
865 // Next, add all of the client sockets.
866 begin_critical_section(S_SESSION_TABLE);
867 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
868 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
871 // Don't select on dead sessions, only truly idle ones
872 if ( (ptr->state == CON_IDLE)
873 && (ptr->kill_me == 0)
874 && (ptr->client_socket > 0)
876 FD_SET(ptr->client_socket, &readfds);
877 if (ptr->client_socket > highest)
878 highest = ptr->client_socket;
880 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
882 ptr->state = CON_EXECUTING;
885 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
887 ptr->state = CON_STARTING;
891 end_critical_section(S_SESSION_TABLE);
897 // If we got this far, it means that there are no sessions
898 // which a previous thread marked for attention, so we go
899 // ahead and get ready to select().
901 if (!server_shutting_down) {
902 tv.tv_sec = 1; // wake up every second if no input
904 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
911 // Now figure out who made this select() unblock.
912 // First, check for an error or exit condition.
914 if (errno == EBADF) {
915 syslog(LOG_ERR, "sysdep: select() failed: %m");
919 if (errno != EINTR) {
920 syslog(LOG_ERR, "sysdep: exiting: %m");
921 server_shutting_down = 1;
924 if (server_shutting_down) {
931 else if (retval == 0) {
932 if (server_shutting_down) {
938 // Next, check to see if it's a new client connecting on a master socket.
940 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
942 if (FD_ISSET(serviceptr->msock, &readfds)) {
943 ssock = accept(serviceptr->msock, NULL, 0);
945 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
947 // The master socket is non-blocking but the client
948 // sockets need to be blocking, otherwise certain
949 // operations barf on FreeBSD. Not a fatal error.
950 if (fcntl(ssock, F_SETFL, 0) < 0) {
951 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
954 // New context will be created already
955 // set up in the CON_EXECUTING state.
956 con = CreateNewContext();
958 // Assign our new socket number to it.
959 con->tcp_port = serviceptr->tcp_port;
960 con->client_socket = ssock;
961 con->h_command_function = serviceptr->h_command_function;
962 con->h_async_function = serviceptr->h_async_function;
963 con->h_greeting_function = serviceptr->h_greeting_function;
964 con->ServiceName = serviceptr->ServiceName;
966 // Connections on a local client are always from the same host
967 if (serviceptr->sockpath != NULL) {
968 con->is_local_client = 1;
971 // Set the SO_REUSEADDR socket option
973 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
974 con->state = CON_GREETING;
982 // It must be a client socket. Find a context that has data
983 // waiting on its socket *and* is in the CON_IDLE state. Any
984 // active sockets other than our chosen one are marked as
985 // CON_READY so the next thread that comes around can just bind
986 // to one without having to select() again.
987 begin_critical_section(S_SESSION_TABLE);
988 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
989 int checkfd = ptr->client_socket;
990 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
991 if (FD_ISSET(checkfd, &readfds)) {
992 ptr->input_waiting = 1;
994 bind_me = ptr; // I choose you!
995 bind_me->state = CON_EXECUTING;
998 ptr->state = CON_READY;
1000 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1002 bind_me = ptr; // I choose you!
1003 bind_me->state = CON_EXECUTING;
1006 ptr->state = CON_READY;
1011 end_critical_section(S_SESSION_TABLE);
1014 // We're bound to a session
1015 pthread_mutex_lock(&ThreadCountMutex);
1017 pthread_mutex_unlock(&ThreadCountMutex);
1019 if (bind_me != NULL) {
1020 become_session(bind_me);
1022 if (bind_me->state == CON_STARTING) {
1023 bind_me->state = CON_EXECUTING;
1024 begin_session(bind_me);
1025 bind_me->h_greeting_function();
1027 // If the client has sent a command, execute it.
1028 if (CC->input_waiting) {
1029 CC->h_command_function();
1031 while (HaveMoreLinesWaiting(CC))
1032 CC->h_command_function();
1034 CC->input_waiting = 0;
1037 // If there are asynchronous messages waiting and the client supports it, do those now
1038 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1039 CC->h_async_function();
1040 CC->async_waiting = 0;
1043 force_purge = CC->kill_me;
1044 become_session(NULL);
1045 bind_me->state = CON_IDLE;
1048 dead_session_purge(force_purge);
1051 pthread_mutex_lock(&ThreadCountMutex);
1053 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1054 (num_workers > CtdlGetConfigInt("c_min_workers")))
1057 pthread_mutex_unlock(&ThreadCountMutex);
1060 pthread_mutex_unlock(&ThreadCountMutex);
1063 // If control reaches this point, the server is shutting down
1064 pthread_mutex_lock(&ThreadCountMutex);
1066 pthread_mutex_unlock(&ThreadCountMutex);
1072 // Translate text facility name to syslog.h defined value.
1073 int SyslogFacility(char *name)
1082 { LOG_KERN, "kern" },
1083 { LOG_USER, "user" },
1084 { LOG_MAIL, "mail" },
1085 { LOG_DAEMON, "daemon" },
1086 { LOG_AUTH, "auth" },
1087 { LOG_SYSLOG, "syslog" },
1089 { LOG_NEWS, "news" },
1090 { LOG_UUCP, "uucp" },
1091 { LOG_LOCAL0, "local0" },
1092 { LOG_LOCAL1, "local1" },
1093 { LOG_LOCAL2, "local2" },
1094 { LOG_LOCAL3, "local3" },
1095 { LOG_LOCAL4, "local4" },
1096 { LOG_LOCAL5, "local5" },
1097 { LOG_LOCAL6, "local6" },
1098 { LOG_LOCAL7, "local7" },
1101 for(i = 0; facTbl[i].name != NULL; i++) {
1102 if(!strcasecmp(name, facTbl[i].name))
1103 return facTbl[i].facility;