4 * Citadel "system dependent" stuff.
5 * See copyright.txt for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syslog.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
55 #include <libcitadel.h>
58 #include "sysdep_decls.h"
59 #include "citserver.h"
63 #include "housekeeping.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
75 #include "ctdl_module.h"
77 #ifdef DEBUG_MEMORY_LEAKS
85 struct igheap *igheap = NULL;
89 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
90 pthread_key_t MyConKey; /* TSD key for MyContext() */
92 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
94 struct CitContext masterCC;
95 time_t last_purge = 0; /* Last dead session purge */
96 static int num_threads = 0; /* Current number of threads */
97 static int num_workers = 0; /* Current number of worker threads */
98 int num_sessions = 0; /* Current number of sessions */
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
105 * Create an interface to lprintf that follows the coding convention.
106 * This is here until such time as we have replaced all calls to lprintf with CtdlLogPrintf
109 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...)
112 va_start(arg_ptr, format);
113 vlprintf(loglevel, format, arg_ptr);
119 * lprintf() ... Write logging information
121 void lprintf(enum LogLevel loglevel, const char *format, ...) {
123 va_start(arg_ptr, format);
124 vlprintf(loglevel, format, arg_ptr);
128 void vlprintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
130 char buf[SIZ], buf2[SIZ];
133 vsyslog((syslog_facility | loglevel), format, arg_ptr);
136 /* stderr output code */
137 if (enable_syslog || running_as_daemon) return;
139 /* if we run in forground and syslog is disabled, log to terminal */
140 if (loglevel <= verbosity) {
145 gettimeofday(&tv, NULL);
146 /* Promote to time_t; types differ on some OSes (like darwin) */
147 unixtime = tv.tv_sec;
148 localtime_r(&unixtime, &tim);
149 if (CC->cs_pid != 0) {
151 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
152 tim.tm_year + 1900, tim.tm_mon + 1,
153 tim.tm_mday, tim.tm_hour, tim.tm_min,
154 tim.tm_sec, (long)tv.tv_usec,
158 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
159 tim.tm_year + 1900, tim.tm_mon + 1,
160 tim.tm_mday, tim.tm_hour, tim.tm_min,
161 tim.tm_sec, (long)tv.tv_usec);
163 vsprintf(buf2, format, arg_ptr);
165 fprintf(stderr, "%s%s", buf, buf2);
173 * Signal handler to shut down the server.
176 volatile int exit_signal = 0;
177 volatile int shutdown_and_halt = 0;
178 volatile int restart_server = 0;
179 volatile int running_as_daemon = 0;
181 static RETSIGTYPE signal_cleanup(int signum) {
182 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
184 exit_signal = signum;
190 void InitialiseSemaphores(void)
194 /* Set up a bunch of semaphores to be used for critical sections */
195 for (i=0; i<MAX_SEMAPHORES; ++i) {
196 pthread_mutex_init(&Critters[i], NULL);
203 * Some initialization stuff...
205 void init_sysdep(void) {
208 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
212 getrlimit(RLIMIT_NOFILE, &rl);
213 rl.rlim_cur = FD_SETSIZE;
214 rl.rlim_max = FD_SETSIZE;
215 setrlimit(RLIMIT_NOFILE, &rl);
219 /* If we've got OpenSSL, we're going to use it. */
225 * Set up a place to put thread-specific data.
226 * We only need a single pointer per thread - it points to the
227 * CitContext structure (in the ContextList linked list) of the
228 * session to which the calling thread is currently bound.
230 if (pthread_key_create(&MyConKey, NULL) != 0) {
231 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
236 * The action for unexpected signals and exceptions should be to
237 * call signal_cleanup() to gracefully shut down the server.
240 sigaddset(&set, SIGINT);
241 sigaddset(&set, SIGQUIT);
242 sigaddset(&set, SIGHUP);
243 sigaddset(&set, SIGTERM);
244 // sigaddset(&set, SIGSEGV); commented out because
245 // sigaddset(&set, SIGILL); we want core dumps
246 // sigaddset(&set, SIGBUS);
247 sigprocmask(SIG_UNBLOCK, &set, NULL);
249 signal(SIGINT, signal_cleanup);
250 signal(SIGQUIT, signal_cleanup);
251 signal(SIGHUP, signal_cleanup);
252 signal(SIGTERM, signal_cleanup);
253 // signal(SIGSEGV, signal_cleanup); commented out because
254 // signal(SIGILL, signal_cleanup); we want core dumps
255 // signal(SIGBUS, signal_cleanup);
258 * Do not shut down the server on broken pipe signals, otherwise the
259 * whole Citadel service would come down whenever a single client
262 //signal(SIGPIPE, SIG_IGN);
263 signal(SIGPIPE, signal_cleanup);
268 * Obtain a semaphore lock to begin a critical section.
270 void begin_critical_section(int which_one)
272 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
274 /* For all types of critical sections except those listed here,
275 * ensure nobody ever tries to do a critical section within a
276 * transaction; this could lead to deadlock.
278 if ( (which_one != S_FLOORCACHE)
279 #ifdef DEBUG_MEMORY_LEAKS
280 && (which_one != S_DEBUGMEMLEAKS)
282 && (which_one != S_RPLIST)
286 pthread_mutex_lock(&Critters[which_one]);
290 * Release a semaphore lock to end a critical section.
292 void end_critical_section(int which_one)
294 pthread_mutex_unlock(&Critters[which_one]);
300 * This is a generic function to set up a master socket for listening on
301 * a TCP port. The server shuts down if the bind fails.
304 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
306 struct sockaddr_in sin;
308 int actual_queue_len;
310 actual_queue_len = queue_len;
311 if (actual_queue_len < 5) actual_queue_len = 5;
313 memset(&sin, 0, sizeof(sin));
314 sin.sin_family = AF_INET;
315 sin.sin_port = htons((u_short)port_number);
316 if (ip_addr == NULL) {
317 sin.sin_addr.s_addr = INADDR_ANY;
320 sin.sin_addr.s_addr = inet_addr(ip_addr);
323 if (sin.sin_addr.s_addr == !INADDR_ANY) {
324 sin.sin_addr.s_addr = INADDR_ANY;
327 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
330 *errormessage = (char*) malloc(SIZ + 1);
331 snprintf(*errormessage, SIZ,
332 "citserver: Can't create a socket: %s",
334 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
339 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
341 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
342 *errormessage = (char*) malloc(SIZ + 1);
343 snprintf(*errormessage, SIZ,
344 "citserver: Can't bind: %s",
346 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
351 /* set to nonblock - we need this for some obscure situations */
352 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
353 *errormessage = (char*) malloc(SIZ + 1);
354 snprintf(*errormessage, SIZ,
355 "citserver: Can't set socket to non-blocking: %s",
357 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
362 if (listen(s, actual_queue_len) < 0) {
363 *errormessage = (char*) malloc(SIZ + 1);
364 snprintf(*errormessage, SIZ,
365 "citserver: Can't listen: %s",
367 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
378 * Create a Unix domain socket and listen on it
380 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
382 struct sockaddr_un addr;
385 int actual_queue_len;
387 actual_queue_len = queue_len;
388 if (actual_queue_len < 5) actual_queue_len = 5;
390 i = unlink(sockpath);
391 if (i != 0) if (errno != ENOENT) {
392 *errormessage = (char*) malloc(SIZ + 1);
393 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
394 sockpath, strerror(errno));
395 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
399 memset(&addr, 0, sizeof(addr));
400 addr.sun_family = AF_UNIX;
401 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
403 s = socket(AF_UNIX, SOCK_STREAM, 0);
405 *errormessage = (char*) malloc(SIZ + 1);
406 snprintf(*errormessage, SIZ,
407 "citserver: Can't create a socket: %s",
409 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
413 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
414 *errormessage = (char*) malloc(SIZ + 1);
415 snprintf(*errormessage, SIZ,
416 "citserver: Can't bind: %s",
418 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
422 /* set to nonblock - we need this for some obscure situations */
423 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
424 *errormessage = (char*) malloc(SIZ + 1);
425 snprintf(*errormessage, SIZ,
426 "citserver: Can't set socket to non-blocking: %s",
428 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
433 if (listen(s, actual_queue_len) < 0) {
434 *errormessage = (char*) malloc(SIZ + 1);
435 snprintf(*errormessage, SIZ,
436 "citserver: Can't listen: %s",
438 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
442 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
449 * Return a pointer to the CitContext structure bound to the thread which
450 * called this function. If there's no such binding (for example, if it's
451 * called by the housekeeper thread) then a generic 'master' CC is returned.
453 * This function is used *VERY* frequently and must be kept small.
455 struct CitContext *MyContext(void) {
457 register struct CitContext *c;
459 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
460 c == NULL) ? &masterCC : c
466 * Initialize a new context and place it in the list. The session number
467 * used to be the PID (which is why it's called cs_pid), but that was when we
468 * had one process per session. Now we just assign them sequentially, starting
469 * at 1 (don't change it to 0 because masterCC uses 0).
471 struct CitContext *CreateNewContext(void) {
472 struct CitContext *me;
473 static int next_pid = 0;
475 me = (struct CitContext *) malloc(sizeof(struct CitContext));
477 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
480 memset(me, 0, sizeof(struct CitContext));
482 /* The new context will be created already in the CON_EXECUTING state
483 * in order to prevent another thread from grabbing it while it's
486 me->state = CON_EXECUTING;
489 * Generate a unique session number and insert this context into
492 begin_critical_section(S_SESSION_TABLE);
493 me->cs_pid = ++next_pid;
495 me->next = ContextList;
497 if (me->next != NULL) {
501 end_critical_section(S_SESSION_TABLE);
507 * The following functions implement output buffering. If the kernel supplies
508 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
509 * user-space buffering.
513 # define HAVE_TCP_BUFFERING
516 # define HAVE_TCP_BUFFERING
517 # define TCP_CORK TCP_NOPUSH
519 #endif /* TCP_CORK */
520 #endif /* HAVE_DARWIN */
522 #ifdef HAVE_TCP_BUFFERING
523 static unsigned on = 1, off = 0;
524 void buffer_output(void) {
525 struct CitContext *ctx = MyContext();
526 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
530 void unbuffer_output(void) {
531 struct CitContext *ctx = MyContext();
532 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
536 void flush_output(void) {
537 struct CitContext *ctx = MyContext();
538 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
539 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
543 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
544 void buffer_output(void) {
547 void unbuffer_output(void) {
550 void flush_output(void) {
553 void buffer_output(void) {
554 if (CC->buffering == 0) {
557 CC->output_buffer = malloc(SIZ);
561 void flush_output(void) {
562 if (CC->buffering == 1) {
563 client_write(CC->output_buffer, CC->buffer_len);
568 void unbuffer_output(void) {
569 if (CC->buffering == 1) {
571 /* We don't call flush_output because we can't. */
572 client_write(CC->output_buffer, CC->buffer_len);
574 free(CC->output_buffer);
575 CC->output_buffer = NULL;
578 #endif /* HAVE_DARWIN */
579 #endif /* HAVE_TCP_BUFFERING */
584 * client_write() ... Send binary data to the client.
586 void client_write(char *buf, int nbytes)
588 int bytes_written = 0;
590 #ifndef HAVE_TCP_BUFFERING
591 int old_buffer_len = 0;
596 if (Ctx->redirect_buffer != NULL) {
597 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
598 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
599 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
600 Ctx->redirect_alloc);
602 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
603 Ctx->redirect_len += nbytes;
604 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
608 #ifndef HAVE_TCP_BUFFERING
609 /* If we're buffering for later, do that now. */
610 if (Ctx->buffering) {
611 old_buffer_len = Ctx->buffer_len;
612 Ctx->buffer_len += nbytes;
613 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
614 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
619 /* Ok, at this point we're not buffering. Go ahead and write. */
622 if (Ctx->redirect_ssl) {
623 client_write_ssl(buf, nbytes);
628 while (bytes_written < nbytes) {
629 retval = write(Ctx->client_socket, &buf[bytes_written],
630 nbytes - bytes_written);
632 CtdlLogPrintf(CTDL_ERR,
633 "client_write(%d bytes) failed: %s (%d)\n",
634 nbytes - bytes_written,
635 strerror(errno), errno);
637 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
641 bytes_written = bytes_written + retval;
647 * cprintf() ... Send formatted printable data to the client. It is
648 * implemented in terms of client_write() but remains in
649 * sysdep.c in case we port to somewhere without va_args...
651 void cprintf(const char *format, ...) {
655 va_start(arg_ptr, format);
656 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
657 buf[sizeof buf - 2] = '\n';
658 client_write(buf, strlen(buf));
664 * Read data from the client socket.
666 * 1 Requested number of bytes has been read.
667 * 0 Request timed out.
668 * -1 The socket is broken.
669 * If the socket breaks, the session will be terminated.
671 int client_read_to(char *buf, int bytes, int timeout)
680 if (CC->redirect_ssl) {
681 return (client_read_ssl(buf, bytes, timeout));
685 fd = CC->client_socket;
692 retval = select( (fd)+1,
693 &rfds, NULL, NULL, &tv);
695 if (FD_ISSET(fd, &rfds) == 0) {
699 rlen = read(fd, &buf[len], bytes-len);
701 /* The socket has been disconnected! */
711 * Read data from the client socket with default timeout.
712 * (This is implemented in terms of client_read_to() and could be
713 * justifiably moved out of sysdep.c)
715 INLINE int client_read(char *buf, int bytes)
717 return(client_read_to(buf, bytes, config.c_sleeping));
722 * client_getln() ... Get a LF-terminated line of text from the client.
723 * (This is implemented in terms of client_read() and could be
724 * justifiably moved out of sysdep.c)
726 int client_getln(char *buf, int bufsize)
730 /* Read one character at a time.
733 retval = client_read(&buf[i], 1);
734 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
738 /* If we got a long line, discard characters until the newline.
740 if (i == (bufsize-1))
741 while (buf[i] != '\n' && retval == 1)
742 retval = client_read(&buf[i], 1);
744 /* Strip the trailing LF, and the trailing CR if present.
748 && ( (buf[i - 1]==13)
749 || ( buf[i - 1]==10)) ) {
753 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
759 * Cleanup any contexts that are left lying around
761 void context_cleanup(void)
763 struct CitContext *ptr = NULL;
764 struct CitContext *rem = NULL;
767 * Clean up the contexts.
768 * There are no threads so no critical_section stuff is needed.
772 /* Remove the session from the active list */
776 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
786 * The system-dependent part of master_cleanup() - close the master socket.
788 void sysdep_master_cleanup(void) {
789 struct ServiceFunctionHook *serviceptr;
792 * close all protocol master sockets
794 for (serviceptr = ServiceHookTable; serviceptr != NULL;
795 serviceptr = serviceptr->next ) {
797 if (serviceptr->tcp_port > 0)
798 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
799 serviceptr->tcp_port);
801 if (serviceptr->sockpath != NULL)
802 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
803 serviceptr->sockpath);
805 close(serviceptr->msock);
807 /* If it's a Unix domain socket, remove the file. */
808 if (serviceptr->sockpath != NULL) {
809 unlink(serviceptr->sockpath);
818 CtdlDestroyProtoHooks();
819 CtdlDestroyDeleteHooks();
820 CtdlDestroyXmsgHooks();
821 CtdlDestroyNetprocHooks();
822 CtdlDestroyUserHooks();
823 CtdlDestroyMessageHook();
824 CtdlDestroyCleanupHooks();
825 CtdlDestroyFixedOutputHooks();
826 CtdlDestroySessionHooks();
827 CtdlDestroyServiceHook();
828 #ifdef HAVE_BACKTRACE
836 * Terminate another session.
837 * (This could justifiably be moved out of sysdep.c because it
838 * no longer does anything that is system-dependent.)
840 void kill_session(int session_to_kill) {
841 struct CitContext *ptr;
843 begin_critical_section(S_SESSION_TABLE);
844 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
845 if (ptr->cs_pid == session_to_kill) {
849 end_critical_section(S_SESSION_TABLE);
853 void graceful_shutdown(int signum) {
854 kill(current_child, signum);
855 unlink(file_pid_file);
861 * Start running as a daemon.
863 void start_daemon(int unused) {
871 /* Close stdin/stdout/stderr and replace them with /dev/null.
872 * We don't just call close() because we don't want these fd's
873 * to be reused for other files.
882 signal(SIGHUP, SIG_IGN);
883 signal(SIGINT, SIG_IGN);
884 signal(SIGQUIT, SIG_IGN);
888 freopen("/dev/null", "r", stdin);
889 freopen("/dev/null", "w", stdout);
890 freopen("/dev/null", "w", stderr);
893 current_child = fork();
895 signal(SIGTERM, graceful_shutdown);
897 if (current_child < 0) {
902 else if (current_child == 0) {
903 return; /* continue starting citadel. */
907 fp = fopen(file_pid_file, "w");
910 * NB.. The pid file contains the pid of the actual server.
911 * This is not the pid of the watcher process
913 fprintf(fp, ""F_PID_T"\n", current_child);
916 waitpid(current_child, &status, 0);
921 /* Did the main process exit with an actual exit code? */
922 if (WIFEXITED(status)) {
924 /* Exit code 0 means the watcher should exit */
925 if (WEXITSTATUS(status) == 0) {
929 /* Exit code 101-109 means the watcher should exit */
930 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
934 /* Any other exit code means we should restart. */
940 /* Any other type of termination (signals, etc.) should also restart. */
945 } while (do_restart);
947 unlink(file_pid_file);
948 exit(WEXITSTATUS(status));
954 * Generic routine to convert a login name to a full name (gecos)
955 * Returns nonzero if a conversion took place
957 int convert_login(char NameToConvert[]) {
961 pw = getpwnam(NameToConvert);
966 strcpy(NameToConvert, pw->pw_gecos);
967 for (a=0; a<strlen(NameToConvert); ++a) {
968 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
977 * New thread interface.
978 * To create a thread you must call one of the create thread functions.
979 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
980 * struct CtdlThreadNode *node = NULL;
982 * If the thread is created *node will point to the thread control structure for the created thread.
983 * If the thread creation fails *node remains NULL
984 * Do not free the memory pointed to by *node, it doesn't belong to you.
985 * If your thread function returns it will be started again without creating a new thread.
986 * If your thread function wants to exit it should call CtdlThreadExit(ret_code);
987 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
988 * remove the need for the calls to eCrashRegisterThread and friends
992 struct CtdlThreadNode *CtdlThreadList = NULL;
995 * Condition variable and Mutex for thread garbage collection
997 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
998 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
999 */static pthread_t GC_thread;
1000 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
1002 * Pinched the following bits regarding signals from Kannel.org
1006 * Change this thread's signal mask to block user-visible signals
1007 * (HUP, TERM, QUIT, INT), and store the old signal mask in
1009 * Return 0 for success, or -1 if an error occurred.
1013 * This does not work in Darwin alias MacOS X alias Mach kernel,
1014 * however. So we define a dummy function doing nothing.
1016 #if defined(DARWIN_OLD)
1017 static int pthread_sigmask();
1020 static int ctdl_thread_internal_block_signals(sigset_t *old_set_storage)
1023 sigset_t block_signals;
1025 ret = sigemptyset(&block_signals);
1027 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't initialize signal set\n");
1030 ret = sigaddset(&block_signals, SIGHUP);
1031 ret |= sigaddset(&block_signals, SIGTERM);
1032 ret |= sigaddset(&block_signals, SIGQUIT);
1033 ret |= sigaddset(&block_signals, SIGINT);
1035 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't add signal to signal set.\n");
1038 ret = pthread_sigmask(SIG_BLOCK, &block_signals, old_set_storage);
1040 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't disable signals for thread creation\n");
1046 static void ctdl_thread_internal_restore_signals(sigset_t *old_set)
1050 ret = pthread_sigmask(SIG_SETMASK, old_set, NULL);
1052 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't restore signal set.\n");
1057 void ctdl_thread_internal_init(void)
1059 struct CtdlThreadNode *this_thread;
1062 GC_thread = pthread_self();
1063 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
1064 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
1065 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
1066 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
1067 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
1068 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
1069 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
1070 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
1071 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
1074 /* Get ourself a thread entry */
1075 this_thread = malloc(sizeof(struct CtdlThreadNode));
1076 if (this_thread == NULL) {
1077 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1080 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1081 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1083 /* We are garbage collector so create us as running */
1084 this_thread->state = CTDL_THREAD_RUNNING;
1086 if ((ret = pthread_attr_init(&this_thread->attr))) {
1087 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1092 this_thread->name = strdup("Garbage Collection Thread");
1094 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1095 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1097 this_thread->tid = GC_thread;
1099 num_threads++; // Increase the count of threads in the system.
1101 this_thread->next = CtdlThreadList;
1102 CtdlThreadList = this_thread;
1103 if (this_thread->next)
1104 this_thread->next->prev = this_thread;
1108 * A function to tell all threads to exit
1110 void CtdlThreadStopAll(void)
1112 struct CtdlThreadNode *this_thread;
1114 begin_critical_section(S_THREAD_LIST);
1115 this_thread = CtdlThreadList;
1118 if (this_thread->thread_func) // Don't tell garbage collector to stop
1120 pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1121 if (this_thread->state > CTDL_THREAD_STOP_REQ)
1122 this_thread->state = CTDL_THREAD_STOP_REQ;
1123 pthread_mutex_unlock(&this_thread->ThreadMutex);
1124 pthread_cond_signal(&this_thread->ThreadCond);
1125 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (%ld).\n", this_thread->name, this_thread->tid);
1127 this_thread = this_thread->next;
1129 end_critical_section(S_THREAD_LIST);
1134 * A function to signal that we need to do garbage collection on the thread list
1136 void CtdlThreadGC(void)
1138 struct CtdlThreadNode *this_thread;
1140 CtdlLogPrintf(CTDL_DEBUG, "Thread system signalling garbage collection.\n");
1142 begin_critical_section(S_THREAD_LIST);
1143 this_thread = CtdlThreadList;
1146 if (!this_thread->thread_func)
1147 pthread_cond_signal(&this_thread->ThreadCond);
1149 this_thread = this_thread->next;
1151 end_critical_section(S_THREAD_LIST);
1156 * A function to return the number of threads running in the system
1158 int CtdlThreadGetCount(void)
1164 * A function to find the thread structure for this thread
1166 struct CtdlThreadNode *CtdlThreadSelf(void)
1169 struct CtdlThreadNode *this_thread;
1171 self_tid = pthread_self();
1173 begin_critical_section(S_THREAD_LIST);
1174 this_thread = CtdlThreadList;
1177 if (pthread_equal(self_tid, this_thread->tid))
1179 end_critical_section(S_THREAD_LIST);
1182 this_thread = this_thread->next;
1184 end_critical_section(S_THREAD_LIST);
1192 * A function to rename a thread
1193 * Returns a char * and the caller owns the memory and should free it
1195 char *CtdlThreadName(struct CtdlThreadNode *thread, char *name)
1197 struct CtdlThreadNode *this_thread;
1201 this_thread = CtdlThreadSelf();
1203 this_thread = thread;
1206 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread.\n");
1209 begin_critical_section(S_THREAD_LIST);
1212 old_name = this_thread->name;
1213 this_thread->name = strdup (name);
1216 old_name = strdup(this_thread->name);
1217 end_critical_section (S_THREAD_LIST);
1223 * A function to force a thread to exit
1225 void CtdlThreadCancel(struct CtdlThreadNode *thread)
1227 struct CtdlThreadNode *this_thread;
1230 this_thread = CtdlThreadSelf();
1232 this_thread = thread;
1235 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
1236 CtdlThreadStopAll();
1239 begin_critical_section(S_THREAD_LIST);
1240 this_thread->state = CTDL_THREAD_CANCELLED;
1241 pthread_cancel(this_thread->tid);
1242 end_critical_section (S_THREAD_LIST);
1248 * A function for a thread to check if it has been asked to stop
1250 int CtdlThreadCheckStop(void)
1252 struct CtdlThreadNode *this_thread;
1254 this_thread = CtdlThreadSelf();
1257 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
1258 CtdlThreadStopAll();
1261 if(this_thread->state == CTDL_THREAD_STOP_REQ)
1263 this_thread->state = CTDL_THREAD_STOPPING;
1266 else if(this_thread->state < CTDL_THREAD_STOP_REQ)
1274 * A function to ask a thread to exit
1275 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
1277 void CtdlThreadStop(struct CtdlThreadNode *thread)
1279 struct CtdlThreadNode *this_thread;
1282 this_thread = CtdlThreadSelf();
1284 this_thread = thread;
1287 if (!(this_thread->thread_func))
1288 return; // Don't stop garbage collector
1290 begin_critical_section (S_THREAD_LIST);
1291 pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1292 if (this_thread->state > CTDL_THREAD_STOP_REQ)
1293 this_thread->state = CTDL_THREAD_STOP_REQ;
1294 pthread_mutex_unlock(&this_thread->ThreadMutex);
1295 pthread_cond_signal(&this_thread->ThreadCond);
1296 end_critical_section(S_THREAD_LIST);
1300 * So we now have a sleep command that works with threads but it is in seconds
1302 void CtdlThreadSleep(int secs)
1304 struct timespec wake_time;
1305 struct timeval time_now;
1306 struct CtdlThreadNode *self;
1310 self = CtdlThreadSelf();
1313 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
1317 begin_critical_section(S_THREAD_LIST);
1318 pthread_mutex_lock(&self->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1319 state = self->state;
1320 if (state == CTDL_THREAD_RUNNING)
1321 self->state = CTDL_THREAD_SLEEPING;
1322 end_critical_section(S_THREAD_LIST);
1324 if(state != CTDL_THREAD_RUNNING)
1326 CtdlLogPrintf(CTDL_DEBUG, "CtdlThreadSleep() called by a thread that is not running.\n");
1327 pthread_mutex_unlock(&self->ThreadMutex);
1331 memset (&wake_time, 0, sizeof(struct timespec));
1332 gettimeofday(&time_now, NULL);
1333 wake_time.tv_sec = time_now.tv_sec + secs;
1334 wake_time.tv_nsec = time_now.tv_usec * 10;
1335 pthread_cond_timedwait(&self->ThreadCond, &self->ThreadMutex, &wake_time);
1336 begin_critical_section(S_THREAD_LIST);
1337 if (self->state == CTDL_THREAD_SLEEPING) /* Don't change state if something else changed it while we were asleep */
1338 self->state = state;
1339 pthread_mutex_unlock(&self->ThreadMutex);
1340 end_critical_section(S_THREAD_LIST);
1345 * Routine to clean up our thread function on exit
1347 static void ctdl_internal_thread_cleanup(void *arg)
1349 struct CtdlThreadNode *this_thread;
1350 this_thread = CtdlThreadSelf();
1352 * In here we were called by the current thread because it is exiting
1353 * NB. WE ARE THE CURRENT THREAD
1355 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", this_thread->name, this_thread->tid);
1356 begin_critical_section(S_THREAD_LIST);
1357 #ifdef HAVE_BACKTRACE
1358 eCrash_UnregisterThread();
1360 this_thread->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
1361 end_critical_section(S_THREAD_LIST);
1369 * Garbage collection routine.
1370 * Gets called by main() in a loop to clean up the thread list periodically.
1372 void ctdl_internal_thread_gc (void)
1374 struct CtdlThreadNode *this_thread, *that_thread = NULL;
1375 /* struct timespec wake_time;
1376 struct timeval time_now;
1380 * Wait on the condition variable that tells us garbage collection is needed
1381 * We wake up every 10 seconds just in case someone forgot to inform us of a thread exiting
1383 /* pthread_mutex_lock(&thread_gc_mutex);
1384 memset (&wake_time, 0, sizeof(struct timespec));
1385 gettimeofday(&time_now, NULL);
1386 wake_time.tv_sec = time_now.tv_sec + 10;
1387 pthread_cond_timedwait(&thread_gc_cond, &thread_gc_mutex, &wake_time);
1389 CtdlThreadSleep(10);
1391 /* Handle exiting of garbage collector thread */
1392 if(num_threads == 1)
1394 CtdlThreadList->state = CTDL_THREAD_EXITED;
1397 // if (that_thread->state == CTDL_THREAD_STOP_REQ)
1398 // that_thread->state = CTDL_THREAD_STOPPING;
1399 // else if (that_thread->state == CTDL_THREAD_STOPPING)
1400 // that_thread->state = CTDL_THREAD_EXITED;
1404 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
1406 * Woke up to do garbage collection
1408 begin_critical_section(S_THREAD_LIST);
1409 this_thread = CtdlThreadList;
1412 that_thread = this_thread;
1413 this_thread = this_thread->next;
1415 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%ld) \"%s\".\n", that_thread->name, that_thread->tid, CtdlThreadStates[that_thread->state]);
1416 /* Do we need to clean up this thread? */
1417 if (that_thread->state != CTDL_THREAD_EXITED)
1419 if(that_thread->flags & CTDLTHREAD_WORKER)
1420 workers++; /* Sanity check on number of worker threads */
1424 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
1425 { /* Sanity check */
1426 end_critical_section(S_THREAD_LIST);
1427 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
1428 /* pthread_mutex_unlock(&thread_gc_mutex);
1429 */ CtdlThreadStopAll();
1433 if (num_threads <= 0)
1434 { /* Sanity check */
1435 end_critical_section (S_THREAD_LIST);
1436 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
1437 /* pthread_mutex_unlock(&thread_gc_mutex);
1438 */ CtdlThreadStopAll();
1442 /* If we are unlinking the list head then the next becomes the list head */
1443 if (that_thread == CtdlThreadList)
1444 CtdlThreadList = that_thread->next;
1445 if(that_thread->prev)
1446 that_thread->prev->next = that_thread->next;
1447 if(that_thread->next)
1448 that_thread->next->prev = that_thread->next;
1450 if(that_thread->flags & CTDLTHREAD_WORKER)
1451 num_workers--; /* This is a wroker thread so reduce the count. */
1454 * Join on the thread to do clean up and prevent memory leaks
1455 * Also makes sure the thread has cleaned up after itself before we remove it from the list
1456 * If that thread has no function it must be the garbage collector
1458 if (that_thread->thread_func)
1459 pthread_join (that_thread->tid, NULL);
1462 * Now we own that thread entry
1464 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (%ld).\n", that_thread->name, that_thread->tid);
1465 if(that_thread->name)
1466 free(that_thread->name);
1467 pthread_mutex_destroy(&that_thread->ThreadMutex);
1468 pthread_cond_destroy(&that_thread->ThreadCond);
1469 pthread_attr_destroy(&that_thread->attr);
1474 /* Sanity check number of worker threads */
1475 if (workers != num_workers)
1477 end_critical_section(S_THREAD_LIST);
1478 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n", workers, num_workers);
1479 // pthread_mutex_unlock(&thread_gc_mutex);
1480 // CtdlThreadStopAll();
1483 // pthread_mutex_unlock(&thread_gc_mutex);
1485 end_critical_section(S_THREAD_LIST);
1492 * Runtime function for a Citadel Thread.
1493 * This initialises the threads environment and then calls the user supplied thread function
1494 * Note that this is the REAL thread function and wraps the users thread function.
1496 static void *ctdl_internal_thread_func (void *arg)
1498 struct CtdlThreadNode *this_thread;
1501 /* lock and unlock the thread list.
1502 * This causes this thread to wait until all its creation stuff has finished before it
1503 * can continue its execution.
1505 begin_critical_section(S_THREAD_LIST);
1506 // Get our thread data structure
1507 this_thread = (struct CtdlThreadNode *) arg;
1508 this_thread->state = CTDL_THREAD_RUNNING;
1509 this_thread->pid = getpid();
1510 end_critical_section(S_THREAD_LIST);
1512 // Tell the world we are here
1513 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1515 // Register the cleanup function to take care of when we exit.
1516 pthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
1520 * run the thread to do the work
1522 ret = (this_thread->thread_func)(this_thread->user_args);
1525 * Our thread is exiting either because it wanted to end or because the server is stopping
1526 * We need to clean up
1528 pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1536 * Internal function to create a thread.
1537 * Must be called from within a S_THREAD_LIST critical section
1539 struct CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1542 struct CtdlThreadNode *this_thread;
1544 sigset_t old_signal_set;
1546 if (num_threads >= 32767)
1548 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1552 this_thread = malloc(sizeof(struct CtdlThreadNode));
1553 if (this_thread == NULL) {
1554 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1557 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1558 memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1560 this_thread->state = CTDL_THREAD_CREATE;
1562 if ((ret = pthread_attr_init(&this_thread->attr))) {
1563 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1568 /* Our per-thread stacks need to be bigger than the default size,
1569 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1570 * crashes on 64-bit Linux.
1572 if (flags & CTDLTHREAD_BIGSTACK)
1574 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1575 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1576 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1578 pthread_attr_destroy(&this_thread->attr);
1585 * If we got here we are going to create the thread so we must initilise the structure
1586 * first because most implimentations of threading can't create it in a stopped state
1587 * and it might want to do things with its structure that aren't initialised otherwise.
1591 this_thread->name = strdup(name);
1595 this_thread->name = strdup("Un-named Thread");
1598 this_thread->flags = flags;
1599 this_thread->thread_func = thread_func;
1600 this_thread->user_args = args;
1601 pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1602 pthread_cond_init (&(this_thread->ThreadCond), NULL);
1605 * We want to make sure that only the main thread handles signals,
1606 * so that each signal is handled exactly once. To do this, we
1607 * make sure that each new thread has all the signals that we
1608 * handle blocked. To avoid race conditions, we block them in
1609 * the spawning thread first, then create the new thread (which
1610 * inherits the settings), and then restore the old settings in
1611 * the spawning thread. This means that there is a brief period
1612 * when no signals will be processed, but during that time they
1613 * should be queued by the operating system.
1615 if (pthread_equal(GC_thread, pthread_self()))
1616 sigtrick = ctdl_thread_internal_block_signals(&old_signal_set) == 0;
1619 * We pass this_thread into the thread as its args so that it can find out information
1620 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1621 * thread function needs to finish off the setup of the structure
1623 if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1626 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1628 if (this_thread->name)
1629 free (this_thread->name);
1630 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1631 pthread_cond_destroy(&(this_thread->ThreadCond));
1632 pthread_attr_destroy(&this_thread->attr);
1635 ctdl_thread_internal_restore_signals(&old_signal_set);
1640 ctdl_thread_internal_restore_signals(&old_signal_set);
1642 num_threads++; // Increase the count of threads in the system.
1643 if(this_thread->flags & CTDLTHREAD_WORKER)
1646 this_thread->next = CtdlThreadList;
1647 CtdlThreadList = this_thread;
1648 if (this_thread->next)
1649 this_thread->next->prev = this_thread;
1650 // Register for tracing
1651 #ifdef HAVE_BACKTRACE
1652 eCrash_RegisterThread(this_thread->name, 0);
1658 * Wrapper function to create a thread
1659 * ensures the critical section and other protections are in place.
1660 * char *name = name to give to thread, if NULL, use generic name
1661 * int flags = flags to determine type of thread and standard facilities
1663 struct CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1665 struct CtdlThreadNode *ret = NULL;
1667 begin_critical_section(S_THREAD_LIST);
1668 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1669 end_critical_section(S_THREAD_LIST);
1677 * Purge all sessions which have the 'kill_me' flag set.
1678 * This function has code to prevent it from running more than once every
1679 * few seconds, because running it after every single unbind would waste a lot
1680 * of CPU time and keep the context list locked too much. To force it to run
1681 * anyway, set "force" to nonzero.
1684 * After that's done, we raise the size of the worker thread pool
1685 * if such an action is appropriate.
1687 void dead_session_purge(int force) {
1688 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1689 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1692 if ( (time(NULL) - last_purge) < 5 ) {
1693 return; /* Too soon, go away */
1698 begin_critical_section(S_SESSION_TABLE);
1704 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1705 /* Remove the session from the active list */
1707 ptr2->prev->next = ptr2->next;
1710 ContextList = ptr2->next;
1713 ptr2->next->prev = ptr2->prev;
1718 /* And put it on our to-be-destroyed list */
1724 end_critical_section(S_SESSION_TABLE);
1726 /* Now that we no longer have the session list locked, we can take
1727 * our time and destroy any sessions on the to-be-killed list, which
1728 * is allocated privately on this thread's stack.
1730 while (rem != NULL) {
1731 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1738 /* Raise the size of the worker thread pool if necessary. */
1739 begin_critical_section(S_THREAD_LIST);
1740 if ( (num_sessions > num_workers)
1741 && (num_workers < config.c_max_workers) ) {
1742 ctdl_internal_create_thread(NULL, CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER, worker_thread, NULL);
1744 end_critical_section(S_THREAD_LIST);
1745 // FIXME: reduce the number of worker threads too
1753 * masterCC is the context we use when not attached to a session. This
1754 * function initializes it.
1756 void InitializeMasterCC(void) {
1757 memset(&masterCC, 0, sizeof(struct CitContext));
1758 masterCC.internal_pgm = 1;
1759 masterCC.cs_pid = 0;
1768 * Bind a thread to a context. (It's inline merely to speed things up.)
1770 INLINE void become_session(struct CitContext *which_con) {
1771 pthread_setspecific(MyConKey, (void *)which_con );
1777 * This loop just keeps going and going and going...
1779 void *worker_thread(void *arg) {
1782 struct CitContext *ptr;
1783 struct CitContext *bind_me = NULL;
1786 struct CitContext *con= NULL; /* Temporary context pointer */
1787 struct ServiceFunctionHook *serviceptr;
1788 int ssock; /* Descriptor for client socket */
1790 int force_purge = 0;
1795 while (!CtdlThreadCheckStop()) {
1797 /* make doubly sure we're not holding any stale db handles
1798 * which might cause a deadlock.
1800 cdb_check_handles();
1801 do_select: force_purge = 0;
1802 bind_me = NULL; /* Which session shall we handle? */
1804 /* Initialize the fdset. */
1808 begin_critical_section(S_SESSION_TABLE);
1809 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1810 if (ptr->state == CON_IDLE) {
1811 FD_SET(ptr->client_socket, &readfds);
1812 if (ptr->client_socket > highest)
1813 highest = ptr->client_socket;
1815 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1817 ptr->state = CON_EXECUTING;
1820 end_critical_section(S_SESSION_TABLE);
1826 /* If we got this far, it means that there are no sessions
1827 * which a previous thread marked for attention, so we go
1828 * ahead and get ready to select().
1831 /* First, add the various master sockets to the fdset. */
1832 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1833 serviceptr = serviceptr->next ) {
1834 m = serviceptr->msock;
1835 FD_SET(m, &readfds);
1841 if (!CtdlThreadCheckStop()) {
1842 tv.tv_sec = 1; /* wake up every second if no input */
1844 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1847 if (CtdlThreadCheckStop()) return(NULL);
1849 /* Now figure out who made this select() unblock.
1850 * First, check for an error or exit condition.
1853 if (errno == EBADF) {
1854 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1858 if (errno != EINTR) {
1859 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1860 CtdlThreadStopAll();
1861 } else if (!CtdlThreadCheckStop()) {
1862 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
1866 else if(retval == 0) {
1869 /* Next, check to see if it's a new client connecting
1870 * on a master socket.
1872 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1873 serviceptr = serviceptr->next ) {
1875 if (FD_ISSET(serviceptr->msock, &readfds)) {
1876 ssock = accept(serviceptr->msock, NULL, 0);
1878 CtdlLogPrintf(CTDL_DEBUG,
1879 "New client socket %d\n",
1882 /* The master socket is non-blocking but the client
1883 * sockets need to be blocking, otherwise certain
1884 * operations barf on FreeBSD. Not a fatal error.
1886 if (fcntl(ssock, F_SETFL, 0) < 0) {
1887 CtdlLogPrintf(CTDL_EMERG,
1888 "citserver: Can't set socket to blocking: %s\n",
1892 /* New context will be created already
1893 * set up in the CON_EXECUTING state.
1895 con = CreateNewContext();
1897 /* Assign our new socket number to it. */
1898 con->client_socket = ssock;
1899 con->h_command_function =
1900 serviceptr->h_command_function;
1901 con->h_async_function =
1902 serviceptr->h_async_function;
1904 serviceptr->ServiceName;
1906 /* Determine whether it's a local socket */
1907 if (serviceptr->sockpath != NULL)
1908 con->is_local_socket = 1;
1910 /* Set the SO_REUSEADDR socket option */
1912 setsockopt(ssock, SOL_SOCKET,
1916 become_session(con);
1918 serviceptr->h_greeting_function();
1919 become_session(NULL);
1920 con->state = CON_IDLE;
1926 /* It must be a client socket. Find a context that has data
1927 * waiting on its socket *and* is in the CON_IDLE state. Any
1928 * active sockets other than our chosen one are marked as
1929 * CON_READY so the next thread that comes around can just bind
1930 * to one without having to select() again.
1932 begin_critical_section(S_SESSION_TABLE);
1933 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1934 if ( (FD_ISSET(ptr->client_socket, &readfds))
1935 && (ptr->state != CON_EXECUTING) ) {
1936 ptr->input_waiting = 1;
1938 bind_me = ptr; /* I choose you! */
1939 bind_me->state = CON_EXECUTING;
1942 ptr->state = CON_READY;
1946 end_critical_section(S_SESSION_TABLE);
1949 /* We're bound to a session */
1950 if (bind_me != NULL) {
1951 become_session(bind_me);
1953 /* If the client has sent a command, execute it. */
1954 if (CC->input_waiting) {
1955 CC->h_command_function();
1956 CC->input_waiting = 0;
1959 /* If there are asynchronous messages waiting and the
1960 * client supports it, do those now */
1961 if ((CC->is_async) && (CC->async_waiting)
1962 && (CC->h_async_function != NULL)) {
1963 CC->h_async_function();
1964 CC->async_waiting = 0;
1967 force_purge = CC->kill_me;
1968 become_session(NULL);
1969 bind_me->state = CON_IDLE;
1972 dead_session_purge(force_purge);
1974 check_sched_shutdown();
1976 /* If control reaches this point, the server is shutting down */
1985 * Translate text facility name to syslog.h defined value.
1987 int SyslogFacility(char *name)
1996 { LOG_KERN, "kern" },
1997 { LOG_USER, "user" },
1998 { LOG_MAIL, "mail" },
1999 { LOG_DAEMON, "daemon" },
2000 { LOG_AUTH, "auth" },
2001 { LOG_SYSLOG, "syslog" },
2003 { LOG_NEWS, "news" },
2004 { LOG_UUCP, "uucp" },
2005 { LOG_LOCAL0, "local0" },
2006 { LOG_LOCAL1, "local1" },
2007 { LOG_LOCAL2, "local2" },
2008 { LOG_LOCAL3, "local3" },
2009 { LOG_LOCAL4, "local4" },
2010 { LOG_LOCAL5, "local5" },
2011 { LOG_LOCAL6, "local6" },
2012 { LOG_LOCAL7, "local7" },
2015 for(i = 0; facTbl[i].name != NULL; i++) {
2016 if(!strcasecmp(name, facTbl[i].name))
2017 return facTbl[i].facility;
2024 /********** MEM CHEQQER ***********/
2026 #ifdef DEBUG_MEMORY_LEAKS
2033 void *tracked_malloc(size_t size, char *file, int line) {
2034 struct igheap *thisheap;
2037 block = malloc(size);
2038 if (block == NULL) return(block);
2040 thisheap = malloc(sizeof(struct igheap));
2041 if (thisheap == NULL) {
2046 thisheap->block = block;
2047 strcpy(thisheap->file, file);
2048 thisheap->line = line;
2050 begin_critical_section(S_DEBUGMEMLEAKS);
2051 thisheap->next = igheap;
2053 end_critical_section(S_DEBUGMEMLEAKS);
2059 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
2060 struct igheap *thisheap;
2063 block = realloc(ptr, size);
2064 if (block == NULL) return(block);
2066 thisheap = malloc(sizeof(struct igheap));
2067 if (thisheap == NULL) {
2072 thisheap->block = block;
2073 strcpy(thisheap->file, file);
2074 thisheap->line = line;
2076 begin_critical_section(S_DEBUGMEMLEAKS);
2077 thisheap->next = igheap;
2079 end_critical_section(S_DEBUGMEMLEAKS);
2086 void tracked_free(void *ptr) {
2087 struct igheap *thisheap;
2088 struct igheap *trash;
2092 if (igheap == NULL) return;
2093 begin_critical_section(S_DEBUGMEMLEAKS);
2094 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2095 if (thisheap->next != NULL) {
2096 if (thisheap->next->block == ptr) {
2097 trash = thisheap->next;
2098 thisheap->next = thisheap->next->next;
2103 if (igheap->block == ptr) {
2105 igheap = igheap->next;
2108 end_critical_section(S_DEBUGMEMLEAKS);
2111 char *tracked_strdup(const char *s, char *file, int line) {
2114 if (s == NULL) return(NULL);
2115 ptr = tracked_malloc(strlen(s) + 1, file, line);
2116 if (ptr == NULL) return(NULL);
2117 strncpy(ptr, s, strlen(s));
2121 void dump_heap(void) {
2122 struct igheap *thisheap;
2124 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2125 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
2126 thisheap->file, thisheap->line);
2130 #endif /* DEBUG_MEMORY_LEAKS */