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.
28 #include <sys/types.h>
31 #include <sys/socket.h>
33 #include <sys/syslog.h>
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
40 # include <sys/time.h>
47 #include <sys/resource.h>
48 #include <netinet/in.h>
49 #include <netinet/tcp.h>
50 #include <arpa/inet.h>
58 #define SHOW_ME_VAPPEND_PRINTF
59 #include <libcitadel.h>
62 #include "sysdep_decls.h"
63 #include "citserver.h"
67 #include "housekeeping.h"
68 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
72 #ifdef HAVE_SYS_SELECT_H
73 #include <sys/select.h>
80 #include "ctdl_module.h"
87 * Signal handler to shut down the server.
90 volatile int exit_signal = 0;
91 volatile int shutdown_and_halt = 0;
92 volatile int restart_server = 0;
93 volatile int running_as_daemon = 0;
95 static RETSIGTYPE signal_cleanup(int signum) {
96 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
98 server_shutting_down = 1;
101 static RETSIGTYPE signal_exit(int signum) {
108 * Some initialization stuff...
110 void init_sysdep(void) {
113 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
117 getrlimit(RLIMIT_NOFILE, &rl);
118 rl.rlim_cur = FD_SETSIZE;
119 rl.rlim_max = FD_SETSIZE;
120 setrlimit(RLIMIT_NOFILE, &rl);
124 /* If we've got OpenSSL, we're going to use it. */
130 * Set up a place to put thread-specific data.
131 * We only need a single pointer per thread - it points to the
132 * CitContext structure (in the ContextList linked list) of the
133 * session to which the calling thread is currently bound.
135 if (pthread_key_create(&MyConKey, NULL) != 0) {
136 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
140 * Interript, hangup, and terminate signals should cause the server
141 * to gracefully clean up and shut down.
144 sigaddset(&set, SIGINT);
145 sigaddset(&set, SIGHUP);
146 sigaddset(&set, SIGTERM);
147 sigprocmask(SIG_UNBLOCK, &set, NULL);
149 signal(SIGINT, signal_cleanup);
150 signal(SIGHUP, signal_cleanup);
151 signal(SIGTERM, signal_cleanup);
152 signal(SIGUSR2, signal_exit);
155 * Do not shut down the server on broken pipe signals, otherwise the
156 * whole Citadel service would come down whenever a single client
159 signal(SIGPIPE, SIG_IGN);
164 * This is a generic function to set up a master socket for listening on
165 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
167 * ip_addr IP address to bind
168 * port_number port number to bind
169 * queue_len number of incoming connections to allow in the queue
171 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
174 struct sockaddr_in6 sin6;
175 struct sockaddr_in sin4;
179 memset(&sin6, 0, sizeof(sin6));
180 memset(&sin4, 0, sizeof(sin4));
181 sin6.sin6_family = AF_INET6;
182 sin4.sin_family = AF_INET;
184 if ( (ip_addr == NULL) /* any IPv6 */
185 || (IsEmptyStr(ip_addr))
186 || (!strcmp(ip_addr, "*"))
189 sin6.sin6_addr = in6addr_any;
191 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
194 sin4.sin_addr.s_addr = INADDR_ANY;
196 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
199 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
200 snprintf(errormessage, SIZ,
201 "Error binding to [%s] : %s", ip_addr, strerror(errno)
203 syslog(LOG_ALERT, "%s", errormessage);
207 else /* specific IPv6 */
210 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
211 snprintf(errormessage, SIZ,
212 "Error binding to [%s] : %s", ip_addr, strerror(errno)
214 syslog(LOG_ALERT, "%s", errormessage);
219 if (port_number == 0) {
220 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
221 syslog(LOG_ALERT, "%s", errormessage);
224 sin6.sin6_port = htons((u_short) port_number);
225 sin4.sin_port = htons((u_short) port_number);
227 p = getprotobyname("tcp");
229 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
231 snprintf(errormessage, SIZ,
232 "Can't create a listening socket: %s", strerror(errno)
234 syslog(LOG_ALERT, "%s", errormessage);
237 /* Set some socket options that make sense. */
239 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
241 if (ip_version == 6) {
242 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
245 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
249 snprintf(errormessage, SIZ,
250 "Can't bind: %s", strerror(errno)
252 syslog(LOG_ALERT, "%s", errormessage);
256 fcntl(s, F_SETFL, O_NONBLOCK);
258 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
259 snprintf(errormessage, SIZ,
260 "Can't listen: %s", strerror(errno)
262 syslog(LOG_ALERT, "%s", errormessage);
273 * Create a Unix domain socket and listen on it
275 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
277 struct sockaddr_un addr;
280 int actual_queue_len;
281 #ifdef HAVE_STRUCT_UCRED
285 actual_queue_len = queue_len;
286 if (actual_queue_len < 5) actual_queue_len = 5;
288 i = unlink(sockpath);
289 if ((i != 0) && (errno != ENOENT)) {
290 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
291 sockpath, strerror(errno)
293 syslog(LOG_EMERG, "%s", errormessage);
297 memset(&addr, 0, sizeof(addr));
298 addr.sun_family = AF_UNIX;
299 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
301 s = socket(AF_UNIX, SOCK_STREAM, 0);
303 snprintf(errormessage, SIZ,
304 "citserver: Can't create a socket: %s",
306 syslog(LOG_EMERG, "%s", errormessage);
310 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
311 snprintf(errormessage, SIZ,
312 "citserver: Can't bind: %s",
314 syslog(LOG_EMERG, "%s", errormessage);
318 /* set to nonblock - we need this for some obscure situations */
319 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
320 snprintf(errormessage, SIZ,
321 "citserver: Can't set socket to non-blocking: %s",
323 syslog(LOG_EMERG, "%s", errormessage);
328 if (listen(s, actual_queue_len) < 0) {
329 snprintf(errormessage, SIZ,
330 "citserver: Can't listen: %s",
332 syslog(LOG_EMERG, "%s", errormessage);
336 #ifdef HAVE_STRUCT_UCRED
337 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
340 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
347 * The following functions implement output buffering on operating systems which
348 * support it (such as Linux and various BSD flavors).
352 # define HAVE_TCP_BUFFERING
355 # define HAVE_TCP_BUFFERING
356 # define TCP_CORK TCP_NOPUSH
358 #endif /* TCP_CORK */
359 #endif /* HAVE_DARWIN */
361 static unsigned on = 1, off = 0;
363 void buffer_output(void) {
364 #ifdef HAVE_TCP_BUFFERING
366 if (!CC->redirect_ssl)
368 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
372 void unbuffer_output(void) {
373 #ifdef HAVE_TCP_BUFFERING
375 if (!CC->redirect_ssl)
377 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
381 void flush_output(void) {
382 #ifdef HAVE_TCP_BUFFERING
383 struct CitContext *CCC = CC;
384 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
385 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
390 static void flush_client_inbuf(void)
394 FlushStrBuf(CCC->ReadBuf);
395 CCC->RecvBuf->ReadWritePointer = NULL;
402 * client_close() ... close the client socket
404 void client_close(void) {
405 CitContext *CCC = CC;
408 if (CCC->client_socket <= 0) return;
409 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
411 close(CCC->client_socket);
412 CCC->client_socket = -1 ;
419 * client_write() ... Send binary data to the client.
421 int client_write(const char *buf, int nbytes)
423 int bytes_written = 0;
425 #ifndef HAVE_TCP_BUFFERING
426 int old_buffer_len = 0;
432 if (nbytes < 1) return(0);
442 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
444 fd = fopen(fn, "a+");
447 fprintf(fd, "Sending: BufSize: %d BufContent: [",
449 rv = fwrite(buf, nbytes, 1, fd);
455 // flush_client_inbuf();
456 if (Ctx->redirect_buffer != NULL) {
457 StrBufAppendBufPlain(Ctx->redirect_buffer,
463 if (Ctx->redirect_ssl) {
464 client_write_ssl(buf, nbytes);
468 if (Ctx->client_socket == -1) return -1;
470 fdflags = fcntl(Ctx->client_socket, F_GETFL);
472 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
473 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
475 FD_SET(Ctx->client_socket, &wset);
476 if (select(1, NULL, &wset, NULL, NULL) == -1) {
479 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
482 if (server_shutting_down) {
483 CC->kill_me = KILLME_SELECT_INTERRUPTED;
486 /* can't trust fd's and stuff so we need to re-create them */
491 "client_write(%d bytes) select failed: %s (%d)",
492 nbytes - bytes_written,
493 strerror(errno), errno
497 Ctx->kill_me = KILLME_SELECT_FAILED;
503 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
506 "client_write(%d bytes) failed: %s (%d)",
507 nbytes - bytes_written,
508 strerror(errno), errno
512 Ctx->kill_me = KILLME_WRITE_FAILED;
515 bytes_written = bytes_written + retval;
520 void cputbuf(const StrBuf *Buf) {
521 client_write(ChrPtr(Buf), StrLength(Buf));
526 * cprintf() Send formatted printable data to the client.
527 * Implemented in terms of client_write() so it's technically not sysdep...
529 void cprintf(const char *format, ...) {
533 va_start(arg_ptr, format);
534 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
535 buf[sizeof buf - 2] = '\n';
536 client_write(buf, strlen(buf));
542 * Read data from the client socket.
544 * sock socket fd to read from
545 * buf buffer to read into
546 * bytes number of bytes to read
547 * timeout Number of seconds to wait before timing out
549 * Possible return values:
550 * 1 Requested number of bytes has been read.
551 * 0 Request timed out.
552 * -1 Connection is broken, or other error.
554 int client_read_blob(StrBuf *Target, int bytes, int timeout)
561 if (CCC->redirect_ssl) {
567 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
569 fd = fopen(fn, "a+");
570 fprintf(fd, "Reading BLOB: BufSize: %d ",
572 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
578 retval = client_read_sslblob(Target, bytes, timeout);
580 syslog(LOG_CRIT, "client_read_blob() failed");
583 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
585 fd = fopen(fn, "a+");
586 fprintf(fd, "Read: %d BufContent: [",
588 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
603 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
605 fd = fopen(fn, "a+");
606 fprintf(fd, "Reading BLOB: BufSize: %d ",
608 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
614 retval = StrBufReadBLOBBuffered(Target,
616 &CCC->RecvBuf.ReadWritePointer,
623 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
628 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
630 fd = fopen(fn, "a+");
631 fprintf(fd, "Read: %d BufContent: [",
633 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
643 * to make client_read_random_blob() more efficient, increase buffer size.
644 * just use in greeting function, else your buffer may be flushed
646 void client_set_inbound_buf(long N)
649 FlushStrBuf(CCC->RecvBuf.Buf);
650 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
653 int client_read_random_blob(StrBuf *Target, int timeout)
658 rc = client_read_blob(Target, 1, timeout);
664 len = StrLength(CCC->RecvBuf.Buf);
665 pch = ChrPtr(CCC->RecvBuf.Buf);
669 if (CCC->RecvBuf.ReadWritePointer != NULL) {
670 len -= CCC->RecvBuf.ReadWritePointer - pch;
671 pch = CCC->RecvBuf.ReadWritePointer;
673 StrBufAppendBufPlain(Target, pch, len, 0);
674 FlushStrBuf(CCC->RecvBuf.Buf);
675 CCC->RecvBuf.ReadWritePointer = NULL;
682 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
684 fd = fopen(fn, "a+");
685 fprintf(fd, "Read: BufSize: %d BufContent: [",
687 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
695 return StrLength(Target);
703 int client_read_to(char *buf, int bytes, int timeout)
708 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
717 ChrPtr(CCC->MigrateBuf),
718 StrLength(CCC->MigrateBuf) + 1);
719 FlushStrBuf(CCC->MigrateBuf);
725 int HaveMoreLinesWaiting(CitContext *CCC)
727 if ((CCC->kill_me != 0) ||
728 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
729 (StrLength(CCC->RecvBuf.Buf) == 0) &&
730 (CCC->client_socket != -1)) )
738 * Read data from the client socket with default timeout.
739 * (This is implemented in terms of client_read_to() and could be
740 * justifiably moved out of sysdep.c)
742 INLINE int client_read(char *buf, int bytes)
744 return(client_read_to(buf, bytes, config.c_sleeping));
747 int CtdlClientGetLine(StrBuf *Target)
755 if (CCC->redirect_ssl) {
765 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
767 fd = fopen(fn, "a+");
768 pch = ChrPtr(CCC->RecvBuf.Buf);
769 len = StrLength(CCC->RecvBuf.Buf);
770 if (CCC->RecvBuf.ReadWritePointer != NULL)
771 rlen = CCC->RecvBuf.ReadWritePointer - pch;
775 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
778 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
781 rc = client_readline_sslbuffer(Target,
783 &CCC->RecvBuf.ReadWritePointer,
786 pch = ChrPtr(CCC->RecvBuf.Buf);
787 nlen = StrLength(CCC->RecvBuf.Buf);
788 if (CCC->RecvBuf.ReadWritePointer != NULL)
789 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
793 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
794 len, nlen, rlen, nrlen, pch);
796 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
797 len, nlen, rlen, nrlen);
799 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
800 StrLength(Target), ChrPtr(Target));
804 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
815 int len, rlen, nlen, nrlen;
818 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
820 fd = fopen(fn, "a+");
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;
917 * close all protocol master sockets
919 for (serviceptr = ServiceHookTable; serviceptr != NULL;
920 serviceptr = serviceptr->next ) {
922 if (serviceptr->tcp_port > 0)
924 syslog(LOG_INFO, "Closing %d listener on port %d\n",
926 serviceptr->tcp_port);
927 serviceptr->tcp_port = 0;
930 if (serviceptr->sockpath != NULL)
931 syslog(LOG_INFO, "Closing %d listener on '%s'\n",
933 serviceptr->sockpath);
934 if (serviceptr->msock != -1)
935 close(serviceptr->msock);
936 /* If it's a Unix domain socket, remove the file. */
937 if (serviceptr->sockpath != NULL) {
938 unlink(serviceptr->sockpath);
939 serviceptr->sockpath = NULL;
946 * The system-dependent part of master_cleanup() - close the master socket.
948 void sysdep_master_cleanup(void) {
957 CtdlDestroyProtoHooks();
958 CtdlDestroyDeleteHooks();
959 CtdlDestroyXmsgHooks();
960 CtdlDestroyNetprocHooks();
961 CtdlDestroyUserHooks();
962 CtdlDestroyMessageHook();
963 CtdlDestroyCleanupHooks();
964 CtdlDestroyFixedOutputHooks();
965 CtdlDestroySessionHooks();
966 CtdlDestroyServiceHook();
967 CtdlDestroyRoomHooks();
968 CtdlDestroySearchHooks();
969 CtdlDestroyDebugTable();
970 #ifdef HAVE_BACKTRACE
978 void graceful_shutdown(int signum) {
979 kill(current_child, signum);
980 unlink(file_pid_file);
985 int nFireUpsNonRestart = 0;
989 * Start running as a daemon.
991 void start_daemon(int unused) {
999 /* Close stdin/stdout/stderr and replace them with /dev/null.
1000 * We don't just call close() because we don't want these fd's
1001 * to be reused for other files.
1003 if (chdir(ctdl_run_dir) != 0)
1005 "unable to change into directory [%s]: %s",
1006 ctdl_run_dir, strerror(errno));
1013 signal(SIGHUP, SIG_IGN);
1014 signal(SIGINT, SIG_IGN);
1015 signal(SIGQUIT, SIG_IGN);
1019 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1020 (freopen("/dev/null", "w", stdout) != stdout) ||
1021 (freopen("/dev/null", "w", stderr) != stderr))
1023 "unable to reopen stdin/out/err %s",
1028 current_child = fork();
1030 signal(SIGTERM, graceful_shutdown);
1032 if (current_child < 0) {
1037 else if (current_child == 0) {
1038 return; /* continue starting citadel. */
1042 fp = fopen(file_pid_file, "w");
1044 fprintf(fp, ""F_PID_T"\n", getpid());
1047 waitpid(current_child, &status, 0);
1050 nFireUpsNonRestart = nFireUps;
1052 /* Exit code 0 means the watcher should exit */
1053 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1057 /* Exit code 101-109 means the watcher should exit */
1058 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1062 /* Any other exit code, or no exit code, means we should restart. */
1066 ForkedPid = current_child;
1069 } while (do_restart);
1071 unlink(file_pid_file);
1072 exit(WEXITSTATUS(status));
1077 void checkcrash(void)
1079 if (nFireUpsNonRestart != nFireUps)
1083 CrashMail = NewStrBuf();
1084 syslog(LOG_ALERT, "Posting crash message\n");
1085 StrBufPrintf(CrashMail,
1087 " The Citadel server process (citserver) terminated unexpectedly."
1089 " This could be the result of a bug in the server program, or some external "
1091 " You can obtain more information about this by enabling core dumps.\n \n"
1092 " For more information, please see:\n \n"
1093 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1096 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1098 ctdl_run_dir, ForkedPid);
1099 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1100 FreeStrBuf(&CrashMail);
1106 * Generic routine to convert a login name to a full name (gecos)
1107 * Returns nonzero if a conversion took place
1109 int convert_login(char NameToConvert[]) {
1113 pw = getpwnam(NameToConvert);
1118 strcpy(NameToConvert, pw->pw_gecos);
1119 for (a=0; a<strlen(NameToConvert); ++a) {
1120 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1129 * This loop just keeps going and going and going...
1131 void *worker_thread(void *blah) {
1134 CitContext *bind_me = NULL;
1138 int force_purge = 0;
1139 struct ServiceFunctionHook *serviceptr;
1140 int ssock; /* Descriptor for client socket */
1141 CitContext *con = NULL; /* Temporary context pointer */
1146 while (!server_shutting_down) {
1148 /* make doubly sure we're not holding any stale db handles
1149 * which might cause a deadlock.
1151 cdb_check_handles();
1152 do_select: force_purge = 0;
1153 bind_me = NULL; /* Which session shall we handle? */
1155 /* Initialize the fdset. */
1159 /* First, add the various master sockets to the fdset. */
1160 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1161 FD_SET(serviceptr->msock, &readfds);
1162 if (serviceptr->msock > highest) {
1163 highest = serviceptr->msock;
1167 /* Next, add all of the client sockets. */
1168 begin_critical_section(S_SESSION_TABLE);
1169 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1170 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1173 /* Don't select on dead sessions, only truly idle ones */
1174 if ( (ptr->state == CON_IDLE)
1175 && (ptr->kill_me == 0)
1176 && (ptr->client_socket > 0)
1178 FD_SET(ptr->client_socket, &readfds);
1179 if (ptr->client_socket > highest)
1180 highest = ptr->client_socket;
1182 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1184 ptr->state = CON_EXECUTING;
1187 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1189 ptr->state = CON_STARTING;
1193 end_critical_section(S_SESSION_TABLE);
1199 /* If we got this far, it means that there are no sessions
1200 * which a previous thread marked for attention, so we go
1201 * ahead and get ready to select().
1204 if (!server_shutting_down) {
1205 tv.tv_sec = 1; /* wake up every second if no input */
1207 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1214 /* Now figure out who made this select() unblock.
1215 * First, check for an error or exit condition.
1218 if (errno == EBADF) {
1219 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1222 if (errno != EINTR) {
1223 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1224 server_shutting_down = 1;
1228 syslog(LOG_DEBUG, "Interrupted select()\n");
1230 if (server_shutting_down) {
1237 else if (retval == 0) {
1238 if (server_shutting_down) {
1244 /* Next, check to see if it's a new client connecting * on a master socket. */
1246 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1248 if (FD_ISSET(serviceptr->msock, &readfds)) {
1249 ssock = accept(serviceptr->msock, NULL, 0);
1251 syslog(LOG_DEBUG, "New client socket %d", ssock);
1253 /* The master socket is non-blocking but the client
1254 * sockets need to be blocking, otherwise certain
1255 * operations barf on FreeBSD. Not a fatal error.
1257 if (fcntl(ssock, F_SETFL, 0) < 0) {
1259 "citserver: Can't set socket to blocking: %s\n",
1263 /* New context will be created already
1264 * set up in the CON_EXECUTING state.
1266 con = CreateNewContext();
1268 /* Assign our new socket number to it. */
1269 con->tcp_port = serviceptr->tcp_port;
1270 con->client_socket = ssock;
1271 con->h_command_function = serviceptr->h_command_function;
1272 con->h_async_function = serviceptr->h_async_function;
1273 con->h_greeting_function = serviceptr->h_greeting_function;
1274 con->ServiceName = serviceptr->ServiceName;
1276 /* Determine whether it's a local socket */
1277 if (serviceptr->sockpath != NULL) {
1278 con->is_local_socket = 1;
1281 /* Set the SO_REUSEADDR socket option */
1283 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1284 con->state = CON_GREETING;
1292 /* It must be a client socket. Find a context that has data
1293 * waiting on its socket *and* is in the CON_IDLE state. Any
1294 * active sockets other than our chosen one are marked as
1295 * CON_READY so the next thread that comes around can just bind
1296 * to one without having to select() again.
1298 begin_critical_section(S_SESSION_TABLE);
1299 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1300 int checkfd = ptr->client_socket;
1301 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1302 if (FD_ISSET(checkfd, &readfds)) {
1303 ptr->input_waiting = 1;
1305 bind_me = ptr; /* I choose you! */
1306 bind_me->state = CON_EXECUTING;
1309 ptr->state = CON_READY;
1311 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1313 bind_me = ptr; /* I choose you! */
1314 bind_me->state = CON_EXECUTING;
1317 ptr->state = CON_READY;
1322 end_critical_section(S_SESSION_TABLE);
1325 /* We're bound to a session */
1327 if (bind_me != NULL) {
1328 become_session(bind_me);
1330 if (bind_me->state == CON_STARTING) {
1331 bind_me->state = CON_EXECUTING;
1332 begin_session(bind_me);
1333 bind_me->h_greeting_function();
1335 /* If the client has sent a command, execute it. */
1336 if (CC->input_waiting) {
1337 CC->h_command_function();
1339 while (HaveMoreLinesWaiting(CC))
1340 CC->h_command_function();
1342 CC->input_waiting = 0;
1345 /* If there are asynchronous messages waiting and the
1346 * client supports it, do those now */
1347 if ((CC->is_async) && (CC->async_waiting)
1348 && (CC->h_async_function != NULL)) {
1349 CC->h_async_function();
1350 CC->async_waiting = 0;
1353 force_purge = CC->kill_me;
1354 become_session(NULL);
1355 bind_me->state = CON_IDLE;
1358 dead_session_purge(force_purge);
1363 /* If control reaches this point, the server is shutting down */
1372 * Translate text facility name to syslog.h defined value.
1374 int SyslogFacility(char *name)
1383 { LOG_KERN, "kern" },
1384 { LOG_USER, "user" },
1385 { LOG_MAIL, "mail" },
1386 { LOG_DAEMON, "daemon" },
1387 { LOG_AUTH, "auth" },
1388 { LOG_SYSLOG, "syslog" },
1390 { LOG_NEWS, "news" },
1391 { LOG_UUCP, "uucp" },
1392 { LOG_LOCAL0, "local0" },
1393 { LOG_LOCAL1, "local1" },
1394 { LOG_LOCAL2, "local2" },
1395 { LOG_LOCAL3, "local3" },
1396 { LOG_LOCAL4, "local4" },
1397 { LOG_LOCAL5, "local5" },
1398 { LOG_LOCAL6, "local6" },
1399 { LOG_LOCAL7, "local7" },
1402 for(i = 0; facTbl[i].name != NULL; i++) {
1403 if(!strcasecmp(name, facTbl[i].name))
1404 return facTbl[i].facility;