2 * Citadel "system dependent" stuff.
3 * See COPYING for copyright information.
5 * Here's where we (hopefully) have most parts of the Citadel server that
6 * would need to be altered to run the server in a non-POSIX environment.
8 * If we ever port to a different platform and either have multiple
9 * variants of this file or simply load it up with #ifdefs.
20 #include <sys/types.h>
23 #include <sys/socket.h>
25 #include <sys/syslog.h>
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
32 # include <sys/time.h>
39 #include <sys/resource.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
50 #define SHOW_ME_VAPPEND_PRINTF
51 #include <libcitadel.h>
54 #include "sysdep_decls.h"
55 #include "citserver.h"
59 #include "housekeeping.h"
60 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
72 #include "ctdl_module.h"
78 #ifdef DEBUG_MEMORY_LEAKS
86 struct igheap *igheap = NULL;
90 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
92 int syslog_facility = LOG_DAEMON;
93 int enable_syslog = 0;
94 int print_to_logfile = 1;
97 * CtdlLogPrintf() ... Write logging information
99 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
101 va_start(arg_ptr, format);
102 vCtdlLogPrintf(loglevel, format, arg_ptr);
106 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
110 vsyslog((syslog_facility | loglevel), format, arg_ptr);
113 /* stderr output code */
114 if (enable_syslog || !print_to_logfile) return;
116 /* if we run in forground and syslog is disabled, log to terminal */
117 if (loglevel <= verbosity) {
121 CitContext *CCC = CC;
122 ThreadTSD *cTSD = CTP;
123 CtdlThreadNode *node = NULL;
133 if ((node != NULL) && (node->reltid != 0)) {
134 lwpid = node->reltid;
137 gettimeofday(&tv, NULL);
139 /* Promote to time_t; types differ on some OSes (like darwin) */
140 unixtime = tv.tv_sec;
141 localtime_r(&unixtime, &tim);
145 snprintf(LWP, 64, "[LWP:%ld] ", lwpid);
150 if (CCC->cs_pid != 0) {
151 snprintf(SESS, 64, " [%3d] ", CCC->cs_pid);
153 else if (CCC->user.usernum != 0) {
154 snprintf(SESS, 64, " [:%ld] ", CCC->user.usernum);
158 snprintf(formatbuf, SIZ,
159 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s%s%s",
160 tim.tm_year + 1900, tim.tm_mon + 1,
161 tim.tm_mday, tim.tm_hour, tim.tm_min,
162 tim.tm_sec, (long)tv.tv_usec,
166 vfprintf(stderr, formatbuf, arg_ptr);
174 * Signal handler to shut down the server.
177 volatile int exit_signal = 0;
178 volatile int shutdown_and_halt = 0;
179 volatile int restart_server = 0;
180 volatile int running_as_daemon = 0;
182 static RETSIGTYPE signal_cleanup(int signum) {
188 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
189 exit_signal = signum;
193 static RETSIGTYPE signal_exit(int signum) {
200 * Some initialization stuff...
202 void init_sysdep(void) {
205 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
209 getrlimit(RLIMIT_NOFILE, &rl);
210 rl.rlim_cur = FD_SETSIZE;
211 rl.rlim_max = FD_SETSIZE;
212 setrlimit(RLIMIT_NOFILE, &rl);
216 /* If we've got OpenSSL, we're going to use it. */
222 * Set up a place to put thread-specific data.
223 * We only need a single pointer per thread - it points to the
224 * CitContext structure (in the ContextList linked list) of the
225 * session to which the calling thread is currently bound.
227 if (citthread_key_create(&MyConKey, NULL) != 0) {
228 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
233 * The action for unexpected signals and exceptions should be to
234 * call signal_cleanup() to gracefully shut down the server.
237 sigaddset(&set, SIGINT); // intr = shutdown
238 // sigaddset(&set, SIGQUIT); // quit = force quit
239 sigaddset(&set, SIGHUP);
240 sigaddset(&set, SIGTERM);
241 // sigaddset(&set, SIGSEGV); // we want core dumps
242 // sigaddset(&set, SIGILL); // we want core dumps
243 // sigaddset(&set, SIGBUS);
244 sigprocmask(SIG_UNBLOCK, &set, NULL);
246 signal(SIGINT, signal_cleanup); // intr = shutdown
247 // signal(SIGQUIT, signal_cleanup); // quit = force quit
248 signal(SIGHUP, signal_cleanup);
249 signal(SIGTERM, signal_cleanup);
250 signal(SIGUSR2, signal_exit);
251 // signal(SIGSEGV, signal_cleanup); // we want coredumps
252 // signal(SIGILL, signal_cleanup); // we want core dumps
253 // signal(SIGBUS, signal_cleanup);
256 * Do not shut down the server on broken pipe signals, otherwise the
257 * whole Citadel service would come down whenever a single client
260 signal(SIGPIPE, SIG_IGN);
265 * This is a generic function to set up a master socket for listening on
266 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
268 * ip_addr IP address to bind
269 * port_number port number to bind
270 * queue_len number of incoming connections to allow in the queue
272 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
275 struct sockaddr_in6 sin6;
276 struct sockaddr_in sin4;
280 memset(&sin6, 0, sizeof(sin6));
281 memset(&sin4, 0, sizeof(sin4));
282 sin6.sin6_family = AF_INET6;
283 sin4.sin_family = AF_INET;
285 if ( (ip_addr == NULL) /* any IPv6 */
286 || (IsEmptyStr(ip_addr))
287 || (!strcmp(ip_addr, "*"))
290 sin6.sin6_addr = in6addr_any;
292 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
295 sin4.sin_addr.s_addr = INADDR_ANY;
297 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
300 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
301 snprintf(errormessage, SIZ,
302 "Error binding to [%s] : %s", ip_addr, strerror(errno)
304 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
308 else /* specific IPv6 */
311 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
312 snprintf(errormessage, SIZ,
313 "Error binding to [%s] : %s", ip_addr, strerror(errno)
315 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
320 if (port_number == 0) {
321 snprintf(errormessage, SIZ,
322 "Can't start: no port number specified."
324 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
327 sin6.sin6_port = htons((u_short) port_number);
328 sin4.sin_port = htons((u_short) port_number);
330 p = getprotobyname("tcp");
332 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
334 snprintf(errormessage, SIZ,
335 "Can't create a listening socket: %s", strerror(errno)
337 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
340 /* Set some socket options that make sense. */
342 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
344 if (ip_version == 6) {
345 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
348 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
352 snprintf(errormessage, SIZ,
353 "Can't bind: %s", strerror(errno)
355 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
359 fcntl(s, F_SETFL, O_NONBLOCK);
361 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
362 snprintf(errormessage, SIZ,
363 "Can't listen: %s", strerror(errno)
365 CtdlLogPrintf(CTDL_ALERT, "%s\n", errormessage);
376 * Create a Unix domain socket and listen on it
378 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
380 struct sockaddr_un addr;
383 int actual_queue_len;
384 #ifdef HAVE_STRUCT_UCRED
388 actual_queue_len = queue_len;
389 if (actual_queue_len < 5) actual_queue_len = 5;
391 i = unlink(sockpath);
392 if ((i != 0) && (errno != ENOENT)) {
393 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
394 sockpath, strerror(errno)
396 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
400 memset(&addr, 0, sizeof(addr));
401 addr.sun_family = AF_UNIX;
402 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
404 s = socket(AF_UNIX, SOCK_STREAM, 0);
406 snprintf(errormessage, SIZ,
407 "citserver: Can't create a socket: %s",
409 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
413 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
414 snprintf(errormessage, SIZ,
415 "citserver: Can't bind: %s",
417 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
421 /* set to nonblock - we need this for some obscure situations */
422 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
423 snprintf(errormessage, SIZ,
424 "citserver: Can't set socket to non-blocking: %s",
426 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
431 if (listen(s, actual_queue_len) < 0) {
432 snprintf(errormessage, SIZ,
433 "citserver: Can't listen: %s",
435 CtdlLogPrintf(CTDL_EMERG, "%s\n", errormessage);
439 #ifdef HAVE_STRUCT_UCRED
440 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
443 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
450 * The following functions implement output buffering on operating systems which
451 * support it (such as Linux and various BSD flavors).
455 # define HAVE_TCP_BUFFERING
458 # define HAVE_TCP_BUFFERING
459 # define TCP_CORK TCP_NOPUSH
461 #endif /* TCP_CORK */
462 #endif /* HAVE_DARWIN */
464 static unsigned on = 1, off = 0;
466 void buffer_output(void) {
467 #ifdef HAVE_TCP_BUFFERING
469 if (!CC->redirect_ssl)
471 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
475 void unbuffer_output(void) {
476 #ifdef HAVE_TCP_BUFFERING
478 if (!CC->redirect_ssl)
480 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
484 void flush_output(void) {
485 #ifdef HAVE_TCP_BUFFERING
486 struct CitContext *CCC = CC;
487 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
488 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
493 static void flush_client_inbuf(void)
497 FlushStrBuf(CCC->ReadBuf);
498 CCC->RecvBuf->ReadWritePointer = NULL;
504 * client_write() ... Send binary data to the client.
506 int client_write(const char *buf, int nbytes)
508 int bytes_written = 0;
510 #ifndef HAVE_TCP_BUFFERING
511 int old_buffer_len = 0;
517 if (nbytes < 1) return(0);
527 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
529 fd = fopen(fn, "a+");
530 fprintf(fd, "Sending: BufSize: %d BufContent: [",
532 rv = fwrite(buf, nbytes, 1, fd);
539 // flush_client_inbuf();
540 if (Ctx->redirect_buffer != NULL) {
541 StrBufAppendBufPlain(Ctx->redirect_buffer,
547 if (Ctx->redirect_ssl) {
548 client_write_ssl(buf, nbytes);
552 if (Ctx->client_socket == -1) return -1;
554 fdflags = fcntl(Ctx->client_socket, F_GETFL);
556 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
557 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
559 FD_SET(Ctx->client_socket, &wset);
560 if (select(1, NULL, &wset, NULL, NULL) == -1) {
563 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
564 if (CtdlThreadCheckStop()) {
568 /* can't trust fd's and stuff so we need to re-create them */
572 CtdlLogPrintf(CTDL_ERR,
573 "client_write(%d bytes) select failed: %s (%d)\n",
574 nbytes - bytes_written,
575 strerror(errno), errno);
583 retval = write(Ctx->client_socket, &buf[bytes_written],
584 nbytes - bytes_written);
586 CtdlLogPrintf(CTDL_ERR,
587 "client_write(%d bytes) failed: %s (%d)\n",
588 nbytes - bytes_written,
589 strerror(errno), errno);
591 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
595 bytes_written = bytes_written + retval;
600 void cputbuf(const StrBuf *Buf) {
601 client_write(ChrPtr(Buf), StrLength(Buf));
606 * cprintf() Send formatted printable data to the client.
607 * Implemented in terms of client_write() so it's technically not sysdep...
609 void cprintf(const char *format, ...) {
613 va_start(arg_ptr, format);
614 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
615 buf[sizeof buf - 2] = '\n';
616 client_write(buf, strlen(buf));
622 * Read data from the client socket.
624 * sock socket fd to read from
625 * buf buffer to read into
626 * bytes number of bytes to read
627 * timeout Number of seconds to wait before timing out
629 * Possible return values:
630 * 1 Requested number of bytes has been read.
631 * 0 Request timed out.
632 * -1 Connection is broken, or other error.
634 int client_read_blob(StrBuf *Target, int bytes, int timeout)
641 if (CCC->redirect_ssl) {
647 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
649 fd = fopen(fn, "a+");
650 fprintf(fd, "Reading BLOB: BufSize: %d ",
652 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
658 retval = client_read_sslblob(Target, bytes, timeout);
660 CtdlLogPrintf(CTDL_CRIT,
665 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
667 fd = fopen(fn, "a+");
668 fprintf(fd, "Read: %d BufContent: [",
670 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
685 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
687 fd = fopen(fn, "a+");
688 fprintf(fd, "Reading BLOB: BufSize: %d ",
690 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
696 retval = StrBufReadBLOBBuffered(Target,
698 &CCC->RecvBuf.ReadWritePointer,
705 CtdlLogPrintf(CTDL_CRIT,
712 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
714 fd = fopen(fn, "a+");
715 fprintf(fd, "Read: %d BufContent: [",
717 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
729 * to make client_read_random_blob() more efficient, increase buffer size.
730 * just use in greeting function, else your buffer may be flushed
732 void client_set_inbound_buf(long N)
735 FlushStrBuf(CCC->RecvBuf.Buf);
736 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
739 int client_read_random_blob(StrBuf *Target, int timeout)
744 rc = client_read_blob(Target, 1, timeout);
750 len = StrLength(CCC->RecvBuf.Buf);
751 pch = ChrPtr(CCC->RecvBuf.Buf);
755 if (CCC->RecvBuf.ReadWritePointer != NULL) {
756 len -= CCC->RecvBuf.ReadWritePointer - pch;
757 pch = CCC->RecvBuf.ReadWritePointer;
759 StrBufAppendBufPlain(Target, pch, len, 0);
760 FlushStrBuf(CCC->RecvBuf.Buf);
761 CCC->RecvBuf.ReadWritePointer = NULL;
768 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
770 fd = fopen(fn, "a+");
771 fprintf(fd, "Read: BufSize: %d BufContent: [",
773 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
781 return StrLength(Target);
789 int client_read_to(char *buf, int bytes, int timeout)
794 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
803 ChrPtr(CCC->MigrateBuf),
804 StrLength(CCC->MigrateBuf) + 1);
805 FlushStrBuf(CCC->MigrateBuf);
811 int HaveMoreLinesWaiting(CitContext *CCC)
813 if ((CCC->kill_me == 1) || (
814 (CCC->RecvBuf.ReadWritePointer == NULL) &&
815 (StrLength(CCC->RecvBuf.Buf) == 0) &&
816 (CCC->client_socket != -1)) )
824 * Read data from the client socket with default timeout.
825 * (This is implemented in terms of client_read_to() and could be
826 * justifiably moved out of sysdep.c)
828 INLINE int client_read(char *buf, int bytes)
830 return(client_read_to(buf, bytes, config.c_sleeping));
833 int CtdlClientGetLine(StrBuf *Target)
841 if (CCC->redirect_ssl) {
851 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
853 fd = fopen(fn, "a+");
854 pch = ChrPtr(CCC->RecvBuf.Buf);
855 len = StrLength(CCC->RecvBuf.Buf);
856 if (CCC->RecvBuf.ReadWritePointer != NULL)
857 rlen = CCC->RecvBuf.ReadWritePointer - pch;
861 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
864 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
867 rc = client_readline_sslbuffer(Target,
869 &CCC->RecvBuf.ReadWritePointer,
872 pch = ChrPtr(CCC->RecvBuf.Buf);
873 nlen = StrLength(CCC->RecvBuf.Buf);
874 if (CCC->RecvBuf.ReadWritePointer != NULL)
875 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
879 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
880 len, nlen, rlen, nrlen, pch);
882 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
883 len, nlen, rlen, nrlen);
885 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
886 StrLength(Target), ChrPtr(Target));
890 CtdlLogPrintf(CTDL_CRIT,
902 int len, rlen, nlen, nrlen;
905 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
907 fd = fopen(fn, "a+");
908 pch = ChrPtr(CCC->RecvBuf.Buf);
909 len = StrLength(CCC->RecvBuf.Buf);
910 if (CCC->RecvBuf.ReadWritePointer != NULL)
911 rlen = CCC->RecvBuf.ReadWritePointer - pch;
915 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
918 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
921 rc = StrBufTCP_read_buffered_line_fast(Target,
923 &CCC->RecvBuf.ReadWritePointer,
930 pch = ChrPtr(CCC->RecvBuf.Buf);
931 nlen = StrLength(CCC->RecvBuf.Buf);
932 if (CCC->RecvBuf.ReadWritePointer != NULL)
933 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
937 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
938 len, nlen, rlen, nrlen, pch);
940 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
941 len, nlen, rlen, nrlen);
943 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
944 StrLength(Target), ChrPtr(Target));
947 if ((rc < 0) && (Error != NULL))
948 CtdlLogPrintf(CTDL_CRIT,
959 * client_getln() ... Get a LF-terminated line of text from the client.
960 * (This is implemented in terms of client_read() and could be
961 * justifiably moved out of sysdep.c)
963 int client_getln(char *buf, int bufsize)
969 retval = CtdlClientGetLine(CCC->MigrateBuf);
974 i = StrLength(CCC->MigrateBuf);
975 pCh = ChrPtr(CCC->MigrateBuf);
976 /* Strip the trailing LF, and the trailing CR if present.
981 && ( (pCh[i - 1]==13)
982 || ( pCh[i - 1]==10)) ) {
988 FlushStrBuf(CCC->MigrateBuf);
990 safestrncpy(&buf[i], "000", bufsize - i);
997 * Cleanup any contexts that are left lying around
1001 void close_masters (void)
1003 struct ServiceFunctionHook *serviceptr;
1006 * close all protocol master sockets
1008 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1009 serviceptr = serviceptr->next ) {
1011 if (serviceptr->tcp_port > 0)
1013 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
1014 serviceptr->tcp_port);
1015 serviceptr->tcp_port = 0;
1018 if (serviceptr->sockpath != NULL)
1019 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
1020 serviceptr->sockpath);
1022 close(serviceptr->msock);
1023 /* If it's a Unix domain socket, remove the file. */
1024 if (serviceptr->sockpath != NULL) {
1025 unlink(serviceptr->sockpath);
1026 serviceptr->sockpath = NULL;
1033 * The system-dependent part of master_cleanup() - close the master socket.
1035 void sysdep_master_cleanup(void) {
1044 CtdlDestroyProtoHooks();
1045 CtdlDestroyDeleteHooks();
1046 CtdlDestroyXmsgHooks();
1047 CtdlDestroyNetprocHooks();
1048 CtdlDestroyUserHooks();
1049 CtdlDestroyMessageHook();
1050 CtdlDestroyCleanupHooks();
1051 CtdlDestroyFixedOutputHooks();
1052 CtdlDestroySessionHooks();
1053 CtdlDestroyServiceHook();
1054 CtdlDestroyRoomHooks();
1055 CtdlDestroySearchHooks();
1056 #ifdef HAVE_BACKTRACE
1057 /// eCrash_Uninit();
1063 pid_t current_child;
1064 void graceful_shutdown(int signum) {
1065 kill(current_child, signum);
1066 unlink(file_pid_file);
1071 int nFireUpsNonRestart = 0;
1072 pid_t ForkedPid = 1;
1075 * Start running as a daemon.
1077 void start_daemon(int unused) {
1085 /* Close stdin/stdout/stderr and replace them with /dev/null.
1086 * We don't just call close() because we don't want these fd's
1087 * to be reused for other files.
1089 if (chdir(ctdl_run_dir) != 0)
1090 CtdlLogPrintf(CTDL_EMERG,
1091 "unable to change into directory [%s]: %s",
1092 ctdl_run_dir, strerror(errno));
1099 signal(SIGHUP, SIG_IGN);
1100 signal(SIGINT, SIG_IGN);
1101 signal(SIGQUIT, SIG_IGN);
1105 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1106 (freopen("/dev/null", "w", stdout) != stdout) ||
1107 (freopen("/dev/null", "w", stderr) != stderr))
1108 CtdlLogPrintf(CTDL_EMERG,
1109 "unable to reopen stdin/out/err %s",
1114 current_child = fork();
1116 signal(SIGTERM, graceful_shutdown);
1118 if (current_child < 0) {
1123 else if (current_child == 0) {
1124 return; /* continue starting citadel. */
1128 fp = fopen(file_pid_file, "w");
1130 fprintf(fp, ""F_PID_T"\n", getpid());
1133 waitpid(current_child, &status, 0);
1136 nFireUpsNonRestart = nFireUps;
1138 /* Exit code 0 means the watcher should exit */
1139 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1143 /* Exit code 101-109 means the watcher should exit */
1144 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1148 /* Any other exit code, or no exit code, means we should restart. */
1152 ForkedPid = current_child;
1155 } while (do_restart);
1157 unlink(file_pid_file);
1158 exit(WEXITSTATUS(status));
1163 void checkcrash(void)
1165 if (nFireUpsNonRestart != nFireUps)
1169 CrashMail = NewStrBuf();
1170 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1171 StrBufPrintf(CrashMail,
1173 " The Citadel server process (citserver) terminated unexpectedly."
1175 " This could be the result of a bug in the server program, or some external "
1177 " You can obtain more information about this by enabling core dumps.\n \n"
1178 " For more information, please see:\n \n"
1179 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1182 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1184 ctdl_run_dir, ForkedPid);
1185 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1186 FreeStrBuf(&CrashMail);
1192 * Generic routine to convert a login name to a full name (gecos)
1193 * Returns nonzero if a conversion took place
1195 int convert_login(char NameToConvert[]) {
1199 pw = getpwnam(NameToConvert);
1204 strcpy(NameToConvert, pw->pw_gecos);
1205 for (a=0; a<strlen(NameToConvert); ++a) {
1206 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1215 * This loop just keeps going and going and going...
1219 * This current implimentation of worker_thread creates a bottle neck in several situations
1220 * The first thing to remember is that a single thread can handle more than one connection at a time.
1221 * More threads mean less memory for the system to run in.
1222 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1223 * something to happen anywhere.
1224 * This current implimentation requires worker threads to wait in other locations, after it has
1225 * been committed to a single connection which is very wasteful.
1226 * As an extreme case consider this:
1227 * A slow client connects and this slow client sends only one character each second.
1228 * With this current implimentation a single worker thread is dispatched to handle that connection
1229 * until such times as the client timeout expires, an error occurs on the socket or the client
1230 * completes its transmission.
1231 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1232 * second interval between chars.
1234 * It is my intention to re-write this code and the associated client_getln, client_read functions
1235 * to allow any thread to read data on behalf of any connection (context).
1236 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1237 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1239 * This worker thread loop also needs to be able to handle binary data.
1242 void *worker_thread(void *arg) {
1245 CitContext *bind_me = NULL;
1249 int force_purge = 0;
1252 while (!CtdlThreadCheckStop()) {
1254 /* make doubly sure we're not holding any stale db handles
1255 * which might cause a deadlock.
1257 cdb_check_handles();
1258 do_select: force_purge = 0;
1259 bind_me = NULL; /* Which session shall we handle? */
1261 /* Initialize the fdset. */
1265 begin_critical_section(S_SESSION_TABLE);
1266 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1268 client_socket = ptr->client_socket;
1269 /* Dont select on dead sessions only truly idle ones */
1270 if ((ptr->state == CON_IDLE) &&
1271 (CC->kill_me == 0) &&
1272 (client_socket != -1))
1274 FD_SET(client_socket, &readfds);
1275 if (client_socket > highest)
1276 highest = client_socket;
1278 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1280 ptr->state = CON_EXECUTING;
1283 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1285 ptr->state = CON_STARTING;
1289 end_critical_section(S_SESSION_TABLE);
1295 /* If we got this far, it means that there are no sessions
1296 * which a previous thread marked for attention, so we go
1297 * ahead and get ready to select().
1300 if (!CtdlThreadCheckStop()) {
1301 tv.tv_sec = 1; /* wake up every second if no input */
1303 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1308 /* Now figure out who made this select() unblock.
1309 * First, check for an error or exit condition.
1312 if (errno == EBADF) {
1313 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1317 if (errno != EINTR) {
1318 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1319 CtdlThreadStopAll();
1322 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1323 if (CtdlThreadCheckStop()) return(NULL);
1327 else if(retval == 0) {
1328 if (CtdlThreadCheckStop()) return(NULL);
1331 /* It must be a client socket. Find a context that has data
1332 * waiting on its socket *and* is in the CON_IDLE state. Any
1333 * active sockets other than our chosen one are marked as
1334 * CON_READY so the next thread that comes around can just bind
1335 * to one without having to select() again.
1337 begin_critical_section(S_SESSION_TABLE);
1338 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1339 int checkfd = ptr->client_socket;
1340 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1341 if (FD_ISSET(checkfd, &readfds)) {
1342 ptr->input_waiting = 1;
1344 bind_me = ptr; /* I choose you! */
1345 bind_me->state = CON_EXECUTING;
1348 ptr->state = CON_READY;
1350 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1352 bind_me = ptr; /* I choose you! */
1353 bind_me->state = CON_EXECUTING;
1356 ptr->state = CON_READY;
1361 end_critical_section(S_SESSION_TABLE);
1364 /* We're bound to a session */
1365 if (bind_me != NULL) {
1366 become_session(bind_me);
1368 if (bind_me->state == CON_STARTING) {
1369 bind_me->state = CON_EXECUTING;
1370 begin_session(bind_me);
1371 bind_me->h_greeting_function();
1373 /* If the client has sent a command, execute it. */
1374 if (CC->input_waiting) {
1375 CC->h_command_function();
1377 while (HaveMoreLinesWaiting(CC))
1378 CC->h_command_function();
1380 CC->input_waiting = 0;
1383 /* If there are asynchronous messages waiting and the
1384 * client supports it, do those now */
1385 if ((CC->is_async) && (CC->async_waiting)
1386 && (CC->h_async_function != NULL)) {
1387 CC->h_async_function();
1388 CC->async_waiting = 0;
1391 force_purge = CC->kill_me;
1392 become_session(NULL);
1393 bind_me->state = CON_IDLE;
1396 dead_session_purge(force_purge);
1399 /* If control reaches this point, the server is shutting down */
1407 * A function to handle selecting on master sockets.
1408 * In other words it handles new connections.
1411 void *select_on_master (void *arg)
1413 struct ServiceFunctionHook *serviceptr;
1417 int ssock; /* Descriptor for client socket */
1418 CitContext *con= NULL; /* Temporary context pointer */
1422 struct CitContext select_on_master_CC;
1424 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1425 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1427 while (!CtdlThreadCheckStop()) {
1428 /* Initialize the fdset. */
1429 FD_ZERO(&master_fds);
1432 /* First, add the various master sockets to the fdset. */
1433 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1434 serviceptr = serviceptr->next ) {
1435 m = serviceptr->msock;
1436 FD_SET(m, &master_fds);
1442 if (!CtdlThreadCheckStop()) {
1443 tv.tv_sec = 60; /* wake up every second if no input */
1445 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1450 /* Now figure out who made this select() unblock.
1451 * First, check for an error or exit condition.
1454 if (errno == EBADF) {
1455 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1459 if (errno != EINTR) {
1460 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1461 CtdlThreadStopAll();
1463 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1464 if (CtdlThreadCheckStop()) return(NULL);
1468 else if(retval == 0) {
1469 if (CtdlThreadCheckStop()) return(NULL);
1472 /* Next, check to see if it's a new client connecting
1473 * on a master socket.
1475 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1476 serviceptr = serviceptr->next ) {
1478 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1479 ssock = accept(serviceptr->msock, NULL, 0);
1481 CtdlLogPrintf(CTDL_DEBUG,
1482 "New client socket %d\n",
1485 /* The master socket is non-blocking but the client
1486 * sockets need to be blocking, otherwise certain
1487 * operations barf on FreeBSD. Not a fatal error.
1489 if (fcntl(ssock, F_SETFL, 0) < 0) {
1490 CtdlLogPrintf(CTDL_EMERG,
1491 "citserver: Can't set socket to blocking: %s\n",
1495 /* New context will be created already
1496 * set up in the CON_EXECUTING state.
1498 con = CreateNewContext();
1500 /* Assign our new socket number to it. */
1501 con->client_socket = ssock;
1502 con->h_command_function =
1503 serviceptr->h_command_function;
1504 con->h_async_function =
1505 serviceptr->h_async_function;
1506 con->h_greeting_function = serviceptr->h_greeting_function;
1508 serviceptr->ServiceName;
1510 /* Determine whether it's a local socket */
1511 if (serviceptr->sockpath != NULL)
1512 con->is_local_socket = 1;
1514 /* Set the SO_REUSEADDR socket option */
1516 setsockopt(ssock, SOL_SOCKET,
1520 con->state = CON_GREETING;
1529 CtdlClearSystemContext();
1538 * Translate text facility name to syslog.h defined value.
1540 int SyslogFacility(char *name)
1549 { LOG_KERN, "kern" },
1550 { LOG_USER, "user" },
1551 { LOG_MAIL, "mail" },
1552 { LOG_DAEMON, "daemon" },
1553 { LOG_AUTH, "auth" },
1554 { LOG_SYSLOG, "syslog" },
1556 { LOG_NEWS, "news" },
1557 { LOG_UUCP, "uucp" },
1558 { LOG_LOCAL0, "local0" },
1559 { LOG_LOCAL1, "local1" },
1560 { LOG_LOCAL2, "local2" },
1561 { LOG_LOCAL3, "local3" },
1562 { LOG_LOCAL4, "local4" },
1563 { LOG_LOCAL5, "local5" },
1564 { LOG_LOCAL6, "local6" },
1565 { LOG_LOCAL7, "local7" },
1568 for(i = 0; facTbl[i].name != NULL; i++) {
1569 if(!strcasecmp(name, facTbl[i].name))
1570 return facTbl[i].facility;
1577 /********** MEM CHEQQER ***********/
1579 #ifdef DEBUG_MEMORY_LEAKS
1586 void *tracked_malloc(size_t size, char *file, int line) {
1587 struct igheap *thisheap;
1590 block = malloc(size);
1591 if (block == NULL) return(block);
1593 thisheap = malloc(sizeof(struct igheap));
1594 if (thisheap == NULL) {
1599 thisheap->block = block;
1600 strcpy(thisheap->file, file);
1601 thisheap->line = line;
1603 begin_critical_section(S_DEBUGMEMLEAKS);
1604 thisheap->next = igheap;
1606 end_critical_section(S_DEBUGMEMLEAKS);
1612 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1613 struct igheap *thisheap;
1616 block = realloc(ptr, size);
1617 if (block == NULL) return(block);
1619 thisheap = malloc(sizeof(struct igheap));
1620 if (thisheap == NULL) {
1625 thisheap->block = block;
1626 strcpy(thisheap->file, file);
1627 thisheap->line = line;
1629 begin_critical_section(S_DEBUGMEMLEAKS);
1630 thisheap->next = igheap;
1632 end_critical_section(S_DEBUGMEMLEAKS);
1639 void tracked_free(void *ptr) {
1640 struct igheap *thisheap;
1641 struct igheap *trash;
1645 if (igheap == NULL) return;
1646 begin_critical_section(S_DEBUGMEMLEAKS);
1647 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1648 if (thisheap->next != NULL) {
1649 if (thisheap->next->block == ptr) {
1650 trash = thisheap->next;
1651 thisheap->next = thisheap->next->next;
1656 if (igheap->block == ptr) {
1658 igheap = igheap->next;
1661 end_critical_section(S_DEBUGMEMLEAKS);
1664 char *tracked_strdup(const char *s, char *file, int line) {
1667 if (s == NULL) return(NULL);
1668 ptr = tracked_malloc(strlen(s) + 1, file, line);
1669 if (ptr == NULL) return(NULL);
1670 strncpy(ptr, s, strlen(s));
1674 void dump_heap(void) {
1675 struct igheap *thisheap;
1677 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1678 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1679 thisheap->file, thisheap->line);
1683 #endif /* DEBUG_MEMORY_LEAKS */