4 * Citadel "system dependent" stuff.
5 * See copyright.txt 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>
55 #include <libcitadel.h>
58 #include "sysdep_decls.h"
59 #include "citserver.h"
63 #include "housekeeping.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
75 #include "ctdl_module.h"
77 #ifdef DEBUG_MEMORY_LEAKS
85 struct igheap *igheap = NULL;
89 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
90 pthread_key_t MyConKey; /* TSD key for MyContext() */
92 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
94 struct CitContext masterCC;
95 time_t last_purge = 0; /* Last dead session purge */
96 static int num_threads = 0; /* Current number of threads */
97 static int num_workers = 0; /* Current number of worker threads */
98 int num_sessions = 0; /* Current number of sessions */
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
105 * Create an interface to lprintf that follows the coding convention.
106 * This is here until such time as we have replaced all calls to lprintf with CtdlLogPrintf
109 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...)
112 va_start(arg_ptr, format);
113 vlprintf(loglevel, format, arg_ptr);
119 * lprintf() ... Write logging information
121 void lprintf(enum LogLevel loglevel, const char *format, ...) {
123 va_start(arg_ptr, format);
124 vlprintf(loglevel, format, arg_ptr);
128 void vlprintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
130 char buf[SIZ], buf2[SIZ];
133 vsyslog((syslog_facility | loglevel), format, arg_ptr);
136 /* stderr output code */
137 if (enable_syslog || running_as_daemon) return;
139 /* if we run in forground and syslog is disabled, log to terminal */
140 if (loglevel <= verbosity) {
145 gettimeofday(&tv, NULL);
146 /* Promote to time_t; types differ on some OSes (like darwin) */
147 unixtime = tv.tv_sec;
148 localtime_r(&unixtime, &tim);
149 if (CC->cs_pid != 0) {
151 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
152 tim.tm_year + 1900, tim.tm_mon + 1,
153 tim.tm_mday, tim.tm_hour, tim.tm_min,
154 tim.tm_sec, (long)tv.tv_usec,
158 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
159 tim.tm_year + 1900, tim.tm_mon + 1,
160 tim.tm_mday, tim.tm_hour, tim.tm_min,
161 tim.tm_sec, (long)tv.tv_usec);
163 vsprintf(buf2, format, arg_ptr);
165 fprintf(stderr, "%s%s", buf, buf2);
173 * Signal handler to shut down the server.
176 volatile int exit_signal = 0;
177 volatile int shutdown_and_halt = 0;
178 volatile int restart_server = 0;
179 volatile int running_as_daemon = 0;
181 static RETSIGTYPE signal_cleanup(int signum) {
182 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
184 exit_signal = signum;
190 void InitialiseSemaphores(void)
194 /* Set up a bunch of semaphores to be used for critical sections */
195 for (i=0; i<MAX_SEMAPHORES; ++i) {
196 pthread_mutex_init(&Critters[i], NULL);
203 * Some initialization stuff...
205 void init_sysdep(void) {
208 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
212 getrlimit(RLIMIT_NOFILE, &rl);
213 rl.rlim_cur = FD_SETSIZE;
214 rl.rlim_max = FD_SETSIZE;
215 setrlimit(RLIMIT_NOFILE, &rl);
219 /* If we've got OpenSSL, we're going to use it. */
225 * Set up a place to put thread-specific data.
226 * We only need a single pointer per thread - it points to the
227 * CitContext structure (in the ContextList linked list) of the
228 * session to which the calling thread is currently bound.
230 if (pthread_key_create(&MyConKey, NULL) != 0) {
231 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
236 * The action for unexpected signals and exceptions should be to
237 * call signal_cleanup() to gracefully shut down the server.
240 sigaddset(&set, SIGINT);
241 sigaddset(&set, SIGQUIT);
242 sigaddset(&set, SIGHUP);
243 sigaddset(&set, SIGTERM);
244 // sigaddset(&set, SIGSEGV); commented out because
245 // sigaddset(&set, SIGILL); we want core dumps
246 // sigaddset(&set, SIGBUS);
247 sigprocmask(SIG_UNBLOCK, &set, NULL);
249 signal(SIGINT, signal_cleanup);
250 signal(SIGQUIT, signal_cleanup);
251 signal(SIGHUP, signal_cleanup);
252 signal(SIGTERM, signal_cleanup);
253 // signal(SIGSEGV, signal_cleanup); commented out because
254 // signal(SIGILL, signal_cleanup); we want core dumps
255 // signal(SIGBUS, signal_cleanup);
258 * Do not shut down the server on broken pipe signals, otherwise the
259 * whole Citadel service would come down whenever a single client
262 signal(SIGPIPE, SIG_IGN);
267 * Obtain a semaphore lock to begin a critical section.
269 void begin_critical_section(int which_one)
271 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
273 /* For all types of critical sections except those listed here,
274 * ensure nobody ever tries to do a critical section within a
275 * transaction; this could lead to deadlock.
277 if ( (which_one != S_FLOORCACHE)
278 #ifdef DEBUG_MEMORY_LEAKS
279 && (which_one != S_DEBUGMEMLEAKS)
281 && (which_one != S_RPLIST)
285 pthread_mutex_lock(&Critters[which_one]);
289 * Release a semaphore lock to end a critical section.
291 void end_critical_section(int which_one)
293 pthread_mutex_unlock(&Critters[which_one]);
299 * This is a generic function to set up a master socket for listening on
300 * a TCP port. The server shuts down if the bind fails.
303 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
305 struct sockaddr_in sin;
307 int actual_queue_len;
309 actual_queue_len = queue_len;
310 if (actual_queue_len < 5) actual_queue_len = 5;
312 memset(&sin, 0, sizeof(sin));
313 sin.sin_family = AF_INET;
314 sin.sin_port = htons((u_short)port_number);
315 if (ip_addr == NULL) {
316 sin.sin_addr.s_addr = INADDR_ANY;
319 sin.sin_addr.s_addr = inet_addr(ip_addr);
322 if (sin.sin_addr.s_addr == !INADDR_ANY) {
323 sin.sin_addr.s_addr = INADDR_ANY;
326 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
329 *errormessage = (char*) malloc(SIZ + 1);
330 snprintf(*errormessage, SIZ,
331 "citserver: Can't create a socket: %s",
333 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
338 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
340 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
341 *errormessage = (char*) malloc(SIZ + 1);
342 snprintf(*errormessage, SIZ,
343 "citserver: Can't bind: %s",
345 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
350 /* set to nonblock - we need this for some obscure situations */
351 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
352 *errormessage = (char*) malloc(SIZ + 1);
353 snprintf(*errormessage, SIZ,
354 "citserver: Can't set socket to non-blocking: %s",
356 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
361 if (listen(s, actual_queue_len) < 0) {
362 *errormessage = (char*) malloc(SIZ + 1);
363 snprintf(*errormessage, SIZ,
364 "citserver: Can't listen: %s",
366 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
377 * Create a Unix domain socket and listen on it
379 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
381 struct sockaddr_un addr;
384 int actual_queue_len;
386 actual_queue_len = queue_len;
387 if (actual_queue_len < 5) actual_queue_len = 5;
389 i = unlink(sockpath);
390 if (i != 0) if (errno != ENOENT) {
391 *errormessage = (char*) malloc(SIZ + 1);
392 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
393 sockpath, strerror(errno));
394 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
398 memset(&addr, 0, sizeof(addr));
399 addr.sun_family = AF_UNIX;
400 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
402 s = socket(AF_UNIX, SOCK_STREAM, 0);
404 *errormessage = (char*) malloc(SIZ + 1);
405 snprintf(*errormessage, SIZ,
406 "citserver: Can't create a socket: %s",
408 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
412 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
413 *errormessage = (char*) malloc(SIZ + 1);
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 *errormessage = (char*) malloc(SIZ + 1);
424 snprintf(*errormessage, SIZ,
425 "citserver: Can't set socket to non-blocking: %s",
427 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
432 if (listen(s, actual_queue_len) < 0) {
433 *errormessage = (char*) malloc(SIZ + 1);
434 snprintf(*errormessage, SIZ,
435 "citserver: Can't listen: %s",
437 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
441 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
448 * Return a pointer to the CitContext structure bound to the thread which
449 * called this function. If there's no such binding (for example, if it's
450 * called by the housekeeper thread) then a generic 'master' CC is returned.
452 * This function is used *VERY* frequently and must be kept small.
454 struct CitContext *MyContext(void) {
456 register struct CitContext *c;
458 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
459 c == NULL) ? &masterCC : c
465 * Initialize a new context and place it in the list. The session number
466 * used to be the PID (which is why it's called cs_pid), but that was when we
467 * had one process per session. Now we just assign them sequentially, starting
468 * at 1 (don't change it to 0 because masterCC uses 0).
470 struct CitContext *CreateNewContext(void) {
471 struct CitContext *me;
472 static int next_pid = 0;
474 me = (struct CitContext *) malloc(sizeof(struct CitContext));
476 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
479 memset(me, 0, sizeof(struct CitContext));
481 /* The new context will be created already in the CON_EXECUTING state
482 * in order to prevent another thread from grabbing it while it's
485 me->state = CON_EXECUTING;
488 * Generate a unique session number and insert this context into
491 begin_critical_section(S_SESSION_TABLE);
492 me->cs_pid = ++next_pid;
494 me->next = ContextList;
496 if (me->next != NULL) {
500 end_critical_section(S_SESSION_TABLE);
506 * The following functions implement output buffering. If the kernel supplies
507 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
508 * user-space buffering.
512 # define HAVE_TCP_BUFFERING
515 # define HAVE_TCP_BUFFERING
516 # define TCP_CORK TCP_NOPUSH
518 #endif /* TCP_CORK */
519 #endif /* HAVE_DARWIN */
521 #ifdef HAVE_TCP_BUFFERING
522 static unsigned on = 1, off = 0;
523 void buffer_output(void) {
524 struct CitContext *ctx = MyContext();
525 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
529 void unbuffer_output(void) {
530 struct CitContext *ctx = MyContext();
531 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
535 void flush_output(void) {
536 struct CitContext *ctx = MyContext();
537 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
538 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
542 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
543 void buffer_output(void) {
546 void unbuffer_output(void) {
549 void flush_output(void) {
552 void buffer_output(void) {
553 if (CC->buffering == 0) {
556 CC->output_buffer = malloc(SIZ);
560 void flush_output(void) {
561 if (CC->buffering == 1) {
562 client_write(CC->output_buffer, CC->buffer_len);
567 void unbuffer_output(void) {
568 if (CC->buffering == 1) {
570 /* We don't call flush_output because we can't. */
571 client_write(CC->output_buffer, CC->buffer_len);
573 free(CC->output_buffer);
574 CC->output_buffer = NULL;
577 #endif /* HAVE_DARWIN */
578 #endif /* HAVE_TCP_BUFFERING */
583 * client_write() ... Send binary data to the client.
585 void client_write(char *buf, int nbytes)
587 int bytes_written = 0;
589 #ifndef HAVE_TCP_BUFFERING
590 int old_buffer_len = 0;
595 if (Ctx->redirect_buffer != NULL) {
596 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
597 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
598 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
599 Ctx->redirect_alloc);
601 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
602 Ctx->redirect_len += nbytes;
603 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
607 #ifndef HAVE_TCP_BUFFERING
608 /* If we're buffering for later, do that now. */
609 if (Ctx->buffering) {
610 old_buffer_len = Ctx->buffer_len;
611 Ctx->buffer_len += nbytes;
612 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
613 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
618 /* Ok, at this point we're not buffering. Go ahead and write. */
621 if (Ctx->redirect_ssl) {
622 client_write_ssl(buf, nbytes);
627 while (bytes_written < nbytes) {
628 retval = write(Ctx->client_socket, &buf[bytes_written],
629 nbytes - bytes_written);
631 CtdlLogPrintf(CTDL_ERR,
632 "client_write(%d bytes) failed: %s (%d)\n",
633 nbytes - bytes_written,
634 strerror(errno), errno);
636 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
640 bytes_written = bytes_written + retval;
646 * cprintf() ... Send formatted printable data to the client. It is
647 * implemented in terms of client_write() but remains in
648 * sysdep.c in case we port to somewhere without va_args...
650 void cprintf(const char *format, ...) {
654 va_start(arg_ptr, format);
655 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
656 buf[sizeof buf - 2] = '\n';
657 client_write(buf, strlen(buf));
663 * Read data from the client socket.
665 * 1 Requested number of bytes has been read.
666 * 0 Request timed out.
667 * -1 The socket is broken.
668 * If the socket breaks, the session will be terminated.
670 int client_read_to(char *buf, int bytes, int timeout)
679 if (CC->redirect_ssl) {
680 return (client_read_ssl(buf, bytes, timeout));
684 fd = CC->client_socket;
691 retval = select( (fd)+1,
692 &rfds, NULL, NULL, &tv);
694 if (FD_ISSET(fd, &rfds) == 0) {
698 rlen = read(fd, &buf[len], bytes-len);
700 /* The socket has been disconnected! */
710 * Read data from the client socket with default timeout.
711 * (This is implemented in terms of client_read_to() and could be
712 * justifiably moved out of sysdep.c)
714 INLINE int client_read(char *buf, int bytes)
716 return(client_read_to(buf, bytes, config.c_sleeping));
721 * client_getln() ... Get a LF-terminated line of text from the client.
722 * (This is implemented in terms of client_read() and could be
723 * justifiably moved out of sysdep.c)
725 int client_getln(char *buf, int bufsize)
729 /* Read one character at a time.
732 retval = client_read(&buf[i], 1);
733 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
737 /* If we got a long line, discard characters until the newline.
739 if (i == (bufsize-1))
740 while (buf[i] != '\n' && retval == 1)
741 retval = client_read(&buf[i], 1);
743 /* Strip the trailing LF, and the trailing CR if present.
747 && ( (buf[i - 1]==13)
748 || ( buf[i - 1]==10)) ) {
752 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
758 * Cleanup any contexts that are left lying around
760 void context_cleanup(void)
762 struct CitContext *ptr = NULL;
763 struct CitContext *rem = NULL;
766 * Clean up the contexts.
767 * There are no threads so no critical_section stuff is needed.
771 /* Remove the session from the active list */
775 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
785 * The system-dependent part of master_cleanup() - close the master socket.
787 void sysdep_master_cleanup(void) {
788 struct ServiceFunctionHook *serviceptr;
791 * close all protocol master sockets
793 for (serviceptr = ServiceHookTable; serviceptr != NULL;
794 serviceptr = serviceptr->next ) {
796 if (serviceptr->tcp_port > 0)
797 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
798 serviceptr->tcp_port);
800 if (serviceptr->sockpath != NULL)
801 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
802 serviceptr->sockpath);
804 close(serviceptr->msock);
806 /* If it's a Unix domain socket, remove the file. */
807 if (serviceptr->sockpath != NULL) {
808 unlink(serviceptr->sockpath);
817 CtdlDestroyProtoHooks();
818 CtdlDestroyDeleteHooks();
819 CtdlDestroyXmsgHooks();
820 CtdlDestroyNetprocHooks();
821 CtdlDestroyUserHooks();
822 CtdlDestroyMessageHook();
823 CtdlDestroyCleanupHooks();
824 CtdlDestroyFixedOutputHooks();
825 CtdlDestroySessionHooks();
826 CtdlDestroyServiceHook();
827 #ifdef HAVE_BACKTRACE
835 * Terminate another session.
836 * (This could justifiably be moved out of sysdep.c because it
837 * no longer does anything that is system-dependent.)
839 void kill_session(int session_to_kill) {
840 struct CitContext *ptr;
842 begin_critical_section(S_SESSION_TABLE);
843 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
844 if (ptr->cs_pid == session_to_kill) {
848 end_critical_section(S_SESSION_TABLE);
852 void graceful_shutdown(int signum) {
853 kill(current_child, signum);
854 unlink(file_pid_file);
860 * Start running as a daemon.
862 void start_daemon(int unused) {
870 /* Close stdin/stdout/stderr and replace them with /dev/null.
871 * We don't just call close() because we don't want these fd's
872 * to be reused for other files.
881 signal(SIGHUP, SIG_IGN);
882 signal(SIGINT, SIG_IGN);
883 signal(SIGQUIT, SIG_IGN);
887 freopen("/dev/null", "r", stdin);
888 freopen("/dev/null", "w", stdout);
889 freopen("/dev/null", "w", stderr);
892 current_child = fork();
894 signal(SIGTERM, graceful_shutdown);
896 if (current_child < 0) {
901 else if (current_child == 0) {
902 return; /* continue starting citadel. */
906 fp = fopen(file_pid_file, "w");
909 * NB.. The pid file contains the pid of the actual server.
910 * This is not the pid of the watcher process
912 fprintf(fp, ""F_PID_T"\n", current_child);
915 waitpid(current_child, &status, 0);
920 /* Did the main process exit with an actual exit code? */
921 if (WIFEXITED(status)) {
923 /* Exit code 0 means the watcher should exit */
924 if (WEXITSTATUS(status) == 0) {
928 /* Exit code 101-109 means the watcher should exit */
929 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
933 /* Any other exit code means we should restart. */
939 /* Any other type of termination (signals, etc.) should also restart. */
944 } while (do_restart);
946 unlink(file_pid_file);
947 exit(WEXITSTATUS(status));
953 * Generic routine to convert a login name to a full name (gecos)
954 * Returns nonzero if a conversion took place
956 int convert_login(char NameToConvert[]) {
960 pw = getpwnam(NameToConvert);
965 strcpy(NameToConvert, pw->pw_gecos);
966 for (a=0; a<strlen(NameToConvert); ++a) {
967 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
976 * New thread interface.
977 * To create a thread you must call one of the create thread functions.
978 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
979 * struct CtdlThreadNode *node = NULL;
981 * If the thread is created *node will point to the thread control structure for the created thread.
982 * If the thread creation fails *node remains NULL
983 * Do not free the memory pointed to by *node, it doesn't belong to you.
984 * If your thread function returns it will be started again without creating a new thread.
985 * If your thread function wants to exit it should call CtdlThreadExit(ret_code);
986 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
987 * remove the need for the calls to eCrashRegisterThread and friends
991 struct CtdlThreadNode *CtdlThreadList = NULL;
994 * Condition variable and Mutex for thread garbage collection
996 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
997 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
999 static pthread_t GC_thread;
1000 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
1001 double CtdlThreadLoadAvg = 0;
1002 double CtdlThreadWorkerAvg = 0;
1004 * Pinched the following bits regarding signals from Kannel.org
1008 * Change this thread's signal mask to block user-visible signals
1009 * (HUP, TERM, QUIT, INT), and store the old signal mask in
1011 * Return 0 for success, or -1 if an error occurred.
1015 * This does not work in Darwin alias MacOS X alias Mach kernel,
1016 * however. So we define a dummy function doing nothing.
1018 #if defined(DARWIN_OLD)
1019 static int pthread_sigmask();
1022 static int ctdl_thread_internal_block_signals(sigset_t *old_set_storage)
1025 sigset_t block_signals;
1027 ret = sigemptyset(&block_signals);
1029 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't initialize signal set\n");
1032 ret = sigaddset(&block_signals, SIGHUP);
1033 ret |= sigaddset(&block_signals, SIGTERM);
1034 ret |= sigaddset(&block_signals, SIGQUIT);
1035 ret |= sigaddset(&block_signals, SIGINT);
1037 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't add signal to signal set.\n");
1040 ret = pthread_sigmask(SIG_BLOCK, &block_signals, old_set_storage);
1042 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't disable signals for thread creation\n");
1048 static void ctdl_thread_internal_restore_signals(sigset_t *old_set)
1052 ret = pthread_sigmask(SIG_SETMASK, old_set, NULL);
1054 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't restore signal set.\n");
1059 void ctdl_thread_internal_cleanup(void)
1063 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
1065 free (CtdlThreadStates[i]);
1069 void ctdl_thread_internal_init(void)
1071 struct CtdlThreadNode *this_thread;
1074 GC_thread = pthread_self();
1075 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
1076 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
1077 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
1078 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
1079 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
1080 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
1081 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
1082 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
1083 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
1084 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
1086 /* Get ourself a thread entry */
1087 this_thread = malloc(sizeof(struct CtdlThreadNode));
1088 if (this_thread == NULL) {
1089 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1092 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1093 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1095 /* We are garbage collector so create us as running */
1096 this_thread->state = CTDL_THREAD_RUNNING;
1098 if ((ret = pthread_attr_init(&this_thread->attr))) {
1099 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1104 this_thread->name = strdup("Garbage Collection Thread");
1106 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1107 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1109 this_thread->tid = GC_thread;
1111 num_threads++; // Increase the count of threads in the system.
1113 this_thread->next = CtdlThreadList;
1114 CtdlThreadList = this_thread;
1115 if (this_thread->next)
1116 this_thread->next->prev = this_thread;
1117 /* Set up start times */
1118 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
1119 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
1124 * A function to update a threads load averages
1126 void ctdl_thread_internal_update_avgs(struct CtdlThreadNode *this_thread)
1128 struct timeval now, result;
1129 double last_duration;
1131 pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1132 gettimeofday(&now, NULL);
1133 timersub(&now, &(this_thread->last_state_change), &result);
1134 // result now has a timeval for the time we spent in the last state since we last updated
1135 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1136 if (this_thread->state == CTDL_THREAD_SLEEPING)
1137 this_thread->avg_sleeping += last_duration;
1138 if (this_thread->state == CTDL_THREAD_RUNNING)
1139 this_thread->avg_running += last_duration;
1140 if (this_thread->state == CTDL_THREAD_BLOCKED)
1141 this_thread->avg_blocked += last_duration;
1142 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
1143 pthread_mutex_unlock(&this_thread->ThreadMutex);
1147 * A function to chenge the state of a thread
1149 void ctdl_thread_internal_change_state (struct CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
1152 * Wether we change state or not we need update the load values
1154 ctdl_thread_internal_update_avgs(this_thread);
1155 pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1156 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
1157 this_thread->state = new_state;
1158 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
1159 this_thread->state = new_state;
1160 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
1161 this_thread->state = new_state;
1162 pthread_mutex_unlock(&this_thread->ThreadMutex);
1167 * A function to tell all threads to exit
1169 void CtdlThreadStopAll(void)
1171 struct CtdlThreadNode *this_thread;
1173 begin_critical_section(S_THREAD_LIST);
1174 this_thread = CtdlThreadList;
1177 if (this_thread->thread_func) // Don't tell garbage collector to stop
1179 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1180 pthread_cond_signal(&this_thread->ThreadCond);
1181 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (%ld).\n", this_thread->name, this_thread->tid);
1183 this_thread = this_thread->next;
1185 end_critical_section(S_THREAD_LIST);
1190 * A function to signal that we need to do garbage collection on the thread list
1192 void CtdlThreadGC(void)
1194 struct CtdlThreadNode *this_thread;
1196 CtdlLogPrintf(CTDL_DEBUG, "Thread system signalling garbage collection.\n");
1198 begin_critical_section(S_THREAD_LIST);
1199 this_thread = CtdlThreadList;
1202 if (!this_thread->thread_func)
1203 pthread_cond_signal(&this_thread->ThreadCond);
1205 this_thread = this_thread->next;
1207 end_critical_section(S_THREAD_LIST);
1212 * A function to return the number of threads running in the system
1214 int CtdlThreadGetCount(void)
1220 * A function to find the thread structure for this thread
1222 struct CtdlThreadNode *CtdlThreadSelf(void)
1225 struct CtdlThreadNode *this_thread;
1227 self_tid = pthread_self();
1229 begin_critical_section(S_THREAD_LIST);
1230 this_thread = CtdlThreadList;
1233 if (pthread_equal(self_tid, this_thread->tid))
1235 end_critical_section(S_THREAD_LIST);
1238 this_thread = this_thread->next;
1240 end_critical_section(S_THREAD_LIST);
1248 * A function to rename a thread
1249 * Returns a char * and the caller owns the memory and should free it
1251 char *CtdlThreadName(struct CtdlThreadNode *thread, char *name)
1253 struct CtdlThreadNode *this_thread;
1257 this_thread = CtdlThreadSelf();
1259 this_thread = thread;
1262 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread.\n");
1265 begin_critical_section(S_THREAD_LIST);
1268 old_name = this_thread->name;
1269 this_thread->name = strdup (name);
1272 old_name = strdup(this_thread->name);
1273 end_critical_section (S_THREAD_LIST);
1279 * A function to force a thread to exit
1281 void CtdlThreadCancel(struct CtdlThreadNode *thread)
1283 struct CtdlThreadNode *this_thread;
1286 this_thread = CtdlThreadSelf();
1288 this_thread = thread;
1291 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
1292 CtdlThreadStopAll();
1296 if (!this_thread->thread_func)
1298 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
1299 CtdlThreadStopAll();
1303 begin_critical_section(S_THREAD_LIST);
1304 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
1305 pthread_cancel(this_thread->tid);
1306 end_critical_section (S_THREAD_LIST);
1312 * A function for a thread to check if it has been asked to stop
1314 int CtdlThreadCheckStop(void)
1316 struct CtdlThreadNode *this_thread;
1318 this_thread = CtdlThreadSelf();
1321 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
1322 CtdlThreadStopAll();
1325 if(this_thread->state == CTDL_THREAD_STOP_REQ)
1327 this_thread->state = CTDL_THREAD_STOPPING;
1330 else if(this_thread->state < CTDL_THREAD_STOP_REQ)
1338 * A function to ask a thread to exit
1339 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
1341 void CtdlThreadStop(struct CtdlThreadNode *thread)
1343 struct CtdlThreadNode *this_thread;
1346 this_thread = CtdlThreadSelf();
1348 this_thread = thread;
1351 if (!(this_thread->thread_func))
1352 return; // Don't stop garbage collector
1354 begin_critical_section (S_THREAD_LIST);
1355 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1356 pthread_cond_signal(&this_thread->ThreadCond);
1357 end_critical_section(S_THREAD_LIST);
1361 * So we now have a sleep command that works with threads but it is in seconds
1363 void CtdlThreadSleep(int secs)
1365 struct timespec wake_time;
1366 struct timeval time_now;
1367 struct CtdlThreadNode *self;
1370 self = CtdlThreadSelf();
1373 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
1377 begin_critical_section(S_THREAD_LIST);
1378 ctdl_thread_internal_change_state (self, CTDL_THREAD_SLEEPING);
1379 pthread_mutex_lock(&self->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1380 end_critical_section(S_THREAD_LIST);
1382 memset (&wake_time, 0, sizeof(struct timespec));
1383 gettimeofday(&time_now, NULL);
1384 wake_time.tv_sec = time_now.tv_sec + secs;
1385 wake_time.tv_nsec = time_now.tv_usec * 10;
1386 pthread_cond_timedwait(&self->ThreadCond, &self->ThreadMutex, &wake_time);
1387 begin_critical_section(S_THREAD_LIST);
1388 pthread_mutex_unlock(&self->ThreadMutex);
1389 ctdl_thread_internal_change_state (self, CTDL_THREAD_RUNNING);
1390 end_critical_section(S_THREAD_LIST);
1395 * Routine to clean up our thread function on exit
1397 static void ctdl_internal_thread_cleanup(void *arg)
1399 struct CtdlThreadNode *this_thread;
1400 this_thread = CtdlThreadSelf();
1402 * In here we were called by the current thread because it is exiting
1403 * NB. WE ARE THE CURRENT THREAD
1405 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", this_thread->name, this_thread->tid);
1406 begin_critical_section(S_THREAD_LIST);
1407 #ifdef HAVE_BACKTRACE
1408 eCrash_UnregisterThread();
1410 this_thread->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
1411 end_critical_section(S_THREAD_LIST);
1416 * A quick function to show the load averages
1418 void ctdl_thread_internal_calc_loadavg(void)
1420 struct CtdlThreadNode *that_thread;
1421 double load_avg, worker_avg;
1424 begin_critical_section(S_THREAD_LIST);
1425 that_thread = CtdlThreadList;
1430 /* Update load averages */
1431 ctdl_thread_internal_update_avgs(that_thread);
1432 pthread_mutex_lock(&that_thread->ThreadMutex);
1433 that_thread->load_avg = that_thread->avg_sleeping + that_thread->avg_running + that_thread->avg_blocked;
1434 that_thread->load_avg = that_thread->avg_running / that_thread->load_avg * 100;
1435 that_thread->avg_sleeping /= 2;
1436 that_thread->avg_running /= 2;
1437 that_thread->avg_blocked /= 2;
1438 load_avg += that_thread->load_avg;
1439 if (that_thread->flags & CTDLTHREAD_WORKER)
1441 worker_avg += that_thread->load_avg;
1444 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%ld) \"%s\" %f %f %f %f.\n",
1447 CtdlThreadStates[that_thread->state],
1448 that_thread->avg_sleeping,
1449 that_thread->avg_running,
1450 that_thread->avg_blocked,
1451 that_thread->load_avg);
1453 pthread_mutex_unlock(&that_thread->ThreadMutex);
1454 that_thread = that_thread->next;
1456 CtdlThreadLoadAvg = load_avg/num_threads;
1457 CtdlThreadWorkerAvg = worker_avg/workers;
1458 CtdlLogPrintf(CTDL_INFO, "System load average %f, workers averag %f\n", CtdlThreadLoadAvg, CtdlThreadWorkerAvg);
1459 end_critical_section(S_THREAD_LIST);
1464 * Garbage collection routine.
1465 * Gets called by main() in a loop to clean up the thread list periodically.
1467 void ctdl_internal_thread_gc (void)
1469 struct CtdlThreadNode *this_thread, *that_thread;
1472 /* Handle exiting of garbage collector thread */
1473 if(num_threads == 1)
1474 CtdlThreadList->state = CTDL_THREAD_EXITED;
1476 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
1478 * Woke up to do garbage collection
1480 begin_critical_section(S_THREAD_LIST);
1481 this_thread = CtdlThreadList;
1484 that_thread = this_thread;
1485 this_thread = this_thread->next;
1487 /* Do we need to clean up this thread? */
1488 if (that_thread->state != CTDL_THREAD_EXITED)
1490 if(that_thread->flags & CTDLTHREAD_WORKER)
1491 workers++; /* Sanity check on number of worker threads */
1495 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
1496 { /* Sanity check */
1497 end_critical_section(S_THREAD_LIST);
1498 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
1499 CtdlThreadStopAll();
1503 if (num_threads <= 0)
1504 { /* Sanity check */
1505 end_critical_section (S_THREAD_LIST);
1506 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
1507 CtdlThreadStopAll();
1511 /* If we are unlinking the list head then the next becomes the list head */
1512 if (that_thread == CtdlThreadList)
1513 CtdlThreadList = that_thread->next;
1514 if(that_thread->prev)
1515 that_thread->prev->next = that_thread->next;
1516 if(that_thread->next)
1517 that_thread->next->prev = that_thread->next;
1519 if(that_thread->flags & CTDLTHREAD_WORKER)
1520 num_workers--; /* This is a wroker thread so reduce the count. */
1523 * Join on the thread to do clean up and prevent memory leaks
1524 * Also makes sure the thread has cleaned up after itself before we remove it from the list
1525 * If that thread has no function it must be the garbage collector
1527 if (that_thread->thread_func)
1528 pthread_join (that_thread->tid, NULL);
1531 * Now we own that thread entry
1533 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (%ld).\n", that_thread->name, that_thread->tid);
1534 if(that_thread->name)
1535 free(that_thread->name);
1536 pthread_mutex_destroy(&that_thread->ThreadMutex);
1537 pthread_cond_destroy(&that_thread->ThreadCond);
1538 pthread_attr_destroy(&that_thread->attr);
1542 /* Sanity check number of worker threads */
1543 if (workers != num_workers)
1545 end_critical_section(S_THREAD_LIST);
1546 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n", workers, num_workers);
1549 end_critical_section(S_THREAD_LIST);
1556 * Runtime function for a Citadel Thread.
1557 * This initialises the threads environment and then calls the user supplied thread function
1558 * Note that this is the REAL thread function and wraps the users thread function.
1560 static void *ctdl_internal_thread_func (void *arg)
1562 struct CtdlThreadNode *this_thread;
1565 /* lock and unlock the thread list.
1566 * This causes this thread to wait until all its creation stuff has finished before it
1567 * can continue its execution.
1569 begin_critical_section(S_THREAD_LIST);
1570 // Get our thread data structure
1571 this_thread = (struct CtdlThreadNode *) arg;
1572 this_thread->state = CTDL_THREAD_RUNNING;
1573 this_thread->pid = getpid();
1574 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
1575 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
1576 end_critical_section(S_THREAD_LIST);
1578 // Tell the world we are here
1579 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1581 // Register the cleanup function to take care of when we exit.
1582 pthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
1586 * run the thread to do the work
1588 ret = (this_thread->thread_func)(this_thread->user_args);
1591 * Our thread is exiting either because it wanted to end or because the server is stopping
1592 * We need to clean up
1594 pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1602 * Internal function to create a thread.
1603 * Must be called from within a S_THREAD_LIST critical section
1605 struct CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1608 struct CtdlThreadNode *this_thread;
1610 sigset_t old_signal_set;
1612 if (num_threads >= 32767)
1614 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1618 this_thread = malloc(sizeof(struct CtdlThreadNode));
1619 if (this_thread == NULL) {
1620 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1623 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1624 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1626 this_thread->state = CTDL_THREAD_CREATE;
1628 if ((ret = pthread_attr_init(&this_thread->attr))) {
1629 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1634 /* Our per-thread stacks need to be bigger than the default size,
1635 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1636 * crashes on 64-bit Linux.
1638 if (flags & CTDLTHREAD_BIGSTACK)
1640 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1641 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1642 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1644 pthread_attr_destroy(&this_thread->attr);
1651 * If we got here we are going to create the thread so we must initilise the structure
1652 * first because most implimentations of threading can't create it in a stopped state
1653 * and it might want to do things with its structure that aren't initialised otherwise.
1657 this_thread->name = strdup(name);
1661 this_thread->name = strdup("Un-named Thread");
1664 this_thread->flags = flags;
1665 this_thread->thread_func = thread_func;
1666 this_thread->user_args = args;
1667 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1668 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1671 * We want to make sure that only the main thread handles signals,
1672 * so that each signal is handled exactly once. To do this, we
1673 * make sure that each new thread has all the signals that we
1674 * handle blocked. To avoid race conditions, we block them in
1675 * the spawning thread first, then create the new thread (which
1676 * inherits the settings), and then restore the old settings in
1677 * the spawning thread. This means that there is a brief period
1678 * when no signals will be processed, but during that time they
1679 * should be queued by the operating system.
1681 if (pthread_equal(GC_thread, pthread_self()))
1682 sigtrick = ctdl_thread_internal_block_signals(&old_signal_set) == 0;
1685 * We pass this_thread into the thread as its args so that it can find out information
1686 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1687 * thread function needs to finish off the setup of the structure
1689 if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1692 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1694 if (this_thread->name)
1695 free (this_thread->name);
1696 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1697 pthread_cond_destroy(&(this_thread->ThreadCond));
1698 pthread_attr_destroy(&this_thread->attr);
1701 ctdl_thread_internal_restore_signals(&old_signal_set);
1706 ctdl_thread_internal_restore_signals(&old_signal_set);
1708 num_threads++; // Increase the count of threads in the system.
1709 if(this_thread->flags & CTDLTHREAD_WORKER)
1712 this_thread->next = CtdlThreadList;
1713 CtdlThreadList = this_thread;
1714 if (this_thread->next)
1715 this_thread->next->prev = this_thread;
1716 // Register for tracing
1717 #ifdef HAVE_BACKTRACE
1718 eCrash_RegisterThread(this_thread->name, 0);
1724 * Wrapper function to create a thread
1725 * ensures the critical section and other protections are in place.
1726 * char *name = name to give to thread, if NULL, use generic name
1727 * int flags = flags to determine type of thread and standard facilities
1729 struct CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1731 struct CtdlThreadNode *ret = NULL;
1733 begin_critical_section(S_THREAD_LIST);
1734 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1735 end_critical_section(S_THREAD_LIST);
1742 * A warapper function for select so we can show a thread as blocked
1744 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout)
1746 struct CtdlThreadNode *self;
1749 self = CtdlThreadSelf();
1750 ctdl_thread_internal_change_state(self, CTDL_THREAD_BLOCKED);
1751 ret = select(n, readfds, writefds, exceptfds, timeout);
1752 ctdl_thread_internal_change_state(self, CTDL_THREAD_RUNNING);
1757 * Purge all sessions which have the 'kill_me' flag set.
1758 * This function has code to prevent it from running more than once every
1759 * few seconds, because running it after every single unbind would waste a lot
1760 * of CPU time and keep the context list locked too much. To force it to run
1761 * anyway, set "force" to nonzero.
1764 * After that's done, we raise the size of the worker thread pool
1765 * if such an action is appropriate.
1767 void dead_session_purge(int force) {
1768 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1769 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1772 if ( (time(NULL) - last_purge) < 5 ) {
1773 return; /* Too soon, go away */
1778 begin_critical_section(S_SESSION_TABLE);
1784 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1785 /* Remove the session from the active list */
1787 ptr2->prev->next = ptr2->next;
1790 ContextList = ptr2->next;
1793 ptr2->next->prev = ptr2->prev;
1798 /* And put it on our to-be-destroyed list */
1804 end_critical_section(S_SESSION_TABLE);
1806 /* Now that we no longer have the session list locked, we can take
1807 * our time and destroy any sessions on the to-be-killed list, which
1808 * is allocated privately on this thread's stack.
1810 while (rem != NULL) {
1811 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1818 /* Raise the size of the worker thread pool if necessary. */
1819 begin_critical_section(S_THREAD_LIST);
1820 if ( (num_sessions > num_workers)
1821 && (num_workers < config.c_max_workers) ) {
1822 ctdl_internal_create_thread("Worker Thread", CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER, worker_thread, NULL);
1824 end_critical_section(S_THREAD_LIST);
1825 // FIXME: reduce the number of worker threads too
1833 * masterCC is the context we use when not attached to a session. This
1834 * function initializes it.
1836 void InitializeMasterCC(void) {
1837 memset(&masterCC, 0, sizeof(struct CitContext));
1838 masterCC.internal_pgm = 1;
1839 masterCC.cs_pid = 0;
1848 * Bind a thread to a context. (It's inline merely to speed things up.)
1850 INLINE void become_session(struct CitContext *which_con) {
1851 pthread_setspecific(MyConKey, (void *)which_con );
1857 * This loop just keeps going and going and going...
1859 void *worker_thread(void *arg) {
1862 struct CitContext *ptr;
1863 struct CitContext *bind_me = NULL;
1866 struct CitContext *con= NULL; /* Temporary context pointer */
1867 struct ServiceFunctionHook *serviceptr;
1868 int ssock; /* Descriptor for client socket */
1870 int force_purge = 0;
1875 while (!CtdlThreadCheckStop()) {
1877 /* make doubly sure we're not holding any stale db handles
1878 * which might cause a deadlock.
1880 cdb_check_handles();
1881 do_select: force_purge = 0;
1882 bind_me = NULL; /* Which session shall we handle? */
1884 /* Initialize the fdset. */
1888 begin_critical_section(S_SESSION_TABLE);
1889 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1890 if (ptr->state == CON_IDLE) {
1891 FD_SET(ptr->client_socket, &readfds);
1892 if (ptr->client_socket > highest)
1893 highest = ptr->client_socket;
1895 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1897 ptr->state = CON_EXECUTING;
1900 end_critical_section(S_SESSION_TABLE);
1906 /* If we got this far, it means that there are no sessions
1907 * which a previous thread marked for attention, so we go
1908 * ahead and get ready to select().
1911 /* First, add the various master sockets to the fdset. */
1912 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1913 serviceptr = serviceptr->next ) {
1914 m = serviceptr->msock;
1915 FD_SET(m, &readfds);
1921 if (!CtdlThreadCheckStop()) {
1922 tv.tv_sec = 1; /* wake up every second if no input */
1924 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1925 // retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1928 if (CtdlThreadCheckStop()) return(NULL);
1930 /* Now figure out who made this select() unblock.
1931 * First, check for an error or exit condition.
1934 if (errno == EBADF) {
1935 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1939 if (errno != EINTR) {
1940 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1941 CtdlThreadStopAll();
1942 } else if (!CtdlThreadCheckStop()) {
1943 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
1947 else if(retval == 0) {
1950 /* Next, check to see if it's a new client connecting
1951 * on a master socket.
1953 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1954 serviceptr = serviceptr->next ) {
1956 if (FD_ISSET(serviceptr->msock, &readfds)) {
1957 ssock = accept(serviceptr->msock, NULL, 0);
1959 CtdlLogPrintf(CTDL_DEBUG,
1960 "New client socket %d\n",
1963 /* The master socket is non-blocking but the client
1964 * sockets need to be blocking, otherwise certain
1965 * operations barf on FreeBSD. Not a fatal error.
1967 if (fcntl(ssock, F_SETFL, 0) < 0) {
1968 CtdlLogPrintf(CTDL_EMERG,
1969 "citserver: Can't set socket to blocking: %s\n",
1973 /* New context will be created already
1974 * set up in the CON_EXECUTING state.
1976 con = CreateNewContext();
1978 /* Assign our new socket number to it. */
1979 con->client_socket = ssock;
1980 con->h_command_function =
1981 serviceptr->h_command_function;
1982 con->h_async_function =
1983 serviceptr->h_async_function;
1985 serviceptr->ServiceName;
1987 /* Determine whether it's a local socket */
1988 if (serviceptr->sockpath != NULL)
1989 con->is_local_socket = 1;
1991 /* Set the SO_REUSEADDR socket option */
1993 setsockopt(ssock, SOL_SOCKET,
1997 become_session(con);
1999 serviceptr->h_greeting_function();
2000 become_session(NULL);
2001 con->state = CON_IDLE;
2007 /* It must be a client socket. Find a context that has data
2008 * waiting on its socket *and* is in the CON_IDLE state. Any
2009 * active sockets other than our chosen one are marked as
2010 * CON_READY so the next thread that comes around can just bind
2011 * to one without having to select() again.
2013 begin_critical_section(S_SESSION_TABLE);
2014 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2015 if ( (FD_ISSET(ptr->client_socket, &readfds))
2016 && (ptr->state != CON_EXECUTING) ) {
2017 ptr->input_waiting = 1;
2019 bind_me = ptr; /* I choose you! */
2020 bind_me->state = CON_EXECUTING;
2023 ptr->state = CON_READY;
2027 end_critical_section(S_SESSION_TABLE);
2030 /* We're bound to a session */
2031 if (bind_me != NULL) {
2032 become_session(bind_me);
2034 /* If the client has sent a command, execute it. */
2035 if (CC->input_waiting) {
2036 CC->h_command_function();
2037 CC->input_waiting = 0;
2040 /* If there are asynchronous messages waiting and the
2041 * client supports it, do those now */
2042 if ((CC->is_async) && (CC->async_waiting)
2043 && (CC->h_async_function != NULL)) {
2044 CC->h_async_function();
2045 CC->async_waiting = 0;
2048 force_purge = CC->kill_me;
2049 become_session(NULL);
2050 bind_me->state = CON_IDLE;
2053 dead_session_purge(force_purge);
2055 check_sched_shutdown();
2057 /* If control reaches this point, the server is shutting down */
2066 * Translate text facility name to syslog.h defined value.
2068 int SyslogFacility(char *name)
2077 { LOG_KERN, "kern" },
2078 { LOG_USER, "user" },
2079 { LOG_MAIL, "mail" },
2080 { LOG_DAEMON, "daemon" },
2081 { LOG_AUTH, "auth" },
2082 { LOG_SYSLOG, "syslog" },
2084 { LOG_NEWS, "news" },
2085 { LOG_UUCP, "uucp" },
2086 { LOG_LOCAL0, "local0" },
2087 { LOG_LOCAL1, "local1" },
2088 { LOG_LOCAL2, "local2" },
2089 { LOG_LOCAL3, "local3" },
2090 { LOG_LOCAL4, "local4" },
2091 { LOG_LOCAL5, "local5" },
2092 { LOG_LOCAL6, "local6" },
2093 { LOG_LOCAL7, "local7" },
2096 for(i = 0; facTbl[i].name != NULL; i++) {
2097 if(!strcasecmp(name, facTbl[i].name))
2098 return facTbl[i].facility;
2105 /********** MEM CHEQQER ***********/
2107 #ifdef DEBUG_MEMORY_LEAKS
2114 void *tracked_malloc(size_t size, char *file, int line) {
2115 struct igheap *thisheap;
2118 block = malloc(size);
2119 if (block == NULL) return(block);
2121 thisheap = malloc(sizeof(struct igheap));
2122 if (thisheap == NULL) {
2127 thisheap->block = block;
2128 strcpy(thisheap->file, file);
2129 thisheap->line = line;
2131 begin_critical_section(S_DEBUGMEMLEAKS);
2132 thisheap->next = igheap;
2134 end_critical_section(S_DEBUGMEMLEAKS);
2140 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
2141 struct igheap *thisheap;
2144 block = realloc(ptr, size);
2145 if (block == NULL) return(block);
2147 thisheap = malloc(sizeof(struct igheap));
2148 if (thisheap == NULL) {
2153 thisheap->block = block;
2154 strcpy(thisheap->file, file);
2155 thisheap->line = line;
2157 begin_critical_section(S_DEBUGMEMLEAKS);
2158 thisheap->next = igheap;
2160 end_critical_section(S_DEBUGMEMLEAKS);
2167 void tracked_free(void *ptr) {
2168 struct igheap *thisheap;
2169 struct igheap *trash;
2173 if (igheap == NULL) return;
2174 begin_critical_section(S_DEBUGMEMLEAKS);
2175 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2176 if (thisheap->next != NULL) {
2177 if (thisheap->next->block == ptr) {
2178 trash = thisheap->next;
2179 thisheap->next = thisheap->next->next;
2184 if (igheap->block == ptr) {
2186 igheap = igheap->next;
2189 end_critical_section(S_DEBUGMEMLEAKS);
2192 char *tracked_strdup(const char *s, char *file, int line) {
2195 if (s == NULL) return(NULL);
2196 ptr = tracked_malloc(strlen(s) + 1, file, line);
2197 if (ptr == NULL) return(NULL);
2198 strncpy(ptr, s, strlen(s));
2202 void dump_heap(void) {
2203 struct igheap *thisheap;
2205 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2206 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
2207 thisheap->file, thisheap->line);
2211 #endif /* DEBUG_MEMORY_LEAKS */