4 * Citadel "system dependent" stuff.
5 * See COPYING for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syslog.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
52 #define SHOW_ME_VAPPEND_PRINTF
53 #include <libcitadel.h>
56 #include "sysdep_decls.h"
57 #include "citserver.h"
61 #include "housekeeping.h"
62 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
74 #include "ctdl_module.h"
80 #ifdef DEBUG_MEMORY_LEAKS
88 struct igheap *igheap = NULL;
92 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
94 int syslog_facility = LOG_DAEMON;
95 int enable_syslog = 0;
96 int print_to_logfile = 1;
99 * CtdlLogPrintf() ... Write logging information
101 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
103 va_start(arg_ptr, format);
104 vCtdlLogPrintf(loglevel, format, arg_ptr);
108 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
112 vsyslog((syslog_facility | loglevel), format, arg_ptr);
115 /* stderr output code */
116 if (enable_syslog || !print_to_logfile) return;
118 /* if we run in forground and syslog is disabled, log to terminal */
119 if (loglevel <= verbosity) {
124 CitContext *CCC = CC;
125 ThreadTSD *cTSD = CTP;
126 CtdlThreadNode *node = NULL;
131 if ((node != NULL) && (node->reltid != 0))
133 lwpid = node->reltid;
136 gettimeofday(&tv, NULL);
137 /* Promote to time_t; types differ on some OSes (like darwin) */
138 unixtime = tv.tv_sec;
139 localtime_r(&unixtime, &tim);
141 if ((CCC != NULL) && (CCC != &masterCC))
146 char buf[SIZ], buf2[SIZ];
148 if ((CCC != NULL) && (CCC->cs_pid != 0)) {
150 "%04d/%02d/%02d %2d:%02d:%02d.%06ld xx [%3d] ",
151 tim.tm_year + 1900, tim.tm_mon + 1,
152 tim.tm_mday, tim.tm_hour, tim.tm_min,
153 tim.tm_sec, (long)tv.tv_usec,
157 "%04d/%02d/%02d %2d:%02d:%02d.%06ld xx ",
158 tim.tm_year + 1900, tim.tm_mon + 1,
159 tim.tm_mday, tim.tm_hour, tim.tm_min,
160 tim.tm_sec, (long)tv.tv_usec);
162 vsnprintf(buf2, SIZ, format, arg_ptr);
164 fprintf(stderr, ":%s%s", buf, buf2);
168 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
169 tim.tm_year + 1900, tim.tm_mon + 1,
170 tim.tm_mday, tim.tm_hour, tim.tm_min,
171 tim.tm_sec, (long)tv.tv_usec);
175 StrBufAppendPrintf(lBuf,
180 if (CCC->cs_pid != 0)
181 StrBufAppendPrintf(lBuf,
184 else if (CCC->user.usernum != 0)
185 StrBufAppendPrintf(lBuf,
189 StrBufVAppendPrintf(lBuf, format, arg_ptr);
190 fwrite(ChrPtr(lBuf), 1, StrLength(lBuf), stderr);
193 if (CCC == NULL) FreeStrBuf(&lBuf);
201 * Signal handler to shut down the server.
204 volatile int exit_signal = 0;
205 volatile int shutdown_and_halt = 0;
206 volatile int restart_server = 0;
207 volatile int running_as_daemon = 0;
209 static RETSIGTYPE signal_cleanup(int signum) {
215 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
216 exit_signal = signum;
220 static RETSIGTYPE signal_exit(int signum) {
227 * Some initialization stuff...
229 void init_sysdep(void) {
232 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
236 getrlimit(RLIMIT_NOFILE, &rl);
237 rl.rlim_cur = FD_SETSIZE;
238 rl.rlim_max = FD_SETSIZE;
239 setrlimit(RLIMIT_NOFILE, &rl);
243 /* If we've got OpenSSL, we're going to use it. */
249 * Set up a place to put thread-specific data.
250 * We only need a single pointer per thread - it points to the
251 * CitContext structure (in the ContextList linked list) of the
252 * session to which the calling thread is currently bound.
254 if (citthread_key_create(&MyConKey, NULL) != 0) {
255 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
260 * The action for unexpected signals and exceptions should be to
261 * call signal_cleanup() to gracefully shut down the server.
264 sigaddset(&set, SIGINT); // intr = shutdown
265 // sigaddset(&set, SIGQUIT); // quit = force quit
266 sigaddset(&set, SIGHUP);
267 sigaddset(&set, SIGTERM);
268 // sigaddset(&set, SIGSEGV); // we want core dumps
269 // sigaddset(&set, SIGILL); // we want core dumps
270 // sigaddset(&set, SIGBUS);
271 sigprocmask(SIG_UNBLOCK, &set, NULL);
273 signal(SIGINT, signal_cleanup); // intr = shutdown
274 // signal(SIGQUIT, signal_cleanup); // quit = force quit
275 signal(SIGHUP, signal_cleanup);
276 signal(SIGTERM, signal_cleanup);
277 signal(SIGUSR2, signal_exit);
278 // signal(SIGSEGV, signal_cleanup); // we want coredumps
279 // signal(SIGILL, signal_cleanup); // we want core dumps
280 // signal(SIGBUS, signal_cleanup);
283 * Do not shut down the server on broken pipe signals, otherwise the
284 * whole Citadel service would come down whenever a single client
287 signal(SIGPIPE, SIG_IGN);
294 * This is a generic function to set up a master socket for listening on
295 * a TCP port. The server shuts down if the bind fails.
298 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
300 struct sockaddr_in sin;
302 int actual_queue_len;
304 actual_queue_len = queue_len;
305 if (actual_queue_len < 5) actual_queue_len = 5;
307 memset(&sin, 0, sizeof(sin));
308 sin.sin_family = AF_INET;
309 sin.sin_port = htons((u_short)port_number);
310 if (ip_addr == NULL) {
311 sin.sin_addr.s_addr = INADDR_ANY;
314 sin.sin_addr.s_addr = inet_addr(ip_addr);
317 if (sin.sin_addr.s_addr == !INADDR_ANY) {
318 sin.sin_addr.s_addr = INADDR_ANY;
321 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
324 *errormessage = (char*) malloc(SIZ + 1);
325 snprintf(*errormessage, SIZ,
326 "citserver: Can't create a socket: %s",
328 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
333 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
335 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
336 *errormessage = (char*) malloc(SIZ + 1);
337 snprintf(*errormessage, SIZ,
338 "citserver: Can't bind: %s",
340 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
345 /* set to nonblock - we need this for some obscure situations */
346 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
347 *errormessage = (char*) malloc(SIZ + 1);
348 snprintf(*errormessage, SIZ,
349 "citserver: Can't set socket to non-blocking: %s",
351 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
356 if (listen(s, actual_queue_len) < 0) {
357 *errormessage = (char*) malloc(SIZ + 1);
358 snprintf(*errormessage, SIZ,
359 "citserver: Can't listen: %s",
361 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
372 * Create a Unix domain socket and listen on it
374 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
376 struct sockaddr_un addr;
379 int actual_queue_len;
380 #ifdef HAVE_STRUCT_UCRED
384 actual_queue_len = queue_len;
385 if (actual_queue_len < 5) actual_queue_len = 5;
387 i = unlink(sockpath);
388 if ((i != 0) && (errno != ENOENT)) {
389 *errormessage = (char*) malloc(SIZ + 1);
390 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
391 sockpath, strerror(errno));
392 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
396 memset(&addr, 0, sizeof(addr));
397 addr.sun_family = AF_UNIX;
398 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
400 s = socket(AF_UNIX, SOCK_STREAM, 0);
402 *errormessage = (char*) malloc(SIZ + 1);
403 snprintf(*errormessage, SIZ,
404 "citserver: Can't create a socket: %s",
406 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
410 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
411 *errormessage = (char*) malloc(SIZ + 1);
412 snprintf(*errormessage, SIZ,
413 "citserver: Can't bind: %s",
415 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
419 /* set to nonblock - we need this for some obscure situations */
420 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
421 *errormessage = (char*) malloc(SIZ + 1);
422 snprintf(*errormessage, SIZ,
423 "citserver: Can't set socket to non-blocking: %s",
425 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
430 if (listen(s, actual_queue_len) < 0) {
431 *errormessage = (char*) malloc(SIZ + 1);
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);
519 // flush_client_inbuf();
521 if (Ctx->redirect_buffer != NULL) {
522 StrBufAppendBufPlain(Ctx->redirect_buffer,
528 if (Ctx->redirect_ssl) {
529 client_write_ssl(buf, nbytes);
533 if (Ctx->client_socket == -1) return -1;
535 fdflags = fcntl(Ctx->client_socket, F_GETFL);
537 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
538 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
540 FD_SET(Ctx->client_socket, &wset);
541 if (select(1, NULL, &wset, NULL, NULL) == -1) {
544 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
545 if (CtdlThreadCheckStop()) {
549 /* can't trust fd's and stuff so we need to re-create them */
553 CtdlLogPrintf(CTDL_ERR,
554 "client_write(%d bytes) select failed: %s (%d)\n",
555 nbytes - bytes_written,
556 strerror(errno), errno);
564 retval = write(Ctx->client_socket, &buf[bytes_written],
565 nbytes - bytes_written);
567 CtdlLogPrintf(CTDL_ERR,
568 "client_write(%d bytes) failed: %s (%d)\n",
569 nbytes - bytes_written,
570 strerror(errno), errno);
572 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
576 bytes_written = bytes_written + retval;
581 void cputbuf(const StrBuf *Buf) {
582 client_write(ChrPtr(Buf), StrLength(Buf));
587 * cprintf() Send formatted printable data to the client.
588 * Implemented in terms of client_write() so it's technically not sysdep...
590 void cprintf(const char *format, ...) {
594 va_start(arg_ptr, format);
595 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
596 buf[sizeof buf - 2] = '\n';
597 client_write(buf, strlen(buf));
603 * Read data from the client socket.
605 * sock socket fd to read from
606 * buf buffer to read into
607 * bytes number of bytes to read
608 * timeout Number of seconds to wait before timing out
610 * Possible return values:
611 * 1 Requested number of bytes has been read.
612 * 0 Request timed out.
613 * -1 Connection is broken, or other error.
615 int client_read_blob(StrBuf *Target, int bytes, int timeout)
622 if (CCC->redirect_ssl) {
623 retval = client_read_sslblob(Target, bytes, timeout);
625 CtdlLogPrintf(CTDL_CRIT,
633 retval = StrBufReadBLOBBuffered(Target,
642 CtdlLogPrintf(CTDL_CRIT,
655 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
657 fd = fopen(fn, "a+");
658 fprintf(fd, "Read: BufSize: %d BufContent: [",
660 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
674 * to make client_read_random_blob() more efficient, increase buffer size.
675 * just use in greeting function, else your buffer may be flushed
677 void client_set_inbound_buf(long N)
679 FlushStrBuf(CC->ReadBuf);
680 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
683 int client_read_random_blob(StrBuf *Target, int timeout)
688 rc = client_read_blob(Target, 1, timeout);
694 len = StrLength(CCC->ReadBuf);
695 pch = ChrPtr(CCC->ReadBuf);
699 if (CCC->Pos != NULL) {
700 len -= CCC->Pos - pch;
703 StrBufAppendBufPlain(Target, pch, len, 0);
704 FlushStrBuf(CCC->ReadBuf);
712 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
714 fd = fopen(fn, "a+");
715 fprintf(fd, "Read: BufSize: %d BufContent: [",
717 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
725 return StrLength(Target);
733 int client_read_to(char *buf, int bytes, int timeout)
738 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
747 ChrPtr(CCC->MigrateBuf),
748 StrLength(CCC->MigrateBuf) + 1);
749 FlushStrBuf(CCC->MigrateBuf);
755 int HaveMoreLinesWaiting(CitContext *CCC)
757 if ((CCC->kill_me == 1) || (
758 (CCC->Pos == NULL) &&
759 (StrLength(CCC->ReadBuf) == 0) &&
760 (CCC->client_socket != -1)) )
768 * Read data from the client socket with default timeout.
769 * (This is implemented in terms of client_read_to() and could be
770 * justifiably moved out of sysdep.c)
772 INLINE int client_read(char *buf, int bytes)
774 return(client_read_to(buf, bytes, config.c_sleeping));
777 int CtdlClientGetLine(StrBuf *Target)
785 if (CCC->redirect_ssl) {
795 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
797 fd = fopen(fn, "a+");
798 pch = ChrPtr(CCC->ReadBuf);
799 len = StrLength(CCC->ReadBuf);
800 if (CCC->Pos != NULL)
801 rlen = CC->Pos - pch;
805 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
808 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
811 rc = client_readline_sslbuffer(Target,
816 pch = ChrPtr(CCC->ReadBuf);
817 nlen = StrLength(CCC->ReadBuf);
818 if (CCC->Pos != NULL)
819 nrlen = CC->Pos - pch;
823 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
824 len, nlen, rlen, nrlen, pch);
826 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
827 len, nlen, rlen, nrlen);
829 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
830 StrLength(Target), ChrPtr(Target));
834 CtdlLogPrintf(CTDL_CRIT,
846 int len, rlen, nlen, nrlen;
849 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
851 fd = fopen(fn, "a+");
852 pch = ChrPtr(CCC->ReadBuf);
853 len = StrLength(CCC->ReadBuf);
854 if (CCC->Pos != NULL)
855 rlen = CC->Pos - pch;
859 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
862 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
865 rc = StrBufTCP_read_buffered_line_fast(Target,
874 pch = ChrPtr(CCC->ReadBuf);
875 nlen = StrLength(CCC->ReadBuf);
876 if (CCC->Pos != NULL)
877 nrlen = CC->Pos - pch;
881 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
882 len, nlen, rlen, nrlen, pch);
884 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
885 len, nlen, rlen, nrlen);
887 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
888 StrLength(Target), ChrPtr(Target));
891 if ((rc < 0) && (Error != NULL))
892 CtdlLogPrintf(CTDL_CRIT,
903 * client_getln() ... Get a LF-terminated line of text from the client.
904 * (This is implemented in terms of client_read() and could be
905 * justifiably moved out of sysdep.c)
907 int client_getln(char *buf, int bufsize)
913 retval = CtdlClientGetLine(CCC->MigrateBuf);
918 i = StrLength(CCC->MigrateBuf);
919 pCh = ChrPtr(CCC->MigrateBuf);
920 /* Strip the trailing LF, and the trailing CR if present.
925 && ( (pCh[i - 1]==13)
926 || ( pCh[i - 1]==10)) ) {
932 FlushStrBuf(CCC->MigrateBuf);
934 safestrncpy(&buf[i], "000", bufsize - i);
941 * Cleanup any contexts that are left lying around
945 void close_masters (void)
947 struct ServiceFunctionHook *serviceptr;
950 * close all protocol master sockets
952 for (serviceptr = ServiceHookTable; serviceptr != NULL;
953 serviceptr = serviceptr->next ) {
955 if (serviceptr->tcp_port > 0)
957 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
958 serviceptr->tcp_port);
959 serviceptr->tcp_port = 0;
962 if (serviceptr->sockpath != NULL)
963 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
964 serviceptr->sockpath);
966 close(serviceptr->msock);
967 /* If it's a Unix domain socket, remove the file. */
968 if (serviceptr->sockpath != NULL) {
969 unlink(serviceptr->sockpath);
970 serviceptr->sockpath = NULL;
977 * The system-dependent part of master_cleanup() - close the master socket.
979 void sysdep_master_cleanup(void) {
988 CtdlDestroyProtoHooks();
989 CtdlDestroyDeleteHooks();
990 CtdlDestroyXmsgHooks();
991 CtdlDestroyNetprocHooks();
992 CtdlDestroyUserHooks();
993 CtdlDestroyMessageHook();
994 CtdlDestroyCleanupHooks();
995 CtdlDestroyFixedOutputHooks();
996 CtdlDestroySessionHooks();
997 CtdlDestroyServiceHook();
998 CtdlDestroyRoomHooks();
999 #ifdef HAVE_BACKTRACE
1000 /// eCrash_Uninit();
1006 pid_t current_child;
1007 void graceful_shutdown(int signum) {
1008 kill(current_child, signum);
1009 unlink(file_pid_file);
1014 int nFireUpsNonRestart = 0;
1015 pid_t ForkedPid = 1;
1018 * Start running as a daemon.
1020 void start_daemon(int unused) {
1028 /* Close stdin/stdout/stderr and replace them with /dev/null.
1029 * We don't just call close() because we don't want these fd's
1030 * to be reused for other files.
1032 if (chdir(ctdl_run_dir) != 0)
1033 CtdlLogPrintf(CTDL_EMERG,
1034 "unable to change into directory [%s]: %s",
1035 ctdl_run_dir, strerror(errno));
1042 signal(SIGHUP, SIG_IGN);
1043 signal(SIGINT, SIG_IGN);
1044 signal(SIGQUIT, SIG_IGN);
1048 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1049 (freopen("/dev/null", "w", stdout) != stdout) ||
1050 (freopen("/dev/null", "w", stderr) != stderr))
1051 CtdlLogPrintf(CTDL_EMERG,
1052 "unable to reopen stdin/out/err %s",
1057 current_child = fork();
1059 signal(SIGTERM, graceful_shutdown);
1061 if (current_child < 0) {
1066 else if (current_child == 0) {
1067 return; /* continue starting citadel. */
1071 fp = fopen(file_pid_file, "w");
1073 fprintf(fp, ""F_PID_T"\n", getpid());
1076 waitpid(current_child, &status, 0);
1079 nFireUpsNonRestart = nFireUps;
1081 /* Exit code 0 means the watcher should exit */
1082 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1086 /* Exit code 101-109 means the watcher should exit */
1087 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1091 /* Any other exit code, or no exit code, means we should restart. */
1095 ForkedPid = current_child;
1098 } while (do_restart);
1100 unlink(file_pid_file);
1101 exit(WEXITSTATUS(status));
1106 void checkcrash(void)
1108 if (nFireUpsNonRestart != nFireUps)
1112 CrashMail = NewStrBuf();
1113 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1114 StrBufPrintf(CrashMail,
1116 " The Citadel server process (citserver) terminated unexpectedly."
1118 " This could be the result of a bug in the server program, or some external "
1120 " You can obtain more information about this by enabling core dumps.\n \n"
1121 " For more information, please see:\n \n"
1122 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1125 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1127 ctdl_run_dir, ForkedPid);
1128 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1129 FreeStrBuf(&CrashMail);
1135 * Generic routine to convert a login name to a full name (gecos)
1136 * Returns nonzero if a conversion took place
1138 int convert_login(char NameToConvert[]) {
1142 pw = getpwnam(NameToConvert);
1147 strcpy(NameToConvert, pw->pw_gecos);
1148 for (a=0; a<strlen(NameToConvert); ++a) {
1149 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1158 * This loop just keeps going and going and going...
1162 * This current implimentation of worker_thread creates a bottle neck in several situations
1163 * The first thing to remember is that a single thread can handle more than one connection at a time.
1164 * More threads mean less memory for the system to run in.
1165 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1166 * something to happen anywhere.
1167 * This current implimentation requires worker threads to wait in other locations, after it has
1168 * been committed to a single connection which is very wasteful.
1169 * As an extreme case consider this:
1170 * A slow client connects and this slow client sends only one character each second.
1171 * With this current implimentation a single worker thread is dispatched to handle that connection
1172 * until such times as the client timeout expires, an error occurs on the socket or the client
1173 * completes its transmission.
1174 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1175 * second interval between chars.
1177 * It is my intention to re-write this code and the associated client_getln, client_read functions
1178 * to allow any thread to read data on behalf of any connection (context).
1179 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1180 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1182 * This worker thread loop also needs to be able to handle binary data.
1185 void *worker_thread(void *arg) {
1188 CitContext *bind_me = NULL;
1192 int force_purge = 0;
1195 while (!CtdlThreadCheckStop()) {
1197 /* make doubly sure we're not holding any stale db handles
1198 * which might cause a deadlock.
1200 cdb_check_handles();
1201 do_select: force_purge = 0;
1202 bind_me = NULL; /* Which session shall we handle? */
1204 /* Initialize the fdset. */
1208 begin_critical_section(S_SESSION_TABLE);
1209 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1211 client_socket = ptr->client_socket;
1212 /* Dont select on dead sessions only truly idle ones */
1213 if ((ptr->state == CON_IDLE) &&
1214 (CC->kill_me == 0) &&
1215 (client_socket != -1))
1217 FD_SET(client_socket, &readfds);
1218 if (client_socket > highest)
1219 highest = client_socket;
1221 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1223 ptr->state = CON_EXECUTING;
1226 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1228 ptr->state = CON_STARTING;
1232 end_critical_section(S_SESSION_TABLE);
1238 /* If we got this far, it means that there are no sessions
1239 * which a previous thread marked for attention, so we go
1240 * ahead and get ready to select().
1243 if (!CtdlThreadCheckStop()) {
1244 tv.tv_sec = 1; /* wake up every second if no input */
1246 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1251 /* Now figure out who made this select() unblock.
1252 * First, check for an error or exit condition.
1255 if (errno == EBADF) {
1256 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1260 if (errno != EINTR) {
1261 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1262 CtdlThreadStopAll();
1265 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1266 if (CtdlThreadCheckStop()) return(NULL);
1270 else if(retval == 0) {
1271 if (CtdlThreadCheckStop()) return(NULL);
1274 /* It must be a client socket. Find a context that has data
1275 * waiting on its socket *and* is in the CON_IDLE state. Any
1276 * active sockets other than our chosen one are marked as
1277 * CON_READY so the next thread that comes around can just bind
1278 * to one without having to select() again.
1280 begin_critical_section(S_SESSION_TABLE);
1281 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1282 int checkfd = ptr->client_socket;
1283 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1284 if (FD_ISSET(checkfd, &readfds)) {
1285 ptr->input_waiting = 1;
1287 bind_me = ptr; /* I choose you! */
1288 bind_me->state = CON_EXECUTING;
1291 ptr->state = CON_READY;
1293 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1295 bind_me = ptr; /* I choose you! */
1296 bind_me->state = CON_EXECUTING;
1299 ptr->state = CON_READY;
1304 end_critical_section(S_SESSION_TABLE);
1307 /* We're bound to a session */
1308 if (bind_me != NULL) {
1309 become_session(bind_me);
1311 if (bind_me->state == CON_STARTING) {
1312 bind_me->state = CON_EXECUTING;
1313 begin_session(bind_me);
1314 bind_me->h_greeting_function();
1316 /* If the client has sent a command, execute it. */
1317 if (CC->input_waiting) {
1318 CC->h_command_function();
1320 while (HaveMoreLinesWaiting(CC))
1321 CC->h_command_function();
1323 CC->input_waiting = 0;
1326 /* If there are asynchronous messages waiting and the
1327 * client supports it, do those now */
1328 if ((CC->is_async) && (CC->async_waiting)
1329 && (CC->h_async_function != NULL)) {
1330 CC->h_async_function();
1331 CC->async_waiting = 0;
1334 force_purge = CC->kill_me;
1335 become_session(NULL);
1336 bind_me->state = CON_IDLE;
1339 dead_session_purge(force_purge);
1342 /* If control reaches this point, the server is shutting down */
1350 * A function to handle selecting on master sockets.
1351 * In other words it handles new connections.
1354 void *select_on_master (void *arg)
1356 struct ServiceFunctionHook *serviceptr;
1360 int ssock; /* Descriptor for client socket */
1361 CitContext *con= NULL; /* Temporary context pointer */
1365 struct CitContext select_on_master_CC;
1367 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1368 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1370 while (!CtdlThreadCheckStop()) {
1371 /* Initialize the fdset. */
1372 FD_ZERO(&master_fds);
1375 /* First, add the various master sockets to the fdset. */
1376 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1377 serviceptr = serviceptr->next ) {
1378 m = serviceptr->msock;
1379 FD_SET(m, &master_fds);
1385 if (!CtdlThreadCheckStop()) {
1386 tv.tv_sec = 60; /* wake up every second if no input */
1388 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1393 /* Now figure out who made this select() unblock.
1394 * First, check for an error or exit condition.
1397 if (errno == EBADF) {
1398 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1402 if (errno != EINTR) {
1403 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1404 CtdlThreadStopAll();
1406 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1407 if (CtdlThreadCheckStop()) return(NULL);
1411 else if(retval == 0) {
1412 if (CtdlThreadCheckStop()) return(NULL);
1415 /* Next, check to see if it's a new client connecting
1416 * on a master socket.
1418 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1419 serviceptr = serviceptr->next ) {
1421 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1422 ssock = accept(serviceptr->msock, NULL, 0);
1424 CtdlLogPrintf(CTDL_DEBUG,
1425 "New client socket %d\n",
1428 /* The master socket is non-blocking but the client
1429 * sockets need to be blocking, otherwise certain
1430 * operations barf on FreeBSD. Not a fatal error.
1432 if (fcntl(ssock, F_SETFL, 0) < 0) {
1433 CtdlLogPrintf(CTDL_EMERG,
1434 "citserver: Can't set socket to blocking: %s\n",
1438 /* New context will be created already
1439 * set up in the CON_EXECUTING state.
1441 con = CreateNewContext();
1443 /* Assign our new socket number to it. */
1444 con->client_socket = ssock;
1445 con->h_command_function =
1446 serviceptr->h_command_function;
1447 con->h_async_function =
1448 serviceptr->h_async_function;
1449 con->h_greeting_function = serviceptr->h_greeting_function;
1451 serviceptr->ServiceName;
1453 /* Determine whether it's a local socket */
1454 if (serviceptr->sockpath != NULL)
1455 con->is_local_socket = 1;
1457 /* Set the SO_REUSEADDR socket option */
1459 setsockopt(ssock, SOL_SOCKET,
1463 con->state = CON_GREETING;
1472 CtdlClearSystemContext();
1481 * Translate text facility name to syslog.h defined value.
1483 int SyslogFacility(char *name)
1492 { LOG_KERN, "kern" },
1493 { LOG_USER, "user" },
1494 { LOG_MAIL, "mail" },
1495 { LOG_DAEMON, "daemon" },
1496 { LOG_AUTH, "auth" },
1497 { LOG_SYSLOG, "syslog" },
1499 { LOG_NEWS, "news" },
1500 { LOG_UUCP, "uucp" },
1501 { LOG_LOCAL0, "local0" },
1502 { LOG_LOCAL1, "local1" },
1503 { LOG_LOCAL2, "local2" },
1504 { LOG_LOCAL3, "local3" },
1505 { LOG_LOCAL4, "local4" },
1506 { LOG_LOCAL5, "local5" },
1507 { LOG_LOCAL6, "local6" },
1508 { LOG_LOCAL7, "local7" },
1511 for(i = 0; facTbl[i].name != NULL; i++) {
1512 if(!strcasecmp(name, facTbl[i].name))
1513 return facTbl[i].facility;
1520 /********** MEM CHEQQER ***********/
1522 #ifdef DEBUG_MEMORY_LEAKS
1529 void *tracked_malloc(size_t size, char *file, int line) {
1530 struct igheap *thisheap;
1533 block = malloc(size);
1534 if (block == NULL) return(block);
1536 thisheap = malloc(sizeof(struct igheap));
1537 if (thisheap == NULL) {
1542 thisheap->block = block;
1543 strcpy(thisheap->file, file);
1544 thisheap->line = line;
1546 begin_critical_section(S_DEBUGMEMLEAKS);
1547 thisheap->next = igheap;
1549 end_critical_section(S_DEBUGMEMLEAKS);
1555 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1556 struct igheap *thisheap;
1559 block = realloc(ptr, size);
1560 if (block == NULL) return(block);
1562 thisheap = malloc(sizeof(struct igheap));
1563 if (thisheap == NULL) {
1568 thisheap->block = block;
1569 strcpy(thisheap->file, file);
1570 thisheap->line = line;
1572 begin_critical_section(S_DEBUGMEMLEAKS);
1573 thisheap->next = igheap;
1575 end_critical_section(S_DEBUGMEMLEAKS);
1582 void tracked_free(void *ptr) {
1583 struct igheap *thisheap;
1584 struct igheap *trash;
1588 if (igheap == NULL) return;
1589 begin_critical_section(S_DEBUGMEMLEAKS);
1590 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1591 if (thisheap->next != NULL) {
1592 if (thisheap->next->block == ptr) {
1593 trash = thisheap->next;
1594 thisheap->next = thisheap->next->next;
1599 if (igheap->block == ptr) {
1601 igheap = igheap->next;
1604 end_critical_section(S_DEBUGMEMLEAKS);
1607 char *tracked_strdup(const char *s, char *file, int line) {
1610 if (s == NULL) return(NULL);
1611 ptr = tracked_malloc(strlen(s) + 1, file, line);
1612 if (ptr == NULL) return(NULL);
1613 strncpy(ptr, s, strlen(s));
1617 void dump_heap(void) {
1618 struct igheap *thisheap;
1620 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1621 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1622 thisheap->file, thisheap->line);
1626 #endif /* DEBUG_MEMORY_LEAKS */