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 = MyContext();
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) {
188 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
189 exit_signal = signum;
193 static RETSIGTYPE signal_exit(int signum) {
200 * Some initialization stuff...
202 void init_sysdep(void) {
205 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
209 getrlimit(RLIMIT_NOFILE, &rl);
210 rl.rlim_cur = FD_SETSIZE;
211 rl.rlim_max = FD_SETSIZE;
212 setrlimit(RLIMIT_NOFILE, &rl);
216 /* If we've got OpenSSL, we're going to use it. */
222 * Set up a place to put thread-specific data.
223 * We only need a single pointer per thread - it points to the
224 * CitContext structure (in the ContextList linked list) of the
225 * session to which the calling thread is currently bound.
227 if (citthread_key_create(&MyConKey, NULL) != 0) {
228 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
233 * The action for unexpected signals and exceptions should be to
234 * call signal_cleanup() to gracefully shut down the server.
237 sigaddset(&set, SIGINT); // intr = shutdown
238 // sigaddset(&set, SIGQUIT); // quit = force quit
239 sigaddset(&set, SIGHUP);
240 sigaddset(&set, SIGTERM);
241 // sigaddset(&set, SIGSEGV); // we want core dumps
242 // sigaddset(&set, SIGILL); // we want core dumps
243 // sigaddset(&set, SIGBUS);
244 sigprocmask(SIG_UNBLOCK, &set, NULL);
246 signal(SIGINT, signal_cleanup); // intr = shutdown
247 // signal(SIGQUIT, signal_cleanup); // quit = force quit
248 signal(SIGHUP, signal_cleanup);
249 signal(SIGTERM, signal_cleanup);
250 signal(SIGUSR2, signal_exit);
251 // signal(SIGSEGV, signal_cleanup); // we want coredumps
252 // signal(SIGILL, signal_cleanup); // we want core dumps
253 // signal(SIGBUS, signal_cleanup);
256 * Do not shut down the server on broken pipe signals, otherwise the
257 * whole Citadel service would come down whenever a single client
260 signal(SIGPIPE, SIG_IGN);
265 * This is a generic function to set up a master socket for listening on
266 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
268 * ip_addr IP address to bind
269 * port_number port number to bind
270 * queue_len number of incoming connections to allow in the queue
272 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
275 struct sockaddr_in6 sin6;
276 struct sockaddr_in sin4;
280 memset(&sin6, 0, sizeof(sin6));
281 memset(&sin4, 0, sizeof(sin4));
282 sin6.sin6_family = AF_INET6;
283 sin4.sin_family = AF_INET;
285 if ( (ip_addr == NULL) /* any IPv6 */
286 || (IsEmptyStr(ip_addr))
287 || (!strcmp(ip_addr, "*"))
290 sin6.sin6_addr = in6addr_any;
292 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
295 sin4.sin_addr.s_addr = INADDR_ANY;
297 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
300 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
301 snprintf(errormessage, SIZ,
302 "Error binding to [%s] : %s", ip_addr, strerror(errno)
304 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
308 else /* specific IPv6 */
311 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
312 snprintf(errormessage, SIZ,
313 "Error binding to [%s] : %s", ip_addr, strerror(errno)
315 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
320 if (port_number == 0) {
321 snprintf(errormessage, SIZ,
322 "Can't start: no port number specified."
324 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
327 sin6.sin6_port = htons((u_short) port_number);
328 sin4.sin_port = htons((u_short) port_number);
330 p = getprotobyname("tcp");
332 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
334 snprintf(errormessage, SIZ,
335 "Can't create a listening socket: %s", strerror(errno)
337 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
340 /* Set some socket options that make sense. */
342 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
344 if (ip_version == 6) {
345 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
348 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
352 snprintf(errormessage, SIZ,
353 "Can't bind: %s", strerror(errno)
355 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
359 fcntl(s, F_SETFL, O_NONBLOCK);
361 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
362 snprintf(errormessage, SIZ,
363 "Can't listen: %s", strerror(errno)
365 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
376 * Create a Unix domain socket and listen on it
378 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
380 struct sockaddr_un addr;
383 int actual_queue_len;
384 #ifdef HAVE_STRUCT_UCRED
388 actual_queue_len = queue_len;
389 if (actual_queue_len < 5) actual_queue_len = 5;
391 i = unlink(sockpath);
392 if ((i != 0) && (errno != ENOENT)) {
393 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
394 sockpath, strerror(errno)
396 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
400 memset(&addr, 0, sizeof(addr));
401 addr.sun_family = AF_UNIX;
402 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
404 s = socket(AF_UNIX, SOCK_STREAM, 0);
406 snprintf(errormessage, SIZ,
407 "citserver: Can't create a socket: %s",
409 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
413 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
414 snprintf(errormessage, SIZ,
415 "citserver: Can't bind: %s",
417 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
421 /* set to nonblock - we need this for some obscure situations */
422 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
423 snprintf(errormessage, SIZ,
424 "citserver: Can't set socket to non-blocking: %s",
426 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
431 if (listen(s, actual_queue_len) < 0) {
432 snprintf(errormessage, SIZ,
433 "citserver: Can't listen: %s",
435 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
439 #ifdef HAVE_STRUCT_UCRED
440 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
443 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
450 * The following functions implement output buffering on operating systems which
451 * support it (such as Linux and various BSD flavors).
455 # define HAVE_TCP_BUFFERING
458 # define HAVE_TCP_BUFFERING
459 # define TCP_CORK TCP_NOPUSH
461 #endif /* TCP_CORK */
462 #endif /* HAVE_DARWIN */
464 static unsigned on = 1, off = 0;
466 void buffer_output(void) {
467 #ifdef HAVE_TCP_BUFFERING
469 if (!CC->redirect_ssl)
471 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
475 void unbuffer_output(void) {
476 #ifdef HAVE_TCP_BUFFERING
478 if (!CC->redirect_ssl)
480 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
484 void flush_output(void) {
485 #ifdef HAVE_TCP_BUFFERING
486 struct CitContext *CCC = CC;
487 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
488 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
493 static void flush_client_inbuf(void)
497 FlushStrBuf(CCC->ReadBuf);
504 * client_write() ... Send binary data to the client.
506 int client_write(const char *buf, int nbytes)
508 int bytes_written = 0;
510 #ifndef HAVE_TCP_BUFFERING
511 int old_buffer_len = 0;
517 if (nbytes < 1) return(0);
527 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
529 fd = fopen(fn, "a+");
530 fprintf(fd, "Sending: BufSize: %d BufContent: [",
532 rv = fwrite(buf, nbytes, 1, fd);
539 // flush_client_inbuf();
540 if (Ctx->redirect_buffer != NULL) {
541 StrBufAppendBufPlain(Ctx->redirect_buffer,
547 if (Ctx->redirect_ssl) {
548 client_write_ssl(buf, nbytes);
552 if (Ctx->client_socket == -1) return -1;
554 fdflags = fcntl(Ctx->client_socket, F_GETFL);
556 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
557 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
559 FD_SET(Ctx->client_socket, &wset);
560 if (select(1, NULL, &wset, NULL, NULL) == -1) {
563 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
564 if (CtdlThreadCheckStop()) {
568 /* can't trust fd's and stuff so we need to re-create them */
572 CtdlLogPrintf(CTDL_ERR,
573 "client_write(%d bytes) select failed: %s (%d)\n",
574 nbytes - bytes_written,
575 strerror(errno), errno);
583 retval = write(Ctx->client_socket, &buf[bytes_written],
584 nbytes - bytes_written);
586 CtdlLogPrintf(CTDL_ERR,
587 "client_write(%d bytes) failed: %s (%d)\n",
588 nbytes - bytes_written,
589 strerror(errno), errno);
591 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
595 bytes_written = bytes_written + retval;
600 void cputbuf(const StrBuf *Buf) {
601 client_write(ChrPtr(Buf), StrLength(Buf));
606 * cprintf() Send formatted printable data to the client.
607 * Implemented in terms of client_write() so it's technically not sysdep...
609 void cprintf(const char *format, ...) {
613 va_start(arg_ptr, format);
614 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
615 buf[sizeof buf - 2] = '\n';
616 client_write(buf, strlen(buf));
622 * Read data from the client socket.
624 * sock socket fd to read from
625 * buf buffer to read into
626 * bytes number of bytes to read
627 * timeout Number of seconds to wait before timing out
629 * Possible return values:
630 * 1 Requested number of bytes has been read.
631 * 0 Request timed out.
632 * -1 Connection is broken, or other error.
634 int client_read_blob(StrBuf *Target, int bytes, int timeout)
641 if (CCC->redirect_ssl) {
647 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
649 fd = fopen(fn, "a+");
650 fprintf(fd, "Reading BLOB: BufSize: %d ",
652 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
658 retval = client_read_sslblob(Target, bytes, timeout);
660 CtdlLogPrintf(CTDL_CRIT,
665 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
667 fd = fopen(fn, "a+");
668 fprintf(fd, "Read: %d BufContent: [",
670 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
685 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
687 fd = fopen(fn, "a+");
688 fprintf(fd, "Reading BLOB: BufSize: %d ",
690 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
696 retval = StrBufReadBLOBBuffered(Target,
705 CtdlLogPrintf(CTDL_CRIT,
712 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
714 fd = fopen(fn, "a+");
715 fprintf(fd, "Read: %d BufContent: [",
717 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
729 * to make client_read_random_blob() more efficient, increase buffer size.
730 * just use in greeting function, else your buffer may be flushed
732 void client_set_inbound_buf(long N)
734 FlushStrBuf(CC->ReadBuf);
735 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
738 int client_read_random_blob(StrBuf *Target, int timeout)
743 rc = client_read_blob(Target, 1, timeout);
749 len = StrLength(CCC->ReadBuf);
750 pch = ChrPtr(CCC->ReadBuf);
754 if (CCC->Pos != NULL) {
755 len -= CCC->Pos - pch;
758 StrBufAppendBufPlain(Target, pch, len, 0);
759 FlushStrBuf(CCC->ReadBuf);
767 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
769 fd = fopen(fn, "a+");
770 fprintf(fd, "Read: BufSize: %d BufContent: [",
772 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
780 return StrLength(Target);
788 int client_read_to(char *buf, int bytes, int timeout)
793 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
802 ChrPtr(CCC->MigrateBuf),
803 StrLength(CCC->MigrateBuf) + 1);
804 FlushStrBuf(CCC->MigrateBuf);
810 int HaveMoreLinesWaiting(CitContext *CCC)
812 if ((CCC->kill_me == 1) || (
813 (CCC->Pos == NULL) &&
814 (StrLength(CCC->ReadBuf) == 0) &&
815 (CCC->client_socket != -1)) )
823 * Read data from the client socket with default timeout.
824 * (This is implemented in terms of client_read_to() and could be
825 * justifiably moved out of sysdep.c)
827 INLINE int client_read(char *buf, int bytes)
829 return(client_read_to(buf, bytes, config.c_sleeping));
832 int CtdlClientGetLine(StrBuf *Target)
840 if (CCC->redirect_ssl) {
850 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
852 fd = fopen(fn, "a+");
853 pch = ChrPtr(CCC->ReadBuf);
854 len = StrLength(CCC->ReadBuf);
855 if (CCC->Pos != NULL)
856 rlen = CC->Pos - pch;
860 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
863 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
866 rc = client_readline_sslbuffer(Target,
871 pch = ChrPtr(CCC->ReadBuf);
872 nlen = StrLength(CCC->ReadBuf);
873 if (CCC->Pos != NULL)
874 nrlen = CC->Pos - pch;
878 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
879 len, nlen, rlen, nrlen, pch);
881 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
882 len, nlen, rlen, nrlen);
884 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
885 StrLength(Target), ChrPtr(Target));
889 CtdlLogPrintf(CTDL_CRIT,
901 int len, rlen, nlen, nrlen;
904 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
906 fd = fopen(fn, "a+");
907 pch = ChrPtr(CCC->ReadBuf);
908 len = StrLength(CCC->ReadBuf);
909 if (CCC->Pos != NULL)
910 rlen = CC->Pos - pch;
914 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
917 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
920 rc = StrBufTCP_read_buffered_line_fast(Target,
929 pch = ChrPtr(CCC->ReadBuf);
930 nlen = StrLength(CCC->ReadBuf);
931 if (CCC->Pos != NULL)
932 nrlen = CC->Pos - pch;
936 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
937 len, nlen, rlen, nrlen, pch);
939 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
940 len, nlen, rlen, nrlen);
942 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
943 StrLength(Target), ChrPtr(Target));
946 if ((rc < 0) && (Error != NULL))
947 CtdlLogPrintf(CTDL_CRIT,
958 * client_getln() ... Get a LF-terminated line of text from the client.
959 * (This is implemented in terms of client_read() and could be
960 * justifiably moved out of sysdep.c)
962 int client_getln(char *buf, int bufsize)
968 retval = CtdlClientGetLine(CCC->MigrateBuf);
973 i = StrLength(CCC->MigrateBuf);
974 pCh = ChrPtr(CCC->MigrateBuf);
975 /* Strip the trailing LF, and the trailing CR if present.
980 && ( (pCh[i - 1]==13)
981 || ( pCh[i - 1]==10)) ) {
987 FlushStrBuf(CCC->MigrateBuf);
989 safestrncpy(&buf[i], "000", bufsize - i);
996 * Cleanup any contexts that are left lying around
1000 void close_masters (void)
1002 struct ServiceFunctionHook *serviceptr;
1005 * close all protocol master sockets
1007 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1008 serviceptr = serviceptr->next ) {
1010 if (serviceptr->tcp_port > 0)
1012 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
1013 serviceptr->tcp_port);
1014 serviceptr->tcp_port = 0;
1017 if (serviceptr->sockpath != NULL)
1018 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
1019 serviceptr->sockpath);
1021 close(serviceptr->msock);
1022 /* If it's a Unix domain socket, remove the file. */
1023 if (serviceptr->sockpath != NULL) {
1024 unlink(serviceptr->sockpath);
1025 serviceptr->sockpath = NULL;
1032 * The system-dependent part of master_cleanup() - close the master socket.
1034 void sysdep_master_cleanup(void) {
1043 CtdlDestroyProtoHooks();
1044 CtdlDestroyDeleteHooks();
1045 CtdlDestroyXmsgHooks();
1046 CtdlDestroyNetprocHooks();
1047 CtdlDestroyUserHooks();
1048 CtdlDestroyMessageHook();
1049 CtdlDestroyCleanupHooks();
1050 CtdlDestroyFixedOutputHooks();
1051 CtdlDestroySessionHooks();
1052 CtdlDestroyServiceHook();
1053 CtdlDestroyRoomHooks();
1054 #ifdef HAVE_BACKTRACE
1055 /// eCrash_Uninit();
1061 pid_t current_child;
1062 void graceful_shutdown(int signum) {
1063 kill(current_child, signum);
1064 unlink(file_pid_file);
1069 int nFireUpsNonRestart = 0;
1070 pid_t ForkedPid = 1;
1073 * Start running as a daemon.
1075 void start_daemon(int unused) {
1083 /* Close stdin/stdout/stderr and replace them with /dev/null.
1084 * We don't just call close() because we don't want these fd's
1085 * to be reused for other files.
1087 if (chdir(ctdl_run_dir) != 0)
1088 CtdlLogPrintf(CTDL_EMERG,
1089 "unable to change into directory [%s]: %s",
1090 ctdl_run_dir, strerror(errno));
1097 signal(SIGHUP, SIG_IGN);
1098 signal(SIGINT, SIG_IGN);
1099 signal(SIGQUIT, SIG_IGN);
1103 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1104 (freopen("/dev/null", "w", stdout) != stdout) ||
1105 (freopen("/dev/null", "w", stderr) != stderr))
1106 CtdlLogPrintf(CTDL_EMERG,
1107 "unable to reopen stdin/out/err %s",
1112 current_child = fork();
1114 signal(SIGTERM, graceful_shutdown);
1116 if (current_child < 0) {
1121 else if (current_child == 0) {
1122 return; /* continue starting citadel. */
1126 fp = fopen(file_pid_file, "w");
1128 fprintf(fp, ""F_PID_T"\n", getpid());
1131 waitpid(current_child, &status, 0);
1134 nFireUpsNonRestart = nFireUps;
1136 /* Exit code 0 means the watcher should exit */
1137 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1141 /* Exit code 101-109 means the watcher should exit */
1142 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1146 /* Any other exit code, or no exit code, means we should restart. */
1150 ForkedPid = current_child;
1153 } while (do_restart);
1155 unlink(file_pid_file);
1156 exit(WEXITSTATUS(status));
1161 void checkcrash(void)
1163 if (nFireUpsNonRestart != nFireUps)
1167 CrashMail = NewStrBuf();
1168 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1169 StrBufPrintf(CrashMail,
1171 " The Citadel server process (citserver) terminated unexpectedly."
1173 " This could be the result of a bug in the server program, or some external "
1175 " You can obtain more information about this by enabling core dumps.\n \n"
1176 " For more information, please see:\n \n"
1177 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1180 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1182 ctdl_run_dir, ForkedPid);
1183 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1184 FreeStrBuf(&CrashMail);
1190 * Generic routine to convert a login name to a full name (gecos)
1191 * Returns nonzero if a conversion took place
1193 int convert_login(char NameToConvert[]) {
1197 pw = getpwnam(NameToConvert);
1202 strcpy(NameToConvert, pw->pw_gecos);
1203 for (a=0; a<strlen(NameToConvert); ++a) {
1204 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1213 * This loop just keeps going and going and going...
1217 * This current implimentation of worker_thread creates a bottle neck in several situations
1218 * The first thing to remember is that a single thread can handle more than one connection at a time.
1219 * More threads mean less memory for the system to run in.
1220 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1221 * something to happen anywhere.
1222 * This current implimentation requires worker threads to wait in other locations, after it has
1223 * been committed to a single connection which is very wasteful.
1224 * As an extreme case consider this:
1225 * A slow client connects and this slow client sends only one character each second.
1226 * With this current implimentation a single worker thread is dispatched to handle that connection
1227 * until such times as the client timeout expires, an error occurs on the socket or the client
1228 * completes its transmission.
1229 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1230 * second interval between chars.
1232 * It is my intention to re-write this code and the associated client_getln, client_read functions
1233 * to allow any thread to read data on behalf of any connection (context).
1234 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1235 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1237 * This worker thread loop also needs to be able to handle binary data.
1240 void *worker_thread(void *arg) {
1243 CitContext *bind_me = NULL;
1247 int force_purge = 0;
1250 while (!CtdlThreadCheckStop()) {
1252 /* make doubly sure we're not holding any stale db handles
1253 * which might cause a deadlock.
1255 cdb_check_handles();
1256 do_select: force_purge = 0;
1257 bind_me = NULL; /* Which session shall we handle? */
1259 /* Initialize the fdset. */
1263 begin_critical_section(S_SESSION_TABLE);
1264 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1266 client_socket = ptr->client_socket;
1267 /* Dont select on dead sessions only truly idle ones */
1268 if ((ptr->state == CON_IDLE) &&
1269 (CC->kill_me == 0) &&
1270 (client_socket != -1))
1272 FD_SET(client_socket, &readfds);
1273 if (client_socket > highest)
1274 highest = client_socket;
1276 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1278 ptr->state = CON_EXECUTING;
1281 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1283 ptr->state = CON_STARTING;
1287 end_critical_section(S_SESSION_TABLE);
1293 /* If we got this far, it means that there are no sessions
1294 * which a previous thread marked for attention, so we go
1295 * ahead and get ready to select().
1298 if (!CtdlThreadCheckStop()) {
1299 tv.tv_sec = 1; /* wake up every second if no input */
1301 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1306 /* Now figure out who made this select() unblock.
1307 * First, check for an error or exit condition.
1310 if (errno == EBADF) {
1311 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1315 if (errno != EINTR) {
1316 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1317 CtdlThreadStopAll();
1320 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1321 if (CtdlThreadCheckStop()) return(NULL);
1325 else if(retval == 0) {
1326 if (CtdlThreadCheckStop()) return(NULL);
1329 /* It must be a client socket. Find a context that has data
1330 * waiting on its socket *and* is in the CON_IDLE state. Any
1331 * active sockets other than our chosen one are marked as
1332 * CON_READY so the next thread that comes around can just bind
1333 * to one without having to select() again.
1335 begin_critical_section(S_SESSION_TABLE);
1336 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1337 int checkfd = ptr->client_socket;
1338 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1339 if (FD_ISSET(checkfd, &readfds)) {
1340 ptr->input_waiting = 1;
1342 bind_me = ptr; /* I choose you! */
1343 bind_me->state = CON_EXECUTING;
1346 ptr->state = CON_READY;
1348 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1350 bind_me = ptr; /* I choose you! */
1351 bind_me->state = CON_EXECUTING;
1354 ptr->state = CON_READY;
1359 end_critical_section(S_SESSION_TABLE);
1362 /* We're bound to a session */
1363 if (bind_me != NULL) {
1364 become_session(bind_me);
1366 if (bind_me->state == CON_STARTING) {
1367 bind_me->state = CON_EXECUTING;
1368 begin_session(bind_me);
1369 bind_me->h_greeting_function();
1371 /* If the client has sent a command, execute it. */
1372 if (CC->input_waiting) {
1373 CC->h_command_function();
1375 while (HaveMoreLinesWaiting(CC))
1376 CC->h_command_function();
1378 CC->input_waiting = 0;
1381 /* If there are asynchronous messages waiting and the
1382 * client supports it, do those now */
1383 if ((CC->is_async) && (CC->async_waiting)
1384 && (CC->h_async_function != NULL)) {
1385 CC->h_async_function();
1386 CC->async_waiting = 0;
1389 force_purge = CC->kill_me;
1390 become_session(NULL);
1391 bind_me->state = CON_IDLE;
1394 dead_session_purge(force_purge);
1397 /* If control reaches this point, the server is shutting down */
1405 * A function to handle selecting on master sockets.
1406 * In other words it handles new connections.
1409 void *select_on_master (void *arg)
1411 struct ServiceFunctionHook *serviceptr;
1415 int ssock; /* Descriptor for client socket */
1416 CitContext *con= NULL; /* Temporary context pointer */
1420 struct CitContext select_on_master_CC;
1422 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1423 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1425 while (!CtdlThreadCheckStop()) {
1426 /* Initialize the fdset. */
1427 FD_ZERO(&master_fds);
1430 /* First, add the various master sockets to the fdset. */
1431 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1432 serviceptr = serviceptr->next ) {
1433 m = serviceptr->msock;
1434 FD_SET(m, &master_fds);
1440 if (!CtdlThreadCheckStop()) {
1441 tv.tv_sec = 60; /* wake up every second if no input */
1443 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1448 /* Now figure out who made this select() unblock.
1449 * First, check for an error or exit condition.
1452 if (errno == EBADF) {
1453 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1457 if (errno != EINTR) {
1458 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1459 CtdlThreadStopAll();
1461 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1462 if (CtdlThreadCheckStop()) return(NULL);
1466 else if(retval == 0) {
1467 if (CtdlThreadCheckStop()) return(NULL);
1470 /* Next, check to see if it's a new client connecting
1471 * on a master socket.
1473 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1474 serviceptr = serviceptr->next ) {
1476 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1477 ssock = accept(serviceptr->msock, NULL, 0);
1479 CtdlLogPrintf(CTDL_DEBUG,
1480 "New client socket %d\n",
1483 /* The master socket is non-blocking but the client
1484 * sockets need to be blocking, otherwise certain
1485 * operations barf on FreeBSD. Not a fatal error.
1487 if (fcntl(ssock, F_SETFL, 0) < 0) {
1488 CtdlLogPrintf(CTDL_EMERG,
1489 "citserver: Can't set socket to blocking: %s\n",
1493 /* New context will be created already
1494 * set up in the CON_EXECUTING state.
1496 con = CreateNewContext();
1498 /* Assign our new socket number to it. */
1499 con->client_socket = ssock;
1500 con->h_command_function =
1501 serviceptr->h_command_function;
1502 con->h_async_function =
1503 serviceptr->h_async_function;
1504 con->h_greeting_function = serviceptr->h_greeting_function;
1506 serviceptr->ServiceName;
1508 /* Determine whether it's a local socket */
1509 if (serviceptr->sockpath != NULL)
1510 con->is_local_socket = 1;
1512 /* Set the SO_REUSEADDR socket option */
1514 setsockopt(ssock, SOL_SOCKET,
1518 con->state = CON_GREETING;
1527 CtdlClearSystemContext();
1536 * Translate text facility name to syslog.h defined value.
1538 int SyslogFacility(char *name)
1547 { LOG_KERN, "kern" },
1548 { LOG_USER, "user" },
1549 { LOG_MAIL, "mail" },
1550 { LOG_DAEMON, "daemon" },
1551 { LOG_AUTH, "auth" },
1552 { LOG_SYSLOG, "syslog" },
1554 { LOG_NEWS, "news" },
1555 { LOG_UUCP, "uucp" },
1556 { LOG_LOCAL0, "local0" },
1557 { LOG_LOCAL1, "local1" },
1558 { LOG_LOCAL2, "local2" },
1559 { LOG_LOCAL3, "local3" },
1560 { LOG_LOCAL4, "local4" },
1561 { LOG_LOCAL5, "local5" },
1562 { LOG_LOCAL6, "local6" },
1563 { LOG_LOCAL7, "local7" },
1566 for(i = 0; facTbl[i].name != NULL; i++) {
1567 if(!strcasecmp(name, facTbl[i].name))
1568 return facTbl[i].facility;
1575 /********** MEM CHEQQER ***********/
1577 #ifdef DEBUG_MEMORY_LEAKS
1584 void *tracked_malloc(size_t size, char *file, int line) {
1585 struct igheap *thisheap;
1588 block = malloc(size);
1589 if (block == NULL) return(block);
1591 thisheap = malloc(sizeof(struct igheap));
1592 if (thisheap == NULL) {
1597 thisheap->block = block;
1598 strcpy(thisheap->file, file);
1599 thisheap->line = line;
1601 begin_critical_section(S_DEBUGMEMLEAKS);
1602 thisheap->next = igheap;
1604 end_critical_section(S_DEBUGMEMLEAKS);
1610 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1611 struct igheap *thisheap;
1614 block = realloc(ptr, size);
1615 if (block == NULL) return(block);
1617 thisheap = malloc(sizeof(struct igheap));
1618 if (thisheap == NULL) {
1623 thisheap->block = block;
1624 strcpy(thisheap->file, file);
1625 thisheap->line = line;
1627 begin_critical_section(S_DEBUGMEMLEAKS);
1628 thisheap->next = igheap;
1630 end_critical_section(S_DEBUGMEMLEAKS);
1637 void tracked_free(void *ptr) {
1638 struct igheap *thisheap;
1639 struct igheap *trash;
1643 if (igheap == NULL) return;
1644 begin_critical_section(S_DEBUGMEMLEAKS);
1645 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1646 if (thisheap->next != NULL) {
1647 if (thisheap->next->block == ptr) {
1648 trash = thisheap->next;
1649 thisheap->next = thisheap->next->next;
1654 if (igheap->block == ptr) {
1656 igheap = igheap->next;
1659 end_critical_section(S_DEBUGMEMLEAKS);
1662 char *tracked_strdup(const char *s, char *file, int line) {
1665 if (s == NULL) return(NULL);
1666 ptr = tracked_malloc(strlen(s) + 1, file, line);
1667 if (ptr == NULL) return(NULL);
1668 strncpy(ptr, s, strlen(s));
1672 void dump_heap(void) {
1673 struct igheap *thisheap;
1675 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1676 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1677 thisheap->file, thisheap->line);
1681 #endif /* DEBUG_MEMORY_LEAKS */