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>
76 #include "ctdl_module.h"
83 * Signal handler to shut down the server.
86 volatile int exit_signal = 0;
87 volatile int shutdown_and_halt = 0;
88 volatile int restart_server = 0;
89 volatile int running_as_daemon = 0;
91 static RETSIGTYPE signal_cleanup(int signum) {
92 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
94 server_shutting_down = 1;
97 static RETSIGTYPE signal_exit(int signum) {
104 * Some initialization stuff...
106 void init_sysdep(void) {
109 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
113 getrlimit(RLIMIT_NOFILE, &rl);
114 rl.rlim_cur = FD_SETSIZE;
115 rl.rlim_max = FD_SETSIZE;
116 setrlimit(RLIMIT_NOFILE, &rl);
120 /* If we've got OpenSSL, we're going to use it. */
126 * Set up a place to put thread-specific data.
127 * We only need a single pointer per thread - it points to the
128 * CitContext structure (in the ContextList linked list) of the
129 * session to which the calling thread is currently bound.
131 if (pthread_key_create(&MyConKey, NULL) != 0) {
132 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
136 * Interript, hangup, and terminate signals should cause the server
137 * to gracefully clean up and shut down.
140 sigaddset(&set, SIGINT);
141 sigaddset(&set, SIGHUP);
142 sigaddset(&set, SIGTERM);
143 sigprocmask(SIG_UNBLOCK, &set, NULL);
145 signal(SIGINT, signal_cleanup);
146 signal(SIGHUP, signal_cleanup);
147 signal(SIGTERM, signal_cleanup);
148 signal(SIGUSR2, signal_exit);
151 * Do not shut down the server on broken pipe signals, otherwise the
152 * whole Citadel service would come down whenever a single client
155 signal(SIGPIPE, SIG_IGN);
160 * This is a generic function to set up a master socket for listening on
161 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
163 * ip_addr IP address to bind
164 * port_number port number to bind
165 * queue_len number of incoming connections to allow in the queue
167 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
170 struct sockaddr_in6 sin6;
171 struct sockaddr_in sin4;
175 memset(&sin6, 0, sizeof(sin6));
176 memset(&sin4, 0, sizeof(sin4));
177 sin6.sin6_family = AF_INET6;
178 sin4.sin_family = AF_INET;
180 if ( (ip_addr == NULL) /* any IPv6 */
181 || (IsEmptyStr(ip_addr))
182 || (!strcmp(ip_addr, "*"))
185 sin6.sin6_addr = in6addr_any;
187 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
190 sin4.sin_addr.s_addr = INADDR_ANY;
192 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
195 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
196 snprintf(errormessage, SIZ,
197 "Error binding to [%s] : %s", ip_addr, strerror(errno)
199 syslog(LOG_ALERT, "%s", errormessage);
203 else /* specific IPv6 */
206 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
207 snprintf(errormessage, SIZ,
208 "Error binding to [%s] : %s", ip_addr, strerror(errno)
210 syslog(LOG_ALERT, "%s", errormessage);
215 if (port_number == 0) {
216 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
217 syslog(LOG_ALERT, "%s", errormessage);
220 sin6.sin6_port = htons((u_short) port_number);
221 sin4.sin_port = htons((u_short) port_number);
223 p = getprotobyname("tcp");
225 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
227 snprintf(errormessage, SIZ,
228 "Can't create a listening socket: %s", strerror(errno)
230 syslog(LOG_ALERT, "%s", errormessage);
233 /* Set some socket options that make sense. */
235 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
237 if (ip_version == 6) {
238 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
241 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
245 snprintf(errormessage, SIZ,
246 "Can't bind: %s", strerror(errno)
248 syslog(LOG_ALERT, "%s", errormessage);
252 fcntl(s, F_SETFL, O_NONBLOCK);
254 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
255 snprintf(errormessage, SIZ,
256 "Can't listen: %s", strerror(errno)
258 syslog(LOG_ALERT, "%s", errormessage);
269 * Create a Unix domain socket and listen on it
271 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
273 struct sockaddr_un addr;
276 int actual_queue_len;
277 #ifdef HAVE_STRUCT_UCRED
281 actual_queue_len = queue_len;
282 if (actual_queue_len < 5) actual_queue_len = 5;
284 i = unlink(sockpath);
285 if ((i != 0) && (errno != ENOENT)) {
286 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
287 sockpath, strerror(errno)
289 syslog(LOG_EMERG, "%s", errormessage);
293 memset(&addr, 0, sizeof(addr));
294 addr.sun_family = AF_UNIX;
295 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
297 s = socket(AF_UNIX, SOCK_STREAM, 0);
299 snprintf(errormessage, SIZ,
300 "citserver: Can't create a socket: %s",
302 syslog(LOG_EMERG, "%s", errormessage);
306 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
307 snprintf(errormessage, SIZ,
308 "citserver: Can't bind: %s",
310 syslog(LOG_EMERG, "%s", errormessage);
314 /* set to nonblock - we need this for some obscure situations */
315 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
316 snprintf(errormessage, SIZ,
317 "citserver: Can't set socket to non-blocking: %s",
319 syslog(LOG_EMERG, "%s", errormessage);
324 if (listen(s, actual_queue_len) < 0) {
325 snprintf(errormessage, SIZ,
326 "citserver: Can't listen: %s",
328 syslog(LOG_EMERG, "%s", errormessage);
332 #ifdef HAVE_STRUCT_UCRED
333 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
336 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
343 * The following functions implement output buffering on operating systems which
344 * support it (such as Linux and various BSD flavors).
348 # define HAVE_TCP_BUFFERING
351 # define HAVE_TCP_BUFFERING
352 # define TCP_CORK TCP_NOPUSH
354 #endif /* TCP_CORK */
355 #endif /* HAVE_DARWIN */
357 static unsigned on = 1, off = 0;
359 void buffer_output(void) {
360 #ifdef HAVE_TCP_BUFFERING
362 if (!CC->redirect_ssl)
364 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
368 void unbuffer_output(void) {
369 #ifdef HAVE_TCP_BUFFERING
371 if (!CC->redirect_ssl)
373 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
377 void flush_output(void) {
378 #ifdef HAVE_TCP_BUFFERING
379 struct CitContext *CCC = CC;
380 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
381 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
386 static void flush_client_inbuf(void)
390 FlushStrBuf(CCC->ReadBuf);
391 CCC->RecvBuf->ReadWritePointer = NULL;
398 * client_close() ... close the client socket
400 void client_close(void) {
401 CitContext *CCC = CC;
404 if (CCC->client_socket <= 0) return;
405 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
407 close(CCC->client_socket);
408 CCC->client_socket = -1 ;
415 * client_write() ... Send binary data to the client.
417 int client_write(const char *buf, int nbytes)
419 int bytes_written = 0;
421 #ifndef HAVE_TCP_BUFFERING
422 int old_buffer_len = 0;
428 if (nbytes < 1) return(0);
438 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
440 fd = fopen(fn, "a+");
443 fprintf(fd, "Sending: BufSize: %d BufContent: [",
445 rv = fwrite(buf, nbytes, 1, fd);
451 // flush_client_inbuf();
452 if (Ctx->redirect_buffer != NULL) {
453 StrBufAppendBufPlain(Ctx->redirect_buffer,
459 if (Ctx->redirect_ssl) {
460 client_write_ssl(buf, nbytes);
464 if (Ctx->client_socket == -1) return -1;
466 fdflags = fcntl(Ctx->client_socket, F_GETFL);
468 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
469 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
471 FD_SET(Ctx->client_socket, &wset);
472 if (select(1, NULL, &wset, NULL, NULL) == -1) {
475 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
478 if (server_shutting_down) {
479 CC->kill_me = KILLME_SELECT_INTERRUPTED;
482 /* can't trust fd's and stuff so we need to re-create them */
487 "client_write(%d bytes) select failed: %s (%d)",
488 nbytes - bytes_written,
489 strerror(errno), errno
493 Ctx->kill_me = KILLME_SELECT_FAILED;
499 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
502 "client_write(%d bytes) failed: %s (%d)",
503 nbytes - bytes_written,
504 strerror(errno), errno
508 Ctx->kill_me = KILLME_WRITE_FAILED;
511 bytes_written = bytes_written + retval;
516 void cputbuf(const StrBuf *Buf) {
517 client_write(ChrPtr(Buf), StrLength(Buf));
522 * cprintf() Send formatted printable data to the client.
523 * Implemented in terms of client_write() so it's technically not sysdep...
525 void cprintf(const char *format, ...) {
529 va_start(arg_ptr, format);
530 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
531 buf[sizeof buf - 2] = '\n';
532 client_write(buf, strlen(buf));
538 * Read data from the client socket.
540 * sock socket fd to read from
541 * buf buffer to read into
542 * bytes number of bytes to read
543 * timeout Number of seconds to wait before timing out
545 * Possible return values:
546 * 1 Requested number of bytes has been read.
547 * 0 Request timed out.
548 * -1 Connection is broken, or other error.
550 int client_read_blob(StrBuf *Target, int bytes, int timeout)
557 if (CCC->redirect_ssl) {
563 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
565 fd = fopen(fn, "a+");
566 fprintf(fd, "Reading BLOB: BufSize: %d ",
568 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
574 retval = client_read_sslblob(Target, bytes, timeout);
576 syslog(LOG_CRIT, "client_read_blob() failed");
579 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
581 fd = fopen(fn, "a+");
582 fprintf(fd, "Read: %d BufContent: [",
584 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
599 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
601 fd = fopen(fn, "a+");
602 fprintf(fd, "Reading BLOB: BufSize: %d ",
604 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
610 retval = StrBufReadBLOBBuffered(Target,
612 &CCC->RecvBuf.ReadWritePointer,
619 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
624 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
626 fd = fopen(fn, "a+");
627 fprintf(fd, "Read: %d BufContent: [",
629 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
639 * to make client_read_random_blob() more efficient, increase buffer size.
640 * just use in greeting function, else your buffer may be flushed
642 void client_set_inbound_buf(long N)
645 FlushStrBuf(CCC->RecvBuf.Buf);
646 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
649 int client_read_random_blob(StrBuf *Target, int timeout)
654 rc = client_read_blob(Target, 1, timeout);
660 len = StrLength(CCC->RecvBuf.Buf);
661 pch = ChrPtr(CCC->RecvBuf.Buf);
665 if (CCC->RecvBuf.ReadWritePointer != NULL) {
666 len -= CCC->RecvBuf.ReadWritePointer - pch;
667 pch = CCC->RecvBuf.ReadWritePointer;
669 StrBufAppendBufPlain(Target, pch, len, 0);
670 FlushStrBuf(CCC->RecvBuf.Buf);
671 CCC->RecvBuf.ReadWritePointer = NULL;
678 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
680 fd = fopen(fn, "a+");
681 fprintf(fd, "Read: BufSize: %d BufContent: [",
683 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
691 return StrLength(Target);
699 int client_read_to(char *buf, int bytes, int timeout)
704 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
713 ChrPtr(CCC->MigrateBuf),
714 StrLength(CCC->MigrateBuf) + 1);
715 FlushStrBuf(CCC->MigrateBuf);
721 int HaveMoreLinesWaiting(CitContext *CCC)
723 if ((CCC->kill_me != 0) ||
724 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
725 (StrLength(CCC->RecvBuf.Buf) == 0) &&
726 (CCC->client_socket != -1)) )
734 * Read data from the client socket with default timeout.
735 * (This is implemented in terms of client_read_to() and could be
736 * justifiably moved out of sysdep.c)
738 INLINE int client_read(char *buf, int bytes)
740 return(client_read_to(buf, bytes, config.c_sleeping));
743 int CtdlClientGetLine(StrBuf *Target)
751 if (CCC->redirect_ssl) {
761 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
763 fd = fopen(fn, "a+");
764 pch = ChrPtr(CCC->RecvBuf.Buf);
765 len = StrLength(CCC->RecvBuf.Buf);
766 if (CCC->RecvBuf.ReadWritePointer != NULL)
767 rlen = CCC->RecvBuf.ReadWritePointer - pch;
771 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
774 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
777 rc = client_readline_sslbuffer(Target,
779 &CCC->RecvBuf.ReadWritePointer,
782 pch = ChrPtr(CCC->RecvBuf.Buf);
783 nlen = StrLength(CCC->RecvBuf.Buf);
784 if (CCC->RecvBuf.ReadWritePointer != NULL)
785 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
789 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
790 len, nlen, rlen, nrlen, pch);
792 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
793 len, nlen, rlen, nrlen);
795 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
796 StrLength(Target), ChrPtr(Target));
800 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
811 int len, rlen, nlen, nrlen;
814 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
816 fd = fopen(fn, "a+");
817 pch = ChrPtr(CCC->RecvBuf.Buf);
818 len = StrLength(CCC->RecvBuf.Buf);
819 if (CCC->RecvBuf.ReadWritePointer != NULL)
820 rlen = CCC->RecvBuf.ReadWritePointer - pch;
824 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
827 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
830 rc = StrBufTCP_read_buffered_line_fast(Target,
832 &CCC->RecvBuf.ReadWritePointer,
839 pch = ChrPtr(CCC->RecvBuf.Buf);
840 nlen = StrLength(CCC->RecvBuf.Buf);
841 if (CCC->RecvBuf.ReadWritePointer != NULL)
842 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
846 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
847 len, nlen, rlen, nrlen, pch);
849 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
850 len, nlen, rlen, nrlen);
852 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
853 StrLength(Target), ChrPtr(Target));
856 if ((rc < 0) && (Error != NULL)) {
857 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
866 * client_getln() ... Get a LF-terminated line of text from the client.
867 * (This is implemented in terms of client_read() and could be
868 * justifiably moved out of sysdep.c)
870 int client_getln(char *buf, int bufsize)
876 retval = CtdlClientGetLine(CCC->MigrateBuf);
881 i = StrLength(CCC->MigrateBuf);
882 pCh = ChrPtr(CCC->MigrateBuf);
883 /* Strip the trailing LF, and the trailing CR if present.
888 && ( (pCh[i - 1]==13)
889 || ( pCh[i - 1]==10)) ) {
895 FlushStrBuf(CCC->MigrateBuf);
897 safestrncpy(&buf[i], "000", bufsize - i);
904 * Cleanup any contexts that are left lying around
908 void close_masters (void)
910 struct ServiceFunctionHook *serviceptr;
914 * close all protocol master sockets
916 for (serviceptr = ServiceHookTable; serviceptr != NULL;
917 serviceptr = serviceptr->next ) {
919 if (serviceptr->tcp_port > 0)
921 if (serviceptr->msock == -1)
922 Text = "not closing again";
926 syslog(LOG_INFO, "%s %d listener on port %d\n",
929 serviceptr->tcp_port);
930 serviceptr->tcp_port = 0;
933 if (serviceptr->sockpath != NULL)
935 if (serviceptr->msock == -1)
936 Text = "not closing again";
940 syslog(LOG_INFO, "%s %d listener on '%s'\n",
943 serviceptr->sockpath);
946 if (serviceptr->msock != -1)
948 close(serviceptr->msock);
949 serviceptr->msock = -1;
952 /* If it's a Unix domain socket, remove the file. */
953 if (serviceptr->sockpath != NULL) {
954 unlink(serviceptr->sockpath);
955 serviceptr->sockpath = NULL;
962 * The system-dependent part of master_cleanup() - close the master socket.
964 void sysdep_master_cleanup(void) {
973 CtdlDestroyProtoHooks();
974 CtdlDestroyDeleteHooks();
975 CtdlDestroyXmsgHooks();
976 CtdlDestroyNetprocHooks();
977 CtdlDestroyUserHooks();
978 CtdlDestroyMessageHook();
979 CtdlDestroyCleanupHooks();
980 CtdlDestroyFixedOutputHooks();
981 CtdlDestroySessionHooks();
982 CtdlDestroyTDAPVetoHooks();
983 CtdlDestroyServiceHook();
984 CtdlDestroyRoomHooks();
985 CtdlDestroySearchHooks();
986 CtdlDestroyDebugTable();
987 #ifdef HAVE_BACKTRACE
995 void graceful_shutdown(int signum) {
996 kill(current_child, signum);
997 unlink(file_pid_file);
1002 int nFireUpsNonRestart = 0;
1003 pid_t ForkedPid = 1;
1006 * Start running as a daemon.
1008 void start_daemon(int unused) {
1016 /* Close stdin/stdout/stderr and replace them with /dev/null.
1017 * We don't just call close() because we don't want these fd's
1018 * to be reused for other files.
1020 if (chdir(ctdl_run_dir) != 0)
1022 "unable to change into directory [%s]: %s",
1023 ctdl_run_dir, strerror(errno));
1030 signal(SIGHUP, SIG_IGN);
1031 signal(SIGINT, SIG_IGN);
1032 signal(SIGQUIT, SIG_IGN);
1036 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1037 (freopen("/dev/null", "w", stdout) != stdout) ||
1038 (freopen("/dev/null", "w", stderr) != stderr))
1040 "unable to reopen stdin/out/err %s",
1045 current_child = fork();
1047 signal(SIGTERM, graceful_shutdown);
1049 if (current_child < 0) {
1054 else if (current_child == 0) {
1055 return; /* continue starting citadel. */
1059 fp = fopen(file_pid_file, "w");
1061 fprintf(fp, ""F_PID_T"\n", getpid());
1064 waitpid(current_child, &status, 0);
1067 nFireUpsNonRestart = nFireUps;
1069 /* Exit code 0 means the watcher should exit */
1070 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1074 /* Exit code 101-109 means the watcher should exit */
1075 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1079 /* Any other exit code, or no exit code, means we should restart. */
1083 ForkedPid = current_child;
1086 } while (do_restart);
1088 unlink(file_pid_file);
1089 exit(WEXITSTATUS(status));
1094 void checkcrash(void)
1096 if (nFireUpsNonRestart != nFireUps)
1100 CrashMail = NewStrBuf();
1101 syslog(LOG_ALERT, "Posting crash message\n");
1102 StrBufPrintf(CrashMail,
1104 " The Citadel server process (citserver) terminated unexpectedly."
1106 " This could be the result of a bug in the server program, or some external "
1108 " You can obtain more information about this by enabling core dumps.\n \n"
1109 " For more information, please see:\n \n"
1110 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1113 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1115 ctdl_run_dir, ForkedPid);
1116 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1117 FreeStrBuf(&CrashMail);
1123 * Generic routine to convert a login name to a full name (gecos)
1124 * Returns nonzero if a conversion took place
1126 int convert_login(char NameToConvert[]) {
1130 pw = getpwnam(NameToConvert);
1135 strcpy(NameToConvert, pw->pw_gecos);
1136 for (a=0; a<strlen(NameToConvert); ++a) {
1137 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1145 void HuntBadSession(void)
1151 struct ServiceFunctionHook *serviceptr;
1155 /* Next, add all of the client sockets. */
1156 begin_critical_section(S_SESSION_TABLE);
1157 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1158 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1160 /* Initialize the fdset. */
1163 tv.tv_sec = 0; /* wake up every second if no input */
1166 /* Don't select on dead sessions, only truly idle ones */
1167 if ( (ptr->state == CON_IDLE)
1168 && (ptr->kill_me == 0)
1169 && (ptr->client_socket > 0)
1171 FD_SET(ptr->client_socket, &readfds);
1172 if (ptr->client_socket > highest)
1173 highest = ptr->client_socket;
1175 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1180 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1183 ptr->is_local_socket,
1185 ptr->cs_host,ptr->cs_addr);
1188 ptr->client_socket = -1;
1194 end_critical_section(S_SESSION_TABLE);
1197 /* First, add the various master sockets to the fdset. */
1198 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1200 /* Initialize the fdset. */
1202 tv.tv_sec = 0; /* wake up every second if no input */
1205 FD_SET(serviceptr->msock, &readfds);
1206 if (serviceptr->msock > highest) {
1207 highest = serviceptr->msock;
1209 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1212 /* Gotcha! server socket dead? commit suicide! */
1214 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1217 server_shutting_down = 1;
1227 * This loop just keeps going and going and going...
1229 void *worker_thread(void *blah) {
1232 CitContext *bind_me = NULL;
1236 int force_purge = 0;
1237 struct ServiceFunctionHook *serviceptr;
1238 int ssock; /* Descriptor for client socket */
1239 CitContext *con = NULL; /* Temporary context pointer */
1242 pthread_mutex_lock(&ThreadCountMutex);
1244 pthread_mutex_unlock(&ThreadCountMutex);
1246 while (!server_shutting_down) {
1248 /* make doubly sure we're not holding any stale db handles
1249 * which might cause a deadlock.
1251 cdb_check_handles();
1252 do_select: force_purge = 0;
1253 bind_me = NULL; /* Which session shall we handle? */
1255 /* Initialize the fdset. */
1259 /* First, add the various master sockets to the fdset. */
1260 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1261 FD_SET(serviceptr->msock, &readfds);
1262 if (serviceptr->msock > highest) {
1263 highest = serviceptr->msock;
1267 /* Next, add all of the client sockets. */
1268 begin_critical_section(S_SESSION_TABLE);
1269 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1270 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1273 /* Don't select on dead sessions, only truly idle ones */
1274 if ( (ptr->state == CON_IDLE)
1275 && (ptr->kill_me == 0)
1276 && (ptr->client_socket > 0)
1278 FD_SET(ptr->client_socket, &readfds);
1279 if (ptr->client_socket > highest)
1280 highest = ptr->client_socket;
1282 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1284 ptr->state = CON_EXECUTING;
1287 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1289 ptr->state = CON_STARTING;
1293 end_critical_section(S_SESSION_TABLE);
1299 /* If we got this far, it means that there are no sessions
1300 * which a previous thread marked for attention, so we go
1301 * ahead and get ready to select().
1304 if (!server_shutting_down) {
1305 tv.tv_sec = 1; /* wake up every second if no input */
1307 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1314 /* Now figure out who made this select() unblock.
1315 * First, check for an error or exit condition.
1318 if (errno == EBADF) {
1319 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1323 if (errno != EINTR) {
1324 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1325 server_shutting_down = 1;
1329 syslog(LOG_DEBUG, "Interrupted select()\n");
1331 if (server_shutting_down) {
1338 else if (retval == 0) {
1339 if (server_shutting_down) {
1345 /* Next, check to see if it's a new client connecting * on a master socket. */
1347 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1349 if (FD_ISSET(serviceptr->msock, &readfds)) {
1350 ssock = accept(serviceptr->msock, NULL, 0);
1352 syslog(LOG_DEBUG, "New client socket %d", ssock);
1354 /* The master socket is non-blocking but the client
1355 * sockets need to be blocking, otherwise certain
1356 * operations barf on FreeBSD. Not a fatal error.
1358 if (fcntl(ssock, F_SETFL, 0) < 0) {
1360 "citserver: Can't set socket to blocking: %s\n",
1364 /* New context will be created already
1365 * set up in the CON_EXECUTING state.
1367 con = CreateNewContext();
1369 /* Assign our new socket number to it. */
1370 con->tcp_port = serviceptr->tcp_port;
1371 con->client_socket = ssock;
1372 con->h_command_function = serviceptr->h_command_function;
1373 con->h_async_function = serviceptr->h_async_function;
1374 con->h_greeting_function = serviceptr->h_greeting_function;
1375 con->ServiceName = serviceptr->ServiceName;
1377 /* Determine whether it's a local socket */
1378 if (serviceptr->sockpath != NULL) {
1379 con->is_local_socket = 1;
1382 /* Set the SO_REUSEADDR socket option */
1384 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1385 con->state = CON_GREETING;
1393 /* It must be a client socket. Find a context that has data
1394 * waiting on its socket *and* is in the CON_IDLE state. Any
1395 * active sockets other than our chosen one are marked as
1396 * CON_READY so the next thread that comes around can just bind
1397 * to one without having to select() again.
1399 begin_critical_section(S_SESSION_TABLE);
1400 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1401 int checkfd = ptr->client_socket;
1402 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1403 if (FD_ISSET(checkfd, &readfds)) {
1404 ptr->input_waiting = 1;
1406 bind_me = ptr; /* I choose you! */
1407 bind_me->state = CON_EXECUTING;
1410 ptr->state = CON_READY;
1412 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1414 bind_me = ptr; /* I choose you! */
1415 bind_me->state = CON_EXECUTING;
1418 ptr->state = CON_READY;
1423 end_critical_section(S_SESSION_TABLE);
1426 /* We're bound to a session */
1427 pthread_mutex_lock(&ThreadCountMutex);
1429 pthread_mutex_unlock(&ThreadCountMutex);
1431 if (bind_me != NULL) {
1432 become_session(bind_me);
1434 if (bind_me->state == CON_STARTING) {
1435 bind_me->state = CON_EXECUTING;
1436 begin_session(bind_me);
1437 bind_me->h_greeting_function();
1439 /* If the client has sent a command, execute it. */
1440 if (CC->input_waiting) {
1441 CC->h_command_function();
1443 while (HaveMoreLinesWaiting(CC))
1444 CC->h_command_function();
1446 CC->input_waiting = 0;
1449 /* If there are asynchronous messages waiting and the
1450 * client supports it, do those now */
1451 if ((CC->is_async) && (CC->async_waiting)
1452 && (CC->h_async_function != NULL)) {
1453 CC->h_async_function();
1454 CC->async_waiting = 0;
1457 force_purge = CC->kill_me;
1458 become_session(NULL);
1459 bind_me->state = CON_IDLE;
1462 dead_session_purge(force_purge);
1465 pthread_mutex_lock(&ThreadCountMutex);
1467 if ((active_workers + config.c_min_workers < num_workers) &&
1468 (num_workers > config.c_min_workers))
1471 pthread_mutex_unlock(&ThreadCountMutex);
1474 pthread_mutex_unlock(&ThreadCountMutex);
1477 /* If control reaches this point, the server is shutting down */
1478 pthread_mutex_lock(&ThreadCountMutex);
1480 pthread_mutex_unlock(&ThreadCountMutex);
1488 * Translate text facility name to syslog.h defined value.
1490 int SyslogFacility(char *name)
1499 { LOG_KERN, "kern" },
1500 { LOG_USER, "user" },
1501 { LOG_MAIL, "mail" },
1502 { LOG_DAEMON, "daemon" },
1503 { LOG_AUTH, "auth" },
1504 { LOG_SYSLOG, "syslog" },
1506 { LOG_NEWS, "news" },
1507 { LOG_UUCP, "uucp" },
1508 { LOG_LOCAL0, "local0" },
1509 { LOG_LOCAL1, "local1" },
1510 { LOG_LOCAL2, "local2" },
1511 { LOG_LOCAL3, "local3" },
1512 { LOG_LOCAL4, "local4" },
1513 { LOG_LOCAL5, "local5" },
1514 { LOG_LOCAL6, "local6" },
1515 { LOG_LOCAL7, "local7" },
1518 for(i = 0; facTbl[i].name != NULL; i++) {
1519 if(!strcasecmp(name, facTbl[i].name))
1520 return facTbl[i].facility;