2 * Citadel "system dependent" stuff.
3 * See COPYING for copyright information.
5 * Here's where we (hopefully) have most parts of the Citadel server that
6 * would need to be altered to run the server in a non-POSIX environment.
8 * If we ever port to a different platform and either have multiple
9 * variants of this file or simply load it up with #ifdefs.
20 #include <sys/types.h>
23 #include <sys/socket.h>
25 #include <sys/syslog.h>
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
32 # include <sys/time.h>
39 #include <sys/resource.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
50 #define SHOW_ME_VAPPEND_PRINTF
51 #include <libcitadel.h>
54 #include "sysdep_decls.h"
55 #include "citserver.h"
59 #include "housekeeping.h"
60 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
72 #include "ctdl_module.h"
78 #ifdef DEBUG_MEMORY_LEAKS
86 struct igheap *igheap = NULL;
90 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
92 int syslog_facility = LOG_DAEMON;
93 int enable_syslog = 0;
94 int print_to_logfile = 1;
97 * CtdlLogPrintf() ... Write logging information
99 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
101 va_start(arg_ptr, format);
102 vCtdlLogPrintf(loglevel, format, arg_ptr);
106 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
110 vsyslog((syslog_facility | loglevel), format, arg_ptr);
113 /* stderr output code */
114 if (enable_syslog || !print_to_logfile) return;
116 /* if we run in forground and syslog is disabled, log to terminal */
117 if (loglevel <= verbosity) {
121 CitContext *CCC = CC;
122 ThreadTSD *cTSD = CTP;
123 CtdlThreadNode *node = NULL;
133 if ((node != NULL) && (node->reltid != 0)) {
134 lwpid = node->reltid;
137 gettimeofday(&tv, NULL);
139 /* Promote to time_t; types differ on some OSes (like darwin) */
140 unixtime = tv.tv_sec;
141 localtime_r(&unixtime, &tim);
145 snprintf(LWP, 64, "[LWP:%ld] ", lwpid);
150 if (CCC->cs_pid != 0) {
151 snprintf(SESS, 64, " [%3d] ", CCC->cs_pid);
153 else if (CCC->user.usernum != 0) {
154 snprintf(SESS, 64, " [:%ld] ", CCC->user.usernum);
158 snprintf(formatbuf, SIZ,
159 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s%s%s",
160 tim.tm_year + 1900, tim.tm_mon + 1,
161 tim.tm_mday, tim.tm_hour, tim.tm_min,
162 tim.tm_sec, (long)tv.tv_usec,
166 vfprintf(stderr, formatbuf, arg_ptr);
174 * Signal handler to shut down the server.
177 volatile int exit_signal = 0;
178 volatile int shutdown_and_halt = 0;
179 volatile int restart_server = 0;
180 volatile int running_as_daemon = 0;
182 static RETSIGTYPE signal_cleanup(int signum) {
187 Cc->self->signal = signum;
190 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
191 exit_signal = signum;
195 static RETSIGTYPE signal_exit(int signum) {
202 * Some initialization stuff...
204 void init_sysdep(void) {
207 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
211 getrlimit(RLIMIT_NOFILE, &rl);
212 rl.rlim_cur = FD_SETSIZE;
213 rl.rlim_max = FD_SETSIZE;
214 setrlimit(RLIMIT_NOFILE, &rl);
218 /* If we've got OpenSSL, we're going to use it. */
224 * Set up a place to put thread-specific data.
225 * We only need a single pointer per thread - it points to the
226 * CitContext structure (in the ContextList linked list) of the
227 * session to which the calling thread is currently bound.
229 if (citthread_key_create(&MyConKey, NULL) != 0) {
230 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
235 * The action for unexpected signals and exceptions should be to
236 * call signal_cleanup() to gracefully shut down the server.
239 sigaddset(&set, SIGINT); // intr = shutdown
240 // sigaddset(&set, SIGQUIT); // quit = force quit
241 sigaddset(&set, SIGHUP);
242 sigaddset(&set, SIGTERM);
243 // sigaddset(&set, SIGSEGV); // we want core dumps
244 // sigaddset(&set, SIGILL); // we want core dumps
245 // sigaddset(&set, SIGBUS);
246 sigprocmask(SIG_UNBLOCK, &set, NULL);
248 signal(SIGINT, signal_cleanup); // intr = shutdown
249 // signal(SIGQUIT, signal_cleanup); // quit = force quit
250 signal(SIGHUP, signal_cleanup);
251 signal(SIGTERM, signal_cleanup);
252 signal(SIGUSR2, signal_exit);
253 // signal(SIGSEGV, signal_cleanup); // we want coredumps
254 // signal(SIGILL, signal_cleanup); // we want core dumps
255 // signal(SIGBUS, signal_cleanup);
258 * Do not shut down the server on broken pipe signals, otherwise the
259 * whole Citadel service would come down whenever a single client
262 signal(SIGPIPE, SIG_IGN);
267 * This is a generic function to set up a master socket for listening on
268 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
270 * ip_addr IP address to bind
271 * port_number port number to bind
272 * queue_len number of incoming connections to allow in the queue
274 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
277 struct sockaddr_in6 sin6;
278 struct sockaddr_in sin4;
282 memset(&sin6, 0, sizeof(sin6));
283 memset(&sin4, 0, sizeof(sin4));
284 sin6.sin6_family = AF_INET6;
285 sin4.sin_family = AF_INET;
287 if ( (ip_addr == NULL) /* any IPv6 */
288 || (IsEmptyStr(ip_addr))
289 || (!strcmp(ip_addr, "*"))
292 sin6.sin6_addr = in6addr_any;
294 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
297 sin4.sin_addr.s_addr = INADDR_ANY;
299 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
302 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
303 snprintf(errormessage, SIZ,
304 "Error binding to [%s] : %s", ip_addr, strerror(errno)
306 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
310 else /* specific IPv6 */
313 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
314 snprintf(errormessage, SIZ,
315 "Error binding to [%s] : %s", ip_addr, strerror(errno)
317 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
322 if (port_number == 0) {
323 snprintf(errormessage, SIZ,
324 "Can't start: no port number specified."
326 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
329 sin6.sin6_port = htons((u_short) port_number);
330 sin4.sin_port = htons((u_short) port_number);
332 p = getprotobyname("tcp");
334 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
336 snprintf(errormessage, SIZ,
337 "Can't create a listening socket: %s", strerror(errno)
339 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
342 /* Set some socket options that make sense. */
344 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
346 if (ip_version == 6) {
347 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
350 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
354 snprintf(errormessage, SIZ,
355 "Can't bind: %s", strerror(errno)
357 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
361 fcntl(s, F_SETFL, O_NONBLOCK);
363 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
364 snprintf(errormessage, SIZ,
365 "Can't listen: %s", strerror(errno)
367 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
378 * Create a Unix domain socket and listen on it
380 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
382 struct sockaddr_un addr;
385 int actual_queue_len;
386 #ifdef HAVE_STRUCT_UCRED
390 actual_queue_len = queue_len;
391 if (actual_queue_len < 5) actual_queue_len = 5;
393 i = unlink(sockpath);
394 if ((i != 0) && (errno != ENOENT)) {
395 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
396 sockpath, strerror(errno)
398 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
402 memset(&addr, 0, sizeof(addr));
403 addr.sun_family = AF_UNIX;
404 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
406 s = socket(AF_UNIX, SOCK_STREAM, 0);
408 snprintf(errormessage, SIZ,
409 "citserver: Can't create a socket: %s",
411 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
415 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
416 snprintf(errormessage, SIZ,
417 "citserver: Can't bind: %s",
419 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
423 /* set to nonblock - we need this for some obscure situations */
424 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
425 snprintf(errormessage, SIZ,
426 "citserver: Can't set socket to non-blocking: %s",
428 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
433 if (listen(s, actual_queue_len) < 0) {
434 snprintf(errormessage, SIZ,
435 "citserver: Can't listen: %s",
437 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
441 #ifdef HAVE_STRUCT_UCRED
442 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
445 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
452 * The following functions implement output buffering on operating systems which
453 * support it (such as Linux and various BSD flavors).
457 # define HAVE_TCP_BUFFERING
460 # define HAVE_TCP_BUFFERING
461 # define TCP_CORK TCP_NOPUSH
463 #endif /* TCP_CORK */
464 #endif /* HAVE_DARWIN */
466 static unsigned on = 1, off = 0;
468 void buffer_output(void) {
469 #ifdef HAVE_TCP_BUFFERING
471 if (!CC->redirect_ssl)
473 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
477 void unbuffer_output(void) {
478 #ifdef HAVE_TCP_BUFFERING
480 if (!CC->redirect_ssl)
482 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
486 void flush_output(void) {
487 #ifdef HAVE_TCP_BUFFERING
488 struct CitContext *CCC = CC;
489 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
490 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
495 static void flush_client_inbuf(void)
499 FlushStrBuf(CCC->ReadBuf);
500 CCC->RecvBuf->ReadWritePointer = NULL;
506 * client_write() ... Send binary data to the client.
508 int client_write(const char *buf, int nbytes)
510 int bytes_written = 0;
512 #ifndef HAVE_TCP_BUFFERING
513 int old_buffer_len = 0;
519 if (nbytes < 1) return(0);
529 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
531 fd = fopen(fn, "a+");
534 fprintf(fd, "Sending: BufSize: %d BufContent: [",
536 rv = fwrite(buf, nbytes, 1, fd);
542 // flush_client_inbuf();
543 if (Ctx->redirect_buffer != NULL) {
544 StrBufAppendBufPlain(Ctx->redirect_buffer,
550 if (Ctx->redirect_ssl) {
551 client_write_ssl(buf, nbytes);
555 if (Ctx->client_socket == -1) return -1;
557 fdflags = fcntl(Ctx->client_socket, F_GETFL);
559 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
560 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
562 FD_SET(Ctx->client_socket, &wset);
563 if (select(1, NULL, &wset, NULL, NULL) == -1) {
566 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
567 if (CtdlThreadCheckStop()) {
571 /* can't trust fd's and stuff so we need to re-create them */
575 CtdlLogPrintf(CTDL_ERR,
576 "client_write(%d bytes) select failed: %s (%d)\n",
577 nbytes - bytes_written,
578 strerror(errno), errno);
586 retval = write(Ctx->client_socket, &buf[bytes_written],
587 nbytes - bytes_written);
589 CtdlLogPrintf(CTDL_ERR,
590 "client_write(%d bytes) failed: %s (%d)\n",
591 nbytes - bytes_written,
592 strerror(errno), errno);
594 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
598 bytes_written = bytes_written + retval;
603 void cputbuf(const StrBuf *Buf) {
604 client_write(ChrPtr(Buf), StrLength(Buf));
609 * cprintf() Send formatted printable data to the client.
610 * Implemented in terms of client_write() so it's technically not sysdep...
612 void cprintf(const char *format, ...) {
616 va_start(arg_ptr, format);
617 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
618 buf[sizeof buf - 2] = '\n';
619 client_write(buf, strlen(buf));
625 * Read data from the client socket.
627 * sock socket fd to read from
628 * buf buffer to read into
629 * bytes number of bytes to read
630 * timeout Number of seconds to wait before timing out
632 * Possible return values:
633 * 1 Requested number of bytes has been read.
634 * 0 Request timed out.
635 * -1 Connection is broken, or other error.
637 int client_read_blob(StrBuf *Target, int bytes, int timeout)
644 if (CCC->redirect_ssl) {
650 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
652 fd = fopen(fn, "a+");
653 fprintf(fd, "Reading BLOB: BufSize: %d ",
655 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
661 retval = client_read_sslblob(Target, bytes, timeout);
663 CtdlLogPrintf(CTDL_CRIT,
668 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
670 fd = fopen(fn, "a+");
671 fprintf(fd, "Read: %d BufContent: [",
673 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
688 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
690 fd = fopen(fn, "a+");
691 fprintf(fd, "Reading BLOB: BufSize: %d ",
693 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
699 retval = StrBufReadBLOBBuffered(Target,
701 &CCC->RecvBuf.ReadWritePointer,
708 CtdlLogPrintf(CTDL_CRIT,
715 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
717 fd = fopen(fn, "a+");
718 fprintf(fd, "Read: %d BufContent: [",
720 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
732 * to make client_read_random_blob() more efficient, increase buffer size.
733 * just use in greeting function, else your buffer may be flushed
735 void client_set_inbound_buf(long N)
738 FlushStrBuf(CCC->RecvBuf.Buf);
739 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
742 int client_read_random_blob(StrBuf *Target, int timeout)
747 rc = client_read_blob(Target, 1, timeout);
753 len = StrLength(CCC->RecvBuf.Buf);
754 pch = ChrPtr(CCC->RecvBuf.Buf);
758 if (CCC->RecvBuf.ReadWritePointer != NULL) {
759 len -= CCC->RecvBuf.ReadWritePointer - pch;
760 pch = CCC->RecvBuf.ReadWritePointer;
762 StrBufAppendBufPlain(Target, pch, len, 0);
763 FlushStrBuf(CCC->RecvBuf.Buf);
764 CCC->RecvBuf.ReadWritePointer = NULL;
771 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
773 fd = fopen(fn, "a+");
774 fprintf(fd, "Read: BufSize: %d BufContent: [",
776 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
784 return StrLength(Target);
792 int client_read_to(char *buf, int bytes, int timeout)
797 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
806 ChrPtr(CCC->MigrateBuf),
807 StrLength(CCC->MigrateBuf) + 1);
808 FlushStrBuf(CCC->MigrateBuf);
814 int HaveMoreLinesWaiting(CitContext *CCC)
816 if ((CCC->kill_me == 1) || (
817 (CCC->RecvBuf.ReadWritePointer == NULL) &&
818 (StrLength(CCC->RecvBuf.Buf) == 0) &&
819 (CCC->client_socket != -1)) )
827 * Read data from the client socket with default timeout.
828 * (This is implemented in terms of client_read_to() and could be
829 * justifiably moved out of sysdep.c)
831 INLINE int client_read(char *buf, int bytes)
833 return(client_read_to(buf, bytes, config.c_sleeping));
836 int CtdlClientGetLine(StrBuf *Target)
844 if (CCC->redirect_ssl) {
854 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
856 fd = fopen(fn, "a+");
857 pch = ChrPtr(CCC->RecvBuf.Buf);
858 len = StrLength(CCC->RecvBuf.Buf);
859 if (CCC->RecvBuf.ReadWritePointer != NULL)
860 rlen = CCC->RecvBuf.ReadWritePointer - pch;
864 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
867 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
870 rc = client_readline_sslbuffer(Target,
872 &CCC->RecvBuf.ReadWritePointer,
875 pch = ChrPtr(CCC->RecvBuf.Buf);
876 nlen = StrLength(CCC->RecvBuf.Buf);
877 if (CCC->RecvBuf.ReadWritePointer != NULL)
878 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
882 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
883 len, nlen, rlen, nrlen, pch);
885 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
886 len, nlen, rlen, nrlen);
888 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
889 StrLength(Target), ChrPtr(Target));
893 CtdlLogPrintf(CTDL_CRIT,
905 int len, rlen, nlen, nrlen;
908 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
910 fd = fopen(fn, "a+");
911 pch = ChrPtr(CCC->RecvBuf.Buf);
912 len = StrLength(CCC->RecvBuf.Buf);
913 if (CCC->RecvBuf.ReadWritePointer != NULL)
914 rlen = CCC->RecvBuf.ReadWritePointer - pch;
918 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
921 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
924 rc = StrBufTCP_read_buffered_line_fast(Target,
926 &CCC->RecvBuf.ReadWritePointer,
933 pch = ChrPtr(CCC->RecvBuf.Buf);
934 nlen = StrLength(CCC->RecvBuf.Buf);
935 if (CCC->RecvBuf.ReadWritePointer != NULL)
936 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
940 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
941 len, nlen, rlen, nrlen, pch);
943 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
944 len, nlen, rlen, nrlen);
946 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
947 StrLength(Target), ChrPtr(Target));
950 if ((rc < 0) && (Error != NULL))
951 CtdlLogPrintf(CTDL_CRIT,
962 * client_getln() ... Get a LF-terminated line of text from the client.
963 * (This is implemented in terms of client_read() and could be
964 * justifiably moved out of sysdep.c)
966 int client_getln(char *buf, int bufsize)
972 retval = CtdlClientGetLine(CCC->MigrateBuf);
977 i = StrLength(CCC->MigrateBuf);
978 pCh = ChrPtr(CCC->MigrateBuf);
979 /* Strip the trailing LF, and the trailing CR if present.
984 && ( (pCh[i - 1]==13)
985 || ( pCh[i - 1]==10)) ) {
991 FlushStrBuf(CCC->MigrateBuf);
993 safestrncpy(&buf[i], "000", bufsize - i);
1000 * Cleanup any contexts that are left lying around
1004 void close_masters (void)
1006 struct ServiceFunctionHook *serviceptr;
1009 * close all protocol master sockets
1011 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1012 serviceptr = serviceptr->next ) {
1014 if (serviceptr->tcp_port > 0)
1016 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
1017 serviceptr->tcp_port);
1018 serviceptr->tcp_port = 0;
1021 if (serviceptr->sockpath != NULL)
1022 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
1023 serviceptr->sockpath);
1025 close(serviceptr->msock);
1026 /* If it's a Unix domain socket, remove the file. */
1027 if (serviceptr->sockpath != NULL) {
1028 unlink(serviceptr->sockpath);
1029 serviceptr->sockpath = NULL;
1036 * The system-dependent part of master_cleanup() - close the master socket.
1038 void sysdep_master_cleanup(void) {
1047 CtdlDestroyProtoHooks();
1048 CtdlDestroyDeleteHooks();
1049 CtdlDestroyXmsgHooks();
1050 CtdlDestroyNetprocHooks();
1051 CtdlDestroyUserHooks();
1052 CtdlDestroyMessageHook();
1053 CtdlDestroyCleanupHooks();
1054 CtdlDestroyFixedOutputHooks();
1055 CtdlDestroySessionHooks();
1056 CtdlDestroyServiceHook();
1057 CtdlDestroyRoomHooks();
1058 CtdlDestroySearchHooks();
1059 #ifdef HAVE_BACKTRACE
1060 /// eCrash_Uninit();
1066 pid_t current_child;
1067 void graceful_shutdown(int signum) {
1068 kill(current_child, signum);
1069 unlink(file_pid_file);
1074 int nFireUpsNonRestart = 0;
1075 pid_t ForkedPid = 1;
1078 * Start running as a daemon.
1080 void start_daemon(int unused) {
1088 /* Close stdin/stdout/stderr and replace them with /dev/null.
1089 * We don't just call close() because we don't want these fd's
1090 * to be reused for other files.
1092 if (chdir(ctdl_run_dir) != 0)
1093 CtdlLogPrintf(CTDL_EMERG,
1094 "unable to change into directory [%s]: %s",
1095 ctdl_run_dir, strerror(errno));
1102 signal(SIGHUP, SIG_IGN);
1103 signal(SIGINT, SIG_IGN);
1104 signal(SIGQUIT, SIG_IGN);
1108 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1109 (freopen("/dev/null", "w", stdout) != stdout) ||
1110 (freopen("/dev/null", "w", stderr) != stderr))
1111 CtdlLogPrintf(CTDL_EMERG,
1112 "unable to reopen stdin/out/err %s",
1117 current_child = fork();
1119 signal(SIGTERM, graceful_shutdown);
1121 if (current_child < 0) {
1126 else if (current_child == 0) {
1127 return; /* continue starting citadel. */
1131 fp = fopen(file_pid_file, "w");
1133 fprintf(fp, ""F_PID_T"\n", getpid());
1136 waitpid(current_child, &status, 0);
1139 nFireUpsNonRestart = nFireUps;
1141 /* Exit code 0 means the watcher should exit */
1142 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1146 /* Exit code 101-109 means the watcher should exit */
1147 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1151 /* Any other exit code, or no exit code, means we should restart. */
1155 ForkedPid = current_child;
1158 } while (do_restart);
1160 unlink(file_pid_file);
1161 exit(WEXITSTATUS(status));
1166 void checkcrash(void)
1168 if (nFireUpsNonRestart != nFireUps)
1172 CrashMail = NewStrBuf();
1173 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1174 StrBufPrintf(CrashMail,
1176 " The Citadel server process (citserver) terminated unexpectedly."
1178 " This could be the result of a bug in the server program, or some external "
1180 " You can obtain more information about this by enabling core dumps.\n \n"
1181 " For more information, please see:\n \n"
1182 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1185 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1187 ctdl_run_dir, ForkedPid);
1188 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1189 FreeStrBuf(&CrashMail);
1195 * Generic routine to convert a login name to a full name (gecos)
1196 * Returns nonzero if a conversion took place
1198 int convert_login(char NameToConvert[]) {
1202 pw = getpwnam(NameToConvert);
1207 strcpy(NameToConvert, pw->pw_gecos);
1208 for (a=0; a<strlen(NameToConvert); ++a) {
1209 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1218 * This loop just keeps going and going and going...
1222 * This current implimentation of worker_thread creates a bottle neck in several situations
1223 * The first thing to remember is that a single thread can handle more than one connection at a time.
1224 * More threads mean less memory for the system to run in.
1225 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1226 * something to happen anywhere.
1227 * This current implimentation requires worker threads to wait in other locations, after it has
1228 * been committed to a single connection which is very wasteful.
1229 * As an extreme case consider this:
1230 * A slow client connects and this slow client sends only one character each second.
1231 * With this current implimentation a single worker thread is dispatched to handle that connection
1232 * until such times as the client timeout expires, an error occurs on the socket or the client
1233 * completes its transmission.
1234 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1235 * second interval between chars.
1237 * It is my intention to re-write this code and the associated client_getln, client_read functions
1238 * to allow any thread to read data on behalf of any connection (context).
1239 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1240 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1242 * This worker thread loop also needs to be able to handle binary data.
1245 void *worker_thread(void *arg) {
1248 CitContext *bind_me = NULL;
1252 int force_purge = 0;
1255 while (!CtdlThreadCheckStop()) {
1257 /* make doubly sure we're not holding any stale db handles
1258 * which might cause a deadlock.
1260 cdb_check_handles();
1261 do_select: force_purge = 0;
1262 bind_me = NULL; /* Which session shall we handle? */
1264 /* Initialize the fdset. */
1268 begin_critical_section(S_SESSION_TABLE);
1269 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1271 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1273 client_socket = ptr->client_socket;
1274 /* Dont select on dead sessions only truly idle ones */
1275 if ((ptr->state == CON_IDLE) &&
1276 (CC->kill_me == 0) &&
1277 (client_socket > 0))
1279 FD_SET(client_socket, &readfds);
1280 if (client_socket > highest)
1281 highest = client_socket;
1283 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1285 ptr->state = CON_EXECUTING;
1288 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1290 ptr->state = CON_STARTING;
1294 end_critical_section(S_SESSION_TABLE);
1300 /* If we got this far, it means that there are no sessions
1301 * which a previous thread marked for attention, so we go
1302 * ahead and get ready to select().
1305 if (!CtdlThreadCheckStop()) {
1306 tv.tv_sec = 1; /* wake up every second if no input */
1308 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1313 /* Now figure out who made this select() unblock.
1314 * First, check for an error or exit condition.
1317 if (errno == EBADF) {
1318 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1322 if (errno != EINTR) {
1323 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1324 CtdlThreadStopAll();
1327 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1328 if (CtdlThreadCheckStop()) return(NULL);
1332 else if(retval == 0) {
1333 if (CtdlThreadCheckStop()) return(NULL);
1336 /* It must be a client socket. Find a context that has data
1337 * waiting on its socket *and* is in the CON_IDLE state. Any
1338 * active sockets other than our chosen one are marked as
1339 * CON_READY so the next thread that comes around can just bind
1340 * to one without having to select() again.
1342 begin_critical_section(S_SESSION_TABLE);
1343 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1344 int checkfd = ptr->client_socket;
1345 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1346 if (FD_ISSET(checkfd, &readfds)) {
1347 ptr->input_waiting = 1;
1349 bind_me = ptr; /* I choose you! */
1350 bind_me->state = CON_EXECUTING;
1353 ptr->state = CON_READY;
1355 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1357 bind_me = ptr; /* I choose you! */
1358 bind_me->state = CON_EXECUTING;
1361 ptr->state = CON_READY;
1366 end_critical_section(S_SESSION_TABLE);
1369 /* We're bound to a session */
1370 if (bind_me != NULL) {
1371 become_session(bind_me);
1373 if (bind_me->state == CON_STARTING) {
1374 bind_me->state = CON_EXECUTING;
1375 begin_session(bind_me);
1376 bind_me->h_greeting_function();
1378 /* If the client has sent a command, execute it. */
1379 if (CC->input_waiting) {
1380 CC->h_command_function();
1382 while (HaveMoreLinesWaiting(CC))
1383 CC->h_command_function();
1385 CC->input_waiting = 0;
1388 /* If there are asynchronous messages waiting and the
1389 * client supports it, do those now */
1390 if ((CC->is_async) && (CC->async_waiting)
1391 && (CC->h_async_function != NULL)) {
1392 CC->h_async_function();
1393 CC->async_waiting = 0;
1396 force_purge = CC->kill_me;
1397 become_session(NULL);
1398 bind_me->state = CON_IDLE;
1401 dead_session_purge(force_purge);
1404 /* If control reaches this point, the server is shutting down */
1412 * A function to handle selecting on master sockets.
1413 * In other words it handles new connections.
1416 void *select_on_master (void *arg)
1418 struct ServiceFunctionHook *serviceptr;
1422 int ssock; /* Descriptor for client socket */
1423 CitContext *con= NULL; /* Temporary context pointer */
1427 struct CitContext select_on_master_CC;
1429 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1430 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1432 while (!CtdlThreadCheckStop()) {
1433 /* Initialize the fdset. */
1434 FD_ZERO(&master_fds);
1437 /* First, add the various master sockets to the fdset. */
1438 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1439 serviceptr = serviceptr->next ) {
1440 m = serviceptr->msock;
1441 FD_SET(m, &master_fds);
1447 if (!CtdlThreadCheckStop()) {
1448 tv.tv_sec = 60; /* wake up every second if no input */
1450 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1455 /* Now figure out who made this select() unblock.
1456 * First, check for an error or exit condition.
1459 if (errno == EBADF) {
1460 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1464 if (errno != EINTR) {
1465 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1466 CtdlThreadStopAll();
1468 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1469 if (CtdlThreadCheckStop()) return(NULL);
1473 else if(retval == 0) {
1474 if (CtdlThreadCheckStop()) return(NULL);
1477 /* Next, check to see if it's a new client connecting
1478 * on a master socket.
1480 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1481 serviceptr = serviceptr->next ) {
1483 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1484 ssock = accept(serviceptr->msock, NULL, 0);
1486 CtdlLogPrintf(CTDL_DEBUG,
1487 "New client socket %d\n",
1490 /* The master socket is non-blocking but the client
1491 * sockets need to be blocking, otherwise certain
1492 * operations barf on FreeBSD. Not a fatal error.
1494 if (fcntl(ssock, F_SETFL, 0) < 0) {
1495 CtdlLogPrintf(CTDL_EMERG,
1496 "citserver: Can't set socket to blocking: %s\n",
1500 /* New context will be created already
1501 * set up in the CON_EXECUTING state.
1503 con = CreateNewContext();
1505 /* Assign our new socket number to it. */
1506 con->client_socket = ssock;
1507 con->h_command_function =
1508 serviceptr->h_command_function;
1509 con->h_async_function =
1510 serviceptr->h_async_function;
1511 con->h_greeting_function = serviceptr->h_greeting_function;
1513 serviceptr->ServiceName;
1515 /* Determine whether it's a local socket */
1516 if (serviceptr->sockpath != NULL)
1517 con->is_local_socket = 1;
1519 /* Set the SO_REUSEADDR socket option */
1521 setsockopt(ssock, SOL_SOCKET,
1525 con->state = CON_GREETING;
1534 CtdlClearSystemContext();
1543 * Translate text facility name to syslog.h defined value.
1545 int SyslogFacility(char *name)
1554 { LOG_KERN, "kern" },
1555 { LOG_USER, "user" },
1556 { LOG_MAIL, "mail" },
1557 { LOG_DAEMON, "daemon" },
1558 { LOG_AUTH, "auth" },
1559 { LOG_SYSLOG, "syslog" },
1561 { LOG_NEWS, "news" },
1562 { LOG_UUCP, "uucp" },
1563 { LOG_LOCAL0, "local0" },
1564 { LOG_LOCAL1, "local1" },
1565 { LOG_LOCAL2, "local2" },
1566 { LOG_LOCAL3, "local3" },
1567 { LOG_LOCAL4, "local4" },
1568 { LOG_LOCAL5, "local5" },
1569 { LOG_LOCAL6, "local6" },
1570 { LOG_LOCAL7, "local7" },
1573 for(i = 0; facTbl[i].name != NULL; i++) {
1574 if(!strcasecmp(name, facTbl[i].name))
1575 return facTbl[i].facility;
1582 /********** MEM CHEQQER ***********/
1584 #ifdef DEBUG_MEMORY_LEAKS
1591 void *tracked_malloc(size_t size, char *file, int line) {
1592 struct igheap *thisheap;
1595 block = malloc(size);
1596 if (block == NULL) return(block);
1598 thisheap = malloc(sizeof(struct igheap));
1599 if (thisheap == NULL) {
1604 thisheap->block = block;
1605 strcpy(thisheap->file, file);
1606 thisheap->line = line;
1608 begin_critical_section(S_DEBUGMEMLEAKS);
1609 thisheap->next = igheap;
1611 end_critical_section(S_DEBUGMEMLEAKS);
1617 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1618 struct igheap *thisheap;
1621 block = realloc(ptr, size);
1622 if (block == NULL) return(block);
1624 thisheap = malloc(sizeof(struct igheap));
1625 if (thisheap == NULL) {
1630 thisheap->block = block;
1631 strcpy(thisheap->file, file);
1632 thisheap->line = line;
1634 begin_critical_section(S_DEBUGMEMLEAKS);
1635 thisheap->next = igheap;
1637 end_critical_section(S_DEBUGMEMLEAKS);
1644 void tracked_free(void *ptr) {
1645 struct igheap *thisheap;
1646 struct igheap *trash;
1650 if (igheap == NULL) return;
1651 begin_critical_section(S_DEBUGMEMLEAKS);
1652 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1653 if (thisheap->next != NULL) {
1654 if (thisheap->next->block == ptr) {
1655 trash = thisheap->next;
1656 thisheap->next = thisheap->next->next;
1661 if (igheap->block == ptr) {
1663 igheap = igheap->next;
1666 end_critical_section(S_DEBUGMEMLEAKS);
1669 char *tracked_strdup(const char *s, char *file, int line) {
1672 if (s == NULL) return(NULL);
1673 ptr = tracked_malloc(strlen(s) + 1, file, line);
1674 if (ptr == NULL) return(NULL);
1675 strncpy(ptr, s, strlen(s));
1679 void dump_heap(void) {
1680 struct igheap *thisheap;
1682 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1683 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1684 thisheap->file, thisheap->line);
1688 #endif /* DEBUG_MEMORY_LEAKS */