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);
183 exit_signal = signum;
189 void InitialiseSemaphores(void)
193 /* Set up a bunch of semaphores to be used for critical sections */
194 for (i=0; i<MAX_SEMAPHORES; ++i) {
195 pthread_mutex_init(&Critters[i], NULL);
202 * Some initialization stuff...
204 void init_sysdep(void) {
207 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
211 getrlimit(RLIMIT_NOFILE, &rl);
212 rl.rlim_cur = FD_SETSIZE;
213 rl.rlim_max = FD_SETSIZE;
214 setrlimit(RLIMIT_NOFILE, &rl);
218 /* If we've got OpenSSL, we're going to use it. */
224 * Set up a place to put thread-specific data.
225 * We only need a single pointer per thread - it points to the
226 * CitContext structure (in the ContextList linked list) of the
227 * session to which the calling thread is currently bound.
229 if (pthread_key_create(&MyConKey, NULL) != 0) {
230 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
235 * The action for unexpected signals and exceptions should be to
236 * call signal_cleanup() to gracefully shut down the server.
239 sigaddset(&set, SIGINT);
240 sigaddset(&set, SIGQUIT);
241 sigaddset(&set, SIGHUP);
242 sigaddset(&set, SIGTERM);
243 // sigaddset(&set, SIGSEGV); commented out because
244 // sigaddset(&set, SIGILL); we want core dumps
245 // sigaddset(&set, SIGBUS);
246 sigprocmask(SIG_UNBLOCK, &set, NULL);
248 signal(SIGINT, signal_cleanup);
249 signal(SIGQUIT, signal_cleanup);
250 signal(SIGHUP, signal_cleanup);
251 signal(SIGTERM, signal_cleanup);
252 // signal(SIGSEGV, signal_cleanup); commented out because
253 // signal(SIGILL, signal_cleanup); we want core dumps
254 // signal(SIGBUS, signal_cleanup);
257 * Do not shut down the server on broken pipe signals, otherwise the
258 * whole Citadel service would come down whenever a single client
261 signal(SIGPIPE, SIG_IGN);
267 * Obtain a semaphore lock to begin a critical section.
268 * but only if no one else has one
270 int try_critical_section(int which_one)
272 /* For all types of critical sections except those listed here,
273 * ensure nobody ever tries to do a critical section within a
274 * transaction; this could lead to deadlock.
276 if ( (which_one != S_FLOORCACHE)
277 #ifdef DEBUG_MEMORY_LEAKS
278 && (which_one != S_DEBUGMEMLEAKS)
280 && (which_one != S_RPLIST)
284 return (pthread_mutex_trylock(&Critters[which_one]));
289 * Obtain a semaphore lock to begin a critical section.
291 void begin_critical_section(int which_one)
293 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
295 /* For all types of critical sections except those listed here,
296 * ensure nobody ever tries to do a critical section within a
297 * transaction; this could lead to deadlock.
299 if ( (which_one != S_FLOORCACHE)
300 #ifdef DEBUG_MEMORY_LEAKS
301 && (which_one != S_DEBUGMEMLEAKS)
303 && (which_one != S_RPLIST)
307 pthread_mutex_lock(&Critters[which_one]);
311 * Release a semaphore lock to end a critical section.
313 void end_critical_section(int which_one)
315 pthread_mutex_unlock(&Critters[which_one]);
321 * This is a generic function to set up a master socket for listening on
322 * a TCP port. The server shuts down if the bind fails.
325 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
327 struct sockaddr_in sin;
329 int actual_queue_len;
331 actual_queue_len = queue_len;
332 if (actual_queue_len < 5) actual_queue_len = 5;
334 memset(&sin, 0, sizeof(sin));
335 sin.sin_family = AF_INET;
336 sin.sin_port = htons((u_short)port_number);
337 if (ip_addr == NULL) {
338 sin.sin_addr.s_addr = INADDR_ANY;
341 sin.sin_addr.s_addr = inet_addr(ip_addr);
344 if (sin.sin_addr.s_addr == !INADDR_ANY) {
345 sin.sin_addr.s_addr = INADDR_ANY;
348 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
351 *errormessage = (char*) malloc(SIZ + 1);
352 snprintf(*errormessage, SIZ,
353 "citserver: Can't create a socket: %s",
355 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
360 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
362 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
363 *errormessage = (char*) malloc(SIZ + 1);
364 snprintf(*errormessage, SIZ,
365 "citserver: Can't bind: %s",
367 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
372 /* set to nonblock - we need this for some obscure situations */
373 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
374 *errormessage = (char*) malloc(SIZ + 1);
375 snprintf(*errormessage, SIZ,
376 "citserver: Can't set socket to non-blocking: %s",
378 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
383 if (listen(s, actual_queue_len) < 0) {
384 *errormessage = (char*) malloc(SIZ + 1);
385 snprintf(*errormessage, SIZ,
386 "citserver: Can't listen: %s",
388 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
399 * Create a Unix domain socket and listen on it
401 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
403 struct sockaddr_un addr;
406 int actual_queue_len;
408 actual_queue_len = queue_len;
409 if (actual_queue_len < 5) actual_queue_len = 5;
411 i = unlink(sockpath);
412 if (i != 0) if (errno != ENOENT) {
413 *errormessage = (char*) malloc(SIZ + 1);
414 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
415 sockpath, strerror(errno));
416 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
420 memset(&addr, 0, sizeof(addr));
421 addr.sun_family = AF_UNIX;
422 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
424 s = socket(AF_UNIX, SOCK_STREAM, 0);
426 *errormessage = (char*) malloc(SIZ + 1);
427 snprintf(*errormessage, SIZ,
428 "citserver: Can't create a socket: %s",
430 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
434 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
435 *errormessage = (char*) malloc(SIZ + 1);
436 snprintf(*errormessage, SIZ,
437 "citserver: Can't bind: %s",
439 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
443 /* set to nonblock - we need this for some obscure situations */
444 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
445 *errormessage = (char*) malloc(SIZ + 1);
446 snprintf(*errormessage, SIZ,
447 "citserver: Can't set socket to non-blocking: %s",
449 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
454 if (listen(s, actual_queue_len) < 0) {
455 *errormessage = (char*) malloc(SIZ + 1);
456 snprintf(*errormessage, SIZ,
457 "citserver: Can't listen: %s",
459 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
463 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
470 * Return a pointer to the CitContext structure bound to the thread which
471 * called this function. If there's no such binding (for example, if it's
472 * called by the housekeeper thread) then a generic 'master' CC is returned.
474 * This function is used *VERY* frequently and must be kept small.
476 struct CitContext *MyContext(void) {
478 register struct CitContext *c;
480 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
481 c == NULL) ? &masterCC : c
487 * Initialize a new context and place it in the list. The session number
488 * used to be the PID (which is why it's called cs_pid), but that was when we
489 * had one process per session. Now we just assign them sequentially, starting
490 * at 1 (don't change it to 0 because masterCC uses 0).
492 struct CitContext *CreateNewContext(void) {
493 struct CitContext *me;
494 static int next_pid = 0;
496 me = (struct CitContext *) malloc(sizeof(struct CitContext));
498 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
501 memset(me, 0, sizeof(struct CitContext));
503 /* The new context will be created already in the CON_EXECUTING state
504 * in order to prevent another thread from grabbing it while it's
507 me->state = CON_EXECUTING;
510 * Generate a unique session number and insert this context into
513 begin_critical_section(S_SESSION_TABLE);
514 me->cs_pid = ++next_pid;
516 me->next = ContextList;
518 if (me->next != NULL) {
522 end_critical_section(S_SESSION_TABLE);
528 * The following functions implement output buffering. If the kernel supplies
529 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
530 * user-space buffering.
534 # define HAVE_TCP_BUFFERING
537 # define HAVE_TCP_BUFFERING
538 # define TCP_CORK TCP_NOPUSH
540 #endif /* TCP_CORK */
541 #endif /* HAVE_DARWIN */
543 #ifdef HAVE_TCP_BUFFERING
544 static unsigned on = 1, off = 0;
545 void buffer_output(void) {
546 struct CitContext *ctx = MyContext();
547 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
551 void unbuffer_output(void) {
552 struct CitContext *ctx = MyContext();
553 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
557 void flush_output(void) {
558 struct CitContext *ctx = MyContext();
559 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
560 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
564 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
565 void buffer_output(void) {
568 void unbuffer_output(void) {
571 void flush_output(void) {
574 void buffer_output(void) {
575 if (CC->buffering == 0) {
578 CC->output_buffer = malloc(SIZ);
582 void flush_output(void) {
583 if (CC->buffering == 1) {
584 client_write(CC->output_buffer, CC->buffer_len);
589 void unbuffer_output(void) {
590 if (CC->buffering == 1) {
592 /* We don't call flush_output because we can't. */
593 client_write(CC->output_buffer, CC->buffer_len);
595 free(CC->output_buffer);
596 CC->output_buffer = NULL;
599 #endif /* HAVE_DARWIN */
600 #endif /* HAVE_TCP_BUFFERING */
605 * client_write() ... Send binary data to the client.
607 void client_write(char *buf, int nbytes)
609 int bytes_written = 0;
611 #ifndef HAVE_TCP_BUFFERING
612 int old_buffer_len = 0;
617 if (Ctx->redirect_buffer != NULL) {
618 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
619 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
620 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
621 Ctx->redirect_alloc);
623 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
624 Ctx->redirect_len += nbytes;
625 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
629 #ifndef HAVE_TCP_BUFFERING
630 /* If we're buffering for later, do that now. */
631 if (Ctx->buffering) {
632 old_buffer_len = Ctx->buffer_len;
633 Ctx->buffer_len += nbytes;
634 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
635 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
640 /* Ok, at this point we're not buffering. Go ahead and write. */
643 if (Ctx->redirect_ssl) {
644 client_write_ssl(buf, nbytes);
649 while (bytes_written < nbytes) {
650 retval = write(Ctx->client_socket, &buf[bytes_written],
651 nbytes - bytes_written);
653 CtdlLogPrintf(CTDL_ERR,
654 "client_write(%d bytes) failed: %s (%d)\n",
655 nbytes - bytes_written,
656 strerror(errno), errno);
658 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
662 bytes_written = bytes_written + retval;
668 * cprintf() ... Send formatted printable data to the client. It is
669 * implemented in terms of client_write() but remains in
670 * sysdep.c in case we port to somewhere without va_args...
672 void cprintf(const char *format, ...) {
676 va_start(arg_ptr, format);
677 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
678 buf[sizeof buf - 2] = '\n';
679 client_write(buf, strlen(buf));
685 * Read data from the client socket.
687 * 1 Requested number of bytes has been read.
688 * 0 Request timed out.
689 * -1 The socket is broken.
690 * If the socket breaks, the session will be terminated.
692 int client_read_to(char *buf, int bytes, int timeout)
701 if (CC->redirect_ssl) {
702 return (client_read_ssl(buf, bytes, timeout));
706 fd = CC->client_socket;
713 retval = select( (fd)+1,
714 &rfds, NULL, NULL, &tv);
716 if (FD_ISSET(fd, &rfds) == 0) {
720 rlen = read(fd, &buf[len], bytes-len);
722 /* The socket has been disconnected! */
732 * Read data from the client socket with default timeout.
733 * (This is implemented in terms of client_read_to() and could be
734 * justifiably moved out of sysdep.c)
736 INLINE int client_read(char *buf, int bytes)
738 return(client_read_to(buf, bytes, config.c_sleeping));
743 * client_getln() ... Get a LF-terminated line of text from the client.
744 * (This is implemented in terms of client_read() and could be
745 * justifiably moved out of sysdep.c)
747 int client_getln(char *buf, int bufsize)
751 /* Read one character at a time.
754 retval = client_read(&buf[i], 1);
755 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
759 /* If we got a long line, discard characters until the newline.
761 if (i == (bufsize-1))
762 while (buf[i] != '\n' && retval == 1)
763 retval = client_read(&buf[i], 1);
765 /* Strip the trailing LF, and the trailing CR if present.
769 && ( (buf[i - 1]==13)
770 || ( buf[i - 1]==10)) ) {
774 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
780 * Cleanup any contexts that are left lying around
782 void context_cleanup(void)
784 struct CitContext *ptr = NULL;
785 struct CitContext *rem = NULL;
788 * Clean up the contexts.
789 * There are no threads so no critical_section stuff is needed.
793 /* Remove the session from the active list */
797 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
807 * The system-dependent part of master_cleanup() - close the master socket.
809 void sysdep_master_cleanup(void) {
810 struct ServiceFunctionHook *serviceptr;
813 * close all protocol master sockets
815 for (serviceptr = ServiceHookTable; serviceptr != NULL;
816 serviceptr = serviceptr->next ) {
818 if (serviceptr->tcp_port > 0)
819 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
820 serviceptr->tcp_port);
822 if (serviceptr->sockpath != NULL)
823 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
824 serviceptr->sockpath);
826 close(serviceptr->msock);
828 /* If it's a Unix domain socket, remove the file. */
829 if (serviceptr->sockpath != NULL) {
830 unlink(serviceptr->sockpath);
839 CtdlDestroyProtoHooks();
840 CtdlDestroyDeleteHooks();
841 CtdlDestroyXmsgHooks();
842 CtdlDestroyNetprocHooks();
843 CtdlDestroyUserHooks();
844 CtdlDestroyMessageHook();
845 CtdlDestroyCleanupHooks();
846 CtdlDestroyFixedOutputHooks();
847 CtdlDestroySessionHooks();
848 CtdlDestroyServiceHook();
849 #ifdef HAVE_BACKTRACE
857 * Terminate another session.
858 * (This could justifiably be moved out of sysdep.c because it
859 * no longer does anything that is system-dependent.)
861 void kill_session(int session_to_kill) {
862 struct CitContext *ptr;
864 begin_critical_section(S_SESSION_TABLE);
865 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
866 if (ptr->cs_pid == session_to_kill) {
870 end_critical_section(S_SESSION_TABLE);
874 void graceful_shutdown(int signum) {
875 kill(current_child, signum);
876 unlink(file_pid_file);
882 * Start running as a daemon.
884 void start_daemon(int unused) {
892 /* Close stdin/stdout/stderr and replace them with /dev/null.
893 * We don't just call close() because we don't want these fd's
894 * to be reused for other files.
903 signal(SIGHUP, SIG_IGN);
904 signal(SIGINT, SIG_IGN);
905 signal(SIGQUIT, SIG_IGN);
909 freopen("/dev/null", "r", stdin);
910 freopen("/dev/null", "w", stdout);
911 freopen("/dev/null", "w", stderr);
914 current_child = fork();
916 signal(SIGTERM, graceful_shutdown);
918 if (current_child < 0) {
923 else if (current_child == 0) {
924 return; /* continue starting citadel. */
928 fp = fopen(file_pid_file, "w");
931 * NB.. The pid file contains the pid of the actual server.
932 * This is not the pid of the watcher process
934 fprintf(fp, ""F_PID_T"\n", current_child);
937 waitpid(current_child, &status, 0);
942 /* Did the main process exit with an actual exit code? */
943 if (WIFEXITED(status)) {
945 /* Exit code 0 means the watcher should exit */
946 if (WEXITSTATUS(status) == 0) {
950 /* Exit code 101-109 means the watcher should exit */
951 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
955 /* Any other exit code means we should restart. */
961 /* Any other type of termination (signals, etc.) should also restart. */
966 } while (do_restart);
968 unlink(file_pid_file);
969 exit(WEXITSTATUS(status));
975 * Generic routine to convert a login name to a full name (gecos)
976 * Returns nonzero if a conversion took place
978 int convert_login(char NameToConvert[]) {
982 pw = getpwnam(NameToConvert);
987 strcpy(NameToConvert, pw->pw_gecos);
988 for (a=0; a<strlen(NameToConvert); ++a) {
989 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
998 * New thread interface.
999 * To create a thread you must call one of the create thread functions.
1000 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
1001 * struct CtdlThreadNode *node = NULL;
1003 * If the thread is created *node will point to the thread control structure for the created thread.
1004 * If the thread creation fails *node remains NULL
1005 * Do not free the memory pointed to by *node, it doesn't belong to you.
1006 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
1007 * remove the need for the calls to eCrashRegisterThread and friends
1011 struct CtdlThreadNode *CtdlThreadList = NULL;
1014 * Condition variable and Mutex for thread garbage collection
1016 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
1017 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
1019 static pthread_t GC_thread;
1020 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
1021 double CtdlThreadLoadAvg = 0;
1022 double CtdlThreadWorkerAvg = 0;
1023 pthread_key_t ThreadKey;
1026 * Pinched the following bits regarding signals from Kannel.org
1030 * Change this thread's signal mask to block user-visible signals
1031 * (HUP, TERM, QUIT, INT), and store the old signal mask in
1033 * Return 0 for success, or -1 if an error occurred.
1037 * This does not work in Darwin alias MacOS X alias Mach kernel,
1038 * however. So we define a dummy function doing nothing.
1040 #if defined(DARWIN_OLD)
1041 static int pthread_sigmask();
1044 static int ctdl_thread_internal_block_signals(sigset_t *old_set_storage)
1047 sigset_t block_signals;
1049 ret = sigemptyset(&block_signals);
1051 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't initialize signal set\n");
1054 ret = sigaddset(&block_signals, SIGHUP);
1055 ret |= sigaddset(&block_signals, SIGTERM);
1056 ret |= sigaddset(&block_signals, SIGQUIT);
1057 ret |= sigaddset(&block_signals, SIGINT);
1059 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't add signal to signal set.\n");
1062 ret = pthread_sigmask(SIG_BLOCK, &block_signals, old_set_storage);
1064 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't disable signals for thread creation\n");
1070 static void ctdl_thread_internal_restore_signals(sigset_t *old_set)
1074 ret = pthread_sigmask(SIG_SETMASK, old_set, NULL);
1076 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't restore signal set.\n");
1083 * A function to destroy the TSD
1085 static void ctdl_thread_internal_dest_tsd(void *arg)
1095 * A function to initialise the thread TSD
1097 void ctdl_thread_internal_init_tsd(void)
1101 if ((ret = pthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
1102 lprintf(CTDL_EMERG, "pthread_key_create: %s\n",
1109 * Ensure that we have a key for thread-specific data.
1111 * This should be called immediately after startup by any thread
1114 void CtdlThreadAllocTSD(void)
1118 if (pthread_getspecific(ThreadKey) != NULL)
1121 tsd = malloc(sizeof(ThreadTSD));
1125 memset(tsd->cursors, 0, sizeof tsd->cursors);
1128 pthread_setspecific(ThreadKey, tsd);
1132 void ctdl_thread_internal_free_tsd(void)
1134 ctdl_thread_internal_dest_tsd(pthread_getspecific(ThreadKey));
1135 pthread_setspecific(ThreadKey, NULL);
1139 void ctdl_thread_internal_cleanup(void)
1143 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
1145 free (CtdlThreadStates[i]);
1147 ctdl_thread_internal_free_tsd();
1150 void ctdl_thread_internal_init(void)
1152 struct CtdlThreadNode *this_thread;
1155 GC_thread = pthread_self();
1156 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
1157 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
1158 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
1159 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
1160 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
1161 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
1162 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
1163 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
1164 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
1165 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
1167 /* Get ourself a thread entry */
1168 this_thread = malloc(sizeof(struct CtdlThreadNode));
1169 if (this_thread == NULL) {
1170 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1173 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1174 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1176 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1177 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1178 pthread_mutex_init (&(this_thread->SleepMutex), NULL);
1179 pthread_cond_init (&(this_thread->SleepCond), NULL);
1181 /* We are garbage collector so create us as running */
1182 this_thread->state = CTDL_THREAD_RUNNING;
1184 if ((ret = pthread_attr_init(&this_thread->attr))) {
1185 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1190 this_thread->name = "Garbage Collection Thread";
1192 this_thread->tid = GC_thread;
1195 num_threads++; // Increase the count of threads in the system.
1197 this_thread->next = CtdlThreadList;
1198 CtdlThreadList = this_thread;
1199 if (this_thread->next)
1200 this_thread->next->prev = this_thread;
1201 /* Set up start times */
1202 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
1203 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
1208 * A function to update a threads load averages
1210 void ctdl_thread_internal_update_avgs(struct CtdlThreadNode *this_thread)
1212 struct timeval now, result;
1213 double last_duration;
1215 gettimeofday(&now, NULL);
1216 timersub(&now, &(this_thread->last_state_change), &result);
1217 pthread_mutex_lock(&this_thread->ThreadMutex);
1218 // result now has a timeval for the time we spent in the last state since we last updated
1219 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1220 if (this_thread->state == CTDL_THREAD_SLEEPING)
1221 this_thread->avg_sleeping += last_duration;
1222 if (this_thread->state == CTDL_THREAD_RUNNING)
1223 this_thread->avg_running += last_duration;
1224 if (this_thread->state == CTDL_THREAD_BLOCKED)
1225 this_thread->avg_blocked += last_duration;
1226 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
1227 pthread_mutex_unlock(&this_thread->ThreadMutex);
1231 * A function to chenge the state of a thread
1233 void ctdl_thread_internal_change_state (struct CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
1236 * Wether we change state or not we need update the load values
1238 ctdl_thread_internal_update_avgs(this_thread);
1239 pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1240 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
1241 this_thread->state = new_state;
1242 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
1243 this_thread->state = new_state;
1244 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
1245 this_thread->state = new_state;
1246 pthread_mutex_unlock(&this_thread->ThreadMutex);
1251 * A function to tell all threads to exit
1253 void CtdlThreadStopAll(void)
1255 //FIXME: The signalling of the condition should not be in the critical_section
1256 // We need to build a list of threads we are going to signal and then signal them afterwards
1258 struct CtdlThreadNode *this_thread;
1260 begin_critical_section(S_THREAD_LIST);
1261 this_thread = CtdlThreadList;
1264 if (this_thread->thread_func) // Don't tell garbage collector to stop
1266 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1267 // pthread_mutex_lock(&this_thread->ThreadMutex);
1268 pthread_cond_signal(&this_thread->ThreadCond);
1269 pthread_cond_signal(&this_thread->SleepCond);
1270 // pthread_mutex_unlock(&this_thread->ThreadMutex);
1271 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (%ld).\n", this_thread->name, this_thread->tid);
1273 this_thread = this_thread->next;
1275 end_critical_section(S_THREAD_LIST);
1280 * A function to wake up all sleeping threads
1282 void CtdlThreadWakeAll(void)
1284 struct CtdlThreadNode *this_thread;
1286 CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
1288 begin_critical_section(S_THREAD_LIST);
1289 this_thread = CtdlThreadList;
1292 if (!this_thread->thread_func)
1294 // pthread_mutex_lock(&this_thread->ThreadMutex);
1295 pthread_cond_signal(&this_thread->ThreadCond);
1296 pthread_cond_signal(&this_thread->SleepCond);
1297 // pthread_mutex_unlock(&this_thread->ThreadMutex);
1299 this_thread = this_thread->next;
1301 end_critical_section(S_THREAD_LIST);
1306 * A function to return the number of threads running in the system
1308 int CtdlThreadGetCount(void)
1312 begin_critical_section(S_THREAD_LIST);
1314 end_critical_section(S_THREAD_LIST);
1318 int CtdlThreadGetWorkers(void)
1322 begin_critical_section(S_THREAD_LIST);
1324 end_critical_section(S_THREAD_LIST);
1328 double CtdlThreadGetWorkerAvg(void)
1332 begin_critical_section(S_THREAD_LIST);
1333 ret = CtdlThreadWorkerAvg;
1334 end_critical_section(S_THREAD_LIST);
1338 double CtdlThreadGetLoadAvg(void)
1342 begin_critical_section(S_THREAD_LIST);
1343 ret = CtdlThreadLoadAvg;
1344 end_critical_section(S_THREAD_LIST);
1352 * A function to rename a thread
1353 * Returns a const char *
1355 const char *CtdlThreadName(const char *name)
1357 const char *old_name;
1361 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
1364 pthread_mutex_lock(&CT->ThreadMutex);
1365 old_name = CT->name;
1368 pthread_mutex_unlock(&CT->ThreadMutex);
1374 * A function to force a thread to exit
1376 void CtdlThreadCancel(struct CtdlThreadNode *thread)
1378 struct CtdlThreadNode *this_thread;
1383 this_thread = thread;
1386 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
1387 CtdlThreadStopAll();
1391 if (!this_thread->thread_func)
1393 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
1394 CtdlThreadStopAll();
1398 // begin_critical_section(S_THREAD_LIST);
1399 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
1400 pthread_cancel(this_thread->tid);
1401 // end_critical_section (S_THREAD_LIST);
1407 * A function for a thread to check if it has been asked to stop
1409 int CtdlThreadCheckStop(void)
1413 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
1414 CtdlThreadStopAll();
1417 pthread_mutex_lock(&CT->ThreadMutex);
1418 if(CT->state == CTDL_THREAD_STOP_REQ)
1420 CT->state = CTDL_THREAD_STOPPING;
1421 pthread_mutex_unlock(&CT->ThreadMutex);
1424 else if((CT->state < CTDL_THREAD_STOP_REQ) && (CT->state > CTDL_THREAD_CREATE))
1426 pthread_mutex_unlock(&CT->ThreadMutex);
1429 pthread_mutex_unlock(&CT->ThreadMutex);
1435 * A function to ask a thread to exit
1436 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
1438 void CtdlThreadStop(struct CtdlThreadNode *thread)
1440 struct CtdlThreadNode *this_thread;
1445 this_thread = thread;
1448 if (!(this_thread->thread_func))
1449 return; // Don't stop garbage collector
1451 // begin_critical_section (S_THREAD_LIST);
1452 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1453 // pthread_mutex_lock(&this_thread->ThreadMutex);
1454 pthread_cond_signal(&this_thread->ThreadCond);
1455 pthread_cond_signal(&this_thread->SleepCond);
1456 // pthread_mutex_unlock(&this_thread->ThreadMutex);
1457 // end_critical_section(S_THREAD_LIST);
1461 * So we now have a sleep command that works with threads but it is in seconds
1463 void CtdlThreadSleep(int secs)
1465 struct timespec wake_time;
1466 struct timeval time_now;
1471 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
1475 memset (&wake_time, 0, sizeof(struct timespec));
1476 gettimeofday(&time_now, NULL);
1477 wake_time.tv_sec = time_now.tv_sec + secs;
1478 wake_time.tv_nsec = time_now.tv_usec * 10;
1480 // begin_critical_section(S_THREAD_LIST);
1481 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
1482 // end_critical_section(S_THREAD_LIST);
1484 // pthread_mutex_lock(&self->SleepMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1485 pthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1486 pthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
1487 pthread_mutex_unlock(&CT->ThreadMutex);
1488 // pthread_mutex_unlock(&self->SleepMutex);
1490 // begin_critical_section(S_THREAD_LIST);
1491 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
1492 // end_critical_section(S_THREAD_LIST);
1497 * Routine to clean up our thread function on exit
1499 static void ctdl_internal_thread_cleanup(void *arg)
1502 * In here we were called by the current thread because it is exiting
1503 * NB. WE ARE THE CURRENT THREAD
1505 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", CT->name, CT->tid);
1506 // begin_critical_section(S_THREAD_LIST);
1507 #ifdef HAVE_BACKTRACE
1508 eCrash_UnregisterThread();
1510 pthread_mutex_lock(&CT->ThreadMutex);
1511 CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
1512 pthread_mutex_unlock(&CT->ThreadMutex);
1513 // end_critical_section(S_THREAD_LIST);
1518 * A quick function to show the load averages
1520 void ctdl_thread_internal_calc_loadavg(void)
1522 struct CtdlThreadNode *that_thread;
1523 double load_avg, worker_avg;
1526 that_thread = CtdlThreadList;
1531 /* Update load averages */
1532 ctdl_thread_internal_update_avgs(that_thread);
1533 pthread_mutex_lock(&that_thread->ThreadMutex);
1534 that_thread->load_avg = that_thread->avg_sleeping + that_thread->avg_running + that_thread->avg_blocked;
1535 that_thread->load_avg = that_thread->avg_running / that_thread->load_avg * 100;
1536 that_thread->avg_sleeping /= 2;
1537 that_thread->avg_running /= 2;
1538 that_thread->avg_blocked /= 2;
1539 load_avg += that_thread->load_avg;
1540 if (that_thread->flags & CTDLTHREAD_WORKER)
1542 worker_avg += that_thread->load_avg;
1545 #ifdef WITH_THREADLOG
1546 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%ld) \"%s\" %f %f %f %f.\n",
1549 CtdlThreadStates[that_thread->state],
1550 that_thread->avg_sleeping,
1551 that_thread->avg_running,
1552 that_thread->avg_blocked,
1553 that_thread->load_avg);
1555 pthread_mutex_unlock(&that_thread->ThreadMutex);
1556 that_thread = that_thread->next;
1558 CtdlThreadLoadAvg = load_avg/num_threads;
1559 CtdlThreadWorkerAvg = worker_avg/workers;
1560 #ifdef WITH_THREADLOG
1561 CtdlLogPrintf(CTDL_INFO, "System load average %f, workers averag %f, threads %d, workers %d, sessions %d\n", CtdlThreadLoadAvg, CtdlThreadWorkerAvg, num_threads, num_workers, num_sessions);
1567 * Garbage collection routine.
1568 * Gets called by main() in a loop to clean up the thread list periodically.
1570 void CtdlThreadGC (void)
1572 struct CtdlThreadNode *this_thread, *that_thread;
1575 begin_critical_section(S_THREAD_LIST);
1577 /* Handle exiting of garbage collector thread */
1578 if(num_threads == 1)
1579 CtdlThreadList->state = CTDL_THREAD_EXITED;
1581 #ifdef WITH_THREADLOG
1582 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
1585 * Woke up to do garbage collection
1587 this_thread = CtdlThreadList;
1590 that_thread = this_thread;
1591 this_thread = this_thread->next;
1593 /* Do we need to clean up this thread? */
1594 pthread_mutex_lock(&that_thread->ThreadMutex);
1595 if (that_thread->state != CTDL_THREAD_EXITED)
1597 if(that_thread->flags & CTDLTHREAD_WORKER)
1598 workers++; /* Sanity check on number of worker threads */
1599 pthread_mutex_unlock(&that_thread->ThreadMutex);
1603 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
1604 { /* Sanity check */
1605 pthread_mutex_unlock(&that_thread->ThreadMutex);
1606 end_critical_section(S_THREAD_LIST);
1607 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
1612 if (num_threads <= 0)
1613 { /* Sanity check */
1614 pthread_mutex_unlock(&that_thread->ThreadMutex);
1615 end_critical_section(S_THREAD_LIST);
1616 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
1621 if(that_thread->flags & CTDLTHREAD_WORKER)
1622 num_workers--; /* This is a wroker thread so reduce the count. */
1624 /* If we are unlinking the list head then the next becomes the list head */
1625 if (that_thread == CtdlThreadList)
1626 CtdlThreadList = that_thread->next;
1627 if(that_thread->prev)
1628 that_thread->prev->next = that_thread->next;
1629 if(that_thread->next)
1630 that_thread->next->prev = that_thread->next;
1632 pthread_mutex_unlock(&that_thread->ThreadMutex);
1633 pthread_cond_signal(&that_thread->ThreadCond);
1634 pthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
1635 pthread_mutex_lock(&that_thread->ThreadMutex); // Make sure it has done what its doing
1636 pthread_mutex_unlock(&that_thread->ThreadMutex);
1638 * Join on the thread to do clean up and prevent memory leaks
1639 * Also makes sure the thread has cleaned up after itself before we remove it from the list
1640 * If that thread has no function it must be the garbage collector
1642 if (that_thread->thread_func)
1643 pthread_join (that_thread->tid, NULL);
1646 * Now we own that thread entry
1648 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (%ld).\n", that_thread->name, that_thread->tid);
1649 pthread_mutex_destroy(&that_thread->ThreadMutex);
1650 pthread_cond_destroy(&that_thread->ThreadCond);
1651 pthread_mutex_destroy(&that_thread->SleepMutex);
1652 pthread_cond_destroy(&that_thread->SleepCond);
1653 pthread_attr_destroy(&that_thread->attr);
1657 /* Sanity check number of worker threads */
1658 if (workers != num_workers)
1660 end_critical_section(S_THREAD_LIST);
1661 CtdlLogPrintf(CTDL_EMERG,
1662 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
1663 workers, num_workers
1667 end_critical_section(S_THREAD_LIST);
1674 * Runtime function for a Citadel Thread.
1675 * This initialises the threads environment and then calls the user supplied thread function
1676 * Note that this is the REAL thread function and wraps the users thread function.
1678 static void *ctdl_internal_thread_func (void *arg)
1680 struct CtdlThreadNode *this_thread;
1683 /* lock and unlock the thread list.
1684 * This causes this thread to wait until all its creation stuff has finished before it
1685 * can continue its execution.
1687 begin_critical_section(S_THREAD_LIST);
1688 this_thread = (struct CtdlThreadNode *) arg;
1689 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
1690 pthread_mutex_lock(&this_thread->ThreadMutex);
1692 // Register the cleanup function to take care of when we exit.
1693 pthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
1694 // Get our thread data structure
1695 CtdlThreadAllocTSD();
1697 this_thread->pid = getpid();
1698 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
1699 /* Only change to running state if we weren't asked to stop during the create cycle
1700 * Other wise there is a window to allow this threads creation to continue to full grown and
1701 * therby prevent a shutdown of the server.
1703 pthread_mutex_unlock(&this_thread->ThreadMutex);
1705 if (!CtdlThreadCheckStop())
1707 pthread_mutex_lock(&this_thread->ThreadMutex);
1708 this_thread->state = CTDL_THREAD_RUNNING;
1709 pthread_mutex_unlock(&this_thread->ThreadMutex);
1711 end_critical_section(S_THREAD_LIST);
1713 // Register for tracing
1714 #ifdef HAVE_BACKTRACE
1715 eCrash_RegisterThread(this_thread->name, 0);
1718 // Tell the world we are here
1719 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1724 * run the thread to do the work but only if we haven't been asked to stop
1726 if (!CtdlThreadCheckStop())
1727 ret = (this_thread->thread_func)(this_thread->user_args);
1730 * Our thread is exiting either because it wanted to end or because the server is stopping
1731 * We need to clean up
1733 pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1741 * Internal function to create a thread.
1742 * Must be called from within a S_THREAD_LIST critical section
1744 struct CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1747 struct CtdlThreadNode *this_thread;
1749 sigset_t old_signal_set;
1751 if (num_threads >= 32767)
1753 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1757 this_thread = malloc(sizeof(struct CtdlThreadNode));
1758 if (this_thread == NULL) {
1759 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1762 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1763 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1765 /* Create the mutex's early so we can use them */
1766 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1767 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1768 pthread_mutex_init (&(this_thread->SleepMutex), NULL);
1769 pthread_cond_init (&(this_thread->SleepCond), NULL);
1771 pthread_mutex_lock(&this_thread->ThreadMutex);
1773 this_thread->state = CTDL_THREAD_CREATE;
1775 if ((ret = pthread_attr_init(&this_thread->attr))) {
1776 pthread_mutex_unlock(&this_thread->ThreadMutex);
1777 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1778 pthread_cond_destroy(&(this_thread->ThreadCond));
1779 pthread_mutex_destroy(&(this_thread->SleepMutex));
1780 pthread_cond_destroy(&(this_thread->SleepCond));
1781 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1786 /* Our per-thread stacks need to be bigger than the default size,
1787 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1788 * crashes on 64-bit Linux.
1790 if (flags & CTDLTHREAD_BIGSTACK)
1792 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1793 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1794 pthread_mutex_unlock(&this_thread->ThreadMutex);
1795 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1796 pthread_cond_destroy(&(this_thread->ThreadCond));
1797 pthread_mutex_destroy(&(this_thread->SleepMutex));
1798 pthread_cond_destroy(&(this_thread->SleepCond));
1799 pthread_attr_destroy(&this_thread->attr);
1800 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1808 * If we got here we are going to create the thread so we must initilise the structure
1809 * first because most implimentations of threading can't create it in a stopped state
1810 * and it might want to do things with its structure that aren't initialised otherwise.
1814 this_thread->name = name;
1818 this_thread->name = "Un-named Thread";
1821 this_thread->flags = flags;
1822 this_thread->thread_func = thread_func;
1823 this_thread->user_args = args;
1824 /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
1825 * load average for the system. If we don't do this then we create a mass of threads at the same time
1826 * because the creation didn't affect the load average.
1828 this_thread->avg_blocked = 2;
1831 * We want to make sure that only the main thread handles signals,
1832 * so that each signal is handled exactly once. To do this, we
1833 * make sure that each new thread has all the signals that we
1834 * handle blocked. To avoid race conditions, we block them in
1835 * the spawning thread first, then create the new thread (which
1836 * inherits the settings), and then restore the old settings in
1837 * the spawning thread. This means that there is a brief period
1838 * when no signals will be processed, but during that time they
1839 * should be queued by the operating system.
1841 // if (pthread_equal(GC_thread, pthread_self()))
1842 // sigtrick = ctdl_thread_internal_block_signals(&old_signal_set) == 0;
1845 * We pass this_thread into the thread as its args so that it can find out information
1846 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1847 * thread function needs to finish off the setup of the structure
1849 if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1852 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1854 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1855 pthread_cond_destroy(&(this_thread->ThreadCond));
1856 pthread_mutex_destroy(&(this_thread->SleepMutex));
1857 pthread_cond_destroy(&(this_thread->SleepCond));
1858 pthread_attr_destroy(&this_thread->attr);
1861 // ctdl_thread_internal_restore_signals(&old_signal_set);
1866 // ctdl_thread_internal_restore_signals(&old_signal_set);
1868 num_threads++; // Increase the count of threads in the system.
1869 if(this_thread->flags & CTDLTHREAD_WORKER)
1872 this_thread->next = CtdlThreadList;
1873 CtdlThreadList = this_thread;
1874 if (this_thread->next)
1875 this_thread->next->prev = this_thread;
1877 pthread_mutex_unlock(&this_thread->ThreadMutex);
1879 ctdl_thread_internal_calc_loadavg();
1884 * Wrapper function to create a thread
1885 * ensures the critical section and other protections are in place.
1886 * char *name = name to give to thread, if NULL, use generic name
1887 * int flags = flags to determine type of thread and standard facilities
1889 struct CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1891 struct CtdlThreadNode *ret = NULL;
1893 begin_critical_section(S_THREAD_LIST);
1894 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1895 end_critical_section(S_THREAD_LIST);
1902 * A warapper function for select so we can show a thread as blocked
1904 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout, struct CtdlThreadNode *self)
1908 ctdl_thread_internal_change_state(self, CTDL_THREAD_BLOCKED);
1909 ret = select(n, readfds, writefds, exceptfds, timeout);
1910 ctdl_thread_internal_change_state(self, CTDL_THREAD_RUNNING);
1915 * Purge all sessions which have the 'kill_me' flag set.
1916 * This function has code to prevent it from running more than once every
1917 * few seconds, because running it after every single unbind would waste a lot
1918 * of CPU time and keep the context list locked too much. To force it to run
1919 * anyway, set "force" to nonzero.
1921 void dead_session_purge(int force) {
1922 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1923 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1926 if ( (time(NULL) - last_purge) < 5 ) {
1927 return; /* Too soon, go away */
1932 if (try_critical_section(S_SESSION_TABLE))
1940 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1941 /* Remove the session from the active list */
1943 ptr2->prev->next = ptr2->next;
1946 ContextList = ptr2->next;
1949 ptr2->next->prev = ptr2->prev;
1953 /* And put it on our to-be-destroyed list */
1958 end_critical_section(S_SESSION_TABLE);
1960 /* Now that we no longer have the session list locked, we can take
1961 * our time and destroy any sessions on the to-be-killed list, which
1962 * is allocated privately on this thread's stack.
1964 while (rem != NULL) {
1965 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1978 * masterCC is the context we use when not attached to a session. This
1979 * function initializes it.
1981 void InitializeMasterCC(void) {
1982 memset(&masterCC, 0, sizeof(struct CitContext));
1983 masterCC.internal_pgm = 1;
1984 masterCC.cs_pid = 0;
1993 * Bind a thread to a context. (It's inline merely to speed things up.)
1995 INLINE void become_session(struct CitContext *which_con) {
1996 pthread_setspecific(MyConKey, (void *)which_con );
2002 * This loop just keeps going and going and going...
2004 void *worker_thread(void *arg) {
2007 struct CitContext *ptr;
2008 struct CitContext *bind_me = NULL;
2011 struct CitContext *con= NULL; /* Temporary context pointer */
2012 struct ServiceFunctionHook *serviceptr;
2013 int ssock; /* Descriptor for client socket */
2015 int force_purge = 0;
2019 while (!CtdlThreadCheckStop()) {
2021 /* make doubly sure we're not holding any stale db handles
2022 * which might cause a deadlock.
2024 cdb_check_handles();
2025 do_select: force_purge = 0;
2026 bind_me = NULL; /* Which session shall we handle? */
2028 /* Initialize the fdset. */
2032 begin_critical_section(S_SESSION_TABLE);
2033 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2034 if (ptr->state == CON_IDLE) {
2035 FD_SET(ptr->client_socket, &readfds);
2036 if (ptr->client_socket > highest)
2037 highest = ptr->client_socket;
2039 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
2041 ptr->state = CON_EXECUTING;
2044 end_critical_section(S_SESSION_TABLE);
2050 /* If we got this far, it means that there are no sessions
2051 * which a previous thread marked for attention, so we go
2052 * ahead and get ready to select().
2055 /* First, add the various master sockets to the fdset. */
2056 for (serviceptr = ServiceHookTable; serviceptr != NULL;
2057 serviceptr = serviceptr->next ) {
2058 m = serviceptr->msock;
2059 FD_SET(m, &readfds);
2065 if (!CtdlThreadCheckStop()) {
2066 tv.tv_sec = 1; /* wake up every second if no input */
2068 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv, CT);
2071 if (CtdlThreadCheckStop()) return(NULL);
2073 /* Now figure out who made this select() unblock.
2074 * First, check for an error or exit condition.
2077 if (errno == EBADF) {
2078 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
2082 if (errno != EINTR) {
2083 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
2084 CtdlThreadStopAll();
2085 } else if (!CtdlThreadCheckStop()) {
2086 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
2090 else if(retval == 0) {
2093 /* Next, check to see if it's a new client connecting
2094 * on a master socket.
2096 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
2097 serviceptr = serviceptr->next ) {
2099 if (FD_ISSET(serviceptr->msock, &readfds)) {
2100 ssock = accept(serviceptr->msock, NULL, 0);
2102 CtdlLogPrintf(CTDL_DEBUG,
2103 "New client socket %d\n",
2106 /* The master socket is non-blocking but the client
2107 * sockets need to be blocking, otherwise certain
2108 * operations barf on FreeBSD. Not a fatal error.
2110 if (fcntl(ssock, F_SETFL, 0) < 0) {
2111 CtdlLogPrintf(CTDL_EMERG,
2112 "citserver: Can't set socket to blocking: %s\n",
2116 /* New context will be created already
2117 * set up in the CON_EXECUTING state.
2119 con = CreateNewContext();
2121 /* Assign our new socket number to it. */
2122 con->client_socket = ssock;
2123 con->h_command_function =
2124 serviceptr->h_command_function;
2125 con->h_async_function =
2126 serviceptr->h_async_function;
2128 serviceptr->ServiceName;
2130 /* Determine whether it's a local socket */
2131 if (serviceptr->sockpath != NULL)
2132 con->is_local_socket = 1;
2134 /* Set the SO_REUSEADDR socket option */
2136 setsockopt(ssock, SOL_SOCKET,
2140 become_session(con);
2142 serviceptr->h_greeting_function();
2143 become_session(NULL);
2144 con->state = CON_IDLE;
2150 /* It must be a client socket. Find a context that has data
2151 * waiting on its socket *and* is in the CON_IDLE state. Any
2152 * active sockets other than our chosen one are marked as
2153 * CON_READY so the next thread that comes around can just bind
2154 * to one without having to select() again.
2156 begin_critical_section(S_SESSION_TABLE);
2157 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2158 if ( (FD_ISSET(ptr->client_socket, &readfds))
2159 && (ptr->state != CON_EXECUTING) ) {
2160 ptr->input_waiting = 1;
2162 bind_me = ptr; /* I choose you! */
2163 bind_me->state = CON_EXECUTING;
2166 ptr->state = CON_READY;
2170 end_critical_section(S_SESSION_TABLE);
2173 /* We're bound to a session */
2174 if (bind_me != NULL) {
2175 become_session(bind_me);
2177 /* If the client has sent a command, execute it. */
2178 if (CC->input_waiting) {
2179 CC->h_command_function();
2180 CC->input_waiting = 0;
2183 /* If there are asynchronous messages waiting and the
2184 * client supports it, do those now */
2185 if ((CC->is_async) && (CC->async_waiting)
2186 && (CC->h_async_function != NULL)) {
2187 CC->h_async_function();
2188 CC->async_waiting = 0;
2191 force_purge = CC->kill_me;
2192 become_session(NULL);
2193 bind_me->state = CON_IDLE;
2196 dead_session_purge(force_purge);
2199 /* If control reaches this point, the server is shutting down */
2208 * Translate text facility name to syslog.h defined value.
2210 int SyslogFacility(char *name)
2219 { LOG_KERN, "kern" },
2220 { LOG_USER, "user" },
2221 { LOG_MAIL, "mail" },
2222 { LOG_DAEMON, "daemon" },
2223 { LOG_AUTH, "auth" },
2224 { LOG_SYSLOG, "syslog" },
2226 { LOG_NEWS, "news" },
2227 { LOG_UUCP, "uucp" },
2228 { LOG_LOCAL0, "local0" },
2229 { LOG_LOCAL1, "local1" },
2230 { LOG_LOCAL2, "local2" },
2231 { LOG_LOCAL3, "local3" },
2232 { LOG_LOCAL4, "local4" },
2233 { LOG_LOCAL5, "local5" },
2234 { LOG_LOCAL6, "local6" },
2235 { LOG_LOCAL7, "local7" },
2238 for(i = 0; facTbl[i].name != NULL; i++) {
2239 if(!strcasecmp(name, facTbl[i].name))
2240 return facTbl[i].facility;
2247 /********** MEM CHEQQER ***********/
2249 #ifdef DEBUG_MEMORY_LEAKS
2256 void *tracked_malloc(size_t size, char *file, int line) {
2257 struct igheap *thisheap;
2260 block = malloc(size);
2261 if (block == NULL) return(block);
2263 thisheap = malloc(sizeof(struct igheap));
2264 if (thisheap == NULL) {
2269 thisheap->block = block;
2270 strcpy(thisheap->file, file);
2271 thisheap->line = line;
2273 begin_critical_section(S_DEBUGMEMLEAKS);
2274 thisheap->next = igheap;
2276 end_critical_section(S_DEBUGMEMLEAKS);
2282 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
2283 struct igheap *thisheap;
2286 block = realloc(ptr, size);
2287 if (block == NULL) return(block);
2289 thisheap = malloc(sizeof(struct igheap));
2290 if (thisheap == NULL) {
2295 thisheap->block = block;
2296 strcpy(thisheap->file, file);
2297 thisheap->line = line;
2299 begin_critical_section(S_DEBUGMEMLEAKS);
2300 thisheap->next = igheap;
2302 end_critical_section(S_DEBUGMEMLEAKS);
2309 void tracked_free(void *ptr) {
2310 struct igheap *thisheap;
2311 struct igheap *trash;
2315 if (igheap == NULL) return;
2316 begin_critical_section(S_DEBUGMEMLEAKS);
2317 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2318 if (thisheap->next != NULL) {
2319 if (thisheap->next->block == ptr) {
2320 trash = thisheap->next;
2321 thisheap->next = thisheap->next->next;
2326 if (igheap->block == ptr) {
2328 igheap = igheap->next;
2331 end_critical_section(S_DEBUGMEMLEAKS);
2334 char *tracked_strdup(const char *s, char *file, int line) {
2337 if (s == NULL) return(NULL);
2338 ptr = tracked_malloc(strlen(s) + 1, file, line);
2339 if (ptr == NULL) return(NULL);
2340 strncpy(ptr, s, strlen(s));
2344 void dump_heap(void) {
2345 struct igheap *thisheap;
2347 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2348 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
2349 thisheap->file, thisheap->line);
2353 #endif /* DEBUG_MEMORY_LEAKS */