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;
103 void DestroyWorkerList(void);
106 * lprintf() ... Write logging information
108 void lprintf(enum LogLevel loglevel, const char *format, ...) {
112 va_start(arg_ptr, format);
113 vsyslog((syslog_facility | loglevel), format, arg_ptr);
117 /* stderr output code */
118 if (enable_syslog || running_as_daemon) return;
120 /* if we run in forground and syslog is disabled, log to terminal */
121 if (loglevel <= verbosity) {
126 gettimeofday(&tv, NULL);
127 /* Promote to time_t; types differ on some OSes (like darwin) */
128 unixtime = tv.tv_sec;
129 localtime_r(&unixtime, &tim);
130 if (CC->cs_pid != 0) {
132 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
133 tim.tm_year + 1900, tim.tm_mon + 1,
134 tim.tm_mday, tim.tm_hour, tim.tm_min,
135 tim.tm_sec, (long)tv.tv_usec,
139 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
140 tim.tm_year + 1900, tim.tm_mon + 1,
141 tim.tm_mday, tim.tm_hour, tim.tm_min,
142 tim.tm_sec, (long)tv.tv_usec);
144 va_start(arg_ptr, format);
145 vfprintf(stderr, format, arg_ptr);
154 * Signal handler to shut down the server.
157 volatile int time_to_die = 0;
158 volatile int shutdown_and_halt = 0;
159 volatile int restart_server = 0;
160 volatile int running_as_daemon = 0;
162 static RETSIGTYPE signal_cleanup(int signum) {
163 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
165 master_cleanup(signum);
169 * Some initialization stuff...
171 void init_sysdep(void) {
175 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
179 getrlimit(RLIMIT_NOFILE, &rl);
180 rl.rlim_cur = FD_SETSIZE;
181 rl.rlim_max = FD_SETSIZE;
182 setrlimit(RLIMIT_NOFILE, &rl);
186 /* If we've got OpenSSL, we're going to use it. */
191 /* Set up a bunch of semaphores to be used for critical sections */
192 for (i=0; i<MAX_SEMAPHORES; ++i) {
193 pthread_mutex_init(&Critters[i], NULL);
197 * Set up a place to put thread-specific data.
198 * We only need a single pointer per thread - it points to the
199 * CitContext structure (in the ContextList linked list) of the
200 * session to which the calling thread is currently bound.
202 if (pthread_key_create(&MyConKey, NULL) != 0) {
203 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
208 * The action for unexpected signals and exceptions should be to
209 * call signal_cleanup() to gracefully shut down the server.
212 sigaddset(&set, SIGINT);
213 sigaddset(&set, SIGQUIT);
214 sigaddset(&set, SIGHUP);
215 sigaddset(&set, SIGTERM);
216 // sigaddset(&set, SIGSEGV); commented out because
217 // sigaddset(&set, SIGILL); we want core dumps
218 // sigaddset(&set, SIGBUS);
219 sigprocmask(SIG_UNBLOCK, &set, NULL);
221 signal(SIGINT, signal_cleanup);
222 signal(SIGQUIT, signal_cleanup);
223 signal(SIGHUP, signal_cleanup);
224 signal(SIGTERM, signal_cleanup);
225 // signal(SIGSEGV, signal_cleanup); commented out because
226 // signal(SIGILL, signal_cleanup); we want core dumps
227 // signal(SIGBUS, signal_cleanup);
230 * Do not shut down the server on broken pipe signals, otherwise the
231 * whole Citadel service would come down whenever a single client
234 signal(SIGPIPE, SIG_IGN);
239 * Obtain a semaphore lock to begin a critical section.
241 void begin_critical_section(int which_one)
243 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
245 /* For all types of critical sections except those listed here,
246 * ensure nobody ever tries to do a critical section within a
247 * transaction; this could lead to deadlock.
249 if ( (which_one != S_FLOORCACHE)
250 #ifdef DEBUG_MEMORY_LEAKS
251 && (which_one != S_DEBUGMEMLEAKS)
253 && (which_one != S_RPLIST)
257 pthread_mutex_lock(&Critters[which_one]);
261 * Release a semaphore lock to end a critical section.
263 void end_critical_section(int which_one)
265 pthread_mutex_unlock(&Critters[which_one]);
271 * This is a generic function to set up a master socket for listening on
272 * a TCP port. The server shuts down if the bind fails.
275 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
277 struct sockaddr_in sin;
279 int actual_queue_len;
281 actual_queue_len = queue_len;
282 if (actual_queue_len < 5) actual_queue_len = 5;
284 memset(&sin, 0, sizeof(sin));
285 sin.sin_family = AF_INET;
286 sin.sin_port = htons((u_short)port_number);
287 if (ip_addr == NULL) {
288 sin.sin_addr.s_addr = INADDR_ANY;
291 sin.sin_addr.s_addr = inet_addr(ip_addr);
294 if (sin.sin_addr.s_addr == !INADDR_ANY) {
295 sin.sin_addr.s_addr = INADDR_ANY;
298 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
301 *errormessage = (char*) malloc(SIZ + 1);
302 snprintf(*errormessage, SIZ,
303 "citserver: Can't create a socket: %s",
305 lprintf(CTDL_EMERG, "%s\n", *errormessage);
310 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
312 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
313 *errormessage = (char*) malloc(SIZ + 1);
314 snprintf(*errormessage, SIZ,
315 "citserver: Can't bind: %s",
317 lprintf(CTDL_EMERG, "%s\n", *errormessage);
322 /* set to nonblock - we need this for some obscure situations */
323 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
324 *errormessage = (char*) malloc(SIZ + 1);
325 snprintf(*errormessage, SIZ,
326 "citserver: Can't set socket to non-blocking: %s",
328 lprintf(CTDL_EMERG, "%s\n", *errormessage);
333 if (listen(s, actual_queue_len) < 0) {
334 *errormessage = (char*) malloc(SIZ + 1);
335 snprintf(*errormessage, SIZ,
336 "citserver: Can't listen: %s",
338 lprintf(CTDL_EMERG, "%s\n", *errormessage);
349 * Create a Unix domain socket and listen on it
351 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
353 struct sockaddr_un addr;
356 int actual_queue_len;
358 actual_queue_len = queue_len;
359 if (actual_queue_len < 5) actual_queue_len = 5;
361 i = unlink(sockpath);
362 if (i != 0) if (errno != ENOENT) {
363 *errormessage = (char*) malloc(SIZ + 1);
364 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
365 sockpath, strerror(errno));
366 lprintf(CTDL_EMERG, "%s\n", *errormessage);
370 memset(&addr, 0, sizeof(addr));
371 addr.sun_family = AF_UNIX;
372 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
374 s = socket(AF_UNIX, SOCK_STREAM, 0);
376 *errormessage = (char*) malloc(SIZ + 1);
377 snprintf(*errormessage, SIZ,
378 "citserver: Can't create a socket: %s",
380 lprintf(CTDL_EMERG, "%s\n", *errormessage);
384 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
385 *errormessage = (char*) malloc(SIZ + 1);
386 snprintf(*errormessage, SIZ,
387 "citserver: Can't bind: %s",
389 lprintf(CTDL_EMERG, "%s\n", *errormessage);
393 /* set to nonblock - we need this for some obscure situations */
394 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
395 *errormessage = (char*) malloc(SIZ + 1);
396 snprintf(*errormessage, SIZ,
397 "citserver: Can't set socket to non-blocking: %s",
399 lprintf(CTDL_EMERG, "%s\n", *errormessage);
404 if (listen(s, actual_queue_len) < 0) {
405 *errormessage = (char*) malloc(SIZ + 1);
406 snprintf(*errormessage, SIZ,
407 "citserver: Can't listen: %s",
409 lprintf(CTDL_EMERG, "%s\n", *errormessage);
413 chmod(sockpath, 0777);
420 * Return a pointer to the CitContext structure bound to the thread which
421 * called this function. If there's no such binding (for example, if it's
422 * called by the housekeeper thread) then a generic 'master' CC is returned.
424 * This function is used *VERY* frequently and must be kept small.
426 struct CitContext *MyContext(void) {
428 register struct CitContext *c;
430 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
431 c == NULL) ? &masterCC : c
437 * Initialize a new context and place it in the list. The session number
438 * used to be the PID (which is why it's called cs_pid), but that was when we
439 * had one process per session. Now we just assign them sequentially, starting
440 * at 1 (don't change it to 0 because masterCC uses 0).
442 struct CitContext *CreateNewContext(void) {
443 struct CitContext *me;
444 static int next_pid = 0;
446 me = (struct CitContext *) malloc(sizeof(struct CitContext));
448 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
451 memset(me, 0, sizeof(struct CitContext));
453 /* The new context will be created already in the CON_EXECUTING state
454 * in order to prevent another thread from grabbing it while it's
457 me->state = CON_EXECUTING;
460 * Generate a unique session number and insert this context into
463 begin_critical_section(S_SESSION_TABLE);
464 me->cs_pid = ++next_pid;
466 me->next = ContextList;
468 if (me->next != NULL) {
472 end_critical_section(S_SESSION_TABLE);
478 * The following functions implement output buffering. If the kernel supplies
479 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
480 * user-space buffering.
484 # define HAVE_TCP_BUFFERING
487 # define HAVE_TCP_BUFFERING
488 # define TCP_CORK TCP_NOPUSH
490 #endif /* TCP_CORK */
491 #endif /* HAVE_DARWIN */
493 #ifdef HAVE_TCP_BUFFERING
494 static unsigned on = 1, off = 0;
495 void buffer_output(void) {
496 struct CitContext *ctx = MyContext();
497 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
501 void unbuffer_output(void) {
502 struct CitContext *ctx = MyContext();
503 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
507 void flush_output(void) {
508 struct CitContext *ctx = MyContext();
509 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
510 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
513 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
514 void buffer_output(void) {
517 void unbuffer_output(void) {
520 void flush_output(void) {
523 void buffer_output(void) {
524 if (CC->buffering == 0) {
527 CC->output_buffer = malloc(SIZ);
531 void flush_output(void) {
532 if (CC->buffering == 1) {
533 client_write(CC->output_buffer, CC->buffer_len);
538 void unbuffer_output(void) {
539 if (CC->buffering == 1) {
541 /* We don't call flush_output because we can't. */
542 client_write(CC->output_buffer, CC->buffer_len);
544 free(CC->output_buffer);
545 CC->output_buffer = NULL;
553 * client_write() ... Send binary data to the client.
555 void client_write(char *buf, int nbytes)
557 int bytes_written = 0;
559 #ifndef HAVE_TCP_BUFFERING
560 int old_buffer_len = 0;
563 if (CC->redirect_buffer != NULL) {
564 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
565 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
566 CC->redirect_buffer = realloc(CC->redirect_buffer,
569 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
570 CC->redirect_len += nbytes;
571 CC->redirect_buffer[CC->redirect_len] = 0;
575 #ifndef HAVE_TCP_BUFFERING
576 /* If we're buffering for later, do that now. */
578 old_buffer_len = CC->buffer_len;
579 CC->buffer_len += nbytes;
580 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
581 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
586 /* Ok, at this point we're not buffering. Go ahead and write. */
589 if (CC->redirect_ssl) {
590 client_write_ssl(buf, nbytes);
595 while (bytes_written < nbytes) {
596 retval = write(CC->client_socket, &buf[bytes_written],
597 nbytes - bytes_written);
600 "client_write(%d bytes) failed: %s (%d)\n",
601 nbytes - bytes_written,
602 strerror(errno), errno);
606 bytes_written = bytes_written + retval;
612 * cprintf() ... Send formatted printable data to the client. It is
613 * implemented in terms of client_write() but remains in
614 * sysdep.c in case we port to somewhere without va_args...
616 void cprintf(const char *format, ...) {
620 va_start(arg_ptr, format);
621 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
622 buf[sizeof buf - 2] = '\n';
623 client_write(buf, strlen(buf));
629 * Read data from the client socket.
631 * 1 Requested number of bytes has been read.
632 * 0 Request timed out.
633 * -1 The socket is broken.
634 * If the socket breaks, the session will be terminated.
636 int client_read_to(char *buf, int bytes, int timeout)
644 if (CC->redirect_ssl) {
645 return (client_read_ssl(buf, bytes, timeout));
651 FD_SET(CC->client_socket, &rfds);
655 retval = select( (CC->client_socket)+1,
656 &rfds, NULL, NULL, &tv);
658 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
662 rlen = read(CC->client_socket, &buf[len], bytes-len);
664 /* The socket has been disconnected! */
674 * Read data from the client socket with default timeout.
675 * (This is implemented in terms of client_read_to() and could be
676 * justifiably moved out of sysdep.c)
678 INLINE int client_read(char *buf, int bytes)
680 return(client_read_to(buf, bytes, config.c_sleeping));
685 * client_getln() ... Get a LF-terminated line of text from the client.
686 * (This is implemented in terms of client_read() and could be
687 * justifiably moved out of sysdep.c)
689 int client_getln(char *buf, int bufsize)
693 /* Read one character at a time.
696 retval = client_read(&buf[i], 1);
697 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
701 /* If we got a long line, discard characters until the newline.
703 if (i == (bufsize-1))
704 while (buf[i] != '\n' && retval == 1)
705 retval = client_read(&buf[i], 1);
707 /* Strip the trailing LF, and the trailing CR if present.
710 while ( (strlen(buf) > 0) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
711 buf[strlen(buf)-1] = 0;
713 if (retval < 0) safestrncpy(buf, "000", bufsize);
720 * The system-dependent part of master_cleanup() - close the master socket.
722 void sysdep_master_cleanup(void) {
723 struct ServiceFunctionHook *serviceptr;
725 ///// DestroyWorkerList();
727 * close all protocol master sockets
729 for (serviceptr = ServiceHookTable; serviceptr != NULL;
730 serviceptr = serviceptr->next ) {
732 if (serviceptr->tcp_port > 0)
733 lprintf(CTDL_INFO, "Closing listener on port %d\n",
734 serviceptr->tcp_port);
736 if (serviceptr->sockpath != NULL)
737 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
738 serviceptr->sockpath);
740 close(serviceptr->msock);
742 /* If it's a Unix domain socket, remove the file. */
743 if (serviceptr->sockpath != NULL) {
744 unlink(serviceptr->sockpath);
750 serv_calendar_destroy();
751 CtdlDestroyProtoHooks();
752 CtdlDestroyDeleteHooks();
753 CtdlDestroyXmsgHooks();
754 CtdlDestroyNetprocHooks();
755 CtdlDestroyUserHooks();
756 CtdlDestroyMessageHook();
757 CtdlDestroyCleanupHooks();
758 CtdlDestroyFixedOutputHooks();
759 CtdlDestroySessionHooks();
760 CtdlDestroyServiceHook();
767 * Terminate another session.
768 * (This could justifiably be moved out of sysdep.c because it
769 * no longer does anything that is system-dependent.)
771 void kill_session(int session_to_kill) {
772 struct CitContext *ptr;
774 begin_critical_section(S_SESSION_TABLE);
775 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
776 if (ptr->cs_pid == session_to_kill) {
780 end_critical_section(S_SESSION_TABLE);
784 void graceful_shutdown(int signum) {
785 kill(current_child, signum);
786 unlink(file_pid_file);
792 * Start running as a daemon.
794 void start_daemon(int unused) {
802 /* Close stdin/stdout/stderr and replace them with /dev/null.
803 * We don't just call close() because we don't want these fd's
804 * to be reused for other files.
813 signal(SIGHUP, SIG_IGN);
814 signal(SIGINT, SIG_IGN);
815 signal(SIGQUIT, SIG_IGN);
819 freopen("/dev/null", "r", stdin);
820 freopen("/dev/null", "w", stdout);
821 freopen("/dev/null", "w", stderr);
824 current_child = fork();
826 signal(SIGTERM, graceful_shutdown);
828 if (current_child < 0) {
833 else if (current_child == 0) {
834 return; /* continue starting citadel. */
838 fp = fopen(file_pid_file, "w");
840 fprintf(fp, ""F_PID_T"\n", child);
843 waitpid(current_child, &status, 0);
848 /* Did the main process exit with an actual exit code? */
849 if (WIFEXITED(status)) {
851 /* Exit code 0 means the watcher should exit */
852 if (WEXITSTATUS(status) == 0) {
856 /* Exit code 101-109 means the watcher should exit */
857 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
861 /* Any other exit code means we should restart. */
867 /* Any other type of termination (signals, etc.) should also restart. */
872 } while (do_restart);
874 unlink(file_pid_file);
875 exit(WEXITSTATUS(status));
881 * Generic routine to convert a login name to a full name (gecos)
882 * Returns nonzero if a conversion took place
884 int convert_login(char NameToConvert[]) {
888 pw = getpwnam(NameToConvert);
893 strcpy(NameToConvert, pw->pw_gecos);
894 for (a=0; a<strlen(NameToConvert); ++a) {
895 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
901 struct worker_node *worker_list = NULL;
905 * create a worker thread. this function must always be called from within
906 * an S_WORKER_LIST critical section!
908 void create_worker(void) {
910 struct worker_node *n;
913 n = malloc(sizeof(struct worker_node));
915 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
920 if ((ret = pthread_attr_init(&attr))) {
921 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
926 /* Our per-thread stacks need to be bigger than the default size,
927 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
928 * crashes on 64-bit Linux.
930 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
931 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
934 pthread_attr_destroy(&attr);
938 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
941 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
945 n->next = worker_list;
947 pthread_attr_destroy(&attr);
950 void DestroyWorkerList(void)
952 struct CitContext *ptr; /* general-purpose utility pointer */
953 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
955 begin_critical_section(S_SESSION_TABLE);
958 /* Remove the session from the active list */
962 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
963 end_critical_section(S_SESSION_TABLE);
965 begin_critical_section(S_SESSION_TABLE);
969 end_critical_section(S_SESSION_TABLE);
971 struct worker_node *cur, *p;
983 * Create the indexer thread and begin its operation.
984 * Then create the checkpoint thread and begin its operation.
986 void create_maintenance_threads(void) {
990 if ((ret = pthread_attr_init(&attr))) {
991 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
996 /* Our per-thread stacks need to be bigger than the default size,
997 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
998 * crashes on 64-bit Linux.
1000 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1001 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1004 pthread_attr_destroy(&attr);
1008 if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
1009 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1012 if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
1013 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1016 lprintf(CTDL_NOTICE, "Spawned indexer (%ld) and checkpoint (%ld) thread. \n",
1017 indexer_thread_tid, checkpoint_thread_tid);
1018 pthread_attr_destroy(&attr);
1024 * Purge all sessions which have the 'kill_me' flag set.
1025 * This function has code to prevent it from running more than once every
1026 * few seconds, because running it after every single unbind would waste a lot
1027 * of CPU time and keep the context list locked too much. To force it to run
1028 * anyway, set "force" to nonzero.
1031 * After that's done, we raise the size of the worker thread pool
1032 * if such an action is appropriate.
1034 void dead_session_purge(int force) {
1035 struct CitContext *ptr; /* general-purpose utility pointer */
1036 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1039 if ( (time(NULL) - last_purge) < 5 ) {
1040 return; /* Too soon, go away */
1045 begin_critical_section(S_SESSION_TABLE);
1046 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1047 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1049 /* Remove the session from the active list */
1051 ptr->prev->next = ptr->next;
1054 ContextList = ptr->next;
1057 ptr->next->prev = ptr->prev;
1062 /* And put it on our to-be-destroyed list */
1068 end_critical_section(S_SESSION_TABLE);
1070 /* Now that we no longer have the session list locked, we can take
1071 * our time and destroy any sessions on the to-be-killed list, which
1072 * is allocated privately on this thread's stack.
1074 while (rem != NULL) {
1075 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1082 /* Raise the size of the worker thread pool if necessary. */
1083 if ( (num_sessions > num_threads)
1084 && (num_threads < config.c_max_workers) ) {
1085 begin_critical_section(S_WORKER_LIST);
1087 end_critical_section(S_WORKER_LIST);
1096 * masterCC is the context we use when not attached to a session. This
1097 * function initializes it.
1099 void InitializeMasterCC(void) {
1100 memset(&masterCC, 0, sizeof(struct CitContext));
1101 masterCC.internal_pgm = 1;
1102 masterCC.cs_pid = 0;
1111 * Bind a thread to a context. (It's inline merely to speed things up.)
1113 INLINE void become_session(struct CitContext *which_con) {
1114 pthread_setspecific(MyConKey, (void *)which_con );
1120 * This loop just keeps going and going and going...
1122 void *worker_thread(void *arg) {
1125 struct CitContext *ptr;
1126 struct CitContext *bind_me = NULL;
1129 struct CitContext *con= NULL; /* Temporary context pointer */
1130 struct ServiceFunctionHook *serviceptr;
1131 int ssock; /* Descriptor for client socket */
1133 int force_purge = 0;
1140 while (!time_to_die) {
1142 /* make doubly sure we're not holding any stale db handles
1143 * which might cause a deadlock.
1145 cdb_check_handles();
1146 do_select: force_purge = 0;
1147 bind_me = NULL; /* Which session shall we handle? */
1149 /* Initialize the fdset. */
1153 begin_critical_section(S_SESSION_TABLE);
1154 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1155 if (ptr->state == CON_IDLE) {
1156 FD_SET(ptr->client_socket, &readfds);
1157 if (ptr->client_socket > highest)
1158 highest = ptr->client_socket;
1160 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1162 ptr->state = CON_EXECUTING;
1165 end_critical_section(S_SESSION_TABLE);
1171 /* If we got this far, it means that there are no sessions
1172 * which a previous thread marked for attention, so we go
1173 * ahead and get ready to select().
1176 /* First, add the various master sockets to the fdset. */
1177 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1178 serviceptr = serviceptr->next ) {
1179 m = serviceptr->msock;
1180 FD_SET(m, &readfds);
1187 tv.tv_sec = 1; /* wake up every second if no input */
1189 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1192 if (time_to_die) return(NULL);
1194 /* Now figure out who made this select() unblock.
1195 * First, check for an error or exit condition.
1198 if (errno == EBADF) {
1199 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1203 if (errno != EINTR) {
1204 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1206 } else if (!time_to_die)
1210 /* Next, check to see if it's a new client connecting
1211 * on a master socket.
1213 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1214 serviceptr = serviceptr->next ) {
1216 if (FD_ISSET(serviceptr->msock, &readfds)) {
1217 ssock = accept(serviceptr->msock, NULL, 0);
1220 "New client socket %d\n",
1223 /* The master socket is non-blocking but the client
1224 * sockets need to be blocking, otherwise certain
1225 * operations barf on FreeBSD. Not a fatal error.
1227 if (fcntl(ssock, F_SETFL, 0) < 0) {
1229 "citserver: Can't set socket to blocking: %s\n",
1233 /* New context will be created already
1234 * set up in the CON_EXECUTING state.
1236 con = CreateNewContext();
1238 /* Assign our new socket number to it. */
1239 con->client_socket = ssock;
1240 con->h_command_function =
1241 serviceptr->h_command_function;
1242 con->h_async_function =
1243 serviceptr->h_async_function;
1245 /* Determine whether it's a local socket */
1246 if (serviceptr->sockpath != NULL)
1247 con->is_local_socket = 1;
1249 /* Set the SO_REUSEADDR socket option */
1251 setsockopt(ssock, SOL_SOCKET,
1255 become_session(con);
1257 serviceptr->h_greeting_function();
1258 become_session(NULL);
1259 con->state = CON_IDLE;
1265 /* It must be a client socket. Find a context that has data
1266 * waiting on its socket *and* is in the CON_IDLE state. Any
1267 * active sockets other than our chosen one are marked as
1268 * CON_READY so the next thread that comes around can just bind
1269 * to one without having to select() again.
1271 begin_critical_section(S_SESSION_TABLE);
1272 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1273 if ( (FD_ISSET(ptr->client_socket, &readfds))
1274 && (ptr->state != CON_EXECUTING) ) {
1275 ptr->input_waiting = 1;
1277 bind_me = ptr; /* I choose you! */
1278 bind_me->state = CON_EXECUTING;
1281 ptr->state = CON_READY;
1285 end_critical_section(S_SESSION_TABLE);
1288 /* We're bound to a session */
1289 if (bind_me != NULL) {
1290 become_session(bind_me);
1292 /* If the client has sent a command, execute it. */
1293 if (CC->input_waiting) {
1294 CC->h_command_function();
1295 CC->input_waiting = 0;
1298 /* If there are asynchronous messages waiting and the
1299 * client supports it, do those now */
1300 if ((CC->is_async) && (CC->async_waiting)
1301 && (CC->h_async_function != NULL)) {
1302 CC->h_async_function();
1303 CC->async_waiting = 0;
1306 force_purge = CC->kill_me;
1307 become_session(NULL);
1308 bind_me->state = CON_IDLE;
1311 dead_session_purge(force_purge);
1313 check_sched_shutdown();
1315 if (con != NULL) free (con);//// TODO: could this harm other threads?
1316 /* If control reaches this point, the server is shutting down */
1325 * Translate text facility name to syslog.h defined value.
1327 int SyslogFacility(char *name)
1336 { LOG_KERN, "kern" },
1337 { LOG_USER, "user" },
1338 { LOG_MAIL, "mail" },
1339 { LOG_DAEMON, "daemon" },
1340 { LOG_AUTH, "auth" },
1341 { LOG_SYSLOG, "syslog" },
1343 { LOG_NEWS, "news" },
1344 { LOG_UUCP, "uucp" },
1345 { LOG_LOCAL0, "local0" },
1346 { LOG_LOCAL1, "local1" },
1347 { LOG_LOCAL2, "local2" },
1348 { LOG_LOCAL3, "local3" },
1349 { LOG_LOCAL4, "local4" },
1350 { LOG_LOCAL5, "local5" },
1351 { LOG_LOCAL6, "local6" },
1352 { LOG_LOCAL7, "local7" },
1355 for(i = 0; facTbl[i].name != NULL; i++) {
1356 if(!strcasecmp(name, facTbl[i].name))
1357 return facTbl[i].facility;
1364 /********** MEM CHEQQER ***********/
1366 #ifdef DEBUG_MEMORY_LEAKS
1373 void *tracked_malloc(size_t size, char *file, int line) {
1374 struct igheap *thisheap;
1377 block = malloc(size);
1378 if (block == NULL) return(block);
1380 thisheap = malloc(sizeof(struct igheap));
1381 if (thisheap == NULL) {
1386 thisheap->block = block;
1387 strcpy(thisheap->file, file);
1388 thisheap->line = line;
1390 begin_critical_section(S_DEBUGMEMLEAKS);
1391 thisheap->next = igheap;
1393 end_critical_section(S_DEBUGMEMLEAKS);
1399 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1400 struct igheap *thisheap;
1403 block = realloc(ptr, size);
1404 if (block == NULL) return(block);
1406 thisheap = malloc(sizeof(struct igheap));
1407 if (thisheap == NULL) {
1412 thisheap->block = block;
1413 strcpy(thisheap->file, file);
1414 thisheap->line = line;
1416 begin_critical_section(S_DEBUGMEMLEAKS);
1417 thisheap->next = igheap;
1419 end_critical_section(S_DEBUGMEMLEAKS);
1426 void tracked_free(void *ptr) {
1427 struct igheap *thisheap;
1428 struct igheap *trash;
1432 if (igheap == NULL) return;
1433 begin_critical_section(S_DEBUGMEMLEAKS);
1434 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1435 if (thisheap->next != NULL) {
1436 if (thisheap->next->block == ptr) {
1437 trash = thisheap->next;
1438 thisheap->next = thisheap->next->next;
1443 if (igheap->block == ptr) {
1445 igheap = igheap->next;
1448 end_critical_section(S_DEBUGMEMLEAKS);
1451 char *tracked_strdup(const char *s, char *file, int line) {
1454 if (s == NULL) return(NULL);
1455 ptr = tracked_malloc(strlen(s) + 1, file, line);
1456 if (ptr == NULL) return(NULL);
1457 strncpy(ptr, s, strlen(s));
1461 void dump_heap(void) {
1462 struct igheap *thisheap;
1464 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1465 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1466 thisheap->file, thisheap->line);
1470 #endif /* DEBUG_MEMORY_LEAKS */