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;
130 if ((node != NULL) && (node->reltid != 0)) {
131 lwpid = node->reltid;
134 gettimeofday(&tv, NULL);
136 /* Promote to time_t; types differ on some OSes (like darwin) */
137 unixtime = tv.tv_sec;
138 localtime_r(&unixtime, &tim);
141 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
142 tim.tm_year + 1900, tim.tm_mon + 1,
143 tim.tm_mday, tim.tm_hour, tim.tm_min,
144 tim.tm_sec, (long)tv.tv_usec
148 fprintf(stderr, "[LWP:%ld] ", lwpid);
152 if (CCC->cs_pid != 0) {
153 fprintf(stderr, "[%3d] ", CCC->cs_pid);
155 else if (CCC->user.usernum != 0) {
156 fprintf(stderr, "[:%ld] ", CCC->user.usernum);
160 vfprintf(stderr, format, arg_ptr);
168 * Signal handler to shut down the server.
171 volatile int exit_signal = 0;
172 volatile int shutdown_and_halt = 0;
173 volatile int restart_server = 0;
174 volatile int running_as_daemon = 0;
176 static RETSIGTYPE signal_cleanup(int signum) {
182 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
183 exit_signal = signum;
187 static RETSIGTYPE signal_exit(int signum) {
194 * Some initialization stuff...
196 void init_sysdep(void) {
199 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
203 getrlimit(RLIMIT_NOFILE, &rl);
204 rl.rlim_cur = FD_SETSIZE;
205 rl.rlim_max = FD_SETSIZE;
206 setrlimit(RLIMIT_NOFILE, &rl);
210 /* If we've got OpenSSL, we're going to use it. */
216 * Set up a place to put thread-specific data.
217 * We only need a single pointer per thread - it points to the
218 * CitContext structure (in the ContextList linked list) of the
219 * session to which the calling thread is currently bound.
221 if (citthread_key_create(&MyConKey, NULL) != 0) {
222 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
227 * The action for unexpected signals and exceptions should be to
228 * call signal_cleanup() to gracefully shut down the server.
231 sigaddset(&set, SIGINT); // intr = shutdown
232 // sigaddset(&set, SIGQUIT); // quit = force quit
233 sigaddset(&set, SIGHUP);
234 sigaddset(&set, SIGTERM);
235 // sigaddset(&set, SIGSEGV); // we want core dumps
236 // sigaddset(&set, SIGILL); // we want core dumps
237 // sigaddset(&set, SIGBUS);
238 sigprocmask(SIG_UNBLOCK, &set, NULL);
240 signal(SIGINT, signal_cleanup); // intr = shutdown
241 // signal(SIGQUIT, signal_cleanup); // quit = force quit
242 signal(SIGHUP, signal_cleanup);
243 signal(SIGTERM, signal_cleanup);
244 signal(SIGUSR2, signal_exit);
245 // signal(SIGSEGV, signal_cleanup); // we want coredumps
246 // signal(SIGILL, signal_cleanup); // we want core dumps
247 // signal(SIGBUS, signal_cleanup);
250 * Do not shut down the server on broken pipe signals, otherwise the
251 * whole Citadel service would come down whenever a single client
254 signal(SIGPIPE, SIG_IGN);
259 * This is a generic function to set up a master socket for listening on
260 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
262 * ip_addr IP address to bind
263 * port_number port number to bind
264 * queue_len number of incoming connections to allow in the queue
266 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
269 struct sockaddr_in6 sin6;
270 struct sockaddr_in sin4;
274 memset(&sin6, 0, sizeof(sin6));
275 memset(&sin4, 0, sizeof(sin4));
276 sin6.sin6_family = AF_INET6;
277 sin4.sin_family = AF_INET;
279 if ( (ip_addr == NULL) /* any IPv6 */
280 || (IsEmptyStr(ip_addr))
281 || (!strcmp(ip_addr, "*"))
284 sin6.sin6_addr = in6addr_any;
286 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
289 sin4.sin_addr.s_addr = INADDR_ANY;
291 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
294 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
295 snprintf(errormessage, SIZ,
296 "Error binding to [%s] : %s", ip_addr, strerror(errno)
298 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
302 else /* specific IPv6 */
305 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
306 snprintf(errormessage, SIZ,
307 "Error binding to [%s] : %s", ip_addr, strerror(errno)
309 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
314 if (port_number == 0) {
315 snprintf(errormessage, SIZ,
316 "Can't start: no port number specified."
318 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
321 sin6.sin6_port = htons((u_short) port_number);
322 sin4.sin_port = htons((u_short) port_number);
324 p = getprotobyname("tcp");
326 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
328 snprintf(errormessage, SIZ,
329 "Can't create a listening socket: %s", strerror(errno)
331 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
334 /* Set some socket options that make sense. */
336 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
338 if (ip_version == 6) {
339 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
342 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
346 snprintf(errormessage, SIZ,
347 "Can't bind: %s", strerror(errno)
349 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
353 fcntl(s, F_SETFL, O_NONBLOCK);
355 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
356 snprintf(errormessage, SIZ,
357 "Can't listen: %s", strerror(errno)
359 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
370 * Create a Unix domain socket and listen on it
372 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
374 struct sockaddr_un addr;
377 int actual_queue_len;
378 #ifdef HAVE_STRUCT_UCRED
382 actual_queue_len = queue_len;
383 if (actual_queue_len < 5) actual_queue_len = 5;
385 i = unlink(sockpath);
386 if ((i != 0) && (errno != ENOENT)) {
387 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
388 sockpath, strerror(errno)
390 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
394 memset(&addr, 0, sizeof(addr));
395 addr.sun_family = AF_UNIX;
396 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
398 s = socket(AF_UNIX, SOCK_STREAM, 0);
400 snprintf(errormessage, SIZ,
401 "citserver: Can't create a socket: %s",
403 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
407 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
408 snprintf(errormessage, SIZ,
409 "citserver: Can't bind: %s",
411 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
415 /* set to nonblock - we need this for some obscure situations */
416 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
417 snprintf(errormessage, SIZ,
418 "citserver: Can't set socket to non-blocking: %s",
420 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
425 if (listen(s, actual_queue_len) < 0) {
426 snprintf(errormessage, SIZ,
427 "citserver: Can't listen: %s",
429 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
433 #ifdef HAVE_STRUCT_UCRED
434 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
437 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
444 * The following functions implement output buffering on operating systems which
445 * support it (such as Linux and various BSD flavors).
449 # define HAVE_TCP_BUFFERING
452 # define HAVE_TCP_BUFFERING
453 # define TCP_CORK TCP_NOPUSH
455 #endif /* TCP_CORK */
456 #endif /* HAVE_DARWIN */
458 static unsigned on = 1, off = 0;
460 void buffer_output(void) {
461 #ifdef HAVE_TCP_BUFFERING
463 if (!CC->redirect_ssl)
465 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
469 void unbuffer_output(void) {
470 #ifdef HAVE_TCP_BUFFERING
472 if (!CC->redirect_ssl)
474 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
478 void flush_output(void) {
479 #ifdef HAVE_TCP_BUFFERING
480 struct CitContext *CCC = CC;
481 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
482 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
487 static void flush_client_inbuf(void)
491 FlushStrBuf(CCC->ReadBuf);
498 * client_write() ... Send binary data to the client.
500 int client_write(const char *buf, int nbytes)
502 int bytes_written = 0;
504 #ifndef HAVE_TCP_BUFFERING
505 int old_buffer_len = 0;
511 if (nbytes < 1) return(0);
521 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
523 fd = fopen(fn, "a+");
524 fprintf(fd, "Sending: BufSize: %d BufContent: [",
526 rv = fwrite(buf, nbytes, 1, fd);
533 // flush_client_inbuf();
534 if (Ctx->redirect_buffer != NULL) {
535 StrBufAppendBufPlain(Ctx->redirect_buffer,
541 if (Ctx->redirect_ssl) {
542 client_write_ssl(buf, nbytes);
546 if (Ctx->client_socket == -1) return -1;
548 fdflags = fcntl(Ctx->client_socket, F_GETFL);
550 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
551 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
553 FD_SET(Ctx->client_socket, &wset);
554 if (select(1, NULL, &wset, NULL, NULL) == -1) {
557 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
558 if (CtdlThreadCheckStop()) {
562 /* can't trust fd's and stuff so we need to re-create them */
566 CtdlLogPrintf(CTDL_ERR,
567 "client_write(%d bytes) select failed: %s (%d)\n",
568 nbytes - bytes_written,
569 strerror(errno), errno);
577 retval = write(Ctx->client_socket, &buf[bytes_written],
578 nbytes - bytes_written);
580 CtdlLogPrintf(CTDL_ERR,
581 "client_write(%d bytes) failed: %s (%d)\n",
582 nbytes - bytes_written,
583 strerror(errno), errno);
585 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
589 bytes_written = bytes_written + retval;
594 void cputbuf(const StrBuf *Buf) {
595 client_write(ChrPtr(Buf), StrLength(Buf));
600 * cprintf() Send formatted printable data to the client.
601 * Implemented in terms of client_write() so it's technically not sysdep...
603 void cprintf(const char *format, ...) {
607 va_start(arg_ptr, format);
608 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
609 buf[sizeof buf - 2] = '\n';
610 client_write(buf, strlen(buf));
616 * Read data from the client socket.
618 * sock socket fd to read from
619 * buf buffer to read into
620 * bytes number of bytes to read
621 * timeout Number of seconds to wait before timing out
623 * Possible return values:
624 * 1 Requested number of bytes has been read.
625 * 0 Request timed out.
626 * -1 Connection is broken, or other error.
628 int client_read_blob(StrBuf *Target, int bytes, int timeout)
635 if (CCC->redirect_ssl) {
641 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
643 fd = fopen(fn, "a+");
644 fprintf(fd, "Reading BLOB: BufSize: %d ",
646 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
652 retval = client_read_sslblob(Target, bytes, timeout);
654 CtdlLogPrintf(CTDL_CRIT,
659 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
661 fd = fopen(fn, "a+");
662 fprintf(fd, "Read: %d BufContent: [",
664 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
679 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
681 fd = fopen(fn, "a+");
682 fprintf(fd, "Reading BLOB: BufSize: %d ",
684 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
690 retval = StrBufReadBLOBBuffered(Target,
699 CtdlLogPrintf(CTDL_CRIT,
706 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
708 fd = fopen(fn, "a+");
709 fprintf(fd, "Read: %d BufContent: [",
711 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
723 * to make client_read_random_blob() more efficient, increase buffer size.
724 * just use in greeting function, else your buffer may be flushed
726 void client_set_inbound_buf(long N)
728 FlushStrBuf(CC->ReadBuf);
729 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
732 int client_read_random_blob(StrBuf *Target, int timeout)
737 rc = client_read_blob(Target, 1, timeout);
743 len = StrLength(CCC->ReadBuf);
744 pch = ChrPtr(CCC->ReadBuf);
748 if (CCC->Pos != NULL) {
749 len -= CCC->Pos - pch;
752 StrBufAppendBufPlain(Target, pch, len, 0);
753 FlushStrBuf(CCC->ReadBuf);
761 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
763 fd = fopen(fn, "a+");
764 fprintf(fd, "Read: BufSize: %d BufContent: [",
766 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
774 return StrLength(Target);
782 int client_read_to(char *buf, int bytes, int timeout)
787 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
796 ChrPtr(CCC->MigrateBuf),
797 StrLength(CCC->MigrateBuf) + 1);
798 FlushStrBuf(CCC->MigrateBuf);
804 int HaveMoreLinesWaiting(CitContext *CCC)
806 if ((CCC->kill_me == 1) || (
807 (CCC->Pos == NULL) &&
808 (StrLength(CCC->ReadBuf) == 0) &&
809 (CCC->client_socket != -1)) )
817 * Read data from the client socket with default timeout.
818 * (This is implemented in terms of client_read_to() and could be
819 * justifiably moved out of sysdep.c)
821 INLINE int client_read(char *buf, int bytes)
823 return(client_read_to(buf, bytes, config.c_sleeping));
826 int CtdlClientGetLine(StrBuf *Target)
834 if (CCC->redirect_ssl) {
844 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
846 fd = fopen(fn, "a+");
847 pch = ChrPtr(CCC->ReadBuf);
848 len = StrLength(CCC->ReadBuf);
849 if (CCC->Pos != NULL)
850 rlen = CC->Pos - pch;
854 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
857 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
860 rc = client_readline_sslbuffer(Target,
865 pch = ChrPtr(CCC->ReadBuf);
866 nlen = StrLength(CCC->ReadBuf);
867 if (CCC->Pos != NULL)
868 nrlen = CC->Pos - pch;
872 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
873 len, nlen, rlen, nrlen, pch);
875 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
876 len, nlen, rlen, nrlen);
878 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
879 StrLength(Target), ChrPtr(Target));
883 CtdlLogPrintf(CTDL_CRIT,
895 int len, rlen, nlen, nrlen;
898 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
900 fd = fopen(fn, "a+");
901 pch = ChrPtr(CCC->ReadBuf);
902 len = StrLength(CCC->ReadBuf);
903 if (CCC->Pos != NULL)
904 rlen = CC->Pos - pch;
908 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
911 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
914 rc = StrBufTCP_read_buffered_line_fast(Target,
923 pch = ChrPtr(CCC->ReadBuf);
924 nlen = StrLength(CCC->ReadBuf);
925 if (CCC->Pos != NULL)
926 nrlen = CC->Pos - pch;
930 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
931 len, nlen, rlen, nrlen, pch);
933 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
934 len, nlen, rlen, nrlen);
936 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
937 StrLength(Target), ChrPtr(Target));
940 if ((rc < 0) && (Error != NULL))
941 CtdlLogPrintf(CTDL_CRIT,
952 * client_getln() ... Get a LF-terminated line of text from the client.
953 * (This is implemented in terms of client_read() and could be
954 * justifiably moved out of sysdep.c)
956 int client_getln(char *buf, int bufsize)
962 retval = CtdlClientGetLine(CCC->MigrateBuf);
967 i = StrLength(CCC->MigrateBuf);
968 pCh = ChrPtr(CCC->MigrateBuf);
969 /* Strip the trailing LF, and the trailing CR if present.
974 && ( (pCh[i - 1]==13)
975 || ( pCh[i - 1]==10)) ) {
981 FlushStrBuf(CCC->MigrateBuf);
983 safestrncpy(&buf[i], "000", bufsize - i);
990 * Cleanup any contexts that are left lying around
994 void close_masters (void)
996 struct ServiceFunctionHook *serviceptr;
999 * close all protocol master sockets
1001 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1002 serviceptr = serviceptr->next ) {
1004 if (serviceptr->tcp_port > 0)
1006 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
1007 serviceptr->tcp_port);
1008 serviceptr->tcp_port = 0;
1011 if (serviceptr->sockpath != NULL)
1012 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
1013 serviceptr->sockpath);
1015 close(serviceptr->msock);
1016 /* If it's a Unix domain socket, remove the file. */
1017 if (serviceptr->sockpath != NULL) {
1018 unlink(serviceptr->sockpath);
1019 serviceptr->sockpath = NULL;
1026 * The system-dependent part of master_cleanup() - close the master socket.
1028 void sysdep_master_cleanup(void) {
1037 CtdlDestroyProtoHooks();
1038 CtdlDestroyDeleteHooks();
1039 CtdlDestroyXmsgHooks();
1040 CtdlDestroyNetprocHooks();
1041 CtdlDestroyUserHooks();
1042 CtdlDestroyMessageHook();
1043 CtdlDestroyCleanupHooks();
1044 CtdlDestroyFixedOutputHooks();
1045 CtdlDestroySessionHooks();
1046 CtdlDestroyServiceHook();
1047 CtdlDestroyRoomHooks();
1048 #ifdef HAVE_BACKTRACE
1049 /// eCrash_Uninit();
1055 pid_t current_child;
1056 void graceful_shutdown(int signum) {
1057 kill(current_child, signum);
1058 unlink(file_pid_file);
1063 int nFireUpsNonRestart = 0;
1064 pid_t ForkedPid = 1;
1067 * Start running as a daemon.
1069 void start_daemon(int unused) {
1077 /* Close stdin/stdout/stderr and replace them with /dev/null.
1078 * We don't just call close() because we don't want these fd's
1079 * to be reused for other files.
1081 if (chdir(ctdl_run_dir) != 0)
1082 CtdlLogPrintf(CTDL_EMERG,
1083 "unable to change into directory [%s]: %s",
1084 ctdl_run_dir, strerror(errno));
1091 signal(SIGHUP, SIG_IGN);
1092 signal(SIGINT, SIG_IGN);
1093 signal(SIGQUIT, SIG_IGN);
1097 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1098 (freopen("/dev/null", "w", stdout) != stdout) ||
1099 (freopen("/dev/null", "w", stderr) != stderr))
1100 CtdlLogPrintf(CTDL_EMERG,
1101 "unable to reopen stdin/out/err %s",
1106 current_child = fork();
1108 signal(SIGTERM, graceful_shutdown);
1110 if (current_child < 0) {
1115 else if (current_child == 0) {
1116 return; /* continue starting citadel. */
1120 fp = fopen(file_pid_file, "w");
1122 fprintf(fp, ""F_PID_T"\n", getpid());
1125 waitpid(current_child, &status, 0);
1128 nFireUpsNonRestart = nFireUps;
1130 /* Exit code 0 means the watcher should exit */
1131 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1135 /* Exit code 101-109 means the watcher should exit */
1136 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1140 /* Any other exit code, or no exit code, means we should restart. */
1144 ForkedPid = current_child;
1147 } while (do_restart);
1149 unlink(file_pid_file);
1150 exit(WEXITSTATUS(status));
1155 void checkcrash(void)
1157 if (nFireUpsNonRestart != nFireUps)
1161 CrashMail = NewStrBuf();
1162 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1163 StrBufPrintf(CrashMail,
1165 " The Citadel server process (citserver) terminated unexpectedly."
1167 " This could be the result of a bug in the server program, or some external "
1169 " You can obtain more information about this by enabling core dumps.\n \n"
1170 " For more information, please see:\n \n"
1171 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1174 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1176 ctdl_run_dir, ForkedPid);
1177 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1178 FreeStrBuf(&CrashMail);
1184 * Generic routine to convert a login name to a full name (gecos)
1185 * Returns nonzero if a conversion took place
1187 int convert_login(char NameToConvert[]) {
1191 pw = getpwnam(NameToConvert);
1196 strcpy(NameToConvert, pw->pw_gecos);
1197 for (a=0; a<strlen(NameToConvert); ++a) {
1198 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1207 * This loop just keeps going and going and going...
1211 * This current implimentation of worker_thread creates a bottle neck in several situations
1212 * The first thing to remember is that a single thread can handle more than one connection at a time.
1213 * More threads mean less memory for the system to run in.
1214 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1215 * something to happen anywhere.
1216 * This current implimentation requires worker threads to wait in other locations, after it has
1217 * been committed to a single connection which is very wasteful.
1218 * As an extreme case consider this:
1219 * A slow client connects and this slow client sends only one character each second.
1220 * With this current implimentation a single worker thread is dispatched to handle that connection
1221 * until such times as the client timeout expires, an error occurs on the socket or the client
1222 * completes its transmission.
1223 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1224 * second interval between chars.
1226 * It is my intention to re-write this code and the associated client_getln, client_read functions
1227 * to allow any thread to read data on behalf of any connection (context).
1228 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1229 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1231 * This worker thread loop also needs to be able to handle binary data.
1234 void *worker_thread(void *arg) {
1237 CitContext *bind_me = NULL;
1241 int force_purge = 0;
1244 while (!CtdlThreadCheckStop()) {
1246 /* make doubly sure we're not holding any stale db handles
1247 * which might cause a deadlock.
1249 cdb_check_handles();
1250 do_select: force_purge = 0;
1251 bind_me = NULL; /* Which session shall we handle? */
1253 /* Initialize the fdset. */
1257 begin_critical_section(S_SESSION_TABLE);
1258 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1260 client_socket = ptr->client_socket;
1261 /* Dont select on dead sessions only truly idle ones */
1262 if ((ptr->state == CON_IDLE) &&
1263 (CC->kill_me == 0) &&
1264 (client_socket != -1))
1266 FD_SET(client_socket, &readfds);
1267 if (client_socket > highest)
1268 highest = client_socket;
1270 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1272 ptr->state = CON_EXECUTING;
1275 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1277 ptr->state = CON_STARTING;
1281 end_critical_section(S_SESSION_TABLE);
1287 /* If we got this far, it means that there are no sessions
1288 * which a previous thread marked for attention, so we go
1289 * ahead and get ready to select().
1292 if (!CtdlThreadCheckStop()) {
1293 tv.tv_sec = 1; /* wake up every second if no input */
1295 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1300 /* Now figure out who made this select() unblock.
1301 * First, check for an error or exit condition.
1304 if (errno == EBADF) {
1305 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1309 if (errno != EINTR) {
1310 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1311 CtdlThreadStopAll();
1314 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1315 if (CtdlThreadCheckStop()) return(NULL);
1319 else if(retval == 0) {
1320 if (CtdlThreadCheckStop()) return(NULL);
1323 /* It must be a client socket. Find a context that has data
1324 * waiting on its socket *and* is in the CON_IDLE state. Any
1325 * active sockets other than our chosen one are marked as
1326 * CON_READY so the next thread that comes around can just bind
1327 * to one without having to select() again.
1329 begin_critical_section(S_SESSION_TABLE);
1330 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1331 int checkfd = ptr->client_socket;
1332 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1333 if (FD_ISSET(checkfd, &readfds)) {
1334 ptr->input_waiting = 1;
1336 bind_me = ptr; /* I choose you! */
1337 bind_me->state = CON_EXECUTING;
1340 ptr->state = CON_READY;
1342 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1344 bind_me = ptr; /* I choose you! */
1345 bind_me->state = CON_EXECUTING;
1348 ptr->state = CON_READY;
1353 end_critical_section(S_SESSION_TABLE);
1356 /* We're bound to a session */
1357 if (bind_me != NULL) {
1358 become_session(bind_me);
1360 if (bind_me->state == CON_STARTING) {
1361 bind_me->state = CON_EXECUTING;
1362 begin_session(bind_me);
1363 bind_me->h_greeting_function();
1365 /* If the client has sent a command, execute it. */
1366 if (CC->input_waiting) {
1367 CC->h_command_function();
1369 while (HaveMoreLinesWaiting(CC))
1370 CC->h_command_function();
1372 CC->input_waiting = 0;
1375 /* If there are asynchronous messages waiting and the
1376 * client supports it, do those now */
1377 if ((CC->is_async) && (CC->async_waiting)
1378 && (CC->h_async_function != NULL)) {
1379 CC->h_async_function();
1380 CC->async_waiting = 0;
1383 force_purge = CC->kill_me;
1384 become_session(NULL);
1385 bind_me->state = CON_IDLE;
1388 dead_session_purge(force_purge);
1391 /* If control reaches this point, the server is shutting down */
1399 * A function to handle selecting on master sockets.
1400 * In other words it handles new connections.
1403 void *select_on_master (void *arg)
1405 struct ServiceFunctionHook *serviceptr;
1409 int ssock; /* Descriptor for client socket */
1410 CitContext *con= NULL; /* Temporary context pointer */
1414 struct CitContext select_on_master_CC;
1416 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1417 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1419 while (!CtdlThreadCheckStop()) {
1420 /* Initialize the fdset. */
1421 FD_ZERO(&master_fds);
1424 /* First, add the various master sockets to the fdset. */
1425 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1426 serviceptr = serviceptr->next ) {
1427 m = serviceptr->msock;
1428 FD_SET(m, &master_fds);
1434 if (!CtdlThreadCheckStop()) {
1435 tv.tv_sec = 60; /* wake up every second if no input */
1437 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1442 /* Now figure out who made this select() unblock.
1443 * First, check for an error or exit condition.
1446 if (errno == EBADF) {
1447 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1451 if (errno != EINTR) {
1452 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1453 CtdlThreadStopAll();
1455 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1456 if (CtdlThreadCheckStop()) return(NULL);
1460 else if(retval == 0) {
1461 if (CtdlThreadCheckStop()) return(NULL);
1464 /* Next, check to see if it's a new client connecting
1465 * on a master socket.
1467 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1468 serviceptr = serviceptr->next ) {
1470 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1471 ssock = accept(serviceptr->msock, NULL, 0);
1473 CtdlLogPrintf(CTDL_DEBUG,
1474 "New client socket %d\n",
1477 /* The master socket is non-blocking but the client
1478 * sockets need to be blocking, otherwise certain
1479 * operations barf on FreeBSD. Not a fatal error.
1481 if (fcntl(ssock, F_SETFL, 0) < 0) {
1482 CtdlLogPrintf(CTDL_EMERG,
1483 "citserver: Can't set socket to blocking: %s\n",
1487 /* New context will be created already
1488 * set up in the CON_EXECUTING state.
1490 con = CreateNewContext();
1492 /* Assign our new socket number to it. */
1493 con->client_socket = ssock;
1494 con->h_command_function =
1495 serviceptr->h_command_function;
1496 con->h_async_function =
1497 serviceptr->h_async_function;
1498 con->h_greeting_function = serviceptr->h_greeting_function;
1500 serviceptr->ServiceName;
1502 /* Determine whether it's a local socket */
1503 if (serviceptr->sockpath != NULL)
1504 con->is_local_socket = 1;
1506 /* Set the SO_REUSEADDR socket option */
1508 setsockopt(ssock, SOL_SOCKET,
1512 con->state = CON_GREETING;
1521 CtdlClearSystemContext();
1530 * Translate text facility name to syslog.h defined value.
1532 int SyslogFacility(char *name)
1541 { LOG_KERN, "kern" },
1542 { LOG_USER, "user" },
1543 { LOG_MAIL, "mail" },
1544 { LOG_DAEMON, "daemon" },
1545 { LOG_AUTH, "auth" },
1546 { LOG_SYSLOG, "syslog" },
1548 { LOG_NEWS, "news" },
1549 { LOG_UUCP, "uucp" },
1550 { LOG_LOCAL0, "local0" },
1551 { LOG_LOCAL1, "local1" },
1552 { LOG_LOCAL2, "local2" },
1553 { LOG_LOCAL3, "local3" },
1554 { LOG_LOCAL4, "local4" },
1555 { LOG_LOCAL5, "local5" },
1556 { LOG_LOCAL6, "local6" },
1557 { LOG_LOCAL7, "local7" },
1560 for(i = 0; facTbl[i].name != NULL; i++) {
1561 if(!strcasecmp(name, facTbl[i].name))
1562 return facTbl[i].facility;
1569 /********** MEM CHEQQER ***********/
1571 #ifdef DEBUG_MEMORY_LEAKS
1578 void *tracked_malloc(size_t size, char *file, int line) {
1579 struct igheap *thisheap;
1582 block = malloc(size);
1583 if (block == NULL) return(block);
1585 thisheap = malloc(sizeof(struct igheap));
1586 if (thisheap == NULL) {
1591 thisheap->block = block;
1592 strcpy(thisheap->file, file);
1593 thisheap->line = line;
1595 begin_critical_section(S_DEBUGMEMLEAKS);
1596 thisheap->next = igheap;
1598 end_critical_section(S_DEBUGMEMLEAKS);
1604 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1605 struct igheap *thisheap;
1608 block = realloc(ptr, size);
1609 if (block == NULL) return(block);
1611 thisheap = malloc(sizeof(struct igheap));
1612 if (thisheap == NULL) {
1617 thisheap->block = block;
1618 strcpy(thisheap->file, file);
1619 thisheap->line = line;
1621 begin_critical_section(S_DEBUGMEMLEAKS);
1622 thisheap->next = igheap;
1624 end_critical_section(S_DEBUGMEMLEAKS);
1631 void tracked_free(void *ptr) {
1632 struct igheap *thisheap;
1633 struct igheap *trash;
1637 if (igheap == NULL) return;
1638 begin_critical_section(S_DEBUGMEMLEAKS);
1639 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1640 if (thisheap->next != NULL) {
1641 if (thisheap->next->block == ptr) {
1642 trash = thisheap->next;
1643 thisheap->next = thisheap->next->next;
1648 if (igheap->block == ptr) {
1650 igheap = igheap->next;
1653 end_critical_section(S_DEBUGMEMLEAKS);
1656 char *tracked_strdup(const char *s, char *file, int line) {
1659 if (s == NULL) return(NULL);
1660 ptr = tracked_malloc(strlen(s) + 1, file, line);
1661 if (ptr == NULL) return(NULL);
1662 strncpy(ptr, s, strlen(s));
1666 void dump_heap(void) {
1667 struct igheap *thisheap;
1669 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1670 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1671 thisheap->file, thisheap->line);
1675 #endif /* DEBUG_MEMORY_LEAKS */