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>
26 #include <sys/syslog.h>
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
33 # include <sys/time.h>
40 #include <sys/resource.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
56 #include "serv_extensions.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;
105 * lprintf() ... Write logging information
107 void lprintf(enum LogLevel loglevel, const char *format, ...) {
111 va_start(arg_ptr, format);
112 vsyslog((syslog_facility | loglevel), format, arg_ptr);
116 /* stderr output code */
117 if (enable_syslog || running_as_daemon) return;
119 /* if we run in forground and syslog is disabled, log to terminal */
120 if (loglevel <= verbosity) {
125 gettimeofday(&tv, NULL);
126 /* Promote to time_t; types differ on some OSes (like darwin) */
127 unixtime = tv.tv_sec;
128 localtime_r(&unixtime, &tim);
129 if (CC->cs_pid != 0) {
131 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
132 tim.tm_year + 1900, tim.tm_mon + 1,
133 tim.tm_mday, tim.tm_hour, tim.tm_min,
134 tim.tm_sec, (long)tv.tv_usec,
138 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
139 tim.tm_year + 1900, tim.tm_mon + 1,
140 tim.tm_mday, tim.tm_hour, tim.tm_min,
141 tim.tm_sec, (long)tv.tv_usec);
143 va_start(arg_ptr, format);
144 vfprintf(stderr, format, arg_ptr);
153 * Signal handler to shut down the server.
156 volatile int time_to_die = 0;
157 volatile int shutdown_and_halt = 0;
159 static RETSIGTYPE signal_cleanup(int signum) {
160 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
162 master_cleanup(signum);
167 * Some initialization stuff...
169 void init_sysdep(void) {
173 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
177 getrlimit(RLIMIT_NOFILE, &rl);
178 rl.rlim_cur = FD_SETSIZE;
179 rl.rlim_max = FD_SETSIZE;
180 setrlimit(RLIMIT_NOFILE, &rl);
184 /* If we've got OpenSSL, we're going to use it. */
189 /* Set up a bunch of semaphores to be used for critical sections */
190 for (i=0; i<MAX_SEMAPHORES; ++i) {
191 pthread_mutex_init(&Critters[i], NULL);
195 * Set up a place to put thread-specific data.
196 * We only need a single pointer per thread - it points to the
197 * CitContext structure (in the ContextList linked list) of the
198 * session to which the calling thread is currently bound.
200 if (pthread_key_create(&MyConKey, NULL) != 0) {
201 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
206 * The action for unexpected signals and exceptions should be to
207 * call signal_cleanup() to gracefully shut down the server.
210 sigaddset(&set, SIGINT);
211 sigaddset(&set, SIGQUIT);
212 sigaddset(&set, SIGHUP);
213 sigaddset(&set, SIGTERM);
214 // sigaddset(&set, SIGSEGV); commented out because
215 // sigaddset(&set, SIGILL); we want core dumps
216 // sigaddset(&set, SIGBUS);
217 sigprocmask(SIG_UNBLOCK, &set, NULL);
219 signal(SIGINT, signal_cleanup);
220 signal(SIGQUIT, signal_cleanup);
221 signal(SIGHUP, signal_cleanup);
222 signal(SIGTERM, signal_cleanup);
223 // signal(SIGSEGV, signal_cleanup); commented out because
224 // signal(SIGILL, signal_cleanup); we want core dumps
225 // signal(SIGBUS, signal_cleanup);
228 * Do not shut down the server on broken pipe signals, otherwise the
229 * whole Citadel service would come down whenever a single client
232 signal(SIGPIPE, SIG_IGN);
237 * Obtain a semaphore lock to begin a critical section.
239 void begin_critical_section(int which_one)
241 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
243 /* For all types of critical sections except those listed here,
244 * ensure nobody ever tries to do a critical section within a
245 * transaction; this could lead to deadlock.
247 if ( (which_one != S_FLOORCACHE)
248 #ifdef DEBUG_MEMORY_LEAKS
249 && (which_one != S_DEBUGMEMLEAKS)
251 && (which_one != S_RPLIST)
255 pthread_mutex_lock(&Critters[which_one]);
259 * Release a semaphore lock to end a critical section.
261 void end_critical_section(int which_one)
263 pthread_mutex_unlock(&Critters[which_one]);
269 * This is a generic function to set up a master socket for listening on
270 * a TCP port. The server shuts down if the bind fails.
273 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
275 struct sockaddr_in sin;
277 int actual_queue_len;
279 actual_queue_len = queue_len;
280 if (actual_queue_len < 5) actual_queue_len = 5;
282 memset(&sin, 0, sizeof(sin));
283 sin.sin_family = AF_INET;
284 sin.sin_port = htons((u_short)port_number);
285 if (ip_addr == NULL) {
286 sin.sin_addr.s_addr = INADDR_ANY;
289 sin.sin_addr.s_addr = inet_addr(ip_addr);
292 if (sin.sin_addr.s_addr == INADDR_NONE) {
293 sin.sin_addr.s_addr = INADDR_ANY;
296 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
299 *errormessage = (char*) malloc(SIZ + 1);
300 snprintf(*errormessage, SIZ,
301 "citserver: Can't create a socket: %s",
303 lprintf(CTDL_EMERG, "%s\n", *errormessage);
308 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
310 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
311 *errormessage = (char*) malloc(SIZ + 1);
312 snprintf(*errormessage, SIZ,
313 "citserver: Can't bind: %s",
315 lprintf(CTDL_EMERG, "%s\n", *errormessage);
320 /* set to nonblock - we need this for some obscure situations */
321 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
322 *errormessage = (char*) malloc(SIZ + 1);
323 snprintf(*errormessage, SIZ,
324 "citserver: Can't set socket to non-blocking: %s",
326 lprintf(CTDL_EMERG, "%s\n", *errormessage);
331 if (listen(s, actual_queue_len) < 0) {
332 *errormessage = (char*) malloc(SIZ + 1);
333 snprintf(*errormessage, SIZ,
334 "citserver: Can't listen: %s",
336 lprintf(CTDL_EMERG, "%s\n", *errormessage);
347 * Create a Unix domain socket and listen on it
349 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
351 struct sockaddr_un addr;
354 int actual_queue_len;
356 actual_queue_len = queue_len;
357 if (actual_queue_len < 5) actual_queue_len = 5;
359 i = unlink(sockpath);
360 if (i != 0) if (errno != ENOENT) {
361 *errormessage = (char*) malloc(SIZ + 1);
362 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
363 sockpath, strerror(errno));
364 lprintf(CTDL_EMERG, "%s\n", *errormessage);
368 memset(&addr, 0, sizeof(addr));
369 addr.sun_family = AF_UNIX;
370 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
372 s = socket(AF_UNIX, SOCK_STREAM, 0);
374 *errormessage = (char*) malloc(SIZ + 1);
375 snprintf(*errormessage, SIZ,
376 "citserver: Can't create a socket: %s",
378 lprintf(CTDL_EMERG, "%s\n", *errormessage);
382 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
383 *errormessage = (char*) malloc(SIZ + 1);
384 snprintf(*errormessage, SIZ,
385 "citserver: Can't bind: %s",
387 lprintf(CTDL_EMERG, "%s\n", *errormessage);
391 /* set to nonblock - we need this for some obscure situations */
392 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
393 *errormessage = (char*) malloc(SIZ + 1);
394 snprintf(*errormessage, SIZ,
395 "citserver: Can't set socket to non-blocking: %s",
397 lprintf(CTDL_EMERG, "%s\n", *errormessage);
402 if (listen(s, actual_queue_len) < 0) {
403 *errormessage = (char*) malloc(SIZ + 1);
404 snprintf(*errormessage, SIZ,
405 "citserver: Can't listen: %s",
407 lprintf(CTDL_EMERG, "%s\n", *errormessage);
411 chmod(sockpath, 0777);
418 * Return a pointer to the CitContext structure bound to the thread which
419 * called this function. If there's no such binding (for example, if it's
420 * called by the housekeeper thread) then a generic 'master' CC is returned.
422 * This function is used *VERY* frequently and must be kept small.
424 struct CitContext *MyContext(void) {
426 register struct CitContext *c;
428 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
429 c == NULL) ? &masterCC : c
435 * Initialize a new context and place it in the list. The session number
436 * used to be the PID (which is why it's called cs_pid), but that was when we
437 * had one process per session. Now we just assign them sequentially, starting
438 * at 1 (don't change it to 0 because masterCC uses 0).
440 struct CitContext *CreateNewContext(void) {
441 struct CitContext *me;
442 static int next_pid = 0;
444 me = (struct CitContext *) malloc(sizeof(struct CitContext));
446 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
449 memset(me, 0, sizeof(struct CitContext));
451 /* The new context will be created already in the CON_EXECUTING state
452 * in order to prevent another thread from grabbing it while it's
455 me->state = CON_EXECUTING;
458 * Generate a unique session number and insert this context into
461 begin_critical_section(S_SESSION_TABLE);
462 me->cs_pid = ++next_pid;
464 me->next = ContextList;
466 if (me->next != NULL) {
470 end_critical_section(S_SESSION_TABLE);
476 * The following functions implement output buffering. If the kernel supplies
477 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
478 * user-space buffering.
481 # define HAVE_TCP_BUFFERING
484 # define HAVE_TCP_BUFFERING
485 # define TCP_CORK TCP_NOPUSH
490 #ifdef HAVE_TCP_BUFFERING
491 static unsigned on = 1, off = 0;
492 void buffer_output(void) {
493 struct CitContext *ctx = MyContext();
494 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
498 void unbuffer_output(void) {
499 struct CitContext *ctx = MyContext();
500 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
504 void flush_output(void) {
505 struct CitContext *ctx = MyContext();
506 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
507 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
510 void buffer_output(void) {
511 if (CC->buffering == 0) {
514 CC->output_buffer = malloc(SIZ);
518 void flush_output(void) {
519 if (CC->buffering == 1) {
520 client_write(CC->output_buffer, CC->buffer_len);
525 void unbuffer_output(void) {
526 if (CC->buffering == 1) {
528 /* We don't call flush_output because we can't. */
529 client_write(CC->output_buffer, CC->buffer_len);
531 free(CC->output_buffer);
532 CC->output_buffer = NULL;
540 * client_write() ... Send binary data to the client.
542 void client_write(char *buf, int nbytes)
544 int bytes_written = 0;
546 #ifndef HAVE_TCP_BUFFERING
547 int old_buffer_len = 0;
550 if (CC->redirect_buffer != NULL) {
551 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
552 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
553 CC->redirect_buffer = realloc(CC->redirect_buffer,
556 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
557 CC->redirect_len += nbytes;
558 CC->redirect_buffer[CC->redirect_len] = 0;
562 #ifndef HAVE_TCP_BUFFERING
563 /* If we're buffering for later, do that now. */
565 old_buffer_len = CC->buffer_len;
566 CC->buffer_len += nbytes;
567 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
568 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
573 /* Ok, at this point we're not buffering. Go ahead and write. */
576 if (CC->redirect_ssl) {
577 client_write_ssl(buf, nbytes);
582 while (bytes_written < nbytes) {
583 retval = write(CC->client_socket, &buf[bytes_written],
584 nbytes - bytes_written);
587 "client_write(%d bytes) failed: %s (%d)\n",
588 nbytes - bytes_written,
589 strerror(errno), errno);
593 bytes_written = bytes_written + retval;
599 * cprintf() ... Send formatted printable data to the client. It is
600 * implemented in terms of client_write() but remains in
601 * sysdep.c in case we port to somewhere without va_args...
603 void cprintf(const char *format, ...) {
607 va_start(arg_ptr, format);
608 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
609 buf[sizeof buf - 2] = '\n';
610 client_write(buf, strlen(buf));
616 * Read data from the client socket.
618 * 1 Requested number of bytes has been read.
619 * 0 Request timed out.
620 * -1 The socket is broken.
621 * If the socket breaks, the session will be terminated.
623 int client_read_to(char *buf, int bytes, int timeout)
631 if (CC->redirect_ssl) {
632 return (client_read_ssl(buf, bytes, timeout));
638 FD_SET(CC->client_socket, &rfds);
642 retval = select( (CC->client_socket)+1,
643 &rfds, NULL, NULL, &tv);
645 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
649 rlen = read(CC->client_socket, &buf[len], bytes-len);
651 /* The socket has been disconnected! */
661 * Read data from the client socket with default timeout.
662 * (This is implemented in terms of client_read_to() and could be
663 * justifiably moved out of sysdep.c)
665 INLINE int client_read(char *buf, int bytes)
667 return(client_read_to(buf, bytes, config.c_sleeping));
672 * client_getln() ... Get a LF-terminated line of text from the client.
673 * (This is implemented in terms of client_read() and could be
674 * justifiably moved out of sysdep.c)
676 int client_getln(char *buf, int bufsize)
680 /* Read one character at a time.
683 retval = client_read(&buf[i], 1);
684 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
688 /* If we got a long line, discard characters until the newline.
690 if (i == (bufsize-1))
691 while (buf[i] != '\n' && retval == 1)
692 retval = client_read(&buf[i], 1);
694 /* Strip the trailing LF, and the trailing CR if present.
697 while ( (strlen(buf) > 0) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
698 buf[strlen(buf)-1] = 0;
700 if (retval < 0) safestrncpy(buf, "000", bufsize);
707 * The system-dependent part of master_cleanup() - close the master socket.
709 void sysdep_master_cleanup(void) {
710 struct ServiceFunctionHook *serviceptr;
713 * close all protocol master sockets
715 for (serviceptr = ServiceHookTable; serviceptr != NULL;
716 serviceptr = serviceptr->next ) {
718 if (serviceptr->tcp_port > 0)
719 lprintf(CTDL_INFO, "Closing listener on port %d\n",
720 serviceptr->tcp_port);
722 if (serviceptr->sockpath != NULL)
723 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
724 serviceptr->sockpath);
726 close(serviceptr->msock);
728 /* If it's a Unix domain socket, remove the file. */
729 if (serviceptr->sockpath != NULL) {
730 unlink(serviceptr->sockpath);
737 * Terminate another session.
738 * (This could justifiably be moved out of sysdep.c because it
739 * no longer does anything that is system-dependent.)
741 void kill_session(int session_to_kill) {
742 struct CitContext *ptr;
744 begin_critical_section(S_SESSION_TABLE);
745 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
746 if (ptr->cs_pid == session_to_kill) {
750 end_critical_section(S_SESSION_TABLE);
757 * Start running as a daemon.
759 void start_daemon(int unused) {
762 /* Close stdin/stdout/stderr and replace them with /dev/null.
763 * We don't just call close() because we don't want these fd's
764 * to be reused for other files.
766 nullfd = open("/dev/null", O_RDWR);
768 fprintf(stderr, "/dev/null: %s\n", strerror(errno));
778 signal(SIGHUP,SIG_IGN);
779 signal(SIGINT,SIG_IGN);
780 signal(SIGQUIT,SIG_IGN);
786 * Generic routine to convert a login name to a full name (gecos)
787 * Returns nonzero if a conversion took place
789 int convert_login(char NameToConvert[]) {
793 pw = getpwnam(NameToConvert);
798 strcpy(NameToConvert, pw->pw_gecos);
799 for (a=0; a<strlen(NameToConvert); ++a) {
800 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
806 struct worker_node *worker_list = NULL;
810 * create a worker thread. this function must always be called from within
811 * an S_WORKER_LIST critical section!
813 void create_worker(void) {
815 struct worker_node *n;
818 n = malloc(sizeof(struct worker_node));
820 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
825 if ((ret = pthread_attr_init(&attr))) {
826 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
831 /* Our per-thread stacks need to be bigger than the default size,
832 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
833 * crashes on 64-bit Linux.
835 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
836 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
839 pthread_attr_destroy(&attr);
843 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
846 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
850 n->next = worker_list;
852 pthread_attr_destroy(&attr);
857 * Create the indexer thread and begin its operation.
858 * Then create the checkpoint thread and begin its operation.
860 void create_maintenance_threads(void) {
864 if ((ret = pthread_attr_init(&attr))) {
865 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
870 /* Our per-thread stacks need to be bigger than the default size,
871 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
872 * crashes on 64-bit Linux.
874 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
875 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
878 pthread_attr_destroy(&attr);
882 if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
883 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
886 if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
887 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
890 pthread_attr_destroy(&attr);
896 * Purge all sessions which have the 'kill_me' flag set.
897 * This function has code to prevent it from running more than once every
898 * few seconds, because running it after every single unbind would waste a lot
899 * of CPU time and keep the context list locked too much. To force it to run
900 * anyway, set "force" to nonzero.
903 * After that's done, we raise the size of the worker thread pool
904 * if such an action is appropriate.
906 void dead_session_purge(int force) {
907 struct CitContext *ptr; /* general-purpose utility pointer */
908 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
911 if ( (time(NULL) - last_purge) < 5 ) {
912 return; /* Too soon, go away */
917 begin_critical_section(S_SESSION_TABLE);
918 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
919 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
921 /* Remove the session from the active list */
923 ptr->prev->next = ptr->next;
926 ContextList = ptr->next;
929 ptr->next->prev = ptr->prev;
934 /* And put it on our to-be-destroyed list */
940 end_critical_section(S_SESSION_TABLE);
942 /* Now that we no longer have the session list locked, we can take
943 * our time and destroy any sessions on the to-be-killed list, which
944 * is allocated privately on this thread's stack.
946 while (rem != NULL) {
947 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
954 /* Raise the size of the worker thread pool if necessary. */
955 if ( (num_sessions > num_threads)
956 && (num_threads < config.c_max_workers) ) {
957 begin_critical_section(S_WORKER_LIST);
959 end_critical_section(S_WORKER_LIST);
968 * masterCC is the context we use when not attached to a session. This
969 * function initializes it.
971 void InitializeMasterCC(void) {
972 memset(&masterCC, 0, sizeof(struct CitContext));
973 masterCC.internal_pgm = 1;
983 * Bind a thread to a context. (It's inline merely to speed things up.)
985 INLINE void become_session(struct CitContext *which_con) {
986 pthread_setspecific(MyConKey, (void *)which_con );
992 * This loop just keeps going and going and going...
994 void *worker_thread(void *arg) {
997 struct CitContext *ptr;
998 struct CitContext *bind_me = NULL;
1001 struct CitContext *con= NULL; /* Temporary context pointer */
1002 struct ServiceFunctionHook *serviceptr;
1003 int ssock; /* Descriptor for client socket */
1005 int force_purge = 0;
1012 while (!time_to_die) {
1014 /* make doubly sure we're not holding any stale db handles
1015 * which might cause a deadlock.
1017 cdb_check_handles();
1018 do_select: force_purge = 0;
1019 bind_me = NULL; /* Which session shall we handle? */
1021 /* Initialize the fdset. */
1025 begin_critical_section(S_SESSION_TABLE);
1026 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1027 if (ptr->state == CON_IDLE) {
1028 FD_SET(ptr->client_socket, &readfds);
1029 if (ptr->client_socket > highest)
1030 highest = ptr->client_socket;
1032 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1034 ptr->state = CON_EXECUTING;
1037 end_critical_section(S_SESSION_TABLE);
1043 /* If we got this far, it means that there are no sessions
1044 * which a previous thread marked for attention, so we go
1045 * ahead and get ready to select().
1048 /* First, add the various master sockets to the fdset. */
1049 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1050 serviceptr = serviceptr->next ) {
1051 m = serviceptr->msock;
1052 FD_SET(m, &readfds);
1059 tv.tv_sec = 1; /* wake up every second if no input */
1061 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1064 if (time_to_die) return(NULL);
1066 /* Now figure out who made this select() unblock.
1067 * First, check for an error or exit condition.
1070 if (errno == EBADF) {
1071 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1075 if (errno != EINTR) {
1076 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1078 } else if (!time_to_die)
1082 /* Next, check to see if it's a new client connecting
1083 * on a master socket.
1085 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1086 serviceptr = serviceptr->next ) {
1088 if (FD_ISSET(serviceptr->msock, &readfds)) {
1089 ssock = accept(serviceptr->msock, NULL, 0);
1092 "New client socket %d\n",
1095 /* The master socket is non-blocking but the client
1096 * sockets need to be blocking, otherwise certain
1097 * operations barf on FreeBSD. Not a fatal error.
1099 if (fcntl(ssock, F_SETFL, 0) < 0) {
1101 "citserver: Can't set socket to blocking: %s\n",
1105 /* New context will be created already
1106 * set up in the CON_EXECUTING state.
1108 con = CreateNewContext();
1110 /* Assign our new socket number to it. */
1111 con->client_socket = ssock;
1112 con->h_command_function =
1113 serviceptr->h_command_function;
1114 con->h_async_function =
1115 serviceptr->h_async_function;
1117 /* Determine whether it's a local socket */
1118 if (serviceptr->sockpath != NULL)
1119 con->is_local_socket = 1;
1121 /* Set the SO_REUSEADDR socket option */
1123 setsockopt(ssock, SOL_SOCKET,
1127 become_session(con);
1129 serviceptr->h_greeting_function();
1130 become_session(NULL);
1131 con->state = CON_IDLE;
1137 /* It must be a client socket. Find a context that has data
1138 * waiting on its socket *and* is in the CON_IDLE state. Any
1139 * active sockets other than our chosen one are marked as
1140 * CON_READY so the next thread that comes around can just bind
1141 * to one without having to select() again.
1143 begin_critical_section(S_SESSION_TABLE);
1144 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1145 if ( (FD_ISSET(ptr->client_socket, &readfds))
1146 && (ptr->state != CON_EXECUTING) ) {
1147 ptr->input_waiting = 1;
1149 bind_me = ptr; /* I choose you! */
1150 bind_me->state = CON_EXECUTING;
1153 ptr->state = CON_READY;
1157 end_critical_section(S_SESSION_TABLE);
1160 /* We're bound to a session */
1161 if (bind_me != NULL) {
1162 become_session(bind_me);
1164 /* If the client has sent a command, execute it. */
1165 if (CC->input_waiting) {
1166 CC->h_command_function();
1167 CC->input_waiting = 0;
1170 /* If there are asynchronous messages waiting and the
1171 * client supports it, do those now */
1172 if ((CC->is_async) && (CC->async_waiting)
1173 && (CC->h_async_function != NULL)) {
1174 CC->h_async_function();
1175 CC->async_waiting = 0;
1178 force_purge = CC->kill_me;
1179 become_session(NULL);
1180 bind_me->state = CON_IDLE;
1183 dead_session_purge(force_purge);
1185 check_sched_shutdown();
1188 /* If control reaches this point, the server is shutting down */
1197 * Translate text facility name to syslog.h defined value.
1199 int SyslogFacility(char *name)
1208 { LOG_KERN, "kern" },
1209 { LOG_USER, "user" },
1210 { LOG_MAIL, "mail" },
1211 { LOG_DAEMON, "daemon" },
1212 { LOG_AUTH, "auth" },
1213 { LOG_SYSLOG, "syslog" },
1215 { LOG_NEWS, "news" },
1216 { LOG_UUCP, "uucp" },
1217 { LOG_LOCAL0, "local0" },
1218 { LOG_LOCAL1, "local1" },
1219 { LOG_LOCAL2, "local2" },
1220 { LOG_LOCAL3, "local3" },
1221 { LOG_LOCAL4, "local4" },
1222 { LOG_LOCAL5, "local5" },
1223 { LOG_LOCAL6, "local6" },
1224 { LOG_LOCAL7, "local7" },
1227 for(i = 0; facTbl[i].name != NULL; i++) {
1228 if(!strcasecmp(name, facTbl[i].name))
1229 return facTbl[i].facility;
1236 /********** MEM CHEQQER ***********/
1238 #ifdef DEBUG_MEMORY_LEAKS
1245 void *tracked_malloc(size_t size, char *file, int line) {
1246 struct igheap *thisheap;
1249 block = malloc(size);
1250 if (block == NULL) return(block);
1252 thisheap = malloc(sizeof(struct igheap));
1253 if (thisheap == NULL) {
1258 thisheap->block = block;
1259 strcpy(thisheap->file, file);
1260 thisheap->line = line;
1262 begin_critical_section(S_DEBUGMEMLEAKS);
1263 thisheap->next = igheap;
1265 end_critical_section(S_DEBUGMEMLEAKS);
1271 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1272 struct igheap *thisheap;
1275 block = realloc(ptr, size);
1276 if (block == NULL) return(block);
1278 thisheap = malloc(sizeof(struct igheap));
1279 if (thisheap == NULL) {
1284 thisheap->block = block;
1285 strcpy(thisheap->file, file);
1286 thisheap->line = line;
1288 begin_critical_section(S_DEBUGMEMLEAKS);
1289 thisheap->next = igheap;
1291 end_critical_section(S_DEBUGMEMLEAKS);
1298 void tracked_free(void *ptr) {
1299 struct igheap *thisheap;
1300 struct igheap *trash;
1304 if (igheap == NULL) return;
1305 begin_critical_section(S_DEBUGMEMLEAKS);
1306 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1307 if (thisheap->next != NULL) {
1308 if (thisheap->next->block == ptr) {
1309 trash = thisheap->next;
1310 thisheap->next = thisheap->next->next;
1315 if (igheap->block == ptr) {
1317 igheap = igheap->next;
1320 end_critical_section(S_DEBUGMEMLEAKS);
1323 char *tracked_strdup(const char *s, char *file, int line) {
1326 if (s == NULL) return(NULL);
1327 ptr = tracked_malloc(strlen(s) + 1, file, line);
1328 if (ptr == NULL) return(NULL);
1329 strncpy(ptr, s, strlen(s));
1333 void dump_heap(void) {
1334 struct igheap *thisheap;
1336 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1337 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1338 thisheap->file, thisheap->line);
1342 #endif /* DEBUG_MEMORY_LEAKS */