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)
548 if ((CCC->kill_me != 0) ||
549 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
550 (StrLength(CCC->RecvBuf.Buf) == 0) &&
551 (CCC->client_socket != -1)) )
559 * Read data from the client socket with default timeout.
560 * (This is implemented in terms of client_read_to() and could be
561 * justifiably moved out of sysdep.c)
563 INLINE int client_read(char *buf, int bytes)
565 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
568 int CtdlClientGetLine(StrBuf *Target)
576 if (CCC->redirect_ssl) {
577 rc = client_readline_sslbuffer(Target, CCC->RecvBuf.Buf, &CCC->RecvBuf.ReadWritePointer, 1);
583 rc = StrBufTCP_read_buffered_line_fast(Target,
585 &CCC->RecvBuf.ReadWritePointer,
597 * client_getln() ... Get a LF-terminated line of text from the client.
598 * (This is implemented in terms of client_read() and could be
599 * justifiably moved out of sysdep.c)
601 int client_getln(char *buf, int bufsize)
607 retval = CtdlClientGetLine(CCC->MigrateBuf);
612 i = StrLength(CCC->MigrateBuf);
613 pCh = ChrPtr(CCC->MigrateBuf);
614 /* Strip the trailing LF, and the trailing CR if present.
619 && ( (pCh[i - 1]==13)
620 || ( pCh[i - 1]==10)) ) {
626 FlushStrBuf(CCC->MigrateBuf);
628 safestrncpy(&buf[i], "000", bufsize - i);
635 * Cleanup any contexts that are left lying around
639 void close_masters (void)
641 struct ServiceFunctionHook *serviceptr;
645 * close all protocol master sockets
647 for (serviceptr = ServiceHookTable; serviceptr != NULL;
648 serviceptr = serviceptr->next ) {
650 if (serviceptr->tcp_port > 0)
652 if (serviceptr->msock == -1) {
653 Text = "not closing again";
658 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
663 serviceptr->tcp_port = 0;
666 if (serviceptr->sockpath != NULL)
668 if (serviceptr->msock == -1) {
669 Text = "not closing again";
674 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
681 if (serviceptr->msock != -1)
683 close(serviceptr->msock);
684 serviceptr->msock = -1;
687 /* If it's a Unix domain socket, remove the file. */
688 if (serviceptr->sockpath != NULL) {
689 unlink(serviceptr->sockpath);
690 serviceptr->sockpath = NULL;
697 * The system-dependent part of master_cleanup() - close the master socket.
699 void sysdep_master_cleanup(void) {
708 CtdlDestroyProtoHooks();
709 CtdlDestroyDeleteHooks();
710 CtdlDestroyXmsgHooks();
711 CtdlDestroyUserHooks();
712 CtdlDestroyMessageHook();
713 CtdlDestroyCleanupHooks();
714 CtdlDestroyFixedOutputHooks();
715 CtdlDestroySessionHooks();
716 CtdlDestroyServiceHook();
717 CtdlDestroyRoomHooks();
718 CtdlDestroySearchHooks();
724 void graceful_shutdown(int signum) {
725 kill(current_child, signum);
726 unlink(file_pid_file);
731 int nFireUpsNonRestart = 0;
735 * Start running as a daemon.
737 void start_daemon(int unused) {
744 //if (chdir(ctdl_run_dir) != 0) {
745 //syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
748 /* Close stdin/stdout/stderr and replace them with /dev/null.
749 * We don't just call close() because we don't want these fd's
750 * to be reused for other files.
757 signal(SIGHUP, SIG_IGN);
758 signal(SIGINT, SIG_IGN);
759 signal(SIGQUIT, SIG_IGN);
763 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
764 (freopen("/dev/null", "w", stdout) != stdout) ||
765 (freopen("/dev/null", "w", stderr) != stderr)
767 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
771 current_child = fork();
772 signal(SIGTERM, graceful_shutdown);
773 if (current_child < 0) {
777 else if (current_child == 0) {
778 return; /* continue starting citadel. */
781 fp = fopen(file_pid_file, "w");
783 fprintf(fp, ""F_PID_T"\n", getpid());
786 waitpid(current_child, &status, 0);
788 nFireUpsNonRestart = nFireUps;
790 /* Exit code 0 means the watcher should exit */
791 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
795 /* Exit code 101-109 means the watcher should exit */
796 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
800 /* Any other exit code, or no exit code, means we should restart. */
804 ForkedPid = current_child;
807 } while (do_restart);
809 unlink(file_pid_file);
810 exit(WEXITSTATUS(status));
815 void checkcrash(void)
817 if (nFireUpsNonRestart != nFireUps)
820 CrashMail = NewStrBuf();
821 syslog(LOG_ALERT, "sysdep: posting crash message");
822 StrBufPrintf(CrashMail,
824 " The Citadel server process (citserver) terminated unexpectedly."
826 " This could be the result of a bug in the server program, or some external "
828 " You can obtain more information about this by enabling core dumps.\n \n"
829 " For more information, please see:\n \n"
830 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
833 " If you have already done this, the core dump is likely to be found at %score.%d\n"
835 ctdl_run_dir, ForkedPid);
836 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
837 FreeStrBuf(&CrashMail);
843 * Generic routine to convert a login name to a full name (gecos)
844 * Returns nonzero if a conversion took place
846 int convert_login(char NameToConvert[]) {
850 pw = getpwnam(NameToConvert);
855 strcpy(NameToConvert, pw->pw_gecos);
856 for (a=0; a<strlen(NameToConvert); ++a) {
857 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
865 void HuntBadSession(void)
871 struct ServiceFunctionHook *serviceptr;
873 /* Next, add all of the client sockets. */
874 begin_critical_section(S_SESSION_TABLE);
875 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
876 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
878 /* Initialize the fdset. */
881 tv.tv_sec = 0; /* wake up every second if no input */
884 /* Don't select on dead sessions, only truly idle ones */
885 if ( (ptr->state == CON_IDLE)
886 && (ptr->kill_me == 0)
887 && (ptr->client_socket > 0)
889 FD_SET(ptr->client_socket, &readfds);
890 if (ptr->client_socket > highest)
891 highest = ptr->client_socket;
893 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
897 "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
905 ptr->client_socket = -1;
910 end_critical_section(S_SESSION_TABLE);
912 /* First, add the various master sockets to the fdset. */
913 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
915 /* Initialize the fdset. */
917 tv.tv_sec = 0; /* wake up every second if no input */
920 FD_SET(serviceptr->msock, &readfds);
921 if (serviceptr->msock > highest) {
922 highest = serviceptr->msock;
924 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
927 /* Gotcha! server socket dead? commit suicide! */
928 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
929 server_shutting_down = 1;
937 * This loop just keeps going and going and going...
939 void *worker_thread(void *blah) {
942 CitContext *bind_me = NULL;
947 struct ServiceFunctionHook *serviceptr;
948 int ssock; /* Descriptor for client socket */
949 CitContext *con = NULL; /* Temporary context pointer */
952 pthread_mutex_lock(&ThreadCountMutex);
954 pthread_mutex_unlock(&ThreadCountMutex);
956 while (!server_shutting_down) {
958 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
960 do_select: force_purge = 0;
961 bind_me = NULL; /* Which session shall we handle? */
963 /* Initialize the fdset. */
967 /* First, add the various master sockets to the fdset. */
968 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
969 FD_SET(serviceptr->msock, &readfds);
970 if (serviceptr->msock > highest) {
971 highest = serviceptr->msock;
975 /* Next, add all of the client sockets. */
976 begin_critical_section(S_SESSION_TABLE);
977 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
978 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
981 /* Don't select on dead sessions, only truly idle ones */
982 if ( (ptr->state == CON_IDLE)
983 && (ptr->kill_me == 0)
984 && (ptr->client_socket > 0)
986 FD_SET(ptr->client_socket, &readfds);
987 if (ptr->client_socket > highest)
988 highest = ptr->client_socket;
990 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
992 ptr->state = CON_EXECUTING;
995 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
997 ptr->state = CON_STARTING;
1001 end_critical_section(S_SESSION_TABLE);
1007 /* If we got this far, it means that there are no sessions
1008 * which a previous thread marked for attention, so we go
1009 * ahead and get ready to select().
1012 if (!server_shutting_down) {
1013 tv.tv_sec = 1; /* wake up every second if no input */
1015 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1022 /* Now figure out who made this select() unblock.
1023 * First, check for an error or exit condition.
1026 if (errno == EBADF) {
1027 syslog(LOG_ERR, "sysdep: select() failed: %m");
1031 if (errno != EINTR) {
1032 syslog(LOG_ERR, "sysdep: exiting: %m");
1033 server_shutting_down = 1;
1036 if (server_shutting_down) {
1043 else if (retval == 0) {
1044 if (server_shutting_down) {
1050 /* Next, check to see if it's a new client connecting on a master socket. */
1052 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1054 if (FD_ISSET(serviceptr->msock, &readfds)) {
1055 ssock = accept(serviceptr->msock, NULL, 0);
1057 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1059 /* The master socket is non-blocking but the client
1060 * sockets need to be blocking, otherwise certain
1061 * operations barf on FreeBSD. Not a fatal error.
1063 if (fcntl(ssock, F_SETFL, 0) < 0) {
1064 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1067 /* New context will be created already
1068 * set up in the CON_EXECUTING state.
1070 con = CreateNewContext();
1072 /* Assign our new socket number to it. */
1073 con->tcp_port = serviceptr->tcp_port;
1074 con->client_socket = ssock;
1075 con->h_command_function = serviceptr->h_command_function;
1076 con->h_async_function = serviceptr->h_async_function;
1077 con->h_greeting_function = serviceptr->h_greeting_function;
1078 con->ServiceName = serviceptr->ServiceName;
1080 /* Connections on a local client are always from the same host */
1081 if (serviceptr->sockpath != NULL) {
1082 con->is_local_client = 1;
1085 /* Set the SO_REUSEADDR socket option */
1087 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1088 con->state = CON_GREETING;
1096 /* It must be a client socket. Find a context that has data
1097 * waiting on its socket *and* is in the CON_IDLE state. Any
1098 * active sockets other than our chosen one are marked as
1099 * CON_READY so the next thread that comes around can just bind
1100 * to one without having to select() again.
1102 begin_critical_section(S_SESSION_TABLE);
1103 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1104 int checkfd = ptr->client_socket;
1105 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1106 if (FD_ISSET(checkfd, &readfds)) {
1107 ptr->input_waiting = 1;
1109 bind_me = ptr; /* I choose you! */
1110 bind_me->state = CON_EXECUTING;
1113 ptr->state = CON_READY;
1115 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1117 bind_me = ptr; /* I choose you! */
1118 bind_me->state = CON_EXECUTING;
1121 ptr->state = CON_READY;
1126 end_critical_section(S_SESSION_TABLE);
1129 /* We're bound to a session */
1130 pthread_mutex_lock(&ThreadCountMutex);
1132 pthread_mutex_unlock(&ThreadCountMutex);
1134 if (bind_me != NULL) {
1135 become_session(bind_me);
1137 if (bind_me->state == CON_STARTING) {
1138 bind_me->state = CON_EXECUTING;
1139 begin_session(bind_me);
1140 bind_me->h_greeting_function();
1142 /* If the client has sent a command, execute it. */
1143 if (CC->input_waiting) {
1144 CC->h_command_function();
1146 while (HaveMoreLinesWaiting(CC))
1147 CC->h_command_function();
1149 CC->input_waiting = 0;
1152 /* If there are asynchronous messages waiting and the client supports it, do those now */
1153 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1154 CC->h_async_function();
1155 CC->async_waiting = 0;
1158 force_purge = CC->kill_me;
1159 become_session(NULL);
1160 bind_me->state = CON_IDLE;
1163 dead_session_purge(force_purge);
1166 pthread_mutex_lock(&ThreadCountMutex);
1168 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1169 (num_workers > CtdlGetConfigInt("c_min_workers")))
1172 pthread_mutex_unlock(&ThreadCountMutex);
1175 pthread_mutex_unlock(&ThreadCountMutex);
1178 /* If control reaches this point, the server is shutting down */
1179 pthread_mutex_lock(&ThreadCountMutex);
1181 pthread_mutex_unlock(&ThreadCountMutex);
1188 * Translate text facility name to syslog.h defined value.
1190 int SyslogFacility(char *name)
1199 { LOG_KERN, "kern" },
1200 { LOG_USER, "user" },
1201 { LOG_MAIL, "mail" },
1202 { LOG_DAEMON, "daemon" },
1203 { LOG_AUTH, "auth" },
1204 { LOG_SYSLOG, "syslog" },
1206 { LOG_NEWS, "news" },
1207 { LOG_UUCP, "uucp" },
1208 { LOG_LOCAL0, "local0" },
1209 { LOG_LOCAL1, "local1" },
1210 { LOG_LOCAL2, "local2" },
1211 { LOG_LOCAL3, "local3" },
1212 { LOG_LOCAL4, "local4" },
1213 { LOG_LOCAL5, "local5" },
1214 { LOG_LOCAL6, "local6" },
1215 { LOG_LOCAL7, "local7" },
1218 for(i = 0; facTbl[i].name != NULL; i++) {
1219 if(!strcasecmp(name, facTbl[i].name))
1220 return facTbl[i].facility;