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.
26 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/syslog.h>
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
37 # include <sys/time.h>
44 #include <sys/resource.h>
45 #include <netinet/in.h>
46 #include <netinet/tcp.h>
47 #include <arpa/inet.h>
60 #include "serv_extensions.h"
61 #include "sysdep_decls.h"
62 #include "citserver.h"
66 #include "housekeeping.h"
68 #include "serv_crypto.h"
69 #include "serv_fulltext.h"
71 #ifdef HAVE_SYS_SELECT_H
72 #include <sys/select.h>
80 #ifdef DEBUG_MEMORY_LEAKS
88 struct igheap *igheap = NULL;
92 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
93 pthread_key_t MyConKey; /* TSD key for MyContext() */
95 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
97 struct CitContext masterCC;
98 time_t last_purge = 0; /* Last dead session purge */
99 static int num_threads = 0; /* Current number of threads */
100 int num_sessions = 0; /* Current number of sessions */
101 pthread_t indexer_thread_tid;
103 int syslog_facility = (-1);
104 int enable_syslog = 0;
105 extern int running_as_daemon;
108 * lprintf() ... Write logging information
110 void lprintf(enum LogLevel loglevel, const char *format, ...) {
114 va_start(arg_ptr, format);
115 vsyslog(loglevel, format, arg_ptr);
119 /* stderr output code */
120 if (enable_syslog || running_as_daemon) return;
122 /* if we run in forground and syslog is disabled, log to terminal */
123 if (loglevel <= verbosity) {
128 gettimeofday(&tv, NULL);
129 /* Promote to time_t; types differ on some OSes (like darwin) */
130 unixtime = tv.tv_sec;
131 localtime_r(&unixtime, &tim);
132 if (CC->cs_pid != 0) {
134 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
135 tim.tm_year + 1900, tim.tm_mon + 1,
136 tim.tm_mday, tim.tm_hour, tim.tm_min,
137 tim.tm_sec, (long)tv.tv_usec,
141 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
142 tim.tm_year + 1900, tim.tm_mon + 1,
143 tim.tm_mday, tim.tm_hour, tim.tm_min,
144 tim.tm_sec, (long)tv.tv_usec);
146 va_start(arg_ptr, format);
147 vfprintf(stderr, format, arg_ptr);
156 * Signal handler to shut down the server.
159 volatile int time_to_die = 0;
161 static RETSIGTYPE signal_cleanup(int signum) {
162 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
164 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)
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)
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_NONE) {
294 sin.sin_addr.s_addr = INADDR_ANY;
297 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
300 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
306 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
308 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
309 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
315 /* set to nonblock - we need this for some obscure situations */
316 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
318 "citserver: Can't set socket to non-blocking: %s\n",
324 if (listen(s, actual_queue_len) < 0) {
325 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
337 * Create a Unix domain socket and listen on it
339 int ig_uds_server(char *sockpath, int queue_len)
341 struct sockaddr_un addr;
344 int actual_queue_len;
346 actual_queue_len = queue_len;
347 if (actual_queue_len < 5) actual_queue_len = 5;
349 i = unlink(sockpath);
350 if (i != 0) if (errno != ENOENT) {
351 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
352 sockpath, strerror(errno));
356 memset(&addr, 0, sizeof(addr));
357 addr.sun_family = AF_UNIX;
358 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
360 s = socket(AF_UNIX, SOCK_STREAM, 0);
362 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
367 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
368 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
373 /* set to nonblock - we need this for some obscure situations */
374 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
376 "citserver: Can't set socket to non-blocking: %s\n",
382 if (listen(s, actual_queue_len) < 0) {
383 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
388 chmod(sockpath, 0777);
395 * Return a pointer to the CitContext structure bound to the thread which
396 * called this function. If there's no such binding (for example, if it's
397 * called by the housekeeper thread) then a generic 'master' CC is returned.
399 * This function is used *VERY* frequently and must be kept small.
401 struct CitContext *MyContext(void) {
403 register struct CitContext *c;
405 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
406 c == NULL) ? &masterCC : c
412 * Initialize a new context and place it in the list. The session number
413 * used to be the PID (which is why it's called cs_pid), but that was when we
414 * had one process per session. Now we just assign them sequentially, starting
415 * at 1 (don't change it to 0 because masterCC uses 0).
417 struct CitContext *CreateNewContext(void) {
418 struct CitContext *me;
419 static int next_pid = 0;
421 me = (struct CitContext *) malloc(sizeof(struct CitContext));
423 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
426 memset(me, 0, sizeof(struct CitContext));
428 /* The new context will be created already in the CON_EXECUTING state
429 * in order to prevent another thread from grabbing it while it's
432 me->state = CON_EXECUTING;
435 * Generate a unique session number and insert this context into
438 begin_critical_section(S_SESSION_TABLE);
439 me->cs_pid = ++next_pid;
441 me->next = ContextList;
443 if (me->next != NULL) {
447 end_critical_section(S_SESSION_TABLE);
453 * The following functions implement output buffering. If the kernel supplies
454 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
455 * user-space buffering.
458 # define HAVE_TCP_BUFFERING
461 # define HAVE_TCP_BUFFERING
462 # define TCP_CORK TCP_NOPUSH
467 #ifdef HAVE_TCP_BUFFERING
468 static unsigned on = 1, off = 0;
469 void buffer_output(void) {
470 struct CitContext *ctx = MyContext();
471 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
475 void unbuffer_output(void) {
476 struct CitContext *ctx = MyContext();
477 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
481 void flush_output(void) {
482 struct CitContext *ctx = MyContext();
483 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
484 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
487 void buffer_output(void) {
488 if (CC->buffering == 0) {
491 CC->output_buffer = malloc(SIZ);
495 void flush_output(void) {
496 if (CC->buffering == 1) {
497 client_write(CC->output_buffer, CC->buffer_len);
502 void unbuffer_output(void) {
503 if (CC->buffering == 1) {
505 /* We don't call flush_output because we can't. */
506 client_write(CC->output_buffer, CC->buffer_len);
508 free(CC->output_buffer);
509 CC->output_buffer = NULL;
517 * client_write() ... Send binary data to the client.
519 void client_write(char *buf, int nbytes)
521 int bytes_written = 0;
523 #ifndef HAVE_TCP_BUFFERING
524 int old_buffer_len = 0;
527 if (CC->redirect_buffer != NULL) {
528 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
529 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
530 CC->redirect_buffer = realloc(CC->redirect_buffer,
533 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
534 CC->redirect_len += nbytes;
535 CC->redirect_buffer[CC->redirect_len] = 0;
539 #ifndef HAVE_TCP_BUFFERING
540 /* If we're buffering for later, do that now. */
542 old_buffer_len = CC->buffer_len;
543 CC->buffer_len += nbytes;
544 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
545 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
550 /* Ok, at this point we're not buffering. Go ahead and write. */
553 if (CC->redirect_ssl) {
554 client_write_ssl(buf, nbytes);
559 while (bytes_written < nbytes) {
560 retval = write(CC->client_socket, &buf[bytes_written],
561 nbytes - bytes_written);
563 lprintf(CTDL_ERR, "client_write() failed: %s\n",
568 bytes_written = bytes_written + retval;
574 * cprintf() ... Send formatted printable data to the client. It is
575 * implemented in terms of client_write() but remains in
576 * sysdep.c in case we port to somewhere without va_args...
578 void cprintf(const char *format, ...) {
582 va_start(arg_ptr, format);
583 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
584 buf[sizeof buf - 2] = '\n';
585 client_write(buf, strlen(buf));
591 * Read data from the client socket.
593 * 1 Requested number of bytes has been read.
594 * 0 Request timed out.
595 * -1 The socket is broken.
596 * If the socket breaks, the session will be terminated.
598 int client_read_to(char *buf, int bytes, int timeout)
606 if (CC->redirect_ssl) {
607 return (client_read_ssl(buf, bytes, timeout));
613 FD_SET(CC->client_socket, &rfds);
617 retval = select( (CC->client_socket)+1,
618 &rfds, NULL, NULL, &tv);
620 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
624 rlen = read(CC->client_socket, &buf[len], bytes-len);
626 lprintf(CTDL_ERR, "client_read() failed: %s\n",
637 * Read data from the client socket with default timeout.
638 * (This is implemented in terms of client_read_to() and could be
639 * justifiably moved out of sysdep.c)
641 INLINE int client_read(char *buf, int bytes)
643 return(client_read_to(buf, bytes, config.c_sleeping));
648 * client_getln() ... Get a LF-terminated line of text from the client.
649 * (This is implemented in terms of client_read() and could be
650 * justifiably moved out of sysdep.c)
652 int client_getln(char *buf, int bufsize)
656 /* Read one character at a time.
659 retval = client_read(&buf[i], 1);
660 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
664 /* If we got a long line, discard characters until the newline.
666 if (i == (bufsize-1))
667 while (buf[i] != '\n' && retval == 1)
668 retval = client_read(&buf[i], 1);
670 /* Strip the trailing newline and any trailing nonprintables (cr's)
673 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
674 buf[strlen(buf)-1] = 0;
675 if (retval < 0) safestrncpy(buf, "000", bufsize);
682 * The system-dependent part of master_cleanup() - close the master socket.
684 void sysdep_master_cleanup(void) {
685 struct ServiceFunctionHook *serviceptr;
688 * close all protocol master sockets
690 for (serviceptr = ServiceHookTable; serviceptr != NULL;
691 serviceptr = serviceptr->next ) {
693 if (serviceptr->tcp_port > 0)
694 lprintf(CTDL_INFO, "Closing listener on port %d\n",
695 serviceptr->tcp_port);
697 if (serviceptr->sockpath != NULL)
698 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
699 serviceptr->sockpath);
701 close(serviceptr->msock);
703 /* If it's a Unix domain socket, remove the file. */
704 if (serviceptr->sockpath != NULL) {
705 unlink(serviceptr->sockpath);
712 * Terminate another session.
713 * (This could justifiably be moved out of sysdep.c because it
714 * no longer does anything that is system-dependent.)
716 void kill_session(int session_to_kill) {
717 struct CitContext *ptr;
719 begin_critical_section(S_SESSION_TABLE);
720 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
721 if (ptr->cs_pid == session_to_kill) {
725 end_critical_section(S_SESSION_TABLE);
732 * Start running as a daemon.
734 void start_daemon(int unused) {
735 close(0); close(1); close(2);
738 signal(SIGHUP,SIG_IGN);
739 signal(SIGINT,SIG_IGN);
740 signal(SIGQUIT,SIG_IGN);
746 * Generic routine to convert a login name to a full name (gecos)
747 * Returns nonzero if a conversion took place
749 int convert_login(char NameToConvert[]) {
753 pw = getpwnam(NameToConvert);
758 strcpy(NameToConvert, pw->pw_gecos);
759 for (a=0; a<strlen(NameToConvert); ++a) {
760 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
766 struct worker_node *worker_list = NULL;
770 * create a worker thread. this function must always be called from within
771 * an S_WORKER_LIST critical section!
773 void create_worker(void) {
775 struct worker_node *n;
778 n = malloc(sizeof(struct worker_node));
780 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
785 if ((ret = pthread_attr_init(&attr))) {
786 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
791 /* Our per-thread stacks need to be bigger than the default size,
792 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
793 * crashes on 64-bit Linux.
795 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
796 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
799 pthread_attr_destroy(&attr);
803 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
806 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
810 n->next = worker_list;
812 pthread_attr_destroy(&attr);
817 * Create the indexer thread and begin its operation.
819 void create_indexer_thread(void) {
823 if ((ret = pthread_attr_init(&attr))) {
824 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
829 /* Our per-thread stacks need to be bigger than the default size,
830 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
831 * crashes on 64-bit Linux.
833 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
834 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
837 pthread_attr_destroy(&attr);
841 if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0))
843 lprintf(CTDL_ALERT, "Can't create indexer thread: %s\n",
847 pthread_attr_destroy(&attr);
853 * Purge all sessions which have the 'kill_me' flag set.
854 * This function has code to prevent it from running more than once every
855 * few seconds, because running it after every single unbind would waste a lot
856 * of CPU time and keep the context list locked too much. To force it to run
857 * anyway, set "force" to nonzero.
860 * After that's done, we raise the size of the worker thread pool
861 * if such an action is appropriate.
863 void dead_session_purge(int force) {
864 struct CitContext *ptr; /* general-purpose utility pointer */
865 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
868 if ( (time(NULL) - last_purge) < 5 ) {
869 return; /* Too soon, go away */
874 begin_critical_section(S_SESSION_TABLE);
875 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
876 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
878 /* Remove the session from the active list */
880 ptr->prev->next = ptr->next;
883 ContextList = ptr->next;
886 ptr->next->prev = ptr->prev;
891 /* And put it on our to-be-destroyed list */
897 end_critical_section(S_SESSION_TABLE);
899 /* Now that we no longer have the session list locked, we can take
900 * our time and destroy any sessions on the to-be-killed list, which
901 * is allocated privately on this thread's stack.
903 while (rem != NULL) {
904 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
911 /* Raise the size of the worker thread pool if necessary. */
912 if ( (num_sessions > num_threads)
913 && (num_threads < config.c_max_workers) ) {
914 begin_critical_section(S_WORKER_LIST);
916 end_critical_section(S_WORKER_LIST);
925 * masterCC is the context we use when not attached to a session. This
926 * function initializes it.
928 void InitializeMasterCC(void) {
929 memset(&masterCC, 0, sizeof(struct CitContext));
930 masterCC.internal_pgm = 1;
940 * Bind a thread to a context. (It's inline merely to speed things up.)
942 INLINE void become_session(struct CitContext *which_con) {
943 pthread_setspecific(MyConKey, (void *)which_con );
949 * This loop just keeps going and going and going...
951 void *worker_thread(void *arg) {
954 struct CitContext *ptr;
955 struct CitContext *bind_me = NULL;
958 struct CitContext *con= NULL; /* Temporary context pointer */
959 struct ServiceFunctionHook *serviceptr;
960 int ssock; /* Descriptor for client socket */
969 while (!time_to_die) {
971 /* make doubly sure we're not holding any stale db handles
972 * which might cause a deadlock.
975 do_select: force_purge = 0;
976 bind_me = NULL; /* Which session shall we handle? */
978 /* Initialize the fdset. */
982 begin_critical_section(S_SESSION_TABLE);
983 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
984 if (ptr->state == CON_IDLE) {
985 FD_SET(ptr->client_socket, &readfds);
986 if (ptr->client_socket > highest)
987 highest = ptr->client_socket;
989 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
991 ptr->state = CON_EXECUTING;
994 end_critical_section(S_SESSION_TABLE);
1000 /* If we got this far, it means that there are no sessions
1001 * which a previous thread marked for attention, so we go
1002 * ahead and get ready to select().
1005 /* First, add the various master sockets to the fdset. */
1006 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1007 serviceptr = serviceptr->next ) {
1008 m = serviceptr->msock;
1009 FD_SET(m, &readfds);
1016 tv.tv_sec = 1; /* wake up every second if no input */
1018 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1021 if (time_to_die) return(NULL);
1023 /* Now figure out who made this select() unblock.
1024 * First, check for an error or exit condition.
1027 if (errno == EBADF) {
1028 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1032 if (errno != EINTR) {
1033 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1035 } else if (!time_to_die)
1039 /* Next, check to see if it's a new client connecting
1040 * on a master socket.
1042 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1043 serviceptr = serviceptr->next ) {
1045 if (FD_ISSET(serviceptr->msock, &readfds)) {
1046 ssock = accept(serviceptr->msock, NULL, 0);
1049 "New client socket %d\n",
1052 /* New context will be created already
1053 * set up in the CON_EXECUTING state.
1055 con = CreateNewContext();
1057 /* Assign new socket number to it. */
1058 con->client_socket = ssock;
1059 con->h_command_function =
1060 serviceptr->h_command_function;
1061 con->h_async_function =
1062 serviceptr->h_async_function;
1064 /* Determine whether local socket */
1065 if (serviceptr->sockpath != NULL)
1066 con->is_local_socket = 1;
1068 /* Set the SO_REUSEADDR socket option */
1070 setsockopt(ssock, SOL_SOCKET,
1074 become_session(con);
1076 serviceptr->h_greeting_function();
1077 become_session(NULL);
1078 con->state = CON_IDLE;
1084 /* It must be a client socket. Find a context that has data
1085 * waiting on its socket *and* is in the CON_IDLE state. Any
1086 * active sockets other than our chosen one are marked as
1087 * CON_READY so the next thread that comes around can just bind
1088 * to one without having to select() again.
1090 begin_critical_section(S_SESSION_TABLE);
1091 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1092 if ( (FD_ISSET(ptr->client_socket, &readfds))
1093 && (ptr->state != CON_EXECUTING) ) {
1094 ptr->input_waiting = 1;
1096 bind_me = ptr; /* I choose you! */
1097 bind_me->state = CON_EXECUTING;
1100 ptr->state = CON_READY;
1104 end_critical_section(S_SESSION_TABLE);
1107 /* We're bound to a session */
1108 if (bind_me != NULL) {
1109 become_session(bind_me);
1111 /* If the client has sent a command, execute it. */
1112 if (CC->input_waiting) {
1113 CC->h_command_function();
1114 CC->input_waiting = 0;
1117 /* If there are asynchronous messages waiting and the
1118 * client supports it, do those now */
1119 if ((CC->is_async) && (CC->async_waiting)
1120 && (CC->h_async_function != NULL)) {
1121 CC->h_async_function();
1122 CC->async_waiting = 0;
1125 force_purge = CC->kill_me;
1126 become_session(NULL);
1127 bind_me->state = CON_IDLE;
1130 dead_session_purge(force_purge);
1132 check_sched_shutdown();
1135 /* If control reaches this point, the server is shutting down */
1144 * Translate text facility name to syslog.h defined value.
1146 int SyslogFacility(char *name)
1155 { LOG_KERN, "kern" },
1156 { LOG_USER, "user" },
1157 { LOG_MAIL, "mail" },
1158 { LOG_DAEMON, "daemon" },
1159 { LOG_AUTH, "auth" },
1160 { LOG_SYSLOG, "syslog" },
1162 { LOG_NEWS, "news" },
1163 { LOG_UUCP, "uucp" },
1164 { LOG_LOCAL0, "local0" },
1165 { LOG_LOCAL1, "local1" },
1166 { LOG_LOCAL2, "local2" },
1167 { LOG_LOCAL3, "local3" },
1168 { LOG_LOCAL4, "local4" },
1169 { LOG_LOCAL5, "local5" },
1170 { LOG_LOCAL6, "local6" },
1171 { LOG_LOCAL7, "local7" },
1174 for(i = 0; facTbl[i].name != NULL; i++) {
1175 if(!strcasecmp(name, facTbl[i].name))
1176 return facTbl[i].facility;
1183 /********** MEM CHEQQER ***********/
1185 #ifdef DEBUG_MEMORY_LEAKS
1192 void *tracked_malloc(size_t size, char *file, int line) {
1193 struct igheap *thisheap;
1196 block = malloc(size);
1197 if (block == NULL) return(block);
1199 thisheap = malloc(sizeof(struct igheap));
1200 if (thisheap == NULL) {
1205 thisheap->block = block;
1206 strcpy(thisheap->file, file);
1207 thisheap->line = line;
1209 begin_critical_section(S_DEBUGMEMLEAKS);
1210 thisheap->next = igheap;
1212 end_critical_section(S_DEBUGMEMLEAKS);
1218 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1219 struct igheap *thisheap;
1222 block = realloc(ptr, size);
1223 if (block == NULL) return(block);
1225 thisheap = malloc(sizeof(struct igheap));
1226 if (thisheap == NULL) {
1231 thisheap->block = block;
1232 strcpy(thisheap->file, file);
1233 thisheap->line = line;
1235 begin_critical_section(S_DEBUGMEMLEAKS);
1236 thisheap->next = igheap;
1238 end_critical_section(S_DEBUGMEMLEAKS);
1245 void tracked_free(void *ptr) {
1246 struct igheap *thisheap;
1247 struct igheap *trash;
1251 if (igheap == NULL) return;
1252 begin_critical_section(S_DEBUGMEMLEAKS);
1253 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1254 if (thisheap->next != NULL) {
1255 if (thisheap->next->block == ptr) {
1256 trash = thisheap->next;
1257 thisheap->next = thisheap->next->next;
1262 if (igheap->block == ptr) {
1264 igheap = igheap->next;
1267 end_critical_section(S_DEBUGMEMLEAKS);
1270 char *tracked_strdup(const char *s, char *file, int line) {
1273 if (s == NULL) return(NULL);
1274 ptr = tracked_malloc(strlen(s) + 1, file, line);
1275 if (ptr == NULL) return(NULL);
1276 strncpy(ptr, s, strlen(s));
1280 void dump_heap(void) {
1281 struct igheap *thisheap;
1283 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1284 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1285 thisheap->file, thisheap->line);
1289 #endif /* DEBUG_MEMORY_LEAKS */