2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * would need to be altered to run the server in a non-POSIX environment.
7 * If we ever port to a different platform and either have multiple
8 * variants of this file or simply load it up with #ifdefs.
10 * Copyright (c) 1987-2011 by the citadel.org team
12 * This program is open source software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <sys/syslog.h>
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
46 # include <sys/time.h>
53 #include <sys/resource.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
64 #define SHOW_ME_VAPPEND_PRINTF
65 #include <libcitadel.h>
68 #include "sysdep_decls.h"
69 #include "citserver.h"
73 #include "housekeeping.h"
74 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
78 #ifdef HAVE_SYS_SELECT_H
79 #include <sys/select.h>
86 #include "ctdl_module.h"
93 * Signal handler to shut down the server.
96 volatile int exit_signal = 0;
97 volatile int shutdown_and_halt = 0;
98 volatile int restart_server = 0;
99 volatile int running_as_daemon = 0;
101 static RETSIGTYPE signal_cleanup(int signum) {
102 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
103 exit_signal = signum;
106 static RETSIGTYPE signal_exit(int signum) {
113 * Some initialization stuff...
115 void init_sysdep(void) {
118 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
122 getrlimit(RLIMIT_NOFILE, &rl);
123 rl.rlim_cur = FD_SETSIZE;
124 rl.rlim_max = FD_SETSIZE;
125 setrlimit(RLIMIT_NOFILE, &rl);
129 /* If we've got OpenSSL, we're going to use it. */
135 * Set up a place to put thread-specific data.
136 * We only need a single pointer per thread - it points to the
137 * CitContext structure (in the ContextList linked list) of the
138 * session to which the calling thread is currently bound.
140 if (pthread_key_create(&MyConKey, NULL) != 0) {
141 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
145 * Interript, hangup, and terminate signals should cause the server
146 * to gracefully clean up and shut down.
149 sigaddset(&set, SIGINT);
150 sigaddset(&set, SIGHUP);
151 sigaddset(&set, SIGTERM);
152 sigprocmask(SIG_UNBLOCK, &set, NULL);
154 signal(SIGINT, signal_cleanup);
155 signal(SIGHUP, signal_cleanup);
156 signal(SIGTERM, signal_cleanup);
157 signal(SIGUSR2, signal_exit);
160 * Do not shut down the server on broken pipe signals, otherwise the
161 * whole Citadel service would come down whenever a single client
164 signal(SIGPIPE, SIG_IGN);
169 * This is a generic function to set up a master socket for listening on
170 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
172 * ip_addr IP address to bind
173 * port_number port number to bind
174 * queue_len number of incoming connections to allow in the queue
176 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
179 struct sockaddr_in6 sin6;
180 struct sockaddr_in sin4;
184 memset(&sin6, 0, sizeof(sin6));
185 memset(&sin4, 0, sizeof(sin4));
186 sin6.sin6_family = AF_INET6;
187 sin4.sin_family = AF_INET;
189 if ( (ip_addr == NULL) /* any IPv6 */
190 || (IsEmptyStr(ip_addr))
191 || (!strcmp(ip_addr, "*"))
194 sin6.sin6_addr = in6addr_any;
196 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
199 sin4.sin_addr.s_addr = INADDR_ANY;
201 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
204 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
205 snprintf(errormessage, SIZ,
206 "Error binding to [%s] : %s", ip_addr, strerror(errno)
208 syslog(LOG_ALERT, "%s", errormessage);
212 else /* specific IPv6 */
215 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
216 snprintf(errormessage, SIZ,
217 "Error binding to [%s] : %s", ip_addr, strerror(errno)
219 syslog(LOG_ALERT, "%s", errormessage);
224 if (port_number == 0) {
225 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
226 syslog(LOG_ALERT, "%s", errormessage);
229 sin6.sin6_port = htons((u_short) port_number);
230 sin4.sin_port = htons((u_short) port_number);
232 p = getprotobyname("tcp");
234 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
236 snprintf(errormessage, SIZ,
237 "Can't create a listening socket: %s", strerror(errno)
239 syslog(LOG_ALERT, "%s", errormessage);
242 /* Set some socket options that make sense. */
244 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
246 if (ip_version == 6) {
247 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
250 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
254 snprintf(errormessage, SIZ,
255 "Can't bind: %s", strerror(errno)
257 syslog(LOG_ALERT, "%s", errormessage);
261 fcntl(s, F_SETFL, O_NONBLOCK);
263 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
264 snprintf(errormessage, SIZ,
265 "Can't listen: %s", strerror(errno)
267 syslog(LOG_ALERT, "%s", errormessage);
278 * Create a Unix domain socket and listen on it
280 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
282 struct sockaddr_un addr;
285 int actual_queue_len;
286 #ifdef HAVE_STRUCT_UCRED
290 actual_queue_len = queue_len;
291 if (actual_queue_len < 5) actual_queue_len = 5;
293 i = unlink(sockpath);
294 if ((i != 0) && (errno != ENOENT)) {
295 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
296 sockpath, strerror(errno)
298 syslog(LOG_EMERG, "%s", errormessage);
302 memset(&addr, 0, sizeof(addr));
303 addr.sun_family = AF_UNIX;
304 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
306 s = socket(AF_UNIX, SOCK_STREAM, 0);
308 snprintf(errormessage, SIZ,
309 "citserver: Can't create a socket: %s",
311 syslog(LOG_EMERG, "%s", errormessage);
315 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
316 snprintf(errormessage, SIZ,
317 "citserver: Can't bind: %s",
319 syslog(LOG_EMERG, "%s", errormessage);
323 /* set to nonblock - we need this for some obscure situations */
324 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
325 snprintf(errormessage, SIZ,
326 "citserver: Can't set socket to non-blocking: %s",
328 syslog(LOG_EMERG, "%s", errormessage);
333 if (listen(s, actual_queue_len) < 0) {
334 snprintf(errormessage, SIZ,
335 "citserver: Can't listen: %s",
337 syslog(LOG_EMERG, "%s", errormessage);
341 #ifdef HAVE_STRUCT_UCRED
342 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
345 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
352 * The following functions implement output buffering on operating systems which
353 * support it (such as Linux and various BSD flavors).
357 # define HAVE_TCP_BUFFERING
360 # define HAVE_TCP_BUFFERING
361 # define TCP_CORK TCP_NOPUSH
363 #endif /* TCP_CORK */
364 #endif /* HAVE_DARWIN */
366 static unsigned on = 1, off = 0;
368 void buffer_output(void) {
369 #ifdef HAVE_TCP_BUFFERING
371 if (!CC->redirect_ssl)
373 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
377 void unbuffer_output(void) {
378 #ifdef HAVE_TCP_BUFFERING
380 if (!CC->redirect_ssl)
382 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
386 void flush_output(void) {
387 #ifdef HAVE_TCP_BUFFERING
388 struct CitContext *CCC = CC;
389 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
390 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
395 static void flush_client_inbuf(void)
399 FlushStrBuf(CCC->ReadBuf);
407 * client_close() ... close the client socket
409 void client_close(void) {
410 CitContext *CCC = CC;
413 if (CCC->client_socket < 0) return;
414 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
415 close(CCC->client_socket);
416 CCC->client_socket = -1 ;
423 * client_write() ... Send binary data to the client.
425 int client_write(const char *buf, int nbytes)
427 int bytes_written = 0;
429 #ifndef HAVE_TCP_BUFFERING
430 int old_buffer_len = 0;
436 if (nbytes < 1) return(0);
446 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
448 fd = fopen(fn, "a+");
449 fprintf(fd, "Sending: BufSize: %d BufContent: [",
451 rv = fwrite(buf, nbytes, 1, fd);
458 // flush_client_inbuf();
459 if (Ctx->redirect_buffer != NULL) {
460 StrBufAppendBufPlain(Ctx->redirect_buffer,
466 if (Ctx->redirect_ssl) {
467 client_write_ssl(buf, nbytes);
471 if (Ctx->client_socket == -1) return -1;
473 fdflags = fcntl(Ctx->client_socket, F_GETFL);
475 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
476 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
478 FD_SET(Ctx->client_socket, &wset);
479 if (select(1, NULL, &wset, NULL, NULL) == -1) {
482 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
485 if (CtdlThreadCheckStop()) {
486 CC->kill_me = KILLME_SELECT_INTERRUPTED;
489 /* can't trust fd's and stuff so we need to re-create them */
494 "client_write(%d bytes) select failed: %s (%d)",
495 nbytes - bytes_written,
496 strerror(errno), errno
500 Ctx->kill_me = KILLME_SELECT_FAILED;
506 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
509 "client_write(%d bytes) failed: %s (%d)",
510 nbytes - bytes_written,
511 strerror(errno), errno
515 Ctx->kill_me = KILLME_WRITE_FAILED;
518 bytes_written = bytes_written + retval;
523 void cputbuf(const StrBuf *Buf) {
524 client_write(ChrPtr(Buf), StrLength(Buf));
529 * cprintf() Send formatted printable data to the client.
530 * Implemented in terms of client_write() so it's technically not sysdep...
532 void cprintf(const char *format, ...) {
536 va_start(arg_ptr, format);
537 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
538 buf[sizeof buf - 2] = '\n';
539 client_write(buf, strlen(buf));
545 * Read data from the client socket.
547 * sock socket fd to read from
548 * buf buffer to read into
549 * bytes number of bytes to read
550 * timeout Number of seconds to wait before timing out
552 * Possible return values:
553 * 1 Requested number of bytes has been read.
554 * 0 Request timed out.
555 * -1 Connection is broken, or other error.
557 int client_read_blob(StrBuf *Target, int bytes, int timeout)
564 if (CCC->redirect_ssl) {
570 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
572 fd = fopen(fn, "a+");
573 fprintf(fd, "Reading BLOB: BufSize: %d ",
575 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
581 retval = client_read_sslblob(Target, bytes, timeout);
583 syslog(LOG_CRIT, "%s failed", __FUNCTION__);
586 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
588 fd = fopen(fn, "a+");
589 fprintf(fd, "Read: %d BufContent: [",
591 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
606 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
608 fd = fopen(fn, "a+");
609 fprintf(fd, "Reading BLOB: BufSize: %d ",
611 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
617 retval = StrBufReadBLOBBuffered(Target,
626 syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
631 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
633 fd = fopen(fn, "a+");
634 fprintf(fd, "Read: %d BufContent: [",
636 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
646 * to make client_read_random_blob() more efficient, increase buffer size.
647 * just use in greeting function, else your buffer may be flushed
649 void client_set_inbound_buf(long N)
651 FlushStrBuf(CC->ReadBuf);
652 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
655 int client_read_random_blob(StrBuf *Target, int timeout)
660 rc = client_read_blob(Target, 1, timeout);
666 len = StrLength(CCC->ReadBuf);
667 pch = ChrPtr(CCC->ReadBuf);
671 if (CCC->Pos != NULL) {
672 len -= CCC->Pos - pch;
675 StrBufAppendBufPlain(Target, pch, len, 0);
676 FlushStrBuf(CCC->ReadBuf);
684 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
686 fd = fopen(fn, "a+");
687 fprintf(fd, "Read: BufSize: %d BufContent: [",
689 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
697 return StrLength(Target);
705 int client_read_to(char *buf, int bytes, int timeout)
710 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
719 ChrPtr(CCC->MigrateBuf),
720 StrLength(CCC->MigrateBuf) + 1);
721 FlushStrBuf(CCC->MigrateBuf);
727 int HaveMoreLinesWaiting(CitContext *CCC)
729 if ((CCC->kill_me != 0) || (
730 (CCC->Pos == NULL) &&
731 (StrLength(CCC->ReadBuf) == 0) &&
732 (CCC->client_socket != -1)) )
740 * Read data from the client socket with default timeout.
741 * (This is implemented in terms of client_read_to() and could be
742 * justifiably moved out of sysdep.c)
744 INLINE int client_read(char *buf, int bytes)
746 return(client_read_to(buf, bytes, config.c_sleeping));
749 int CtdlClientGetLine(StrBuf *Target)
757 if (CCC->redirect_ssl) {
767 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
769 fd = fopen(fn, "a+");
770 pch = ChrPtr(CCC->ReadBuf);
771 len = StrLength(CCC->ReadBuf);
772 if (CCC->Pos != NULL)
773 rlen = CC->Pos - pch;
777 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
780 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
783 rc = client_readline_sslbuffer(Target,
788 pch = ChrPtr(CCC->ReadBuf);
789 nlen = StrLength(CCC->ReadBuf);
790 if (CCC->Pos != NULL)
791 nrlen = CC->Pos - pch;
795 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
796 len, nlen, rlen, nrlen, pch);
798 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
799 len, nlen, rlen, nrlen);
801 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
802 StrLength(Target), ChrPtr(Target));
818 int len, rlen, nlen, nrlen;
821 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
823 fd = fopen(fn, "a+");
824 pch = ChrPtr(CCC->ReadBuf);
825 len = StrLength(CCC->ReadBuf);
826 if (CCC->Pos != NULL)
827 rlen = CC->Pos - pch;
831 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
834 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
837 rc = StrBufTCP_read_buffered_line_fast(Target,
846 pch = ChrPtr(CCC->ReadBuf);
847 nlen = StrLength(CCC->ReadBuf);
848 if (CCC->Pos != NULL)
849 nrlen = CC->Pos - pch;
853 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
854 len, nlen, rlen, nrlen, pch);
856 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
857 len, nlen, rlen, nrlen);
859 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
860 StrLength(Target), ChrPtr(Target));
863 if ((rc < 0) && (Error != NULL))
875 * client_getln() ... Get a LF-terminated line of text from the client.
876 * (This is implemented in terms of client_read() and could be
877 * justifiably moved out of sysdep.c)
879 int client_getln(char *buf, int bufsize)
885 retval = CtdlClientGetLine(CCC->MigrateBuf);
890 i = StrLength(CCC->MigrateBuf);
891 pCh = ChrPtr(CCC->MigrateBuf);
892 /* Strip the trailing LF, and the trailing CR if present.
897 && ( (pCh[i - 1]==13)
898 || ( pCh[i - 1]==10)) ) {
904 FlushStrBuf(CCC->MigrateBuf);
906 safestrncpy(&buf[i], "000", bufsize - i);
913 * Cleanup any contexts that are left lying around
917 void close_masters (void)
919 struct ServiceFunctionHook *serviceptr;
922 * close all protocol master sockets
924 for (serviceptr = ServiceHookTable; serviceptr != NULL;
925 serviceptr = serviceptr->next ) {
927 if (serviceptr->tcp_port > 0)
929 syslog(LOG_INFO, "Closing listener on port %d\n",
930 serviceptr->tcp_port);
931 serviceptr->tcp_port = 0;
934 if (serviceptr->sockpath != NULL)
935 syslog(LOG_INFO, "Closing listener on '%s'\n",
936 serviceptr->sockpath);
938 close(serviceptr->msock);
939 /* If it's a Unix domain socket, remove the file. */
940 if (serviceptr->sockpath != NULL) {
941 unlink(serviceptr->sockpath);
942 serviceptr->sockpath = NULL;
949 * The system-dependent part of master_cleanup() - close the master socket.
951 void sysdep_master_cleanup(void) {
960 CtdlDestroyProtoHooks();
961 CtdlDestroyDeleteHooks();
962 CtdlDestroyXmsgHooks();
963 CtdlDestroyNetprocHooks();
964 CtdlDestroyUserHooks();
965 CtdlDestroyMessageHook();
966 CtdlDestroyCleanupHooks();
967 CtdlDestroyFixedOutputHooks();
968 CtdlDestroySessionHooks();
969 CtdlDestroyServiceHook();
970 CtdlDestroyRoomHooks();
971 CtdlDestroySearchHooks();
972 #ifdef HAVE_BACKTRACE
980 void graceful_shutdown(int signum) {
981 kill(current_child, signum);
982 unlink(file_pid_file);
987 int nFireUpsNonRestart = 0;
991 * Start running as a daemon.
993 void start_daemon(int unused) {
1001 /* Close stdin/stdout/stderr and replace them with /dev/null.
1002 * We don't just call close() because we don't want these fd's
1003 * to be reused for other files.
1005 if (chdir(ctdl_run_dir) != 0)
1007 "unable to change into directory [%s]: %s",
1008 ctdl_run_dir, strerror(errno));
1015 signal(SIGHUP, SIG_IGN);
1016 signal(SIGINT, SIG_IGN);
1017 signal(SIGQUIT, SIG_IGN);
1021 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1022 (freopen("/dev/null", "w", stdout) != stdout) ||
1023 (freopen("/dev/null", "w", stderr) != stderr))
1025 "unable to reopen stdin/out/err %s",
1030 current_child = fork();
1032 signal(SIGTERM, graceful_shutdown);
1034 if (current_child < 0) {
1039 else if (current_child == 0) {
1040 return; /* continue starting citadel. */
1044 fp = fopen(file_pid_file, "w");
1046 fprintf(fp, ""F_PID_T"\n", getpid());
1049 waitpid(current_child, &status, 0);
1052 nFireUpsNonRestart = nFireUps;
1054 /* Exit code 0 means the watcher should exit */
1055 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1059 /* Exit code 101-109 means the watcher should exit */
1060 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1064 /* Any other exit code, or no exit code, means we should restart. */
1068 ForkedPid = current_child;
1071 } while (do_restart);
1073 unlink(file_pid_file);
1074 exit(WEXITSTATUS(status));
1079 void checkcrash(void)
1081 if (nFireUpsNonRestart != nFireUps)
1085 CrashMail = NewStrBuf();
1086 syslog(LOG_ALERT, "Posting crash message\n");
1087 StrBufPrintf(CrashMail,
1089 " The Citadel server process (citserver) terminated unexpectedly."
1091 " This could be the result of a bug in the server program, or some external "
1093 " You can obtain more information about this by enabling core dumps.\n \n"
1094 " For more information, please see:\n \n"
1095 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1098 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1100 ctdl_run_dir, ForkedPid);
1101 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1102 FreeStrBuf(&CrashMail);
1108 * Generic routine to convert a login name to a full name (gecos)
1109 * Returns nonzero if a conversion took place
1111 int convert_login(char NameToConvert[]) {
1115 pw = getpwnam(NameToConvert);
1120 strcpy(NameToConvert, pw->pw_gecos);
1121 for (a=0; a<strlen(NameToConvert); ++a) {
1122 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1131 * This loop just keeps going and going and going...
1133 void *worker_thread(void *blah) {
1136 CitContext *bind_me = NULL;
1140 int force_purge = 0;
1142 while (!CtdlThreadCheckStop()) {
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 begin_critical_section(S_SESSION_TABLE);
1156 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1157 /* Don't select on dead sessions, only truly idle ones */
1158 if ( (ptr->state == CON_IDLE)
1159 && (ptr->kill_me == 0)
1160 && (ptr->client_socket != -1)
1162 FD_SET(ptr->client_socket, &readfds);
1163 if (ptr->client_socket > highest)
1164 highest = ptr->client_socket;
1166 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1168 ptr->state = CON_EXECUTING;
1171 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1173 ptr->state = CON_STARTING;
1177 end_critical_section(S_SESSION_TABLE);
1183 /* If we got this far, it means that there are no sessions
1184 * which a previous thread marked for attention, so we go
1185 * ahead and get ready to select().
1188 if (!CtdlThreadCheckStop()) {
1189 tv.tv_sec = 1; /* wake up every second if no input */
1191 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1197 /* Now figure out who made this select() unblock.
1198 * First, check for an error or exit condition.
1201 if (errno == EBADF) {
1202 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1205 if (errno != EINTR) {
1206 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1207 CtdlThreadStopAll();
1210 syslog(LOG_DEBUG, "Interrupted select()\n");
1211 if (CtdlThreadCheckStop()) return(NULL);
1215 else if (retval == 0) {
1216 if (CtdlThreadCheckStop()) return(NULL);
1219 /* It must be a client socket. Find a context that has data
1220 * waiting on its socket *and* is in the CON_IDLE state. Any
1221 * active sockets other than our chosen one are marked as
1222 * CON_READY so the next thread that comes around can just bind
1223 * to one without having to select() again.
1225 begin_critical_section(S_SESSION_TABLE);
1226 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1227 int checkfd = ptr->client_socket;
1228 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1229 if (FD_ISSET(checkfd, &readfds)) {
1230 ptr->input_waiting = 1;
1232 bind_me = ptr; /* I choose you! */
1233 bind_me->state = CON_EXECUTING;
1236 ptr->state = CON_READY;
1238 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1240 bind_me = ptr; /* I choose you! */
1241 bind_me->state = CON_EXECUTING;
1244 ptr->state = CON_READY;
1249 end_critical_section(S_SESSION_TABLE);
1252 /* We're bound to a session */
1253 if (bind_me != NULL) {
1254 become_session(bind_me);
1256 if (bind_me->state == CON_STARTING) {
1257 bind_me->state = CON_EXECUTING;
1258 begin_session(bind_me);
1259 bind_me->h_greeting_function();
1261 /* If the client has sent a command, execute it. */
1262 if (CC->input_waiting) {
1263 CC->h_command_function();
1265 while (HaveMoreLinesWaiting(CC))
1266 CC->h_command_function();
1268 CC->input_waiting = 0;
1271 /* If there are asynchronous messages waiting and the
1272 * client supports it, do those now */
1273 if ((CC->is_async) && (CC->async_waiting)
1274 && (CC->h_async_function != NULL)) {
1275 CC->h_async_function();
1276 CC->async_waiting = 0;
1279 force_purge = CC->kill_me;
1280 become_session(NULL);
1281 bind_me->state = CON_IDLE;
1284 dead_session_purge(force_purge);
1287 /* If control reaches this point, the server is shutting down */
1295 * A function to handle selecting on master sockets.
1296 * In other words it handles new connections.
1299 void *select_on_master(void *blah)
1301 struct ServiceFunctionHook *serviceptr;
1305 int ssock; /* Descriptor for client socket */
1306 CitContext *con = NULL; /* Temporary context pointer */
1310 struct CitContext select_on_master_CC;
1312 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1313 pthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1315 while (!CtdlThreadCheckStop()) {
1316 /* Initialize the fdset. */
1317 FD_ZERO(&master_fds);
1320 /* First, add the various master sockets to the fdset. */
1321 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1322 serviceptr = serviceptr->next ) {
1323 m = serviceptr->msock;
1324 FD_SET(m, &master_fds);
1330 if (!CtdlThreadCheckStop()) {
1331 tv.tv_sec = 60; /* wake up every second if no input */
1333 retval = select(highest + 1, &master_fds, NULL, NULL, &tv);
1338 /* Now figure out who made this select() unblock.
1339 * First, check for an error or exit condition.
1342 if (errno == EBADF) {
1343 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1347 if (errno != EINTR) {
1348 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1349 CtdlThreadStopAll();
1351 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1352 if (CtdlThreadCheckStop()) return(NULL);
1356 else if(retval == 0) {
1357 if (CtdlThreadCheckStop()) return(NULL);
1360 /* Next, check to see if it's a new client connecting
1361 * on a master socket.
1363 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1364 serviceptr = serviceptr->next ) {
1366 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1367 ssock = accept(serviceptr->msock, NULL, 0);
1369 syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1371 /* The master socket is non-blocking but the client
1372 * sockets need to be blocking, otherwise certain
1373 * operations barf on FreeBSD. Not a fatal error.
1375 if (fcntl(ssock, F_SETFL, 0) < 0) {
1377 "citserver: Can't set socket to blocking: %s\n",
1381 /* New context will be created already
1382 * set up in the CON_EXECUTING state.
1384 con = CreateNewContext();
1386 /* Assign our new socket number to it. */
1387 con->client_socket = ssock;
1388 con->h_command_function = serviceptr->h_command_function;
1389 con->h_async_function = serviceptr->h_async_function;
1390 con->h_greeting_function = serviceptr->h_greeting_function;
1391 con->ServiceName = serviceptr->ServiceName;
1393 /* Determine whether it's a local socket */
1394 if (serviceptr->sockpath != NULL) {
1395 con->is_local_socket = 1;
1398 /* Set the SO_REUSEADDR socket option */
1400 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1401 con->state = CON_GREETING;
1409 CtdlClearSystemContext();
1418 * Translate text facility name to syslog.h defined value.
1420 int SyslogFacility(char *name)
1429 { LOG_KERN, "kern" },
1430 { LOG_USER, "user" },
1431 { LOG_MAIL, "mail" },
1432 { LOG_DAEMON, "daemon" },
1433 { LOG_AUTH, "auth" },
1434 { LOG_SYSLOG, "syslog" },
1436 { LOG_NEWS, "news" },
1437 { LOG_UUCP, "uucp" },
1438 { LOG_LOCAL0, "local0" },
1439 { LOG_LOCAL1, "local1" },
1440 { LOG_LOCAL2, "local2" },
1441 { LOG_LOCAL3, "local3" },
1442 { LOG_LOCAL4, "local4" },
1443 { LOG_LOCAL5, "local5" },
1444 { LOG_LOCAL6, "local6" },
1445 { LOG_LOCAL7, "local7" },
1448 for(i = 0; facTbl[i].name != NULL; i++) {
1449 if(!strcasecmp(name, facTbl[i].name))
1450 return facTbl[i].facility;