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);
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) {
642 retval = client_read_sslblob(Target, bytes, timeout);
644 CtdlLogPrintf(CTDL_CRIT,
652 retval = StrBufReadBLOBBuffered(Target,
661 CtdlLogPrintf(CTDL_CRIT,
674 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
676 fd = fopen(fn, "a+");
677 fprintf(fd, "Read: BufSize: %d BufContent: [",
679 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
693 * to make client_read_random_blob() more efficient, increase buffer size.
694 * just use in greeting function, else your buffer may be flushed
696 void client_set_inbound_buf(long N)
698 FlushStrBuf(CC->ReadBuf);
699 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
702 int client_read_random_blob(StrBuf *Target, int timeout)
707 rc = client_read_blob(Target, 1, timeout);
713 len = StrLength(CCC->ReadBuf);
714 pch = ChrPtr(CCC->ReadBuf);
718 if (CCC->Pos != NULL) {
719 len -= CCC->Pos - pch;
722 StrBufAppendBufPlain(Target, pch, len, 0);
723 FlushStrBuf(CCC->ReadBuf);
731 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
733 fd = fopen(fn, "a+");
734 fprintf(fd, "Read: BufSize: %d BufContent: [",
736 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
744 return StrLength(Target);
752 int client_read_to(char *buf, int bytes, int timeout)
757 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
766 ChrPtr(CCC->MigrateBuf),
767 StrLength(CCC->MigrateBuf) + 1);
768 FlushStrBuf(CCC->MigrateBuf);
774 int HaveMoreLinesWaiting(CitContext *CCC)
776 if ((CCC->kill_me == 1) || (
777 (CCC->Pos == NULL) &&
778 (StrLength(CCC->ReadBuf) == 0) &&
779 (CCC->client_socket != -1)) )
787 * Read data from the client socket with default timeout.
788 * (This is implemented in terms of client_read_to() and could be
789 * justifiably moved out of sysdep.c)
791 INLINE int client_read(char *buf, int bytes)
793 return(client_read_to(buf, bytes, config.c_sleeping));
796 int CtdlClientGetLine(StrBuf *Target)
804 if (CCC->redirect_ssl) {
814 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
816 fd = fopen(fn, "a+");
817 pch = ChrPtr(CCC->ReadBuf);
818 len = StrLength(CCC->ReadBuf);
819 if (CCC->Pos != NULL)
820 rlen = CC->Pos - pch;
824 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
827 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
830 rc = client_readline_sslbuffer(Target,
835 pch = ChrPtr(CCC->ReadBuf);
836 nlen = StrLength(CCC->ReadBuf);
837 if (CCC->Pos != NULL)
838 nrlen = CC->Pos - pch;
842 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
843 len, nlen, rlen, nrlen, pch);
845 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
846 len, nlen, rlen, nrlen);
848 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
849 StrLength(Target), ChrPtr(Target));
853 CtdlLogPrintf(CTDL_CRIT,
865 int len, rlen, nlen, nrlen;
868 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
870 fd = fopen(fn, "a+");
871 pch = ChrPtr(CCC->ReadBuf);
872 len = StrLength(CCC->ReadBuf);
873 if (CCC->Pos != NULL)
874 rlen = CC->Pos - pch;
878 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
881 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
884 rc = StrBufTCP_read_buffered_line_fast(Target,
893 pch = ChrPtr(CCC->ReadBuf);
894 nlen = StrLength(CCC->ReadBuf);
895 if (CCC->Pos != NULL)
896 nrlen = CC->Pos - pch;
900 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
901 len, nlen, rlen, nrlen, pch);
903 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
904 len, nlen, rlen, nrlen);
906 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
907 StrLength(Target), ChrPtr(Target));
910 if ((rc < 0) && (Error != NULL))
911 CtdlLogPrintf(CTDL_CRIT,
922 * client_getln() ... Get a LF-terminated line of text from the client.
923 * (This is implemented in terms of client_read() and could be
924 * justifiably moved out of sysdep.c)
926 int client_getln(char *buf, int bufsize)
932 retval = CtdlClientGetLine(CCC->MigrateBuf);
937 i = StrLength(CCC->MigrateBuf);
938 pCh = ChrPtr(CCC->MigrateBuf);
939 /* Strip the trailing LF, and the trailing CR if present.
944 && ( (pCh[i - 1]==13)
945 || ( pCh[i - 1]==10)) ) {
951 FlushStrBuf(CCC->MigrateBuf);
953 safestrncpy(&buf[i], "000", bufsize - i);
960 * Cleanup any contexts that are left lying around
964 void close_masters (void)
966 struct ServiceFunctionHook *serviceptr;
969 * close all protocol master sockets
971 for (serviceptr = ServiceHookTable; serviceptr != NULL;
972 serviceptr = serviceptr->next ) {
974 if (serviceptr->tcp_port > 0)
976 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
977 serviceptr->tcp_port);
978 serviceptr->tcp_port = 0;
981 if (serviceptr->sockpath != NULL)
982 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
983 serviceptr->sockpath);
985 close(serviceptr->msock);
986 /* If it's a Unix domain socket, remove the file. */
987 if (serviceptr->sockpath != NULL) {
988 unlink(serviceptr->sockpath);
989 serviceptr->sockpath = NULL;
996 * The system-dependent part of master_cleanup() - close the master socket.
998 void sysdep_master_cleanup(void) {
1007 CtdlDestroyProtoHooks();
1008 CtdlDestroyDeleteHooks();
1009 CtdlDestroyXmsgHooks();
1010 CtdlDestroyNetprocHooks();
1011 CtdlDestroyUserHooks();
1012 CtdlDestroyMessageHook();
1013 CtdlDestroyCleanupHooks();
1014 CtdlDestroyFixedOutputHooks();
1015 CtdlDestroySessionHooks();
1016 CtdlDestroyServiceHook();
1017 CtdlDestroyRoomHooks();
1018 #ifdef HAVE_BACKTRACE
1019 /// eCrash_Uninit();
1025 pid_t current_child;
1026 void graceful_shutdown(int signum) {
1027 kill(current_child, signum);
1028 unlink(file_pid_file);
1033 int nFireUpsNonRestart = 0;
1034 pid_t ForkedPid = 1;
1037 * Start running as a daemon.
1039 void start_daemon(int unused) {
1047 /* Close stdin/stdout/stderr and replace them with /dev/null.
1048 * We don't just call close() because we don't want these fd's
1049 * to be reused for other files.
1051 if (chdir(ctdl_run_dir) != 0)
1052 CtdlLogPrintf(CTDL_EMERG,
1053 "unable to change into directory [%s]: %s",
1054 ctdl_run_dir, strerror(errno));
1061 signal(SIGHUP, SIG_IGN);
1062 signal(SIGINT, SIG_IGN);
1063 signal(SIGQUIT, SIG_IGN);
1067 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1068 (freopen("/dev/null", "w", stdout) != stdout) ||
1069 (freopen("/dev/null", "w", stderr) != stderr))
1070 CtdlLogPrintf(CTDL_EMERG,
1071 "unable to reopen stdin/out/err %s",
1076 current_child = fork();
1078 signal(SIGTERM, graceful_shutdown);
1080 if (current_child < 0) {
1085 else if (current_child == 0) {
1086 return; /* continue starting citadel. */
1090 fp = fopen(file_pid_file, "w");
1092 fprintf(fp, ""F_PID_T"\n", getpid());
1095 waitpid(current_child, &status, 0);
1098 nFireUpsNonRestart = nFireUps;
1100 /* Exit code 0 means the watcher should exit */
1101 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1105 /* Exit code 101-109 means the watcher should exit */
1106 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1110 /* Any other exit code, or no exit code, means we should restart. */
1114 ForkedPid = current_child;
1117 } while (do_restart);
1119 unlink(file_pid_file);
1120 exit(WEXITSTATUS(status));
1125 void checkcrash(void)
1127 if (nFireUpsNonRestart != nFireUps)
1131 CrashMail = NewStrBuf();
1132 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1133 StrBufPrintf(CrashMail,
1135 " The Citadel server process (citserver) terminated unexpectedly."
1137 " This could be the result of a bug in the server program, or some external "
1139 " You can obtain more information about this by enabling core dumps.\n \n"
1140 " For more information, please see:\n \n"
1141 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1144 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1146 ctdl_run_dir, ForkedPid);
1147 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1148 FreeStrBuf(&CrashMail);
1154 * Generic routine to convert a login name to a full name (gecos)
1155 * Returns nonzero if a conversion took place
1157 int convert_login(char NameToConvert[]) {
1161 pw = getpwnam(NameToConvert);
1166 strcpy(NameToConvert, pw->pw_gecos);
1167 for (a=0; a<strlen(NameToConvert); ++a) {
1168 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1177 * This loop just keeps going and going and going...
1181 * This current implimentation of worker_thread creates a bottle neck in several situations
1182 * The first thing to remember is that a single thread can handle more than one connection at a time.
1183 * More threads mean less memory for the system to run in.
1184 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1185 * something to happen anywhere.
1186 * This current implimentation requires worker threads to wait in other locations, after it has
1187 * been committed to a single connection which is very wasteful.
1188 * As an extreme case consider this:
1189 * A slow client connects and this slow client sends only one character each second.
1190 * With this current implimentation a single worker thread is dispatched to handle that connection
1191 * until such times as the client timeout expires, an error occurs on the socket or the client
1192 * completes its transmission.
1193 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1194 * second interval between chars.
1196 * It is my intention to re-write this code and the associated client_getln, client_read functions
1197 * to allow any thread to read data on behalf of any connection (context).
1198 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1199 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1201 * This worker thread loop also needs to be able to handle binary data.
1204 void *worker_thread(void *arg) {
1207 CitContext *bind_me = NULL;
1211 int force_purge = 0;
1214 while (!CtdlThreadCheckStop()) {
1216 /* make doubly sure we're not holding any stale db handles
1217 * which might cause a deadlock.
1219 cdb_check_handles();
1220 do_select: force_purge = 0;
1221 bind_me = NULL; /* Which session shall we handle? */
1223 /* Initialize the fdset. */
1227 begin_critical_section(S_SESSION_TABLE);
1228 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1230 client_socket = ptr->client_socket;
1231 /* Dont select on dead sessions only truly idle ones */
1232 if ((ptr->state == CON_IDLE) &&
1233 (CC->kill_me == 0) &&
1234 (client_socket != -1))
1236 FD_SET(client_socket, &readfds);
1237 if (client_socket > highest)
1238 highest = client_socket;
1240 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1242 ptr->state = CON_EXECUTING;
1245 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1247 ptr->state = CON_STARTING;
1251 end_critical_section(S_SESSION_TABLE);
1257 /* If we got this far, it means that there are no sessions
1258 * which a previous thread marked for attention, so we go
1259 * ahead and get ready to select().
1262 if (!CtdlThreadCheckStop()) {
1263 tv.tv_sec = 1; /* wake up every second if no input */
1265 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1270 /* Now figure out who made this select() unblock.
1271 * First, check for an error or exit condition.
1274 if (errno == EBADF) {
1275 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1279 if (errno != EINTR) {
1280 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1281 CtdlThreadStopAll();
1284 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1285 if (CtdlThreadCheckStop()) return(NULL);
1289 else if(retval == 0) {
1290 if (CtdlThreadCheckStop()) return(NULL);
1293 /* It must be a client socket. Find a context that has data
1294 * waiting on its socket *and* is in the CON_IDLE state. Any
1295 * active sockets other than our chosen one are marked as
1296 * CON_READY so the next thread that comes around can just bind
1297 * to one without having to select() again.
1299 begin_critical_section(S_SESSION_TABLE);
1300 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1301 int checkfd = ptr->client_socket;
1302 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1303 if (FD_ISSET(checkfd, &readfds)) {
1304 ptr->input_waiting = 1;
1306 bind_me = ptr; /* I choose you! */
1307 bind_me->state = CON_EXECUTING;
1310 ptr->state = CON_READY;
1312 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1314 bind_me = ptr; /* I choose you! */
1315 bind_me->state = CON_EXECUTING;
1318 ptr->state = CON_READY;
1323 end_critical_section(S_SESSION_TABLE);
1326 /* We're bound to a session */
1327 if (bind_me != NULL) {
1328 become_session(bind_me);
1330 if (bind_me->state == CON_STARTING) {
1331 bind_me->state = CON_EXECUTING;
1332 begin_session(bind_me);
1333 bind_me->h_greeting_function();
1335 /* If the client has sent a command, execute it. */
1336 if (CC->input_waiting) {
1337 CC->h_command_function();
1339 while (HaveMoreLinesWaiting(CC))
1340 CC->h_command_function();
1342 CC->input_waiting = 0;
1345 /* If there are asynchronous messages waiting and the
1346 * client supports it, do those now */
1347 if ((CC->is_async) && (CC->async_waiting)
1348 && (CC->h_async_function != NULL)) {
1349 CC->h_async_function();
1350 CC->async_waiting = 0;
1353 force_purge = CC->kill_me;
1354 become_session(NULL);
1355 bind_me->state = CON_IDLE;
1358 dead_session_purge(force_purge);
1361 /* If control reaches this point, the server is shutting down */
1369 * A function to handle selecting on master sockets.
1370 * In other words it handles new connections.
1373 void *select_on_master (void *arg)
1375 struct ServiceFunctionHook *serviceptr;
1379 int ssock; /* Descriptor for client socket */
1380 CitContext *con= NULL; /* Temporary context pointer */
1384 struct CitContext select_on_master_CC;
1386 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1387 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1389 while (!CtdlThreadCheckStop()) {
1390 /* Initialize the fdset. */
1391 FD_ZERO(&master_fds);
1394 /* First, add the various master sockets to the fdset. */
1395 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1396 serviceptr = serviceptr->next ) {
1397 m = serviceptr->msock;
1398 FD_SET(m, &master_fds);
1404 if (!CtdlThreadCheckStop()) {
1405 tv.tv_sec = 60; /* wake up every second if no input */
1407 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1412 /* Now figure out who made this select() unblock.
1413 * First, check for an error or exit condition.
1416 if (errno == EBADF) {
1417 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1421 if (errno != EINTR) {
1422 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1423 CtdlThreadStopAll();
1425 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1426 if (CtdlThreadCheckStop()) return(NULL);
1430 else if(retval == 0) {
1431 if (CtdlThreadCheckStop()) return(NULL);
1434 /* Next, check to see if it's a new client connecting
1435 * on a master socket.
1437 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1438 serviceptr = serviceptr->next ) {
1440 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1441 ssock = accept(serviceptr->msock, NULL, 0);
1443 CtdlLogPrintf(CTDL_DEBUG,
1444 "New client socket %d\n",
1447 /* The master socket is non-blocking but the client
1448 * sockets need to be blocking, otherwise certain
1449 * operations barf on FreeBSD. Not a fatal error.
1451 if (fcntl(ssock, F_SETFL, 0) < 0) {
1452 CtdlLogPrintf(CTDL_EMERG,
1453 "citserver: Can't set socket to blocking: %s\n",
1457 /* New context will be created already
1458 * set up in the CON_EXECUTING state.
1460 con = CreateNewContext();
1462 /* Assign our new socket number to it. */
1463 con->client_socket = ssock;
1464 con->h_command_function =
1465 serviceptr->h_command_function;
1466 con->h_async_function =
1467 serviceptr->h_async_function;
1468 con->h_greeting_function = serviceptr->h_greeting_function;
1470 serviceptr->ServiceName;
1472 /* Determine whether it's a local socket */
1473 if (serviceptr->sockpath != NULL)
1474 con->is_local_socket = 1;
1476 /* Set the SO_REUSEADDR socket option */
1478 setsockopt(ssock, SOL_SOCKET,
1482 con->state = CON_GREETING;
1491 CtdlClearSystemContext();
1500 * Translate text facility name to syslog.h defined value.
1502 int SyslogFacility(char *name)
1511 { LOG_KERN, "kern" },
1512 { LOG_USER, "user" },
1513 { LOG_MAIL, "mail" },
1514 { LOG_DAEMON, "daemon" },
1515 { LOG_AUTH, "auth" },
1516 { LOG_SYSLOG, "syslog" },
1518 { LOG_NEWS, "news" },
1519 { LOG_UUCP, "uucp" },
1520 { LOG_LOCAL0, "local0" },
1521 { LOG_LOCAL1, "local1" },
1522 { LOG_LOCAL2, "local2" },
1523 { LOG_LOCAL3, "local3" },
1524 { LOG_LOCAL4, "local4" },
1525 { LOG_LOCAL5, "local5" },
1526 { LOG_LOCAL6, "local6" },
1527 { LOG_LOCAL7, "local7" },
1530 for(i = 0; facTbl[i].name != NULL; i++) {
1531 if(!strcasecmp(name, facTbl[i].name))
1532 return facTbl[i].facility;
1539 /********** MEM CHEQQER ***********/
1541 #ifdef DEBUG_MEMORY_LEAKS
1548 void *tracked_malloc(size_t size, char *file, int line) {
1549 struct igheap *thisheap;
1552 block = malloc(size);
1553 if (block == NULL) return(block);
1555 thisheap = malloc(sizeof(struct igheap));
1556 if (thisheap == NULL) {
1561 thisheap->block = block;
1562 strcpy(thisheap->file, file);
1563 thisheap->line = line;
1565 begin_critical_section(S_DEBUGMEMLEAKS);
1566 thisheap->next = igheap;
1568 end_critical_section(S_DEBUGMEMLEAKS);
1574 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1575 struct igheap *thisheap;
1578 block = realloc(ptr, size);
1579 if (block == NULL) return(block);
1581 thisheap = malloc(sizeof(struct igheap));
1582 if (thisheap == NULL) {
1587 thisheap->block = block;
1588 strcpy(thisheap->file, file);
1589 thisheap->line = line;
1591 begin_critical_section(S_DEBUGMEMLEAKS);
1592 thisheap->next = igheap;
1594 end_critical_section(S_DEBUGMEMLEAKS);
1601 void tracked_free(void *ptr) {
1602 struct igheap *thisheap;
1603 struct igheap *trash;
1607 if (igheap == NULL) return;
1608 begin_critical_section(S_DEBUGMEMLEAKS);
1609 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1610 if (thisheap->next != NULL) {
1611 if (thisheap->next->block == ptr) {
1612 trash = thisheap->next;
1613 thisheap->next = thisheap->next->next;
1618 if (igheap->block == ptr) {
1620 igheap = igheap->next;
1623 end_critical_section(S_DEBUGMEMLEAKS);
1626 char *tracked_strdup(const char *s, char *file, int line) {
1629 if (s == NULL) return(NULL);
1630 ptr = tracked_malloc(strlen(s) + 1, file, line);
1631 if (ptr == NULL) return(NULL);
1632 strncpy(ptr, s, strlen(s));
1636 void dump_heap(void) {
1637 struct igheap *thisheap;
1639 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1640 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1641 thisheap->file, thisheap->line);
1645 #endif /* DEBUG_MEMORY_LEAKS */