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-2021 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, destruct_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 - backtrace follows:", signum);
59 bt_size = backtrace(bt, 1024);
60 bt_syms = backtrace_symbols(bt, bt_size);
61 for (i = 1; i < bt_size; i++) {
62 syslog(LOG_DEBUG, "%s", bt_syms[i]);
67 server_shutting_down = 1;
71 // Some initialization stuff...
72 void init_sysdep(void) {
75 // Avoid vulnerabilities related to FD_SETSIZE if we can.
79 getrlimit(RLIMIT_NOFILE, &rl);
80 rl.rlim_cur = FD_SETSIZE;
81 rl.rlim_max = FD_SETSIZE;
82 setrlimit(RLIMIT_NOFILE, &rl);
86 // If we've got OpenSSL, we're going to use it.
91 if (pthread_key_create(&ThreadKey, NULL) != 0) { // TSD for threads
92 syslog(LOG_ERR, "pthread_key_create() : %m");
96 if (pthread_key_create(&MyConKey, NULL) != 0) { // TSD for sessions
97 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
101 // Interript, hangup, and terminate signals should cause the server to shut down.
103 sigaddset(&set, SIGINT);
104 sigaddset(&set, SIGHUP);
105 sigaddset(&set, SIGTERM);
106 sigaddset(&set, SIGSEGV);
107 sigprocmask(SIG_UNBLOCK, &set, NULL);
109 signal(SIGINT, signal_cleanup);
110 signal(SIGHUP, signal_cleanup);
111 signal(SIGTERM, signal_cleanup);
112 signal(SIGSEGV, signal_cleanup);
114 // Do not shut down the server on broken pipe signals, otherwise the
115 // whole Citadel service would come down whenever a single client
117 signal(SIGPIPE, SIG_IGN);
121 // This is a generic function to set up a master socket for listening on
122 // a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
124 // ip_addr IP address to bind
125 // port_number port number to bind
126 // queue_len number of incoming connections to allow in the queue
127 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len) {
129 struct sockaddr_in6 sin6;
130 struct sockaddr_in sin4;
134 memset(&sin6, 0, sizeof(sin6));
135 memset(&sin4, 0, sizeof(sin4));
136 sin6.sin6_family = AF_INET6;
137 sin4.sin_family = AF_INET;
139 if ( (ip_addr == NULL) // any IPv6
140 || (IsEmptyStr(ip_addr))
141 || (!strcmp(ip_addr, "*"))
144 sin6.sin6_addr = in6addr_any;
146 else if (!strcmp(ip_addr, "0.0.0.0")) // any IPv4
149 sin4.sin_addr.s_addr = INADDR_ANY;
151 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) // specific IPv4
154 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
155 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
159 else // specific IPv6
162 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
163 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
168 if (port_number == 0) {
169 syslog(LOG_ALERT, "tcpserver: no port number was specified");
172 sin6.sin6_port = htons((u_short) port_number);
173 sin4.sin_port = htons((u_short) port_number);
175 p = getprotobyname("tcp");
177 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
181 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
183 syslog(LOG_ALERT, "tcpserver: socket: %m");
186 // Set some socket options that make sense.
188 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
190 if (ip_version == 6) {
191 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
194 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
198 syslog(LOG_ALERT, "tcpserver: bind: %m");
202 fcntl(s, F_SETFL, O_NONBLOCK);
204 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
205 syslog(LOG_ALERT, "tcpserver: listen: %m");
212 // Create a Unix domain socket and listen on it
213 int ctdl_uds_server(char *sockpath, int queue_len) {
214 struct sockaddr_un addr;
217 int actual_queue_len;
218 #ifdef HAVE_STRUCT_UCRED
222 actual_queue_len = queue_len;
223 if (actual_queue_len < 5) actual_queue_len = 5;
225 i = unlink(sockpath);
226 if ((i != 0) && (errno != ENOENT)) {
227 syslog(LOG_ERR, "udsserver: %m");
231 memset(&addr, 0, sizeof(addr));
232 addr.sun_family = AF_UNIX;
233 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
235 s = socket(AF_UNIX, SOCK_STREAM, 0);
237 syslog(LOG_ERR, "udsserver: socket: %m");
241 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
242 syslog(LOG_ERR, "udsserver: bind: %m");
246 // set to nonblock - we need this for some obscure situations
247 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
248 syslog(LOG_ERR, "udsserver: fcntl: %m");
253 if (listen(s, actual_queue_len) < 0) {
254 syslog(LOG_ERR, "udsserver: listen: %m");
258 #ifdef HAVE_STRUCT_UCRED
259 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
262 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
267 // The following functions implement output buffering on operating systems which
268 // support it (such as Linux and various BSD flavors).
271 # define HAVE_TCP_BUFFERING
274 # define HAVE_TCP_BUFFERING
275 # define TCP_CORK TCP_NOPUSH
278 #endif // HAVE_DARWIN
280 static unsigned on = 1, off = 0;
282 void buffer_output(void) {
283 #ifdef HAVE_TCP_BUFFERING
285 if (!CC->redirect_ssl)
287 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
291 void unbuffer_output(void) {
292 #ifdef HAVE_TCP_BUFFERING
294 if (!CC->redirect_ssl)
296 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
300 void flush_output(void) {
301 #ifdef HAVE_TCP_BUFFERING
302 struct CitContext *CCC = CC;
303 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
304 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
309 // close the client socket
310 void client_close(void) {
311 CitContext *CCC = CC;
314 if (CCC->client_socket <= 0) return;
315 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
316 close(CCC->client_socket);
317 CCC->client_socket = -1 ;
321 // Send binary data to the client.
322 int client_write(const char *buf, int nbytes)
324 int bytes_written = 0;
326 #ifndef HAVE_TCP_BUFFERING
327 int old_buffer_len = 0;
333 if (nbytes < 1) return(0);
337 if (Ctx->redirect_buffer != NULL) {
338 StrBufAppendBufPlain(Ctx->redirect_buffer,
344 if (Ctx->redirect_ssl) {
345 client_write_ssl(buf, nbytes);
349 if (Ctx->client_socket == -1) return -1;
351 fdflags = fcntl(Ctx->client_socket, F_GETFL);
353 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
354 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
356 FD_SET(Ctx->client_socket, &wset);
357 if (select(1, NULL, &wset, NULL, NULL) == -1) {
360 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
361 if (server_shutting_down) {
362 CC->kill_me = KILLME_SELECT_INTERRUPTED;
365 // can't trust fd's and stuff so we need to re-create them
369 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
371 Ctx->kill_me = KILLME_SELECT_FAILED;
377 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
379 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
381 Ctx->kill_me = KILLME_WRITE_FAILED;
384 bytes_written = bytes_written + retval;
389 void cputbuf(const StrBuf *Buf) {
390 client_write(ChrPtr(Buf), StrLength(Buf));
394 // Send formatted printable data to the client.
395 // Implemented in terms of client_write() so it's technically not sysdep...
396 void cprintf(const char *format, ...) {
400 va_start(arg_ptr, format);
401 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
402 buf[sizeof buf - 2] = '\n';
403 client_write(buf, strlen(buf));
408 // Read data from the client socket.
410 // sock socket fd to read from
411 // buf buffer to read into
412 // bytes number of bytes to read
413 // timeout Number of seconds to wait before timing out
415 // Possible return values:
416 // 1 Requested number of bytes has been read.
417 // 0 Request timed out.
418 // -1 Connection is broken, or other error.
419 int client_read_blob(StrBuf *Target, int bytes, int timeout) {
425 if (CCC->redirect_ssl) {
426 retval = client_read_sslblob(Target, bytes, timeout);
428 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
434 retval = StrBufReadBLOBBuffered(Target,
436 &CCC->RecvBuf.ReadWritePointer,
444 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
453 // to make client_read_random_blob() more efficient, increase buffer size.
454 // just use in greeting function, else your buffer may be flushed
455 void client_set_inbound_buf(long N)
458 FlushStrBuf(CCC->RecvBuf.Buf);
459 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
462 int client_read_random_blob(StrBuf *Target, int timeout)
467 rc = client_read_blob(Target, 1, timeout);
473 len = StrLength(CCC->RecvBuf.Buf);
474 pch = ChrPtr(CCC->RecvBuf.Buf);
478 if (CCC->RecvBuf.ReadWritePointer != NULL) {
479 len -= CCC->RecvBuf.ReadWritePointer - pch;
480 pch = CCC->RecvBuf.ReadWritePointer;
482 StrBufAppendBufPlain(Target, pch, len, 0);
483 FlushStrBuf(CCC->RecvBuf.Buf);
484 CCC->RecvBuf.ReadWritePointer = NULL;
485 return StrLength(Target);
493 int client_read_to(char *buf, int bytes, int timeout)
498 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
507 ChrPtr(CCC->MigrateBuf),
508 StrLength(CCC->MigrateBuf) + 1);
509 FlushStrBuf(CCC->MigrateBuf);
515 int HaveMoreLinesWaiting(CitContext *CCC) {
516 if ((CCC->kill_me != 0) ||
517 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
518 (StrLength(CCC->RecvBuf.Buf) == 0) &&
519 (CCC->client_socket != -1)) )
526 // Read data from the client socket with default timeout.
527 // (This is implemented in terms of client_read_to() and could be
528 // justifiably moved out of sysdep.c)
529 INLINE int client_read(char *buf, int bytes) {
530 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
533 int CtdlClientGetLine(StrBuf *Target) {
540 if (CCC->redirect_ssl) {
541 rc = client_readline_sslbuffer(Target, CCC->RecvBuf.Buf, &CCC->RecvBuf.ReadWritePointer, 1);
547 rc = StrBufTCP_read_buffered_line_fast(Target,
549 &CCC->RecvBuf.ReadWritePointer,
560 // Get a LF-terminated line of text from the client.
561 // (This is implemented in terms of client_read() and could be
562 // justifiably moved out of sysdep.c)
563 int client_getln(char *buf, int bufsize) {
568 retval = CtdlClientGetLine(CCC->MigrateBuf);
573 i = StrLength(CCC->MigrateBuf);
574 pCh = ChrPtr(CCC->MigrateBuf);
575 // Strip the trailing LF, and the trailing CR if present.
579 && ( (pCh[i - 1]==13)
580 || ( pCh[i - 1]==10)) ) {
586 FlushStrBuf(CCC->MigrateBuf);
588 safestrncpy(&buf[i], "000", bufsize - i);
594 // Cleanup any contexts that are left lying around
595 void close_masters(void) {
596 struct ServiceFunctionHook *serviceptr;
599 // close all protocol master sockets
600 for (serviceptr = ServiceHookTable; serviceptr != NULL;
601 serviceptr = serviceptr->next ) {
603 if (serviceptr->tcp_port > 0) {
604 if (serviceptr->msock == -1) {
605 Text = "not closing again";
610 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
615 serviceptr->tcp_port = 0;
618 if (serviceptr->sockpath != NULL) {
619 if (serviceptr->msock == -1) {
620 Text = "not closing again";
625 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
632 if (serviceptr->msock != -1) {
633 close(serviceptr->msock);
634 serviceptr->msock = -1;
637 // If it's a Unix domain socket, remove the file.
638 if (serviceptr->sockpath != NULL) {
639 unlink(serviceptr->sockpath);
640 serviceptr->sockpath = NULL;
646 // The system-dependent part of master_cleanup() - close the master socket.
647 void sysdep_master_cleanup(void) {
658 void graceful_shutdown(int signum) {
659 kill(current_child, signum);
660 unlink(file_pid_file);
665 int nFireUpsNonRestart = 0;
668 // Start running as a daemon.
669 void start_daemon(int unused) {
676 // Close stdin/stdout/stderr and replace them with /dev/null.
677 // We don't just call close() because we don't want these fd's
678 // to be reused for other files.
684 signal(SIGHUP, SIG_IGN);
685 signal(SIGINT, SIG_IGN);
686 signal(SIGQUIT, SIG_IGN);
690 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
691 (freopen("/dev/null", "w", stdout) != stdout) ||
692 (freopen("/dev/null", "w", stderr) != stderr)
694 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
698 current_child = fork();
699 signal(SIGTERM, graceful_shutdown);
700 if (current_child < 0) {
704 else if (current_child == 0) {
705 return; // continue starting citadel.
708 fp = fopen(file_pid_file, "w");
710 fprintf(fp, ""F_PID_T"\n", getpid());
713 waitpid(current_child, &status, 0);
715 nFireUpsNonRestart = nFireUps;
717 // Exit code 0 means the watcher should exit
718 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
722 // Exit code 101-109 means the watcher should exit
723 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
727 // Any other exit code, or no exit code, means we should restart.
731 ForkedPid = current_child;
734 } while (do_restart);
736 unlink(file_pid_file);
737 exit(WEXITSTATUS(status));
741 void checkcrash(void) {
742 if (nFireUpsNonRestart != nFireUps) {
744 CrashMail = NewStrBuf();
745 syslog(LOG_ALERT, "sysdep: posting crash message");
746 StrBufPrintf(CrashMail,
748 " The Citadel server process (citserver) terminated unexpectedly."
750 " This could be the result of a bug in the server program, or some external "
752 " You can obtain more information about this by enabling core dumps.\n \n"
753 " For more information, please see:\n \n"
754 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
757 " If you have already done this, the core dump is likely to be found at %score.%d\n"
759 ctdl_run_dir, ForkedPid);
760 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
761 FreeStrBuf(&CrashMail);
766 // Generic routine to convert a login name to a full name (gecos)
767 // Returns nonzero if a conversion took place
768 int convert_login(char NameToConvert[]) {
772 pw = getpwnam(NameToConvert);
777 strcpy(NameToConvert, pw->pw_gecos);
778 for (a=0; a<strlen(NameToConvert); ++a) {
779 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
786 void HuntBadSession(void) {
791 struct ServiceFunctionHook *serviceptr;
793 // Next, add all of the client sockets
794 begin_critical_section(S_SESSION_TABLE);
795 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
796 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
798 // Initialize the fdset.
801 tv.tv_sec = 0; // wake up every second if no input
804 // Don't select on dead sessions, only truly idle ones
805 if ( (ptr->state == CON_IDLE)
806 && (ptr->kill_me == 0)
807 && (ptr->client_socket > 0)
809 FD_SET(ptr->client_socket, &readfds);
810 if (ptr->client_socket > highest)
811 highest = ptr->client_socket;
813 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
817 "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
825 ptr->client_socket = -1;
830 end_critical_section(S_SESSION_TABLE);
832 // First, add the various master sockets to the fdset.
833 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
835 // Initialize the fdset.
837 tv.tv_sec = 0; // wake up every second if no input
840 FD_SET(serviceptr->msock, &readfds);
841 if (serviceptr->msock > highest) {
842 highest = serviceptr->msock;
844 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
847 // Gotcha! server socket dead? commit suicide!
848 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
849 server_shutting_down = 1;
856 // This loop just keeps going and going and going...
857 void *worker_thread(void *blah) {
860 CitContext *bind_me = NULL;
865 struct ServiceFunctionHook *serviceptr;
866 int ssock; // Descriptor for client socket
867 CitContext *con = NULL; // Temporary context pointer
870 pthread_mutex_lock(&ThreadCountMutex);
872 pthread_mutex_unlock(&ThreadCountMutex);
874 while (!server_shutting_down) {
876 // make doubly sure we're not holding any stale db handles which might cause a deadlock
878 do_select: force_purge = 0;
879 bind_me = NULL; // Which session shall we handle?
881 // Initialize the fdset
885 // First, add the various master sockets to the fdset.
886 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
887 FD_SET(serviceptr->msock, &readfds);
888 if (serviceptr->msock > highest) {
889 highest = serviceptr->msock;
893 // Next, add all of the client sockets.
894 begin_critical_section(S_SESSION_TABLE);
895 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
896 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
899 // Don't select on dead sessions, only truly idle ones
900 if ( (ptr->state == CON_IDLE)
901 && (ptr->kill_me == 0)
902 && (ptr->client_socket > 0)
904 FD_SET(ptr->client_socket, &readfds);
905 if (ptr->client_socket > highest)
906 highest = ptr->client_socket;
908 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
910 ptr->state = CON_EXECUTING;
913 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
915 ptr->state = CON_STARTING;
919 end_critical_section(S_SESSION_TABLE);
925 // If we got this far, it means that there are no sessions
926 // which a previous thread marked for attention, so we go
927 // ahead and get ready to select().
929 if (!server_shutting_down) {
930 tv.tv_sec = 1; // wake up every second if no input
932 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
939 // Now figure out who made this select() unblock.
940 // First, check for an error or exit condition.
942 if (errno == EBADF) {
943 syslog(LOG_ERR, "sysdep: select() failed: %m");
947 if (errno != EINTR) {
948 syslog(LOG_ERR, "sysdep: exiting: %m");
949 server_shutting_down = 1;
952 if (server_shutting_down) {
959 else if (retval == 0) {
960 if (server_shutting_down) {
966 // Next, check to see if it's a new client connecting on a master socket.
968 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
970 if (FD_ISSET(serviceptr->msock, &readfds)) {
971 ssock = accept(serviceptr->msock, NULL, 0);
973 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
975 // The master socket is non-blocking but the client
976 // sockets need to be blocking, otherwise certain
977 // operations barf on FreeBSD. Not a fatal error.
978 if (fcntl(ssock, F_SETFL, 0) < 0) {
979 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
982 // New context will be created already
983 // set up in the CON_EXECUTING state.
984 con = CreateNewContext();
986 // Assign our new socket number to it.
987 con->tcp_port = serviceptr->tcp_port;
988 con->client_socket = ssock;
989 con->h_command_function = serviceptr->h_command_function;
990 con->h_async_function = serviceptr->h_async_function;
991 con->h_greeting_function = serviceptr->h_greeting_function;
992 con->ServiceName = serviceptr->ServiceName;
994 // Connections on a local client are always from the same host
995 if (serviceptr->sockpath != NULL) {
996 con->is_local_client = 1;
999 // Set the SO_REUSEADDR socket option
1001 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1002 con->state = CON_GREETING;
1010 // It must be a client socket. Find a context that has data
1011 // waiting on its socket *and* is in the CON_IDLE state. Any
1012 // active sockets other than our chosen one are marked as
1013 // CON_READY so the next thread that comes around can just bind
1014 // to one without having to select() again.
1015 begin_critical_section(S_SESSION_TABLE);
1016 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1017 int checkfd = ptr->client_socket;
1018 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1019 if (FD_ISSET(checkfd, &readfds)) {
1020 ptr->input_waiting = 1;
1022 bind_me = ptr; // I choose you!
1023 bind_me->state = CON_EXECUTING;
1026 ptr->state = CON_READY;
1028 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1030 bind_me = ptr; // I choose you!
1031 bind_me->state = CON_EXECUTING;
1034 ptr->state = CON_READY;
1039 end_critical_section(S_SESSION_TABLE);
1042 // We're bound to a session
1043 pthread_mutex_lock(&ThreadCountMutex);
1045 pthread_mutex_unlock(&ThreadCountMutex);
1047 if (bind_me != NULL) {
1048 become_session(bind_me);
1050 if (bind_me->state == CON_STARTING) {
1051 bind_me->state = CON_EXECUTING;
1052 begin_session(bind_me);
1053 bind_me->h_greeting_function();
1055 // If the client has sent a command, execute it.
1056 if (CC->input_waiting) {
1057 CC->h_command_function();
1059 while (HaveMoreLinesWaiting(CC))
1060 CC->h_command_function();
1062 CC->input_waiting = 0;
1065 // If there are asynchronous messages waiting and the client supports it, do those now
1066 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1067 CC->h_async_function();
1068 CC->async_waiting = 0;
1071 force_purge = CC->kill_me;
1072 become_session(NULL);
1073 bind_me->state = CON_IDLE;
1076 dead_session_purge(force_purge);
1079 pthread_mutex_lock(&ThreadCountMutex);
1081 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1082 (num_workers > CtdlGetConfigInt("c_min_workers")))
1085 pthread_mutex_unlock(&ThreadCountMutex);
1088 pthread_mutex_unlock(&ThreadCountMutex);
1091 // If control reaches this point, the server is shutting down
1092 pthread_mutex_lock(&ThreadCountMutex);
1094 pthread_mutex_unlock(&ThreadCountMutex);
1100 // Translate text facility name to syslog.h defined value.
1101 int SyslogFacility(char *name)
1110 { LOG_KERN, "kern" },
1111 { LOG_USER, "user" },
1112 { LOG_MAIL, "mail" },
1113 { LOG_DAEMON, "daemon" },
1114 { LOG_AUTH, "auth" },
1115 { LOG_SYSLOG, "syslog" },
1117 { LOG_NEWS, "news" },
1118 { LOG_UUCP, "uucp" },
1119 { LOG_LOCAL0, "local0" },
1120 { LOG_LOCAL1, "local1" },
1121 { LOG_LOCAL2, "local2" },
1122 { LOG_LOCAL3, "local3" },
1123 { LOG_LOCAL4, "local4" },
1124 { LOG_LOCAL5, "local5" },
1125 { LOG_LOCAL6, "local6" },
1126 { LOG_LOCAL7, "local7" },
1129 for(i = 0; facTbl[i].name != NULL; i++) {
1130 if(!strcasecmp(name, facTbl[i].name))
1131 return facTbl[i].facility;