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) {
107 syslog(LOG_DEBUG, "Caught signal %d; shutting down.\n", signum);
108 exit_signal = signum;
112 static RETSIGTYPE signal_exit(int signum) {
119 * Some initialization stuff...
121 void init_sysdep(void) {
124 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
128 getrlimit(RLIMIT_NOFILE, &rl);
129 rl.rlim_cur = FD_SETSIZE;
130 rl.rlim_max = FD_SETSIZE;
131 setrlimit(RLIMIT_NOFILE, &rl);
135 /* If we've got OpenSSL, we're going to use it. */
141 * Set up a place to put thread-specific data.
142 * We only need a single pointer per thread - it points to the
143 * CitContext structure (in the ContextList linked list) of the
144 * session to which the calling thread is currently bound.
146 if (citthread_key_create(&MyConKey, NULL) != 0) {
147 syslog(LOG_CRIT, "Can't create TSD key: %s\n",
152 * The action for unexpected signals and exceptions should be to
153 * call signal_cleanup() to gracefully shut down the server.
156 sigaddset(&set, SIGINT); // intr = shutdown
157 sigaddset(&set, SIGHUP);
158 sigaddset(&set, SIGTERM);
159 sigprocmask(SIG_UNBLOCK, &set, NULL);
161 signal(SIGINT, signal_cleanup); // intr = shutdown
162 signal(SIGHUP, signal_cleanup);
163 signal(SIGTERM, signal_cleanup);
164 signal(SIGUSR2, signal_exit);
167 * Do not shut down the server on broken pipe signals, otherwise the
168 * whole Citadel service would come down whenever a single client
171 signal(SIGPIPE, SIG_IGN);
176 * This is a generic function to set up a master socket for listening on
177 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
179 * ip_addr IP address to bind
180 * port_number port number to bind
181 * queue_len number of incoming connections to allow in the queue
183 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
186 struct sockaddr_in6 sin6;
187 struct sockaddr_in sin4;
191 memset(&sin6, 0, sizeof(sin6));
192 memset(&sin4, 0, sizeof(sin4));
193 sin6.sin6_family = AF_INET6;
194 sin4.sin_family = AF_INET;
196 if ( (ip_addr == NULL) /* any IPv6 */
197 || (IsEmptyStr(ip_addr))
198 || (!strcmp(ip_addr, "*"))
201 sin6.sin6_addr = in6addr_any;
203 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
206 sin4.sin_addr.s_addr = INADDR_ANY;
208 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
211 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
212 snprintf(errormessage, SIZ,
213 "Error binding to [%s] : %s", ip_addr, strerror(errno)
215 syslog(LOG_ALERT, "%s\n", errormessage);
219 else /* specific IPv6 */
222 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
223 snprintf(errormessage, SIZ,
224 "Error binding to [%s] : %s", ip_addr, strerror(errno)
226 syslog(LOG_ALERT, "%s\n", errormessage);
231 if (port_number == 0) {
232 snprintf(errormessage, SIZ,
233 "Can't start: no port number specified."
235 syslog(LOG_ALERT, "%s\n", errormessage);
238 sin6.sin6_port = htons((u_short) port_number);
239 sin4.sin_port = htons((u_short) port_number);
241 p = getprotobyname("tcp");
243 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
245 snprintf(errormessage, SIZ,
246 "Can't create a listening socket: %s", strerror(errno)
248 syslog(LOG_ALERT, "%s\n", errormessage);
251 /* Set some socket options that make sense. */
253 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
255 if (ip_version == 6) {
256 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
259 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
263 snprintf(errormessage, SIZ,
264 "Can't bind: %s", strerror(errno)
266 syslog(LOG_ALERT, "%s\n", errormessage);
270 fcntl(s, F_SETFL, O_NONBLOCK);
272 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
273 snprintf(errormessage, SIZ,
274 "Can't listen: %s", strerror(errno)
276 syslog(LOG_ALERT, "%s\n", errormessage);
287 * Create a Unix domain socket and listen on it
289 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
291 struct sockaddr_un addr;
294 int actual_queue_len;
295 #ifdef HAVE_STRUCT_UCRED
299 actual_queue_len = queue_len;
300 if (actual_queue_len < 5) actual_queue_len = 5;
302 i = unlink(sockpath);
303 if ((i != 0) && (errno != ENOENT)) {
304 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
305 sockpath, strerror(errno)
307 syslog(LOG_EMERG, "%s\n", errormessage);
311 memset(&addr, 0, sizeof(addr));
312 addr.sun_family = AF_UNIX;
313 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
315 s = socket(AF_UNIX, SOCK_STREAM, 0);
317 snprintf(errormessage, SIZ,
318 "citserver: Can't create a socket: %s",
320 syslog(LOG_EMERG, "%s\n", errormessage);
324 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
325 snprintf(errormessage, SIZ,
326 "citserver: Can't bind: %s",
328 syslog(LOG_EMERG, "%s\n", errormessage);
332 /* set to nonblock - we need this for some obscure situations */
333 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
334 snprintf(errormessage, SIZ,
335 "citserver: Can't set socket to non-blocking: %s",
337 syslog(LOG_EMERG, "%s\n", errormessage);
342 if (listen(s, actual_queue_len) < 0) {
343 snprintf(errormessage, SIZ,
344 "citserver: Can't listen: %s",
346 syslog(LOG_EMERG, "%s\n", errormessage);
350 #ifdef HAVE_STRUCT_UCRED
351 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
354 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
361 * The following functions implement output buffering on operating systems which
362 * support it (such as Linux and various BSD flavors).
366 # define HAVE_TCP_BUFFERING
369 # define HAVE_TCP_BUFFERING
370 # define TCP_CORK TCP_NOPUSH
372 #endif /* TCP_CORK */
373 #endif /* HAVE_DARWIN */
375 static unsigned on = 1, off = 0;
377 void buffer_output(void) {
378 #ifdef HAVE_TCP_BUFFERING
380 if (!CC->redirect_ssl)
382 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
386 void unbuffer_output(void) {
387 #ifdef HAVE_TCP_BUFFERING
389 if (!CC->redirect_ssl)
391 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
395 void flush_output(void) {
396 #ifdef HAVE_TCP_BUFFERING
397 struct CitContext *CCC = CC;
398 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
399 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
404 static void flush_client_inbuf(void)
408 FlushStrBuf(CCC->ReadBuf);
416 * client_close() ... close the client socket
418 void client_close(void) {
419 CitContext *CCC = CC;
423 if (CCC->client_socket < 0) return;
424 syslog(LOG_DEBUG, "Closing socket %d\n", CCC->client_socket);
425 r = close(CCC->client_socket);
426 if (!r) syslog(LOG_INFO, "close() failed: %s\n", strerror(errno));
427 CCC->client_socket = -1 ;
434 * client_write() ... Send binary data to the client.
436 int client_write(const char *buf, int nbytes)
438 int bytes_written = 0;
440 #ifndef HAVE_TCP_BUFFERING
441 int old_buffer_len = 0;
447 if (nbytes < 1) return(0);
457 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
459 fd = fopen(fn, "a+");
460 fprintf(fd, "Sending: BufSize: %d BufContent: [",
462 rv = fwrite(buf, nbytes, 1, fd);
469 // flush_client_inbuf();
470 if (Ctx->redirect_buffer != NULL) {
471 StrBufAppendBufPlain(Ctx->redirect_buffer,
477 if (Ctx->redirect_ssl) {
478 client_write_ssl(buf, nbytes);
482 if (Ctx->client_socket == -1) return -1;
484 fdflags = fcntl(Ctx->client_socket, F_GETFL);
486 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
487 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
489 FD_SET(Ctx->client_socket, &wset);
490 if (select(1, NULL, &wset, NULL, NULL) == -1) {
493 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
494 if (CtdlThreadCheckStop()) {
495 CC->kill_me = KILLME_SELECT_INTERRUPTED;
498 /* can't trust fd's and stuff so we need to re-create them */
503 "client_write(%d bytes) select failed: %s (%d)\n",
504 nbytes - bytes_written,
505 strerror(errno), errno
509 Ctx->kill_me = KILLME_SELECT_FAILED;
515 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
518 "client_write(%d bytes) failed: %s (%d)\n",
519 nbytes - bytes_written,
520 strerror(errno), errno
524 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
525 Ctx->kill_me = KILLME_WRITE_FAILED;
528 bytes_written = bytes_written + retval;
533 void cputbuf(const StrBuf *Buf) {
534 client_write(ChrPtr(Buf), StrLength(Buf));
539 * cprintf() Send formatted printable data to the client.
540 * Implemented in terms of client_write() so it's technically not sysdep...
542 void cprintf(const char *format, ...) {
546 va_start(arg_ptr, format);
547 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
548 buf[sizeof buf - 2] = '\n';
549 client_write(buf, strlen(buf));
555 * Read data from the client socket.
557 * sock socket fd to read from
558 * buf buffer to read into
559 * bytes number of bytes to read
560 * timeout Number of seconds to wait before timing out
562 * Possible return values:
563 * 1 Requested number of bytes has been read.
564 * 0 Request timed out.
565 * -1 Connection is broken, or other error.
567 int client_read_blob(StrBuf *Target, int bytes, int timeout)
574 if (CCC->redirect_ssl) {
580 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
582 fd = fopen(fn, "a+");
583 fprintf(fd, "Reading BLOB: BufSize: %d ",
585 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
591 retval = client_read_sslblob(Target, bytes, timeout);
598 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
600 fd = fopen(fn, "a+");
601 fprintf(fd, "Read: %d BufContent: [",
603 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
618 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
620 fd = fopen(fn, "a+");
621 fprintf(fd, "Reading BLOB: BufSize: %d ",
623 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
629 retval = StrBufReadBLOBBuffered(Target,
638 syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
643 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
645 fd = fopen(fn, "a+");
646 fprintf(fd, "Read: %d BufContent: [",
648 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
658 * to make client_read_random_blob() more efficient, increase buffer size.
659 * just use in greeting function, else your buffer may be flushed
661 void client_set_inbound_buf(long N)
663 FlushStrBuf(CC->ReadBuf);
664 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
667 int client_read_random_blob(StrBuf *Target, int timeout)
672 rc = client_read_blob(Target, 1, timeout);
678 len = StrLength(CCC->ReadBuf);
679 pch = ChrPtr(CCC->ReadBuf);
683 if (CCC->Pos != NULL) {
684 len -= CCC->Pos - pch;
687 StrBufAppendBufPlain(Target, pch, len, 0);
688 FlushStrBuf(CCC->ReadBuf);
696 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
698 fd = fopen(fn, "a+");
699 fprintf(fd, "Read: BufSize: %d BufContent: [",
701 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
709 return StrLength(Target);
717 int client_read_to(char *buf, int bytes, int timeout)
722 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
731 ChrPtr(CCC->MigrateBuf),
732 StrLength(CCC->MigrateBuf) + 1);
733 FlushStrBuf(CCC->MigrateBuf);
739 int HaveMoreLinesWaiting(CitContext *CCC)
741 if ((CCC->kill_me != 0) || (
742 (CCC->Pos == NULL) &&
743 (StrLength(CCC->ReadBuf) == 0) &&
744 (CCC->client_socket != -1)) )
752 * Read data from the client socket with default timeout.
753 * (This is implemented in terms of client_read_to() and could be
754 * justifiably moved out of sysdep.c)
756 INLINE int client_read(char *buf, int bytes)
758 return(client_read_to(buf, bytes, config.c_sleeping));
761 int CtdlClientGetLine(StrBuf *Target)
769 if (CCC->redirect_ssl) {
779 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
781 fd = fopen(fn, "a+");
782 pch = ChrPtr(CCC->ReadBuf);
783 len = StrLength(CCC->ReadBuf);
784 if (CCC->Pos != NULL)
785 rlen = CC->Pos - pch;
789 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
792 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
795 rc = client_readline_sslbuffer(Target,
800 pch = ChrPtr(CCC->ReadBuf);
801 nlen = StrLength(CCC->ReadBuf);
802 if (CCC->Pos != NULL)
803 nrlen = CC->Pos - pch;
807 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
808 len, nlen, rlen, nrlen, pch);
810 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
811 len, nlen, rlen, nrlen);
813 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
814 StrLength(Target), ChrPtr(Target));
830 int len, rlen, nlen, nrlen;
833 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
835 fd = fopen(fn, "a+");
836 pch = ChrPtr(CCC->ReadBuf);
837 len = StrLength(CCC->ReadBuf);
838 if (CCC->Pos != NULL)
839 rlen = CC->Pos - pch;
843 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
846 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
849 rc = StrBufTCP_read_buffered_line_fast(Target,
858 pch = ChrPtr(CCC->ReadBuf);
859 nlen = StrLength(CCC->ReadBuf);
860 if (CCC->Pos != NULL)
861 nrlen = CC->Pos - pch;
865 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
866 len, nlen, rlen, nrlen, pch);
868 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
869 len, nlen, rlen, nrlen);
871 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
872 StrLength(Target), ChrPtr(Target));
875 if ((rc < 0) && (Error != NULL))
887 * client_getln() ... Get a LF-terminated line of text from the client.
888 * (This is implemented in terms of client_read() and could be
889 * justifiably moved out of sysdep.c)
891 int client_getln(char *buf, int bufsize)
897 retval = CtdlClientGetLine(CCC->MigrateBuf);
902 i = StrLength(CCC->MigrateBuf);
903 pCh = ChrPtr(CCC->MigrateBuf);
904 /* Strip the trailing LF, and the trailing CR if present.
909 && ( (pCh[i - 1]==13)
910 || ( pCh[i - 1]==10)) ) {
916 FlushStrBuf(CCC->MigrateBuf);
918 safestrncpy(&buf[i], "000", bufsize - i);
925 * Cleanup any contexts that are left lying around
929 void close_masters (void)
931 struct ServiceFunctionHook *serviceptr;
934 * close all protocol master sockets
936 for (serviceptr = ServiceHookTable; serviceptr != NULL;
937 serviceptr = serviceptr->next ) {
939 if (serviceptr->tcp_port > 0)
941 syslog(LOG_INFO, "Closing listener on port %d\n",
942 serviceptr->tcp_port);
943 serviceptr->tcp_port = 0;
946 if (serviceptr->sockpath != NULL)
947 syslog(LOG_INFO, "Closing listener on '%s'\n",
948 serviceptr->sockpath);
950 close(serviceptr->msock);
951 /* If it's a Unix domain socket, remove the file. */
952 if (serviceptr->sockpath != NULL) {
953 unlink(serviceptr->sockpath);
954 serviceptr->sockpath = NULL;
961 * The system-dependent part of master_cleanup() - close the master socket.
963 void sysdep_master_cleanup(void) {
972 CtdlDestroyProtoHooks();
973 CtdlDestroyDeleteHooks();
974 CtdlDestroyXmsgHooks();
975 CtdlDestroyNetprocHooks();
976 CtdlDestroyUserHooks();
977 CtdlDestroyMessageHook();
978 CtdlDestroyCleanupHooks();
979 CtdlDestroyFixedOutputHooks();
980 CtdlDestroySessionHooks();
981 CtdlDestroyServiceHook();
982 CtdlDestroyRoomHooks();
983 CtdlDestroySearchHooks();
984 #ifdef HAVE_BACKTRACE
992 void graceful_shutdown(int signum) {
993 kill(current_child, signum);
994 unlink(file_pid_file);
999 int nFireUpsNonRestart = 0;
1000 pid_t ForkedPid = 1;
1003 * Start running as a daemon.
1005 void start_daemon(int unused) {
1013 /* Close stdin/stdout/stderr and replace them with /dev/null.
1014 * We don't just call close() because we don't want these fd's
1015 * to be reused for other files.
1017 if (chdir(ctdl_run_dir) != 0)
1019 "unable to change into directory [%s]: %s",
1020 ctdl_run_dir, strerror(errno));
1027 signal(SIGHUP, SIG_IGN);
1028 signal(SIGINT, SIG_IGN);
1029 signal(SIGQUIT, SIG_IGN);
1033 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1034 (freopen("/dev/null", "w", stdout) != stdout) ||
1035 (freopen("/dev/null", "w", stderr) != stderr))
1037 "unable to reopen stdin/out/err %s",
1042 current_child = fork();
1044 signal(SIGTERM, graceful_shutdown);
1046 if (current_child < 0) {
1051 else if (current_child == 0) {
1052 return; /* continue starting citadel. */
1056 fp = fopen(file_pid_file, "w");
1058 fprintf(fp, ""F_PID_T"\n", getpid());
1061 waitpid(current_child, &status, 0);
1064 nFireUpsNonRestart = nFireUps;
1066 /* Exit code 0 means the watcher should exit */
1067 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1071 /* Exit code 101-109 means the watcher should exit */
1072 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1076 /* Any other exit code, or no exit code, means we should restart. */
1080 ForkedPid = current_child;
1083 } while (do_restart);
1085 unlink(file_pid_file);
1086 exit(WEXITSTATUS(status));
1091 void checkcrash(void)
1093 if (nFireUpsNonRestart != nFireUps)
1097 CrashMail = NewStrBuf();
1098 syslog(LOG_ALERT, "Posting crash message\n");
1099 StrBufPrintf(CrashMail,
1101 " The Citadel server process (citserver) terminated unexpectedly."
1103 " This could be the result of a bug in the server program, or some external "
1105 " You can obtain more information about this by enabling core dumps.\n \n"
1106 " For more information, please see:\n \n"
1107 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1110 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1112 ctdl_run_dir, ForkedPid);
1113 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1114 FreeStrBuf(&CrashMail);
1120 * Generic routine to convert a login name to a full name (gecos)
1121 * Returns nonzero if a conversion took place
1123 int convert_login(char NameToConvert[]) {
1127 pw = getpwnam(NameToConvert);
1132 strcpy(NameToConvert, pw->pw_gecos);
1133 for (a=0; a<strlen(NameToConvert); ++a) {
1134 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1143 * This loop just keeps going and going and going...
1145 void *worker_thread(void *arg) {
1148 CitContext *bind_me = NULL;
1152 int force_purge = 0;
1155 while (!CtdlThreadCheckStop()) {
1157 /* make doubly sure we're not holding any stale db handles
1158 * which might cause a deadlock.
1160 cdb_check_handles();
1161 do_select: force_purge = 0;
1162 bind_me = NULL; /* Which session shall we handle? */
1164 /* Initialize the fdset. */
1168 begin_critical_section(S_SESSION_TABLE);
1169 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1170 /* Don't select on dead sessions, only truly idle ones */
1171 if ( (ptr->state == CON_IDLE)
1172 && (ptr->kill_me == 0)
1173 && (ptr->client_socket != -1)
1175 FD_SET(ptr->client_socket, &readfds);
1176 if (ptr->client_socket > highest)
1177 highest = ptr->client_socket;
1179 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1181 ptr->state = CON_EXECUTING;
1184 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1186 ptr->state = CON_STARTING;
1190 end_critical_section(S_SESSION_TABLE);
1196 /* If we got this far, it means that there are no sessions
1197 * which a previous thread marked for attention, so we go
1198 * ahead and get ready to select().
1201 if (!CtdlThreadCheckStop()) {
1202 tv.tv_sec = 1; /* wake up every second if no input */
1204 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1209 /* Now figure out who made this select() unblock.
1210 * First, check for an error or exit condition.
1213 if (errno == EBADF) {
1214 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1218 if (errno != EINTR) {
1219 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1220 CtdlThreadStopAll();
1223 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1224 if (CtdlThreadCheckStop()) return(NULL);
1228 else if(retval == 0) {
1229 if (CtdlThreadCheckStop()) return(NULL);
1232 /* It must be a client socket. Find a context that has data
1233 * waiting on its socket *and* is in the CON_IDLE state. Any
1234 * active sockets other than our chosen one are marked as
1235 * CON_READY so the next thread that comes around can just bind
1236 * to one without having to select() again.
1238 begin_critical_section(S_SESSION_TABLE);
1239 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1240 int checkfd = ptr->client_socket;
1241 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1242 if (FD_ISSET(checkfd, &readfds)) {
1243 ptr->input_waiting = 1;
1245 bind_me = ptr; /* I choose you! */
1246 bind_me->state = CON_EXECUTING;
1249 ptr->state = CON_READY;
1251 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1253 bind_me = ptr; /* I choose you! */
1254 bind_me->state = CON_EXECUTING;
1257 ptr->state = CON_READY;
1262 end_critical_section(S_SESSION_TABLE);
1265 /* We're bound to a session */
1266 if (bind_me != NULL) {
1267 become_session(bind_me);
1269 if (bind_me->state == CON_STARTING) {
1270 bind_me->state = CON_EXECUTING;
1271 begin_session(bind_me);
1272 bind_me->h_greeting_function();
1274 /* If the client has sent a command, execute it. */
1275 if (CC->input_waiting) {
1276 CC->h_command_function();
1278 while (HaveMoreLinesWaiting(CC))
1279 CC->h_command_function();
1281 CC->input_waiting = 0;
1284 /* If there are asynchronous messages waiting and the
1285 * client supports it, do those now */
1286 if ((CC->is_async) && (CC->async_waiting)
1287 && (CC->h_async_function != NULL)) {
1288 CC->h_async_function();
1289 CC->async_waiting = 0;
1292 force_purge = CC->kill_me;
1293 become_session(NULL);
1294 bind_me->state = CON_IDLE;
1297 dead_session_purge(force_purge);
1300 /* If control reaches this point, the server is shutting down */
1308 * A function to handle selecting on master sockets.
1309 * In other words it handles new connections.
1312 void *select_on_master (void *arg)
1314 struct ServiceFunctionHook *serviceptr;
1318 int ssock; /* Descriptor for client socket */
1319 CitContext *con= NULL; /* Temporary context pointer */
1323 struct CitContext select_on_master_CC;
1325 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1326 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1328 while (!CtdlThreadCheckStop()) {
1329 /* Initialize the fdset. */
1330 FD_ZERO(&master_fds);
1333 /* First, add the various master sockets to the fdset. */
1334 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1335 serviceptr = serviceptr->next ) {
1336 m = serviceptr->msock;
1337 FD_SET(m, &master_fds);
1343 if (!CtdlThreadCheckStop()) {
1344 tv.tv_sec = 60; /* wake up every second if no input */
1346 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1351 /* Now figure out who made this select() unblock.
1352 * First, check for an error or exit condition.
1355 if (errno == EBADF) {
1356 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1360 if (errno != EINTR) {
1361 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1362 CtdlThreadStopAll();
1364 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1365 if (CtdlThreadCheckStop()) return(NULL);
1369 else if(retval == 0) {
1370 if (CtdlThreadCheckStop()) return(NULL);
1373 /* Next, check to see if it's a new client connecting
1374 * on a master socket.
1376 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1377 serviceptr = serviceptr->next ) {
1379 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1380 ssock = accept(serviceptr->msock, NULL, 0);
1382 syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1384 /* The master socket is non-blocking but the client
1385 * sockets need to be blocking, otherwise certain
1386 * operations barf on FreeBSD. Not a fatal error.
1388 if (fcntl(ssock, F_SETFL, 0) < 0) {
1390 "citserver: Can't set socket to blocking: %s\n",
1394 /* New context will be created already
1395 * set up in the CON_EXECUTING state.
1397 con = CreateNewContext();
1399 /* Assign our new socket number to it. */
1400 con->client_socket = ssock;
1401 con->h_command_function = serviceptr->h_command_function;
1402 con->h_async_function = serviceptr->h_async_function;
1403 con->h_greeting_function = serviceptr->h_greeting_function;
1404 con->ServiceName = serviceptr->ServiceName;
1406 /* Determine whether it's a local socket */
1407 if (serviceptr->sockpath != NULL) {
1408 con->is_local_socket = 1;
1411 /* Set the SO_REUSEADDR socket option */
1413 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1414 con->state = CON_GREETING;
1422 CtdlClearSystemContext();
1431 * Translate text facility name to syslog.h defined value.
1433 int SyslogFacility(char *name)
1442 { LOG_KERN, "kern" },
1443 { LOG_USER, "user" },
1444 { LOG_MAIL, "mail" },
1445 { LOG_DAEMON, "daemon" },
1446 { LOG_AUTH, "auth" },
1447 { LOG_SYSLOG, "syslog" },
1449 { LOG_NEWS, "news" },
1450 { LOG_UUCP, "uucp" },
1451 { LOG_LOCAL0, "local0" },
1452 { LOG_LOCAL1, "local1" },
1453 { LOG_LOCAL2, "local2" },
1454 { LOG_LOCAL3, "local3" },
1455 { LOG_LOCAL4, "local4" },
1456 { LOG_LOCAL5, "local5" },
1457 { LOG_LOCAL6, "local6" },
1458 { LOG_LOCAL7, "local7" },
1461 for(i = 0; facTbl[i].name != NULL; i++) {
1462 if(!strcasecmp(name, facTbl[i].name))
1463 return facTbl[i].facility;