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-2019 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. */
89 if (pthread_key_create(&ThreadKey, NULL) != 0) { // TSD for threads
90 syslog(LOG_ERR, "pthread_key_create() : %m");
94 if (pthread_key_create(&MyConKey, NULL) != 0) { // TSD for sessions
95 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)
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 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
164 else /* specific IPv6 */
167 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
168 syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
173 if (port_number == 0) {
174 syslog(LOG_ALERT, "tcpserver: no port number was specified");
177 sin6.sin6_port = htons((u_short) port_number);
178 sin4.sin_port = htons((u_short) port_number);
180 p = getprotobyname("tcp");
182 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
186 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
188 syslog(LOG_ALERT, "tcpserver: socket: %m");
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 syslog(LOG_ALERT, "tcpserver: bind: %m");
207 fcntl(s, F_SETFL, O_NONBLOCK);
209 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
210 syslog(LOG_ALERT, "tcpserver: listen: %m");
218 * Create a Unix domain socket and listen on it
220 int ctdl_uds_server(char *sockpath, int queue_len)
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 syslog(LOG_ERR, "udsserver: %m");
239 memset(&addr, 0, sizeof(addr));
240 addr.sun_family = AF_UNIX;
241 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
243 s = socket(AF_UNIX, SOCK_STREAM, 0);
245 syslog(LOG_ERR, "udsserver: socket: %m");
249 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
250 syslog(LOG_ERR, "udsserver: bind: %m");
254 /* set to nonblock - we need this for some obscure situations */
255 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
256 syslog(LOG_ERR, "udsserver: fcntl: %m");
261 if (listen(s, actual_queue_len) < 0) {
262 syslog(LOG_ERR, "udsserver: listen: %m");
266 #ifdef HAVE_STRUCT_UCRED
267 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
270 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
276 * The following functions implement output buffering on operating systems which
277 * support it (such as Linux and various BSD flavors).
281 # define HAVE_TCP_BUFFERING
284 # define HAVE_TCP_BUFFERING
285 # define TCP_CORK TCP_NOPUSH
287 #endif /* TCP_CORK */
288 #endif /* HAVE_DARWIN */
290 static unsigned on = 1, off = 0;
292 void buffer_output(void) {
293 #ifdef HAVE_TCP_BUFFERING
295 if (!CC->redirect_ssl)
297 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
301 void unbuffer_output(void) {
302 #ifdef HAVE_TCP_BUFFERING
304 if (!CC->redirect_ssl)
306 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
310 void flush_output(void) {
311 #ifdef HAVE_TCP_BUFFERING
312 struct CitContext *CCC = CC;
313 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
314 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
319 static void flush_client_inbuf(void)
323 FlushStrBuf(CCC->ReadBuf);
324 CCC->RecvBuf->ReadWritePointer = NULL;
330 * client_close() ... close the client socket
332 void client_close(void) {
333 CitContext *CCC = CC;
336 if (CCC->client_socket <= 0) return;
337 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
338 close(CCC->client_socket);
339 CCC->client_socket = -1 ;
344 * client_write() ... Send binary data to the client.
346 int client_write(const char *buf, int nbytes)
348 int bytes_written = 0;
350 #ifndef HAVE_TCP_BUFFERING
351 int old_buffer_len = 0;
357 if (nbytes < 1) return(0);
367 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
369 fd = fopen(fn, "a+");
371 syslog(LOG_ERR, "%s: %m", fn);
374 fprintf(fd, "Sending: BufSize: %d BufContent: [", nbytes);
375 rv = fwrite(buf, nbytes, 1, fd);
380 // flush_client_inbuf();
381 if (Ctx->redirect_buffer != NULL) {
382 StrBufAppendBufPlain(Ctx->redirect_buffer,
388 if (Ctx->redirect_ssl) {
389 client_write_ssl(buf, nbytes);
393 if (Ctx->client_socket == -1) return -1;
395 fdflags = fcntl(Ctx->client_socket, F_GETFL);
397 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
398 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
400 FD_SET(Ctx->client_socket, &wset);
401 if (select(1, NULL, &wset, NULL, NULL) == -1) {
404 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
405 if (server_shutting_down) {
406 CC->kill_me = KILLME_SELECT_INTERRUPTED;
409 /* can't trust fd's and stuff so we need to re-create them */
413 syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
415 Ctx->kill_me = KILLME_SELECT_FAILED;
421 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
423 syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
425 Ctx->kill_me = KILLME_WRITE_FAILED;
428 bytes_written = bytes_written + retval;
433 void cputbuf(const StrBuf *Buf) {
434 client_write(ChrPtr(Buf), StrLength(Buf));
439 * cprintf() Send formatted printable data to the client.
440 * Implemented in terms of client_write() so it's technically not sysdep...
442 void cprintf(const char *format, ...) {
446 va_start(arg_ptr, format);
447 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
448 buf[sizeof buf - 2] = '\n';
449 client_write(buf, strlen(buf));
455 * Read data from the client socket.
457 * sock socket fd to read from
458 * buf buffer to read into
459 * bytes number of bytes to read
460 * timeout Number of seconds to wait before timing out
462 * Possible return values:
463 * 1 Requested number of bytes has been read.
464 * 0 Request timed out.
465 * -1 Connection is broken, or other error.
467 int client_read_blob(StrBuf *Target, int bytes, int timeout)
474 if (CCC->redirect_ssl) {
480 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
482 fd = fopen(fn, "a+");
484 syslog(LOG_ERR, "%s: %m", fn);
487 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
488 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
494 retval = client_read_sslblob(Target, bytes, timeout);
496 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
499 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
501 fd = fopen(fn, "a+");
503 syslog(LOG_ERR, "%s: %m", fn);
506 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
507 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
520 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
522 fd = fopen(fn, "a+");
524 syslog(LOG_ERR, "%s: %m", fn);
527 fprintf(fd, "Reading BLOB: BufSize: %d ",
529 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
533 retval = StrBufReadBLOBBuffered(Target,
535 &CCC->RecvBuf.ReadWritePointer,
543 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
548 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
550 fd = fopen(fn, "a+");
552 syslog(LOG_ERR, "%s: %m", fn);
555 fprintf(fd, "Read: %d BufContent: [",
557 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
567 * to make client_read_random_blob() more efficient, increase buffer size.
568 * just use in greeting function, else your buffer may be flushed
570 void client_set_inbound_buf(long N)
573 FlushStrBuf(CCC->RecvBuf.Buf);
574 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
577 int client_read_random_blob(StrBuf *Target, int timeout)
582 rc = client_read_blob(Target, 1, timeout);
588 len = StrLength(CCC->RecvBuf.Buf);
589 pch = ChrPtr(CCC->RecvBuf.Buf);
593 if (CCC->RecvBuf.ReadWritePointer != NULL) {
594 len -= CCC->RecvBuf.ReadWritePointer - pch;
595 pch = CCC->RecvBuf.ReadWritePointer;
597 StrBufAppendBufPlain(Target, pch, len, 0);
598 FlushStrBuf(CCC->RecvBuf.Buf);
599 CCC->RecvBuf.ReadWritePointer = NULL;
606 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
608 fd = fopen(fn, "a+");
610 syslog(LOG_ERR, "%s: %m", fn);
613 fprintf(fd, "Read: BufSize: %d BufContent: [",
615 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
620 return StrLength(Target);
628 int client_read_to(char *buf, int bytes, int timeout)
633 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
642 ChrPtr(CCC->MigrateBuf),
643 StrLength(CCC->MigrateBuf) + 1);
644 FlushStrBuf(CCC->MigrateBuf);
650 int HaveMoreLinesWaiting(CitContext *CCC)
652 if ((CCC->kill_me != 0) ||
653 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
654 (StrLength(CCC->RecvBuf.Buf) == 0) &&
655 (CCC->client_socket != -1)) )
663 * Read data from the client socket with default timeout.
664 * (This is implemented in terms of client_read_to() and could be
665 * justifiably moved out of sysdep.c)
667 INLINE int client_read(char *buf, int bytes)
669 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
672 int CtdlClientGetLine(StrBuf *Target)
680 if (CCC->redirect_ssl) {
690 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
692 fd = fopen(fn, "a+");
694 syslog(LOG_ERR, "%s: %m", fn);
697 pch = ChrPtr(CCC->RecvBuf.Buf);
698 len = StrLength(CCC->RecvBuf.Buf);
699 if (CCC->RecvBuf.ReadWritePointer != NULL)
700 rlen = CCC->RecvBuf.ReadWritePointer - pch;
704 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
707 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
710 rc = client_readline_sslbuffer(Target,
712 &CCC->RecvBuf.ReadWritePointer,
715 pch = ChrPtr(CCC->RecvBuf.Buf);
716 nlen = StrLength(CCC->RecvBuf.Buf);
717 if (CCC->RecvBuf.ReadWritePointer != NULL)
718 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
722 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
723 len, nlen, rlen, nrlen, pch);
725 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
726 len, nlen, rlen, nrlen);
728 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
729 StrLength(Target), ChrPtr(Target));
733 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed");
744 int len, rlen, nlen, nrlen;
747 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
749 fd = fopen(fn, "a+");
751 syslog(LOG_ERR, "%s: %m", fn);
754 pch = ChrPtr(CCC->RecvBuf.Buf);
755 len = StrLength(CCC->RecvBuf.Buf);
756 if (CCC->RecvBuf.ReadWritePointer != NULL)
757 rlen = CCC->RecvBuf.ReadWritePointer - pch;
761 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
764 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
767 rc = StrBufTCP_read_buffered_line_fast(Target,
769 &CCC->RecvBuf.ReadWritePointer,
777 pch = ChrPtr(CCC->RecvBuf.Buf);
778 nlen = StrLength(CCC->RecvBuf.Buf);
779 if (CCC->RecvBuf.ReadWritePointer != NULL)
780 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
784 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
785 len, nlen, rlen, nrlen, pch);
787 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
788 len, nlen, rlen, nrlen);
790 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
791 StrLength(Target), ChrPtr(Target));
794 if ((rc < 0) && (Error != NULL)) {
795 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed: %s", Error);
804 * client_getln() ... Get a LF-terminated line of text from the client.
805 * (This is implemented in terms of client_read() and could be
806 * justifiably moved out of sysdep.c)
808 int client_getln(char *buf, int bufsize)
814 retval = CtdlClientGetLine(CCC->MigrateBuf);
819 i = StrLength(CCC->MigrateBuf);
820 pCh = ChrPtr(CCC->MigrateBuf);
821 /* Strip the trailing LF, and the trailing CR if present.
826 && ( (pCh[i - 1]==13)
827 || ( pCh[i - 1]==10)) ) {
833 FlushStrBuf(CCC->MigrateBuf);
835 safestrncpy(&buf[i], "000", bufsize - i);
842 * Cleanup any contexts that are left lying around
846 void close_masters (void)
848 struct ServiceFunctionHook *serviceptr;
852 * close all protocol master sockets
854 for (serviceptr = ServiceHookTable; serviceptr != NULL;
855 serviceptr = serviceptr->next ) {
857 if (serviceptr->tcp_port > 0)
859 if (serviceptr->msock == -1) {
860 Text = "not closing again";
865 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
870 serviceptr->tcp_port = 0;
873 if (serviceptr->sockpath != NULL)
875 if (serviceptr->msock == -1) {
876 Text = "not closing again";
881 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
888 if (serviceptr->msock != -1)
890 close(serviceptr->msock);
891 serviceptr->msock = -1;
894 /* If it's a Unix domain socket, remove the file. */
895 if (serviceptr->sockpath != NULL) {
896 unlink(serviceptr->sockpath);
897 serviceptr->sockpath = NULL;
904 * The system-dependent part of master_cleanup() - close the master socket.
906 void sysdep_master_cleanup(void) {
915 CtdlDestroyProtoHooks();
916 CtdlDestroyDeleteHooks();
917 CtdlDestroyXmsgHooks();
918 CtdlDestroyUserHooks();
919 CtdlDestroyMessageHook();
920 CtdlDestroyCleanupHooks();
921 CtdlDestroyFixedOutputHooks();
922 CtdlDestroySessionHooks();
923 CtdlDestroyServiceHook();
924 CtdlDestroyRoomHooks();
925 CtdlDestroySearchHooks();
931 void graceful_shutdown(int signum) {
932 kill(current_child, signum);
933 unlink(file_pid_file);
938 int nFireUpsNonRestart = 0;
942 * Start running as a daemon.
944 void start_daemon(int unused) {
952 /* Close stdin/stdout/stderr and replace them with /dev/null.
953 * We don't just call close() because we don't want these fd's
954 * to be reused for other files.
956 if (chdir(ctdl_run_dir) != 0) {
957 syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
965 signal(SIGHUP, SIG_IGN);
966 signal(SIGINT, SIG_IGN);
967 signal(SIGQUIT, SIG_IGN);
971 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
972 (freopen("/dev/null", "w", stdout) != stdout) ||
973 (freopen("/dev/null", "w", stderr) != stderr)
975 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
979 current_child = fork();
980 signal(SIGTERM, graceful_shutdown);
981 if (current_child < 0) {
985 else if (current_child == 0) {
986 return; /* continue starting citadel. */
989 fp = fopen(file_pid_file, "w");
991 fprintf(fp, ""F_PID_T"\n", getpid());
994 waitpid(current_child, &status, 0);
996 nFireUpsNonRestart = nFireUps;
998 /* Exit code 0 means the watcher should exit */
999 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1003 /* Exit code 101-109 means the watcher should exit */
1004 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1008 /* Any other exit code, or no exit code, means we should restart. */
1012 ForkedPid = current_child;
1015 } while (do_restart);
1017 unlink(file_pid_file);
1018 exit(WEXITSTATUS(status));
1023 void checkcrash(void)
1025 if (nFireUpsNonRestart != nFireUps)
1028 CrashMail = NewStrBuf();
1029 syslog(LOG_ALERT, "sysdep: posting crash message");
1030 StrBufPrintf(CrashMail,
1032 " The Citadel server process (citserver) terminated unexpectedly."
1034 " This could be the result of a bug in the server program, or some external "
1036 " You can obtain more information about this by enabling core dumps.\n \n"
1037 " For more information, please see:\n \n"
1038 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1041 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1043 ctdl_run_dir, ForkedPid);
1044 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1045 FreeStrBuf(&CrashMail);
1051 * Generic routine to convert a login name to a full name (gecos)
1052 * Returns nonzero if a conversion took place
1054 int convert_login(char NameToConvert[]) {
1058 pw = getpwnam(NameToConvert);
1063 strcpy(NameToConvert, pw->pw_gecos);
1064 for (a=0; a<strlen(NameToConvert); ++a) {
1065 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1073 void HuntBadSession(void)
1079 struct ServiceFunctionHook *serviceptr;
1081 /* Next, add all of the client sockets. */
1082 begin_critical_section(S_SESSION_TABLE);
1083 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1084 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1086 /* Initialize the fdset. */
1089 tv.tv_sec = 0; /* wake up every second if no input */
1092 /* Don't select on dead sessions, only truly idle ones */
1093 if ( (ptr->state == CON_IDLE)
1094 && (ptr->kill_me == 0)
1095 && (ptr->client_socket > 0)
1097 FD_SET(ptr->client_socket, &readfds);
1098 if (ptr->client_socket > highest)
1099 highest = ptr->client_socket;
1101 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
1105 "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
1113 ptr->client_socket = -1;
1118 end_critical_section(S_SESSION_TABLE);
1120 /* First, add the various master sockets to the fdset. */
1121 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1123 /* Initialize the fdset. */
1125 tv.tv_sec = 0; /* wake up every second if no input */
1128 FD_SET(serviceptr->msock, &readfds);
1129 if (serviceptr->msock > highest) {
1130 highest = serviceptr->msock;
1132 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1135 /* Gotcha! server socket dead? commit suicide! */
1136 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
1137 server_shutting_down = 1;
1145 * This loop just keeps going and going and going...
1147 void *worker_thread(void *blah) {
1150 CitContext *bind_me = NULL;
1154 int force_purge = 0;
1155 struct ServiceFunctionHook *serviceptr;
1156 int ssock; /* Descriptor for client socket */
1157 CitContext *con = NULL; /* Temporary context pointer */
1160 pthread_mutex_lock(&ThreadCountMutex);
1162 pthread_mutex_unlock(&ThreadCountMutex);
1164 while (!server_shutting_down) {
1166 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
1167 cdb_check_handles();
1168 do_select: force_purge = 0;
1169 bind_me = NULL; /* Which session shall we handle? */
1171 /* Initialize the fdset. */
1175 /* First, add the various master sockets to the fdset. */
1176 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1177 FD_SET(serviceptr->msock, &readfds);
1178 if (serviceptr->msock > highest) {
1179 highest = serviceptr->msock;
1183 /* Next, add all of the client sockets. */
1184 begin_critical_section(S_SESSION_TABLE);
1185 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1186 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1189 /* Don't select on dead sessions, only truly idle ones */
1190 if ( (ptr->state == CON_IDLE)
1191 && (ptr->kill_me == 0)
1192 && (ptr->client_socket > 0)
1194 FD_SET(ptr->client_socket, &readfds);
1195 if (ptr->client_socket > highest)
1196 highest = ptr->client_socket;
1198 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1200 ptr->state = CON_EXECUTING;
1203 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1205 ptr->state = CON_STARTING;
1209 end_critical_section(S_SESSION_TABLE);
1215 /* If we got this far, it means that there are no sessions
1216 * which a previous thread marked for attention, so we go
1217 * ahead and get ready to select().
1220 if (!server_shutting_down) {
1221 tv.tv_sec = 1; /* wake up every second if no input */
1223 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1230 /* Now figure out who made this select() unblock.
1231 * First, check for an error or exit condition.
1234 if (errno == EBADF) {
1235 syslog(LOG_ERR, "sysdep: select() failed: %m");
1239 if (errno != EINTR) {
1240 syslog(LOG_ERR, "sysdep: exiting: %m");
1241 server_shutting_down = 1;
1244 if (server_shutting_down) {
1251 else if (retval == 0) {
1252 if (server_shutting_down) {
1258 /* Next, check to see if it's a new client connecting on a master socket. */
1260 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1262 if (FD_ISSET(serviceptr->msock, &readfds)) {
1263 ssock = accept(serviceptr->msock, NULL, 0);
1265 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1267 /* The master socket is non-blocking but the client
1268 * sockets need to be blocking, otherwise certain
1269 * operations barf on FreeBSD. Not a fatal error.
1271 if (fcntl(ssock, F_SETFL, 0) < 0) {
1272 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1275 /* New context will be created already
1276 * set up in the CON_EXECUTING state.
1278 con = CreateNewContext();
1280 /* Assign our new socket number to it. */
1281 con->tcp_port = serviceptr->tcp_port;
1282 con->client_socket = ssock;
1283 con->h_command_function = serviceptr->h_command_function;
1284 con->h_async_function = serviceptr->h_async_function;
1285 con->h_greeting_function = serviceptr->h_greeting_function;
1286 con->ServiceName = serviceptr->ServiceName;
1288 /* Connections on a local client are always from the same host */
1289 if (serviceptr->sockpath != NULL) {
1290 con->is_local_client = 1;
1293 /* Set the SO_REUSEADDR socket option */
1295 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1296 con->state = CON_GREETING;
1304 /* It must be a client socket. Find a context that has data
1305 * waiting on its socket *and* is in the CON_IDLE state. Any
1306 * active sockets other than our chosen one are marked as
1307 * CON_READY so the next thread that comes around can just bind
1308 * to one without having to select() again.
1310 begin_critical_section(S_SESSION_TABLE);
1311 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1312 int checkfd = ptr->client_socket;
1313 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1314 if (FD_ISSET(checkfd, &readfds)) {
1315 ptr->input_waiting = 1;
1317 bind_me = ptr; /* I choose you! */
1318 bind_me->state = CON_EXECUTING;
1321 ptr->state = CON_READY;
1323 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1325 bind_me = ptr; /* I choose you! */
1326 bind_me->state = CON_EXECUTING;
1329 ptr->state = CON_READY;
1334 end_critical_section(S_SESSION_TABLE);
1337 /* We're bound to a session */
1338 pthread_mutex_lock(&ThreadCountMutex);
1340 pthread_mutex_unlock(&ThreadCountMutex);
1342 if (bind_me != NULL) {
1343 become_session(bind_me);
1345 if (bind_me->state == CON_STARTING) {
1346 bind_me->state = CON_EXECUTING;
1347 begin_session(bind_me);
1348 bind_me->h_greeting_function();
1350 /* If the client has sent a command, execute it. */
1351 if (CC->input_waiting) {
1352 CC->h_command_function();
1354 while (HaveMoreLinesWaiting(CC))
1355 CC->h_command_function();
1357 CC->input_waiting = 0;
1360 /* If there are asynchronous messages waiting and the client supports it, do those now */
1361 if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1362 CC->h_async_function();
1363 CC->async_waiting = 0;
1366 force_purge = CC->kill_me;
1367 become_session(NULL);
1368 bind_me->state = CON_IDLE;
1371 dead_session_purge(force_purge);
1374 pthread_mutex_lock(&ThreadCountMutex);
1376 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1377 (num_workers > CtdlGetConfigInt("c_min_workers")))
1380 pthread_mutex_unlock(&ThreadCountMutex);
1383 pthread_mutex_unlock(&ThreadCountMutex);
1386 /* If control reaches this point, the server is shutting down */
1387 pthread_mutex_lock(&ThreadCountMutex);
1389 pthread_mutex_unlock(&ThreadCountMutex);
1396 * Translate text facility name to syslog.h defined value.
1398 int SyslogFacility(char *name)
1407 { LOG_KERN, "kern" },
1408 { LOG_USER, "user" },
1409 { LOG_MAIL, "mail" },
1410 { LOG_DAEMON, "daemon" },
1411 { LOG_AUTH, "auth" },
1412 { LOG_SYSLOG, "syslog" },
1414 { LOG_NEWS, "news" },
1415 { LOG_UUCP, "uucp" },
1416 { LOG_LOCAL0, "local0" },
1417 { LOG_LOCAL1, "local1" },
1418 { LOG_LOCAL2, "local2" },
1419 { LOG_LOCAL3, "local3" },
1420 { LOG_LOCAL4, "local4" },
1421 { LOG_LOCAL5, "local5" },
1422 { LOG_LOCAL6, "local6" },
1423 { LOG_LOCAL7, "local7" },
1426 for(i = 0; facTbl[i].name != NULL; i++) {
1427 if(!strcasecmp(name, facTbl[i].name))
1428 return facTbl[i].facility;