2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * might need tweaking when run on different operating system variants.
7 * Copyright (c) 1987-2021 by the citadel.org team
9 * This program is open source software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License, version 3.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
26 #include <sys/syslog.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
35 #define SHOW_ME_VAPPEND_PRINTF
36 #include <libcitadel.h>
37 #include "citserver.h"
39 #include "ctdl_module.h"
40 #include "sysdep_decls.h"
41 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
42 #include "housekeeping.h"
46 * Signal handler to shut down the server.
49 volatile int exit_signal = 0;
50 volatile int shutdown_and_halt = 0;
51 volatile int restart_server = 0;
52 volatile int running_as_daemon = 0;
55 static RETSIGTYPE signal_cleanup(int signum) {
56 syslog(LOG_DEBUG, "sysdep: caught signal %d; shutting down.", signum);
58 server_shutting_down = 1;
62 static RETSIGTYPE signal_exit(int signum) {
68 * Some initialization stuff...
70 void init_sysdep(void) {
73 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
77 getrlimit(RLIMIT_NOFILE, &rl);
78 rl.rlim_cur = FD_SETSIZE;
79 rl.rlim_max = FD_SETSIZE;
80 setrlimit(RLIMIT_NOFILE, &rl);
84 /* If we've got OpenSSL, we're going to use it. */
89 if (pthread_key_create(&ThreadKey, NULL) != 0) { // TSD for threads
90 syslog(LOG_ERR, "pthread_key_create() : %m");
94 if (pthread_key_create(&MyConKey, NULL) != 0) { // TSD for sessions
95 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
100 * Interript, hangup, and terminate signals should cause the server
101 * to gracefully clean up and shut down.
104 sigaddset(&set, SIGINT);
105 sigaddset(&set, SIGHUP);
106 sigaddset(&set, SIGTERM);
107 sigprocmask(SIG_UNBLOCK, &set, NULL);
109 signal(SIGINT, signal_cleanup);
110 signal(SIGHUP, signal_cleanup);
111 signal(SIGTERM, signal_cleanup);
112 signal(SIGUSR2, signal_exit);
115 * Do not shut down the server on broken pipe signals, otherwise the
116 * whole Citadel service would come down whenever a single client
119 signal(SIGPIPE, SIG_IGN);
124 * This is a generic function to set up a master socket for listening on
125 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
127 * ip_addr IP address to bind
128 * port_number port number to bind
129 * queue_len number of incoming connections to allow in the queue
131 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len)
134 struct sockaddr_in6 sin6;
135 struct sockaddr_in sin4;
139 memset(&sin6, 0, sizeof(sin6));
140 memset(&sin4, 0, sizeof(sin4));
141 sin6.sin6_family = AF_INET6;
142 sin4.sin_family = AF_INET;
144 if ( (ip_addr == NULL) /* any IPv6 */
145 || (IsEmptyStr(ip_addr))
146 || (!strcmp(ip_addr, "*"))
149 sin6.sin6_addr = in6addr_any;
151 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
154 sin4.sin_addr.s_addr = INADDR_ANY;
156 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
159 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
160 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
164 else /* specific IPv6 */
167 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
168 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
173 if (port_number == 0) {
174 syslog(LOG_ALERT, "tcpserver: no port number was specified");
177 sin6.sin6_port = htons((u_short) port_number);
178 sin4.sin_port = htons((u_short) port_number);
180 p = getprotobyname("tcp");
182 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
186 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
188 syslog(LOG_ALERT, "tcpserver: socket: %m");
191 /* Set some socket options that make sense. */
193 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
195 if (ip_version == 6) {
196 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
199 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
203 syslog(LOG_ALERT, "tcpserver: bind: %m");
207 fcntl(s, F_SETFL, O_NONBLOCK);
209 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
210 syslog(LOG_ALERT, "tcpserver: listen: %m");
218 * Create a Unix domain socket and listen on it
220 int ctdl_uds_server(char *sockpath, int queue_len)
222 struct sockaddr_un addr;
225 int actual_queue_len;
226 #ifdef HAVE_STRUCT_UCRED
230 actual_queue_len = queue_len;
231 if (actual_queue_len < 5) actual_queue_len = 5;
233 i = unlink(sockpath);
234 if ((i != 0) && (errno != ENOENT)) {
235 syslog(LOG_ERR, "udsserver: %m");
239 memset(&addr, 0, sizeof(addr));
240 addr.sun_family = AF_UNIX;
241 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
243 s = socket(AF_UNIX, SOCK_STREAM, 0);
245 syslog(LOG_ERR, "udsserver: socket: %m");
249 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
250 syslog(LOG_ERR, "udsserver: bind: %m");
254 /* set to nonblock - we need this for some obscure situations */
255 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
256 syslog(LOG_ERR, "udsserver: fcntl: %m");
261 if (listen(s, actual_queue_len) < 0) {
262 syslog(LOG_ERR, "udsserver: listen: %m");
266 #ifdef HAVE_STRUCT_UCRED
267 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
270 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
276 * The following functions implement output buffering on operating systems which
277 * support it (such as Linux and various BSD flavors).
281 # define HAVE_TCP_BUFFERING
284 # define HAVE_TCP_BUFFERING
285 # define TCP_CORK TCP_NOPUSH
287 #endif /* TCP_CORK */
288 #endif /* HAVE_DARWIN */
290 static unsigned on = 1, off = 0;
292 void buffer_output(void) {
293 #ifdef HAVE_TCP_BUFFERING
295 if (!CC->redirect_ssl)
297 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
301 void unbuffer_output(void) {
302 #ifdef HAVE_TCP_BUFFERING
304 if (!CC->redirect_ssl)
306 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
310 void flush_output(void) {
311 #ifdef HAVE_TCP_BUFFERING
312 struct CitContext *CCC = CC;
313 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
314 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
319 static void flush_client_inbuf(void)
323 FlushStrBuf(CCC->ReadBuf);
324 CCC->RecvBuf->ReadWritePointer = NULL;
330 * client_close() ... close the client socket
332 void client_close(void) {
333 CitContext *CCC = CC;
336 if (CCC->client_socket <= 0) return;
337 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
338 close(CCC->client_socket);
339 CCC->client_socket = -1 ;
344 * client_write() ... Send binary data to the client.
346 int client_write(const char *buf, int nbytes)
348 int bytes_written = 0;
350 #ifndef HAVE_TCP_BUFFERING
351 int old_buffer_len = 0;
357 if (nbytes < 1) return(0);
361 if (Ctx->redirect_buffer != NULL) {
362 StrBufAppendBufPlain(Ctx->redirect_buffer,
368 if (Ctx->redirect_ssl) {
369 client_write_ssl(buf, nbytes);
373 if (Ctx->client_socket == -1) return -1;
375 fdflags = fcntl(Ctx->client_socket, F_GETFL);
377 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
378 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
380 FD_SET(Ctx->client_socket, &wset);
381 if (select(1, NULL, &wset, NULL, NULL) == -1) {
384 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
385 if (server_shutting_down) {
386 CC->kill_me = KILLME_SELECT_INTERRUPTED;
389 /* can't trust fd's and stuff so we need to re-create them */
393 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
395 Ctx->kill_me = KILLME_SELECT_FAILED;
401 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
403 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
405 Ctx->kill_me = KILLME_WRITE_FAILED;
408 bytes_written = bytes_written + retval;
413 void cputbuf(const StrBuf *Buf) {
414 client_write(ChrPtr(Buf), StrLength(Buf));
419 * cprintf() Send formatted printable data to the client.
420 * Implemented in terms of client_write() so it's technically not sysdep...
422 void cprintf(const char *format, ...) {
426 va_start(arg_ptr, format);
427 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
428 buf[sizeof buf - 2] = '\n';
429 client_write(buf, strlen(buf));
435 * Read data from the client socket.
437 * sock socket fd to read from
438 * buf buffer to read into
439 * bytes number of bytes to read
440 * timeout Number of seconds to wait before timing out
442 * Possible return values:
443 * 1 Requested number of bytes has been read.
444 * 0 Request timed out.
445 * -1 Connection is broken, or other error.
447 int client_read_blob(StrBuf *Target, int bytes, int timeout)
454 if (CCC->redirect_ssl) {
455 retval = client_read_sslblob(Target, bytes, timeout);
457 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
463 retval = StrBufReadBLOBBuffered(Target,
465 &CCC->RecvBuf.ReadWritePointer,
473 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
483 * to make client_read_random_blob() more efficient, increase buffer size.
484 * just use in greeting function, else your buffer may be flushed
486 void client_set_inbound_buf(long N)
489 FlushStrBuf(CCC->RecvBuf.Buf);
490 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
493 int client_read_random_blob(StrBuf *Target, int timeout)
498 rc = client_read_blob(Target, 1, timeout);
504 len = StrLength(CCC->RecvBuf.Buf);
505 pch = ChrPtr(CCC->RecvBuf.Buf);
509 if (CCC->RecvBuf.ReadWritePointer != NULL) {
510 len -= CCC->RecvBuf.ReadWritePointer - pch;
511 pch = CCC->RecvBuf.ReadWritePointer;
513 StrBufAppendBufPlain(Target, pch, len, 0);
514 FlushStrBuf(CCC->RecvBuf.Buf);
515 CCC->RecvBuf.ReadWritePointer = NULL;
516 return StrLength(Target);
524 int client_read_to(char *buf, int bytes, int timeout)
529 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
538 ChrPtr(CCC->MigrateBuf),
539 StrLength(CCC->MigrateBuf) + 1);
540 FlushStrBuf(CCC->MigrateBuf);
546 int HaveMoreLinesWaiting(CitContext *CCC) {
547 if ((CCC->kill_me != 0) ||
548 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
549 (StrLength(CCC->RecvBuf.Buf) == 0) &&
550 (CCC->client_socket != -1)) )
558 * Read data from the client socket with default timeout.
559 * (This is implemented in terms of client_read_to() and could be
560 * justifiably moved out of sysdep.c)
562 INLINE int client_read(char *buf, int bytes) {
563 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
566 int CtdlClientGetLine(StrBuf *Target) {
573 if (CCC->redirect_ssl) {
574 rc = client_readline_sslbuffer(Target, CCC->RecvBuf.Buf, &CCC->RecvBuf.ReadWritePointer, 1);
580 rc = StrBufTCP_read_buffered_line_fast(Target,
582 &CCC->RecvBuf.ReadWritePointer,
594 * client_getln() ... Get a LF-terminated line of text from the client.
595 * (This is implemented in terms of client_read() and could be
596 * justifiably moved out of sysdep.c)
598 int client_getln(char *buf, int bufsize) {
603 retval = CtdlClientGetLine(CCC->MigrateBuf);
608 i = StrLength(CCC->MigrateBuf);
609 pCh = ChrPtr(CCC->MigrateBuf);
610 /* Strip the trailing LF, and the trailing CR if present.
615 && ( (pCh[i - 1]==13)
616 || ( pCh[i - 1]==10)) ) {
622 FlushStrBuf(CCC->MigrateBuf);
624 safestrncpy(&buf[i], "000", bufsize - i);
631 * Cleanup any contexts that are left lying around
633 void close_masters(void) {
634 struct ServiceFunctionHook *serviceptr;
638 * close all protocol master sockets
640 for (serviceptr = ServiceHookTable; serviceptr != NULL;
641 serviceptr = serviceptr->next ) {
643 if (serviceptr->tcp_port > 0) {
644 if (serviceptr->msock == -1) {
645 Text = "not closing again";
650 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
655 serviceptr->tcp_port = 0;
658 if (serviceptr->sockpath != NULL) {
659 if (serviceptr->msock == -1) {
660 Text = "not closing again";
665 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
672 if (serviceptr->msock != -1) {
673 close(serviceptr->msock);
674 serviceptr->msock = -1;
677 /* If it's a Unix domain socket, remove the file. */
678 if (serviceptr->sockpath != NULL) {
679 unlink(serviceptr->sockpath);
680 serviceptr->sockpath = NULL;
687 * The system-dependent part of master_cleanup() - close the master socket.
689 void sysdep_master_cleanup(void) {
700 void graceful_shutdown(int signum) {
701 kill(current_child, signum);
702 unlink(file_pid_file);
707 int nFireUpsNonRestart = 0;
711 * Start running as a daemon.
713 void start_daemon(int unused) {
720 //if (chdir(ctdl_run_dir) != 0) {
721 //syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
724 /* Close stdin/stdout/stderr and replace them with /dev/null.
725 * We don't just call close() because we don't want these fd's
726 * to be reused for other files.
733 signal(SIGHUP, SIG_IGN);
734 signal(SIGINT, SIG_IGN);
735 signal(SIGQUIT, SIG_IGN);
739 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
740 (freopen("/dev/null", "w", stdout) != stdout) ||
741 (freopen("/dev/null", "w", stderr) != stderr)
743 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
747 current_child = fork();
748 signal(SIGTERM, graceful_shutdown);
749 if (current_child < 0) {
753 else if (current_child == 0) {
754 return; /* continue starting citadel. */
757 fp = fopen(file_pid_file, "w");
759 fprintf(fp, ""F_PID_T"\n", getpid());
762 waitpid(current_child, &status, 0);
764 nFireUpsNonRestart = nFireUps;
766 /* Exit code 0 means the watcher should exit */
767 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
771 /* Exit code 101-109 means the watcher should exit */
772 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
776 /* Any other exit code, or no exit code, means we should restart. */
780 ForkedPid = current_child;
783 } while (do_restart);
785 unlink(file_pid_file);
786 exit(WEXITSTATUS(status));
790 void checkcrash(void) {
791 if (nFireUpsNonRestart != nFireUps) {
793 CrashMail = NewStrBuf();
794 syslog(LOG_ALERT, "sysdep: posting crash message");
795 StrBufPrintf(CrashMail,
797 " The Citadel server process (citserver) terminated unexpectedly."
799 " This could be the result of a bug in the server program, or some external "
801 " You can obtain more information about this by enabling core dumps.\n \n"
802 " For more information, please see:\n \n"
803 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
806 " If you have already done this, the core dump is likely to be found at %score.%d\n"
808 ctdl_run_dir, ForkedPid);
809 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
810 FreeStrBuf(&CrashMail);
816 * Generic routine to convert a login name to a full name (gecos)
817 * Returns nonzero if a conversion took place
819 int convert_login(char NameToConvert[]) {
823 pw = getpwnam(NameToConvert);
828 strcpy(NameToConvert, pw->pw_gecos);
829 for (a=0; a<strlen(NameToConvert); ++a) {
830 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
837 void HuntBadSession(void) {
842 struct ServiceFunctionHook *serviceptr;
844 /* Next, add all of the client sockets. */
845 begin_critical_section(S_SESSION_TABLE);
846 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
847 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
849 /* Initialize the fdset. */
852 tv.tv_sec = 0; /* wake up every second if no input */
855 /* Don't select on dead sessions, only truly idle ones */
856 if ( (ptr->state == CON_IDLE)
857 && (ptr->kill_me == 0)
858 && (ptr->client_socket > 0)
860 FD_SET(ptr->client_socket, &readfds);
861 if (ptr->client_socket > highest)
862 highest = ptr->client_socket;
864 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
868 "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
876 ptr->client_socket = -1;
881 end_critical_section(S_SESSION_TABLE);
883 /* First, add the various master sockets to the fdset. */
884 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
886 /* Initialize the fdset. */
888 tv.tv_sec = 0; /* wake up every second if no input */
891 FD_SET(serviceptr->msock, &readfds);
892 if (serviceptr->msock > highest) {
893 highest = serviceptr->msock;
895 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
898 /* Gotcha! server socket dead? commit suicide! */
899 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
900 server_shutting_down = 1;
908 * This loop just keeps going and going and going...
910 void *worker_thread(void *blah) {
913 CitContext *bind_me = NULL;
918 struct ServiceFunctionHook *serviceptr;
919 int ssock; /* Descriptor for client socket */
920 CitContext *con = NULL; /* Temporary context pointer */
923 pthread_mutex_lock(&ThreadCountMutex);
925 pthread_mutex_unlock(&ThreadCountMutex);
927 while (!server_shutting_down) {
929 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
931 do_select: force_purge = 0;
932 bind_me = NULL; /* Which session shall we handle? */
934 /* Initialize the fdset. */
938 /* First, add the various master sockets to the fdset. */
939 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
940 FD_SET(serviceptr->msock, &readfds);
941 if (serviceptr->msock > highest) {
942 highest = serviceptr->msock;
946 /* Next, add all of the client sockets. */
947 begin_critical_section(S_SESSION_TABLE);
948 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
949 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
952 /* Don't select on dead sessions, only truly idle ones */
953 if ( (ptr->state == CON_IDLE)
954 && (ptr->kill_me == 0)
955 && (ptr->client_socket > 0)
957 FD_SET(ptr->client_socket, &readfds);
958 if (ptr->client_socket > highest)
959 highest = ptr->client_socket;
961 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
963 ptr->state = CON_EXECUTING;
966 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
968 ptr->state = CON_STARTING;
972 end_critical_section(S_SESSION_TABLE);
978 /* If we got this far, it means that there are no sessions
979 * which a previous thread marked for attention, so we go
980 * ahead and get ready to select().
983 if (!server_shutting_down) {
984 tv.tv_sec = 1; /* wake up every second if no input */
986 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
993 /* Now figure out who made this select() unblock.
994 * First, check for an error or exit condition.
997 if (errno == EBADF) {
998 syslog(LOG_ERR, "sysdep: select() failed: %m");
1002 if (errno != EINTR) {
1003 syslog(LOG_ERR, "sysdep: exiting: %m");
1004 server_shutting_down = 1;
1007 if (server_shutting_down) {
1014 else if (retval == 0) {
1015 if (server_shutting_down) {
1021 /* Next, check to see if it's a new client connecting on a master socket. */
1023 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1025 if (FD_ISSET(serviceptr->msock, &readfds)) {
1026 ssock = accept(serviceptr->msock, NULL, 0);
1028 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1030 /* The master socket is non-blocking but the client
1031 * sockets need to be blocking, otherwise certain
1032 * operations barf on FreeBSD. Not a fatal error.
1034 if (fcntl(ssock, F_SETFL, 0) < 0) {
1035 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1038 /* New context will be created already
1039 * set up in the CON_EXECUTING state.
1041 con = CreateNewContext();
1043 /* Assign our new socket number to it. */
1044 con->tcp_port = serviceptr->tcp_port;
1045 con->client_socket = ssock;
1046 con->h_command_function = serviceptr->h_command_function;
1047 con->h_async_function = serviceptr->h_async_function;
1048 con->h_greeting_function = serviceptr->h_greeting_function;
1049 con->ServiceName = serviceptr->ServiceName;
1051 /* Connections on a local client are always from the same host */
1052 if (serviceptr->sockpath != NULL) {
1053 con->is_local_client = 1;
1056 /* Set the SO_REUSEADDR socket option */
1058 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1059 con->state = CON_GREETING;
1067 /* It must be a client socket. Find a context that has data
1068 * waiting on its socket *and* is in the CON_IDLE state. Any
1069 * active sockets other than our chosen one are marked as
1070 * CON_READY so the next thread that comes around can just bind
1071 * to one without having to select() again.
1073 begin_critical_section(S_SESSION_TABLE);
1074 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1075 int checkfd = ptr->client_socket;
1076 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1077 if (FD_ISSET(checkfd, &readfds)) {
1078 ptr->input_waiting = 1;
1080 bind_me = ptr; /* I choose you! */
1081 bind_me->state = CON_EXECUTING;
1084 ptr->state = CON_READY;
1086 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1088 bind_me = ptr; /* I choose you! */
1089 bind_me->state = CON_EXECUTING;
1092 ptr->state = CON_READY;
1097 end_critical_section(S_SESSION_TABLE);
1100 /* We're bound to a session */
1101 pthread_mutex_lock(&ThreadCountMutex);
1103 pthread_mutex_unlock(&ThreadCountMutex);
1105 if (bind_me != NULL) {
1106 become_session(bind_me);
1108 if (bind_me->state == CON_STARTING) {
1109 bind_me->state = CON_EXECUTING;
1110 begin_session(bind_me);
1111 bind_me->h_greeting_function();
1113 /* If the client has sent a command, execute it. */
1114 if (CC->input_waiting) {
1115 CC->h_command_function();
1117 while (HaveMoreLinesWaiting(CC))
1118 CC->h_command_function();
1120 CC->input_waiting = 0;
1123 /* If there are asynchronous messages waiting and the client supports it, do those now */
1124 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1125 CC->h_async_function();
1126 CC->async_waiting = 0;
1129 force_purge = CC->kill_me;
1130 become_session(NULL);
1131 bind_me->state = CON_IDLE;
1134 dead_session_purge(force_purge);
1137 pthread_mutex_lock(&ThreadCountMutex);
1139 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1140 (num_workers > CtdlGetConfigInt("c_min_workers")))
1143 pthread_mutex_unlock(&ThreadCountMutex);
1146 pthread_mutex_unlock(&ThreadCountMutex);
1149 /* If control reaches this point, the server is shutting down */
1150 pthread_mutex_lock(&ThreadCountMutex);
1152 pthread_mutex_unlock(&ThreadCountMutex);
1159 * Translate text facility name to syslog.h defined value.
1161 int SyslogFacility(char *name)
1170 { LOG_KERN, "kern" },
1171 { LOG_USER, "user" },
1172 { LOG_MAIL, "mail" },
1173 { LOG_DAEMON, "daemon" },
1174 { LOG_AUTH, "auth" },
1175 { LOG_SYSLOG, "syslog" },
1177 { LOG_NEWS, "news" },
1178 { LOG_UUCP, "uucp" },
1179 { LOG_LOCAL0, "local0" },
1180 { LOG_LOCAL1, "local1" },
1181 { LOG_LOCAL2, "local2" },
1182 { LOG_LOCAL3, "local3" },
1183 { LOG_LOCAL4, "local4" },
1184 { LOG_LOCAL5, "local5" },
1185 { LOG_LOCAL6, "local6" },
1186 { LOG_LOCAL7, "local7" },
1189 for(i = 0; facTbl[i].name != NULL; i++) {
1190 if(!strcasecmp(name, facTbl[i].name))
1191 return facTbl[i].facility;