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>
76 #ifdef DEBUG_MEMORY_LEAKS
84 struct igheap *igheap = NULL;
88 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
89 pthread_key_t MyConKey; /* TSD key for MyContext() */
91 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
93 struct CitContext masterCC;
94 time_t last_purge = 0; /* Last dead session purge */
95 static int num_threads = 0; /* Current number of threads */
96 int num_sessions = 0; /* Current number of sessions */
98 int syslog_facility = LOG_DAEMON;
99 int enable_syslog = 0;
101 void DestroyWorkerList(void);
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 time_to_die = 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 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
184 master_cleanup(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 lprintf(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 /* lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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 lprintf(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);
632 "client_write(%d bytes) failed: %s (%d)\n",
633 nbytes - bytes_written,
634 strerror(errno), errno);
636 // lprintf(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);
759 * The system-dependent part of master_cleanup() - close the master socket.
761 void sysdep_master_cleanup(void) {
762 struct ServiceFunctionHook *serviceptr;
764 ///// DestroyWorkerList();
766 * close all protocol master sockets
768 for (serviceptr = ServiceHookTable; serviceptr != NULL;
769 serviceptr = serviceptr->next ) {
771 if (serviceptr->tcp_port > 0)
772 lprintf(CTDL_INFO, "Closing listener on port %d\n",
773 serviceptr->tcp_port);
775 if (serviceptr->sockpath != NULL)
776 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
777 serviceptr->sockpath);
779 close(serviceptr->msock);
781 /* If it's a Unix domain socket, remove the file. */
782 if (serviceptr->sockpath != NULL) {
783 unlink(serviceptr->sockpath);
789 serv_calendar_destroy(); // FIXME: Shouldn't be here, should be by a cleanup hook surely.
790 CtdlDestroyProtoHooks();
791 CtdlDestroyDeleteHooks();
792 CtdlDestroyXmsgHooks();
793 CtdlDestroyNetprocHooks();
794 CtdlDestroyUserHooks();
795 CtdlDestroyMessageHook();
796 CtdlDestroyCleanupHooks();
797 CtdlDestroyFixedOutputHooks();
798 CtdlDestroySessionHooks();
799 CtdlDestroyServiceHook();
800 #ifdef HAVE_BACKTRACE
809 * Terminate another session.
810 * (This could justifiably be moved out of sysdep.c because it
811 * no longer does anything that is system-dependent.)
813 void kill_session(int session_to_kill) {
814 struct CitContext *ptr;
816 begin_critical_section(S_SESSION_TABLE);
817 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
818 if (ptr->cs_pid == session_to_kill) {
822 end_critical_section(S_SESSION_TABLE);
826 void graceful_shutdown(int signum) {
827 kill(current_child, signum);
828 unlink(file_pid_file);
834 * Start running as a daemon.
836 void start_daemon(int unused) {
844 /* Close stdin/stdout/stderr and replace them with /dev/null.
845 * We don't just call close() because we don't want these fd's
846 * to be reused for other files.
855 signal(SIGHUP, SIG_IGN);
856 signal(SIGINT, SIG_IGN);
857 signal(SIGQUIT, SIG_IGN);
861 freopen("/dev/null", "r", stdin);
862 freopen("/dev/null", "w", stdout);
863 freopen("/dev/null", "w", stderr);
866 current_child = fork();
868 signal(SIGTERM, graceful_shutdown);
870 if (current_child < 0) {
875 else if (current_child == 0) {
876 return; /* continue starting citadel. */
880 fp = fopen(file_pid_file, "w");
883 * NB.. The pid file contains the pid of the actual server.
884 * This is not the pid of the watcher process
886 fprintf(fp, ""F_PID_T"\n", current_child);
889 waitpid(current_child, &status, 0);
894 /* Did the main process exit with an actual exit code? */
895 if (WIFEXITED(status)) {
897 /* Exit code 0 means the watcher should exit */
898 if (WEXITSTATUS(status) == 0) {
902 /* Exit code 101-109 means the watcher should exit */
903 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
907 /* Any other exit code means we should restart. */
913 /* Any other type of termination (signals, etc.) should also restart. */
918 } while (do_restart);
920 unlink(file_pid_file);
921 exit(WEXITSTATUS(status));
927 * Generic routine to convert a login name to a full name (gecos)
928 * Returns nonzero if a conversion took place
930 int convert_login(char NameToConvert[]) {
934 pw = getpwnam(NameToConvert);
939 strcpy(NameToConvert, pw->pw_gecos);
940 for (a=0; a<strlen(NameToConvert); ++a) {
941 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
950 * New thread interface.
951 * To create a thread you must call one of the create thread functions.
952 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
953 * struct CtdlThreadNode *node = NULL;
955 * If the thread is created *node will point to the thread control structure for the created thread.
956 * If the thread creation fails *node remains NULL
957 * Do not free the memory pointed to by *node, it doesn't belong to you.
958 * If your thread function returns it will be started again without creating a new thread.
959 * If your thread function wants to exit it should call CtdlThreadExit(ret_code);
960 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
961 * remove the need for the calls to eCrashRegisterThread and friends
964 // FIXME: these defines should be else where
965 #define CTDLTHREAD_BIGSTACK 0x0001
967 struct CtdlThreadNode *CtdlThreadList = NULL;
968 static pthread_mutex_t ThreadWaiterMutex = PTHREAD_MUTEX_INITIALIZER;
969 static pthread_cond_t ThreadWaiterCond = PTHREAD_COND_INITIALIZER;
973 * So we now have a sleep command that works with threads but it is in seconds
975 void CtdlThreadSleep(int secs)
978 struct timespec wake_time;
979 struct timeval time_now;
982 memset (&wake_time, 0, sizeof(struct timespec));
983 gettimeofday(&time_now, NULL);
984 wake_time.tv_sec = time_now.tv_sec + secs;
985 pthread_cond_timedwait(&ThreadWaiterCond, &ThreadWaiterMutex, &wake_time);
990 * Routine to clean up our thread function on exit
992 void ctdl_internal_thread_cleanup(void *arg)
994 struct CtdlThreadNode *this_thread;
995 // arg is a pointer to our thread structure
996 this_thread = (struct CtdlThreadNode *) arg;
997 if (this_thread->valid)
1000 * In here we were called by the current thread because it is exiting
1001 * NB. WE ARE THE CURRENT THREAD
1003 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", this_thread->name, this_thread->tid);
1004 this_thread->running = FALSE;
1005 this_thread->valid = FALSE; // needs to be last thing else house keeping will unlink us too early
1007 * Our thread is exiting either because it wanted to end or because the server is stopping
1008 * We need to clean up
1010 #ifdef HAVE_BACKTRACE
1011 eCrash_UnregisterThread();
1016 if (this_thread->tid == pthread_self())
1018 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC a thread is trying to clean up after itself.\n");
1023 * In here we were called by some other thread that wants to clean up any dead threads
1024 * NB. WE ARE NOT THE THREAD BEING CLEANED
1026 // We probably got called by house keeping or master shutdown so we unlink the dead threads here
1029 begin_critical_section(S_THREAD_LIST);
1030 if(this_thread->name)
1031 free(this_thread->name);
1032 if(this_thread->prev)
1033 this_thread->prev->next = this_thread->next;
1034 if(this_thread->next)
1035 this_thread->next->prev = this_thread->next;
1036 end_critical_section(S_THREAD_LIST);
1043 * Garbage collection routine.
1044 * Gets called by do_housekeeping() and in master_cleanup() to clean up the thread list
1046 void ctdl_internal_thread_gc (int shutdown)
1048 struct CtdlThreadNode *this_thread, *that_thread;
1050 this_thread = CtdlThreadList;
1053 that_thread = this_thread;
1054 this_thread = this_thread->next;
1056 if(shutdown && that_thread->valid)
1057 { // We want the threads to shutdown so first ask it nicely
1058 that_thread->running = FALSE;
1059 // Wait for it to exit
1062 if(that_thread->valid) // Be more brutal about it
1063 pthread_cancel (that_thread->tid);
1064 // Wait for it to exit
1068 if (that_thread->valid == FALSE)
1070 CtdlLogPrintf(CTDL_NOTICE, "Joining thread \"%s\" (%ld)\n", that_thread->name, that_thread->tid);
1071 pthread_join(that_thread->tid, NULL);
1072 ctdl_internal_thread_cleanup(that_thread);
1078 * Runtime function for a Citadel Thread.
1079 * This initialises the threads environment and then calls the user supplied thread function
1080 * Note that this is the REAL thread function and wraps the users thread function.
1082 void *ctdl_internal_thread_func (void *arg)
1084 struct CtdlThreadNode *this_thread;
1087 // Get our thread data structure
1088 this_thread = (struct CtdlThreadNode *) arg;
1089 // Tell the world we are here
1090 CtdlLogPrintf(CTDL_NOTICE, "Spawned a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1092 num_threads++; // Increase the count of threads in the system.
1094 // Register for tracing
1095 #ifdef HAVE_BACKTRACE
1096 eCrash_RegisterThread(this_thread->name, 0);
1099 // Register the cleanup function to take care of when we exit.
1100 pthread_cleanup_push(ctdl_internal_thread_cleanup, arg);
1102 this_thread->running = TRUE;
1104 while ((!time_to_die) && (this_thread->running))
1105 { // Call the users thread function
1106 ret = (this_thread->thread_func)(this_thread->user_args);
1110 * Our thread is exiting either because it wanted to end or because the server is stopping
1111 * We need to clean up
1113 #ifdef HAVE_BACKTRACE
1114 eCrash_UnregisterThread();
1117 pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1125 * Internal function to create a thread.
1126 * Must be called from within a S_THREAD_LIST critical section
1128 int ctdl_internal_create_thread(char *name, int flags, void *(*thread_func) (void *arg), void *arg, struct CtdlThreadNode **new_thread)
1131 pthread_attr_t attr;
1132 struct CtdlThreadNode *this_thread;
1136 lprintf(CTDL_EMERG, "Possible attempt to overwrite an existing thread!!!\n");
1140 this_thread = malloc(sizeof(struct CtdlThreadNode));
1141 if (this_thread == NULL) {
1142 lprintf(CTDL_EMERG, "can't allocate CtdlThreadNode, exiting\n");
1145 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1146 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1148 if ((ret = pthread_attr_init(&attr))) {
1149 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1154 /* Our per-thread stacks need to be bigger than the default size,
1155 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1156 * crashes on 64-bit Linux.
1158 if (flags & CTDLTHREAD_BIGSTACK)
1160 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1161 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1163 pthread_attr_destroy(&attr);
1170 * If we got here we are going to create the thread so we must initilise the structure
1171 * first because most implimentations of threading can't create it in a stopped state
1172 * and it might want to do things with its structure that aren't initialised otherwise.
1176 this_thread->name = strdup(name);
1180 this_thread->name = strdup("Unknown Thread");
1182 this_thread->flags = flags;
1183 this_thread->thread_func = thread_func;
1184 this_thread->user_args = arg;
1185 this_thread->valid = 1; // Need this to prevent house keeping unlinking us from the list
1187 * We pass this_thread into the thread as its args so that it can find out information
1188 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1189 * thread function needs to finish off the setup of the structure
1191 if ((ret = pthread_create(&this_thread->tid, &attr, ctdl_internal_thread_func, this_thread) != 0))
1194 lprintf(CTDL_ALERT, "Can't create thread: %s\n",
1196 if (this_thread->name)
1197 free (this_thread->name);
1199 pthread_attr_destroy(&attr);
1203 this_thread->next = CtdlThreadList;
1204 CtdlThreadList = this_thread;
1205 *new_thread = this_thread;
1206 pthread_attr_destroy(&attr);
1211 * Wrapper function to create a thread
1212 * ensures the critical section and other protections are in place.
1213 * char *name = name to give to thread, if NULL, use generic name
1214 * int flags = flags to determine type of thread and standard facilities
1216 int CtdlCreateThread(char *name, int flags, void *(*thread_func) (void *arg), void *arg, struct CtdlThreadNode **new_thread)
1220 begin_critical_section(S_THREAD_LIST);
1221 ret = ctdl_internal_create_thread(name, flags, thread_func, arg, new_thread);
1222 end_critical_section(S_THREAD_LIST);
1229 * Old thread interface.
1233 struct worker_node *worker_list = NULL;
1237 * create a worker thread. this function must always be called from within
1238 * an S_WORKER_LIST critical section!
1240 void create_worker(void) {
1242 struct worker_node *n;
1243 pthread_attr_t attr;
1245 n = malloc(sizeof(struct worker_node));
1247 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
1252 if ((ret = pthread_attr_init(&attr))) {
1253 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1259 /* Our per-thread stacks need to be bigger than the default size,
1260 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1261 * crashes on 64-bit Linux.
1263 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1264 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1267 pthread_attr_destroy(&attr);
1272 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
1275 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
1278 pthread_attr_destroy(&attr);
1283 n->next = worker_list;
1285 pthread_attr_destroy(&attr);
1288 void DestroyWorkerList(void)
1290 struct CitContext *ptr; /* general-purpose utility pointer */
1291 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1293 begin_critical_section(S_SESSION_TABLE);
1295 while (ptr != NULL){
1296 /* Remove the session from the active list */
1300 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1301 end_critical_section(S_SESSION_TABLE);
1303 begin_critical_section(S_SESSION_TABLE);
1307 end_critical_section(S_SESSION_TABLE);
1309 struct worker_node *cur, *p;
1321 * Create the maintenance threads and begin their operation.
1323 void create_maintenance_threads(void) {
1325 pthread_attr_t attr;
1327 if ((ret = pthread_attr_init(&attr))) {
1328 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1333 /* Our per-thread stacks need to be bigger than the default size,
1334 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1335 * crashes on 64-bit Linux.
1337 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1338 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1341 pthread_attr_destroy(&attr);
1345 struct MaintenanceThreadHook *fcn;
1347 lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1349 for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1350 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1351 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1355 lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1356 fcn->MaintenanceThread_tid);
1361 pthread_attr_destroy(&attr);
1367 * Purge all sessions which have the 'kill_me' flag set.
1368 * This function has code to prevent it from running more than once every
1369 * few seconds, because running it after every single unbind would waste a lot
1370 * of CPU time and keep the context list locked too much. To force it to run
1371 * anyway, set "force" to nonzero.
1374 * After that's done, we raise the size of the worker thread pool
1375 * if such an action is appropriate.
1377 void dead_session_purge(int force) {
1378 struct CitContext *ptr; /* general-purpose utility pointer */
1379 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1382 if ( (time(NULL) - last_purge) < 5 ) {
1383 return; /* Too soon, go away */
1388 begin_critical_section(S_SESSION_TABLE);
1389 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1390 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1392 /* Remove the session from the active list */
1394 ptr->prev->next = ptr->next;
1397 ContextList = ptr->next;
1400 ptr->next->prev = ptr->prev;
1405 /* And put it on our to-be-destroyed list */
1411 end_critical_section(S_SESSION_TABLE);
1413 /* Now that we no longer have the session list locked, we can take
1414 * our time and destroy any sessions on the to-be-killed list, which
1415 * is allocated privately on this thread's stack.
1417 while (rem != NULL) {
1418 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1425 /* Raise the size of the worker thread pool if necessary. */
1426 if ( (num_sessions > num_threads)
1427 && (num_threads < config.c_max_workers) ) {
1428 begin_critical_section(S_WORKER_LIST);
1430 end_critical_section(S_WORKER_LIST);
1439 * masterCC is the context we use when not attached to a session. This
1440 * function initializes it.
1442 void InitializeMasterCC(void) {
1443 memset(&masterCC, 0, sizeof(struct CitContext));
1444 masterCC.internal_pgm = 1;
1445 masterCC.cs_pid = 0;
1454 * Bind a thread to a context. (It's inline merely to speed things up.)
1456 INLINE void become_session(struct CitContext *which_con) {
1457 pthread_setspecific(MyConKey, (void *)which_con );
1463 * This loop just keeps going and going and going...
1465 void *worker_thread(void *arg) {
1468 struct CitContext *ptr;
1469 struct CitContext *bind_me = NULL;
1472 struct CitContext *con= NULL; /* Temporary context pointer */
1473 struct ServiceFunctionHook *serviceptr;
1474 int ssock; /* Descriptor for client socket */
1476 int force_purge = 0;
1483 // Register for tracing
1484 #ifdef HAVE_BACKTRACE
1485 eCrash_RegisterThread("WorkerThread", 0);
1487 while (!time_to_die) {
1489 /* make doubly sure we're not holding any stale db handles
1490 * which might cause a deadlock.
1492 cdb_check_handles();
1493 do_select: force_purge = 0;
1494 bind_me = NULL; /* Which session shall we handle? */
1496 /* Initialize the fdset. */
1500 begin_critical_section(S_SESSION_TABLE);
1501 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1502 if (ptr->state == CON_IDLE) {
1503 FD_SET(ptr->client_socket, &readfds);
1504 if (ptr->client_socket > highest)
1505 highest = ptr->client_socket;
1507 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1509 ptr->state = CON_EXECUTING;
1512 end_critical_section(S_SESSION_TABLE);
1518 /* If we got this far, it means that there are no sessions
1519 * which a previous thread marked for attention, so we go
1520 * ahead and get ready to select().
1523 /* First, add the various master sockets to the fdset. */
1524 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1525 serviceptr = serviceptr->next ) {
1526 m = serviceptr->msock;
1527 FD_SET(m, &readfds);
1534 tv.tv_sec = 1; /* wake up every second if no input */
1536 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1539 if (time_to_die) return(NULL);
1541 /* Now figure out who made this select() unblock.
1542 * First, check for an error or exit condition.
1545 if (errno == EBADF) {
1546 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1550 if (errno != EINTR) {
1551 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1553 } else if (!time_to_die)
1557 /* Next, check to see if it's a new client connecting
1558 * on a master socket.
1560 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1561 serviceptr = serviceptr->next ) {
1563 if (FD_ISSET(serviceptr->msock, &readfds)) {
1564 ssock = accept(serviceptr->msock, NULL, 0);
1567 "New client socket %d\n",
1570 /* The master socket is non-blocking but the client
1571 * sockets need to be blocking, otherwise certain
1572 * operations barf on FreeBSD. Not a fatal error.
1574 if (fcntl(ssock, F_SETFL, 0) < 0) {
1576 "citserver: Can't set socket to blocking: %s\n",
1580 /* New context will be created already
1581 * set up in the CON_EXECUTING state.
1583 con = CreateNewContext();
1585 /* Assign our new socket number to it. */
1586 con->client_socket = ssock;
1587 con->h_command_function =
1588 serviceptr->h_command_function;
1589 con->h_async_function =
1590 serviceptr->h_async_function;
1592 serviceptr->ServiceName;
1594 /* Determine whether it's a local socket */
1595 if (serviceptr->sockpath != NULL)
1596 con->is_local_socket = 1;
1598 /* Set the SO_REUSEADDR socket option */
1600 setsockopt(ssock, SOL_SOCKET,
1604 become_session(con);
1606 serviceptr->h_greeting_function();
1607 become_session(NULL);
1608 con->state = CON_IDLE;
1614 /* It must be a client socket. Find a context that has data
1615 * waiting on its socket *and* is in the CON_IDLE state. Any
1616 * active sockets other than our chosen one are marked as
1617 * CON_READY so the next thread that comes around can just bind
1618 * to one without having to select() again.
1620 begin_critical_section(S_SESSION_TABLE);
1621 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1622 if ( (FD_ISSET(ptr->client_socket, &readfds))
1623 && (ptr->state != CON_EXECUTING) ) {
1624 ptr->input_waiting = 1;
1626 bind_me = ptr; /* I choose you! */
1627 bind_me->state = CON_EXECUTING;
1630 ptr->state = CON_READY;
1634 end_critical_section(S_SESSION_TABLE);
1637 /* We're bound to a session */
1638 if (bind_me != NULL) {
1639 become_session(bind_me);
1641 /* If the client has sent a command, execute it. */
1642 if (CC->input_waiting) {
1643 CC->h_command_function();
1644 CC->input_waiting = 0;
1647 /* If there are asynchronous messages waiting and the
1648 * client supports it, do those now */
1649 if ((CC->is_async) && (CC->async_waiting)
1650 && (CC->h_async_function != NULL)) {
1651 CC->h_async_function();
1652 CC->async_waiting = 0;
1655 force_purge = CC->kill_me;
1656 become_session(NULL);
1657 bind_me->state = CON_IDLE;
1660 dead_session_purge(force_purge);
1662 check_sched_shutdown();
1664 if (con != NULL) free (con);//// TODO: could this harm other threads?
1665 /* If control reaches this point, the server is shutting down */
1666 #ifdef HAVE_BACKTRACE
1667 eCrash_UnregisterThread();
1677 * Translate text facility name to syslog.h defined value.
1679 int SyslogFacility(char *name)
1688 { LOG_KERN, "kern" },
1689 { LOG_USER, "user" },
1690 { LOG_MAIL, "mail" },
1691 { LOG_DAEMON, "daemon" },
1692 { LOG_AUTH, "auth" },
1693 { LOG_SYSLOG, "syslog" },
1695 { LOG_NEWS, "news" },
1696 { LOG_UUCP, "uucp" },
1697 { LOG_LOCAL0, "local0" },
1698 { LOG_LOCAL1, "local1" },
1699 { LOG_LOCAL2, "local2" },
1700 { LOG_LOCAL3, "local3" },
1701 { LOG_LOCAL4, "local4" },
1702 { LOG_LOCAL5, "local5" },
1703 { LOG_LOCAL6, "local6" },
1704 { LOG_LOCAL7, "local7" },
1707 for(i = 0; facTbl[i].name != NULL; i++) {
1708 if(!strcasecmp(name, facTbl[i].name))
1709 return facTbl[i].facility;
1716 /********** MEM CHEQQER ***********/
1718 #ifdef DEBUG_MEMORY_LEAKS
1725 void *tracked_malloc(size_t size, char *file, int line) {
1726 struct igheap *thisheap;
1729 block = malloc(size);
1730 if (block == NULL) return(block);
1732 thisheap = malloc(sizeof(struct igheap));
1733 if (thisheap == NULL) {
1738 thisheap->block = block;
1739 strcpy(thisheap->file, file);
1740 thisheap->line = line;
1742 begin_critical_section(S_DEBUGMEMLEAKS);
1743 thisheap->next = igheap;
1745 end_critical_section(S_DEBUGMEMLEAKS);
1751 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1752 struct igheap *thisheap;
1755 block = realloc(ptr, size);
1756 if (block == NULL) return(block);
1758 thisheap = malloc(sizeof(struct igheap));
1759 if (thisheap == NULL) {
1764 thisheap->block = block;
1765 strcpy(thisheap->file, file);
1766 thisheap->line = line;
1768 begin_critical_section(S_DEBUGMEMLEAKS);
1769 thisheap->next = igheap;
1771 end_critical_section(S_DEBUGMEMLEAKS);
1778 void tracked_free(void *ptr) {
1779 struct igheap *thisheap;
1780 struct igheap *trash;
1784 if (igheap == NULL) return;
1785 begin_critical_section(S_DEBUGMEMLEAKS);
1786 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1787 if (thisheap->next != NULL) {
1788 if (thisheap->next->block == ptr) {
1789 trash = thisheap->next;
1790 thisheap->next = thisheap->next->next;
1795 if (igheap->block == ptr) {
1797 igheap = igheap->next;
1800 end_critical_section(S_DEBUGMEMLEAKS);
1803 char *tracked_strdup(const char *s, char *file, int line) {
1806 if (s == NULL) return(NULL);
1807 ptr = tracked_malloc(strlen(s) + 1, file, line);
1808 if (ptr == NULL) return(NULL);
1809 strncpy(ptr, s, strlen(s));
1813 void dump_heap(void) {
1814 struct igheap *thisheap;
1816 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1817 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1818 thisheap->file, thisheap->line);
1822 #endif /* DEBUG_MEMORY_LEAKS */