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.
24 #include <sys/syslog.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
35 #define SHOW_ME_VAPPEND_PRINTF
36 #include <libcitadel.h>
38 #include "citserver.h"
40 #include "ctdl_module.h"
42 #include "sysdep_decls.h"
43 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
45 #include "housekeeping.h"
48 * Signal handler to shut down the server.
51 volatile int exit_signal = 0;
52 volatile int shutdown_and_halt = 0;
53 volatile int restart_server = 0;
54 volatile int running_as_daemon = 0;
56 static RETSIGTYPE signal_cleanup(int signum) {
57 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
59 server_shutting_down = 1;
62 static RETSIGTYPE signal_exit(int signum) {
69 * Some initialization stuff...
71 void init_sysdep(void) {
74 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
78 getrlimit(RLIMIT_NOFILE, &rl);
79 rl.rlim_cur = FD_SETSIZE;
80 rl.rlim_max = FD_SETSIZE;
81 setrlimit(RLIMIT_NOFILE, &rl);
85 /* If we've got OpenSSL, we're going to use it. */
91 * Set up a place to put thread-specific data.
92 * We only need a single pointer per thread - it points to the
93 * CitContext structure (in the ContextList linked list) of the
94 * session to which the calling thread is currently bound.
96 if (pthread_key_create(&MyConKey, NULL) != 0) {
97 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
101 * Interript, hangup, and terminate signals should cause the server
102 * to gracefully clean up and shut down.
105 sigaddset(&set, SIGINT);
106 sigaddset(&set, SIGHUP);
107 sigaddset(&set, SIGTERM);
108 sigprocmask(SIG_UNBLOCK, &set, NULL);
110 signal(SIGINT, signal_cleanup);
111 signal(SIGHUP, signal_cleanup);
112 signal(SIGTERM, signal_cleanup);
113 signal(SIGUSR2, signal_exit);
116 * Do not shut down the server on broken pipe signals, otherwise the
117 * whole Citadel service would come down whenever a single client
120 signal(SIGPIPE, SIG_IGN);
125 * This is a generic function to set up a master socket for listening on
126 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
128 * ip_addr IP address to bind
129 * port_number port number to bind
130 * queue_len number of incoming connections to allow in the queue
132 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
135 struct sockaddr_in6 sin6;
136 struct sockaddr_in sin4;
140 memset(&sin6, 0, sizeof(sin6));
141 memset(&sin4, 0, sizeof(sin4));
142 sin6.sin6_family = AF_INET6;
143 sin4.sin_family = AF_INET;
145 if ( (ip_addr == NULL) /* any IPv6 */
146 || (IsEmptyStr(ip_addr))
147 || (!strcmp(ip_addr, "*"))
150 sin6.sin6_addr = in6addr_any;
152 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
155 sin4.sin_addr.s_addr = INADDR_ANY;
157 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
160 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
161 snprintf(errormessage, SIZ,
162 "Error binding to [%s] : %s", ip_addr, strerror(errno)
164 syslog(LOG_ALERT, "%s", errormessage);
168 else /* specific IPv6 */
171 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
172 snprintf(errormessage, SIZ,
173 "Error binding to [%s] : %s", ip_addr, strerror(errno)
175 syslog(LOG_ALERT, "%s", errormessage);
180 if (port_number == 0) {
181 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
182 syslog(LOG_ALERT, "%s", errormessage);
185 sin6.sin6_port = htons((u_short) port_number);
186 sin4.sin_port = htons((u_short) port_number);
188 p = getprotobyname("tcp");
190 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
192 snprintf(errormessage, SIZ,
193 "Can't create a listening socket: %s", strerror(errno)
195 syslog(LOG_ALERT, "%s", errormessage);
198 /* Set some socket options that make sense. */
200 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
202 if (ip_version == 6) {
203 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
206 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
210 snprintf(errormessage, SIZ,
211 "Can't bind: %s", strerror(errno)
213 syslog(LOG_ALERT, "%s", errormessage);
217 fcntl(s, F_SETFL, O_NONBLOCK);
219 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
220 snprintf(errormessage, SIZ,
221 "Can't listen: %s", strerror(errno)
223 syslog(LOG_ALERT, "%s", errormessage);
234 * Create a Unix domain socket and listen on it
236 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
238 struct sockaddr_un addr;
241 int actual_queue_len;
242 #ifdef HAVE_STRUCT_UCRED
246 actual_queue_len = queue_len;
247 if (actual_queue_len < 5) actual_queue_len = 5;
249 i = unlink(sockpath);
250 if ((i != 0) && (errno != ENOENT)) {
251 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
252 sockpath, strerror(errno)
254 syslog(LOG_EMERG, "%s", errormessage);
258 memset(&addr, 0, sizeof(addr));
259 addr.sun_family = AF_UNIX;
260 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
262 s = socket(AF_UNIX, SOCK_STREAM, 0);
264 snprintf(errormessage, SIZ, "citserver: Can't create a socket: %s", strerror(errno));
265 syslog(LOG_EMERG, "%s", errormessage);
269 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
270 snprintf(errormessage, SIZ, "citserver: Can't bind: %s", strerror(errno));
271 syslog(LOG_EMERG, "%s", errormessage);
275 /* set to nonblock - we need this for some obscure situations */
276 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
277 snprintf(errormessage, SIZ, "citserver: Can't set socket to non-blocking: %s", strerror(errno));
278 syslog(LOG_EMERG, "%s", errormessage);
283 if (listen(s, actual_queue_len) < 0) {
284 snprintf(errormessage, SIZ, "citserver: Can't listen: %s", strerror(errno));
285 syslog(LOG_EMERG, "%s", errormessage);
289 #ifdef HAVE_STRUCT_UCRED
290 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
293 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
300 * The following functions implement output buffering on operating systems which
301 * support it (such as Linux and various BSD flavors).
305 # define HAVE_TCP_BUFFERING
308 # define HAVE_TCP_BUFFERING
309 # define TCP_CORK TCP_NOPUSH
311 #endif /* TCP_CORK */
312 #endif /* HAVE_DARWIN */
314 static unsigned on = 1, off = 0;
316 void buffer_output(void) {
317 #ifdef HAVE_TCP_BUFFERING
319 if (!CC->redirect_ssl)
321 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
325 void unbuffer_output(void) {
326 #ifdef HAVE_TCP_BUFFERING
328 if (!CC->redirect_ssl)
330 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
334 void flush_output(void) {
335 #ifdef HAVE_TCP_BUFFERING
336 struct CitContext *CCC = CC;
337 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
338 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
343 static void flush_client_inbuf(void)
347 FlushStrBuf(CCC->ReadBuf);
348 CCC->RecvBuf->ReadWritePointer = NULL;
355 * client_close() ... close the client socket
357 void client_close(void) {
358 CitContext *CCC = CC;
361 if (CCC->client_socket <= 0) return;
362 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
364 close(CCC->client_socket);
365 CCC->client_socket = -1 ;
372 * client_write() ... Send binary data to the client.
374 int client_write(const char *buf, int nbytes)
376 int bytes_written = 0;
378 #ifndef HAVE_TCP_BUFFERING
379 int old_buffer_len = 0;
385 if (nbytes < 1) return(0);
395 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
397 fd = fopen(fn, "a+");
399 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
403 fprintf(fd, "Sending: BufSize: %d BufContent: [",
405 rv = fwrite(buf, nbytes, 1, fd);
410 // flush_client_inbuf();
411 if (Ctx->redirect_buffer != NULL) {
412 StrBufAppendBufPlain(Ctx->redirect_buffer,
418 if (Ctx->redirect_ssl) {
419 client_write_ssl(buf, nbytes);
423 if (Ctx->client_socket == -1) return -1;
425 fdflags = fcntl(Ctx->client_socket, F_GETFL);
427 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
428 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
430 FD_SET(Ctx->client_socket, &wset);
431 if (select(1, NULL, &wset, NULL, NULL) == -1) {
434 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
437 if (server_shutting_down) {
438 CC->kill_me = KILLME_SELECT_INTERRUPTED;
441 /* can't trust fd's and stuff so we need to re-create them */
446 "client_write(%d bytes) select failed: %s (%d)",
447 nbytes - bytes_written,
448 strerror(errno), errno
452 Ctx->kill_me = KILLME_SELECT_FAILED;
458 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
461 "client_write(%d bytes) failed: %s (%d)",
462 nbytes - bytes_written,
463 strerror(errno), errno
467 Ctx->kill_me = KILLME_WRITE_FAILED;
470 bytes_written = bytes_written + retval;
475 void cputbuf(const StrBuf *Buf) {
476 client_write(ChrPtr(Buf), StrLength(Buf));
481 * cprintf() Send formatted printable data to the client.
482 * Implemented in terms of client_write() so it's technically not sysdep...
484 void cprintf(const char *format, ...) {
488 va_start(arg_ptr, format);
489 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
490 buf[sizeof buf - 2] = '\n';
491 client_write(buf, strlen(buf));
497 * Read data from the client socket.
499 * sock socket fd to read from
500 * buf buffer to read into
501 * bytes number of bytes to read
502 * timeout Number of seconds to wait before timing out
504 * Possible return values:
505 * 1 Requested number of bytes has been read.
506 * 0 Request timed out.
507 * -1 Connection is broken, or other error.
509 int client_read_blob(StrBuf *Target, int bytes, int timeout)
516 if (CCC->redirect_ssl) {
522 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
524 fd = fopen(fn, "a+");
526 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
530 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
531 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
537 retval = client_read_sslblob(Target, bytes, timeout);
539 syslog(LOG_CRIT, "client_read_blob() failed");
542 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
544 fd = fopen(fn, "a+");
546 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
550 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
551 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
564 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
566 fd = fopen(fn, "a+");
568 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
572 fprintf(fd, "Reading BLOB: BufSize: %d ",
574 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
578 retval = StrBufReadBLOBBuffered(Target,
580 &CCC->RecvBuf.ReadWritePointer,
588 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
593 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
595 fd = fopen(fn, "a+");
597 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
601 fprintf(fd, "Read: %d BufContent: [",
603 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
613 * to make client_read_random_blob() more efficient, increase buffer size.
614 * just use in greeting function, else your buffer may be flushed
616 void client_set_inbound_buf(long N)
619 FlushStrBuf(CCC->RecvBuf.Buf);
620 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
623 int client_read_random_blob(StrBuf *Target, int timeout)
628 rc = client_read_blob(Target, 1, timeout);
634 len = StrLength(CCC->RecvBuf.Buf);
635 pch = ChrPtr(CCC->RecvBuf.Buf);
639 if (CCC->RecvBuf.ReadWritePointer != NULL) {
640 len -= CCC->RecvBuf.ReadWritePointer - pch;
641 pch = CCC->RecvBuf.ReadWritePointer;
643 StrBufAppendBufPlain(Target, pch, len, 0);
644 FlushStrBuf(CCC->RecvBuf.Buf);
645 CCC->RecvBuf.ReadWritePointer = NULL;
652 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
654 fd = fopen(fn, "a+");
656 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
660 fprintf(fd, "Read: BufSize: %d BufContent: [",
662 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
667 return StrLength(Target);
675 int client_read_to(char *buf, int bytes, int timeout)
680 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
689 ChrPtr(CCC->MigrateBuf),
690 StrLength(CCC->MigrateBuf) + 1);
691 FlushStrBuf(CCC->MigrateBuf);
697 int HaveMoreLinesWaiting(CitContext *CCC)
699 if ((CCC->kill_me != 0) ||
700 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
701 (StrLength(CCC->RecvBuf.Buf) == 0) &&
702 (CCC->client_socket != -1)) )
710 * Read data from the client socket with default timeout.
711 * (This is implemented in terms of client_read_to() and could be
712 * justifiably moved out of sysdep.c)
714 INLINE int client_read(char *buf, int bytes)
716 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
719 int CtdlClientGetLine(StrBuf *Target)
727 if (CCC->redirect_ssl) {
737 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
739 fd = fopen(fn, "a+");
741 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
745 pch = ChrPtr(CCC->RecvBuf.Buf);
746 len = StrLength(CCC->RecvBuf.Buf);
747 if (CCC->RecvBuf.ReadWritePointer != NULL)
748 rlen = CCC->RecvBuf.ReadWritePointer - pch;
752 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
755 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
758 rc = client_readline_sslbuffer(Target,
760 &CCC->RecvBuf.ReadWritePointer,
763 pch = ChrPtr(CCC->RecvBuf.Buf);
764 nlen = StrLength(CCC->RecvBuf.Buf);
765 if (CCC->RecvBuf.ReadWritePointer != NULL)
766 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
770 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
771 len, nlen, rlen, nrlen, pch);
773 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
774 len, nlen, rlen, nrlen);
776 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
777 StrLength(Target), ChrPtr(Target));
781 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
792 int len, rlen, nlen, nrlen;
795 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
797 fd = fopen(fn, "a+");
799 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
803 pch = ChrPtr(CCC->RecvBuf.Buf);
804 len = StrLength(CCC->RecvBuf.Buf);
805 if (CCC->RecvBuf.ReadWritePointer != NULL)
806 rlen = CCC->RecvBuf.ReadWritePointer - pch;
810 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
813 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
816 rc = StrBufTCP_read_buffered_line_fast(Target,
818 &CCC->RecvBuf.ReadWritePointer,
826 pch = ChrPtr(CCC->RecvBuf.Buf);
827 nlen = StrLength(CCC->RecvBuf.Buf);
828 if (CCC->RecvBuf.ReadWritePointer != NULL)
829 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
833 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
834 len, nlen, rlen, nrlen, pch);
836 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
837 len, nlen, rlen, nrlen);
839 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
840 StrLength(Target), ChrPtr(Target));
843 if ((rc < 0) && (Error != NULL)) {
844 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
853 * client_getln() ... Get a LF-terminated line of text from the client.
854 * (This is implemented in terms of client_read() and could be
855 * justifiably moved out of sysdep.c)
857 int client_getln(char *buf, int bufsize)
863 retval = CtdlClientGetLine(CCC->MigrateBuf);
868 i = StrLength(CCC->MigrateBuf);
869 pCh = ChrPtr(CCC->MigrateBuf);
870 /* Strip the trailing LF, and the trailing CR if present.
875 && ( (pCh[i - 1]==13)
876 || ( pCh[i - 1]==10)) ) {
882 FlushStrBuf(CCC->MigrateBuf);
884 safestrncpy(&buf[i], "000", bufsize - i);
891 * Cleanup any contexts that are left lying around
895 void close_masters (void)
897 struct ServiceFunctionHook *serviceptr;
901 * close all protocol master sockets
903 for (serviceptr = ServiceHookTable; serviceptr != NULL;
904 serviceptr = serviceptr->next ) {
906 if (serviceptr->tcp_port > 0)
908 if (serviceptr->msock == -1)
909 Text = "not closing again";
913 syslog(LOG_INFO, "%s %d listener on port %d",
918 serviceptr->tcp_port = 0;
921 if (serviceptr->sockpath != NULL)
923 if (serviceptr->msock == -1)
924 Text = "not closing again";
928 syslog(LOG_INFO, "%s %d listener on '%s'",
935 if (serviceptr->msock != -1)
937 close(serviceptr->msock);
938 serviceptr->msock = -1;
941 /* If it's a Unix domain socket, remove the file. */
942 if (serviceptr->sockpath != NULL) {
943 unlink(serviceptr->sockpath);
944 serviceptr->sockpath = NULL;
951 * The system-dependent part of master_cleanup() - close the master socket.
953 void sysdep_master_cleanup(void) {
962 CtdlDestroyProtoHooks();
963 CtdlDestroyDeleteHooks();
964 CtdlDestroyXmsgHooks();
965 CtdlDestroyNetprocHooks();
966 CtdlDestroyUserHooks();
967 CtdlDestroyMessageHook();
968 CtdlDestroyCleanupHooks();
969 CtdlDestroyFixedOutputHooks();
970 CtdlDestroySessionHooks();
971 CtdlDestroyTDAPVetoHooks();
972 CtdlDestroyServiceHook();
973 CtdlDestroyRoomHooks();
974 CtdlDestroySearchHooks();
975 CtdlDestroyDebugTable();
976 #ifdef HAVE_BACKTRACE
984 void graceful_shutdown(int signum) {
985 kill(current_child, signum);
986 unlink(file_pid_file);
991 int nFireUpsNonRestart = 0;
995 * Start running as a daemon.
997 void start_daemon(int unused) {
1005 /* Close stdin/stdout/stderr and replace them with /dev/null.
1006 * We don't just call close() because we don't want these fd's
1007 * to be reused for other files.
1009 if (chdir(ctdl_run_dir) != 0)
1011 "unable to change into directory [%s]: %s",
1012 ctdl_run_dir, strerror(errno));
1019 signal(SIGHUP, SIG_IGN);
1020 signal(SIGINT, SIG_IGN);
1021 signal(SIGQUIT, SIG_IGN);
1025 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1026 (freopen("/dev/null", "w", stdout) != stdout) ||
1027 (freopen("/dev/null", "w", stderr) != stderr))
1029 "unable to reopen stdin/out/err %s",
1034 current_child = fork();
1036 signal(SIGTERM, graceful_shutdown);
1038 if (current_child < 0) {
1043 else if (current_child == 0) {
1044 return; /* continue starting citadel. */
1048 fp = fopen(file_pid_file, "w");
1050 fprintf(fp, ""F_PID_T"\n", getpid());
1053 waitpid(current_child, &status, 0);
1056 nFireUpsNonRestart = nFireUps;
1058 /* Exit code 0 means the watcher should exit */
1059 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1063 /* Exit code 101-109 means the watcher should exit */
1064 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1068 /* Any other exit code, or no exit code, means we should restart. */
1072 ForkedPid = current_child;
1075 } while (do_restart);
1077 unlink(file_pid_file);
1078 exit(WEXITSTATUS(status));
1083 void checkcrash(void)
1085 if (nFireUpsNonRestart != nFireUps)
1088 const char *msgs[1] = {"crash"};
1089 const long lens[1] = {sizeof("crash") - 1};
1090 CrashMail = NewStrBuf();
1091 syslog(LOG_ALERT, "Posting crash message\n");
1092 StrBufPrintf(CrashMail,
1094 " The Citadel server process (citserver) terminated unexpectedly."
1096 " This could be the result of a bug in the server program, or some external "
1098 " You can obtain more information about this by enabling core dumps.\n \n"
1099 " For more information, please see:\n \n"
1100 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1103 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1105 ctdl_run_dir, ForkedPid);
1106 CtdlAideFPMessage(ChrPtr(CrashMail),
1107 "Citadel server process terminated unexpectedly",
1111 FreeStrBuf(&CrashMail);
1117 * Generic routine to convert a login name to a full name (gecos)
1118 * Returns nonzero if a conversion took place
1120 int convert_login(char NameToConvert[]) {
1124 pw = getpwnam(NameToConvert);
1129 strcpy(NameToConvert, pw->pw_gecos);
1130 for (a=0; a<strlen(NameToConvert); ++a) {
1131 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1139 void HuntBadSession(void)
1145 struct ServiceFunctionHook *serviceptr;
1149 /* Next, add all of the client sockets. */
1150 begin_critical_section(S_SESSION_TABLE);
1151 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1152 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1154 /* Initialize the fdset. */
1157 tv.tv_sec = 0; /* wake up every second if no input */
1160 /* Don't select on dead sessions, only truly idle ones */
1161 if ( (ptr->state == CON_IDLE)
1162 && (ptr->kill_me == 0)
1163 && (ptr->client_socket > 0)
1165 FD_SET(ptr->client_socket, &readfds);
1166 if (ptr->client_socket > highest)
1167 highest = ptr->client_socket;
1169 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1174 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1177 ptr->is_local_socket,
1179 ptr->cs_host,ptr->cs_addr);
1182 ptr->client_socket = -1;
1188 end_critical_section(S_SESSION_TABLE);
1191 /* First, add the various master sockets to the fdset. */
1192 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1194 /* Initialize the fdset. */
1196 tv.tv_sec = 0; /* wake up every second if no input */
1199 FD_SET(serviceptr->msock, &readfds);
1200 if (serviceptr->msock > highest) {
1201 highest = serviceptr->msock;
1203 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1206 /* Gotcha! server socket dead? commit suicide! */
1208 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1211 server_shutting_down = 1;
1219 const char *WorkerLogStr = "W";
1221 * This loop just keeps going and going and going...
1223 void *worker_thread(void *blah) {
1226 CitContext *bind_me = NULL;
1230 int force_purge = 0;
1231 struct ServiceFunctionHook *serviceptr;
1232 int ssock; /* Descriptor for client socket */
1233 CitContext *con = NULL; /* Temporary context pointer */
1236 pthread_mutex_lock(&ThreadCountMutex);
1238 pthread_mutex_unlock(&ThreadCountMutex);
1240 pthread_setspecific(evConKey, WorkerLogStr);
1242 while (!server_shutting_down) {
1244 /* make doubly sure we're not holding any stale db handles
1245 * which might cause a deadlock.
1247 cdb_check_handles();
1248 do_select: force_purge = 0;
1249 bind_me = NULL; /* Which session shall we handle? */
1251 /* Initialize the fdset. */
1255 /* First, add the various master sockets to the fdset. */
1256 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1257 FD_SET(serviceptr->msock, &readfds);
1258 if (serviceptr->msock > highest) {
1259 highest = serviceptr->msock;
1263 /* Next, add all of the client sockets. */
1264 begin_critical_section(S_SESSION_TABLE);
1265 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1266 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1269 /* Don't select on dead sessions, only truly idle ones */
1270 if ( (ptr->state == CON_IDLE)
1271 && (ptr->kill_me == 0)
1272 && (ptr->client_socket > 0)
1274 FD_SET(ptr->client_socket, &readfds);
1275 if (ptr->client_socket > highest)
1276 highest = ptr->client_socket;
1278 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1280 ptr->state = CON_EXECUTING;
1283 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1285 ptr->state = CON_STARTING;
1289 end_critical_section(S_SESSION_TABLE);
1295 /* If we got this far, it means that there are no sessions
1296 * which a previous thread marked for attention, so we go
1297 * ahead and get ready to select().
1300 if (!server_shutting_down) {
1301 tv.tv_sec = 1; /* wake up every second if no input */
1303 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1310 /* Now figure out who made this select() unblock.
1311 * First, check for an error or exit condition.
1314 if (errno == EBADF) {
1315 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1319 if (errno != EINTR) {
1320 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1321 server_shutting_down = 1;
1325 syslog(LOG_DEBUG, "Interrupted select()\n");
1327 if (server_shutting_down) {
1334 else if (retval == 0) {
1335 if (server_shutting_down) {
1341 /* Next, check to see if it's a new client connecting * on a master socket. */
1343 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1345 if (FD_ISSET(serviceptr->msock, &readfds)) {
1346 ssock = accept(serviceptr->msock, NULL, 0);
1348 syslog(LOG_DEBUG, "New client socket %d", ssock);
1350 /* The master socket is non-blocking but the client
1351 * sockets need to be blocking, otherwise certain
1352 * operations barf on FreeBSD. Not a fatal error.
1354 if (fcntl(ssock, F_SETFL, 0) < 0) {
1355 syslog(LOG_EMERG, "citserver: Can't set socket to blocking: %s", strerror(errno));
1358 /* New context will be created already
1359 * set up in the CON_EXECUTING state.
1361 con = CreateNewContext();
1363 /* Assign our new socket number to it. */
1364 con->tcp_port = serviceptr->tcp_port;
1365 con->client_socket = ssock;
1366 con->h_command_function = serviceptr->h_command_function;
1367 con->h_async_function = serviceptr->h_async_function;
1368 con->h_greeting_function = serviceptr->h_greeting_function;
1369 con->ServiceName = serviceptr->ServiceName;
1371 /* Determine whether it's a local socket */
1372 if (serviceptr->sockpath != NULL) {
1373 con->is_local_socket = 1;
1376 /* Set the SO_REUSEADDR socket option */
1378 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1379 con->state = CON_GREETING;
1387 /* It must be a client socket. Find a context that has data
1388 * waiting on its socket *and* is in the CON_IDLE state. Any
1389 * active sockets other than our chosen one are marked as
1390 * CON_READY so the next thread that comes around can just bind
1391 * to one without having to select() again.
1393 begin_critical_section(S_SESSION_TABLE);
1394 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1395 int checkfd = ptr->client_socket;
1396 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1397 if (FD_ISSET(checkfd, &readfds)) {
1398 ptr->input_waiting = 1;
1400 bind_me = ptr; /* I choose you! */
1401 bind_me->state = CON_EXECUTING;
1404 ptr->state = CON_READY;
1406 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1408 bind_me = ptr; /* I choose you! */
1409 bind_me->state = CON_EXECUTING;
1412 ptr->state = CON_READY;
1417 end_critical_section(S_SESSION_TABLE);
1420 /* We're bound to a session */
1421 pthread_mutex_lock(&ThreadCountMutex);
1423 pthread_mutex_unlock(&ThreadCountMutex);
1425 if (bind_me != NULL) {
1426 become_session(bind_me);
1428 if (bind_me->state == CON_STARTING) {
1429 bind_me->state = CON_EXECUTING;
1430 begin_session(bind_me);
1431 bind_me->h_greeting_function();
1433 /* If the client has sent a command, execute it. */
1434 if (CC->input_waiting) {
1435 CC->h_command_function();
1437 while (HaveMoreLinesWaiting(CC))
1438 CC->h_command_function();
1440 CC->input_waiting = 0;
1443 /* If there are asynchronous messages waiting and the
1444 * client supports it, do those now */
1445 if ((CC->is_async) && (CC->async_waiting)
1446 && (CC->h_async_function != NULL)) {
1447 CC->h_async_function();
1448 CC->async_waiting = 0;
1451 force_purge = CC->kill_me;
1452 become_session(NULL);
1453 bind_me->state = CON_IDLE;
1456 dead_session_purge(force_purge);
1459 pthread_mutex_lock(&ThreadCountMutex);
1461 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1462 (num_workers > CtdlGetConfigInt("c_min_workers")))
1465 pthread_mutex_unlock(&ThreadCountMutex);
1468 pthread_mutex_unlock(&ThreadCountMutex);
1471 /* If control reaches this point, the server is shutting down */
1472 pthread_mutex_lock(&ThreadCountMutex);
1474 pthread_mutex_unlock(&ThreadCountMutex);
1482 * Translate text facility name to syslog.h defined value.
1484 int SyslogFacility(char *name)
1493 { LOG_KERN, "kern" },
1494 { LOG_USER, "user" },
1495 { LOG_MAIL, "mail" },
1496 { LOG_DAEMON, "daemon" },
1497 { LOG_AUTH, "auth" },
1498 { LOG_SYSLOG, "syslog" },
1500 { LOG_NEWS, "news" },
1501 { LOG_UUCP, "uucp" },
1502 { LOG_LOCAL0, "local0" },
1503 { LOG_LOCAL1, "local1" },
1504 { LOG_LOCAL2, "local2" },
1505 { LOG_LOCAL3, "local3" },
1506 { LOG_LOCAL4, "local4" },
1507 { LOG_LOCAL5, "local5" },
1508 { LOG_LOCAL6, "local6" },
1509 { LOG_LOCAL7, "local7" },
1512 for(i = 0; facTbl[i].name != NULL; i++) {
1513 if(!strcasecmp(name, facTbl[i].name))
1514 return facTbl[i].facility;