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>
57 #include "sysdep_decls.h"
58 #include "citserver.h"
62 #include "housekeeping.h"
64 #include "serv_crypto.h"
65 #include "serv_fulltext.h"
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 */
97 pthread_t indexer_thread_tid;
98 pthread_t checkpoint_thread_tid;
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
102 extern int running_as_daemon;
104 void DestroyWorkerList(void);
107 * lprintf() ... Write logging information
109 void lprintf(enum LogLevel loglevel, const char *format, ...) {
113 va_start(arg_ptr, format);
114 vsyslog((syslog_facility | loglevel), format, arg_ptr);
118 /* stderr output code */
119 if (enable_syslog || running_as_daemon) return;
121 /* if we run in forground and syslog is disabled, log to terminal */
122 if (loglevel <= verbosity) {
127 gettimeofday(&tv, NULL);
128 /* Promote to time_t; types differ on some OSes (like darwin) */
129 unixtime = tv.tv_sec;
130 localtime_r(&unixtime, &tim);
131 if (CC->cs_pid != 0) {
133 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
134 tim.tm_year + 1900, tim.tm_mon + 1,
135 tim.tm_mday, tim.tm_hour, tim.tm_min,
136 tim.tm_sec, (long)tv.tv_usec,
140 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
141 tim.tm_year + 1900, tim.tm_mon + 1,
142 tim.tm_mday, tim.tm_hour, tim.tm_min,
143 tim.tm_sec, (long)tv.tv_usec);
145 va_start(arg_ptr, format);
146 vfprintf(stderr, format, arg_ptr);
155 * Signal handler to shut down the server.
158 volatile int time_to_die = 0;
159 volatile int shutdown_and_halt = 0;
161 static RETSIGTYPE signal_cleanup(int signum) {
162 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
164 master_cleanup(signum);
168 * Some initialization stuff...
170 void init_sysdep(void) {
174 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
178 getrlimit(RLIMIT_NOFILE, &rl);
179 rl.rlim_cur = FD_SETSIZE;
180 rl.rlim_max = FD_SETSIZE;
181 setrlimit(RLIMIT_NOFILE, &rl);
185 /* If we've got OpenSSL, we're going to use it. */
190 /* Set up a bunch of semaphores to be used for critical sections */
191 for (i=0; i<MAX_SEMAPHORES; ++i) {
192 pthread_mutex_init(&Critters[i], NULL);
196 * Set up a place to put thread-specific data.
197 * We only need a single pointer per thread - it points to the
198 * CitContext structure (in the ContextList linked list) of the
199 * session to which the calling thread is currently bound.
201 if (pthread_key_create(&MyConKey, NULL) != 0) {
202 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
207 * The action for unexpected signals and exceptions should be to
208 * call signal_cleanup() to gracefully shut down the server.
211 sigaddset(&set, SIGINT);
212 sigaddset(&set, SIGQUIT);
213 sigaddset(&set, SIGHUP);
214 sigaddset(&set, SIGTERM);
215 // sigaddset(&set, SIGSEGV); commented out because
216 // sigaddset(&set, SIGILL); we want core dumps
217 // sigaddset(&set, SIGBUS);
218 sigprocmask(SIG_UNBLOCK, &set, NULL);
220 signal(SIGINT, signal_cleanup);
221 signal(SIGQUIT, signal_cleanup);
222 signal(SIGHUP, signal_cleanup);
223 signal(SIGTERM, signal_cleanup);
224 // signal(SIGSEGV, signal_cleanup); commented out because
225 // signal(SIGILL, signal_cleanup); we want core dumps
226 // signal(SIGBUS, signal_cleanup);
229 * Do not shut down the server on broken pipe signals, otherwise the
230 * whole Citadel service would come down whenever a single client
233 signal(SIGPIPE, SIG_IGN);
238 * Obtain a semaphore lock to begin a critical section.
240 void begin_critical_section(int which_one)
242 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
244 /* For all types of critical sections except those listed here,
245 * ensure nobody ever tries to do a critical section within a
246 * transaction; this could lead to deadlock.
248 if ( (which_one != S_FLOORCACHE)
249 #ifdef DEBUG_MEMORY_LEAKS
250 && (which_one != S_DEBUGMEMLEAKS)
252 && (which_one != S_RPLIST)
256 pthread_mutex_lock(&Critters[which_one]);
260 * Release a semaphore lock to end a critical section.
262 void end_critical_section(int which_one)
264 pthread_mutex_unlock(&Critters[which_one]);
270 * This is a generic function to set up a master socket for listening on
271 * a TCP port. The server shuts down if the bind fails.
274 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
276 struct sockaddr_in sin;
278 int actual_queue_len;
280 actual_queue_len = queue_len;
281 if (actual_queue_len < 5) actual_queue_len = 5;
283 memset(&sin, 0, sizeof(sin));
284 sin.sin_family = AF_INET;
285 sin.sin_port = htons((u_short)port_number);
286 if (ip_addr == NULL) {
287 sin.sin_addr.s_addr = INADDR_ANY;
290 sin.sin_addr.s_addr = inet_addr(ip_addr);
293 if (sin.sin_addr.s_addr == !INADDR_ANY) {
294 sin.sin_addr.s_addr = INADDR_ANY;
297 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
300 *errormessage = (char*) malloc(SIZ + 1);
301 snprintf(*errormessage, SIZ,
302 "citserver: Can't create a socket: %s",
304 lprintf(CTDL_EMERG, "%s\n", *errormessage);
309 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
311 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
312 *errormessage = (char*) malloc(SIZ + 1);
313 snprintf(*errormessage, SIZ,
314 "citserver: Can't bind: %s",
316 lprintf(CTDL_EMERG, "%s\n", *errormessage);
321 /* set to nonblock - we need this for some obscure situations */
322 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
323 *errormessage = (char*) malloc(SIZ + 1);
324 snprintf(*errormessage, SIZ,
325 "citserver: Can't set socket to non-blocking: %s",
327 lprintf(CTDL_EMERG, "%s\n", *errormessage);
332 if (listen(s, actual_queue_len) < 0) {
333 *errormessage = (char*) malloc(SIZ + 1);
334 snprintf(*errormessage, SIZ,
335 "citserver: Can't listen: %s",
337 lprintf(CTDL_EMERG, "%s\n", *errormessage);
348 * Create a Unix domain socket and listen on it
350 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
352 struct sockaddr_un addr;
355 int actual_queue_len;
357 actual_queue_len = queue_len;
358 if (actual_queue_len < 5) actual_queue_len = 5;
360 i = unlink(sockpath);
361 if (i != 0) if (errno != ENOENT) {
362 *errormessage = (char*) malloc(SIZ + 1);
363 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
364 sockpath, strerror(errno));
365 lprintf(CTDL_EMERG, "%s\n", *errormessage);
369 memset(&addr, 0, sizeof(addr));
370 addr.sun_family = AF_UNIX;
371 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
373 s = socket(AF_UNIX, SOCK_STREAM, 0);
375 *errormessage = (char*) malloc(SIZ + 1);
376 snprintf(*errormessage, SIZ,
377 "citserver: Can't create a socket: %s",
379 lprintf(CTDL_EMERG, "%s\n", *errormessage);
383 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
384 *errormessage = (char*) malloc(SIZ + 1);
385 snprintf(*errormessage, SIZ,
386 "citserver: Can't bind: %s",
388 lprintf(CTDL_EMERG, "%s\n", *errormessage);
392 /* set to nonblock - we need this for some obscure situations */
393 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
394 *errormessage = (char*) malloc(SIZ + 1);
395 snprintf(*errormessage, SIZ,
396 "citserver: Can't set socket to non-blocking: %s",
398 lprintf(CTDL_EMERG, "%s\n", *errormessage);
403 if (listen(s, actual_queue_len) < 0) {
404 *errormessage = (char*) malloc(SIZ + 1);
405 snprintf(*errormessage, SIZ,
406 "citserver: Can't listen: %s",
408 lprintf(CTDL_EMERG, "%s\n", *errormessage);
412 chmod(sockpath, 0777);
419 * Return a pointer to the CitContext structure bound to the thread which
420 * called this function. If there's no such binding (for example, if it's
421 * called by the housekeeper thread) then a generic 'master' CC is returned.
423 * This function is used *VERY* frequently and must be kept small.
425 struct CitContext *MyContext(void) {
427 register struct CitContext *c;
429 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
430 c == NULL) ? &masterCC : c
436 * Initialize a new context and place it in the list. The session number
437 * used to be the PID (which is why it's called cs_pid), but that was when we
438 * had one process per session. Now we just assign them sequentially, starting
439 * at 1 (don't change it to 0 because masterCC uses 0).
441 struct CitContext *CreateNewContext(void) {
442 struct CitContext *me;
443 static int next_pid = 0;
445 me = (struct CitContext *) malloc(sizeof(struct CitContext));
447 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
450 memset(me, 0, sizeof(struct CitContext));
452 /* The new context will be created already in the CON_EXECUTING state
453 * in order to prevent another thread from grabbing it while it's
456 me->state = CON_EXECUTING;
459 * Generate a unique session number and insert this context into
462 begin_critical_section(S_SESSION_TABLE);
463 me->cs_pid = ++next_pid;
465 me->next = ContextList;
467 if (me->next != NULL) {
471 end_critical_section(S_SESSION_TABLE);
477 * The following functions implement output buffering. If the kernel supplies
478 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
479 * user-space buffering.
483 # define HAVE_TCP_BUFFERING
486 # define HAVE_TCP_BUFFERING
487 # define TCP_CORK TCP_NOPUSH
489 #endif /* TCP_CORK */
490 #endif /* HAVE_DARWIN */
492 #ifdef HAVE_TCP_BUFFERING
493 static unsigned on = 1, off = 0;
494 void buffer_output(void) {
495 struct CitContext *ctx = MyContext();
496 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
500 void unbuffer_output(void) {
501 struct CitContext *ctx = MyContext();
502 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
506 void flush_output(void) {
507 struct CitContext *ctx = MyContext();
508 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
509 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
512 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
513 void buffer_output(void) {
516 void unbuffer_output(void) {
519 void flush_output(void) {
522 void buffer_output(void) {
523 if (CC->buffering == 0) {
526 CC->output_buffer = malloc(SIZ);
530 void flush_output(void) {
531 if (CC->buffering == 1) {
532 client_write(CC->output_buffer, CC->buffer_len);
537 void unbuffer_output(void) {
538 if (CC->buffering == 1) {
540 /* We don't call flush_output because we can't. */
541 client_write(CC->output_buffer, CC->buffer_len);
543 free(CC->output_buffer);
544 CC->output_buffer = NULL;
552 * client_write() ... Send binary data to the client.
554 void client_write(char *buf, int nbytes)
556 int bytes_written = 0;
558 #ifndef HAVE_TCP_BUFFERING
559 int old_buffer_len = 0;
562 if (CC->redirect_buffer != NULL) {
563 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
564 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
565 CC->redirect_buffer = realloc(CC->redirect_buffer,
568 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
569 CC->redirect_len += nbytes;
570 CC->redirect_buffer[CC->redirect_len] = 0;
574 #ifndef HAVE_TCP_BUFFERING
575 /* If we're buffering for later, do that now. */
577 old_buffer_len = CC->buffer_len;
578 CC->buffer_len += nbytes;
579 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
580 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
585 /* Ok, at this point we're not buffering. Go ahead and write. */
588 if (CC->redirect_ssl) {
589 client_write_ssl(buf, nbytes);
594 while (bytes_written < nbytes) {
595 retval = write(CC->client_socket, &buf[bytes_written],
596 nbytes - bytes_written);
599 "client_write(%d bytes) failed: %s (%d)\n",
600 nbytes - bytes_written,
601 strerror(errno), errno);
605 bytes_written = bytes_written + retval;
611 * cprintf() ... Send formatted printable data to the client. It is
612 * implemented in terms of client_write() but remains in
613 * sysdep.c in case we port to somewhere without va_args...
615 void cprintf(const char *format, ...) {
619 va_start(arg_ptr, format);
620 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
621 buf[sizeof buf - 2] = '\n';
622 client_write(buf, strlen(buf));
628 * Read data from the client socket.
630 * 1 Requested number of bytes has been read.
631 * 0 Request timed out.
632 * -1 The socket is broken.
633 * If the socket breaks, the session will be terminated.
635 int client_read_to(char *buf, int bytes, int timeout)
643 if (CC->redirect_ssl) {
644 return (client_read_ssl(buf, bytes, timeout));
650 FD_SET(CC->client_socket, &rfds);
654 retval = select( (CC->client_socket)+1,
655 &rfds, NULL, NULL, &tv);
657 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
661 rlen = read(CC->client_socket, &buf[len], bytes-len);
663 /* The socket has been disconnected! */
673 * Read data from the client socket with default timeout.
674 * (This is implemented in terms of client_read_to() and could be
675 * justifiably moved out of sysdep.c)
677 INLINE int client_read(char *buf, int bytes)
679 return(client_read_to(buf, bytes, config.c_sleeping));
684 * client_getln() ... Get a LF-terminated line of text from the client.
685 * (This is implemented in terms of client_read() and could be
686 * justifiably moved out of sysdep.c)
688 int client_getln(char *buf, int bufsize)
692 /* Read one character at a time.
695 retval = client_read(&buf[i], 1);
696 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
700 /* If we got a long line, discard characters until the newline.
702 if (i == (bufsize-1))
703 while (buf[i] != '\n' && retval == 1)
704 retval = client_read(&buf[i], 1);
706 /* Strip the trailing LF, and the trailing CR if present.
709 while ( (strlen(buf) > 0) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
710 buf[strlen(buf)-1] = 0;
712 if (retval < 0) safestrncpy(buf, "000", bufsize);
719 * The system-dependent part of master_cleanup() - close the master socket.
721 void sysdep_master_cleanup(void) {
722 struct ServiceFunctionHook *serviceptr;
724 ///// DestroyWorkerList();
726 * close all protocol master sockets
728 for (serviceptr = ServiceHookTable; serviceptr != NULL;
729 serviceptr = serviceptr->next ) {
731 if (serviceptr->tcp_port > 0)
732 lprintf(CTDL_INFO, "Closing listener on port %d\n",
733 serviceptr->tcp_port);
735 if (serviceptr->sockpath != NULL)
736 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
737 serviceptr->sockpath);
739 close(serviceptr->msock);
741 /* If it's a Unix domain socket, remove the file. */
742 if (serviceptr->sockpath != NULL) {
743 unlink(serviceptr->sockpath);
749 serv_calendar_destroy();
750 CtdlDestroyProtoHooks();
751 CtdlDestroyDeleteHooks();
752 CtdlDestroyXmsgHooks();
753 CtdlDestroyNetprocHooks();
754 CtdlDestroyUserHooks();
755 CtdlDestroyMessageHook();
756 CtdlDestroyCleanupHooks();
757 CtdlDestroyFixedOutputHooks();
758 CtdlDestroySessionHooks();
759 CtdlDestroyServiceHook();
766 * Terminate another session.
767 * (This could justifiably be moved out of sysdep.c because it
768 * no longer does anything that is system-dependent.)
770 void kill_session(int session_to_kill) {
771 struct CitContext *ptr;
773 begin_critical_section(S_SESSION_TABLE);
774 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
775 if (ptr->cs_pid == session_to_kill) {
779 end_critical_section(S_SESSION_TABLE);
783 void graceful_shutdown(int signum) {
784 kill(current_child, signum);
785 unlink(file_pid_file);
791 * Start running as a daemon.
793 void start_daemon(int unused) {
801 /* Close stdin/stdout/stderr and replace them with /dev/null.
802 * We don't just call close() because we don't want these fd's
803 * to be reused for other files.
812 signal(SIGHUP, SIG_IGN);
813 signal(SIGINT, SIG_IGN);
814 signal(SIGQUIT, SIG_IGN);
818 freopen("/dev/null", "r", stdin);
819 freopen("/dev/null", "w", stdout);
820 freopen("/dev/null", "w", stderr);
823 current_child = fork();
825 signal(SIGTERM, graceful_shutdown);
827 if (current_child < 0) {
832 else if (current_child == 0) {
833 return; /* continue starting citadel. */
837 fp = fopen(file_pid_file, "w");
839 fprintf(fp, ""F_PID_T"\n", child);
842 waitpid(current_child, &status, 0);
847 /* Did the main process exit with an actual exit code? */
848 if (WIFEXITED(status)) {
850 /* Exit code 0 means the watcher should exit */
851 if (WEXITSTATUS(status) == 0) {
855 /* Exit code 101-109 means the watcher should exit */
856 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
860 /* Any other exit code means we should restart. */
866 /* Any other type of termination (signals, etc.) should also restart. */
871 } while (do_restart);
873 unlink(file_pid_file);
874 exit(WEXITSTATUS(status));
880 * Generic routine to convert a login name to a full name (gecos)
881 * Returns nonzero if a conversion took place
883 int convert_login(char NameToConvert[]) {
887 pw = getpwnam(NameToConvert);
892 strcpy(NameToConvert, pw->pw_gecos);
893 for (a=0; a<strlen(NameToConvert); ++a) {
894 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
900 struct worker_node *worker_list = NULL;
904 * create a worker thread. this function must always be called from within
905 * an S_WORKER_LIST critical section!
907 void create_worker(void) {
909 struct worker_node *n;
912 n = malloc(sizeof(struct worker_node));
914 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
919 if ((ret = pthread_attr_init(&attr))) {
920 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
925 /* Our per-thread stacks need to be bigger than the default size,
926 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
927 * crashes on 64-bit Linux.
929 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
930 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
933 pthread_attr_destroy(&attr);
937 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
940 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
944 n->next = worker_list;
946 pthread_attr_destroy(&attr);
949 void DestroyWorkerList(void)
951 struct CitContext *ptr; /* general-purpose utility pointer */
952 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
954 begin_critical_section(S_SESSION_TABLE);
957 /* Remove the session from the active list */
961 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
962 end_critical_section(S_SESSION_TABLE);
964 begin_critical_section(S_SESSION_TABLE);
968 end_critical_section(S_SESSION_TABLE);
970 struct worker_node *cur, *p;
982 * Create the indexer thread and begin its operation.
983 * Then create the checkpoint thread and begin its operation.
985 void create_maintenance_threads(void) {
989 if ((ret = pthread_attr_init(&attr))) {
990 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
995 /* Our per-thread stacks need to be bigger than the default size,
996 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
997 * crashes on 64-bit Linux.
999 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1000 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1003 pthread_attr_destroy(&attr);
1007 if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
1008 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1011 if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
1012 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1015 lprintf(CTDL_NOTICE, "Spawned indexer (%ld) and checkpoint (%ld) thread. \n",
1016 indexer_thread_tid, checkpoint_thread_tid);
1017 pthread_attr_destroy(&attr);
1023 * Purge all sessions which have the 'kill_me' flag set.
1024 * This function has code to prevent it from running more than once every
1025 * few seconds, because running it after every single unbind would waste a lot
1026 * of CPU time and keep the context list locked too much. To force it to run
1027 * anyway, set "force" to nonzero.
1030 * After that's done, we raise the size of the worker thread pool
1031 * if such an action is appropriate.
1033 void dead_session_purge(int force) {
1034 struct CitContext *ptr; /* general-purpose utility pointer */
1035 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1038 if ( (time(NULL) - last_purge) < 5 ) {
1039 return; /* Too soon, go away */
1044 begin_critical_section(S_SESSION_TABLE);
1045 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1046 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1048 /* Remove the session from the active list */
1050 ptr->prev->next = ptr->next;
1053 ContextList = ptr->next;
1056 ptr->next->prev = ptr->prev;
1061 /* And put it on our to-be-destroyed list */
1067 end_critical_section(S_SESSION_TABLE);
1069 /* Now that we no longer have the session list locked, we can take
1070 * our time and destroy any sessions on the to-be-killed list, which
1071 * is allocated privately on this thread's stack.
1073 while (rem != NULL) {
1074 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1081 /* Raise the size of the worker thread pool if necessary. */
1082 if ( (num_sessions > num_threads)
1083 && (num_threads < config.c_max_workers) ) {
1084 begin_critical_section(S_WORKER_LIST);
1086 end_critical_section(S_WORKER_LIST);
1095 * masterCC is the context we use when not attached to a session. This
1096 * function initializes it.
1098 void InitializeMasterCC(void) {
1099 memset(&masterCC, 0, sizeof(struct CitContext));
1100 masterCC.internal_pgm = 1;
1101 masterCC.cs_pid = 0;
1110 * Bind a thread to a context. (It's inline merely to speed things up.)
1112 INLINE void become_session(struct CitContext *which_con) {
1113 pthread_setspecific(MyConKey, (void *)which_con );
1119 * This loop just keeps going and going and going...
1121 void *worker_thread(void *arg) {
1124 struct CitContext *ptr;
1125 struct CitContext *bind_me = NULL;
1128 struct CitContext *con= NULL; /* Temporary context pointer */
1129 struct ServiceFunctionHook *serviceptr;
1130 int ssock; /* Descriptor for client socket */
1132 int force_purge = 0;
1139 while (!time_to_die) {
1141 /* make doubly sure we're not holding any stale db handles
1142 * which might cause a deadlock.
1144 cdb_check_handles();
1145 do_select: force_purge = 0;
1146 bind_me = NULL; /* Which session shall we handle? */
1148 /* Initialize the fdset. */
1152 begin_critical_section(S_SESSION_TABLE);
1153 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1154 if (ptr->state == CON_IDLE) {
1155 FD_SET(ptr->client_socket, &readfds);
1156 if (ptr->client_socket > highest)
1157 highest = ptr->client_socket;
1159 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1161 ptr->state = CON_EXECUTING;
1164 end_critical_section(S_SESSION_TABLE);
1170 /* If we got this far, it means that there are no sessions
1171 * which a previous thread marked for attention, so we go
1172 * ahead and get ready to select().
1175 /* First, add the various master sockets to the fdset. */
1176 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1177 serviceptr = serviceptr->next ) {
1178 m = serviceptr->msock;
1179 FD_SET(m, &readfds);
1186 tv.tv_sec = 1; /* wake up every second if no input */
1188 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1191 if (time_to_die) return(NULL);
1193 /* Now figure out who made this select() unblock.
1194 * First, check for an error or exit condition.
1197 if (errno == EBADF) {
1198 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1202 if (errno != EINTR) {
1203 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1205 } else if (!time_to_die)
1209 /* Next, check to see if it's a new client connecting
1210 * on a master socket.
1212 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1213 serviceptr = serviceptr->next ) {
1215 if (FD_ISSET(serviceptr->msock, &readfds)) {
1216 ssock = accept(serviceptr->msock, NULL, 0);
1219 "New client socket %d\n",
1222 /* The master socket is non-blocking but the client
1223 * sockets need to be blocking, otherwise certain
1224 * operations barf on FreeBSD. Not a fatal error.
1226 if (fcntl(ssock, F_SETFL, 0) < 0) {
1228 "citserver: Can't set socket to blocking: %s\n",
1232 /* New context will be created already
1233 * set up in the CON_EXECUTING state.
1235 con = CreateNewContext();
1237 /* Assign our new socket number to it. */
1238 con->client_socket = ssock;
1239 con->h_command_function =
1240 serviceptr->h_command_function;
1241 con->h_async_function =
1242 serviceptr->h_async_function;
1244 /* Determine whether it's a local socket */
1245 if (serviceptr->sockpath != NULL)
1246 con->is_local_socket = 1;
1248 /* Set the SO_REUSEADDR socket option */
1250 setsockopt(ssock, SOL_SOCKET,
1254 become_session(con);
1256 serviceptr->h_greeting_function();
1257 become_session(NULL);
1258 con->state = CON_IDLE;
1264 /* It must be a client socket. Find a context that has data
1265 * waiting on its socket *and* is in the CON_IDLE state. Any
1266 * active sockets other than our chosen one are marked as
1267 * CON_READY so the next thread that comes around can just bind
1268 * to one without having to select() again.
1270 begin_critical_section(S_SESSION_TABLE);
1271 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1272 if ( (FD_ISSET(ptr->client_socket, &readfds))
1273 && (ptr->state != CON_EXECUTING) ) {
1274 ptr->input_waiting = 1;
1276 bind_me = ptr; /* I choose you! */
1277 bind_me->state = CON_EXECUTING;
1280 ptr->state = CON_READY;
1284 end_critical_section(S_SESSION_TABLE);
1287 /* We're bound to a session */
1288 if (bind_me != NULL) {
1289 become_session(bind_me);
1291 /* If the client has sent a command, execute it. */
1292 if (CC->input_waiting) {
1293 CC->h_command_function();
1294 CC->input_waiting = 0;
1297 /* If there are asynchronous messages waiting and the
1298 * client supports it, do those now */
1299 if ((CC->is_async) && (CC->async_waiting)
1300 && (CC->h_async_function != NULL)) {
1301 CC->h_async_function();
1302 CC->async_waiting = 0;
1305 force_purge = CC->kill_me;
1306 become_session(NULL);
1307 bind_me->state = CON_IDLE;
1310 dead_session_purge(force_purge);
1312 check_sched_shutdown();
1314 if (con != NULL) free (con);//// TODO: could this harm other threads?
1315 /* If control reaches this point, the server is shutting down */
1324 * Translate text facility name to syslog.h defined value.
1326 int SyslogFacility(char *name)
1335 { LOG_KERN, "kern" },
1336 { LOG_USER, "user" },
1337 { LOG_MAIL, "mail" },
1338 { LOG_DAEMON, "daemon" },
1339 { LOG_AUTH, "auth" },
1340 { LOG_SYSLOG, "syslog" },
1342 { LOG_NEWS, "news" },
1343 { LOG_UUCP, "uucp" },
1344 { LOG_LOCAL0, "local0" },
1345 { LOG_LOCAL1, "local1" },
1346 { LOG_LOCAL2, "local2" },
1347 { LOG_LOCAL3, "local3" },
1348 { LOG_LOCAL4, "local4" },
1349 { LOG_LOCAL5, "local5" },
1350 { LOG_LOCAL6, "local6" },
1351 { LOG_LOCAL7, "local7" },
1354 for(i = 0; facTbl[i].name != NULL; i++) {
1355 if(!strcasecmp(name, facTbl[i].name))
1356 return facTbl[i].facility;
1363 /********** MEM CHEQQER ***********/
1365 #ifdef DEBUG_MEMORY_LEAKS
1372 void *tracked_malloc(size_t size, char *file, int line) {
1373 struct igheap *thisheap;
1376 block = malloc(size);
1377 if (block == NULL) return(block);
1379 thisheap = malloc(sizeof(struct igheap));
1380 if (thisheap == NULL) {
1385 thisheap->block = block;
1386 strcpy(thisheap->file, file);
1387 thisheap->line = line;
1389 begin_critical_section(S_DEBUGMEMLEAKS);
1390 thisheap->next = igheap;
1392 end_critical_section(S_DEBUGMEMLEAKS);
1398 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1399 struct igheap *thisheap;
1402 block = realloc(ptr, size);
1403 if (block == NULL) return(block);
1405 thisheap = malloc(sizeof(struct igheap));
1406 if (thisheap == NULL) {
1411 thisheap->block = block;
1412 strcpy(thisheap->file, file);
1413 thisheap->line = line;
1415 begin_critical_section(S_DEBUGMEMLEAKS);
1416 thisheap->next = igheap;
1418 end_critical_section(S_DEBUGMEMLEAKS);
1425 void tracked_free(void *ptr) {
1426 struct igheap *thisheap;
1427 struct igheap *trash;
1431 if (igheap == NULL) return;
1432 begin_critical_section(S_DEBUGMEMLEAKS);
1433 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1434 if (thisheap->next != NULL) {
1435 if (thisheap->next->block == ptr) {
1436 trash = thisheap->next;
1437 thisheap->next = thisheap->next->next;
1442 if (igheap->block == ptr) {
1444 igheap = igheap->next;
1447 end_critical_section(S_DEBUGMEMLEAKS);
1450 char *tracked_strdup(const char *s, char *file, int line) {
1453 if (s == NULL) return(NULL);
1454 ptr = tracked_malloc(strlen(s) + 1, file, line);
1455 if (ptr == NULL) return(NULL);
1456 strncpy(ptr, s, strlen(s));
1460 void dump_heap(void) {
1461 struct igheap *thisheap;
1463 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1464 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1465 thisheap->file, thisheap->line);
1469 #endif /* DEBUG_MEMORY_LEAKS */