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);
381 fprintf(fd, "Sending: BufSize: %d BufContent: [", nbytes);
382 rv = fwrite(buf, nbytes, 1, fd);
387 // flush_client_inbuf();
388 if (Ctx->redirect_buffer != NULL) {
389 StrBufAppendBufPlain(Ctx->redirect_buffer,
395 if (Ctx->redirect_ssl) {
396 client_write_ssl(buf, nbytes);
400 if (Ctx->client_socket == -1) return -1;
402 fdflags = fcntl(Ctx->client_socket, F_GETFL);
404 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
405 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
407 FD_SET(Ctx->client_socket, &wset);
408 if (select(1, NULL, &wset, NULL, NULL) == -1) {
411 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
412 if (server_shutting_down) {
413 CC->kill_me = KILLME_SELECT_INTERRUPTED;
416 /* can't trust fd's and stuff so we need to re-create them */
420 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
422 Ctx->kill_me = KILLME_SELECT_FAILED;
428 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
430 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
432 Ctx->kill_me = KILLME_WRITE_FAILED;
435 bytes_written = bytes_written + retval;
440 void cputbuf(const StrBuf *Buf) {
441 client_write(ChrPtr(Buf), StrLength(Buf));
446 * cprintf() Send formatted printable data to the client.
447 * Implemented in terms of client_write() so it's technically not sysdep...
449 void cprintf(const char *format, ...) {
453 va_start(arg_ptr, format);
454 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
455 buf[sizeof buf - 2] = '\n';
456 client_write(buf, strlen(buf));
462 * Read data from the client socket.
464 * sock socket fd to read from
465 * buf buffer to read into
466 * bytes number of bytes to read
467 * timeout Number of seconds to wait before timing out
469 * Possible return values:
470 * 1 Requested number of bytes has been read.
471 * 0 Request timed out.
472 * -1 Connection is broken, or other error.
474 int client_read_blob(StrBuf *Target, int bytes, int timeout)
481 if (CCC->redirect_ssl) {
487 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
489 fd = fopen(fn, "a+");
491 syslog(LOG_ERR, "%s: %m", fn);
494 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
495 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
501 retval = client_read_sslblob(Target, bytes, timeout);
503 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
506 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
508 fd = fopen(fn, "a+");
510 syslog(LOG_ERR, "%s: %m", fn);
513 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
514 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
527 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
529 fd = fopen(fn, "a+");
531 syslog(LOG_ERR, "%s: %m", fn);
534 fprintf(fd, "Reading BLOB: BufSize: %d ",
536 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
540 retval = StrBufReadBLOBBuffered(Target,
542 &CCC->RecvBuf.ReadWritePointer,
550 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
555 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
557 fd = fopen(fn, "a+");
559 syslog(LOG_ERR, "%s: %m", fn);
562 fprintf(fd, "Read: %d BufContent: [",
564 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
574 * to make client_read_random_blob() more efficient, increase buffer size.
575 * just use in greeting function, else your buffer may be flushed
577 void client_set_inbound_buf(long N)
580 FlushStrBuf(CCC->RecvBuf.Buf);
581 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
584 int client_read_random_blob(StrBuf *Target, int timeout)
589 rc = client_read_blob(Target, 1, timeout);
595 len = StrLength(CCC->RecvBuf.Buf);
596 pch = ChrPtr(CCC->RecvBuf.Buf);
600 if (CCC->RecvBuf.ReadWritePointer != NULL) {
601 len -= CCC->RecvBuf.ReadWritePointer - pch;
602 pch = CCC->RecvBuf.ReadWritePointer;
604 StrBufAppendBufPlain(Target, pch, len, 0);
605 FlushStrBuf(CCC->RecvBuf.Buf);
606 CCC->RecvBuf.ReadWritePointer = NULL;
613 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
615 fd = fopen(fn, "a+");
617 syslog(LOG_ERR, "%s: %m", fn);
620 fprintf(fd, "Read: BufSize: %d BufContent: [",
622 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
627 return StrLength(Target);
635 int client_read_to(char *buf, int bytes, int timeout)
640 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
649 ChrPtr(CCC->MigrateBuf),
650 StrLength(CCC->MigrateBuf) + 1);
651 FlushStrBuf(CCC->MigrateBuf);
657 int HaveMoreLinesWaiting(CitContext *CCC)
659 if ((CCC->kill_me != 0) ||
660 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
661 (StrLength(CCC->RecvBuf.Buf) == 0) &&
662 (CCC->client_socket != -1)) )
670 * Read data from the client socket with default timeout.
671 * (This is implemented in terms of client_read_to() and could be
672 * justifiably moved out of sysdep.c)
674 INLINE int client_read(char *buf, int bytes)
676 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
679 int CtdlClientGetLine(StrBuf *Target)
687 if (CCC->redirect_ssl) {
697 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
699 fd = fopen(fn, "a+");
701 syslog(LOG_ERR, "%s: %m", fn);
704 pch = ChrPtr(CCC->RecvBuf.Buf);
705 len = StrLength(CCC->RecvBuf.Buf);
706 if (CCC->RecvBuf.ReadWritePointer != NULL)
707 rlen = CCC->RecvBuf.ReadWritePointer - pch;
711 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
714 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
717 rc = client_readline_sslbuffer(Target,
719 &CCC->RecvBuf.ReadWritePointer,
722 pch = ChrPtr(CCC->RecvBuf.Buf);
723 nlen = StrLength(CCC->RecvBuf.Buf);
724 if (CCC->RecvBuf.ReadWritePointer != NULL)
725 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
729 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
730 len, nlen, rlen, nrlen, pch);
732 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
733 len, nlen, rlen, nrlen);
735 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
736 StrLength(Target), ChrPtr(Target));
740 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed");
751 int len, rlen, nlen, nrlen;
754 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
756 fd = fopen(fn, "a+");
758 syslog(LOG_ERR, "%s: %m", fn);
761 pch = ChrPtr(CCC->RecvBuf.Buf);
762 len = StrLength(CCC->RecvBuf.Buf);
763 if (CCC->RecvBuf.ReadWritePointer != NULL)
764 rlen = CCC->RecvBuf.ReadWritePointer - pch;
768 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
771 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
774 rc = StrBufTCP_read_buffered_line_fast(Target,
776 &CCC->RecvBuf.ReadWritePointer,
784 pch = ChrPtr(CCC->RecvBuf.Buf);
785 nlen = StrLength(CCC->RecvBuf.Buf);
786 if (CCC->RecvBuf.ReadWritePointer != NULL)
787 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
791 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
792 len, nlen, rlen, nrlen, pch);
794 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
795 len, nlen, rlen, nrlen);
797 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
798 StrLength(Target), ChrPtr(Target));
801 if ((rc < 0) && (Error != NULL)) {
802 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed: %s", Error);
811 * client_getln() ... Get a LF-terminated line of text from the client.
812 * (This is implemented in terms of client_read() and could be
813 * justifiably moved out of sysdep.c)
815 int client_getln(char *buf, int bufsize)
821 retval = CtdlClientGetLine(CCC->MigrateBuf);
826 i = StrLength(CCC->MigrateBuf);
827 pCh = ChrPtr(CCC->MigrateBuf);
828 /* Strip the trailing LF, and the trailing CR if present.
833 && ( (pCh[i - 1]==13)
834 || ( pCh[i - 1]==10)) ) {
840 FlushStrBuf(CCC->MigrateBuf);
842 safestrncpy(&buf[i], "000", bufsize - i);
849 * Cleanup any contexts that are left lying around
853 void close_masters (void)
855 struct ServiceFunctionHook *serviceptr;
859 * close all protocol master sockets
861 for (serviceptr = ServiceHookTable; serviceptr != NULL;
862 serviceptr = serviceptr->next ) {
864 if (serviceptr->tcp_port > 0)
866 if (serviceptr->msock == -1) {
867 Text = "not closing again";
872 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
877 serviceptr->tcp_port = 0;
880 if (serviceptr->sockpath != NULL)
882 if (serviceptr->msock == -1) {
883 Text = "not closing again";
888 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
895 if (serviceptr->msock != -1)
897 close(serviceptr->msock);
898 serviceptr->msock = -1;
901 /* If it's a Unix domain socket, remove the file. */
902 if (serviceptr->sockpath != NULL) {
903 unlink(serviceptr->sockpath);
904 serviceptr->sockpath = NULL;
911 * The system-dependent part of master_cleanup() - close the master socket.
913 void sysdep_master_cleanup(void) {
922 CtdlDestroyProtoHooks();
923 CtdlDestroyDeleteHooks();
924 CtdlDestroyXmsgHooks();
925 CtdlDestroyUserHooks();
926 CtdlDestroyMessageHook();
927 CtdlDestroyCleanupHooks();
928 CtdlDestroyFixedOutputHooks();
929 CtdlDestroySessionHooks();
930 CtdlDestroyServiceHook();
931 CtdlDestroyRoomHooks();
932 CtdlDestroySearchHooks();
938 void graceful_shutdown(int signum) {
939 kill(current_child, signum);
940 unlink(file_pid_file);
945 int nFireUpsNonRestart = 0;
949 * Start running as a daemon.
951 void start_daemon(int unused) {
959 /* Close stdin/stdout/stderr and replace them with /dev/null.
960 * We don't just call close() because we don't want these fd's
961 * to be reused for other files.
963 if (chdir(ctdl_run_dir) != 0) {
964 syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
972 signal(SIGHUP, SIG_IGN);
973 signal(SIGINT, SIG_IGN);
974 signal(SIGQUIT, SIG_IGN);
978 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
979 (freopen("/dev/null", "w", stdout) != stdout) ||
980 (freopen("/dev/null", "w", stderr) != stderr)
982 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
986 current_child = fork();
987 signal(SIGTERM, graceful_shutdown);
988 if (current_child < 0) {
992 else if (current_child == 0) {
993 return; /* continue starting citadel. */
996 fp = fopen(file_pid_file, "w");
998 fprintf(fp, ""F_PID_T"\n", getpid());
1001 waitpid(current_child, &status, 0);
1003 nFireUpsNonRestart = nFireUps;
1005 /* Exit code 0 means the watcher should exit */
1006 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1010 /* Exit code 101-109 means the watcher should exit */
1011 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1015 /* Any other exit code, or no exit code, means we should restart. */
1019 ForkedPid = current_child;
1022 } while (do_restart);
1024 unlink(file_pid_file);
1025 exit(WEXITSTATUS(status));
1030 void checkcrash(void)
1032 if (nFireUpsNonRestart != nFireUps)
1035 CrashMail = NewStrBuf();
1036 syslog(LOG_ALERT, "sysdep: posting crash message");
1037 StrBufPrintf(CrashMail,
1039 " The Citadel server process (citserver) terminated unexpectedly."
1041 " This could be the result of a bug in the server program, or some external "
1043 " You can obtain more information about this by enabling core dumps.\n \n"
1044 " For more information, please see:\n \n"
1045 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1048 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1050 ctdl_run_dir, ForkedPid);
1051 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1052 FreeStrBuf(&CrashMail);
1058 * Generic routine to convert a login name to a full name (gecos)
1059 * Returns nonzero if a conversion took place
1061 int convert_login(char NameToConvert[]) {
1065 pw = getpwnam(NameToConvert);
1070 strcpy(NameToConvert, pw->pw_gecos);
1071 for (a=0; a<strlen(NameToConvert); ++a) {
1072 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1080 void HuntBadSession(void)
1086 struct ServiceFunctionHook *serviceptr;
1088 /* Next, add all of the client sockets. */
1089 begin_critical_section(S_SESSION_TABLE);
1090 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1091 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1093 /* Initialize the fdset. */
1096 tv.tv_sec = 0; /* wake up every second if no input */
1099 /* Don't select on dead sessions, only truly idle ones */
1100 if ( (ptr->state == CON_IDLE)
1101 && (ptr->kill_me == 0)
1102 && (ptr->client_socket > 0)
1104 FD_SET(ptr->client_socket, &readfds);
1105 if (ptr->client_socket > highest)
1106 highest = ptr->client_socket;
1108 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
1112 "sysdep: killing session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]",
1115 ptr->is_local_socket,
1117 ptr->cs_host,ptr->cs_addr
1120 ptr->client_socket = -1;
1125 end_critical_section(S_SESSION_TABLE);
1127 /* First, add the various master sockets to the fdset. */
1128 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1130 /* Initialize the fdset. */
1132 tv.tv_sec = 0; /* wake up every second if no input */
1135 FD_SET(serviceptr->msock, &readfds);
1136 if (serviceptr->msock > highest) {
1137 highest = serviceptr->msock;
1139 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1142 /* Gotcha! server socket dead? commit suicide! */
1143 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
1144 server_shutting_down = 1;
1152 * This loop just keeps going and going and going...
1154 void *worker_thread(void *blah) {
1157 CitContext *bind_me = NULL;
1161 int force_purge = 0;
1162 struct ServiceFunctionHook *serviceptr;
1163 int ssock; /* Descriptor for client socket */
1164 CitContext *con = NULL; /* Temporary context pointer */
1167 pthread_mutex_lock(&ThreadCountMutex);
1169 pthread_mutex_unlock(&ThreadCountMutex);
1171 while (!server_shutting_down) {
1173 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
1174 cdb_check_handles();
1175 do_select: force_purge = 0;
1176 bind_me = NULL; /* Which session shall we handle? */
1178 /* Initialize the fdset. */
1182 /* First, add the various master sockets to the fdset. */
1183 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1184 FD_SET(serviceptr->msock, &readfds);
1185 if (serviceptr->msock > highest) {
1186 highest = serviceptr->msock;
1190 /* Next, add all of the client sockets. */
1191 begin_critical_section(S_SESSION_TABLE);
1192 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1193 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1196 /* Don't select on dead sessions, only truly idle ones */
1197 if ( (ptr->state == CON_IDLE)
1198 && (ptr->kill_me == 0)
1199 && (ptr->client_socket > 0)
1201 FD_SET(ptr->client_socket, &readfds);
1202 if (ptr->client_socket > highest)
1203 highest = ptr->client_socket;
1205 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1207 ptr->state = CON_EXECUTING;
1210 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1212 ptr->state = CON_STARTING;
1216 end_critical_section(S_SESSION_TABLE);
1222 /* If we got this far, it means that there are no sessions
1223 * which a previous thread marked for attention, so we go
1224 * ahead and get ready to select().
1227 if (!server_shutting_down) {
1228 tv.tv_sec = 1; /* wake up every second if no input */
1230 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1237 /* Now figure out who made this select() unblock.
1238 * First, check for an error or exit condition.
1241 if (errno == EBADF) {
1242 syslog(LOG_ERR, "sysdep: select() failed: %m");
1246 if (errno != EINTR) {
1247 syslog(LOG_ERR, "sysdep: exiting: %m");
1248 server_shutting_down = 1;
1251 if (server_shutting_down) {
1258 else if (retval == 0) {
1259 if (server_shutting_down) {
1265 /* Next, check to see if it's a new client connecting on a master socket. */
1267 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1269 if (FD_ISSET(serviceptr->msock, &readfds)) {
1270 ssock = accept(serviceptr->msock, NULL, 0);
1272 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1274 /* The master socket is non-blocking but the client
1275 * sockets need to be blocking, otherwise certain
1276 * operations barf on FreeBSD. Not a fatal error.
1278 if (fcntl(ssock, F_SETFL, 0) < 0) {
1279 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1282 /* New context will be created already
1283 * set up in the CON_EXECUTING state.
1285 con = CreateNewContext();
1287 /* Assign our new socket number to it. */
1288 con->tcp_port = serviceptr->tcp_port;
1289 con->client_socket = ssock;
1290 con->h_command_function = serviceptr->h_command_function;
1291 con->h_async_function = serviceptr->h_async_function;
1292 con->h_greeting_function = serviceptr->h_greeting_function;
1293 con->ServiceName = serviceptr->ServiceName;
1295 /* Determine whether it's a local socket */
1296 if (serviceptr->sockpath != NULL) {
1297 con->is_local_socket = 1;
1300 /* Set the SO_REUSEADDR socket option */
1302 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1303 con->state = CON_GREETING;
1311 /* It must be a client socket. Find a context that has data
1312 * waiting on its socket *and* is in the CON_IDLE state. Any
1313 * active sockets other than our chosen one are marked as
1314 * CON_READY so the next thread that comes around can just bind
1315 * to one without having to select() again.
1317 begin_critical_section(S_SESSION_TABLE);
1318 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1319 int checkfd = ptr->client_socket;
1320 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1321 if (FD_ISSET(checkfd, &readfds)) {
1322 ptr->input_waiting = 1;
1324 bind_me = ptr; /* I choose you! */
1325 bind_me->state = CON_EXECUTING;
1328 ptr->state = CON_READY;
1330 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1332 bind_me = ptr; /* I choose you! */
1333 bind_me->state = CON_EXECUTING;
1336 ptr->state = CON_READY;
1341 end_critical_section(S_SESSION_TABLE);
1344 /* We're bound to a session */
1345 pthread_mutex_lock(&ThreadCountMutex);
1347 pthread_mutex_unlock(&ThreadCountMutex);
1349 if (bind_me != NULL) {
1350 become_session(bind_me);
1352 if (bind_me->state == CON_STARTING) {
1353 bind_me->state = CON_EXECUTING;
1354 begin_session(bind_me);
1355 bind_me->h_greeting_function();
1357 /* If the client has sent a command, execute it. */
1358 if (CC->input_waiting) {
1359 CC->h_command_function();
1361 while (HaveMoreLinesWaiting(CC))
1362 CC->h_command_function();
1364 CC->input_waiting = 0;
1367 /* If there are asynchronous messages waiting and the client supports it, do those now */
1368 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1369 CC->h_async_function();
1370 CC->async_waiting = 0;
1373 force_purge = CC->kill_me;
1374 become_session(NULL);
1375 bind_me->state = CON_IDLE;
1378 dead_session_purge(force_purge);
1381 pthread_mutex_lock(&ThreadCountMutex);
1383 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1384 (num_workers > CtdlGetConfigInt("c_min_workers")))
1387 pthread_mutex_unlock(&ThreadCountMutex);
1390 pthread_mutex_unlock(&ThreadCountMutex);
1393 /* If control reaches this point, the server is shutting down */
1394 pthread_mutex_lock(&ThreadCountMutex);
1396 pthread_mutex_unlock(&ThreadCountMutex);
1403 * Translate text facility name to syslog.h defined value.
1405 int SyslogFacility(char *name)
1414 { LOG_KERN, "kern" },
1415 { LOG_USER, "user" },
1416 { LOG_MAIL, "mail" },
1417 { LOG_DAEMON, "daemon" },
1418 { LOG_AUTH, "auth" },
1419 { LOG_SYSLOG, "syslog" },
1421 { LOG_NEWS, "news" },
1422 { LOG_UUCP, "uucp" },
1423 { LOG_LOCAL0, "local0" },
1424 { LOG_LOCAL1, "local1" },
1425 { LOG_LOCAL2, "local2" },
1426 { LOG_LOCAL3, "local3" },
1427 { LOG_LOCAL4, "local4" },
1428 { LOG_LOCAL5, "local5" },
1429 { LOG_LOCAL6, "local6" },
1430 { LOG_LOCAL7, "local7" },
1433 for(i = 0; facTbl[i].name != NULL; i++) {
1434 if(!strcasecmp(name, facTbl[i].name))
1435 return facTbl[i].facility;