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+");
410 fprintf(fd, "Sending: BufSize: %d BufContent: [",
412 rv = fwrite(buf, nbytes, 1, fd);
418 // flush_client_inbuf();
419 if (Ctx->redirect_buffer != NULL) {
420 StrBufAppendBufPlain(Ctx->redirect_buffer,
426 if (Ctx->redirect_ssl) {
427 client_write_ssl(buf, nbytes);
431 if (Ctx->client_socket == -1) return -1;
433 fdflags = fcntl(Ctx->client_socket, F_GETFL);
435 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
436 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
438 FD_SET(Ctx->client_socket, &wset);
439 if (select(1, NULL, &wset, NULL, NULL) == -1) {
442 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
445 if (server_shutting_down) {
446 CC->kill_me = KILLME_SELECT_INTERRUPTED;
449 /* can't trust fd's and stuff so we need to re-create them */
454 "client_write(%d bytes) select failed: %s (%d)",
455 nbytes - bytes_written,
456 strerror(errno), errno
460 Ctx->kill_me = KILLME_SELECT_FAILED;
466 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
469 "client_write(%d bytes) failed: %s (%d)",
470 nbytes - bytes_written,
471 strerror(errno), errno
475 Ctx->kill_me = KILLME_WRITE_FAILED;
478 bytes_written = bytes_written + retval;
483 void cputbuf(const StrBuf *Buf) {
484 client_write(ChrPtr(Buf), StrLength(Buf));
489 * cprintf() Send formatted printable data to the client.
490 * Implemented in terms of client_write() so it's technically not sysdep...
492 void cprintf(const char *format, ...) {
496 va_start(arg_ptr, format);
497 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
498 buf[sizeof buf - 2] = '\n';
499 client_write(buf, strlen(buf));
505 * Read data from the client socket.
507 * sock socket fd to read from
508 * buf buffer to read into
509 * bytes number of bytes to read
510 * timeout Number of seconds to wait before timing out
512 * Possible return values:
513 * 1 Requested number of bytes has been read.
514 * 0 Request timed out.
515 * -1 Connection is broken, or other error.
517 int client_read_blob(StrBuf *Target, int bytes, int timeout)
524 if (CCC->redirect_ssl) {
530 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
532 fd = fopen(fn, "a+");
533 fprintf(fd, "Reading BLOB: BufSize: %d ",
535 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
541 retval = client_read_sslblob(Target, bytes, timeout);
543 syslog(LOG_CRIT, "client_read_blob() failed");
546 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
548 fd = fopen(fn, "a+");
549 fprintf(fd, "Read: %d BufContent: [",
551 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
566 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
568 fd = fopen(fn, "a+");
569 fprintf(fd, "Reading BLOB: BufSize: %d ",
571 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
577 retval = StrBufReadBLOBBuffered(Target,
579 &CCC->RecvBuf.ReadWritePointer,
586 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
591 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
593 fd = fopen(fn, "a+");
594 fprintf(fd, "Read: %d BufContent: [",
596 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
606 * to make client_read_random_blob() more efficient, increase buffer size.
607 * just use in greeting function, else your buffer may be flushed
609 void client_set_inbound_buf(long N)
612 FlushStrBuf(CCC->RecvBuf.Buf);
613 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
616 int client_read_random_blob(StrBuf *Target, int timeout)
621 rc = client_read_blob(Target, 1, timeout);
627 len = StrLength(CCC->RecvBuf.Buf);
628 pch = ChrPtr(CCC->RecvBuf.Buf);
632 if (CCC->RecvBuf.ReadWritePointer != NULL) {
633 len -= CCC->RecvBuf.ReadWritePointer - pch;
634 pch = CCC->RecvBuf.ReadWritePointer;
636 StrBufAppendBufPlain(Target, pch, len, 0);
637 FlushStrBuf(CCC->RecvBuf.Buf);
638 CCC->RecvBuf.ReadWritePointer = NULL;
645 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
647 fd = fopen(fn, "a+");
648 fprintf(fd, "Read: BufSize: %d BufContent: [",
650 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
658 return StrLength(Target);
666 int client_read_to(char *buf, int bytes, int timeout)
671 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
680 ChrPtr(CCC->MigrateBuf),
681 StrLength(CCC->MigrateBuf) + 1);
682 FlushStrBuf(CCC->MigrateBuf);
688 int HaveMoreLinesWaiting(CitContext *CCC)
690 if ((CCC->kill_me != 0) ||
691 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
692 (StrLength(CCC->RecvBuf.Buf) == 0) &&
693 (CCC->client_socket != -1)) )
701 * Read data from the client socket with default timeout.
702 * (This is implemented in terms of client_read_to() and could be
703 * justifiably moved out of sysdep.c)
705 INLINE int client_read(char *buf, int bytes)
707 return(client_read_to(buf, bytes, config.c_sleeping));
710 int CtdlClientGetLine(StrBuf *Target)
718 if (CCC->redirect_ssl) {
728 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
730 fd = fopen(fn, "a+");
731 pch = ChrPtr(CCC->RecvBuf.Buf);
732 len = StrLength(CCC->RecvBuf.Buf);
733 if (CCC->RecvBuf.ReadWritePointer != NULL)
734 rlen = CCC->RecvBuf.ReadWritePointer - pch;
738 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
741 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
744 rc = client_readline_sslbuffer(Target,
746 &CCC->RecvBuf.ReadWritePointer,
749 pch = ChrPtr(CCC->RecvBuf.Buf);
750 nlen = StrLength(CCC->RecvBuf.Buf);
751 if (CCC->RecvBuf.ReadWritePointer != NULL)
752 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
756 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
757 len, nlen, rlen, nrlen, pch);
759 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
760 len, nlen, rlen, nrlen);
762 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
763 StrLength(Target), ChrPtr(Target));
767 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
778 int len, rlen, nlen, nrlen;
781 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
783 fd = fopen(fn, "a+");
784 pch = ChrPtr(CCC->RecvBuf.Buf);
785 len = StrLength(CCC->RecvBuf.Buf);
786 if (CCC->RecvBuf.ReadWritePointer != NULL)
787 rlen = CCC->RecvBuf.ReadWritePointer - pch;
791 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
794 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
797 rc = StrBufTCP_read_buffered_line_fast(Target,
799 &CCC->RecvBuf.ReadWritePointer,
806 pch = ChrPtr(CCC->RecvBuf.Buf);
807 nlen = StrLength(CCC->RecvBuf.Buf);
808 if (CCC->RecvBuf.ReadWritePointer != NULL)
809 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
813 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
814 len, nlen, rlen, nrlen, pch);
816 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
817 len, nlen, rlen, nrlen);
819 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
820 StrLength(Target), ChrPtr(Target));
823 if ((rc < 0) && (Error != NULL)) {
824 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
833 * client_getln() ... Get a LF-terminated line of text from the client.
834 * (This is implemented in terms of client_read() and could be
835 * justifiably moved out of sysdep.c)
837 int client_getln(char *buf, int bufsize)
843 retval = CtdlClientGetLine(CCC->MigrateBuf);
848 i = StrLength(CCC->MigrateBuf);
849 pCh = ChrPtr(CCC->MigrateBuf);
850 /* Strip the trailing LF, and the trailing CR if present.
855 && ( (pCh[i - 1]==13)
856 || ( pCh[i - 1]==10)) ) {
862 FlushStrBuf(CCC->MigrateBuf);
864 safestrncpy(&buf[i], "000", bufsize - i);
871 * Cleanup any contexts that are left lying around
875 void close_masters (void)
877 struct ServiceFunctionHook *serviceptr;
881 * close all protocol master sockets
883 for (serviceptr = ServiceHookTable; serviceptr != NULL;
884 serviceptr = serviceptr->next ) {
886 if (serviceptr->tcp_port > 0)
888 if (serviceptr->msock == -1)
889 Text = "not closing again";
893 syslog(LOG_INFO, "%s %d listener on port %d\n",
896 serviceptr->tcp_port);
897 serviceptr->tcp_port = 0;
900 if (serviceptr->sockpath != NULL)
902 if (serviceptr->msock == -1)
903 Text = "not closing again";
907 syslog(LOG_INFO, "%s %d listener on '%s'\n",
910 serviceptr->sockpath);
913 if (serviceptr->msock != -1)
915 close(serviceptr->msock);
916 serviceptr->msock = -1;
919 /* If it's a Unix domain socket, remove the file. */
920 if (serviceptr->sockpath != NULL) {
921 unlink(serviceptr->sockpath);
922 serviceptr->sockpath = NULL;
929 * The system-dependent part of master_cleanup() - close the master socket.
931 void sysdep_master_cleanup(void) {
940 CtdlDestroyProtoHooks();
941 CtdlDestroyDeleteHooks();
942 CtdlDestroyXmsgHooks();
943 CtdlDestroyNetprocHooks();
944 CtdlDestroyUserHooks();
945 CtdlDestroyMessageHook();
946 CtdlDestroyCleanupHooks();
947 CtdlDestroyFixedOutputHooks();
948 CtdlDestroySessionHooks();
949 CtdlDestroyTDAPVetoHooks();
950 CtdlDestroyServiceHook();
951 CtdlDestroyRoomHooks();
952 CtdlDestroySearchHooks();
953 CtdlDestroyDebugTable();
954 #ifdef HAVE_BACKTRACE
962 void graceful_shutdown(int signum) {
963 kill(current_child, signum);
964 unlink(file_pid_file);
969 int nFireUpsNonRestart = 0;
973 * Start running as a daemon.
975 void start_daemon(int unused) {
983 /* Close stdin/stdout/stderr and replace them with /dev/null.
984 * We don't just call close() because we don't want these fd's
985 * to be reused for other files.
987 if (chdir(ctdl_run_dir) != 0)
989 "unable to change into directory [%s]: %s",
990 ctdl_run_dir, strerror(errno));
997 signal(SIGHUP, SIG_IGN);
998 signal(SIGINT, SIG_IGN);
999 signal(SIGQUIT, SIG_IGN);
1003 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1004 (freopen("/dev/null", "w", stdout) != stdout) ||
1005 (freopen("/dev/null", "w", stderr) != stderr))
1007 "unable to reopen stdin/out/err %s",
1012 current_child = fork();
1014 signal(SIGTERM, graceful_shutdown);
1016 if (current_child < 0) {
1021 else if (current_child == 0) {
1022 return; /* continue starting citadel. */
1026 fp = fopen(file_pid_file, "w");
1028 fprintf(fp, ""F_PID_T"\n", getpid());
1031 waitpid(current_child, &status, 0);
1034 nFireUpsNonRestart = nFireUps;
1036 /* Exit code 0 means the watcher should exit */
1037 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1041 /* Exit code 101-109 means the watcher should exit */
1042 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1046 /* Any other exit code, or no exit code, means we should restart. */
1050 ForkedPid = current_child;
1053 } while (do_restart);
1055 unlink(file_pid_file);
1056 exit(WEXITSTATUS(status));
1061 void checkcrash(void)
1063 if (nFireUpsNonRestart != nFireUps)
1067 CrashMail = NewStrBuf();
1068 syslog(LOG_ALERT, "Posting crash message\n");
1069 StrBufPrintf(CrashMail,
1071 " The Citadel server process (citserver) terminated unexpectedly."
1073 " This could be the result of a bug in the server program, or some external "
1075 " You can obtain more information about this by enabling core dumps.\n \n"
1076 " For more information, please see:\n \n"
1077 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1080 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1082 ctdl_run_dir, ForkedPid);
1083 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1084 FreeStrBuf(&CrashMail);
1090 * Generic routine to convert a login name to a full name (gecos)
1091 * Returns nonzero if a conversion took place
1093 int convert_login(char NameToConvert[]) {
1097 pw = getpwnam(NameToConvert);
1102 strcpy(NameToConvert, pw->pw_gecos);
1103 for (a=0; a<strlen(NameToConvert); ++a) {
1104 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1112 void HuntBadSession(void)
1118 struct ServiceFunctionHook *serviceptr;
1122 /* Next, add all of the client sockets. */
1123 begin_critical_section(S_SESSION_TABLE);
1124 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1125 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1127 /* Initialize the fdset. */
1130 tv.tv_sec = 0; /* wake up every second if no input */
1133 /* Don't select on dead sessions, only truly idle ones */
1134 if ( (ptr->state == CON_IDLE)
1135 && (ptr->kill_me == 0)
1136 && (ptr->client_socket > 0)
1138 FD_SET(ptr->client_socket, &readfds);
1139 if (ptr->client_socket > highest)
1140 highest = ptr->client_socket;
1142 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1147 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1150 ptr->is_local_socket,
1152 ptr->cs_host,ptr->cs_addr);
1155 ptr->client_socket = -1;
1161 end_critical_section(S_SESSION_TABLE);
1164 /* First, add the various master sockets to the fdset. */
1165 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1167 /* Initialize the fdset. */
1169 tv.tv_sec = 0; /* wake up every second if no input */
1172 FD_SET(serviceptr->msock, &readfds);
1173 if (serviceptr->msock > highest) {
1174 highest = serviceptr->msock;
1176 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1179 /* Gotcha! server socket dead? commit suicide! */
1181 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1184 server_shutting_down = 1;
1192 const char *WorkerLogStr = "W";
1194 * This loop just keeps going and going and going...
1196 void *worker_thread(void *blah) {
1199 CitContext *bind_me = NULL;
1203 int force_purge = 0;
1204 struct ServiceFunctionHook *serviceptr;
1205 int ssock; /* Descriptor for client socket */
1206 CitContext *con = NULL; /* Temporary context pointer */
1209 pthread_mutex_lock(&ThreadCountMutex);
1211 pthread_mutex_unlock(&ThreadCountMutex);
1213 pthread_setspecific(evConKey, WorkerLogStr);
1215 while (!server_shutting_down) {
1217 /* make doubly sure we're not holding any stale db handles
1218 * which might cause a deadlock.
1220 cdb_check_handles();
1221 do_select: force_purge = 0;
1222 bind_me = NULL; /* Which session shall we handle? */
1224 /* Initialize the fdset. */
1228 /* First, add the various master sockets to the fdset. */
1229 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1230 FD_SET(serviceptr->msock, &readfds);
1231 if (serviceptr->msock > highest) {
1232 highest = serviceptr->msock;
1236 /* Next, add all of the client sockets. */
1237 begin_critical_section(S_SESSION_TABLE);
1238 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1239 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1242 /* Don't select on dead sessions, only truly idle ones */
1243 if ( (ptr->state == CON_IDLE)
1244 && (ptr->kill_me == 0)
1245 && (ptr->client_socket > 0)
1247 FD_SET(ptr->client_socket, &readfds);
1248 if (ptr->client_socket > highest)
1249 highest = ptr->client_socket;
1251 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1253 ptr->state = CON_EXECUTING;
1256 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1258 ptr->state = CON_STARTING;
1262 end_critical_section(S_SESSION_TABLE);
1268 /* If we got this far, it means that there are no sessions
1269 * which a previous thread marked for attention, so we go
1270 * ahead and get ready to select().
1273 if (!server_shutting_down) {
1274 tv.tv_sec = 1; /* wake up every second if no input */
1276 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1283 /* Now figure out who made this select() unblock.
1284 * First, check for an error or exit condition.
1287 if (errno == EBADF) {
1288 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1292 if (errno != EINTR) {
1293 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1294 server_shutting_down = 1;
1298 syslog(LOG_DEBUG, "Interrupted select()\n");
1300 if (server_shutting_down) {
1307 else if (retval == 0) {
1308 if (server_shutting_down) {
1314 /* Next, check to see if it's a new client connecting * on a master socket. */
1316 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1318 if (FD_ISSET(serviceptr->msock, &readfds)) {
1319 ssock = accept(serviceptr->msock, NULL, 0);
1321 syslog(LOG_DEBUG, "New client socket %d", ssock);
1323 /* The master socket is non-blocking but the client
1324 * sockets need to be blocking, otherwise certain
1325 * operations barf on FreeBSD. Not a fatal error.
1327 if (fcntl(ssock, F_SETFL, 0) < 0) {
1329 "citserver: Can't set socket to blocking: %s\n",
1333 /* New context will be created already
1334 * set up in the CON_EXECUTING state.
1336 con = CreateNewContext();
1338 /* Assign our new socket number to it. */
1339 con->tcp_port = serviceptr->tcp_port;
1340 con->client_socket = ssock;
1341 con->h_command_function = serviceptr->h_command_function;
1342 con->h_async_function = serviceptr->h_async_function;
1343 con->h_greeting_function = serviceptr->h_greeting_function;
1344 con->ServiceName = serviceptr->ServiceName;
1346 /* Determine whether it's a local socket */
1347 if (serviceptr->sockpath != NULL) {
1348 con->is_local_socket = 1;
1351 /* Set the SO_REUSEADDR socket option */
1353 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1354 con->state = CON_GREETING;
1362 /* It must be a client socket. Find a context that has data
1363 * waiting on its socket *and* is in the CON_IDLE state. Any
1364 * active sockets other than our chosen one are marked as
1365 * CON_READY so the next thread that comes around can just bind
1366 * to one without having to select() again.
1368 begin_critical_section(S_SESSION_TABLE);
1369 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1370 int checkfd = ptr->client_socket;
1371 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1372 if (FD_ISSET(checkfd, &readfds)) {
1373 ptr->input_waiting = 1;
1375 bind_me = ptr; /* I choose you! */
1376 bind_me->state = CON_EXECUTING;
1379 ptr->state = CON_READY;
1381 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1383 bind_me = ptr; /* I choose you! */
1384 bind_me->state = CON_EXECUTING;
1387 ptr->state = CON_READY;
1392 end_critical_section(S_SESSION_TABLE);
1395 /* We're bound to a session */
1396 pthread_mutex_lock(&ThreadCountMutex);
1398 pthread_mutex_unlock(&ThreadCountMutex);
1400 if (bind_me != NULL) {
1401 become_session(bind_me);
1403 if (bind_me->state == CON_STARTING) {
1404 bind_me->state = CON_EXECUTING;
1405 begin_session(bind_me);
1406 bind_me->h_greeting_function();
1408 /* If the client has sent a command, execute it. */
1409 if (CC->input_waiting) {
1410 CC->h_command_function();
1412 while (HaveMoreLinesWaiting(CC))
1413 CC->h_command_function();
1415 CC->input_waiting = 0;
1418 /* If there are asynchronous messages waiting and the
1419 * client supports it, do those now */
1420 if ((CC->is_async) && (CC->async_waiting)
1421 && (CC->h_async_function != NULL)) {
1422 CC->h_async_function();
1423 CC->async_waiting = 0;
1426 force_purge = CC->kill_me;
1427 become_session(NULL);
1428 bind_me->state = CON_IDLE;
1431 dead_session_purge(force_purge);
1434 pthread_mutex_lock(&ThreadCountMutex);
1436 if ((active_workers + config.c_min_workers < num_workers) &&
1437 (num_workers > config.c_min_workers))
1440 pthread_mutex_unlock(&ThreadCountMutex);
1443 pthread_mutex_unlock(&ThreadCountMutex);
1446 /* If control reaches this point, the server is shutting down */
1447 pthread_mutex_lock(&ThreadCountMutex);
1449 pthread_mutex_unlock(&ThreadCountMutex);
1457 * Translate text facility name to syslog.h defined value.
1459 int SyslogFacility(char *name)
1468 { LOG_KERN, "kern" },
1469 { LOG_USER, "user" },
1470 { LOG_MAIL, "mail" },
1471 { LOG_DAEMON, "daemon" },
1472 { LOG_AUTH, "auth" },
1473 { LOG_SYSLOG, "syslog" },
1475 { LOG_NEWS, "news" },
1476 { LOG_UUCP, "uucp" },
1477 { LOG_LOCAL0, "local0" },
1478 { LOG_LOCAL1, "local1" },
1479 { LOG_LOCAL2, "local2" },
1480 { LOG_LOCAL3, "local3" },
1481 { LOG_LOCAL4, "local4" },
1482 { LOG_LOCAL5, "local5" },
1483 { LOG_LOCAL6, "local6" },
1484 { LOG_LOCAL7, "local7" },
1487 for(i = 0; facTbl[i].name != NULL; i++) {
1488 if(!strcasecmp(name, facTbl[i].name))
1489 return facTbl[i].facility;