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;
913 * close all protocol master sockets
915 for (serviceptr = ServiceHookTable; serviceptr != NULL;
916 serviceptr = serviceptr->next ) {
918 if (serviceptr->tcp_port > 0)
920 syslog(LOG_INFO, "Closing %d listener on port %d\n",
922 serviceptr->tcp_port);
923 serviceptr->tcp_port = 0;
926 if (serviceptr->sockpath != NULL)
927 syslog(LOG_INFO, "Closing %d listener on '%s'\n",
929 serviceptr->sockpath);
930 if (serviceptr->msock != -1)
931 close(serviceptr->msock);
932 /* If it's a Unix domain socket, remove the file. */
933 if (serviceptr->sockpath != NULL) {
934 unlink(serviceptr->sockpath);
935 serviceptr->sockpath = NULL;
942 * The system-dependent part of master_cleanup() - close the master socket.
944 void sysdep_master_cleanup(void) {
953 CtdlDestroyProtoHooks();
954 CtdlDestroyDeleteHooks();
955 CtdlDestroyXmsgHooks();
956 CtdlDestroyNetprocHooks();
957 CtdlDestroyUserHooks();
958 CtdlDestroyMessageHook();
959 CtdlDestroyCleanupHooks();
960 CtdlDestroyFixedOutputHooks();
961 CtdlDestroySessionHooks();
962 CtdlDestroyServiceHook();
963 CtdlDestroyRoomHooks();
964 CtdlDestroySearchHooks();
965 CtdlDestroyDebugTable();
966 #ifdef HAVE_BACKTRACE
974 void graceful_shutdown(int signum) {
975 kill(current_child, signum);
976 unlink(file_pid_file);
981 int nFireUpsNonRestart = 0;
985 * Start running as a daemon.
987 void start_daemon(int unused) {
995 /* Close stdin/stdout/stderr and replace them with /dev/null.
996 * We don't just call close() because we don't want these fd's
997 * to be reused for other files.
999 if (chdir(ctdl_run_dir) != 0)
1001 "unable to change into directory [%s]: %s",
1002 ctdl_run_dir, strerror(errno));
1009 signal(SIGHUP, SIG_IGN);
1010 signal(SIGINT, SIG_IGN);
1011 signal(SIGQUIT, SIG_IGN);
1015 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1016 (freopen("/dev/null", "w", stdout) != stdout) ||
1017 (freopen("/dev/null", "w", stderr) != stderr))
1019 "unable to reopen stdin/out/err %s",
1024 current_child = fork();
1026 signal(SIGTERM, graceful_shutdown);
1028 if (current_child < 0) {
1033 else if (current_child == 0) {
1034 return; /* continue starting citadel. */
1038 fp = fopen(file_pid_file, "w");
1040 fprintf(fp, ""F_PID_T"\n", getpid());
1043 waitpid(current_child, &status, 0);
1046 nFireUpsNonRestart = nFireUps;
1048 /* Exit code 0 means the watcher should exit */
1049 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1053 /* Exit code 101-109 means the watcher should exit */
1054 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1058 /* Any other exit code, or no exit code, means we should restart. */
1062 ForkedPid = current_child;
1065 } while (do_restart);
1067 unlink(file_pid_file);
1068 exit(WEXITSTATUS(status));
1073 void checkcrash(void)
1075 if (nFireUpsNonRestart != nFireUps)
1079 CrashMail = NewStrBuf();
1080 syslog(LOG_ALERT, "Posting crash message\n");
1081 StrBufPrintf(CrashMail,
1083 " The Citadel server process (citserver) terminated unexpectedly."
1085 " This could be the result of a bug in the server program, or some external "
1087 " You can obtain more information about this by enabling core dumps.\n \n"
1088 " For more information, please see:\n \n"
1089 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1092 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1094 ctdl_run_dir, ForkedPid);
1095 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1096 FreeStrBuf(&CrashMail);
1102 * Generic routine to convert a login name to a full name (gecos)
1103 * Returns nonzero if a conversion took place
1105 int convert_login(char NameToConvert[]) {
1109 pw = getpwnam(NameToConvert);
1114 strcpy(NameToConvert, pw->pw_gecos);
1115 for (a=0; a<strlen(NameToConvert); ++a) {
1116 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1125 * This loop just keeps going and going and going...
1127 void *worker_thread(void *blah) {
1130 CitContext *bind_me = NULL;
1134 int force_purge = 0;
1135 struct ServiceFunctionHook *serviceptr;
1136 int ssock; /* Descriptor for client socket */
1137 CitContext *con = NULL; /* Temporary context pointer */
1142 while (!server_shutting_down) {
1144 /* make doubly sure we're not holding any stale db handles
1145 * which might cause a deadlock.
1147 cdb_check_handles();
1148 do_select: force_purge = 0;
1149 bind_me = NULL; /* Which session shall we handle? */
1151 /* Initialize the fdset. */
1155 /* First, add the various master sockets to the fdset. */
1156 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1157 FD_SET(serviceptr->msock, &readfds);
1158 if (serviceptr->msock > highest) {
1159 highest = serviceptr->msock;
1163 /* Next, add all of the client sockets. */
1164 begin_critical_section(S_SESSION_TABLE);
1165 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1166 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1169 /* Don't select on dead sessions, only truly idle ones */
1170 if ( (ptr->state == CON_IDLE)
1171 && (ptr->kill_me == 0)
1172 && (ptr->client_socket > 0)
1174 FD_SET(ptr->client_socket, &readfds);
1175 if (ptr->client_socket > highest)
1176 highest = ptr->client_socket;
1178 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1180 ptr->state = CON_EXECUTING;
1183 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1185 ptr->state = CON_STARTING;
1189 end_critical_section(S_SESSION_TABLE);
1195 /* If we got this far, it means that there are no sessions
1196 * which a previous thread marked for attention, so we go
1197 * ahead and get ready to select().
1200 if (!server_shutting_down) {
1201 tv.tv_sec = 1; /* wake up every second if no input */
1203 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1210 /* Now figure out who made this select() unblock.
1211 * First, check for an error or exit condition.
1214 if (errno == EBADF) {
1215 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1218 if (errno != EINTR) {
1219 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1220 server_shutting_down = 1;
1224 syslog(LOG_DEBUG, "Interrupted select()\n");
1226 if (server_shutting_down) {
1233 else if (retval == 0) {
1234 if (server_shutting_down) {
1240 /* Next, check to see if it's a new client connecting * on a master socket. */
1242 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1244 if (FD_ISSET(serviceptr->msock, &readfds)) {
1245 ssock = accept(serviceptr->msock, NULL, 0);
1247 syslog(LOG_DEBUG, "New client socket %d", ssock);
1249 /* The master socket is non-blocking but the client
1250 * sockets need to be blocking, otherwise certain
1251 * operations barf on FreeBSD. Not a fatal error.
1253 if (fcntl(ssock, F_SETFL, 0) < 0) {
1255 "citserver: Can't set socket to blocking: %s\n",
1259 /* New context will be created already
1260 * set up in the CON_EXECUTING state.
1262 con = CreateNewContext();
1264 /* Assign our new socket number to it. */
1265 con->tcp_port = serviceptr->tcp_port;
1266 con->client_socket = ssock;
1267 con->h_command_function = serviceptr->h_command_function;
1268 con->h_async_function = serviceptr->h_async_function;
1269 con->h_greeting_function = serviceptr->h_greeting_function;
1270 con->ServiceName = serviceptr->ServiceName;
1272 /* Determine whether it's a local socket */
1273 if (serviceptr->sockpath != NULL) {
1274 con->is_local_socket = 1;
1277 /* Set the SO_REUSEADDR socket option */
1279 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1280 con->state = CON_GREETING;
1288 /* It must be a client socket. Find a context that has data
1289 * waiting on its socket *and* is in the CON_IDLE state. Any
1290 * active sockets other than our chosen one are marked as
1291 * CON_READY so the next thread that comes around can just bind
1292 * to one without having to select() again.
1294 begin_critical_section(S_SESSION_TABLE);
1295 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1296 int checkfd = ptr->client_socket;
1297 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1298 if (FD_ISSET(checkfd, &readfds)) {
1299 ptr->input_waiting = 1;
1301 bind_me = ptr; /* I choose you! */
1302 bind_me->state = CON_EXECUTING;
1305 ptr->state = CON_READY;
1307 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1309 bind_me = ptr; /* I choose you! */
1310 bind_me->state = CON_EXECUTING;
1313 ptr->state = CON_READY;
1318 end_critical_section(S_SESSION_TABLE);
1321 /* We're bound to a session */
1323 if (bind_me != NULL) {
1324 become_session(bind_me);
1326 if (bind_me->state == CON_STARTING) {
1327 bind_me->state = CON_EXECUTING;
1328 begin_session(bind_me);
1329 bind_me->h_greeting_function();
1331 /* If the client has sent a command, execute it. */
1332 if (CC->input_waiting) {
1333 CC->h_command_function();
1335 while (HaveMoreLinesWaiting(CC))
1336 CC->h_command_function();
1338 CC->input_waiting = 0;
1341 /* If there are asynchronous messages waiting and the
1342 * client supports it, do those now */
1343 if ((CC->is_async) && (CC->async_waiting)
1344 && (CC->h_async_function != NULL)) {
1345 CC->h_async_function();
1346 CC->async_waiting = 0;
1349 force_purge = CC->kill_me;
1350 become_session(NULL);
1351 bind_me->state = CON_IDLE;
1354 dead_session_purge(force_purge);
1359 /* If control reaches this point, the server is shutting down */
1368 * Translate text facility name to syslog.h defined value.
1370 int SyslogFacility(char *name)
1379 { LOG_KERN, "kern" },
1380 { LOG_USER, "user" },
1381 { LOG_MAIL, "mail" },
1382 { LOG_DAEMON, "daemon" },
1383 { LOG_AUTH, "auth" },
1384 { LOG_SYSLOG, "syslog" },
1386 { LOG_NEWS, "news" },
1387 { LOG_UUCP, "uucp" },
1388 { LOG_LOCAL0, "local0" },
1389 { LOG_LOCAL1, "local1" },
1390 { LOG_LOCAL2, "local2" },
1391 { LOG_LOCAL3, "local3" },
1392 { LOG_LOCAL4, "local4" },
1393 { LOG_LOCAL5, "local5" },
1394 { LOG_LOCAL6, "local6" },
1395 { LOG_LOCAL7, "local7" },
1398 for(i = 0; facTbl[i].name != NULL; i++) {
1399 if(!strcasecmp(name, facTbl[i].name))
1400 return facTbl[i].facility;