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) {
106 Cc->self->signal = signum;
109 syslog(LOG_DEBUG, "Caught signal %d; shutting down.\n", signum);
110 exit_signal = signum;
114 static RETSIGTYPE signal_exit(int signum) {
121 * Some initialization stuff...
123 void init_sysdep(void) {
126 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
130 getrlimit(RLIMIT_NOFILE, &rl);
131 rl.rlim_cur = FD_SETSIZE;
132 rl.rlim_max = FD_SETSIZE;
133 setrlimit(RLIMIT_NOFILE, &rl);
137 /* If we've got OpenSSL, we're going to use it. */
143 * Set up a place to put thread-specific data.
144 * We only need a single pointer per thread - it points to the
145 * CitContext structure (in the ContextList linked list) of the
146 * session to which the calling thread is currently bound.
148 if (citthread_key_create(&MyConKey, NULL) != 0) {
149 syslog(LOG_CRIT, "Can't create TSD key: %s\n",
154 * The action for unexpected signals and exceptions should be to
155 * call signal_cleanup() to gracefully shut down the server.
158 sigaddset(&set, SIGINT); // intr = shutdown
159 sigaddset(&set, SIGHUP);
160 sigaddset(&set, SIGTERM);
161 sigprocmask(SIG_UNBLOCK, &set, NULL);
163 signal(SIGINT, signal_cleanup); // intr = shutdown
164 signal(SIGHUP, signal_cleanup);
165 signal(SIGTERM, signal_cleanup);
166 signal(SIGUSR2, signal_exit);
169 * Do not shut down the server on broken pipe signals, otherwise the
170 * whole Citadel service would come down whenever a single client
173 signal(SIGPIPE, SIG_IGN);
178 * This is a generic function to set up a master socket for listening on
179 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
181 * ip_addr IP address to bind
182 * port_number port number to bind
183 * queue_len number of incoming connections to allow in the queue
185 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
188 struct sockaddr_in6 sin6;
189 struct sockaddr_in sin4;
193 memset(&sin6, 0, sizeof(sin6));
194 memset(&sin4, 0, sizeof(sin4));
195 sin6.sin6_family = AF_INET6;
196 sin4.sin_family = AF_INET;
198 if ( (ip_addr == NULL) /* any IPv6 */
199 || (IsEmptyStr(ip_addr))
200 || (!strcmp(ip_addr, "*"))
203 sin6.sin6_addr = in6addr_any;
205 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
208 sin4.sin_addr.s_addr = INADDR_ANY;
210 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
213 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
214 snprintf(errormessage, SIZ,
215 "Error binding to [%s] : %s", ip_addr, strerror(errno)
217 syslog(LOG_ALERT, "%s\n", errormessage);
221 else /* specific IPv6 */
224 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
225 snprintf(errormessage, SIZ,
226 "Error binding to [%s] : %s", ip_addr, strerror(errno)
228 syslog(LOG_ALERT, "%s\n", errormessage);
233 if (port_number == 0) {
234 snprintf(errormessage, SIZ,
235 "Can't start: no port number specified."
237 syslog(LOG_ALERT, "%s\n", errormessage);
240 sin6.sin6_port = htons((u_short) port_number);
241 sin4.sin_port = htons((u_short) port_number);
243 p = getprotobyname("tcp");
245 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
247 snprintf(errormessage, SIZ,
248 "Can't create a listening socket: %s", strerror(errno)
250 syslog(LOG_ALERT, "%s\n", errormessage);
253 /* Set some socket options that make sense. */
255 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
257 if (ip_version == 6) {
258 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
261 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
265 snprintf(errormessage, SIZ,
266 "Can't bind: %s", strerror(errno)
268 syslog(LOG_ALERT, "%s\n", errormessage);
272 fcntl(s, F_SETFL, O_NONBLOCK);
274 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
275 snprintf(errormessage, SIZ,
276 "Can't listen: %s", strerror(errno)
278 syslog(LOG_ALERT, "%s\n", errormessage);
289 * Create a Unix domain socket and listen on it
291 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
293 struct sockaddr_un addr;
296 int actual_queue_len;
297 #ifdef HAVE_STRUCT_UCRED
301 actual_queue_len = queue_len;
302 if (actual_queue_len < 5) actual_queue_len = 5;
304 i = unlink(sockpath);
305 if ((i != 0) && (errno != ENOENT)) {
306 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
307 sockpath, strerror(errno)
309 syslog(LOG_EMERG, "%s\n", errormessage);
313 memset(&addr, 0, sizeof(addr));
314 addr.sun_family = AF_UNIX;
315 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
317 s = socket(AF_UNIX, SOCK_STREAM, 0);
319 snprintf(errormessage, SIZ,
320 "citserver: Can't create a socket: %s",
322 syslog(LOG_EMERG, "%s\n", errormessage);
326 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
327 snprintf(errormessage, SIZ,
328 "citserver: Can't bind: %s",
330 syslog(LOG_EMERG, "%s\n", errormessage);
334 /* set to nonblock - we need this for some obscure situations */
335 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
336 snprintf(errormessage, SIZ,
337 "citserver: Can't set socket to non-blocking: %s",
339 syslog(LOG_EMERG, "%s\n", errormessage);
344 if (listen(s, actual_queue_len) < 0) {
345 snprintf(errormessage, SIZ,
346 "citserver: Can't listen: %s",
348 syslog(LOG_EMERG, "%s\n", errormessage);
352 #ifdef HAVE_STRUCT_UCRED
353 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
356 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
363 * The following functions implement output buffering on operating systems which
364 * support it (such as Linux and various BSD flavors).
368 # define HAVE_TCP_BUFFERING
371 # define HAVE_TCP_BUFFERING
372 # define TCP_CORK TCP_NOPUSH
374 #endif /* TCP_CORK */
375 #endif /* HAVE_DARWIN */
377 static unsigned on = 1, off = 0;
379 void buffer_output(void) {
380 #ifdef HAVE_TCP_BUFFERING
382 if (!CC->redirect_ssl)
384 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
388 void unbuffer_output(void) {
389 #ifdef HAVE_TCP_BUFFERING
391 if (!CC->redirect_ssl)
393 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
397 void flush_output(void) {
398 #ifdef HAVE_TCP_BUFFERING
399 struct CitContext *CCC = CC;
400 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
401 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
406 static void flush_client_inbuf(void)
410 FlushStrBuf(CCC->ReadBuf);
411 CCC->RecvBuf->ReadWritePointer = NULL;
418 * client_close() ... close the client socket
420 void client_close(void) {
421 CitContext *CCC = CC;
425 if (CCC->client_socket <= 0) return;
426 syslog(LOG_DEBUG, "Closing socket %d\n", CCC->client_socket);
427 r = close(CCC->client_socket);
428 if (!r) syslog(LOG_INFO, "close() failed: %s\n", strerror(errno));
429 CCC->client_socket = -1 ;
436 * client_write() ... Send binary data to the client.
438 int client_write(const char *buf, int nbytes)
440 int bytes_written = 0;
442 #ifndef HAVE_TCP_BUFFERING
443 int old_buffer_len = 0;
449 if (nbytes < 1) return(0);
459 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
461 fd = fopen(fn, "a+");
464 fprintf(fd, "Sending: BufSize: %d BufContent: [",
466 rv = fwrite(buf, nbytes, 1, fd);
472 // flush_client_inbuf();
473 if (Ctx->redirect_buffer != NULL) {
474 StrBufAppendBufPlain(Ctx->redirect_buffer,
480 if (Ctx->redirect_ssl) {
481 client_write_ssl(buf, nbytes);
485 if (Ctx->client_socket == -1) return -1;
487 fdflags = fcntl(Ctx->client_socket, F_GETFL);
489 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
490 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
492 FD_SET(Ctx->client_socket, &wset);
493 if (select(1, NULL, &wset, NULL, NULL) == -1) {
496 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
497 if (CtdlThreadCheckStop()) {
498 CC->kill_me = KILLME_SELECT_INTERRUPTED;
501 /* can't trust fd's and stuff so we need to re-create them */
506 "client_write(%d bytes) select failed: %s (%d)\n",
507 nbytes - bytes_written,
508 strerror(errno), errno
512 Ctx->kill_me = KILLME_SELECT_FAILED;
518 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
521 "client_write(%d bytes) failed: %s (%d)\n",
522 nbytes - bytes_written,
523 strerror(errno), errno
527 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
528 Ctx->kill_me = KILLME_WRITE_FAILED;
531 bytes_written = bytes_written + retval;
536 void cputbuf(const StrBuf *Buf) {
537 client_write(ChrPtr(Buf), StrLength(Buf));
542 * cprintf() Send formatted printable data to the client.
543 * Implemented in terms of client_write() so it's technically not sysdep...
545 void cprintf(const char *format, ...) {
549 va_start(arg_ptr, format);
550 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
551 buf[sizeof buf - 2] = '\n';
552 client_write(buf, strlen(buf));
558 * Read data from the client socket.
560 * sock socket fd to read from
561 * buf buffer to read into
562 * bytes number of bytes to read
563 * timeout Number of seconds to wait before timing out
565 * Possible return values:
566 * 1 Requested number of bytes has been read.
567 * 0 Request timed out.
568 * -1 Connection is broken, or other error.
570 int client_read_blob(StrBuf *Target, int bytes, int timeout)
577 if (CCC->redirect_ssl) {
583 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
585 fd = fopen(fn, "a+");
586 fprintf(fd, "Reading BLOB: BufSize: %d ",
588 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
594 retval = client_read_sslblob(Target, bytes, timeout);
601 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
603 fd = fopen(fn, "a+");
604 fprintf(fd, "Read: %d BufContent: [",
606 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
621 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
623 fd = fopen(fn, "a+");
624 fprintf(fd, "Reading BLOB: BufSize: %d ",
626 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
632 retval = StrBufReadBLOBBuffered(Target,
634 &CCC->RecvBuf.ReadWritePointer,
641 syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
646 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
648 fd = fopen(fn, "a+");
649 fprintf(fd, "Read: %d BufContent: [",
651 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
661 * to make client_read_random_blob() more efficient, increase buffer size.
662 * just use in greeting function, else your buffer may be flushed
664 void client_set_inbound_buf(long N)
667 FlushStrBuf(CCC->RecvBuf.Buf);
668 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
671 int client_read_random_blob(StrBuf *Target, int timeout)
676 rc = client_read_blob(Target, 1, timeout);
682 len = StrLength(CCC->RecvBuf.Buf);
683 pch = ChrPtr(CCC->RecvBuf.Buf);
687 if (CCC->RecvBuf.ReadWritePointer != NULL) {
688 len -= CCC->RecvBuf.ReadWritePointer - pch;
689 pch = CCC->RecvBuf.ReadWritePointer;
691 StrBufAppendBufPlain(Target, pch, len, 0);
692 FlushStrBuf(CCC->RecvBuf.Buf);
693 CCC->RecvBuf.ReadWritePointer = NULL;
700 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
702 fd = fopen(fn, "a+");
703 fprintf(fd, "Read: BufSize: %d BufContent: [",
705 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
713 return StrLength(Target);
721 int client_read_to(char *buf, int bytes, int timeout)
726 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
735 ChrPtr(CCC->MigrateBuf),
736 StrLength(CCC->MigrateBuf) + 1);
737 FlushStrBuf(CCC->MigrateBuf);
743 int HaveMoreLinesWaiting(CitContext *CCC)
745 if ((CCC->kill_me != 0) ||
746 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
747 (StrLength(CCC->RecvBuf.Buf) == 0) &&
748 (CCC->client_socket != -1)) )
756 * Read data from the client socket with default timeout.
757 * (This is implemented in terms of client_read_to() and could be
758 * justifiably moved out of sysdep.c)
760 INLINE int client_read(char *buf, int bytes)
762 return(client_read_to(buf, bytes, config.c_sleeping));
765 int CtdlClientGetLine(StrBuf *Target)
773 if (CCC->redirect_ssl) {
783 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
785 fd = fopen(fn, "a+");
786 pch = ChrPtr(CCC->RecvBuf.Buf);
787 len = StrLength(CCC->RecvBuf.Buf);
788 if (CCC->RecvBuf.ReadWritePointer != NULL)
789 rlen = CCC->RecvBuf.ReadWritePointer - pch;
793 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
796 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
799 rc = client_readline_sslbuffer(Target,
801 &CCC->RecvBuf.ReadWritePointer,
804 pch = ChrPtr(CCC->RecvBuf.Buf);
805 nlen = StrLength(CCC->RecvBuf.Buf);
806 if (CCC->RecvBuf.ReadWritePointer != NULL)
807 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
811 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
812 len, nlen, rlen, nrlen, pch);
814 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
815 len, nlen, rlen, nrlen);
817 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
818 StrLength(Target), ChrPtr(Target));
834 int len, rlen, nlen, nrlen;
837 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
839 fd = fopen(fn, "a+");
840 pch = ChrPtr(CCC->RecvBuf.Buf);
841 len = StrLength(CCC->RecvBuf.Buf);
842 if (CCC->RecvBuf.ReadWritePointer != NULL)
843 rlen = CCC->RecvBuf.ReadWritePointer - pch;
847 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
850 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
853 rc = StrBufTCP_read_buffered_line_fast(Target,
855 &CCC->RecvBuf.ReadWritePointer,
862 pch = ChrPtr(CCC->RecvBuf.Buf);
863 nlen = StrLength(CCC->RecvBuf.Buf);
864 if (CCC->RecvBuf.ReadWritePointer != NULL)
865 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
869 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
870 len, nlen, rlen, nrlen, pch);
872 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
873 len, nlen, rlen, nrlen);
875 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
876 StrLength(Target), ChrPtr(Target));
879 if ((rc < 0) && (Error != NULL))
891 * client_getln() ... Get a LF-terminated line of text from the client.
892 * (This is implemented in terms of client_read() and could be
893 * justifiably moved out of sysdep.c)
895 int client_getln(char *buf, int bufsize)
901 retval = CtdlClientGetLine(CCC->MigrateBuf);
906 i = StrLength(CCC->MigrateBuf);
907 pCh = ChrPtr(CCC->MigrateBuf);
908 /* Strip the trailing LF, and the trailing CR if present.
913 && ( (pCh[i - 1]==13)
914 || ( pCh[i - 1]==10)) ) {
920 FlushStrBuf(CCC->MigrateBuf);
922 safestrncpy(&buf[i], "000", bufsize - i);
929 * Cleanup any contexts that are left lying around
933 void close_masters (void)
935 struct ServiceFunctionHook *serviceptr;
938 * close all protocol master sockets
940 for (serviceptr = ServiceHookTable; serviceptr != NULL;
941 serviceptr = serviceptr->next ) {
943 if (serviceptr->tcp_port > 0)
945 syslog(LOG_INFO, "Closing listener on port %d\n",
946 serviceptr->tcp_port);
947 serviceptr->tcp_port = 0;
950 if (serviceptr->sockpath != NULL)
951 syslog(LOG_INFO, "Closing listener on '%s'\n",
952 serviceptr->sockpath);
954 close(serviceptr->msock);
955 /* If it's a Unix domain socket, remove the file. */
956 if (serviceptr->sockpath != NULL) {
957 unlink(serviceptr->sockpath);
958 serviceptr->sockpath = NULL;
965 * The system-dependent part of master_cleanup() - close the master socket.
967 void sysdep_master_cleanup(void) {
976 CtdlDestroyProtoHooks();
977 CtdlDestroyDeleteHooks();
978 CtdlDestroyXmsgHooks();
979 CtdlDestroyNetprocHooks();
980 CtdlDestroyUserHooks();
981 CtdlDestroyMessageHook();
982 CtdlDestroyCleanupHooks();
983 CtdlDestroyFixedOutputHooks();
984 CtdlDestroySessionHooks();
985 CtdlDestroyServiceHook();
986 CtdlDestroyRoomHooks();
987 CtdlDestroySearchHooks();
988 #ifdef HAVE_BACKTRACE
996 void graceful_shutdown(int signum) {
997 kill(current_child, signum);
998 unlink(file_pid_file);
1003 int nFireUpsNonRestart = 0;
1004 pid_t ForkedPid = 1;
1007 * Start running as a daemon.
1009 void start_daemon(int unused) {
1017 /* Close stdin/stdout/stderr and replace them with /dev/null.
1018 * We don't just call close() because we don't want these fd's
1019 * to be reused for other files.
1021 if (chdir(ctdl_run_dir) != 0)
1023 "unable to change into directory [%s]: %s",
1024 ctdl_run_dir, strerror(errno));
1031 signal(SIGHUP, SIG_IGN);
1032 signal(SIGINT, SIG_IGN);
1033 signal(SIGQUIT, SIG_IGN);
1037 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1038 (freopen("/dev/null", "w", stdout) != stdout) ||
1039 (freopen("/dev/null", "w", stderr) != stderr))
1041 "unable to reopen stdin/out/err %s",
1046 current_child = fork();
1048 signal(SIGTERM, graceful_shutdown);
1050 if (current_child < 0) {
1055 else if (current_child == 0) {
1056 return; /* continue starting citadel. */
1060 fp = fopen(file_pid_file, "w");
1062 fprintf(fp, ""F_PID_T"\n", getpid());
1065 waitpid(current_child, &status, 0);
1068 nFireUpsNonRestart = nFireUps;
1070 /* Exit code 0 means the watcher should exit */
1071 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1075 /* Exit code 101-109 means the watcher should exit */
1076 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1080 /* Any other exit code, or no exit code, means we should restart. */
1084 ForkedPid = current_child;
1087 } while (do_restart);
1089 unlink(file_pid_file);
1090 exit(WEXITSTATUS(status));
1095 void checkcrash(void)
1097 if (nFireUpsNonRestart != nFireUps)
1101 CrashMail = NewStrBuf();
1102 syslog(LOG_ALERT, "Posting crash message\n");
1103 StrBufPrintf(CrashMail,
1105 " The Citadel server process (citserver) terminated unexpectedly."
1107 " This could be the result of a bug in the server program, or some external "
1109 " You can obtain more information about this by enabling core dumps.\n \n"
1110 " For more information, please see:\n \n"
1111 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1114 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1116 ctdl_run_dir, ForkedPid);
1117 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1118 FreeStrBuf(&CrashMail);
1124 * Generic routine to convert a login name to a full name (gecos)
1125 * Returns nonzero if a conversion took place
1127 int convert_login(char NameToConvert[]) {
1131 pw = getpwnam(NameToConvert);
1136 strcpy(NameToConvert, pw->pw_gecos);
1137 for (a=0; a<strlen(NameToConvert); ++a) {
1138 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1147 * This loop just keeps going and going and going...
1149 void *worker_thread(void *arg) {
1152 CitContext *bind_me = NULL;
1156 int force_purge = 0;
1159 while (!CtdlThreadCheckStop()) {
1161 /* make doubly sure we're not holding any stale db handles
1162 * which might cause a deadlock.
1164 cdb_check_handles();
1165 do_select: force_purge = 0;
1166 bind_me = NULL; /* Which session shall we handle? */
1168 /* Initialize the fdset. */
1172 begin_critical_section(S_SESSION_TABLE);
1173 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1174 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1177 /* Don't select on dead sessions, only truly idle ones */
1178 if ( (ptr->state == CON_IDLE)
1179 && (ptr->kill_me == 0)
1180 && (ptr->client_socket > 0)
1182 FD_SET(ptr->client_socket, &readfds);
1183 if (ptr->client_socket > highest)
1184 highest = ptr->client_socket;
1186 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1188 ptr->state = CON_EXECUTING;
1191 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1193 ptr->state = CON_STARTING;
1197 end_critical_section(S_SESSION_TABLE);
1203 /* If we got this far, it means that there are no sessions
1204 * which a previous thread marked for attention, so we go
1205 * ahead and get ready to select().
1208 if (!CtdlThreadCheckStop()) {
1209 tv.tv_sec = 1; /* wake up every second if no input */
1211 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1216 /* Now figure out who made this select() unblock.
1217 * First, check for an error or exit condition.
1220 if (errno == EBADF) {
1221 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1225 if (errno != EINTR) {
1226 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1227 CtdlThreadStopAll();
1231 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1233 if (CtdlThreadCheckStop()) return(NULL);
1237 else if(retval == 0) {
1238 if (CtdlThreadCheckStop()) return(NULL);
1241 /* It must be a client socket. Find a context that has data
1242 * waiting on its socket *and* is in the CON_IDLE state. Any
1243 * active sockets other than our chosen one are marked as
1244 * CON_READY so the next thread that comes around can just bind
1245 * to one without having to select() again.
1247 begin_critical_section(S_SESSION_TABLE);
1248 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1249 int checkfd = ptr->client_socket;
1250 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1251 if (FD_ISSET(checkfd, &readfds)) {
1252 ptr->input_waiting = 1;
1254 bind_me = ptr; /* I choose you! */
1255 bind_me->state = CON_EXECUTING;
1258 ptr->state = CON_READY;
1260 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1262 bind_me = ptr; /* I choose you! */
1263 bind_me->state = CON_EXECUTING;
1266 ptr->state = CON_READY;
1271 end_critical_section(S_SESSION_TABLE);
1274 /* We're bound to a session */
1275 if (bind_me != NULL) {
1276 become_session(bind_me);
1278 if (bind_me->state == CON_STARTING) {
1279 bind_me->state = CON_EXECUTING;
1280 begin_session(bind_me);
1281 bind_me->h_greeting_function();
1283 /* If the client has sent a command, execute it. */
1284 if (CC->input_waiting) {
1285 CC->h_command_function();
1287 while (HaveMoreLinesWaiting(CC))
1288 CC->h_command_function();
1290 CC->input_waiting = 0;
1293 /* If there are asynchronous messages waiting and the
1294 * client supports it, do those now */
1295 if ((CC->is_async) && (CC->async_waiting)
1296 && (CC->h_async_function != NULL)) {
1297 CC->h_async_function();
1298 CC->async_waiting = 0;
1301 force_purge = CC->kill_me;
1302 become_session(NULL);
1303 bind_me->state = CON_IDLE;
1306 dead_session_purge(force_purge);
1309 /* If control reaches this point, the server is shutting down */
1317 * A function to handle selecting on master sockets.
1318 * In other words it handles new connections.
1321 void *select_on_master (void *arg)
1323 struct ServiceFunctionHook *serviceptr;
1327 int ssock; /* Descriptor for client socket */
1328 CitContext *con= NULL; /* Temporary context pointer */
1332 struct CitContext select_on_master_CC;
1334 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1335 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1337 while (!CtdlThreadCheckStop()) {
1338 /* Initialize the fdset. */
1339 FD_ZERO(&master_fds);
1342 /* First, add the various master sockets to the fdset. */
1343 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1344 serviceptr = serviceptr->next ) {
1345 m = serviceptr->msock;
1346 FD_SET(m, &master_fds);
1352 if (!CtdlThreadCheckStop()) {
1353 tv.tv_sec = 60; /* wake up every second if no input */
1355 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1360 /* Now figure out who made this select() unblock.
1361 * First, check for an error or exit condition.
1364 if (errno == EBADF) {
1365 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1369 if (errno != EINTR) {
1370 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1371 CtdlThreadStopAll();
1374 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1376 if (CtdlThreadCheckStop()) return(NULL);
1380 else if(retval == 0) {
1381 if (CtdlThreadCheckStop()) return(NULL);
1384 /* Next, check to see if it's a new client connecting
1385 * on a master socket.
1387 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1388 serviceptr = serviceptr->next ) {
1390 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1391 ssock = accept(serviceptr->msock, NULL, 0);
1393 syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1395 /* The master socket is non-blocking but the client
1396 * sockets need to be blocking, otherwise certain
1397 * operations barf on FreeBSD. Not a fatal error.
1399 if (fcntl(ssock, F_SETFL, 0) < 0) {
1401 "citserver: Can't set socket to blocking: %s\n",
1405 /* New context will be created already
1406 * set up in the CON_EXECUTING state.
1408 con = CreateNewContext();
1410 /* Assign our new socket number to it. */
1411 con->client_socket = ssock;
1412 con->h_command_function = serviceptr->h_command_function;
1413 con->h_async_function = serviceptr->h_async_function;
1414 con->h_greeting_function = serviceptr->h_greeting_function;
1415 con->ServiceName = serviceptr->ServiceName;
1417 /* Determine whether it's a local socket */
1418 if (serviceptr->sockpath != NULL) {
1419 con->is_local_socket = 1;
1422 /* Set the SO_REUSEADDR socket option */
1424 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1425 con->state = CON_GREETING;
1433 CtdlClearSystemContext();
1442 * Translate text facility name to syslog.h defined value.
1444 int SyslogFacility(char *name)
1453 { LOG_KERN, "kern" },
1454 { LOG_USER, "user" },
1455 { LOG_MAIL, "mail" },
1456 { LOG_DAEMON, "daemon" },
1457 { LOG_AUTH, "auth" },
1458 { LOG_SYSLOG, "syslog" },
1460 { LOG_NEWS, "news" },
1461 { LOG_UUCP, "uucp" },
1462 { LOG_LOCAL0, "local0" },
1463 { LOG_LOCAL1, "local1" },
1464 { LOG_LOCAL2, "local2" },
1465 { LOG_LOCAL3, "local3" },
1466 { LOG_LOCAL4, "local4" },
1467 { LOG_LOCAL5, "local5" },
1468 { LOG_LOCAL6, "local6" },
1469 { LOG_LOCAL7, "local7" },
1472 for(i = 0; facTbl[i].name != NULL; i++) {
1473 if(!strcasecmp(name, facTbl[i].name))
1474 return facTbl[i].facility;