2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * would need to be altered to run the server in a non-POSIX environment.
7 * If we ever port to a different platform and either have multiple
8 * variants of this file or simply load it up with #ifdefs.
10 * Copyright (c) 1987-2011 by the citadel.org team
12 * This program is open source software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License, version 3.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
27 #include <sys/syslog.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <netinet/tcp.h>
36 #include <arpa/inet.h>
38 #define SHOW_ME_VAPPEND_PRINTF
39 #include <libcitadel.h>
41 #include "citserver.h"
42 #include "ctdl_module.h"
44 #include "sysdep_decls.h"
45 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
47 #include "housekeeping.h"
50 * Signal handler to shut down the server.
53 volatile int exit_signal = 0;
54 volatile int shutdown_and_halt = 0;
55 volatile int restart_server = 0;
56 volatile int running_as_daemon = 0;
58 static RETSIGTYPE signal_cleanup(int signum) {
59 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
61 server_shutting_down = 1;
64 static RETSIGTYPE signal_exit(int signum) {
71 * Some initialization stuff...
73 void init_sysdep(void) {
76 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
80 getrlimit(RLIMIT_NOFILE, &rl);
81 rl.rlim_cur = FD_SETSIZE;
82 rl.rlim_max = FD_SETSIZE;
83 setrlimit(RLIMIT_NOFILE, &rl);
87 /* If we've got OpenSSL, we're going to use it. */
93 * Set up a place to put thread-specific data.
94 * We only need a single pointer per thread - it points to the
95 * CitContext structure (in the ContextList linked list) of the
96 * session to which the calling thread is currently bound.
98 if (pthread_key_create(&MyConKey, NULL) != 0) {
99 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
103 * Interript, hangup, and terminate signals should cause the server
104 * to gracefully clean up and shut down.
107 sigaddset(&set, SIGINT);
108 sigaddset(&set, SIGHUP);
109 sigaddset(&set, SIGTERM);
110 sigprocmask(SIG_UNBLOCK, &set, NULL);
112 signal(SIGINT, signal_cleanup);
113 signal(SIGHUP, signal_cleanup);
114 signal(SIGTERM, signal_cleanup);
115 signal(SIGUSR2, signal_exit);
118 * Do not shut down the server on broken pipe signals, otherwise the
119 * whole Citadel service would come down whenever a single client
122 signal(SIGPIPE, SIG_IGN);
127 * This is a generic function to set up a master socket for listening on
128 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
130 * ip_addr IP address to bind
131 * port_number port number to bind
132 * queue_len number of incoming connections to allow in the queue
134 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
137 struct sockaddr_in6 sin6;
138 struct sockaddr_in sin4;
142 memset(&sin6, 0, sizeof(sin6));
143 memset(&sin4, 0, sizeof(sin4));
144 sin6.sin6_family = AF_INET6;
145 sin4.sin_family = AF_INET;
147 if ( (ip_addr == NULL) /* any IPv6 */
148 || (IsEmptyStr(ip_addr))
149 || (!strcmp(ip_addr, "*"))
152 sin6.sin6_addr = in6addr_any;
154 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
157 sin4.sin_addr.s_addr = INADDR_ANY;
159 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
162 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
163 snprintf(errormessage, SIZ,
164 "Error binding to [%s] : %s", ip_addr, strerror(errno)
166 syslog(LOG_ALERT, "%s", errormessage);
170 else /* specific IPv6 */
173 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
174 snprintf(errormessage, SIZ,
175 "Error binding to [%s] : %s", ip_addr, strerror(errno)
177 syslog(LOG_ALERT, "%s", errormessage);
182 if (port_number == 0) {
183 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
184 syslog(LOG_ALERT, "%s", errormessage);
187 sin6.sin6_port = htons((u_short) port_number);
188 sin4.sin_port = htons((u_short) port_number);
190 p = getprotobyname("tcp");
192 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
194 snprintf(errormessage, SIZ,
195 "Can't create a listening socket: %s", strerror(errno)
197 syslog(LOG_ALERT, "%s", errormessage);
200 /* Set some socket options that make sense. */
202 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
204 if (ip_version == 6) {
205 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
208 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
212 snprintf(errormessage, SIZ,
213 "Can't bind: %s", strerror(errno)
215 syslog(LOG_ALERT, "%s", errormessage);
219 fcntl(s, F_SETFL, O_NONBLOCK);
221 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
222 snprintf(errormessage, SIZ,
223 "Can't listen: %s", strerror(errno)
225 syslog(LOG_ALERT, "%s", errormessage);
236 * Create a Unix domain socket and listen on it
238 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
240 struct sockaddr_un addr;
243 int actual_queue_len;
244 #ifdef HAVE_STRUCT_UCRED
248 actual_queue_len = queue_len;
249 if (actual_queue_len < 5) actual_queue_len = 5;
251 i = unlink(sockpath);
252 if ((i != 0) && (errno != ENOENT)) {
253 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
254 sockpath, strerror(errno)
256 syslog(LOG_EMERG, "%s", errormessage);
260 memset(&addr, 0, sizeof(addr));
261 addr.sun_family = AF_UNIX;
262 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
264 s = socket(AF_UNIX, SOCK_STREAM, 0);
266 snprintf(errormessage, SIZ,
267 "citserver: Can't create a socket: %s",
269 syslog(LOG_EMERG, "%s", errormessage);
273 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
274 snprintf(errormessage, SIZ,
275 "citserver: Can't bind: %s",
277 syslog(LOG_EMERG, "%s", errormessage);
281 /* set to nonblock - we need this for some obscure situations */
282 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
283 snprintf(errormessage, SIZ,
284 "citserver: Can't set socket to non-blocking: %s",
286 syslog(LOG_EMERG, "%s", errormessage);
291 if (listen(s, actual_queue_len) < 0) {
292 snprintf(errormessage, SIZ,
293 "citserver: Can't listen: %s",
295 syslog(LOG_EMERG, "%s", errormessage);
299 #ifdef HAVE_STRUCT_UCRED
300 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
303 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
310 * The following functions implement output buffering on operating systems which
311 * support it (such as Linux and various BSD flavors).
315 # define HAVE_TCP_BUFFERING
318 # define HAVE_TCP_BUFFERING
319 # define TCP_CORK TCP_NOPUSH
321 #endif /* TCP_CORK */
322 #endif /* HAVE_DARWIN */
324 static unsigned on = 1, off = 0;
326 void buffer_output(void) {
327 #ifdef HAVE_TCP_BUFFERING
329 if (!CC->redirect_ssl)
331 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
335 void unbuffer_output(void) {
336 #ifdef HAVE_TCP_BUFFERING
338 if (!CC->redirect_ssl)
340 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
344 void flush_output(void) {
345 #ifdef HAVE_TCP_BUFFERING
346 struct CitContext *CCC = CC;
347 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
348 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
353 static void flush_client_inbuf(void)
357 FlushStrBuf(CCC->ReadBuf);
358 CCC->RecvBuf->ReadWritePointer = NULL;
365 * client_close() ... close the client socket
367 void client_close(void) {
368 CitContext *CCC = CC;
371 if (CCC->client_socket <= 0) return;
372 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
374 close(CCC->client_socket);
375 CCC->client_socket = -1 ;
382 * client_write() ... Send binary data to the client.
384 int client_write(const char *buf, int nbytes)
386 int bytes_written = 0;
388 #ifndef HAVE_TCP_BUFFERING
389 int old_buffer_len = 0;
395 if (nbytes < 1) return(0);
405 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
407 fd = fopen(fn, "a+");
409 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
413 fprintf(fd, "Sending: BufSize: %d BufContent: [",
415 rv = fwrite(buf, nbytes, 1, fd);
420 // flush_client_inbuf();
421 if (Ctx->redirect_buffer != NULL) {
422 StrBufAppendBufPlain(Ctx->redirect_buffer,
428 if (Ctx->redirect_ssl) {
429 client_write_ssl(buf, nbytes);
433 if (Ctx->client_socket == -1) return -1;
435 fdflags = fcntl(Ctx->client_socket, F_GETFL);
437 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
438 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
440 FD_SET(Ctx->client_socket, &wset);
441 if (select(1, NULL, &wset, NULL, NULL) == -1) {
444 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
447 if (server_shutting_down) {
448 CC->kill_me = KILLME_SELECT_INTERRUPTED;
451 /* can't trust fd's and stuff so we need to re-create them */
456 "client_write(%d bytes) select failed: %s (%d)",
457 nbytes - bytes_written,
458 strerror(errno), errno
462 Ctx->kill_me = KILLME_SELECT_FAILED;
468 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
471 "client_write(%d bytes) failed: %s (%d)",
472 nbytes - bytes_written,
473 strerror(errno), errno
477 Ctx->kill_me = KILLME_WRITE_FAILED;
480 bytes_written = bytes_written + retval;
485 void cputbuf(const StrBuf *Buf) {
486 client_write(ChrPtr(Buf), StrLength(Buf));
491 * cprintf() Send formatted printable data to the client.
492 * Implemented in terms of client_write() so it's technically not sysdep...
494 void cprintf(const char *format, ...) {
498 va_start(arg_ptr, format);
499 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
500 buf[sizeof buf - 2] = '\n';
501 client_write(buf, strlen(buf));
507 * Read data from the client socket.
509 * sock socket fd to read from
510 * buf buffer to read into
511 * bytes number of bytes to read
512 * timeout Number of seconds to wait before timing out
514 * Possible return values:
515 * 1 Requested number of bytes has been read.
516 * 0 Request timed out.
517 * -1 Connection is broken, or other error.
519 int client_read_blob(StrBuf *Target, int bytes, int timeout)
526 if (CCC->redirect_ssl) {
532 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
534 fd = fopen(fn, "a+");
536 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
540 fprintf(fd, "Reading BLOB: BufSize: %d ",
542 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
548 retval = client_read_sslblob(Target, bytes, timeout);
550 syslog(LOG_CRIT, "client_read_blob() failed");
553 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
555 fd = fopen(fn, "a+");
557 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
561 fprintf(fd, "Read: %d BufContent: [",
563 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
578 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
580 fd = fopen(fn, "a+");
582 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
586 fprintf(fd, "Reading BLOB: BufSize: %d ",
588 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
594 retval = StrBufReadBLOBBuffered(Target,
596 &CCC->RecvBuf.ReadWritePointer,
603 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
608 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
610 fd = fopen(fn, "a+");
612 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
616 fprintf(fd, "Read: %d BufContent: [",
618 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
628 * to make client_read_random_blob() more efficient, increase buffer size.
629 * just use in greeting function, else your buffer may be flushed
631 void client_set_inbound_buf(long N)
634 FlushStrBuf(CCC->RecvBuf.Buf);
635 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
638 int client_read_random_blob(StrBuf *Target, int timeout)
643 rc = client_read_blob(Target, 1, timeout);
649 len = StrLength(CCC->RecvBuf.Buf);
650 pch = ChrPtr(CCC->RecvBuf.Buf);
654 if (CCC->RecvBuf.ReadWritePointer != NULL) {
655 len -= CCC->RecvBuf.ReadWritePointer - pch;
656 pch = CCC->RecvBuf.ReadWritePointer;
658 StrBufAppendBufPlain(Target, pch, len, 0);
659 FlushStrBuf(CCC->RecvBuf.Buf);
660 CCC->RecvBuf.ReadWritePointer = NULL;
667 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
669 fd = fopen(fn, "a+");
671 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
675 fprintf(fd, "Read: BufSize: %d BufContent: [",
677 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
685 return StrLength(Target);
693 int client_read_to(char *buf, int bytes, int timeout)
698 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
707 ChrPtr(CCC->MigrateBuf),
708 StrLength(CCC->MigrateBuf) + 1);
709 FlushStrBuf(CCC->MigrateBuf);
715 int HaveMoreLinesWaiting(CitContext *CCC)
717 if ((CCC->kill_me != 0) ||
718 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
719 (StrLength(CCC->RecvBuf.Buf) == 0) &&
720 (CCC->client_socket != -1)) )
728 * Read data from the client socket with default timeout.
729 * (This is implemented in terms of client_read_to() and could be
730 * justifiably moved out of sysdep.c)
732 INLINE int client_read(char *buf, int bytes)
734 return(client_read_to(buf, bytes, config.c_sleeping));
737 int CtdlClientGetLine(StrBuf *Target)
745 if (CCC->redirect_ssl) {
755 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
757 fd = fopen(fn, "a+");
759 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
763 pch = ChrPtr(CCC->RecvBuf.Buf);
764 len = StrLength(CCC->RecvBuf.Buf);
765 if (CCC->RecvBuf.ReadWritePointer != NULL)
766 rlen = CCC->RecvBuf.ReadWritePointer - pch;
770 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
773 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
776 rc = client_readline_sslbuffer(Target,
778 &CCC->RecvBuf.ReadWritePointer,
781 pch = ChrPtr(CCC->RecvBuf.Buf);
782 nlen = StrLength(CCC->RecvBuf.Buf);
783 if (CCC->RecvBuf.ReadWritePointer != NULL)
784 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
788 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
789 len, nlen, rlen, nrlen, pch);
791 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
792 len, nlen, rlen, nrlen);
794 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
795 StrLength(Target), ChrPtr(Target));
799 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
810 int len, rlen, nlen, nrlen;
813 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
815 fd = fopen(fn, "a+");
817 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
821 pch = ChrPtr(CCC->RecvBuf.Buf);
822 len = StrLength(CCC->RecvBuf.Buf);
823 if (CCC->RecvBuf.ReadWritePointer != NULL)
824 rlen = CCC->RecvBuf.ReadWritePointer - pch;
828 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
831 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
834 rc = StrBufTCP_read_buffered_line_fast(Target,
836 &CCC->RecvBuf.ReadWritePointer,
843 pch = ChrPtr(CCC->RecvBuf.Buf);
844 nlen = StrLength(CCC->RecvBuf.Buf);
845 if (CCC->RecvBuf.ReadWritePointer != NULL)
846 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
850 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
851 len, nlen, rlen, nrlen, pch);
853 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
854 len, nlen, rlen, nrlen);
856 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
857 StrLength(Target), ChrPtr(Target));
860 if ((rc < 0) && (Error != NULL)) {
861 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
870 * client_getln() ... Get a LF-terminated line of text from the client.
871 * (This is implemented in terms of client_read() and could be
872 * justifiably moved out of sysdep.c)
874 int client_getln(char *buf, int bufsize)
880 retval = CtdlClientGetLine(CCC->MigrateBuf);
885 i = StrLength(CCC->MigrateBuf);
886 pCh = ChrPtr(CCC->MigrateBuf);
887 /* Strip the trailing LF, and the trailing CR if present.
892 && ( (pCh[i - 1]==13)
893 || ( pCh[i - 1]==10)) ) {
899 FlushStrBuf(CCC->MigrateBuf);
901 safestrncpy(&buf[i], "000", bufsize - i);
908 * Cleanup any contexts that are left lying around
912 void close_masters (void)
914 struct ServiceFunctionHook *serviceptr;
918 * close all protocol master sockets
920 for (serviceptr = ServiceHookTable; serviceptr != NULL;
921 serviceptr = serviceptr->next ) {
923 if (serviceptr->tcp_port > 0)
925 if (serviceptr->msock == -1)
926 Text = "not closing again";
930 syslog(LOG_INFO, "%s %d listener on port %d\n",
933 serviceptr->tcp_port);
934 serviceptr->tcp_port = 0;
937 if (serviceptr->sockpath != NULL)
939 if (serviceptr->msock == -1)
940 Text = "not closing again";
944 syslog(LOG_INFO, "%s %d listener on '%s'\n",
947 serviceptr->sockpath);
950 if (serviceptr->msock != -1)
952 close(serviceptr->msock);
953 serviceptr->msock = -1;
956 /* If it's a Unix domain socket, remove the file. */
957 if (serviceptr->sockpath != NULL) {
958 unlink(serviceptr->sockpath);
959 serviceptr->sockpath = NULL;
966 * The system-dependent part of master_cleanup() - close the master socket.
968 void sysdep_master_cleanup(void) {
977 CtdlDestroyProtoHooks();
978 CtdlDestroyDeleteHooks();
979 CtdlDestroyXmsgHooks();
980 CtdlDestroyNetprocHooks();
981 CtdlDestroyUserHooks();
982 CtdlDestroyMessageHook();
983 CtdlDestroyCleanupHooks();
984 CtdlDestroyFixedOutputHooks();
985 CtdlDestroySessionHooks();
986 CtdlDestroyTDAPVetoHooks();
987 CtdlDestroyServiceHook();
988 CtdlDestroyRoomHooks();
989 CtdlDestroySearchHooks();
990 CtdlDestroyDebugTable();
991 #ifdef HAVE_BACKTRACE
999 void graceful_shutdown(int signum) {
1000 kill(current_child, signum);
1001 unlink(file_pid_file);
1006 int nFireUpsNonRestart = 0;
1007 pid_t ForkedPid = 1;
1010 * Start running as a daemon.
1012 void start_daemon(int unused) {
1020 /* Close stdin/stdout/stderr and replace them with /dev/null.
1021 * We don't just call close() because we don't want these fd's
1022 * to be reused for other files.
1024 if (chdir(ctdl_run_dir) != 0)
1026 "unable to change into directory [%s]: %s",
1027 ctdl_run_dir, strerror(errno));
1034 signal(SIGHUP, SIG_IGN);
1035 signal(SIGINT, SIG_IGN);
1036 signal(SIGQUIT, SIG_IGN);
1040 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1041 (freopen("/dev/null", "w", stdout) != stdout) ||
1042 (freopen("/dev/null", "w", stderr) != stderr))
1044 "unable to reopen stdin/out/err %s",
1049 current_child = fork();
1051 signal(SIGTERM, graceful_shutdown);
1053 if (current_child < 0) {
1058 else if (current_child == 0) {
1059 return; /* continue starting citadel. */
1063 fp = fopen(file_pid_file, "w");
1065 fprintf(fp, ""F_PID_T"\n", getpid());
1068 waitpid(current_child, &status, 0);
1071 nFireUpsNonRestart = nFireUps;
1073 /* Exit code 0 means the watcher should exit */
1074 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1078 /* Exit code 101-109 means the watcher should exit */
1079 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1083 /* Any other exit code, or no exit code, means we should restart. */
1087 ForkedPid = current_child;
1090 } while (do_restart);
1092 unlink(file_pid_file);
1093 exit(WEXITSTATUS(status));
1098 void checkcrash(void)
1100 if (nFireUpsNonRestart != nFireUps)
1103 const char *msgs[1] = {"crash"};
1104 const long lens[1] = {sizeof("crash") - 1};
1105 CrashMail = NewStrBuf();
1106 syslog(LOG_ALERT, "Posting crash message\n");
1107 StrBufPrintf(CrashMail,
1109 " The Citadel server process (citserver) terminated unexpectedly."
1111 " This could be the result of a bug in the server program, or some external "
1113 " You can obtain more information about this by enabling core dumps.\n \n"
1114 " For more information, please see:\n \n"
1115 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1118 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1120 ctdl_run_dir, ForkedPid);
1121 CtdlAideFPMessage(ChrPtr(CrashMail),
1122 "Citadel server process terminated unexpectedly",
1126 FreeStrBuf(&CrashMail);
1132 * Generic routine to convert a login name to a full name (gecos)
1133 * Returns nonzero if a conversion took place
1135 int convert_login(char NameToConvert[]) {
1139 pw = getpwnam(NameToConvert);
1144 strcpy(NameToConvert, pw->pw_gecos);
1145 for (a=0; a<strlen(NameToConvert); ++a) {
1146 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1154 void HuntBadSession(void)
1160 struct ServiceFunctionHook *serviceptr;
1164 /* Next, add all of the client sockets. */
1165 begin_critical_section(S_SESSION_TABLE);
1166 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1167 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1169 /* Initialize the fdset. */
1172 tv.tv_sec = 0; /* wake up every second if no input */
1175 /* Don't select on dead sessions, only truly idle ones */
1176 if ( (ptr->state == CON_IDLE)
1177 && (ptr->kill_me == 0)
1178 && (ptr->client_socket > 0)
1180 FD_SET(ptr->client_socket, &readfds);
1181 if (ptr->client_socket > highest)
1182 highest = ptr->client_socket;
1184 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1189 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1192 ptr->is_local_socket,
1194 ptr->cs_host,ptr->cs_addr);
1197 ptr->client_socket = -1;
1203 end_critical_section(S_SESSION_TABLE);
1206 /* First, add the various master sockets to the fdset. */
1207 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1209 /* Initialize the fdset. */
1211 tv.tv_sec = 0; /* wake up every second if no input */
1214 FD_SET(serviceptr->msock, &readfds);
1215 if (serviceptr->msock > highest) {
1216 highest = serviceptr->msock;
1218 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1221 /* Gotcha! server socket dead? commit suicide! */
1223 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1226 server_shutting_down = 1;
1234 const char *WorkerLogStr = "W";
1236 * This loop just keeps going and going and going...
1238 void *worker_thread(void *blah) {
1241 CitContext *bind_me = NULL;
1245 int force_purge = 0;
1246 struct ServiceFunctionHook *serviceptr;
1247 int ssock; /* Descriptor for client socket */
1248 CitContext *con = NULL; /* Temporary context pointer */
1251 pthread_mutex_lock(&ThreadCountMutex);
1253 pthread_mutex_unlock(&ThreadCountMutex);
1255 pthread_setspecific(evConKey, WorkerLogStr);
1257 while (!server_shutting_down) {
1259 /* make doubly sure we're not holding any stale db handles
1260 * which might cause a deadlock.
1262 cdb_check_handles();
1263 do_select: force_purge = 0;
1264 bind_me = NULL; /* Which session shall we handle? */
1266 /* Initialize the fdset. */
1270 /* First, add the various master sockets to the fdset. */
1271 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1272 FD_SET(serviceptr->msock, &readfds);
1273 if (serviceptr->msock > highest) {
1274 highest = serviceptr->msock;
1278 /* Next, add all of the client sockets. */
1279 begin_critical_section(S_SESSION_TABLE);
1280 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1281 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1284 /* Don't select on dead sessions, only truly idle ones */
1285 if ( (ptr->state == CON_IDLE)
1286 && (ptr->kill_me == 0)
1287 && (ptr->client_socket > 0)
1289 FD_SET(ptr->client_socket, &readfds);
1290 if (ptr->client_socket > highest)
1291 highest = ptr->client_socket;
1293 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1295 ptr->state = CON_EXECUTING;
1298 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1300 ptr->state = CON_STARTING;
1304 end_critical_section(S_SESSION_TABLE);
1310 /* If we got this far, it means that there are no sessions
1311 * which a previous thread marked for attention, so we go
1312 * ahead and get ready to select().
1315 if (!server_shutting_down) {
1316 tv.tv_sec = 1; /* wake up every second if no input */
1318 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1325 /* Now figure out who made this select() unblock.
1326 * First, check for an error or exit condition.
1329 if (errno == EBADF) {
1330 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1334 if (errno != EINTR) {
1335 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1336 server_shutting_down = 1;
1340 syslog(LOG_DEBUG, "Interrupted select()\n");
1342 if (server_shutting_down) {
1349 else if (retval == 0) {
1350 if (server_shutting_down) {
1356 /* Next, check to see if it's a new client connecting * on a master socket. */
1358 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1360 if (FD_ISSET(serviceptr->msock, &readfds)) {
1361 ssock = accept(serviceptr->msock, NULL, 0);
1363 syslog(LOG_DEBUG, "New client socket %d", ssock);
1365 /* The master socket is non-blocking but the client
1366 * sockets need to be blocking, otherwise certain
1367 * operations barf on FreeBSD. Not a fatal error.
1369 if (fcntl(ssock, F_SETFL, 0) < 0) {
1371 "citserver: Can't set socket to blocking: %s\n",
1375 /* New context will be created already
1376 * set up in the CON_EXECUTING state.
1378 con = CreateNewContext();
1380 /* Assign our new socket number to it. */
1381 con->tcp_port = serviceptr->tcp_port;
1382 con->client_socket = ssock;
1383 con->h_command_function = serviceptr->h_command_function;
1384 con->h_async_function = serviceptr->h_async_function;
1385 con->h_greeting_function = serviceptr->h_greeting_function;
1386 con->ServiceName = serviceptr->ServiceName;
1388 /* Determine whether it's a local socket */
1389 if (serviceptr->sockpath != NULL) {
1390 con->is_local_socket = 1;
1393 /* Set the SO_REUSEADDR socket option */
1395 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1396 con->state = CON_GREETING;
1404 /* It must be a client socket. Find a context that has data
1405 * waiting on its socket *and* is in the CON_IDLE state. Any
1406 * active sockets other than our chosen one are marked as
1407 * CON_READY so the next thread that comes around can just bind
1408 * to one without having to select() again.
1410 begin_critical_section(S_SESSION_TABLE);
1411 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1412 int checkfd = ptr->client_socket;
1413 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1414 if (FD_ISSET(checkfd, &readfds)) {
1415 ptr->input_waiting = 1;
1417 bind_me = ptr; /* I choose you! */
1418 bind_me->state = CON_EXECUTING;
1421 ptr->state = CON_READY;
1423 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1425 bind_me = ptr; /* I choose you! */
1426 bind_me->state = CON_EXECUTING;
1429 ptr->state = CON_READY;
1434 end_critical_section(S_SESSION_TABLE);
1437 /* We're bound to a session */
1438 pthread_mutex_lock(&ThreadCountMutex);
1440 pthread_mutex_unlock(&ThreadCountMutex);
1442 if (bind_me != NULL) {
1443 become_session(bind_me);
1445 if (bind_me->state == CON_STARTING) {
1446 bind_me->state = CON_EXECUTING;
1447 begin_session(bind_me);
1448 bind_me->h_greeting_function();
1450 /* If the client has sent a command, execute it. */
1451 if (CC->input_waiting) {
1452 CC->h_command_function();
1454 while (HaveMoreLinesWaiting(CC))
1455 CC->h_command_function();
1457 CC->input_waiting = 0;
1460 /* If there are asynchronous messages waiting and the
1461 * client supports it, do those now */
1462 if ((CC->is_async) && (CC->async_waiting)
1463 && (CC->h_async_function != NULL)) {
1464 CC->h_async_function();
1465 CC->async_waiting = 0;
1468 force_purge = CC->kill_me;
1469 become_session(NULL);
1470 bind_me->state = CON_IDLE;
1473 dead_session_purge(force_purge);
1476 pthread_mutex_lock(&ThreadCountMutex);
1478 if ((active_workers + config.c_min_workers < num_workers) &&
1479 (num_workers > config.c_min_workers))
1482 pthread_mutex_unlock(&ThreadCountMutex);
1485 pthread_mutex_unlock(&ThreadCountMutex);
1488 /* If control reaches this point, the server is shutting down */
1489 pthread_mutex_lock(&ThreadCountMutex);
1491 pthread_mutex_unlock(&ThreadCountMutex);
1499 * Translate text facility name to syslog.h defined value.
1501 int SyslogFacility(char *name)
1510 { LOG_KERN, "kern" },
1511 { LOG_USER, "user" },
1512 { LOG_MAIL, "mail" },
1513 { LOG_DAEMON, "daemon" },
1514 { LOG_AUTH, "auth" },
1515 { LOG_SYSLOG, "syslog" },
1517 { LOG_NEWS, "news" },
1518 { LOG_UUCP, "uucp" },
1519 { LOG_LOCAL0, "local0" },
1520 { LOG_LOCAL1, "local1" },
1521 { LOG_LOCAL2, "local2" },
1522 { LOG_LOCAL3, "local3" },
1523 { LOG_LOCAL4, "local4" },
1524 { LOG_LOCAL5, "local5" },
1525 { LOG_LOCAL6, "local6" },
1526 { LOG_LOCAL7, "local7" },
1529 for(i = 0; facTbl[i].name != NULL; i++) {
1530 if(!strcasecmp(name, facTbl[i].name))
1531 return facTbl[i].facility;