2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * would need to be altered to run the server in a non-POSIX environment.
7 * If we ever port to a different platform and either have multiple
8 * variants of this file or simply load it up with #ifdefs.
10 * Copyright (c) 1987-2015 by the citadel.org team
12 * This program is open source software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License, version 3.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
27 #include <sys/syslog.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <netinet/tcp.h>
36 #include <arpa/inet.h>
38 #define SHOW_ME_VAPPEND_PRINTF
39 #include <libcitadel.h>
41 #include "citserver.h"
43 #include "ctdl_module.h"
45 #include "sysdep_decls.h"
46 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
48 #include "housekeeping.h"
51 * Signal handler to shut down the server.
54 volatile int exit_signal = 0;
55 volatile int shutdown_and_halt = 0;
56 volatile int restart_server = 0;
57 volatile int running_as_daemon = 0;
59 static RETSIGTYPE signal_cleanup(int signum) {
60 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
62 server_shutting_down = 1;
65 static RETSIGTYPE signal_exit(int signum) {
72 * Some initialization stuff...
74 void init_sysdep(void) {
77 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
81 getrlimit(RLIMIT_NOFILE, &rl);
82 rl.rlim_cur = FD_SETSIZE;
83 rl.rlim_max = FD_SETSIZE;
84 setrlimit(RLIMIT_NOFILE, &rl);
88 /* If we've got OpenSSL, we're going to use it. */
94 * Set up a place to put thread-specific data.
95 * We only need a single pointer per thread - it points to the
96 * CitContext structure (in the ContextList linked list) of the
97 * session to which the calling thread is currently bound.
99 if (pthread_key_create(&MyConKey, NULL) != 0) {
100 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
104 * Interript, hangup, and terminate signals should cause the server
105 * to gracefully clean up and shut down.
108 sigaddset(&set, SIGINT);
109 sigaddset(&set, SIGHUP);
110 sigaddset(&set, SIGTERM);
111 sigprocmask(SIG_UNBLOCK, &set, NULL);
113 signal(SIGINT, signal_cleanup);
114 signal(SIGHUP, signal_cleanup);
115 signal(SIGTERM, signal_cleanup);
116 signal(SIGUSR2, signal_exit);
119 * Do not shut down the server on broken pipe signals, otherwise the
120 * whole Citadel service would come down whenever a single client
123 signal(SIGPIPE, SIG_IGN);
128 * This is a generic function to set up a master socket for listening on
129 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
131 * ip_addr IP address to bind
132 * port_number port number to bind
133 * queue_len number of incoming connections to allow in the queue
135 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
138 struct sockaddr_in6 sin6;
139 struct sockaddr_in sin4;
143 memset(&sin6, 0, sizeof(sin6));
144 memset(&sin4, 0, sizeof(sin4));
145 sin6.sin6_family = AF_INET6;
146 sin4.sin_family = AF_INET;
148 if ( (ip_addr == NULL) /* any IPv6 */
149 || (IsEmptyStr(ip_addr))
150 || (!strcmp(ip_addr, "*"))
153 sin6.sin6_addr = in6addr_any;
155 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
158 sin4.sin_addr.s_addr = INADDR_ANY;
160 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
163 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
164 snprintf(errormessage, SIZ,
165 "Error binding to [%s] : %s", ip_addr, strerror(errno)
167 syslog(LOG_ALERT, "%s", errormessage);
171 else /* specific IPv6 */
174 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
175 snprintf(errormessage, SIZ,
176 "Error binding to [%s] : %s", ip_addr, strerror(errno)
178 syslog(LOG_ALERT, "%s", errormessage);
183 if (port_number == 0) {
184 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
185 syslog(LOG_ALERT, "%s", errormessage);
188 sin6.sin6_port = htons((u_short) port_number);
189 sin4.sin_port = htons((u_short) port_number);
191 p = getprotobyname("tcp");
193 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
195 snprintf(errormessage, SIZ,
196 "Can't create a listening socket: %s", strerror(errno)
198 syslog(LOG_ALERT, "%s", errormessage);
201 /* Set some socket options that make sense. */
203 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
205 if (ip_version == 6) {
206 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
209 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
213 snprintf(errormessage, SIZ,
214 "Can't bind: %s", strerror(errno)
216 syslog(LOG_ALERT, "%s", errormessage);
220 fcntl(s, F_SETFL, O_NONBLOCK);
222 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
223 snprintf(errormessage, SIZ,
224 "Can't listen: %s", strerror(errno)
226 syslog(LOG_ALERT, "%s", errormessage);
237 * Create a Unix domain socket and listen on it
239 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
241 struct sockaddr_un addr;
244 int actual_queue_len;
245 #ifdef HAVE_STRUCT_UCRED
249 actual_queue_len = queue_len;
250 if (actual_queue_len < 5) actual_queue_len = 5;
252 i = unlink(sockpath);
253 if ((i != 0) && (errno != ENOENT)) {
254 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
255 sockpath, strerror(errno)
257 syslog(LOG_EMERG, "%s", errormessage);
261 memset(&addr, 0, sizeof(addr));
262 addr.sun_family = AF_UNIX;
263 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
265 s = socket(AF_UNIX, SOCK_STREAM, 0);
267 snprintf(errormessage, SIZ,
268 "citserver: Can't create a socket: %s",
270 syslog(LOG_EMERG, "%s", errormessage);
274 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
275 snprintf(errormessage, SIZ,
276 "citserver: Can't bind: %s",
278 syslog(LOG_EMERG, "%s", errormessage);
282 /* set to nonblock - we need this for some obscure situations */
283 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
284 snprintf(errormessage, SIZ,
285 "citserver: Can't set socket to non-blocking: %s",
287 syslog(LOG_EMERG, "%s", errormessage);
292 if (listen(s, actual_queue_len) < 0) {
293 snprintf(errormessage, SIZ,
294 "citserver: Can't listen: %s",
296 syslog(LOG_EMERG, "%s", errormessage);
300 #ifdef HAVE_STRUCT_UCRED
301 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
304 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
311 * The following functions implement output buffering on operating systems which
312 * support it (such as Linux and various BSD flavors).
316 # define HAVE_TCP_BUFFERING
319 # define HAVE_TCP_BUFFERING
320 # define TCP_CORK TCP_NOPUSH
322 #endif /* TCP_CORK */
323 #endif /* HAVE_DARWIN */
325 static unsigned on = 1, off = 0;
327 void buffer_output(void) {
328 #ifdef HAVE_TCP_BUFFERING
330 if (!CC->redirect_ssl)
332 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
336 void unbuffer_output(void) {
337 #ifdef HAVE_TCP_BUFFERING
339 if (!CC->redirect_ssl)
341 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
345 void flush_output(void) {
346 #ifdef HAVE_TCP_BUFFERING
347 struct CitContext *CCC = CC;
348 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
349 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
354 static void flush_client_inbuf(void)
358 FlushStrBuf(CCC->ReadBuf);
359 CCC->RecvBuf->ReadWritePointer = NULL;
366 * client_close() ... close the client socket
368 void client_close(void) {
369 CitContext *CCC = CC;
372 if (CCC->client_socket <= 0) return;
373 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
375 close(CCC->client_socket);
376 CCC->client_socket = -1 ;
383 * client_write() ... Send binary data to the client.
385 int client_write(const char *buf, int nbytes)
387 int bytes_written = 0;
389 #ifndef HAVE_TCP_BUFFERING
390 int old_buffer_len = 0;
396 if (nbytes < 1) return(0);
406 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
408 fd = fopen(fn, "a+");
410 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
414 fprintf(fd, "Sending: BufSize: %d BufContent: [",
416 rv = fwrite(buf, nbytes, 1, fd);
421 // flush_client_inbuf();
422 if (Ctx->redirect_buffer != NULL) {
423 StrBufAppendBufPlain(Ctx->redirect_buffer,
429 if (Ctx->redirect_ssl) {
430 client_write_ssl(buf, nbytes);
434 if (Ctx->client_socket == -1) return -1;
436 fdflags = fcntl(Ctx->client_socket, F_GETFL);
438 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
439 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
441 FD_SET(Ctx->client_socket, &wset);
442 if (select(1, NULL, &wset, NULL, NULL) == -1) {
445 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
448 if (server_shutting_down) {
449 CC->kill_me = KILLME_SELECT_INTERRUPTED;
452 /* can't trust fd's and stuff so we need to re-create them */
457 "client_write(%d bytes) select failed: %s (%d)",
458 nbytes - bytes_written,
459 strerror(errno), errno
463 Ctx->kill_me = KILLME_SELECT_FAILED;
469 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
472 "client_write(%d bytes) failed: %s (%d)",
473 nbytes - bytes_written,
474 strerror(errno), errno
478 Ctx->kill_me = KILLME_WRITE_FAILED;
481 bytes_written = bytes_written + retval;
486 void cputbuf(const StrBuf *Buf) {
487 client_write(ChrPtr(Buf), StrLength(Buf));
492 * cprintf() Send formatted printable data to the client.
493 * Implemented in terms of client_write() so it's technically not sysdep...
495 void cprintf(const char *format, ...) {
499 va_start(arg_ptr, format);
500 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
501 buf[sizeof buf - 2] = '\n';
502 client_write(buf, strlen(buf));
508 * Read data from the client socket.
510 * sock socket fd to read from
511 * buf buffer to read into
512 * bytes number of bytes to read
513 * timeout Number of seconds to wait before timing out
515 * Possible return values:
516 * 1 Requested number of bytes has been read.
517 * 0 Request timed out.
518 * -1 Connection is broken, or other error.
520 int client_read_blob(StrBuf *Target, int bytes, int timeout)
527 if (CCC->redirect_ssl) {
533 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
535 fd = fopen(fn, "a+");
537 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
541 fprintf(fd, "Reading BLOB: BufSize: %d ",
543 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
549 retval = client_read_sslblob(Target, bytes, timeout);
551 syslog(LOG_CRIT, "client_read_blob() failed");
554 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
556 fd = fopen(fn, "a+");
558 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
562 fprintf(fd, "Read: %d BufContent: [",
564 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
579 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
581 fd = fopen(fn, "a+");
583 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
587 fprintf(fd, "Reading BLOB: BufSize: %d ",
589 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
595 retval = StrBufReadBLOBBuffered(Target,
597 &CCC->RecvBuf.ReadWritePointer,
604 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
609 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
611 fd = fopen(fn, "a+");
613 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
617 fprintf(fd, "Read: %d BufContent: [",
619 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
629 * to make client_read_random_blob() more efficient, increase buffer size.
630 * just use in greeting function, else your buffer may be flushed
632 void client_set_inbound_buf(long N)
635 FlushStrBuf(CCC->RecvBuf.Buf);
636 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
639 int client_read_random_blob(StrBuf *Target, int timeout)
644 rc = client_read_blob(Target, 1, timeout);
650 len = StrLength(CCC->RecvBuf.Buf);
651 pch = ChrPtr(CCC->RecvBuf.Buf);
655 if (CCC->RecvBuf.ReadWritePointer != NULL) {
656 len -= CCC->RecvBuf.ReadWritePointer - pch;
657 pch = CCC->RecvBuf.ReadWritePointer;
659 StrBufAppendBufPlain(Target, pch, len, 0);
660 FlushStrBuf(CCC->RecvBuf.Buf);
661 CCC->RecvBuf.ReadWritePointer = NULL;
668 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
670 fd = fopen(fn, "a+");
672 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
676 fprintf(fd, "Read: BufSize: %d BufContent: [",
678 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
686 return StrLength(Target);
694 int client_read_to(char *buf, int bytes, int timeout)
699 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
708 ChrPtr(CCC->MigrateBuf),
709 StrLength(CCC->MigrateBuf) + 1);
710 FlushStrBuf(CCC->MigrateBuf);
716 int HaveMoreLinesWaiting(CitContext *CCC)
718 if ((CCC->kill_me != 0) ||
719 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
720 (StrLength(CCC->RecvBuf.Buf) == 0) &&
721 (CCC->client_socket != -1)) )
729 * Read data from the client socket with default timeout.
730 * (This is implemented in terms of client_read_to() and could be
731 * justifiably moved out of sysdep.c)
733 INLINE int client_read(char *buf, int bytes)
735 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
738 int CtdlClientGetLine(StrBuf *Target)
746 if (CCC->redirect_ssl) {
756 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
758 fd = fopen(fn, "a+");
760 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
764 pch = ChrPtr(CCC->RecvBuf.Buf);
765 len = StrLength(CCC->RecvBuf.Buf);
766 if (CCC->RecvBuf.ReadWritePointer != NULL)
767 rlen = CCC->RecvBuf.ReadWritePointer - pch;
771 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
774 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
777 rc = client_readline_sslbuffer(Target,
779 &CCC->RecvBuf.ReadWritePointer,
782 pch = ChrPtr(CCC->RecvBuf.Buf);
783 nlen = StrLength(CCC->RecvBuf.Buf);
784 if (CCC->RecvBuf.ReadWritePointer != NULL)
785 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
789 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
790 len, nlen, rlen, nrlen, pch);
792 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
793 len, nlen, rlen, nrlen);
795 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
796 StrLength(Target), ChrPtr(Target));
800 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
811 int len, rlen, nlen, nrlen;
814 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
816 fd = fopen(fn, "a+");
818 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
822 pch = ChrPtr(CCC->RecvBuf.Buf);
823 len = StrLength(CCC->RecvBuf.Buf);
824 if (CCC->RecvBuf.ReadWritePointer != NULL)
825 rlen = CCC->RecvBuf.ReadWritePointer - pch;
829 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
832 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
835 rc = StrBufTCP_read_buffered_line_fast(Target,
837 &CCC->RecvBuf.ReadWritePointer,
844 pch = ChrPtr(CCC->RecvBuf.Buf);
845 nlen = StrLength(CCC->RecvBuf.Buf);
846 if (CCC->RecvBuf.ReadWritePointer != NULL)
847 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
851 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
852 len, nlen, rlen, nrlen, pch);
854 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
855 len, nlen, rlen, nrlen);
857 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
858 StrLength(Target), ChrPtr(Target));
861 if ((rc < 0) && (Error != NULL)) {
862 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
871 * client_getln() ... Get a LF-terminated line of text from the client.
872 * (This is implemented in terms of client_read() and could be
873 * justifiably moved out of sysdep.c)
875 int client_getln(char *buf, int bufsize)
881 retval = CtdlClientGetLine(CCC->MigrateBuf);
886 i = StrLength(CCC->MigrateBuf);
887 pCh = ChrPtr(CCC->MigrateBuf);
888 /* Strip the trailing LF, and the trailing CR if present.
893 && ( (pCh[i - 1]==13)
894 || ( pCh[i - 1]==10)) ) {
900 FlushStrBuf(CCC->MigrateBuf);
902 safestrncpy(&buf[i], "000", bufsize - i);
909 * Cleanup any contexts that are left lying around
913 void close_masters (void)
915 struct ServiceFunctionHook *serviceptr;
919 * close all protocol master sockets
921 for (serviceptr = ServiceHookTable; serviceptr != NULL;
922 serviceptr = serviceptr->next ) {
924 if (serviceptr->tcp_port > 0)
926 if (serviceptr->msock == -1)
927 Text = "not closing again";
931 syslog(LOG_INFO, "%s %d listener on port %d\n",
934 serviceptr->tcp_port);
935 serviceptr->tcp_port = 0;
938 if (serviceptr->sockpath != NULL)
940 if (serviceptr->msock == -1)
941 Text = "not closing again";
945 syslog(LOG_INFO, "%s %d listener on '%s'\n",
948 serviceptr->sockpath);
951 if (serviceptr->msock != -1)
953 close(serviceptr->msock);
954 serviceptr->msock = -1;
957 /* If it's a Unix domain socket, remove the file. */
958 if (serviceptr->sockpath != NULL) {
959 unlink(serviceptr->sockpath);
960 serviceptr->sockpath = NULL;
967 * The system-dependent part of master_cleanup() - close the master socket.
969 void sysdep_master_cleanup(void) {
978 CtdlDestroyProtoHooks();
979 CtdlDestroyDeleteHooks();
980 CtdlDestroyXmsgHooks();
981 CtdlDestroyNetprocHooks();
982 CtdlDestroyUserHooks();
983 CtdlDestroyMessageHook();
984 CtdlDestroyCleanupHooks();
985 CtdlDestroyFixedOutputHooks();
986 CtdlDestroySessionHooks();
987 CtdlDestroyTDAPVetoHooks();
988 CtdlDestroyServiceHook();
989 CtdlDestroyRoomHooks();
990 CtdlDestroySearchHooks();
991 CtdlDestroyDebugTable();
992 #ifdef HAVE_BACKTRACE
1000 void graceful_shutdown(int signum) {
1001 kill(current_child, signum);
1002 unlink(file_pid_file);
1007 int nFireUpsNonRestart = 0;
1008 pid_t ForkedPid = 1;
1011 * Start running as a daemon.
1013 void start_daemon(int unused) {
1021 /* Close stdin/stdout/stderr and replace them with /dev/null.
1022 * We don't just call close() because we don't want these fd's
1023 * to be reused for other files.
1025 if (chdir(ctdl_run_dir) != 0)
1027 "unable to change into directory [%s]: %s",
1028 ctdl_run_dir, strerror(errno));
1035 signal(SIGHUP, SIG_IGN);
1036 signal(SIGINT, SIG_IGN);
1037 signal(SIGQUIT, SIG_IGN);
1041 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1042 (freopen("/dev/null", "w", stdout) != stdout) ||
1043 (freopen("/dev/null", "w", stderr) != stderr))
1045 "unable to reopen stdin/out/err %s",
1050 current_child = fork();
1052 signal(SIGTERM, graceful_shutdown);
1054 if (current_child < 0) {
1059 else if (current_child == 0) {
1060 return; /* continue starting citadel. */
1064 fp = fopen(file_pid_file, "w");
1066 fprintf(fp, ""F_PID_T"\n", getpid());
1069 waitpid(current_child, &status, 0);
1072 nFireUpsNonRestart = nFireUps;
1074 /* Exit code 0 means the watcher should exit */
1075 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1079 /* Exit code 101-109 means the watcher should exit */
1080 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1084 /* Any other exit code, or no exit code, means we should restart. */
1088 ForkedPid = current_child;
1091 } while (do_restart);
1093 unlink(file_pid_file);
1094 exit(WEXITSTATUS(status));
1099 void checkcrash(void)
1101 if (nFireUpsNonRestart != nFireUps)
1104 const char *msgs[1] = {"crash"};
1105 const long lens[1] = {sizeof("crash") - 1};
1106 CrashMail = NewStrBuf();
1107 syslog(LOG_ALERT, "Posting crash message\n");
1108 StrBufPrintf(CrashMail,
1110 " The Citadel server process (citserver) terminated unexpectedly."
1112 " This could be the result of a bug in the server program, or some external "
1114 " You can obtain more information about this by enabling core dumps.\n \n"
1115 " For more information, please see:\n \n"
1116 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1119 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1121 ctdl_run_dir, ForkedPid);
1122 CtdlAideFPMessage(ChrPtr(CrashMail),
1123 "Citadel server process terminated unexpectedly",
1127 FreeStrBuf(&CrashMail);
1133 * Generic routine to convert a login name to a full name (gecos)
1134 * Returns nonzero if a conversion took place
1136 int convert_login(char NameToConvert[]) {
1140 pw = getpwnam(NameToConvert);
1145 strcpy(NameToConvert, pw->pw_gecos);
1146 for (a=0; a<strlen(NameToConvert); ++a) {
1147 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1155 void HuntBadSession(void)
1161 struct ServiceFunctionHook *serviceptr;
1165 /* Next, add all of the client sockets. */
1166 begin_critical_section(S_SESSION_TABLE);
1167 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1168 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1170 /* Initialize the fdset. */
1173 tv.tv_sec = 0; /* wake up every second if no input */
1176 /* Don't select on dead sessions, only truly idle ones */
1177 if ( (ptr->state == CON_IDLE)
1178 && (ptr->kill_me == 0)
1179 && (ptr->client_socket > 0)
1181 FD_SET(ptr->client_socket, &readfds);
1182 if (ptr->client_socket > highest)
1183 highest = ptr->client_socket;
1185 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1190 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1193 ptr->is_local_socket,
1195 ptr->cs_host,ptr->cs_addr);
1198 ptr->client_socket = -1;
1204 end_critical_section(S_SESSION_TABLE);
1207 /* First, add the various master sockets to the fdset. */
1208 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1210 /* Initialize the fdset. */
1212 tv.tv_sec = 0; /* wake up every second if no input */
1215 FD_SET(serviceptr->msock, &readfds);
1216 if (serviceptr->msock > highest) {
1217 highest = serviceptr->msock;
1219 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1222 /* Gotcha! server socket dead? commit suicide! */
1224 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1227 server_shutting_down = 1;
1235 const char *WorkerLogStr = "W";
1237 * This loop just keeps going and going and going...
1239 void *worker_thread(void *blah) {
1242 CitContext *bind_me = NULL;
1246 int force_purge = 0;
1247 struct ServiceFunctionHook *serviceptr;
1248 int ssock; /* Descriptor for client socket */
1249 CitContext *con = NULL; /* Temporary context pointer */
1252 pthread_mutex_lock(&ThreadCountMutex);
1254 pthread_mutex_unlock(&ThreadCountMutex);
1256 pthread_setspecific(evConKey, WorkerLogStr);
1258 while (!server_shutting_down) {
1260 /* make doubly sure we're not holding any stale db handles
1261 * which might cause a deadlock.
1263 cdb_check_handles();
1264 do_select: force_purge = 0;
1265 bind_me = NULL; /* Which session shall we handle? */
1267 /* Initialize the fdset. */
1271 /* First, add the various master sockets to the fdset. */
1272 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1273 FD_SET(serviceptr->msock, &readfds);
1274 if (serviceptr->msock > highest) {
1275 highest = serviceptr->msock;
1279 /* Next, add all of the client sockets. */
1280 begin_critical_section(S_SESSION_TABLE);
1281 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1282 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1285 /* Don't select on dead sessions, only truly idle ones */
1286 if ( (ptr->state == CON_IDLE)
1287 && (ptr->kill_me == 0)
1288 && (ptr->client_socket > 0)
1290 FD_SET(ptr->client_socket, &readfds);
1291 if (ptr->client_socket > highest)
1292 highest = ptr->client_socket;
1294 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1296 ptr->state = CON_EXECUTING;
1299 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1301 ptr->state = CON_STARTING;
1305 end_critical_section(S_SESSION_TABLE);
1311 /* If we got this far, it means that there are no sessions
1312 * which a previous thread marked for attention, so we go
1313 * ahead and get ready to select().
1316 if (!server_shutting_down) {
1317 tv.tv_sec = 1; /* wake up every second if no input */
1319 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1326 /* Now figure out who made this select() unblock.
1327 * First, check for an error or exit condition.
1330 if (errno == EBADF) {
1331 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1335 if (errno != EINTR) {
1336 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1337 server_shutting_down = 1;
1341 syslog(LOG_DEBUG, "Interrupted select()\n");
1343 if (server_shutting_down) {
1350 else if (retval == 0) {
1351 if (server_shutting_down) {
1357 /* Next, check to see if it's a new client connecting * on a master socket. */
1359 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1361 if (FD_ISSET(serviceptr->msock, &readfds)) {
1362 ssock = accept(serviceptr->msock, NULL, 0);
1364 syslog(LOG_DEBUG, "New client socket %d", ssock);
1366 /* The master socket is non-blocking but the client
1367 * sockets need to be blocking, otherwise certain
1368 * operations barf on FreeBSD. Not a fatal error.
1370 if (fcntl(ssock, F_SETFL, 0) < 0) {
1372 "citserver: Can't set socket to blocking: %s\n",
1376 /* New context will be created already
1377 * set up in the CON_EXECUTING state.
1379 con = CreateNewContext();
1381 /* Assign our new socket number to it. */
1382 con->tcp_port = serviceptr->tcp_port;
1383 con->client_socket = ssock;
1384 con->h_command_function = serviceptr->h_command_function;
1385 con->h_async_function = serviceptr->h_async_function;
1386 con->h_greeting_function = serviceptr->h_greeting_function;
1387 con->ServiceName = serviceptr->ServiceName;
1389 /* Determine whether it's a local socket */
1390 if (serviceptr->sockpath != NULL) {
1391 con->is_local_socket = 1;
1394 /* Set the SO_REUSEADDR socket option */
1396 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1397 con->state = CON_GREETING;
1405 /* It must be a client socket. Find a context that has data
1406 * waiting on its socket *and* is in the CON_IDLE state. Any
1407 * active sockets other than our chosen one are marked as
1408 * CON_READY so the next thread that comes around can just bind
1409 * to one without having to select() again.
1411 begin_critical_section(S_SESSION_TABLE);
1412 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1413 int checkfd = ptr->client_socket;
1414 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1415 if (FD_ISSET(checkfd, &readfds)) {
1416 ptr->input_waiting = 1;
1418 bind_me = ptr; /* I choose you! */
1419 bind_me->state = CON_EXECUTING;
1422 ptr->state = CON_READY;
1424 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1426 bind_me = ptr; /* I choose you! */
1427 bind_me->state = CON_EXECUTING;
1430 ptr->state = CON_READY;
1435 end_critical_section(S_SESSION_TABLE);
1438 /* We're bound to a session */
1439 pthread_mutex_lock(&ThreadCountMutex);
1441 pthread_mutex_unlock(&ThreadCountMutex);
1443 if (bind_me != NULL) {
1444 become_session(bind_me);
1446 if (bind_me->state == CON_STARTING) {
1447 bind_me->state = CON_EXECUTING;
1448 begin_session(bind_me);
1449 bind_me->h_greeting_function();
1451 /* If the client has sent a command, execute it. */
1452 if (CC->input_waiting) {
1453 CC->h_command_function();
1455 while (HaveMoreLinesWaiting(CC))
1456 CC->h_command_function();
1458 CC->input_waiting = 0;
1461 /* If there are asynchronous messages waiting and the
1462 * client supports it, do those now */
1463 if ((CC->is_async) && (CC->async_waiting)
1464 && (CC->h_async_function != NULL)) {
1465 CC->h_async_function();
1466 CC->async_waiting = 0;
1469 force_purge = CC->kill_me;
1470 become_session(NULL);
1471 bind_me->state = CON_IDLE;
1474 dead_session_purge(force_purge);
1477 pthread_mutex_lock(&ThreadCountMutex);
1479 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1480 (num_workers > CtdlGetConfigInt("c_min_workers")))
1483 pthread_mutex_unlock(&ThreadCountMutex);
1486 pthread_mutex_unlock(&ThreadCountMutex);
1489 /* If control reaches this point, the server is shutting down */
1490 pthread_mutex_lock(&ThreadCountMutex);
1492 pthread_mutex_unlock(&ThreadCountMutex);
1500 * Translate text facility name to syslog.h defined value.
1502 int SyslogFacility(char *name)
1511 { LOG_KERN, "kern" },
1512 { LOG_USER, "user" },
1513 { LOG_MAIL, "mail" },
1514 { LOG_DAEMON, "daemon" },
1515 { LOG_AUTH, "auth" },
1516 { LOG_SYSLOG, "syslog" },
1518 { LOG_NEWS, "news" },
1519 { LOG_UUCP, "uucp" },
1520 { LOG_LOCAL0, "local0" },
1521 { LOG_LOCAL1, "local1" },
1522 { LOG_LOCAL2, "local2" },
1523 { LOG_LOCAL3, "local3" },
1524 { LOG_LOCAL4, "local4" },
1525 { LOG_LOCAL5, "local5" },
1526 { LOG_LOCAL6, "local6" },
1527 { LOG_LOCAL7, "local7" },
1530 for(i = 0; facTbl[i].name != NULL; i++) {
1531 if(!strcasecmp(name, facTbl[i].name))
1532 return facTbl[i].facility;