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"
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, SIGHUP);
170 sigaddset(&set, SIGTERM);
171 sigprocmask(SIG_UNBLOCK, &set, NULL);
173 signal(SIGINT, signal_cleanup); // intr = shutdown
174 signal(SIGHUP, signal_cleanup);
175 signal(SIGTERM, signal_cleanup);
176 signal(SIGUSR2, signal_exit);
179 * Do not shut down the server on broken pipe signals, otherwise the
180 * whole Citadel service would come down whenever a single client
183 signal(SIGPIPE, SIG_IGN);
188 * This is a generic function to set up a master socket for listening on
189 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
191 * ip_addr IP address to bind
192 * port_number port number to bind
193 * queue_len number of incoming connections to allow in the queue
195 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
198 struct sockaddr_in6 sin6;
199 struct sockaddr_in sin4;
203 memset(&sin6, 0, sizeof(sin6));
204 memset(&sin4, 0, sizeof(sin4));
205 sin6.sin6_family = AF_INET6;
206 sin4.sin_family = AF_INET;
208 if ( (ip_addr == NULL) /* any IPv6 */
209 || (IsEmptyStr(ip_addr))
210 || (!strcmp(ip_addr, "*"))
213 sin6.sin6_addr = in6addr_any;
215 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
218 sin4.sin_addr.s_addr = INADDR_ANY;
220 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
223 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
224 snprintf(errormessage, SIZ,
225 "Error binding to [%s] : %s", ip_addr, strerror(errno)
227 syslog(LOG_ALERT, "%s\n", errormessage);
231 else /* specific IPv6 */
234 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
235 snprintf(errormessage, SIZ,
236 "Error binding to [%s] : %s", ip_addr, strerror(errno)
238 syslog(LOG_ALERT, "%s\n", errormessage);
243 if (port_number == 0) {
244 snprintf(errormessage, SIZ,
245 "Can't start: no port number specified."
247 syslog(LOG_ALERT, "%s\n", errormessage);
250 sin6.sin6_port = htons((u_short) port_number);
251 sin4.sin_port = htons((u_short) port_number);
253 p = getprotobyname("tcp");
255 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
257 snprintf(errormessage, SIZ,
258 "Can't create a listening socket: %s", strerror(errno)
260 syslog(LOG_ALERT, "%s\n", errormessage);
263 /* Set some socket options that make sense. */
265 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
267 if (ip_version == 6) {
268 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
271 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
275 snprintf(errormessage, SIZ,
276 "Can't bind: %s", strerror(errno)
278 syslog(LOG_ALERT, "%s\n", errormessage);
282 fcntl(s, F_SETFL, O_NONBLOCK);
284 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
285 snprintf(errormessage, SIZ,
286 "Can't listen: %s", strerror(errno)
288 syslog(LOG_ALERT, "%s\n", errormessage);
299 * Create a Unix domain socket and listen on it
301 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
303 struct sockaddr_un addr;
306 int actual_queue_len;
307 #ifdef HAVE_STRUCT_UCRED
311 actual_queue_len = queue_len;
312 if (actual_queue_len < 5) actual_queue_len = 5;
314 i = unlink(sockpath);
315 if ((i != 0) && (errno != ENOENT)) {
316 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
317 sockpath, strerror(errno)
319 syslog(LOG_EMERG, "%s\n", errormessage);
323 memset(&addr, 0, sizeof(addr));
324 addr.sun_family = AF_UNIX;
325 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
327 s = socket(AF_UNIX, SOCK_STREAM, 0);
329 snprintf(errormessage, SIZ,
330 "citserver: Can't create a socket: %s",
332 syslog(LOG_EMERG, "%s\n", errormessage);
336 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
337 snprintf(errormessage, SIZ,
338 "citserver: Can't bind: %s",
340 syslog(LOG_EMERG, "%s\n", errormessage);
344 /* set to nonblock - we need this for some obscure situations */
345 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
346 snprintf(errormessage, SIZ,
347 "citserver: Can't set socket to non-blocking: %s",
349 syslog(LOG_EMERG, "%s\n", errormessage);
354 if (listen(s, actual_queue_len) < 0) {
355 snprintf(errormessage, SIZ,
356 "citserver: Can't listen: %s",
358 syslog(LOG_EMERG, "%s\n", errormessage);
362 #ifdef HAVE_STRUCT_UCRED
363 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
366 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
373 * The following functions implement output buffering on operating systems which
374 * support it (such as Linux and various BSD flavors).
378 # define HAVE_TCP_BUFFERING
381 # define HAVE_TCP_BUFFERING
382 # define TCP_CORK TCP_NOPUSH
384 #endif /* TCP_CORK */
385 #endif /* HAVE_DARWIN */
387 static unsigned on = 1, off = 0;
389 void buffer_output(void) {
390 #ifdef HAVE_TCP_BUFFERING
392 if (!CC->redirect_ssl)
394 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
398 void unbuffer_output(void) {
399 #ifdef HAVE_TCP_BUFFERING
401 if (!CC->redirect_ssl)
403 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
407 void flush_output(void) {
408 #ifdef HAVE_TCP_BUFFERING
409 struct CitContext *CCC = CC;
410 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
411 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
416 static void flush_client_inbuf(void)
420 FlushStrBuf(CCC->ReadBuf);
428 * client_close() ... close the client socket
430 void client_close(void) {
431 CitContext *CCC = CC;
435 if (CCC->client_socket < 0) return;
436 syslog(LOG_DEBUG, "Closing socket %d\n", CCC->client_socket);
437 r = close(CCC->client_socket);
438 if (!r) syslog(LOG_INFO, "close() failed: %s\n", strerror(errno));
439 CCC->client_socket = -1 ;
446 * client_write() ... Send binary data to the client.
448 int client_write(const char *buf, int nbytes)
450 int bytes_written = 0;
452 #ifndef HAVE_TCP_BUFFERING
453 int old_buffer_len = 0;
459 if (nbytes < 1) return(0);
469 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
471 fd = fopen(fn, "a+");
472 fprintf(fd, "Sending: BufSize: %d BufContent: [",
474 rv = fwrite(buf, nbytes, 1, fd);
481 // flush_client_inbuf();
482 if (Ctx->redirect_buffer != NULL) {
483 StrBufAppendBufPlain(Ctx->redirect_buffer,
489 if (Ctx->redirect_ssl) {
490 client_write_ssl(buf, nbytes);
494 if (Ctx->client_socket == -1) return -1;
496 fdflags = fcntl(Ctx->client_socket, F_GETFL);
498 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
499 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
501 FD_SET(Ctx->client_socket, &wset);
502 if (select(1, NULL, &wset, NULL, NULL) == -1) {
505 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
506 if (CtdlThreadCheckStop()) {
507 CC->kill_me = KILLME_SELECT_INTERRUPTED;
510 /* can't trust fd's and stuff so we need to re-create them */
515 "client_write(%d bytes) select failed: %s (%d)\n",
516 nbytes - bytes_written,
517 strerror(errno), errno
521 Ctx->kill_me = KILLME_SELECT_FAILED;
527 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
530 "client_write(%d bytes) failed: %s (%d)\n",
531 nbytes - bytes_written,
532 strerror(errno), errno
536 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
537 Ctx->kill_me = KILLME_WRITE_FAILED;
540 bytes_written = bytes_written + retval;
545 void cputbuf(const StrBuf *Buf) {
546 client_write(ChrPtr(Buf), StrLength(Buf));
551 * cprintf() Send formatted printable data to the client.
552 * Implemented in terms of client_write() so it's technically not sysdep...
554 void cprintf(const char *format, ...) {
558 va_start(arg_ptr, format);
559 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
560 buf[sizeof buf - 2] = '\n';
561 client_write(buf, strlen(buf));
567 * Read data from the client socket.
569 * sock socket fd to read from
570 * buf buffer to read into
571 * bytes number of bytes to read
572 * timeout Number of seconds to wait before timing out
574 * Possible return values:
575 * 1 Requested number of bytes has been read.
576 * 0 Request timed out.
577 * -1 Connection is broken, or other error.
579 int client_read_blob(StrBuf *Target, int bytes, int timeout)
586 if (CCC->redirect_ssl) {
592 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
594 fd = fopen(fn, "a+");
595 fprintf(fd, "Reading BLOB: BufSize: %d ",
597 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
603 retval = client_read_sslblob(Target, bytes, timeout);
610 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
612 fd = fopen(fn, "a+");
613 fprintf(fd, "Read: %d BufContent: [",
615 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
630 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
632 fd = fopen(fn, "a+");
633 fprintf(fd, "Reading BLOB: BufSize: %d ",
635 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
641 retval = StrBufReadBLOBBuffered(Target,
650 syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
655 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
657 fd = fopen(fn, "a+");
658 fprintf(fd, "Read: %d BufContent: [",
660 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
670 * to make client_read_random_blob() more efficient, increase buffer size.
671 * just use in greeting function, else your buffer may be flushed
673 void client_set_inbound_buf(long N)
675 FlushStrBuf(CC->ReadBuf);
676 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
679 int client_read_random_blob(StrBuf *Target, int timeout)
684 rc = client_read_blob(Target, 1, timeout);
690 len = StrLength(CCC->ReadBuf);
691 pch = ChrPtr(CCC->ReadBuf);
695 if (CCC->Pos != NULL) {
696 len -= CCC->Pos - pch;
699 StrBufAppendBufPlain(Target, pch, len, 0);
700 FlushStrBuf(CCC->ReadBuf);
708 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
710 fd = fopen(fn, "a+");
711 fprintf(fd, "Read: BufSize: %d BufContent: [",
713 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
721 return StrLength(Target);
729 int client_read_to(char *buf, int bytes, int timeout)
734 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
743 ChrPtr(CCC->MigrateBuf),
744 StrLength(CCC->MigrateBuf) + 1);
745 FlushStrBuf(CCC->MigrateBuf);
751 int HaveMoreLinesWaiting(CitContext *CCC)
753 if ((CCC->kill_me != 0) || (
754 (CCC->Pos == NULL) &&
755 (StrLength(CCC->ReadBuf) == 0) &&
756 (CCC->client_socket != -1)) )
764 * Read data from the client socket with default timeout.
765 * (This is implemented in terms of client_read_to() and could be
766 * justifiably moved out of sysdep.c)
768 INLINE int client_read(char *buf, int bytes)
770 return(client_read_to(buf, bytes, config.c_sleeping));
773 int CtdlClientGetLine(StrBuf *Target)
781 if (CCC->redirect_ssl) {
791 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
793 fd = fopen(fn, "a+");
794 pch = ChrPtr(CCC->ReadBuf);
795 len = StrLength(CCC->ReadBuf);
796 if (CCC->Pos != NULL)
797 rlen = CC->Pos - pch;
801 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
804 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
807 rc = client_readline_sslbuffer(Target,
812 pch = ChrPtr(CCC->ReadBuf);
813 nlen = StrLength(CCC->ReadBuf);
814 if (CCC->Pos != NULL)
815 nrlen = CC->Pos - pch;
819 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
820 len, nlen, rlen, nrlen, pch);
822 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
823 len, nlen, rlen, nrlen);
825 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
826 StrLength(Target), ChrPtr(Target));
842 int len, rlen, nlen, nrlen;
845 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
847 fd = fopen(fn, "a+");
848 pch = ChrPtr(CCC->ReadBuf);
849 len = StrLength(CCC->ReadBuf);
850 if (CCC->Pos != NULL)
851 rlen = CC->Pos - pch;
855 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
858 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
861 rc = StrBufTCP_read_buffered_line_fast(Target,
870 pch = ChrPtr(CCC->ReadBuf);
871 nlen = StrLength(CCC->ReadBuf);
872 if (CCC->Pos != NULL)
873 nrlen = CC->Pos - pch;
877 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
878 len, nlen, rlen, nrlen, pch);
880 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
881 len, nlen, rlen, nrlen);
883 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
884 StrLength(Target), ChrPtr(Target));
887 if ((rc < 0) && (Error != NULL))
899 * client_getln() ... Get a LF-terminated line of text from the client.
900 * (This is implemented in terms of client_read() and could be
901 * justifiably moved out of sysdep.c)
903 int client_getln(char *buf, int bufsize)
909 retval = CtdlClientGetLine(CCC->MigrateBuf);
914 i = StrLength(CCC->MigrateBuf);
915 pCh = ChrPtr(CCC->MigrateBuf);
916 /* Strip the trailing LF, and the trailing CR if present.
921 && ( (pCh[i - 1]==13)
922 || ( pCh[i - 1]==10)) ) {
928 FlushStrBuf(CCC->MigrateBuf);
930 safestrncpy(&buf[i], "000", bufsize - i);
937 * Cleanup any contexts that are left lying around
941 void close_masters (void)
943 struct ServiceFunctionHook *serviceptr;
946 * close all protocol master sockets
948 for (serviceptr = ServiceHookTable; serviceptr != NULL;
949 serviceptr = serviceptr->next ) {
951 if (serviceptr->tcp_port > 0)
953 syslog(LOG_INFO, "Closing listener on port %d\n",
954 serviceptr->tcp_port);
955 serviceptr->tcp_port = 0;
958 if (serviceptr->sockpath != NULL)
959 syslog(LOG_INFO, "Closing listener on '%s'\n",
960 serviceptr->sockpath);
962 close(serviceptr->msock);
963 /* If it's a Unix domain socket, remove the file. */
964 if (serviceptr->sockpath != NULL) {
965 unlink(serviceptr->sockpath);
966 serviceptr->sockpath = NULL;
973 * The system-dependent part of master_cleanup() - close the master socket.
975 void sysdep_master_cleanup(void) {
984 CtdlDestroyProtoHooks();
985 CtdlDestroyDeleteHooks();
986 CtdlDestroyXmsgHooks();
987 CtdlDestroyNetprocHooks();
988 CtdlDestroyUserHooks();
989 CtdlDestroyMessageHook();
990 CtdlDestroyCleanupHooks();
991 CtdlDestroyFixedOutputHooks();
992 CtdlDestroySessionHooks();
993 CtdlDestroyServiceHook();
994 CtdlDestroyRoomHooks();
995 CtdlDestroySearchHooks();
996 #ifdef HAVE_BACKTRACE
1003 pid_t current_child;
1004 void graceful_shutdown(int signum) {
1005 kill(current_child, signum);
1006 unlink(file_pid_file);
1011 int nFireUpsNonRestart = 0;
1012 pid_t ForkedPid = 1;
1015 * Start running as a daemon.
1017 void start_daemon(int unused) {
1025 /* Close stdin/stdout/stderr and replace them with /dev/null.
1026 * We don't just call close() because we don't want these fd's
1027 * to be reused for other files.
1029 if (chdir(ctdl_run_dir) != 0)
1031 "unable to change into directory [%s]: %s",
1032 ctdl_run_dir, strerror(errno));
1039 signal(SIGHUP, SIG_IGN);
1040 signal(SIGINT, SIG_IGN);
1041 signal(SIGQUIT, SIG_IGN);
1045 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1046 (freopen("/dev/null", "w", stdout) != stdout) ||
1047 (freopen("/dev/null", "w", stderr) != stderr))
1049 "unable to reopen stdin/out/err %s",
1054 current_child = fork();
1056 signal(SIGTERM, graceful_shutdown);
1058 if (current_child < 0) {
1063 else if (current_child == 0) {
1064 return; /* continue starting citadel. */
1068 fp = fopen(file_pid_file, "w");
1070 fprintf(fp, ""F_PID_T"\n", getpid());
1073 waitpid(current_child, &status, 0);
1076 nFireUpsNonRestart = nFireUps;
1078 /* Exit code 0 means the watcher should exit */
1079 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1083 /* Exit code 101-109 means the watcher should exit */
1084 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1088 /* Any other exit code, or no exit code, means we should restart. */
1092 ForkedPid = current_child;
1095 } while (do_restart);
1097 unlink(file_pid_file);
1098 exit(WEXITSTATUS(status));
1103 void checkcrash(void)
1105 if (nFireUpsNonRestart != nFireUps)
1109 CrashMail = NewStrBuf();
1110 syslog(LOG_ALERT, "Posting crash message\n");
1111 StrBufPrintf(CrashMail,
1113 " The Citadel server process (citserver) terminated unexpectedly."
1115 " This could be the result of a bug in the server program, or some external "
1117 " You can obtain more information about this by enabling core dumps.\n \n"
1118 " For more information, please see:\n \n"
1119 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1122 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1124 ctdl_run_dir, ForkedPid);
1125 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1126 FreeStrBuf(&CrashMail);
1132 * Generic routine to convert a login name to a full name (gecos)
1133 * Returns nonzero if a conversion took place
1135 int convert_login(char NameToConvert[]) {
1139 pw = getpwnam(NameToConvert);
1144 strcpy(NameToConvert, pw->pw_gecos);
1145 for (a=0; a<strlen(NameToConvert); ++a) {
1146 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1155 * This loop just keeps going and going and going...
1157 void *worker_thread(void *arg) {
1160 CitContext *bind_me = NULL;
1164 int force_purge = 0;
1167 while (!CtdlThreadCheckStop()) {
1169 /* make doubly sure we're not holding any stale db handles
1170 * which might cause a deadlock.
1172 cdb_check_handles();
1173 do_select: force_purge = 0;
1174 bind_me = NULL; /* Which session shall we handle? */
1176 /* Initialize the fdset. */
1180 begin_critical_section(S_SESSION_TABLE);
1181 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1182 /* Don't select on dead sessions, only truly idle ones */
1183 if ( (ptr->state == CON_IDLE)
1184 && (ptr->kill_me == 0)
1185 && (ptr->client_socket != -1)
1187 FD_SET(ptr->client_socket, &readfds);
1188 if (ptr->client_socket > highest)
1189 highest = ptr->client_socket;
1191 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1193 ptr->state = CON_EXECUTING;
1196 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1198 ptr->state = CON_STARTING;
1202 end_critical_section(S_SESSION_TABLE);
1208 /* If we got this far, it means that there are no sessions
1209 * which a previous thread marked for attention, so we go
1210 * ahead and get ready to select().
1213 if (!CtdlThreadCheckStop()) {
1214 tv.tv_sec = 1; /* wake up every second if no input */
1216 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1221 /* Now figure out who made this select() unblock.
1222 * First, check for an error or exit condition.
1225 if (errno == EBADF) {
1226 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1230 if (errno != EINTR) {
1231 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1232 CtdlThreadStopAll();
1235 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1236 if (CtdlThreadCheckStop()) return(NULL);
1240 else if(retval == 0) {
1241 if (CtdlThreadCheckStop()) return(NULL);
1244 /* It must be a client socket. Find a context that has data
1245 * waiting on its socket *and* is in the CON_IDLE state. Any
1246 * active sockets other than our chosen one are marked as
1247 * CON_READY so the next thread that comes around can just bind
1248 * to one without having to select() again.
1250 begin_critical_section(S_SESSION_TABLE);
1251 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1252 int checkfd = ptr->client_socket;
1253 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1254 if (FD_ISSET(checkfd, &readfds)) {
1255 ptr->input_waiting = 1;
1257 bind_me = ptr; /* I choose you! */
1258 bind_me->state = CON_EXECUTING;
1261 ptr->state = CON_READY;
1263 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1265 bind_me = ptr; /* I choose you! */
1266 bind_me->state = CON_EXECUTING;
1269 ptr->state = CON_READY;
1274 end_critical_section(S_SESSION_TABLE);
1277 /* We're bound to a session */
1278 if (bind_me != NULL) {
1279 become_session(bind_me);
1281 if (bind_me->state == CON_STARTING) {
1282 bind_me->state = CON_EXECUTING;
1283 begin_session(bind_me);
1284 bind_me->h_greeting_function();
1286 /* If the client has sent a command, execute it. */
1287 if (CC->input_waiting) {
1288 CC->h_command_function();
1290 while (HaveMoreLinesWaiting(CC))
1291 CC->h_command_function();
1293 CC->input_waiting = 0;
1296 /* If there are asynchronous messages waiting and the
1297 * client supports it, do those now */
1298 if ((CC->is_async) && (CC->async_waiting)
1299 && (CC->h_async_function != NULL)) {
1300 CC->h_async_function();
1301 CC->async_waiting = 0;
1304 force_purge = CC->kill_me;
1305 become_session(NULL);
1306 bind_me->state = CON_IDLE;
1309 dead_session_purge(force_purge);
1312 /* If control reaches this point, the server is shutting down */
1320 * A function to handle selecting on master sockets.
1321 * In other words it handles new connections.
1324 void *select_on_master (void *arg)
1326 struct ServiceFunctionHook *serviceptr;
1330 int ssock; /* Descriptor for client socket */
1331 CitContext *con= NULL; /* Temporary context pointer */
1335 struct CitContext select_on_master_CC;
1337 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1338 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1340 while (!CtdlThreadCheckStop()) {
1341 /* Initialize the fdset. */
1342 FD_ZERO(&master_fds);
1345 /* First, add the various master sockets to the fdset. */
1346 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1347 serviceptr = serviceptr->next ) {
1348 m = serviceptr->msock;
1349 FD_SET(m, &master_fds);
1355 if (!CtdlThreadCheckStop()) {
1356 tv.tv_sec = 60; /* wake up every second if no input */
1358 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1363 /* Now figure out who made this select() unblock.
1364 * First, check for an error or exit condition.
1367 if (errno == EBADF) {
1368 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1372 if (errno != EINTR) {
1373 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1374 CtdlThreadStopAll();
1376 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1377 if (CtdlThreadCheckStop()) return(NULL);
1381 else if(retval == 0) {
1382 if (CtdlThreadCheckStop()) return(NULL);
1385 /* Next, check to see if it's a new client connecting
1386 * on a master socket.
1388 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1389 serviceptr = serviceptr->next ) {
1391 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1392 ssock = accept(serviceptr->msock, NULL, 0);
1394 syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1396 /* The master socket is non-blocking but the client
1397 * sockets need to be blocking, otherwise certain
1398 * operations barf on FreeBSD. Not a fatal error.
1400 if (fcntl(ssock, F_SETFL, 0) < 0) {
1402 "citserver: Can't set socket to blocking: %s\n",
1406 /* New context will be created already
1407 * set up in the CON_EXECUTING state.
1409 con = CreateNewContext();
1411 /* Assign our new socket number to it. */
1412 con->client_socket = ssock;
1413 con->h_command_function = serviceptr->h_command_function;
1414 con->h_async_function = serviceptr->h_async_function;
1415 con->h_greeting_function = serviceptr->h_greeting_function;
1416 con->ServiceName = serviceptr->ServiceName;
1418 /* Determine whether it's a local socket */
1419 if (serviceptr->sockpath != NULL) {
1420 con->is_local_socket = 1;
1423 /* Set the SO_REUSEADDR socket option */
1425 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1426 con->state = CON_GREETING;
1434 CtdlClearSystemContext();
1443 * Translate text facility name to syslog.h defined value.
1445 int SyslogFacility(char *name)
1454 { LOG_KERN, "kern" },
1455 { LOG_USER, "user" },
1456 { LOG_MAIL, "mail" },
1457 { LOG_DAEMON, "daemon" },
1458 { LOG_AUTH, "auth" },
1459 { LOG_SYSLOG, "syslog" },
1461 { LOG_NEWS, "news" },
1462 { LOG_UUCP, "uucp" },
1463 { LOG_LOCAL0, "local0" },
1464 { LOG_LOCAL1, "local1" },
1465 { LOG_LOCAL2, "local2" },
1466 { LOG_LOCAL3, "local3" },
1467 { LOG_LOCAL4, "local4" },
1468 { LOG_LOCAL5, "local5" },
1469 { LOG_LOCAL6, "local6" },
1470 { LOG_LOCAL7, "local7" },
1473 for(i = 0; facTbl[i].name != NULL; i++) {
1474 if(!strcasecmp(name, facTbl[i].name))
1475 return facTbl[i].facility;
1481 /********** MEM CHEQQER ***********/
1483 #ifdef DEBUG_MEMORY_LEAKS
1490 void *tracked_malloc(size_t size, char *file, int line) {
1491 struct igheap *thisheap;
1494 block = malloc(size);
1495 if (block == NULL) return(block);
1497 thisheap = malloc(sizeof(struct igheap));
1498 if (thisheap == NULL) {
1503 thisheap->block = block;
1504 strcpy(thisheap->file, file);
1505 thisheap->line = line;
1507 begin_critical_section(S_DEBUGMEMLEAKS);
1508 thisheap->next = igheap;
1510 end_critical_section(S_DEBUGMEMLEAKS);
1516 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1517 struct igheap *thisheap;
1520 block = realloc(ptr, size);
1521 if (block == NULL) return(block);
1523 thisheap = malloc(sizeof(struct igheap));
1524 if (thisheap == NULL) {
1529 thisheap->block = block;
1530 strcpy(thisheap->file, file);
1531 thisheap->line = line;
1533 begin_critical_section(S_DEBUGMEMLEAKS);
1534 thisheap->next = igheap;
1536 end_critical_section(S_DEBUGMEMLEAKS);
1543 void tracked_free(void *ptr) {
1544 struct igheap *thisheap;
1545 struct igheap *trash;
1549 if (igheap == NULL) return;
1550 begin_critical_section(S_DEBUGMEMLEAKS);
1551 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1552 if (thisheap->next != NULL) {
1553 if (thisheap->next->block == ptr) {
1554 trash = thisheap->next;
1555 thisheap->next = thisheap->next->next;
1560 if (igheap->block == ptr) {
1562 igheap = igheap->next;
1565 end_critical_section(S_DEBUGMEMLEAKS);
1568 char *tracked_strdup(const char *s, char *file, int line) {
1571 if (s == NULL) return(NULL);
1572 ptr = tracked_malloc(strlen(s) + 1, file, line);
1573 if (ptr == NULL) return(NULL);
1574 strncpy(ptr, s, strlen(s));
1578 void dump_heap(void) {
1579 struct igheap *thisheap;
1581 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1582 syslog(LOG_CRIT, "UNFREED: %30s : %d\n",
1583 thisheap->file, thisheap->line);
1587 #endif /* DEBUG_MEMORY_LEAKS */