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 as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <sys/syslog.h>
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
46 # include <sys/time.h>
53 #include <sys/resource.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
64 #define SHOW_ME_VAPPEND_PRINTF
65 #include <libcitadel.h>
68 #include "sysdep_decls.h"
69 #include "citserver.h"
73 #include "housekeeping.h"
74 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
78 #ifdef HAVE_SYS_SELECT_H
79 #include <sys/select.h>
86 #include "ctdl_module.h"
93 * Signal handler to shut down the server.
96 volatile int exit_signal = 0;
97 volatile int shutdown_and_halt = 0;
98 volatile int restart_server = 0;
99 volatile int running_as_daemon = 0;
101 static RETSIGTYPE signal_cleanup(int signum) {
102 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
103 exit_signal = signum;
104 server_shutting_down = 1;
107 static RETSIGTYPE signal_exit(int signum) {
114 * Some initialization stuff...
116 void init_sysdep(void) {
119 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
123 getrlimit(RLIMIT_NOFILE, &rl);
124 rl.rlim_cur = FD_SETSIZE;
125 rl.rlim_max = FD_SETSIZE;
126 setrlimit(RLIMIT_NOFILE, &rl);
130 /* If we've got OpenSSL, we're going to use it. */
136 * Set up a place to put thread-specific data.
137 * We only need a single pointer per thread - it points to the
138 * CitContext structure (in the ContextList linked list) of the
139 * session to which the calling thread is currently bound.
141 if (pthread_key_create(&MyConKey, NULL) != 0) {
142 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
146 * Interript, hangup, and terminate signals should cause the server
147 * to gracefully clean up and shut down.
150 sigaddset(&set, SIGINT);
151 sigaddset(&set, SIGHUP);
152 sigaddset(&set, SIGTERM);
153 sigprocmask(SIG_UNBLOCK, &set, NULL);
155 signal(SIGINT, signal_cleanup);
156 signal(SIGHUP, signal_cleanup);
157 signal(SIGTERM, signal_cleanup);
158 signal(SIGUSR2, signal_exit);
161 * Do not shut down the server on broken pipe signals, otherwise the
162 * whole Citadel service would come down whenever a single client
165 signal(SIGPIPE, SIG_IGN);
170 * This is a generic function to set up a master socket for listening on
171 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
173 * ip_addr IP address to bind
174 * port_number port number to bind
175 * queue_len number of incoming connections to allow in the queue
177 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
180 struct sockaddr_in6 sin6;
181 struct sockaddr_in sin4;
185 memset(&sin6, 0, sizeof(sin6));
186 memset(&sin4, 0, sizeof(sin4));
187 sin6.sin6_family = AF_INET6;
188 sin4.sin_family = AF_INET;
190 if ( (ip_addr == NULL) /* any IPv6 */
191 || (IsEmptyStr(ip_addr))
192 || (!strcmp(ip_addr, "*"))
195 sin6.sin6_addr = in6addr_any;
197 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
200 sin4.sin_addr.s_addr = INADDR_ANY;
202 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
205 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
206 snprintf(errormessage, SIZ,
207 "Error binding to [%s] : %s", ip_addr, strerror(errno)
209 syslog(LOG_ALERT, "%s", errormessage);
213 else /* specific IPv6 */
216 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
217 snprintf(errormessage, SIZ,
218 "Error binding to [%s] : %s", ip_addr, strerror(errno)
220 syslog(LOG_ALERT, "%s", errormessage);
225 if (port_number == 0) {
226 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
227 syslog(LOG_ALERT, "%s", errormessage);
230 sin6.sin6_port = htons((u_short) port_number);
231 sin4.sin_port = htons((u_short) port_number);
233 p = getprotobyname("tcp");
235 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
237 snprintf(errormessage, SIZ,
238 "Can't create a listening socket: %s", strerror(errno)
240 syslog(LOG_ALERT, "%s", errormessage);
243 /* Set some socket options that make sense. */
245 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
247 if (ip_version == 6) {
248 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
251 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
255 snprintf(errormessage, SIZ,
256 "Can't bind: %s", strerror(errno)
258 syslog(LOG_ALERT, "%s", errormessage);
262 fcntl(s, F_SETFL, O_NONBLOCK);
264 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
265 snprintf(errormessage, SIZ,
266 "Can't listen: %s", strerror(errno)
268 syslog(LOG_ALERT, "%s", errormessage);
279 * Create a Unix domain socket and listen on it
281 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
283 struct sockaddr_un addr;
286 int actual_queue_len;
287 #ifdef HAVE_STRUCT_UCRED
291 actual_queue_len = queue_len;
292 if (actual_queue_len < 5) actual_queue_len = 5;
294 i = unlink(sockpath);
295 if ((i != 0) && (errno != ENOENT)) {
296 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
297 sockpath, strerror(errno)
299 syslog(LOG_EMERG, "%s", errormessage);
303 memset(&addr, 0, sizeof(addr));
304 addr.sun_family = AF_UNIX;
305 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
307 s = socket(AF_UNIX, SOCK_STREAM, 0);
309 snprintf(errormessage, SIZ,
310 "citserver: Can't create a socket: %s",
312 syslog(LOG_EMERG, "%s", errormessage);
316 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
317 snprintf(errormessage, SIZ,
318 "citserver: Can't bind: %s",
320 syslog(LOG_EMERG, "%s", errormessage);
324 /* set to nonblock - we need this for some obscure situations */
325 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
326 snprintf(errormessage, SIZ,
327 "citserver: Can't set socket to non-blocking: %s",
329 syslog(LOG_EMERG, "%s", errormessage);
334 if (listen(s, actual_queue_len) < 0) {
335 snprintf(errormessage, SIZ,
336 "citserver: Can't listen: %s",
338 syslog(LOG_EMERG, "%s", errormessage);
342 #ifdef HAVE_STRUCT_UCRED
343 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
346 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
353 * The following functions implement output buffering on operating systems which
354 * support it (such as Linux and various BSD flavors).
358 # define HAVE_TCP_BUFFERING
361 # define HAVE_TCP_BUFFERING
362 # define TCP_CORK TCP_NOPUSH
364 #endif /* TCP_CORK */
365 #endif /* HAVE_DARWIN */
367 static unsigned on = 1, off = 0;
369 void buffer_output(void) {
370 #ifdef HAVE_TCP_BUFFERING
372 if (!CC->redirect_ssl)
374 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
378 void unbuffer_output(void) {
379 #ifdef HAVE_TCP_BUFFERING
381 if (!CC->redirect_ssl)
383 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
387 void flush_output(void) {
388 #ifdef HAVE_TCP_BUFFERING
389 struct CitContext *CCC = CC;
390 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
391 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
396 static void flush_client_inbuf(void)
400 FlushStrBuf(CCC->ReadBuf);
401 CCC->RecvBuf->ReadWritePointer = NULL;
408 * client_close() ... close the client socket
410 void client_close(void) {
411 CitContext *CCC = CC;
414 if (CCC->client_socket <= 0) return;
415 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
417 close(CCC->client_socket);
418 CCC->client_socket = -1 ;
425 * client_write() ... Send binary data to the client.
427 int client_write(const char *buf, int nbytes)
429 int bytes_written = 0;
431 #ifndef HAVE_TCP_BUFFERING
432 int old_buffer_len = 0;
438 if (nbytes < 1) return(0);
448 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
450 fd = fopen(fn, "a+");
453 fprintf(fd, "Sending: BufSize: %d BufContent: [",
455 rv = fwrite(buf, nbytes, 1, fd);
461 // flush_client_inbuf();
462 if (Ctx->redirect_buffer != NULL) {
463 StrBufAppendBufPlain(Ctx->redirect_buffer,
469 if (Ctx->redirect_ssl) {
470 client_write_ssl(buf, nbytes);
474 if (Ctx->client_socket == -1) return -1;
476 fdflags = fcntl(Ctx->client_socket, F_GETFL);
478 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
479 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
481 FD_SET(Ctx->client_socket, &wset);
482 if (select(1, NULL, &wset, NULL, NULL) == -1) {
485 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
488 if (server_shutting_down) {
489 CC->kill_me = KILLME_SELECT_INTERRUPTED;
492 /* can't trust fd's and stuff so we need to re-create them */
497 "client_write(%d bytes) select failed: %s (%d)",
498 nbytes - bytes_written,
499 strerror(errno), errno
503 Ctx->kill_me = KILLME_SELECT_FAILED;
509 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
512 "client_write(%d bytes) failed: %s (%d)",
513 nbytes - bytes_written,
514 strerror(errno), errno
518 Ctx->kill_me = KILLME_WRITE_FAILED;
521 bytes_written = bytes_written + retval;
526 void cputbuf(const StrBuf *Buf) {
527 client_write(ChrPtr(Buf), StrLength(Buf));
532 * cprintf() Send formatted printable data to the client.
533 * Implemented in terms of client_write() so it's technically not sysdep...
535 void cprintf(const char *format, ...) {
539 va_start(arg_ptr, format);
540 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
541 buf[sizeof buf - 2] = '\n';
542 client_write(buf, strlen(buf));
548 * Read data from the client socket.
550 * sock socket fd to read from
551 * buf buffer to read into
552 * bytes number of bytes to read
553 * timeout Number of seconds to wait before timing out
555 * Possible return values:
556 * 1 Requested number of bytes has been read.
557 * 0 Request timed out.
558 * -1 Connection is broken, or other error.
560 int client_read_blob(StrBuf *Target, int bytes, int timeout)
567 if (CCC->redirect_ssl) {
573 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
575 fd = fopen(fn, "a+");
576 fprintf(fd, "Reading BLOB: BufSize: %d ",
578 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
584 retval = client_read_sslblob(Target, bytes, timeout);
586 syslog(LOG_CRIT, "client_read_blob() failed");
589 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
591 fd = fopen(fn, "a+");
592 fprintf(fd, "Read: %d BufContent: [",
594 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
609 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
611 fd = fopen(fn, "a+");
612 fprintf(fd, "Reading BLOB: BufSize: %d ",
614 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
620 retval = StrBufReadBLOBBuffered(Target,
622 &CCC->RecvBuf.ReadWritePointer,
629 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
634 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
636 fd = fopen(fn, "a+");
637 fprintf(fd, "Read: %d BufContent: [",
639 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
649 * to make client_read_random_blob() more efficient, increase buffer size.
650 * just use in greeting function, else your buffer may be flushed
652 void client_set_inbound_buf(long N)
655 FlushStrBuf(CCC->RecvBuf.Buf);
656 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
659 int client_read_random_blob(StrBuf *Target, int timeout)
664 rc = client_read_blob(Target, 1, timeout);
670 len = StrLength(CCC->RecvBuf.Buf);
671 pch = ChrPtr(CCC->RecvBuf.Buf);
675 if (CCC->RecvBuf.ReadWritePointer != NULL) {
676 len -= CCC->RecvBuf.ReadWritePointer - pch;
677 pch = CCC->RecvBuf.ReadWritePointer;
679 StrBufAppendBufPlain(Target, pch, len, 0);
680 FlushStrBuf(CCC->RecvBuf.Buf);
681 CCC->RecvBuf.ReadWritePointer = NULL;
688 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
690 fd = fopen(fn, "a+");
691 fprintf(fd, "Read: BufSize: %d BufContent: [",
693 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
701 return StrLength(Target);
709 int client_read_to(char *buf, int bytes, int timeout)
714 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
723 ChrPtr(CCC->MigrateBuf),
724 StrLength(CCC->MigrateBuf) + 1);
725 FlushStrBuf(CCC->MigrateBuf);
731 int HaveMoreLinesWaiting(CitContext *CCC)
733 if ((CCC->kill_me != 0) ||
734 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
735 (StrLength(CCC->RecvBuf.Buf) == 0) &&
736 (CCC->client_socket != -1)) )
744 * Read data from the client socket with default timeout.
745 * (This is implemented in terms of client_read_to() and could be
746 * justifiably moved out of sysdep.c)
748 INLINE int client_read(char *buf, int bytes)
750 return(client_read_to(buf, bytes, config.c_sleeping));
753 int CtdlClientGetLine(StrBuf *Target)
761 if (CCC->redirect_ssl) {
771 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
773 fd = fopen(fn, "a+");
774 pch = ChrPtr(CCC->RecvBuf.Buf);
775 len = StrLength(CCC->RecvBuf.Buf);
776 if (CCC->RecvBuf.ReadWritePointer != NULL)
777 rlen = CCC->RecvBuf.ReadWritePointer - pch;
781 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
784 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
787 rc = client_readline_sslbuffer(Target,
789 &CCC->RecvBuf.ReadWritePointer,
792 pch = ChrPtr(CCC->RecvBuf.Buf);
793 nlen = StrLength(CCC->RecvBuf.Buf);
794 if (CCC->RecvBuf.ReadWritePointer != NULL)
795 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
799 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
800 len, nlen, rlen, nrlen, pch);
802 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
803 len, nlen, rlen, nrlen);
805 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
806 StrLength(Target), ChrPtr(Target));
810 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
821 int len, rlen, nlen, nrlen;
824 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
826 fd = fopen(fn, "a+");
827 pch = ChrPtr(CCC->RecvBuf.Buf);
828 len = StrLength(CCC->RecvBuf.Buf);
829 if (CCC->RecvBuf.ReadWritePointer != NULL)
830 rlen = CCC->RecvBuf.ReadWritePointer - pch;
834 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
837 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
840 rc = StrBufTCP_read_buffered_line_fast(Target,
842 &CCC->RecvBuf.ReadWritePointer,
849 pch = ChrPtr(CCC->RecvBuf.Buf);
850 nlen = StrLength(CCC->RecvBuf.Buf);
851 if (CCC->RecvBuf.ReadWritePointer != NULL)
852 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
856 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
857 len, nlen, rlen, nrlen, pch);
859 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
860 len, nlen, rlen, nrlen);
862 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
863 StrLength(Target), ChrPtr(Target));
866 if ((rc < 0) && (Error != NULL)) {
867 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
876 * client_getln() ... Get a LF-terminated line of text from the client.
877 * (This is implemented in terms of client_read() and could be
878 * justifiably moved out of sysdep.c)
880 int client_getln(char *buf, int bufsize)
886 retval = CtdlClientGetLine(CCC->MigrateBuf);
891 i = StrLength(CCC->MigrateBuf);
892 pCh = ChrPtr(CCC->MigrateBuf);
893 /* Strip the trailing LF, and the trailing CR if present.
898 && ( (pCh[i - 1]==13)
899 || ( pCh[i - 1]==10)) ) {
905 FlushStrBuf(CCC->MigrateBuf);
907 safestrncpy(&buf[i], "000", bufsize - i);
914 * Cleanup any contexts that are left lying around
918 void close_masters (void)
920 struct ServiceFunctionHook *serviceptr;
923 * close all protocol master sockets
925 for (serviceptr = ServiceHookTable; serviceptr != NULL;
926 serviceptr = serviceptr->next ) {
928 if (serviceptr->tcp_port > 0)
930 syslog(LOG_INFO, "Closing %d listener on port %d\n",
932 serviceptr->tcp_port);
933 serviceptr->tcp_port = 0;
936 if (serviceptr->sockpath != NULL)
937 syslog(LOG_INFO, "Closing %d listener on '%s'\n",
939 serviceptr->sockpath);
940 if (serviceptr->msock != -1)
941 close(serviceptr->msock);
942 /* If it's a Unix domain socket, remove the file. */
943 if (serviceptr->sockpath != NULL) {
944 unlink(serviceptr->sockpath);
945 serviceptr->sockpath = NULL;
952 * The system-dependent part of master_cleanup() - close the master socket.
954 void sysdep_master_cleanup(void) {
963 CtdlDestroyProtoHooks();
964 CtdlDestroyDeleteHooks();
965 CtdlDestroyXmsgHooks();
966 CtdlDestroyNetprocHooks();
967 CtdlDestroyUserHooks();
968 CtdlDestroyMessageHook();
969 CtdlDestroyCleanupHooks();
970 CtdlDestroyFixedOutputHooks();
971 CtdlDestroySessionHooks();
972 CtdlDestroyServiceHook();
973 CtdlDestroyRoomHooks();
974 CtdlDestroySearchHooks();
975 CtdlDestroyDebugTable();
976 #ifdef HAVE_BACKTRACE
984 void graceful_shutdown(int signum) {
985 kill(current_child, signum);
986 unlink(file_pid_file);
991 int nFireUpsNonRestart = 0;
995 * Start running as a daemon.
997 void start_daemon(int unused) {
1005 /* Close stdin/stdout/stderr and replace them with /dev/null.
1006 * We don't just call close() because we don't want these fd's
1007 * to be reused for other files.
1009 if (chdir(ctdl_run_dir) != 0)
1011 "unable to change into directory [%s]: %s",
1012 ctdl_run_dir, strerror(errno));
1019 signal(SIGHUP, SIG_IGN);
1020 signal(SIGINT, SIG_IGN);
1021 signal(SIGQUIT, SIG_IGN);
1025 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1026 (freopen("/dev/null", "w", stdout) != stdout) ||
1027 (freopen("/dev/null", "w", stderr) != stderr))
1029 "unable to reopen stdin/out/err %s",
1034 current_child = fork();
1036 signal(SIGTERM, graceful_shutdown);
1038 if (current_child < 0) {
1043 else if (current_child == 0) {
1044 return; /* continue starting citadel. */
1048 fp = fopen(file_pid_file, "w");
1050 fprintf(fp, ""F_PID_T"\n", getpid());
1053 waitpid(current_child, &status, 0);
1056 nFireUpsNonRestart = nFireUps;
1058 /* Exit code 0 means the watcher should exit */
1059 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1063 /* Exit code 101-109 means the watcher should exit */
1064 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1068 /* Any other exit code, or no exit code, means we should restart. */
1072 ForkedPid = current_child;
1075 } while (do_restart);
1077 unlink(file_pid_file);
1078 exit(WEXITSTATUS(status));
1083 void checkcrash(void)
1085 if (nFireUpsNonRestart != nFireUps)
1089 CrashMail = NewStrBuf();
1090 syslog(LOG_ALERT, "Posting crash message\n");
1091 StrBufPrintf(CrashMail,
1093 " The Citadel server process (citserver) terminated unexpectedly."
1095 " This could be the result of a bug in the server program, or some external "
1097 " You can obtain more information about this by enabling core dumps.\n \n"
1098 " For more information, please see:\n \n"
1099 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1102 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1104 ctdl_run_dir, ForkedPid);
1105 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1106 FreeStrBuf(&CrashMail);
1112 * Generic routine to convert a login name to a full name (gecos)
1113 * Returns nonzero if a conversion took place
1115 int convert_login(char NameToConvert[]) {
1119 pw = getpwnam(NameToConvert);
1124 strcpy(NameToConvert, pw->pw_gecos);
1125 for (a=0; a<strlen(NameToConvert); ++a) {
1126 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1135 * This loop just keeps going and going and going...
1137 void *worker_thread(void *blah) {
1140 CitContext *bind_me = NULL;
1144 int force_purge = 0;
1145 struct ServiceFunctionHook *serviceptr;
1146 int ssock; /* Descriptor for client socket */
1147 CitContext *con = NULL; /* Temporary context pointer */
1152 while (!server_shutting_down) {
1154 /* make doubly sure we're not holding any stale db handles
1155 * which might cause a deadlock.
1157 cdb_check_handles();
1158 do_select: force_purge = 0;
1159 bind_me = NULL; /* Which session shall we handle? */
1161 /* Initialize the fdset. */
1165 /* First, add the various master sockets to the fdset. */
1166 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1167 FD_SET(serviceptr->msock, &readfds);
1168 if (serviceptr->msock > highest) {
1169 highest = serviceptr->msock;
1173 /* Next, add all of the client sockets. */
1174 begin_critical_section(S_SESSION_TABLE);
1175 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1176 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1179 /* Don't select on dead sessions, only truly idle ones */
1180 if ( (ptr->state == CON_IDLE)
1181 && (ptr->kill_me == 0)
1182 && (ptr->client_socket > 0)
1184 FD_SET(ptr->client_socket, &readfds);
1185 if (ptr->client_socket > highest)
1186 highest = ptr->client_socket;
1188 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1190 ptr->state = CON_EXECUTING;
1193 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1195 ptr->state = CON_STARTING;
1199 end_critical_section(S_SESSION_TABLE);
1205 /* If we got this far, it means that there are no sessions
1206 * which a previous thread marked for attention, so we go
1207 * ahead and get ready to select().
1210 if (!server_shutting_down) {
1211 tv.tv_sec = 1; /* wake up every second if no input */
1213 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1220 /* Now figure out who made this select() unblock.
1221 * First, check for an error or exit condition.
1224 if (errno == EBADF) {
1225 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1228 if (errno != EINTR) {
1229 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1230 server_shutting_down = 1;
1234 syslog(LOG_DEBUG, "Interrupted select()\n");
1236 if (server_shutting_down) {
1243 else if (retval == 0) {
1244 if (server_shutting_down) {
1250 /* Next, check to see if it's a new client connecting * on a master socket. */
1252 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1254 if (FD_ISSET(serviceptr->msock, &readfds)) {
1255 ssock = accept(serviceptr->msock, NULL, 0);
1257 syslog(LOG_DEBUG, "New client socket %d", ssock);
1259 /* The master socket is non-blocking but the client
1260 * sockets need to be blocking, otherwise certain
1261 * operations barf on FreeBSD. Not a fatal error.
1263 if (fcntl(ssock, F_SETFL, 0) < 0) {
1265 "citserver: Can't set socket to blocking: %s\n",
1269 /* New context will be created already
1270 * set up in the CON_EXECUTING state.
1272 con = CreateNewContext();
1274 /* Assign our new socket number to it. */
1275 con->tcp_port = serviceptr->tcp_port;
1276 con->client_socket = ssock;
1277 con->h_command_function = serviceptr->h_command_function;
1278 con->h_async_function = serviceptr->h_async_function;
1279 con->h_greeting_function = serviceptr->h_greeting_function;
1280 con->ServiceName = serviceptr->ServiceName;
1282 /* Determine whether it's a local socket */
1283 if (serviceptr->sockpath != NULL) {
1284 con->is_local_socket = 1;
1287 /* Set the SO_REUSEADDR socket option */
1289 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1290 con->state = CON_GREETING;
1298 /* It must be a client socket. Find a context that has data
1299 * waiting on its socket *and* is in the CON_IDLE state. Any
1300 * active sockets other than our chosen one are marked as
1301 * CON_READY so the next thread that comes around can just bind
1302 * to one without having to select() again.
1304 begin_critical_section(S_SESSION_TABLE);
1305 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1306 int checkfd = ptr->client_socket;
1307 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1308 if (FD_ISSET(checkfd, &readfds)) {
1309 ptr->input_waiting = 1;
1311 bind_me = ptr; /* I choose you! */
1312 bind_me->state = CON_EXECUTING;
1315 ptr->state = CON_READY;
1317 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1319 bind_me = ptr; /* I choose you! */
1320 bind_me->state = CON_EXECUTING;
1323 ptr->state = CON_READY;
1328 end_critical_section(S_SESSION_TABLE);
1331 /* We're bound to a session */
1333 if (bind_me != NULL) {
1334 become_session(bind_me);
1336 if (bind_me->state == CON_STARTING) {
1337 bind_me->state = CON_EXECUTING;
1338 begin_session(bind_me);
1339 bind_me->h_greeting_function();
1341 /* If the client has sent a command, execute it. */
1342 if (CC->input_waiting) {
1343 CC->h_command_function();
1345 while (HaveMoreLinesWaiting(CC))
1346 CC->h_command_function();
1348 CC->input_waiting = 0;
1351 /* If there are asynchronous messages waiting and the
1352 * client supports it, do those now */
1353 if ((CC->is_async) && (CC->async_waiting)
1354 && (CC->h_async_function != NULL)) {
1355 CC->h_async_function();
1356 CC->async_waiting = 0;
1359 force_purge = CC->kill_me;
1360 become_session(NULL);
1361 bind_me->state = CON_IDLE;
1364 dead_session_purge(force_purge);
1369 /* If control reaches this point, the server is shutting down */
1378 * Translate text facility name to syslog.h defined value.
1380 int SyslogFacility(char *name)
1389 { LOG_KERN, "kern" },
1390 { LOG_USER, "user" },
1391 { LOG_MAIL, "mail" },
1392 { LOG_DAEMON, "daemon" },
1393 { LOG_AUTH, "auth" },
1394 { LOG_SYSLOG, "syslog" },
1396 { LOG_NEWS, "news" },
1397 { LOG_UUCP, "uucp" },
1398 { LOG_LOCAL0, "local0" },
1399 { LOG_LOCAL1, "local1" },
1400 { LOG_LOCAL2, "local2" },
1401 { LOG_LOCAL3, "local3" },
1402 { LOG_LOCAL4, "local4" },
1403 { LOG_LOCAL5, "local5" },
1404 { LOG_LOCAL6, "local6" },
1405 { LOG_LOCAL7, "local7" },
1408 for(i = 0; facTbl[i].name != NULL; i++) {
1409 if(!strcasecmp(name, facTbl[i].name))
1410 return facTbl[i].facility;