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"
45 * Signal handler to shut down the server.
48 volatile int exit_signal = 0;
49 volatile int shutdown_and_halt = 0;
50 volatile int restart_server = 0;
51 volatile int running_as_daemon = 0;
53 static RETSIGTYPE signal_cleanup(int signum) {
54 syslog(LOG_DEBUG, "sysdep: caught signal %d; shutting down.", signum);
56 server_shutting_down = 1;
59 static RETSIGTYPE signal_exit(int signum) {
66 * Some initialization stuff...
68 void init_sysdep(void) {
71 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
75 getrlimit(RLIMIT_NOFILE, &rl);
76 rl.rlim_cur = FD_SETSIZE;
77 rl.rlim_max = FD_SETSIZE;
78 setrlimit(RLIMIT_NOFILE, &rl);
82 /* If we've got OpenSSL, we're going to use it. */
88 * Set up a place to put thread-specific data.
89 * We only need a single pointer per thread - it points to the
90 * CitContext structure (in the ContextList linked list) of the
91 * session to which the calling thread is currently bound.
93 if (pthread_key_create(&MyConKey, NULL) != 0) {
94 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
98 * Interript, hangup, and terminate signals should cause the server
99 * to gracefully clean up and shut down.
102 sigaddset(&set, SIGINT);
103 sigaddset(&set, SIGHUP);
104 sigaddset(&set, SIGTERM);
105 sigprocmask(SIG_UNBLOCK, &set, NULL);
107 signal(SIGINT, signal_cleanup);
108 signal(SIGHUP, signal_cleanup);
109 signal(SIGTERM, signal_cleanup);
110 signal(SIGUSR2, signal_exit);
113 * Do not shut down the server on broken pipe signals, otherwise the
114 * whole Citadel service would come down whenever a single client
117 signal(SIGPIPE, SIG_IGN);
122 * This is a generic function to set up a master socket for listening on
123 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
125 * ip_addr IP address to bind
126 * port_number port number to bind
127 * queue_len number of incoming connections to allow in the queue
129 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
132 struct sockaddr_in6 sin6;
133 struct sockaddr_in sin4;
137 memset(&sin6, 0, sizeof(sin6));
138 memset(&sin4, 0, sizeof(sin4));
139 sin6.sin6_family = AF_INET6;
140 sin4.sin_family = AF_INET;
142 if ( (ip_addr == NULL) /* any IPv6 */
143 || (IsEmptyStr(ip_addr))
144 || (!strcmp(ip_addr, "*"))
147 sin6.sin6_addr = in6addr_any;
149 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
152 sin4.sin_addr.s_addr = INADDR_ANY;
154 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
157 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
158 snprintf(errormessage, SIZ, "Error binding to [%s] : %s", ip_addr, strerror(errno));
159 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
163 else /* specific IPv6 */
166 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
167 snprintf(errormessage, SIZ, "Error binding to [%s] : %s", ip_addr, strerror(errno));
168 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
173 if (port_number == 0) {
174 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
175 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
178 sin6.sin6_port = htons((u_short) port_number);
179 sin4.sin_port = htons((u_short) port_number);
181 p = getprotobyname("tcp");
183 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
185 snprintf(errormessage, SIZ, "Can't create a listening socket: %s", strerror(errno));
186 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
189 /* Set some socket options that make sense. */
191 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
193 if (ip_version == 6) {
194 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
197 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
201 snprintf(errormessage, SIZ, "Can't bind: %s", strerror(errno));
202 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
206 fcntl(s, F_SETFL, O_NONBLOCK);
208 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
209 snprintf(errormessage, SIZ, "Can't listen: %s", strerror(errno));
210 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
218 * Create a Unix domain socket and listen on it
220 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
222 struct sockaddr_un addr;
225 int actual_queue_len;
226 #ifdef HAVE_STRUCT_UCRED
230 actual_queue_len = queue_len;
231 if (actual_queue_len < 5) actual_queue_len = 5;
233 i = unlink(sockpath);
234 if ((i != 0) && (errno != ENOENT)) {
235 snprintf(errormessage, SIZ, "can't unlink %s: %s", sockpath, strerror(errno));
236 syslog(LOG_ERR, "udsserver: %s", errormessage);
240 memset(&addr, 0, sizeof(addr));
241 addr.sun_family = AF_UNIX;
242 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
244 s = socket(AF_UNIX, SOCK_STREAM, 0);
246 snprintf(errormessage, SIZ, "can't create a socket: %s", strerror(errno));
247 syslog(LOG_ERR, "udsserver: %s", errormessage);
251 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
252 snprintf(errormessage, SIZ, "can't bind: %s", strerror(errno));
253 syslog(LOG_ERR, "udsserver: %s", errormessage);
257 /* set to nonblock - we need this for some obscure situations */
258 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
259 snprintf(errormessage, SIZ, "can't set socket to non-blocking: %s", strerror(errno));
260 syslog(LOG_ERR, "udsserver: %s", errormessage);
265 if (listen(s, actual_queue_len) < 0) {
266 snprintf(errormessage, SIZ, "can't listen: %s", strerror(errno));
267 syslog(LOG_ERR, "udsserver: %s", errormessage);
271 #ifdef HAVE_STRUCT_UCRED
272 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
275 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
281 * The following functions implement output buffering on operating systems which
282 * support it (such as Linux and various BSD flavors).
286 # define HAVE_TCP_BUFFERING
289 # define HAVE_TCP_BUFFERING
290 # define TCP_CORK TCP_NOPUSH
292 #endif /* TCP_CORK */
293 #endif /* HAVE_DARWIN */
295 static unsigned on = 1, off = 0;
297 void buffer_output(void) {
298 #ifdef HAVE_TCP_BUFFERING
300 if (!CC->redirect_ssl)
302 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
306 void unbuffer_output(void) {
307 #ifdef HAVE_TCP_BUFFERING
309 if (!CC->redirect_ssl)
311 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
315 void flush_output(void) {
316 #ifdef HAVE_TCP_BUFFERING
317 struct CitContext *CCC = CC;
318 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
319 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
324 static void flush_client_inbuf(void)
328 FlushStrBuf(CCC->ReadBuf);
329 CCC->RecvBuf->ReadWritePointer = NULL;
336 * client_close() ... close the client socket
338 void client_close(void) {
339 CitContext *CCC = CC;
342 if (CCC->client_socket <= 0) return;
343 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
344 close(CCC->client_socket);
345 CCC->client_socket = -1 ;
350 * client_write() ... Send binary data to the client.
352 int client_write(const char *buf, int nbytes)
354 int bytes_written = 0;
356 #ifndef HAVE_TCP_BUFFERING
357 int old_buffer_len = 0;
363 if (nbytes < 1) return(0);
373 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
375 fd = fopen(fn, "a+");
377 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);
423 Ctx->kill_me = KILLME_SELECT_FAILED;
429 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
431 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
434 Ctx->kill_me = KILLME_WRITE_FAILED;
437 bytes_written = bytes_written + retval;
442 void cputbuf(const StrBuf *Buf) {
443 client_write(ChrPtr(Buf), StrLength(Buf));
448 * cprintf() Send formatted printable data to the client.
449 * Implemented in terms of client_write() so it's technically not sysdep...
451 void cprintf(const char *format, ...) {
455 va_start(arg_ptr, format);
456 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
457 buf[sizeof buf - 2] = '\n';
458 client_write(buf, strlen(buf));
464 * Read data from the client socket.
466 * sock socket fd to read from
467 * buf buffer to read into
468 * bytes number of bytes to read
469 * timeout Number of seconds to wait before timing out
471 * Possible return values:
472 * 1 Requested number of bytes has been read.
473 * 0 Request timed out.
474 * -1 Connection is broken, or other error.
476 int client_read_blob(StrBuf *Target, int bytes, int timeout)
483 if (CCC->redirect_ssl) {
489 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
491 fd = fopen(fn, "a+");
493 syslog(LOG_ERR, "%s: %m", fn);
497 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
498 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
504 retval = client_read_sslblob(Target, bytes, timeout);
506 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
509 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
511 fd = fopen(fn, "a+");
513 syslog(LOG_ERR, "%s: %m", fn);
517 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
518 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
531 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
533 fd = fopen(fn, "a+");
535 syslog(LOG_ERR, "%s: %m", fn);
539 fprintf(fd, "Reading BLOB: BufSize: %d ",
541 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
545 retval = StrBufReadBLOBBuffered(Target,
547 &CCC->RecvBuf.ReadWritePointer,
555 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
560 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
562 fd = fopen(fn, "a+");
564 syslog(LOG_ERR, "%s: %m", fn);
568 fprintf(fd, "Read: %d BufContent: [",
570 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
580 * to make client_read_random_blob() more efficient, increase buffer size.
581 * just use in greeting function, else your buffer may be flushed
583 void client_set_inbound_buf(long N)
586 FlushStrBuf(CCC->RecvBuf.Buf);
587 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
590 int client_read_random_blob(StrBuf *Target, int timeout)
595 rc = client_read_blob(Target, 1, timeout);
601 len = StrLength(CCC->RecvBuf.Buf);
602 pch = ChrPtr(CCC->RecvBuf.Buf);
606 if (CCC->RecvBuf.ReadWritePointer != NULL) {
607 len -= CCC->RecvBuf.ReadWritePointer - pch;
608 pch = CCC->RecvBuf.ReadWritePointer;
610 StrBufAppendBufPlain(Target, pch, len, 0);
611 FlushStrBuf(CCC->RecvBuf.Buf);
612 CCC->RecvBuf.ReadWritePointer = NULL;
619 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
621 fd = fopen(fn, "a+");
623 syslog(LOG_ERR, "%s: %m", fn);
627 fprintf(fd, "Read: BufSize: %d BufContent: [",
629 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
634 return StrLength(Target);
642 int client_read_to(char *buf, int bytes, int timeout)
647 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
656 ChrPtr(CCC->MigrateBuf),
657 StrLength(CCC->MigrateBuf) + 1);
658 FlushStrBuf(CCC->MigrateBuf);
664 int HaveMoreLinesWaiting(CitContext *CCC)
666 if ((CCC->kill_me != 0) ||
667 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
668 (StrLength(CCC->RecvBuf.Buf) == 0) &&
669 (CCC->client_socket != -1)) )
677 * Read data from the client socket with default timeout.
678 * (This is implemented in terms of client_read_to() and could be
679 * justifiably moved out of sysdep.c)
681 INLINE int client_read(char *buf, int bytes)
683 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
686 int CtdlClientGetLine(StrBuf *Target)
694 if (CCC->redirect_ssl) {
704 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
706 fd = fopen(fn, "a+");
708 syslog(LOG_ERR, "%s: %m", fn);
712 pch = ChrPtr(CCC->RecvBuf.Buf);
713 len = StrLength(CCC->RecvBuf.Buf);
714 if (CCC->RecvBuf.ReadWritePointer != NULL)
715 rlen = CCC->RecvBuf.ReadWritePointer - pch;
719 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
722 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
725 rc = client_readline_sslbuffer(Target,
727 &CCC->RecvBuf.ReadWritePointer,
730 pch = ChrPtr(CCC->RecvBuf.Buf);
731 nlen = StrLength(CCC->RecvBuf.Buf);
732 if (CCC->RecvBuf.ReadWritePointer != NULL)
733 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
737 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
738 len, nlen, rlen, nrlen, pch);
740 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
741 len, nlen, rlen, nrlen);
743 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
744 StrLength(Target), ChrPtr(Target));
748 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed");
759 int len, rlen, nlen, nrlen;
762 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
764 fd = fopen(fn, "a+");
766 syslog(LOG_ERR, "%s: %m", fn);
770 pch = ChrPtr(CCC->RecvBuf.Buf);
771 len = StrLength(CCC->RecvBuf.Buf);
772 if (CCC->RecvBuf.ReadWritePointer != NULL)
773 rlen = CCC->RecvBuf.ReadWritePointer - pch;
777 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
780 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
783 rc = StrBufTCP_read_buffered_line_fast(Target,
785 &CCC->RecvBuf.ReadWritePointer,
793 pch = ChrPtr(CCC->RecvBuf.Buf);
794 nlen = StrLength(CCC->RecvBuf.Buf);
795 if (CCC->RecvBuf.ReadWritePointer != NULL)
796 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
800 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
801 len, nlen, rlen, nrlen, pch);
803 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
804 len, nlen, rlen, nrlen);
806 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
807 StrLength(Target), ChrPtr(Target));
810 if ((rc < 0) && (Error != NULL)) {
811 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed: %s", Error);
820 * client_getln() ... Get a LF-terminated line of text from the client.
821 * (This is implemented in terms of client_read() and could be
822 * justifiably moved out of sysdep.c)
824 int client_getln(char *buf, int bufsize)
830 retval = CtdlClientGetLine(CCC->MigrateBuf);
835 i = StrLength(CCC->MigrateBuf);
836 pCh = ChrPtr(CCC->MigrateBuf);
837 /* Strip the trailing LF, and the trailing CR if present.
842 && ( (pCh[i - 1]==13)
843 || ( pCh[i - 1]==10)) ) {
849 FlushStrBuf(CCC->MigrateBuf);
851 safestrncpy(&buf[i], "000", bufsize - i);
858 * Cleanup any contexts that are left lying around
862 void close_masters (void)
864 struct ServiceFunctionHook *serviceptr;
868 * close all protocol master sockets
870 for (serviceptr = ServiceHookTable; serviceptr != NULL;
871 serviceptr = serviceptr->next ) {
873 if (serviceptr->tcp_port > 0)
875 if (serviceptr->msock == -1) {
876 Text = "not closing again";
881 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
886 serviceptr->tcp_port = 0;
889 if (serviceptr->sockpath != NULL)
891 if (serviceptr->msock == -1) {
892 Text = "not closing again";
897 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
904 if (serviceptr->msock != -1)
906 close(serviceptr->msock);
907 serviceptr->msock = -1;
910 /* If it's a Unix domain socket, remove the file. */
911 if (serviceptr->sockpath != NULL) {
912 unlink(serviceptr->sockpath);
913 serviceptr->sockpath = NULL;
920 * The system-dependent part of master_cleanup() - close the master socket.
922 void sysdep_master_cleanup(void) {
931 CtdlDestroyProtoHooks();
932 CtdlDestroyDeleteHooks();
933 CtdlDestroyXmsgHooks();
934 CtdlDestroyNetprocHooks();
935 CtdlDestroyUserHooks();
936 CtdlDestroyMessageHook();
937 CtdlDestroyCleanupHooks();
938 CtdlDestroyFixedOutputHooks();
939 CtdlDestroySessionHooks();
940 CtdlDestroyServiceHook();
941 CtdlDestroyRoomHooks();
942 CtdlDestroySearchHooks();
943 #ifdef HAVE_BACKTRACE
951 void graceful_shutdown(int signum) {
952 kill(current_child, signum);
953 unlink(file_pid_file);
958 int nFireUpsNonRestart = 0;
962 * Start running as a daemon.
964 void start_daemon(int unused) {
972 /* Close stdin/stdout/stderr and replace them with /dev/null.
973 * We don't just call close() because we don't want these fd's
974 * to be reused for other files.
976 if (chdir(ctdl_run_dir) != 0) {
977 syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
985 signal(SIGHUP, SIG_IGN);
986 signal(SIGINT, SIG_IGN);
987 signal(SIGQUIT, SIG_IGN);
991 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
992 (freopen("/dev/null", "w", stdout) != stdout) ||
993 (freopen("/dev/null", "w", stderr) != stderr)
995 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
999 current_child = fork();
1000 signal(SIGTERM, graceful_shutdown);
1001 if (current_child < 0) {
1005 else if (current_child == 0) {
1006 return; /* continue starting citadel. */
1009 fp = fopen(file_pid_file, "w");
1011 fprintf(fp, ""F_PID_T"\n", getpid());
1014 waitpid(current_child, &status, 0);
1016 nFireUpsNonRestart = nFireUps;
1018 /* Exit code 0 means the watcher should exit */
1019 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1023 /* Exit code 101-109 means the watcher should exit */
1024 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1028 /* Any other exit code, or no exit code, means we should restart. */
1032 ForkedPid = current_child;
1035 } while (do_restart);
1037 unlink(file_pid_file);
1038 exit(WEXITSTATUS(status));
1043 void checkcrash(void)
1045 if (nFireUpsNonRestart != nFireUps)
1048 CrashMail = NewStrBuf();
1049 syslog(LOG_ALERT, "sysdep: posting crash message");
1050 StrBufPrintf(CrashMail,
1052 " The Citadel server process (citserver) terminated unexpectedly."
1054 " This could be the result of a bug in the server program, or some external "
1056 " You can obtain more information about this by enabling core dumps.\n \n"
1057 " For more information, please see:\n \n"
1058 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1061 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1063 ctdl_run_dir, ForkedPid);
1064 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1065 FreeStrBuf(&CrashMail);
1071 * Generic routine to convert a login name to a full name (gecos)
1072 * Returns nonzero if a conversion took place
1074 int convert_login(char NameToConvert[]) {
1078 pw = getpwnam(NameToConvert);
1083 strcpy(NameToConvert, pw->pw_gecos);
1084 for (a=0; a<strlen(NameToConvert); ++a) {
1085 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1093 void HuntBadSession(void)
1099 struct ServiceFunctionHook *serviceptr;
1103 /* Next, add all of the client sockets. */
1104 begin_critical_section(S_SESSION_TABLE);
1105 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1106 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1108 /* Initialize the fdset. */
1111 tv.tv_sec = 0; /* wake up every second if no input */
1114 /* Don't select on dead sessions, only truly idle ones */
1115 if ( (ptr->state == CON_IDLE)
1116 && (ptr->kill_me == 0)
1117 && (ptr->client_socket > 0)
1119 FD_SET(ptr->client_socket, &readfds);
1120 if (ptr->client_socket > highest)
1121 highest = ptr->client_socket;
1123 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1128 "sysdep: killing session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]",
1131 ptr->is_local_socket,
1133 ptr->cs_host,ptr->cs_addr);
1136 ptr->client_socket = -1;
1142 end_critical_section(S_SESSION_TABLE);
1145 /* First, add the various master sockets to the fdset. */
1146 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1148 /* Initialize the fdset. */
1150 tv.tv_sec = 0; /* wake up every second if no input */
1153 FD_SET(serviceptr->msock, &readfds);
1154 if (serviceptr->msock > highest) {
1155 highest = serviceptr->msock;
1157 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1160 /* Gotcha! server socket dead? commit suicide! */
1161 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
1162 server_shutting_down = 1;
1170 const char *WorkerLogStr = "W";
1172 * This loop just keeps going and going and going...
1174 void *worker_thread(void *blah) {
1177 CitContext *bind_me = NULL;
1181 int force_purge = 0;
1182 struct ServiceFunctionHook *serviceptr;
1183 int ssock; /* Descriptor for client socket */
1184 CitContext *con = NULL; /* Temporary context pointer */
1187 pthread_mutex_lock(&ThreadCountMutex);
1189 pthread_mutex_unlock(&ThreadCountMutex);
1191 while (!server_shutting_down) {
1193 /* make doubly sure we're not holding any stale db handles
1194 * which might cause a deadlock.
1196 cdb_check_handles();
1197 do_select: force_purge = 0;
1198 bind_me = NULL; /* Which session shall we handle? */
1200 /* Initialize the fdset. */
1204 /* First, add the various master sockets to the fdset. */
1205 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1206 FD_SET(serviceptr->msock, &readfds);
1207 if (serviceptr->msock > highest) {
1208 highest = serviceptr->msock;
1212 /* Next, add all of the client sockets. */
1213 begin_critical_section(S_SESSION_TABLE);
1214 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1215 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1218 /* Don't select on dead sessions, only truly idle ones */
1219 if ( (ptr->state == CON_IDLE)
1220 && (ptr->kill_me == 0)
1221 && (ptr->client_socket > 0)
1223 FD_SET(ptr->client_socket, &readfds);
1224 if (ptr->client_socket > highest)
1225 highest = ptr->client_socket;
1227 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1229 ptr->state = CON_EXECUTING;
1232 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1234 ptr->state = CON_STARTING;
1238 end_critical_section(S_SESSION_TABLE);
1244 /* If we got this far, it means that there are no sessions
1245 * which a previous thread marked for attention, so we go
1246 * ahead and get ready to select().
1249 if (!server_shutting_down) {
1250 tv.tv_sec = 1; /* wake up every second if no input */
1252 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1259 /* Now figure out who made this select() unblock.
1260 * First, check for an error or exit condition.
1263 if (errno == EBADF) {
1264 syslog(LOG_ERR, "sysdep: select() failed: %m");
1268 if (errno != EINTR) {
1269 syslog(LOG_ERR, "sysdep: exiting: %m");
1270 server_shutting_down = 1;
1273 if (server_shutting_down) {
1280 else if (retval == 0) {
1281 if (server_shutting_down) {
1287 /* Next, check to see if it's a new client connecting * on a master socket. */
1289 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1291 if (FD_ISSET(serviceptr->msock, &readfds)) {
1292 ssock = accept(serviceptr->msock, NULL, 0);
1294 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1296 /* The master socket is non-blocking but the client
1297 * sockets need to be blocking, otherwise certain
1298 * operations barf on FreeBSD. Not a fatal error.
1300 if (fcntl(ssock, F_SETFL, 0) < 0) {
1301 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1304 /* New context will be created already
1305 * set up in the CON_EXECUTING state.
1307 con = CreateNewContext();
1309 /* Assign our new socket number to it. */
1310 con->tcp_port = serviceptr->tcp_port;
1311 con->client_socket = ssock;
1312 con->h_command_function = serviceptr->h_command_function;
1313 con->h_async_function = serviceptr->h_async_function;
1314 con->h_greeting_function = serviceptr->h_greeting_function;
1315 con->ServiceName = serviceptr->ServiceName;
1317 /* Determine whether it's a local socket */
1318 if (serviceptr->sockpath != NULL) {
1319 con->is_local_socket = 1;
1322 /* Set the SO_REUSEADDR socket option */
1324 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1325 con->state = CON_GREETING;
1333 /* It must be a client socket. Find a context that has data
1334 * waiting on its socket *and* is in the CON_IDLE state. Any
1335 * active sockets other than our chosen one are marked as
1336 * CON_READY so the next thread that comes around can just bind
1337 * to one without having to select() again.
1339 begin_critical_section(S_SESSION_TABLE);
1340 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1341 int checkfd = ptr->client_socket;
1342 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1343 if (FD_ISSET(checkfd, &readfds)) {
1344 ptr->input_waiting = 1;
1346 bind_me = ptr; /* I choose you! */
1347 bind_me->state = CON_EXECUTING;
1350 ptr->state = CON_READY;
1352 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1354 bind_me = ptr; /* I choose you! */
1355 bind_me->state = CON_EXECUTING;
1358 ptr->state = CON_READY;
1363 end_critical_section(S_SESSION_TABLE);
1366 /* We're bound to a session */
1367 pthread_mutex_lock(&ThreadCountMutex);
1369 pthread_mutex_unlock(&ThreadCountMutex);
1371 if (bind_me != NULL) {
1372 become_session(bind_me);
1374 if (bind_me->state == CON_STARTING) {
1375 bind_me->state = CON_EXECUTING;
1376 begin_session(bind_me);
1377 bind_me->h_greeting_function();
1379 /* If the client has sent a command, execute it. */
1380 if (CC->input_waiting) {
1381 CC->h_command_function();
1383 while (HaveMoreLinesWaiting(CC))
1384 CC->h_command_function();
1386 CC->input_waiting = 0;
1389 /* If there are asynchronous messages waiting and the
1390 * client supports it, do those now */
1391 if ((CC->is_async) && (CC->async_waiting)
1392 && (CC->h_async_function != NULL)) {
1393 CC->h_async_function();
1394 CC->async_waiting = 0;
1397 force_purge = CC->kill_me;
1398 become_session(NULL);
1399 bind_me->state = CON_IDLE;
1402 dead_session_purge(force_purge);
1405 pthread_mutex_lock(&ThreadCountMutex);
1407 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1408 (num_workers > CtdlGetConfigInt("c_min_workers")))
1411 pthread_mutex_unlock(&ThreadCountMutex);
1414 pthread_mutex_unlock(&ThreadCountMutex);
1417 /* If control reaches this point, the server is shutting down */
1418 pthread_mutex_lock(&ThreadCountMutex);
1420 pthread_mutex_unlock(&ThreadCountMutex);
1428 * Translate text facility name to syslog.h defined value.
1430 int SyslogFacility(char *name)
1439 { LOG_KERN, "kern" },
1440 { LOG_USER, "user" },
1441 { LOG_MAIL, "mail" },
1442 { LOG_DAEMON, "daemon" },
1443 { LOG_AUTH, "auth" },
1444 { LOG_SYSLOG, "syslog" },
1446 { LOG_NEWS, "news" },
1447 { LOG_UUCP, "uucp" },
1448 { LOG_LOCAL0, "local0" },
1449 { LOG_LOCAL1, "local1" },
1450 { LOG_LOCAL2, "local2" },
1451 { LOG_LOCAL3, "local3" },
1452 { LOG_LOCAL4, "local4" },
1453 { LOG_LOCAL5, "local5" },
1454 { LOG_LOCAL6, "local6" },
1455 { LOG_LOCAL7, "local7" },
1458 for(i = 0; facTbl[i].name != NULL; i++) {
1459 if(!strcasecmp(name, facTbl[i].name))
1460 return facTbl[i].facility;