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 free 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"
92 #ifdef DEBUG_MEMORY_LEAKS
100 struct igheap *igheap = NULL;
105 * Signal handler to shut down the server.
108 volatile int exit_signal = 0;
109 volatile int shutdown_and_halt = 0;
110 volatile int restart_server = 0;
111 volatile int running_as_daemon = 0;
113 static RETSIGTYPE signal_cleanup(int signum) {
119 syslog(LOG_DEBUG, "Caught signal %d; shutting down.\n", signum);
120 exit_signal = signum;
124 static RETSIGTYPE signal_exit(int signum) {
131 * Some initialization stuff...
133 void init_sysdep(void) {
136 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
140 getrlimit(RLIMIT_NOFILE, &rl);
141 rl.rlim_cur = FD_SETSIZE;
142 rl.rlim_max = FD_SETSIZE;
143 setrlimit(RLIMIT_NOFILE, &rl);
147 /* If we've got OpenSSL, we're going to use it. */
153 * Set up a place to put thread-specific data.
154 * We only need a single pointer per thread - it points to the
155 * CitContext structure (in the ContextList linked list) of the
156 * session to which the calling thread is currently bound.
158 if (citthread_key_create(&MyConKey, NULL) != 0) {
159 syslog(LOG_CRIT, "Can't create TSD key: %s\n",
164 * The action for unexpected signals and exceptions should be to
165 * call signal_cleanup() to gracefully shut down the server.
168 sigaddset(&set, SIGINT); // intr = shutdown
169 // sigaddset(&set, SIGQUIT); // quit = force quit
170 sigaddset(&set, SIGHUP);
171 sigaddset(&set, SIGTERM);
172 // sigaddset(&set, SIGSEGV); // we want core dumps
173 // sigaddset(&set, SIGILL); // we want core dumps
174 // sigaddset(&set, SIGBUS);
175 sigprocmask(SIG_UNBLOCK, &set, NULL);
177 signal(SIGINT, signal_cleanup); // intr = shutdown
178 // signal(SIGQUIT, signal_cleanup); // quit = force quit
179 signal(SIGHUP, signal_cleanup);
180 signal(SIGTERM, signal_cleanup);
181 signal(SIGUSR2, signal_exit);
182 // signal(SIGSEGV, signal_cleanup); // we want coredumps
183 // signal(SIGILL, signal_cleanup); // we want core dumps
184 // signal(SIGBUS, signal_cleanup);
187 * Do not shut down the server on broken pipe signals, otherwise the
188 * whole Citadel service would come down whenever a single client
191 signal(SIGPIPE, SIG_IGN);
196 * This is a generic function to set up a master socket for listening on
197 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
199 * ip_addr IP address to bind
200 * port_number port number to bind
201 * queue_len number of incoming connections to allow in the queue
203 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
206 struct sockaddr_in6 sin6;
207 struct sockaddr_in sin4;
211 memset(&sin6, 0, sizeof(sin6));
212 memset(&sin4, 0, sizeof(sin4));
213 sin6.sin6_family = AF_INET6;
214 sin4.sin_family = AF_INET;
216 if ( (ip_addr == NULL) /* any IPv6 */
217 || (IsEmptyStr(ip_addr))
218 || (!strcmp(ip_addr, "*"))
221 sin6.sin6_addr = in6addr_any;
223 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
226 sin4.sin_addr.s_addr = INADDR_ANY;
228 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
231 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
232 snprintf(errormessage, SIZ,
233 "Error binding to [%s] : %s", ip_addr, strerror(errno)
235 syslog(LOG_ALERT, "%s\n", errormessage);
239 else /* specific IPv6 */
242 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
243 snprintf(errormessage, SIZ,
244 "Error binding to [%s] : %s", ip_addr, strerror(errno)
246 syslog(LOG_ALERT, "%s\n", errormessage);
251 if (port_number == 0) {
252 snprintf(errormessage, SIZ,
253 "Can't start: no port number specified."
255 syslog(LOG_ALERT, "%s\n", errormessage);
258 sin6.sin6_port = htons((u_short) port_number);
259 sin4.sin_port = htons((u_short) port_number);
261 p = getprotobyname("tcp");
263 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
265 snprintf(errormessage, SIZ,
266 "Can't create a listening socket: %s", strerror(errno)
268 syslog(LOG_ALERT, "%s\n", errormessage);
271 /* Set some socket options that make sense. */
273 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
275 if (ip_version == 6) {
276 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
279 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
283 snprintf(errormessage, SIZ,
284 "Can't bind: %s", strerror(errno)
286 syslog(LOG_ALERT, "%s\n", errormessage);
290 fcntl(s, F_SETFL, O_NONBLOCK);
292 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
293 snprintf(errormessage, SIZ,
294 "Can't listen: %s", strerror(errno)
296 syslog(LOG_ALERT, "%s\n", errormessage);
307 * Create a Unix domain socket and listen on it
309 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
311 struct sockaddr_un addr;
314 int actual_queue_len;
315 #ifdef HAVE_STRUCT_UCRED
319 actual_queue_len = queue_len;
320 if (actual_queue_len < 5) actual_queue_len = 5;
322 i = unlink(sockpath);
323 if ((i != 0) && (errno != ENOENT)) {
324 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
325 sockpath, strerror(errno)
327 syslog(LOG_EMERG, "%s\n", errormessage);
331 memset(&addr, 0, sizeof(addr));
332 addr.sun_family = AF_UNIX;
333 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
335 s = socket(AF_UNIX, SOCK_STREAM, 0);
337 snprintf(errormessage, SIZ,
338 "citserver: Can't create a socket: %s",
340 syslog(LOG_EMERG, "%s\n", errormessage);
344 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
345 snprintf(errormessage, SIZ,
346 "citserver: Can't bind: %s",
348 syslog(LOG_EMERG, "%s\n", errormessage);
352 /* set to nonblock - we need this for some obscure situations */
353 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
354 snprintf(errormessage, SIZ,
355 "citserver: Can't set socket to non-blocking: %s",
357 syslog(LOG_EMERG, "%s\n", errormessage);
362 if (listen(s, actual_queue_len) < 0) {
363 snprintf(errormessage, SIZ,
364 "citserver: Can't listen: %s",
366 syslog(LOG_EMERG, "%s\n", errormessage);
370 #ifdef HAVE_STRUCT_UCRED
371 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
374 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
381 * The following functions implement output buffering on operating systems which
382 * support it (such as Linux and various BSD flavors).
386 # define HAVE_TCP_BUFFERING
389 # define HAVE_TCP_BUFFERING
390 # define TCP_CORK TCP_NOPUSH
392 #endif /* TCP_CORK */
393 #endif /* HAVE_DARWIN */
395 static unsigned on = 1, off = 0;
397 void buffer_output(void) {
398 #ifdef HAVE_TCP_BUFFERING
400 if (!CC->redirect_ssl)
402 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
406 void unbuffer_output(void) {
407 #ifdef HAVE_TCP_BUFFERING
409 if (!CC->redirect_ssl)
411 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
415 void flush_output(void) {
416 #ifdef HAVE_TCP_BUFFERING
417 struct CitContext *CCC = CC;
418 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
419 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
424 static void flush_client_inbuf(void)
428 FlushStrBuf(CCC->ReadBuf);
435 * client_write() ... Send binary data to the client.
437 int client_write(const char *buf, int nbytes)
439 int bytes_written = 0;
441 #ifndef HAVE_TCP_BUFFERING
442 int old_buffer_len = 0;
448 if (nbytes < 1) return(0);
458 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
460 fd = fopen(fn, "a+");
461 fprintf(fd, "Sending: BufSize: %d BufContent: [",
463 rv = fwrite(buf, nbytes, 1, fd);
470 // flush_client_inbuf();
471 if (Ctx->redirect_buffer != NULL) {
472 StrBufAppendBufPlain(Ctx->redirect_buffer,
478 if (Ctx->redirect_ssl) {
479 client_write_ssl(buf, nbytes);
483 if (Ctx->client_socket == -1) return -1;
485 fdflags = fcntl(Ctx->client_socket, F_GETFL);
487 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
488 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
490 FD_SET(Ctx->client_socket, &wset);
491 if (select(1, NULL, &wset, NULL, NULL) == -1) {
494 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
495 if (CtdlThreadCheckStop()) {
499 /* can't trust fd's and stuff so we need to re-create them */
504 "client_write(%d bytes) select failed: %s (%d)\n",
505 nbytes - bytes_written,
506 strerror(errno), errno);
514 retval = write(Ctx->client_socket, &buf[bytes_written],
515 nbytes - bytes_written);
518 "client_write(%d bytes) failed: %s (%d)\n",
519 nbytes - bytes_written,
520 strerror(errno), errno);
522 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
526 bytes_written = bytes_written + retval;
531 void cputbuf(const StrBuf *Buf) {
532 client_write(ChrPtr(Buf), StrLength(Buf));
537 * cprintf() Send formatted printable data to the client.
538 * Implemented in terms of client_write() so it's technically not sysdep...
540 void cprintf(const char *format, ...) {
544 va_start(arg_ptr, format);
545 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
546 buf[sizeof buf - 2] = '\n';
547 client_write(buf, strlen(buf));
553 * Read data from the client socket.
555 * sock socket fd to read from
556 * buf buffer to read into
557 * bytes number of bytes to read
558 * timeout Number of seconds to wait before timing out
560 * Possible return values:
561 * 1 Requested number of bytes has been read.
562 * 0 Request timed out.
563 * -1 Connection is broken, or other error.
565 int client_read_blob(StrBuf *Target, int bytes, int timeout)
572 if (CCC->redirect_ssl) {
578 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
580 fd = fopen(fn, "a+");
581 fprintf(fd, "Reading BLOB: BufSize: %d ",
583 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
589 retval = client_read_sslblob(Target, bytes, timeout);
596 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
598 fd = fopen(fn, "a+");
599 fprintf(fd, "Read: %d BufContent: [",
601 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
616 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
618 fd = fopen(fn, "a+");
619 fprintf(fd, "Reading BLOB: BufSize: %d ",
621 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
627 retval = StrBufReadBLOBBuffered(Target,
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);
660 * to make client_read_random_blob() more efficient, increase buffer size.
661 * just use in greeting function, else your buffer may be flushed
663 void client_set_inbound_buf(long N)
665 FlushStrBuf(CC->ReadBuf);
666 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
669 int client_read_random_blob(StrBuf *Target, int timeout)
674 rc = client_read_blob(Target, 1, timeout);
680 len = StrLength(CCC->ReadBuf);
681 pch = ChrPtr(CCC->ReadBuf);
685 if (CCC->Pos != NULL) {
686 len -= CCC->Pos - pch;
689 StrBufAppendBufPlain(Target, pch, len, 0);
690 FlushStrBuf(CCC->ReadBuf);
698 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
700 fd = fopen(fn, "a+");
701 fprintf(fd, "Read: BufSize: %d BufContent: [",
703 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
711 return StrLength(Target);
719 int client_read_to(char *buf, int bytes, int timeout)
724 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
733 ChrPtr(CCC->MigrateBuf),
734 StrLength(CCC->MigrateBuf) + 1);
735 FlushStrBuf(CCC->MigrateBuf);
741 int HaveMoreLinesWaiting(CitContext *CCC)
743 if ((CCC->kill_me == 1) || (
744 (CCC->Pos == NULL) &&
745 (StrLength(CCC->ReadBuf) == 0) &&
746 (CCC->client_socket != -1)) )
754 * Read data from the client socket with default timeout.
755 * (This is implemented in terms of client_read_to() and could be
756 * justifiably moved out of sysdep.c)
758 INLINE int client_read(char *buf, int bytes)
760 return(client_read_to(buf, bytes, config.c_sleeping));
763 int CtdlClientGetLine(StrBuf *Target)
771 if (CCC->redirect_ssl) {
781 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
783 fd = fopen(fn, "a+");
784 pch = ChrPtr(CCC->ReadBuf);
785 len = StrLength(CCC->ReadBuf);
786 if (CCC->Pos != NULL)
787 rlen = CC->Pos - pch;
791 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
794 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
797 rc = client_readline_sslbuffer(Target,
802 pch = ChrPtr(CCC->ReadBuf);
803 nlen = StrLength(CCC->ReadBuf);
804 if (CCC->Pos != NULL)
805 nrlen = CC->Pos - pch;
809 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
810 len, nlen, rlen, nrlen, pch);
812 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
813 len, nlen, rlen, nrlen);
815 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
816 StrLength(Target), ChrPtr(Target));
832 int len, rlen, nlen, nrlen;
835 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
837 fd = fopen(fn, "a+");
838 pch = ChrPtr(CCC->ReadBuf);
839 len = StrLength(CCC->ReadBuf);
840 if (CCC->Pos != NULL)
841 rlen = CC->Pos - pch;
845 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
848 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
851 rc = StrBufTCP_read_buffered_line_fast(Target,
860 pch = ChrPtr(CCC->ReadBuf);
861 nlen = StrLength(CCC->ReadBuf);
862 if (CCC->Pos != NULL)
863 nrlen = CC->Pos - pch;
867 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
868 len, nlen, rlen, nrlen, pch);
870 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
871 len, nlen, rlen, nrlen);
873 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
874 StrLength(Target), ChrPtr(Target));
877 if ((rc < 0) && (Error != NULL))
889 * client_getln() ... Get a LF-terminated line of text from the client.
890 * (This is implemented in terms of client_read() and could be
891 * justifiably moved out of sysdep.c)
893 int client_getln(char *buf, int bufsize)
899 retval = CtdlClientGetLine(CCC->MigrateBuf);
904 i = StrLength(CCC->MigrateBuf);
905 pCh = ChrPtr(CCC->MigrateBuf);
906 /* Strip the trailing LF, and the trailing CR if present.
911 && ( (pCh[i - 1]==13)
912 || ( pCh[i - 1]==10)) ) {
918 FlushStrBuf(CCC->MigrateBuf);
920 safestrncpy(&buf[i], "000", bufsize - i);
927 * Cleanup any contexts that are left lying around
931 void close_masters (void)
933 struct ServiceFunctionHook *serviceptr;
936 * close all protocol master sockets
938 for (serviceptr = ServiceHookTable; serviceptr != NULL;
939 serviceptr = serviceptr->next ) {
941 if (serviceptr->tcp_port > 0)
943 syslog(LOG_INFO, "Closing listener on port %d\n",
944 serviceptr->tcp_port);
945 serviceptr->tcp_port = 0;
948 if (serviceptr->sockpath != NULL)
949 syslog(LOG_INFO, "Closing listener on '%s'\n",
950 serviceptr->sockpath);
952 close(serviceptr->msock);
953 /* If it's a Unix domain socket, remove the file. */
954 if (serviceptr->sockpath != NULL) {
955 unlink(serviceptr->sockpath);
956 serviceptr->sockpath = NULL;
963 * The system-dependent part of master_cleanup() - close the master socket.
965 void sysdep_master_cleanup(void) {
974 CtdlDestroyProtoHooks();
975 CtdlDestroyDeleteHooks();
976 CtdlDestroyXmsgHooks();
977 CtdlDestroyNetprocHooks();
978 CtdlDestroyUserHooks();
979 CtdlDestroyMessageHook();
980 CtdlDestroyCleanupHooks();
981 CtdlDestroyFixedOutputHooks();
982 CtdlDestroySessionHooks();
983 CtdlDestroyServiceHook();
984 CtdlDestroyRoomHooks();
985 CtdlDestroySearchHooks();
986 #ifdef HAVE_BACKTRACE
994 void graceful_shutdown(int signum) {
995 kill(current_child, signum);
996 unlink(file_pid_file);
1001 int nFireUpsNonRestart = 0;
1002 pid_t ForkedPid = 1;
1005 * Start running as a daemon.
1007 void start_daemon(int unused) {
1015 /* Close stdin/stdout/stderr and replace them with /dev/null.
1016 * We don't just call close() because we don't want these fd's
1017 * to be reused for other files.
1019 if (chdir(ctdl_run_dir) != 0)
1021 "unable to change into directory [%s]: %s",
1022 ctdl_run_dir, strerror(errno));
1029 signal(SIGHUP, SIG_IGN);
1030 signal(SIGINT, SIG_IGN);
1031 signal(SIGQUIT, SIG_IGN);
1035 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1036 (freopen("/dev/null", "w", stdout) != stdout) ||
1037 (freopen("/dev/null", "w", stderr) != stderr))
1039 "unable to reopen stdin/out/err %s",
1044 current_child = fork();
1046 signal(SIGTERM, graceful_shutdown);
1048 if (current_child < 0) {
1053 else if (current_child == 0) {
1054 return; /* continue starting citadel. */
1058 fp = fopen(file_pid_file, "w");
1060 fprintf(fp, ""F_PID_T"\n", getpid());
1063 waitpid(current_child, &status, 0);
1066 nFireUpsNonRestart = nFireUps;
1068 /* Exit code 0 means the watcher should exit */
1069 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1073 /* Exit code 101-109 means the watcher should exit */
1074 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1078 /* Any other exit code, or no exit code, means we should restart. */
1082 ForkedPid = current_child;
1085 } while (do_restart);
1087 unlink(file_pid_file);
1088 exit(WEXITSTATUS(status));
1093 void checkcrash(void)
1095 if (nFireUpsNonRestart != nFireUps)
1099 CrashMail = NewStrBuf();
1100 syslog(LOG_ALERT, "Posting crash message\n");
1101 StrBufPrintf(CrashMail,
1103 " The Citadel server process (citserver) terminated unexpectedly."
1105 " This could be the result of a bug in the server program, or some external "
1107 " You can obtain more information about this by enabling core dumps.\n \n"
1108 " For more information, please see:\n \n"
1109 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1112 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1114 ctdl_run_dir, ForkedPid);
1115 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1116 FreeStrBuf(&CrashMail);
1122 * Generic routine to convert a login name to a full name (gecos)
1123 * Returns nonzero if a conversion took place
1125 int convert_login(char NameToConvert[]) {
1129 pw = getpwnam(NameToConvert);
1134 strcpy(NameToConvert, pw->pw_gecos);
1135 for (a=0; a<strlen(NameToConvert); ++a) {
1136 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1145 * This loop just keeps going and going and going...
1149 * This current implimentation of worker_thread creates a bottle neck in several situations
1150 * The first thing to remember is that a single thread can handle more than one connection at a time.
1151 * More threads mean less memory for the system to run in.
1152 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1153 * something to happen anywhere.
1154 * This current implimentation requires worker threads to wait in other locations, after it has
1155 * been committed to a single connection which is very wasteful.
1156 * As an extreme case consider this:
1157 * A slow client connects and this slow client sends only one character each second.
1158 * With this current implimentation a single worker thread is dispatched to handle that connection
1159 * until such times as the client timeout expires, an error occurs on the socket or the client
1160 * completes its transmission.
1161 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1162 * second interval between chars.
1164 * It is my intention to re-write this code and the associated client_getln, client_read functions
1165 * to allow any thread to read data on behalf of any connection (context).
1166 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1167 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1169 * This worker thread loop also needs to be able to handle binary data.
1172 void *worker_thread(void *arg) {
1175 CitContext *bind_me = NULL;
1179 int force_purge = 0;
1182 while (!CtdlThreadCheckStop()) {
1184 /* make doubly sure we're not holding any stale db handles
1185 * which might cause a deadlock.
1187 cdb_check_handles();
1188 do_select: force_purge = 0;
1189 bind_me = NULL; /* Which session shall we handle? */
1191 /* Initialize the fdset. */
1195 begin_critical_section(S_SESSION_TABLE);
1196 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1198 client_socket = ptr->client_socket;
1199 /* Dont select on dead sessions only truly idle ones */
1200 if ((ptr->state == CON_IDLE) &&
1201 (CC->kill_me == 0) &&
1202 (client_socket != -1))
1204 FD_SET(client_socket, &readfds);
1205 if (client_socket > highest)
1206 highest = client_socket;
1208 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1210 ptr->state = CON_EXECUTING;
1213 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1215 ptr->state = CON_STARTING;
1219 end_critical_section(S_SESSION_TABLE);
1225 /* If we got this far, it means that there are no sessions
1226 * which a previous thread marked for attention, so we go
1227 * ahead and get ready to select().
1230 if (!CtdlThreadCheckStop()) {
1231 tv.tv_sec = 1; /* wake up every second if no input */
1233 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1238 /* Now figure out who made this select() unblock.
1239 * First, check for an error or exit condition.
1242 if (errno == EBADF) {
1243 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1247 if (errno != EINTR) {
1248 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1249 CtdlThreadStopAll();
1252 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1253 if (CtdlThreadCheckStop()) return(NULL);
1257 else if(retval == 0) {
1258 if (CtdlThreadCheckStop()) return(NULL);
1261 /* It must be a client socket. Find a context that has data
1262 * waiting on its socket *and* is in the CON_IDLE state. Any
1263 * active sockets other than our chosen one are marked as
1264 * CON_READY so the next thread that comes around can just bind
1265 * to one without having to select() again.
1267 begin_critical_section(S_SESSION_TABLE);
1268 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1269 int checkfd = ptr->client_socket;
1270 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1271 if (FD_ISSET(checkfd, &readfds)) {
1272 ptr->input_waiting = 1;
1274 bind_me = ptr; /* I choose you! */
1275 bind_me->state = CON_EXECUTING;
1278 ptr->state = CON_READY;
1280 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1282 bind_me = ptr; /* I choose you! */
1283 bind_me->state = CON_EXECUTING;
1286 ptr->state = CON_READY;
1291 end_critical_section(S_SESSION_TABLE);
1294 /* We're bound to a session */
1295 if (bind_me != NULL) {
1296 become_session(bind_me);
1298 if (bind_me->state == CON_STARTING) {
1299 bind_me->state = CON_EXECUTING;
1300 begin_session(bind_me);
1301 bind_me->h_greeting_function();
1303 /* If the client has sent a command, execute it. */
1304 if (CC->input_waiting) {
1305 CC->h_command_function();
1307 while (HaveMoreLinesWaiting(CC))
1308 CC->h_command_function();
1310 CC->input_waiting = 0;
1313 /* If there are asynchronous messages waiting and the
1314 * client supports it, do those now */
1315 if ((CC->is_async) && (CC->async_waiting)
1316 && (CC->h_async_function != NULL)) {
1317 CC->h_async_function();
1318 CC->async_waiting = 0;
1321 force_purge = CC->kill_me;
1322 become_session(NULL);
1323 bind_me->state = CON_IDLE;
1326 dead_session_purge(force_purge);
1329 /* If control reaches this point, the server is shutting down */
1337 * A function to handle selecting on master sockets.
1338 * In other words it handles new connections.
1341 void *select_on_master (void *arg)
1343 struct ServiceFunctionHook *serviceptr;
1347 int ssock; /* Descriptor for client socket */
1348 CitContext *con= NULL; /* Temporary context pointer */
1352 struct CitContext select_on_master_CC;
1354 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1355 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1357 while (!CtdlThreadCheckStop()) {
1358 /* Initialize the fdset. */
1359 FD_ZERO(&master_fds);
1362 /* First, add the various master sockets to the fdset. */
1363 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1364 serviceptr = serviceptr->next ) {
1365 m = serviceptr->msock;
1366 FD_SET(m, &master_fds);
1372 if (!CtdlThreadCheckStop()) {
1373 tv.tv_sec = 60; /* wake up every second if no input */
1375 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1380 /* Now figure out who made this select() unblock.
1381 * First, check for an error or exit condition.
1384 if (errno == EBADF) {
1385 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1389 if (errno != EINTR) {
1390 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1391 CtdlThreadStopAll();
1393 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1394 if (CtdlThreadCheckStop()) return(NULL);
1398 else if(retval == 0) {
1399 if (CtdlThreadCheckStop()) return(NULL);
1402 /* Next, check to see if it's a new client connecting
1403 * on a master socket.
1405 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1406 serviceptr = serviceptr->next ) {
1408 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1409 ssock = accept(serviceptr->msock, NULL, 0);
1412 "New client socket %d\n",
1415 /* The master socket is non-blocking but the client
1416 * sockets need to be blocking, otherwise certain
1417 * operations barf on FreeBSD. Not a fatal error.
1419 if (fcntl(ssock, F_SETFL, 0) < 0) {
1421 "citserver: Can't set socket to blocking: %s\n",
1425 /* New context will be created already
1426 * set up in the CON_EXECUTING state.
1428 con = CreateNewContext();
1430 /* Assign our new socket number to it. */
1431 con->client_socket = ssock;
1432 con->h_command_function =
1433 serviceptr->h_command_function;
1434 con->h_async_function =
1435 serviceptr->h_async_function;
1436 con->h_greeting_function = serviceptr->h_greeting_function;
1438 serviceptr->ServiceName;
1440 /* Determine whether it's a local socket */
1441 if (serviceptr->sockpath != NULL)
1442 con->is_local_socket = 1;
1444 /* Set the SO_REUSEADDR socket option */
1446 setsockopt(ssock, SOL_SOCKET,
1450 con->state = CON_GREETING;
1459 CtdlClearSystemContext();
1468 * Translate text facility name to syslog.h defined value.
1470 int SyslogFacility(char *name)
1479 { LOG_KERN, "kern" },
1480 { LOG_USER, "user" },
1481 { LOG_MAIL, "mail" },
1482 { LOG_DAEMON, "daemon" },
1483 { LOG_AUTH, "auth" },
1484 { LOG_SYSLOG, "syslog" },
1486 { LOG_NEWS, "news" },
1487 { LOG_UUCP, "uucp" },
1488 { LOG_LOCAL0, "local0" },
1489 { LOG_LOCAL1, "local1" },
1490 { LOG_LOCAL2, "local2" },
1491 { LOG_LOCAL3, "local3" },
1492 { LOG_LOCAL4, "local4" },
1493 { LOG_LOCAL5, "local5" },
1494 { LOG_LOCAL6, "local6" },
1495 { LOG_LOCAL7, "local7" },
1498 for(i = 0; facTbl[i].name != NULL; i++) {
1499 if(!strcasecmp(name, facTbl[i].name))
1500 return facTbl[i].facility;
1506 /********** MEM CHEQQER ***********/
1508 #ifdef DEBUG_MEMORY_LEAKS
1515 void *tracked_malloc(size_t size, char *file, int line) {
1516 struct igheap *thisheap;
1519 block = malloc(size);
1520 if (block == NULL) return(block);
1522 thisheap = malloc(sizeof(struct igheap));
1523 if (thisheap == NULL) {
1528 thisheap->block = block;
1529 strcpy(thisheap->file, file);
1530 thisheap->line = line;
1532 begin_critical_section(S_DEBUGMEMLEAKS);
1533 thisheap->next = igheap;
1535 end_critical_section(S_DEBUGMEMLEAKS);
1541 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1542 struct igheap *thisheap;
1545 block = realloc(ptr, size);
1546 if (block == NULL) return(block);
1548 thisheap = malloc(sizeof(struct igheap));
1549 if (thisheap == NULL) {
1554 thisheap->block = block;
1555 strcpy(thisheap->file, file);
1556 thisheap->line = line;
1558 begin_critical_section(S_DEBUGMEMLEAKS);
1559 thisheap->next = igheap;
1561 end_critical_section(S_DEBUGMEMLEAKS);
1568 void tracked_free(void *ptr) {
1569 struct igheap *thisheap;
1570 struct igheap *trash;
1574 if (igheap == NULL) return;
1575 begin_critical_section(S_DEBUGMEMLEAKS);
1576 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1577 if (thisheap->next != NULL) {
1578 if (thisheap->next->block == ptr) {
1579 trash = thisheap->next;
1580 thisheap->next = thisheap->next->next;
1585 if (igheap->block == ptr) {
1587 igheap = igheap->next;
1590 end_critical_section(S_DEBUGMEMLEAKS);
1593 char *tracked_strdup(const char *s, char *file, int line) {
1596 if (s == NULL) return(NULL);
1597 ptr = tracked_malloc(strlen(s) + 1, file, line);
1598 if (ptr == NULL) return(NULL);
1599 strncpy(ptr, s, strlen(s));
1603 void dump_heap(void) {
1604 struct igheap *thisheap;
1606 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1607 syslog(LOG_CRIT, "UNFREED: %30s : %d\n",
1608 thisheap->file, thisheap->line);
1612 #endif /* DEBUG_MEMORY_LEAKS */