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-2017 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. */
90 * Set up a place to put thread-specific data.
91 * We only need a single pointer per thread - it points to the
92 * CitContext structure (in the ContextList linked list) of the
93 * session to which the calling thread is currently bound.
95 if (pthread_key_create(&MyConKey, NULL) != 0) {
96 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, char *errormessage)
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 snprintf(errormessage, SIZ, "Error binding to [%s] : %s", ip_addr, strerror(errno));
161 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
165 else /* specific IPv6 */
168 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
169 snprintf(errormessage, SIZ, "Error binding to [%s] : %s", ip_addr, strerror(errno));
170 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
175 if (port_number == 0) {
176 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
177 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
180 sin6.sin6_port = htons((u_short) port_number);
181 sin4.sin_port = htons((u_short) port_number);
183 p = getprotobyname("tcp");
185 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
187 snprintf(errormessage, SIZ, "Can't create a listening socket: %s", strerror(errno));
188 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
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 snprintf(errormessage, SIZ, "Can't bind: %s", strerror(errno));
204 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
208 fcntl(s, F_SETFL, O_NONBLOCK);
210 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
211 snprintf(errormessage, SIZ, "Can't listen: %s", strerror(errno));
212 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
220 * Create a Unix domain socket and listen on it
222 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
224 struct sockaddr_un addr;
227 int actual_queue_len;
228 #ifdef HAVE_STRUCT_UCRED
232 actual_queue_len = queue_len;
233 if (actual_queue_len < 5) actual_queue_len = 5;
235 i = unlink(sockpath);
236 if ((i != 0) && (errno != ENOENT)) {
237 snprintf(errormessage, SIZ, "can't unlink %s: %s", sockpath, strerror(errno));
238 syslog(LOG_ERR, "udsserver: %s", errormessage);
242 memset(&addr, 0, sizeof(addr));
243 addr.sun_family = AF_UNIX;
244 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
246 s = socket(AF_UNIX, SOCK_STREAM, 0);
248 snprintf(errormessage, SIZ, "can't create a socket: %s", strerror(errno));
249 syslog(LOG_ERR, "udsserver: %s", errormessage);
253 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
254 snprintf(errormessage, SIZ, "can't bind: %s", strerror(errno));
255 syslog(LOG_ERR, "udsserver: %s", errormessage);
259 /* set to nonblock - we need this for some obscure situations */
260 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
261 snprintf(errormessage, SIZ, "can't set socket to non-blocking: %s", strerror(errno));
262 syslog(LOG_ERR, "udsserver: %s", errormessage);
267 if (listen(s, actual_queue_len) < 0) {
268 snprintf(errormessage, SIZ, "can't listen: %s", strerror(errno));
269 syslog(LOG_ERR, "udsserver: %s", errormessage);
273 #ifdef HAVE_STRUCT_UCRED
274 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
277 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
283 * The following functions implement output buffering on operating systems which
284 * support it (such as Linux and various BSD flavors).
288 # define HAVE_TCP_BUFFERING
291 # define HAVE_TCP_BUFFERING
292 # define TCP_CORK TCP_NOPUSH
294 #endif /* TCP_CORK */
295 #endif /* HAVE_DARWIN */
297 static unsigned on = 1, off = 0;
299 void buffer_output(void) {
300 #ifdef HAVE_TCP_BUFFERING
302 if (!CC->redirect_ssl)
304 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
308 void unbuffer_output(void) {
309 #ifdef HAVE_TCP_BUFFERING
311 if (!CC->redirect_ssl)
313 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
317 void flush_output(void) {
318 #ifdef HAVE_TCP_BUFFERING
319 struct CitContext *CCC = CC;
320 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
321 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
326 static void flush_client_inbuf(void)
330 FlushStrBuf(CCC->ReadBuf);
331 CCC->RecvBuf->ReadWritePointer = NULL;
337 * client_close() ... close the client socket
339 void client_close(void) {
340 CitContext *CCC = CC;
343 if (CCC->client_socket <= 0) return;
344 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
345 close(CCC->client_socket);
346 CCC->client_socket = -1 ;
351 * client_write() ... Send binary data to the client.
353 int client_write(const char *buf, int nbytes)
355 int bytes_written = 0;
357 #ifndef HAVE_TCP_BUFFERING
358 int old_buffer_len = 0;
364 if (nbytes < 1) return(0);
374 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
376 fd = fopen(fn, "a+");
378 syslog(LOG_ERR, "%s: %m", fn);
382 fprintf(fd, "Sending: BufSize: %d BufContent: [", nbytes);
383 rv = fwrite(buf, nbytes, 1, fd);
388 // flush_client_inbuf();
389 if (Ctx->redirect_buffer != NULL) {
390 StrBufAppendBufPlain(Ctx->redirect_buffer,
396 if (Ctx->redirect_ssl) {
397 client_write_ssl(buf, nbytes);
401 if (Ctx->client_socket == -1) return -1;
403 fdflags = fcntl(Ctx->client_socket, F_GETFL);
405 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
406 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
408 FD_SET(Ctx->client_socket, &wset);
409 if (select(1, NULL, &wset, NULL, NULL) == -1) {
412 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
413 if (server_shutting_down) {
414 CC->kill_me = KILLME_SELECT_INTERRUPTED;
417 /* can't trust fd's and stuff so we need to re-create them */
421 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
424 Ctx->kill_me = KILLME_SELECT_FAILED;
430 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
432 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
435 Ctx->kill_me = KILLME_WRITE_FAILED;
438 bytes_written = bytes_written + retval;
443 void cputbuf(const StrBuf *Buf) {
444 client_write(ChrPtr(Buf), StrLength(Buf));
449 * cprintf() Send formatted printable data to the client.
450 * Implemented in terms of client_write() so it's technically not sysdep...
452 void cprintf(const char *format, ...) {
456 va_start(arg_ptr, format);
457 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
458 buf[sizeof buf - 2] = '\n';
459 client_write(buf, strlen(buf));
465 * Read data from the client socket.
467 * sock socket fd to read from
468 * buf buffer to read into
469 * bytes number of bytes to read
470 * timeout Number of seconds to wait before timing out
472 * Possible return values:
473 * 1 Requested number of bytes has been read.
474 * 0 Request timed out.
475 * -1 Connection is broken, or other error.
477 int client_read_blob(StrBuf *Target, int bytes, int timeout)
484 if (CCC->redirect_ssl) {
490 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
492 fd = fopen(fn, "a+");
494 syslog(LOG_ERR, "%s: %m", fn);
498 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
499 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
505 retval = client_read_sslblob(Target, bytes, timeout);
507 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
510 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
512 fd = fopen(fn, "a+");
514 syslog(LOG_ERR, "%s: %m", fn);
518 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
519 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
532 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
534 fd = fopen(fn, "a+");
536 syslog(LOG_ERR, "%s: %m", fn);
540 fprintf(fd, "Reading BLOB: BufSize: %d ",
542 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
546 retval = StrBufReadBLOBBuffered(Target,
548 &CCC->RecvBuf.ReadWritePointer,
556 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
561 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
563 fd = fopen(fn, "a+");
565 syslog(LOG_ERR, "%s: %m", fn);
569 fprintf(fd, "Read: %d BufContent: [",
571 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
581 * to make client_read_random_blob() more efficient, increase buffer size.
582 * just use in greeting function, else your buffer may be flushed
584 void client_set_inbound_buf(long N)
587 FlushStrBuf(CCC->RecvBuf.Buf);
588 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
591 int client_read_random_blob(StrBuf *Target, int timeout)
596 rc = client_read_blob(Target, 1, timeout);
602 len = StrLength(CCC->RecvBuf.Buf);
603 pch = ChrPtr(CCC->RecvBuf.Buf);
607 if (CCC->RecvBuf.ReadWritePointer != NULL) {
608 len -= CCC->RecvBuf.ReadWritePointer - pch;
609 pch = CCC->RecvBuf.ReadWritePointer;
611 StrBufAppendBufPlain(Target, pch, len, 0);
612 FlushStrBuf(CCC->RecvBuf.Buf);
613 CCC->RecvBuf.ReadWritePointer = NULL;
620 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
622 fd = fopen(fn, "a+");
624 syslog(LOG_ERR, "%s: %m", fn);
628 fprintf(fd, "Read: BufSize: %d BufContent: [",
630 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
635 return StrLength(Target);
643 int client_read_to(char *buf, int bytes, int timeout)
648 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
657 ChrPtr(CCC->MigrateBuf),
658 StrLength(CCC->MigrateBuf) + 1);
659 FlushStrBuf(CCC->MigrateBuf);
665 int HaveMoreLinesWaiting(CitContext *CCC)
667 if ((CCC->kill_me != 0) ||
668 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
669 (StrLength(CCC->RecvBuf.Buf) == 0) &&
670 (CCC->client_socket != -1)) )
678 * Read data from the client socket with default timeout.
679 * (This is implemented in terms of client_read_to() and could be
680 * justifiably moved out of sysdep.c)
682 INLINE int client_read(char *buf, int bytes)
684 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
687 int CtdlClientGetLine(StrBuf *Target)
695 if (CCC->redirect_ssl) {
705 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
707 fd = fopen(fn, "a+");
709 syslog(LOG_ERR, "%s: %m", fn);
713 pch = ChrPtr(CCC->RecvBuf.Buf);
714 len = StrLength(CCC->RecvBuf.Buf);
715 if (CCC->RecvBuf.ReadWritePointer != NULL)
716 rlen = CCC->RecvBuf.ReadWritePointer - pch;
720 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
723 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
726 rc = client_readline_sslbuffer(Target,
728 &CCC->RecvBuf.ReadWritePointer,
731 pch = ChrPtr(CCC->RecvBuf.Buf);
732 nlen = StrLength(CCC->RecvBuf.Buf);
733 if (CCC->RecvBuf.ReadWritePointer != NULL)
734 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
738 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
739 len, nlen, rlen, nrlen, pch);
741 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
742 len, nlen, rlen, nrlen);
744 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
745 StrLength(Target), ChrPtr(Target));
749 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed");
760 int len, rlen, nlen, nrlen;
763 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
765 fd = fopen(fn, "a+");
767 syslog(LOG_ERR, "%s: %m", fn);
771 pch = ChrPtr(CCC->RecvBuf.Buf);
772 len = StrLength(CCC->RecvBuf.Buf);
773 if (CCC->RecvBuf.ReadWritePointer != NULL)
774 rlen = CCC->RecvBuf.ReadWritePointer - pch;
778 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
781 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
784 rc = StrBufTCP_read_buffered_line_fast(Target,
786 &CCC->RecvBuf.ReadWritePointer,
794 pch = ChrPtr(CCC->RecvBuf.Buf);
795 nlen = StrLength(CCC->RecvBuf.Buf);
796 if (CCC->RecvBuf.ReadWritePointer != NULL)
797 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
801 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
802 len, nlen, rlen, nrlen, pch);
804 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
805 len, nlen, rlen, nrlen);
807 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
808 StrLength(Target), ChrPtr(Target));
811 if ((rc < 0) && (Error != NULL)) {
812 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed: %s", Error);
821 * client_getln() ... Get a LF-terminated line of text from the client.
822 * (This is implemented in terms of client_read() and could be
823 * justifiably moved out of sysdep.c)
825 int client_getln(char *buf, int bufsize)
831 retval = CtdlClientGetLine(CCC->MigrateBuf);
836 i = StrLength(CCC->MigrateBuf);
837 pCh = ChrPtr(CCC->MigrateBuf);
838 /* Strip the trailing LF, and the trailing CR if present.
843 && ( (pCh[i - 1]==13)
844 || ( pCh[i - 1]==10)) ) {
850 FlushStrBuf(CCC->MigrateBuf);
852 safestrncpy(&buf[i], "000", bufsize - i);
859 * Cleanup any contexts that are left lying around
863 void close_masters (void)
865 struct ServiceFunctionHook *serviceptr;
869 * close all protocol master sockets
871 for (serviceptr = ServiceHookTable; serviceptr != NULL;
872 serviceptr = serviceptr->next ) {
874 if (serviceptr->tcp_port > 0)
876 if (serviceptr->msock == -1) {
877 Text = "not closing again";
882 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
887 serviceptr->tcp_port = 0;
890 if (serviceptr->sockpath != NULL)
892 if (serviceptr->msock == -1) {
893 Text = "not closing again";
898 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
905 if (serviceptr->msock != -1)
907 close(serviceptr->msock);
908 serviceptr->msock = -1;
911 /* If it's a Unix domain socket, remove the file. */
912 if (serviceptr->sockpath != NULL) {
913 unlink(serviceptr->sockpath);
914 serviceptr->sockpath = NULL;
921 * The system-dependent part of master_cleanup() - close the master socket.
923 void sysdep_master_cleanup(void) {
932 CtdlDestroyProtoHooks();
933 CtdlDestroyDeleteHooks();
934 CtdlDestroyXmsgHooks();
935 CtdlDestroyNetprocHooks();
936 CtdlDestroyUserHooks();
937 CtdlDestroyMessageHook();
938 CtdlDestroyCleanupHooks();
939 CtdlDestroyFixedOutputHooks();
940 CtdlDestroySessionHooks();
941 CtdlDestroyServiceHook();
942 CtdlDestroyRoomHooks();
943 CtdlDestroySearchHooks();
944 #ifdef HAVE_BACKTRACE
952 void graceful_shutdown(int signum) {
953 kill(current_child, signum);
954 unlink(file_pid_file);
959 int nFireUpsNonRestart = 0;
963 * Start running as a daemon.
965 void start_daemon(int unused) {
973 /* Close stdin/stdout/stderr and replace them with /dev/null.
974 * We don't just call close() because we don't want these fd's
975 * to be reused for other files.
977 if (chdir(ctdl_run_dir) != 0) {
978 syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
986 signal(SIGHUP, SIG_IGN);
987 signal(SIGINT, SIG_IGN);
988 signal(SIGQUIT, SIG_IGN);
992 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
993 (freopen("/dev/null", "w", stdout) != stdout) ||
994 (freopen("/dev/null", "w", stderr) != stderr)
996 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
1000 current_child = fork();
1001 signal(SIGTERM, graceful_shutdown);
1002 if (current_child < 0) {
1006 else if (current_child == 0) {
1007 return; /* continue starting citadel. */
1010 fp = fopen(file_pid_file, "w");
1012 fprintf(fp, ""F_PID_T"\n", getpid());
1015 waitpid(current_child, &status, 0);
1017 nFireUpsNonRestart = nFireUps;
1019 /* Exit code 0 means the watcher should exit */
1020 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1024 /* Exit code 101-109 means the watcher should exit */
1025 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1029 /* Any other exit code, or no exit code, means we should restart. */
1033 ForkedPid = current_child;
1036 } while (do_restart);
1038 unlink(file_pid_file);
1039 exit(WEXITSTATUS(status));
1044 void checkcrash(void)
1046 if (nFireUpsNonRestart != nFireUps)
1049 CrashMail = NewStrBuf();
1050 syslog(LOG_ALERT, "sysdep: posting crash message");
1051 StrBufPrintf(CrashMail,
1053 " The Citadel server process (citserver) terminated unexpectedly."
1055 " This could be the result of a bug in the server program, or some external "
1057 " You can obtain more information about this by enabling core dumps.\n \n"
1058 " For more information, please see:\n \n"
1059 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1062 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1064 ctdl_run_dir, ForkedPid);
1065 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1066 FreeStrBuf(&CrashMail);
1072 * Generic routine to convert a login name to a full name (gecos)
1073 * Returns nonzero if a conversion took place
1075 int convert_login(char NameToConvert[]) {
1079 pw = getpwnam(NameToConvert);
1084 strcpy(NameToConvert, pw->pw_gecos);
1085 for (a=0; a<strlen(NameToConvert); ++a) {
1086 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1094 void HuntBadSession(void)
1100 struct ServiceFunctionHook *serviceptr;
1102 /* Next, add all of the client sockets. */
1103 begin_critical_section(S_SESSION_TABLE);
1104 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1105 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1107 /* Initialize the fdset. */
1110 tv.tv_sec = 0; /* wake up every second if no input */
1113 /* Don't select on dead sessions, only truly idle ones */
1114 if ( (ptr->state == CON_IDLE)
1115 && (ptr->kill_me == 0)
1116 && (ptr->client_socket > 0)
1118 FD_SET(ptr->client_socket, &readfds);
1119 if (ptr->client_socket > highest)
1120 highest = ptr->client_socket;
1122 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
1126 "sysdep: killing session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]",
1129 ptr->is_local_socket,
1131 ptr->cs_host,ptr->cs_addr
1134 ptr->client_socket = -1;
1139 end_critical_section(S_SESSION_TABLE);
1141 /* First, add the various master sockets to the fdset. */
1142 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1144 /* Initialize the fdset. */
1146 tv.tv_sec = 0; /* wake up every second if no input */
1149 FD_SET(serviceptr->msock, &readfds);
1150 if (serviceptr->msock > highest) {
1151 highest = serviceptr->msock;
1153 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1156 /* Gotcha! server socket dead? commit suicide! */
1157 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
1158 server_shutting_down = 1;
1166 * This loop just keeps going and going and going...
1168 void *worker_thread(void *blah) {
1171 CitContext *bind_me = NULL;
1175 int force_purge = 0;
1176 struct ServiceFunctionHook *serviceptr;
1177 int ssock; /* Descriptor for client socket */
1178 CitContext *con = NULL; /* Temporary context pointer */
1181 pthread_mutex_lock(&ThreadCountMutex);
1183 pthread_mutex_unlock(&ThreadCountMutex);
1185 while (!server_shutting_down) {
1187 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
1188 cdb_check_handles();
1189 do_select: force_purge = 0;
1190 bind_me = NULL; /* Which session shall we handle? */
1192 /* Initialize the fdset. */
1196 /* First, add the various master sockets to the fdset. */
1197 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1198 FD_SET(serviceptr->msock, &readfds);
1199 if (serviceptr->msock > highest) {
1200 highest = serviceptr->msock;
1204 /* Next, add all of the client sockets. */
1205 begin_critical_section(S_SESSION_TABLE);
1206 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1207 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1210 /* Don't select on dead sessions, only truly idle ones */
1211 if ( (ptr->state == CON_IDLE)
1212 && (ptr->kill_me == 0)
1213 && (ptr->client_socket > 0)
1215 FD_SET(ptr->client_socket, &readfds);
1216 if (ptr->client_socket > highest)
1217 highest = ptr->client_socket;
1219 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1221 ptr->state = CON_EXECUTING;
1224 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1226 ptr->state = CON_STARTING;
1230 end_critical_section(S_SESSION_TABLE);
1236 /* If we got this far, it means that there are no sessions
1237 * which a previous thread marked for attention, so we go
1238 * ahead and get ready to select().
1241 if (!server_shutting_down) {
1242 tv.tv_sec = 1; /* wake up every second if no input */
1244 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1251 /* Now figure out who made this select() unblock.
1252 * First, check for an error or exit condition.
1255 if (errno == EBADF) {
1256 syslog(LOG_ERR, "sysdep: select() failed: %m");
1260 if (errno != EINTR) {
1261 syslog(LOG_ERR, "sysdep: exiting: %m");
1262 server_shutting_down = 1;
1265 if (server_shutting_down) {
1272 else if (retval == 0) {
1273 if (server_shutting_down) {
1279 /* Next, check to see if it's a new client connecting on a master socket. */
1281 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1283 if (FD_ISSET(serviceptr->msock, &readfds)) {
1284 ssock = accept(serviceptr->msock, NULL, 0);
1286 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1288 /* The master socket is non-blocking but the client
1289 * sockets need to be blocking, otherwise certain
1290 * operations barf on FreeBSD. Not a fatal error.
1292 if (fcntl(ssock, F_SETFL, 0) < 0) {
1293 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1296 /* New context will be created already
1297 * set up in the CON_EXECUTING state.
1299 con = CreateNewContext();
1301 /* Assign our new socket number to it. */
1302 con->tcp_port = serviceptr->tcp_port;
1303 con->client_socket = ssock;
1304 con->h_command_function = serviceptr->h_command_function;
1305 con->h_async_function = serviceptr->h_async_function;
1306 con->h_greeting_function = serviceptr->h_greeting_function;
1307 con->ServiceName = serviceptr->ServiceName;
1309 /* Determine whether it's a local socket */
1310 if (serviceptr->sockpath != NULL) {
1311 con->is_local_socket = 1;
1314 /* Set the SO_REUSEADDR socket option */
1316 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1317 con->state = CON_GREETING;
1325 /* It must be a client socket. Find a context that has data
1326 * waiting on its socket *and* is in the CON_IDLE state. Any
1327 * active sockets other than our chosen one are marked as
1328 * CON_READY so the next thread that comes around can just bind
1329 * to one without having to select() again.
1331 begin_critical_section(S_SESSION_TABLE);
1332 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1333 int checkfd = ptr->client_socket;
1334 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1335 if (FD_ISSET(checkfd, &readfds)) {
1336 ptr->input_waiting = 1;
1338 bind_me = ptr; /* I choose you! */
1339 bind_me->state = CON_EXECUTING;
1342 ptr->state = CON_READY;
1344 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1346 bind_me = ptr; /* I choose you! */
1347 bind_me->state = CON_EXECUTING;
1350 ptr->state = CON_READY;
1355 end_critical_section(S_SESSION_TABLE);
1358 /* We're bound to a session */
1359 pthread_mutex_lock(&ThreadCountMutex);
1361 pthread_mutex_unlock(&ThreadCountMutex);
1363 if (bind_me != NULL) {
1364 become_session(bind_me);
1366 if (bind_me->state == CON_STARTING) {
1367 bind_me->state = CON_EXECUTING;
1368 begin_session(bind_me);
1369 bind_me->h_greeting_function();
1371 /* If the client has sent a command, execute it. */
1372 if (CC->input_waiting) {
1373 CC->h_command_function();
1375 while (HaveMoreLinesWaiting(CC))
1376 CC->h_command_function();
1378 CC->input_waiting = 0;
1381 /* If there are asynchronous messages waiting and the client supports it, do those now */
1382 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1383 CC->h_async_function();
1384 CC->async_waiting = 0;
1387 force_purge = CC->kill_me;
1388 become_session(NULL);
1389 bind_me->state = CON_IDLE;
1392 dead_session_purge(force_purge);
1395 pthread_mutex_lock(&ThreadCountMutex);
1397 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1398 (num_workers > CtdlGetConfigInt("c_min_workers")))
1401 pthread_mutex_unlock(&ThreadCountMutex);
1404 pthread_mutex_unlock(&ThreadCountMutex);
1407 /* If control reaches this point, the server is shutting down */
1408 pthread_mutex_lock(&ThreadCountMutex);
1410 pthread_mutex_unlock(&ThreadCountMutex);
1417 * Translate text facility name to syslog.h defined value.
1419 int SyslogFacility(char *name)
1428 { LOG_KERN, "kern" },
1429 { LOG_USER, "user" },
1430 { LOG_MAIL, "mail" },
1431 { LOG_DAEMON, "daemon" },
1432 { LOG_AUTH, "auth" },
1433 { LOG_SYSLOG, "syslog" },
1435 { LOG_NEWS, "news" },
1436 { LOG_UUCP, "uucp" },
1437 { LOG_LOCAL0, "local0" },
1438 { LOG_LOCAL1, "local1" },
1439 { LOG_LOCAL2, "local2" },
1440 { LOG_LOCAL3, "local3" },
1441 { LOG_LOCAL4, "local4" },
1442 { LOG_LOCAL5, "local5" },
1443 { LOG_LOCAL6, "local6" },
1444 { LOG_LOCAL7, "local7" },
1447 for(i = 0; facTbl[i].name != NULL; i++) {
1448 if(!strcasecmp(name, facTbl[i].name))
1449 return facTbl[i].facility;