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+");
532 fprintf(fd, "Sending: BufSize: %d BufContent: [",
534 rv = fwrite(buf, nbytes, 1, fd);
540 // flush_client_inbuf();
541 if (Ctx->redirect_buffer != NULL) {
542 StrBufAppendBufPlain(Ctx->redirect_buffer,
548 if (Ctx->redirect_ssl) {
549 client_write_ssl(buf, nbytes);
553 if (Ctx->client_socket == -1) return -1;
555 fdflags = fcntl(Ctx->client_socket, F_GETFL);
557 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
558 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
560 FD_SET(Ctx->client_socket, &wset);
561 if (select(1, NULL, &wset, NULL, NULL) == -1) {
564 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
565 if (CtdlThreadCheckStop()) {
569 /* can't trust fd's and stuff so we need to re-create them */
573 CtdlLogPrintf(CTDL_ERR,
574 "client_write(%d bytes) select failed: %s (%d)\n",
575 nbytes - bytes_written,
576 strerror(errno), errno);
584 retval = write(Ctx->client_socket, &buf[bytes_written],
585 nbytes - bytes_written);
587 CtdlLogPrintf(CTDL_ERR,
588 "client_write(%d bytes) failed: %s (%d)\n",
589 nbytes - bytes_written,
590 strerror(errno), errno);
592 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
596 bytes_written = bytes_written + retval;
601 void cputbuf(const StrBuf *Buf) {
602 client_write(ChrPtr(Buf), StrLength(Buf));
607 * cprintf() Send formatted printable data to the client.
608 * Implemented in terms of client_write() so it's technically not sysdep...
610 void cprintf(const char *format, ...) {
614 va_start(arg_ptr, format);
615 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
616 buf[sizeof buf - 2] = '\n';
617 client_write(buf, strlen(buf));
623 * Read data from the client socket.
625 * sock socket fd to read from
626 * buf buffer to read into
627 * bytes number of bytes to read
628 * timeout Number of seconds to wait before timing out
630 * Possible return values:
631 * 1 Requested number of bytes has been read.
632 * 0 Request timed out.
633 * -1 Connection is broken, or other error.
635 int client_read_blob(StrBuf *Target, int bytes, int timeout)
642 if (CCC->redirect_ssl) {
648 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
650 fd = fopen(fn, "a+");
651 fprintf(fd, "Reading BLOB: BufSize: %d ",
653 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
659 retval = client_read_sslblob(Target, bytes, timeout);
661 CtdlLogPrintf(CTDL_CRIT,
666 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
668 fd = fopen(fn, "a+");
669 fprintf(fd, "Read: %d BufContent: [",
671 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
686 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
688 fd = fopen(fn, "a+");
689 fprintf(fd, "Reading BLOB: BufSize: %d ",
691 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
697 retval = StrBufReadBLOBBuffered(Target,
699 &CCC->RecvBuf.ReadWritePointer,
706 CtdlLogPrintf(CTDL_CRIT,
713 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
715 fd = fopen(fn, "a+");
716 fprintf(fd, "Read: %d BufContent: [",
718 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
730 * to make client_read_random_blob() more efficient, increase buffer size.
731 * just use in greeting function, else your buffer may be flushed
733 void client_set_inbound_buf(long N)
736 FlushStrBuf(CCC->RecvBuf.Buf);
737 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
740 int client_read_random_blob(StrBuf *Target, int timeout)
745 rc = client_read_blob(Target, 1, timeout);
751 len = StrLength(CCC->RecvBuf.Buf);
752 pch = ChrPtr(CCC->RecvBuf.Buf);
756 if (CCC->RecvBuf.ReadWritePointer != NULL) {
757 len -= CCC->RecvBuf.ReadWritePointer - pch;
758 pch = CCC->RecvBuf.ReadWritePointer;
760 StrBufAppendBufPlain(Target, pch, len, 0);
761 FlushStrBuf(CCC->RecvBuf.Buf);
762 CCC->RecvBuf.ReadWritePointer = NULL;
769 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
771 fd = fopen(fn, "a+");
772 fprintf(fd, "Read: BufSize: %d BufContent: [",
774 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
782 return StrLength(Target);
790 int client_read_to(char *buf, int bytes, int timeout)
795 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
804 ChrPtr(CCC->MigrateBuf),
805 StrLength(CCC->MigrateBuf) + 1);
806 FlushStrBuf(CCC->MigrateBuf);
812 int HaveMoreLinesWaiting(CitContext *CCC)
814 if ((CCC->kill_me == 1) || (
815 (CCC->RecvBuf.ReadWritePointer == NULL) &&
816 (StrLength(CCC->RecvBuf.Buf) == 0) &&
817 (CCC->client_socket != -1)) )
825 * Read data from the client socket with default timeout.
826 * (This is implemented in terms of client_read_to() and could be
827 * justifiably moved out of sysdep.c)
829 INLINE int client_read(char *buf, int bytes)
831 return(client_read_to(buf, bytes, config.c_sleeping));
834 int CtdlClientGetLine(StrBuf *Target)
842 if (CCC->redirect_ssl) {
852 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
854 fd = fopen(fn, "a+");
855 pch = ChrPtr(CCC->RecvBuf.Buf);
856 len = StrLength(CCC->RecvBuf.Buf);
857 if (CCC->RecvBuf.ReadWritePointer != NULL)
858 rlen = CCC->RecvBuf.ReadWritePointer - pch;
862 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
865 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
868 rc = client_readline_sslbuffer(Target,
870 &CCC->RecvBuf.ReadWritePointer,
873 pch = ChrPtr(CCC->RecvBuf.Buf);
874 nlen = StrLength(CCC->RecvBuf.Buf);
875 if (CCC->RecvBuf.ReadWritePointer != NULL)
876 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
880 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
881 len, nlen, rlen, nrlen, pch);
883 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
884 len, nlen, rlen, nrlen);
886 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
887 StrLength(Target), ChrPtr(Target));
891 CtdlLogPrintf(CTDL_CRIT,
903 int len, rlen, nlen, nrlen;
906 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
908 fd = fopen(fn, "a+");
909 pch = ChrPtr(CCC->RecvBuf.Buf);
910 len = StrLength(CCC->RecvBuf.Buf);
911 if (CCC->RecvBuf.ReadWritePointer != NULL)
912 rlen = CCC->RecvBuf.ReadWritePointer - pch;
916 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
919 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
922 rc = StrBufTCP_read_buffered_line_fast(Target,
924 &CCC->RecvBuf.ReadWritePointer,
931 pch = ChrPtr(CCC->RecvBuf.Buf);
932 nlen = StrLength(CCC->RecvBuf.Buf);
933 if (CCC->RecvBuf.ReadWritePointer != NULL)
934 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
938 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
939 len, nlen, rlen, nrlen, pch);
941 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
942 len, nlen, rlen, nrlen);
944 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
945 StrLength(Target), ChrPtr(Target));
948 if ((rc < 0) && (Error != NULL))
949 CtdlLogPrintf(CTDL_CRIT,
960 * client_getln() ... Get a LF-terminated line of text from the client.
961 * (This is implemented in terms of client_read() and could be
962 * justifiably moved out of sysdep.c)
964 int client_getln(char *buf, int bufsize)
970 retval = CtdlClientGetLine(CCC->MigrateBuf);
975 i = StrLength(CCC->MigrateBuf);
976 pCh = ChrPtr(CCC->MigrateBuf);
977 /* Strip the trailing LF, and the trailing CR if present.
982 && ( (pCh[i - 1]==13)
983 || ( pCh[i - 1]==10)) ) {
989 FlushStrBuf(CCC->MigrateBuf);
991 safestrncpy(&buf[i], "000", bufsize - i);
998 * Cleanup any contexts that are left lying around
1002 void close_masters (void)
1004 struct ServiceFunctionHook *serviceptr;
1007 * close all protocol master sockets
1009 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1010 serviceptr = serviceptr->next ) {
1012 if (serviceptr->tcp_port > 0)
1014 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
1015 serviceptr->tcp_port);
1016 serviceptr->tcp_port = 0;
1019 if (serviceptr->sockpath != NULL)
1020 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
1021 serviceptr->sockpath);
1023 close(serviceptr->msock);
1024 /* If it's a Unix domain socket, remove the file. */
1025 if (serviceptr->sockpath != NULL) {
1026 unlink(serviceptr->sockpath);
1027 serviceptr->sockpath = NULL;
1034 * The system-dependent part of master_cleanup() - close the master socket.
1036 void sysdep_master_cleanup(void) {
1045 CtdlDestroyProtoHooks();
1046 CtdlDestroyDeleteHooks();
1047 CtdlDestroyXmsgHooks();
1048 CtdlDestroyNetprocHooks();
1049 CtdlDestroyUserHooks();
1050 CtdlDestroyMessageHook();
1051 CtdlDestroyCleanupHooks();
1052 CtdlDestroyFixedOutputHooks();
1053 CtdlDestroySessionHooks();
1054 CtdlDestroyServiceHook();
1055 CtdlDestroyRoomHooks();
1056 CtdlDestroySearchHooks();
1057 #ifdef HAVE_BACKTRACE
1058 /// eCrash_Uninit();
1064 pid_t current_child;
1065 void graceful_shutdown(int signum) {
1066 kill(current_child, signum);
1067 unlink(file_pid_file);
1072 int nFireUpsNonRestart = 0;
1073 pid_t ForkedPid = 1;
1076 * Start running as a daemon.
1078 void start_daemon(int unused) {
1086 /* Close stdin/stdout/stderr and replace them with /dev/null.
1087 * We don't just call close() because we don't want these fd's
1088 * to be reused for other files.
1090 if (chdir(ctdl_run_dir) != 0)
1091 CtdlLogPrintf(CTDL_EMERG,
1092 "unable to change into directory [%s]: %s",
1093 ctdl_run_dir, strerror(errno));
1100 signal(SIGHUP, SIG_IGN);
1101 signal(SIGINT, SIG_IGN);
1102 signal(SIGQUIT, SIG_IGN);
1106 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1107 (freopen("/dev/null", "w", stdout) != stdout) ||
1108 (freopen("/dev/null", "w", stderr) != stderr))
1109 CtdlLogPrintf(CTDL_EMERG,
1110 "unable to reopen stdin/out/err %s",
1115 current_child = fork();
1117 signal(SIGTERM, graceful_shutdown);
1119 if (current_child < 0) {
1124 else if (current_child == 0) {
1125 return; /* continue starting citadel. */
1129 fp = fopen(file_pid_file, "w");
1131 fprintf(fp, ""F_PID_T"\n", getpid());
1134 waitpid(current_child, &status, 0);
1137 nFireUpsNonRestart = nFireUps;
1139 /* Exit code 0 means the watcher should exit */
1140 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1144 /* Exit code 101-109 means the watcher should exit */
1145 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1149 /* Any other exit code, or no exit code, means we should restart. */
1153 ForkedPid = current_child;
1156 } while (do_restart);
1158 unlink(file_pid_file);
1159 exit(WEXITSTATUS(status));
1164 void checkcrash(void)
1166 if (nFireUpsNonRestart != nFireUps)
1170 CrashMail = NewStrBuf();
1171 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1172 StrBufPrintf(CrashMail,
1174 " The Citadel server process (citserver) terminated unexpectedly."
1176 " This could be the result of a bug in the server program, or some external "
1178 " You can obtain more information about this by enabling core dumps.\n \n"
1179 " For more information, please see:\n \n"
1180 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1183 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1185 ctdl_run_dir, ForkedPid);
1186 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1187 FreeStrBuf(&CrashMail);
1193 * Generic routine to convert a login name to a full name (gecos)
1194 * Returns nonzero if a conversion took place
1196 int convert_login(char NameToConvert[]) {
1200 pw = getpwnam(NameToConvert);
1205 strcpy(NameToConvert, pw->pw_gecos);
1206 for (a=0; a<strlen(NameToConvert); ++a) {
1207 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1216 * This loop just keeps going and going and going...
1220 * This current implimentation of worker_thread creates a bottle neck in several situations
1221 * The first thing to remember is that a single thread can handle more than one connection at a time.
1222 * More threads mean less memory for the system to run in.
1223 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1224 * something to happen anywhere.
1225 * This current implimentation requires worker threads to wait in other locations, after it has
1226 * been committed to a single connection which is very wasteful.
1227 * As an extreme case consider this:
1228 * A slow client connects and this slow client sends only one character each second.
1229 * With this current implimentation a single worker thread is dispatched to handle that connection
1230 * until such times as the client timeout expires, an error occurs on the socket or the client
1231 * completes its transmission.
1232 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1233 * second interval between chars.
1235 * It is my intention to re-write this code and the associated client_getln, client_read functions
1236 * to allow any thread to read data on behalf of any connection (context).
1237 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1238 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1240 * This worker thread loop also needs to be able to handle binary data.
1243 void *worker_thread(void *arg) {
1246 CitContext *bind_me = NULL;
1250 int force_purge = 0;
1253 while (!CtdlThreadCheckStop()) {
1255 /* make doubly sure we're not holding any stale db handles
1256 * which might cause a deadlock.
1258 cdb_check_handles();
1259 do_select: force_purge = 0;
1260 bind_me = NULL; /* Which session shall we handle? */
1262 /* Initialize the fdset. */
1266 begin_critical_section(S_SESSION_TABLE);
1267 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1269 client_socket = ptr->client_socket;
1270 /* Dont select on dead sessions only truly idle ones */
1271 if ((ptr->state == CON_IDLE) &&
1272 (CC->kill_me == 0) &&
1273 (client_socket != -1))
1275 FD_SET(client_socket, &readfds);
1276 if (client_socket > highest)
1277 highest = client_socket;
1279 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1281 ptr->state = CON_EXECUTING;
1284 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1286 ptr->state = CON_STARTING;
1290 end_critical_section(S_SESSION_TABLE);
1296 /* If we got this far, it means that there are no sessions
1297 * which a previous thread marked for attention, so we go
1298 * ahead and get ready to select().
1301 if (!CtdlThreadCheckStop()) {
1302 tv.tv_sec = 1; /* wake up every second if no input */
1304 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1309 /* Now figure out who made this select() unblock.
1310 * First, check for an error or exit condition.
1313 if (errno == EBADF) {
1314 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1318 if (errno != EINTR) {
1319 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1320 CtdlThreadStopAll();
1323 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1324 if (CtdlThreadCheckStop()) return(NULL);
1328 else if(retval == 0) {
1329 if (CtdlThreadCheckStop()) return(NULL);
1332 /* It must be a client socket. Find a context that has data
1333 * waiting on its socket *and* is in the CON_IDLE state. Any
1334 * active sockets other than our chosen one are marked as
1335 * CON_READY so the next thread that comes around can just bind
1336 * to one without having to select() again.
1338 begin_critical_section(S_SESSION_TABLE);
1339 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1340 int checkfd = ptr->client_socket;
1341 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1342 if (FD_ISSET(checkfd, &readfds)) {
1343 ptr->input_waiting = 1;
1345 bind_me = ptr; /* I choose you! */
1346 bind_me->state = CON_EXECUTING;
1349 ptr->state = CON_READY;
1351 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1353 bind_me = ptr; /* I choose you! */
1354 bind_me->state = CON_EXECUTING;
1357 ptr->state = CON_READY;
1362 end_critical_section(S_SESSION_TABLE);
1365 /* We're bound to a session */
1366 if (bind_me != NULL) {
1367 become_session(bind_me);
1369 if (bind_me->state == CON_STARTING) {
1370 bind_me->state = CON_EXECUTING;
1371 begin_session(bind_me);
1372 bind_me->h_greeting_function();
1374 /* If the client has sent a command, execute it. */
1375 if (CC->input_waiting) {
1376 CC->h_command_function();
1378 while (HaveMoreLinesWaiting(CC))
1379 CC->h_command_function();
1381 CC->input_waiting = 0;
1384 /* If there are asynchronous messages waiting and the
1385 * client supports it, do those now */
1386 if ((CC->is_async) && (CC->async_waiting)
1387 && (CC->h_async_function != NULL)) {
1388 CC->h_async_function();
1389 CC->async_waiting = 0;
1392 force_purge = CC->kill_me;
1393 become_session(NULL);
1394 bind_me->state = CON_IDLE;
1397 dead_session_purge(force_purge);
1400 /* If control reaches this point, the server is shutting down */
1408 * A function to handle selecting on master sockets.
1409 * In other words it handles new connections.
1412 void *select_on_master (void *arg)
1414 struct ServiceFunctionHook *serviceptr;
1418 int ssock; /* Descriptor for client socket */
1419 CitContext *con= NULL; /* Temporary context pointer */
1423 struct CitContext select_on_master_CC;
1425 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1426 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1428 while (!CtdlThreadCheckStop()) {
1429 /* Initialize the fdset. */
1430 FD_ZERO(&master_fds);
1433 /* First, add the various master sockets to the fdset. */
1434 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1435 serviceptr = serviceptr->next ) {
1436 m = serviceptr->msock;
1437 FD_SET(m, &master_fds);
1443 if (!CtdlThreadCheckStop()) {
1444 tv.tv_sec = 60; /* wake up every second if no input */
1446 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1451 /* Now figure out who made this select() unblock.
1452 * First, check for an error or exit condition.
1455 if (errno == EBADF) {
1456 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1460 if (errno != EINTR) {
1461 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1462 CtdlThreadStopAll();
1464 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1465 if (CtdlThreadCheckStop()) return(NULL);
1469 else if(retval == 0) {
1470 if (CtdlThreadCheckStop()) return(NULL);
1473 /* Next, check to see if it's a new client connecting
1474 * on a master socket.
1476 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1477 serviceptr = serviceptr->next ) {
1479 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1480 ssock = accept(serviceptr->msock, NULL, 0);
1482 CtdlLogPrintf(CTDL_DEBUG,
1483 "New client socket %d\n",
1486 /* The master socket is non-blocking but the client
1487 * sockets need to be blocking, otherwise certain
1488 * operations barf on FreeBSD. Not a fatal error.
1490 if (fcntl(ssock, F_SETFL, 0) < 0) {
1491 CtdlLogPrintf(CTDL_EMERG,
1492 "citserver: Can't set socket to blocking: %s\n",
1496 /* New context will be created already
1497 * set up in the CON_EXECUTING state.
1499 con = CreateNewContext();
1501 /* Assign our new socket number to it. */
1502 con->client_socket = ssock;
1503 con->h_command_function =
1504 serviceptr->h_command_function;
1505 con->h_async_function =
1506 serviceptr->h_async_function;
1507 con->h_greeting_function = serviceptr->h_greeting_function;
1509 serviceptr->ServiceName;
1511 /* Determine whether it's a local socket */
1512 if (serviceptr->sockpath != NULL)
1513 con->is_local_socket = 1;
1515 /* Set the SO_REUSEADDR socket option */
1517 setsockopt(ssock, SOL_SOCKET,
1521 con->state = CON_GREETING;
1530 CtdlClearSystemContext();
1539 * Translate text facility name to syslog.h defined value.
1541 int SyslogFacility(char *name)
1550 { LOG_KERN, "kern" },
1551 { LOG_USER, "user" },
1552 { LOG_MAIL, "mail" },
1553 { LOG_DAEMON, "daemon" },
1554 { LOG_AUTH, "auth" },
1555 { LOG_SYSLOG, "syslog" },
1557 { LOG_NEWS, "news" },
1558 { LOG_UUCP, "uucp" },
1559 { LOG_LOCAL0, "local0" },
1560 { LOG_LOCAL1, "local1" },
1561 { LOG_LOCAL2, "local2" },
1562 { LOG_LOCAL3, "local3" },
1563 { LOG_LOCAL4, "local4" },
1564 { LOG_LOCAL5, "local5" },
1565 { LOG_LOCAL6, "local6" },
1566 { LOG_LOCAL7, "local7" },
1569 for(i = 0; facTbl[i].name != NULL; i++) {
1570 if(!strcasecmp(name, facTbl[i].name))
1571 return facTbl[i].facility;
1578 /********** MEM CHEQQER ***********/
1580 #ifdef DEBUG_MEMORY_LEAKS
1587 void *tracked_malloc(size_t size, char *file, int line) {
1588 struct igheap *thisheap;
1591 block = malloc(size);
1592 if (block == NULL) return(block);
1594 thisheap = malloc(sizeof(struct igheap));
1595 if (thisheap == NULL) {
1600 thisheap->block = block;
1601 strcpy(thisheap->file, file);
1602 thisheap->line = line;
1604 begin_critical_section(S_DEBUGMEMLEAKS);
1605 thisheap->next = igheap;
1607 end_critical_section(S_DEBUGMEMLEAKS);
1613 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1614 struct igheap *thisheap;
1617 block = realloc(ptr, size);
1618 if (block == NULL) return(block);
1620 thisheap = malloc(sizeof(struct igheap));
1621 if (thisheap == NULL) {
1626 thisheap->block = block;
1627 strcpy(thisheap->file, file);
1628 thisheap->line = line;
1630 begin_critical_section(S_DEBUGMEMLEAKS);
1631 thisheap->next = igheap;
1633 end_critical_section(S_DEBUGMEMLEAKS);
1640 void tracked_free(void *ptr) {
1641 struct igheap *thisheap;
1642 struct igheap *trash;
1646 if (igheap == NULL) return;
1647 begin_critical_section(S_DEBUGMEMLEAKS);
1648 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1649 if (thisheap->next != NULL) {
1650 if (thisheap->next->block == ptr) {
1651 trash = thisheap->next;
1652 thisheap->next = thisheap->next->next;
1657 if (igheap->block == ptr) {
1659 igheap = igheap->next;
1662 end_critical_section(S_DEBUGMEMLEAKS);
1665 char *tracked_strdup(const char *s, char *file, int line) {
1668 if (s == NULL) return(NULL);
1669 ptr = tracked_malloc(strlen(s) + 1, file, line);
1670 if (ptr == NULL) return(NULL);
1671 strncpy(ptr, s, strlen(s));
1675 void dump_heap(void) {
1676 struct igheap *thisheap;
1678 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1679 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1680 thisheap->file, thisheap->line);
1684 #endif /* DEBUG_MEMORY_LEAKS */