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 = (-1);
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(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;
158 static RETSIGTYPE signal_cleanup(int signum) {
159 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
161 master_cleanup(signum);
166 * Some initialization stuff...
168 void init_sysdep(void) {
172 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
176 getrlimit(RLIMIT_NOFILE, &rl);
177 rl.rlim_cur = FD_SETSIZE;
178 rl.rlim_max = FD_SETSIZE;
179 setrlimit(RLIMIT_NOFILE, &rl);
183 /* If we've got OpenSSL, we're going to use it. */
188 /* Set up a bunch of semaphores to be used for critical sections */
189 for (i=0; i<MAX_SEMAPHORES; ++i) {
190 pthread_mutex_init(&Critters[i], NULL);
194 * Set up a place to put thread-specific data.
195 * We only need a single pointer per thread - it points to the
196 * CitContext structure (in the ContextList linked list) of the
197 * session to which the calling thread is currently bound.
199 if (pthread_key_create(&MyConKey, NULL) != 0) {
200 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
205 * The action for unexpected signals and exceptions should be to
206 * call signal_cleanup() to gracefully shut down the server.
209 sigaddset(&set, SIGINT);
210 sigaddset(&set, SIGQUIT);
211 sigaddset(&set, SIGHUP);
212 sigaddset(&set, SIGTERM);
213 // sigaddset(&set, SIGSEGV); commented out because
214 // sigaddset(&set, SIGILL); we want core dumps
215 // sigaddset(&set, SIGBUS);
216 sigprocmask(SIG_UNBLOCK, &set, NULL);
218 signal(SIGINT, signal_cleanup);
219 signal(SIGQUIT, signal_cleanup);
220 signal(SIGHUP, signal_cleanup);
221 signal(SIGTERM, signal_cleanup);
222 // signal(SIGSEGV, signal_cleanup); commented out because
223 // signal(SIGILL, signal_cleanup); we want core dumps
224 // signal(SIGBUS, signal_cleanup);
227 * Do not shut down the server on broken pipe signals, otherwise the
228 * whole Citadel service would come down whenever a single client
231 signal(SIGPIPE, SIG_IGN);
236 * Obtain a semaphore lock to begin a critical section.
238 void begin_critical_section(int which_one)
240 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
242 /* For all types of critical sections except those listed here,
243 * ensure nobody ever tries to do a critical section within a
244 * transaction; this could lead to deadlock.
246 if ( (which_one != S_FLOORCACHE)
247 #ifdef DEBUG_MEMORY_LEAKS
248 && (which_one != S_DEBUGMEMLEAKS)
253 pthread_mutex_lock(&Critters[which_one]);
257 * Release a semaphore lock to end a critical section.
259 void end_critical_section(int which_one)
261 pthread_mutex_unlock(&Critters[which_one]);
267 * This is a generic function to set up a master socket for listening on
268 * a TCP port. The server shuts down if the bind fails.
271 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
273 struct sockaddr_in sin;
275 int actual_queue_len;
277 actual_queue_len = queue_len;
278 if (actual_queue_len < 5) actual_queue_len = 5;
280 memset(&sin, 0, sizeof(sin));
281 sin.sin_family = AF_INET;
282 sin.sin_port = htons((u_short)port_number);
283 if (ip_addr == NULL) {
284 sin.sin_addr.s_addr = INADDR_ANY;
287 sin.sin_addr.s_addr = inet_addr(ip_addr);
290 if (sin.sin_addr.s_addr == INADDR_NONE) {
291 sin.sin_addr.s_addr = INADDR_ANY;
294 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
297 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
303 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
305 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
306 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
312 /* set to nonblock - we need this for some obscure situations */
313 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
315 "citserver: Can't set socket to non-blocking: %s\n",
321 if (listen(s, actual_queue_len) < 0) {
322 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
334 * Create a Unix domain socket and listen on it
336 int ig_uds_server(char *sockpath, int queue_len)
338 struct sockaddr_un addr;
341 int actual_queue_len;
343 actual_queue_len = queue_len;
344 if (actual_queue_len < 5) actual_queue_len = 5;
346 i = unlink(sockpath);
347 if (i != 0) if (errno != ENOENT) {
348 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
349 sockpath, strerror(errno));
353 memset(&addr, 0, sizeof(addr));
354 addr.sun_family = AF_UNIX;
355 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
357 s = socket(AF_UNIX, SOCK_STREAM, 0);
359 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
364 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
365 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
370 /* set to nonblock - we need this for some obscure situations */
371 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
373 "citserver: Can't set socket to non-blocking: %s\n",
379 if (listen(s, actual_queue_len) < 0) {
380 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
385 chmod(sockpath, 0777);
392 * Return a pointer to the CitContext structure bound to the thread which
393 * called this function. If there's no such binding (for example, if it's
394 * called by the housekeeper thread) then a generic 'master' CC is returned.
396 * This function is used *VERY* frequently and must be kept small.
398 struct CitContext *MyContext(void) {
400 register struct CitContext *c;
402 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
403 c == NULL) ? &masterCC : c
409 * Initialize a new context and place it in the list. The session number
410 * used to be the PID (which is why it's called cs_pid), but that was when we
411 * had one process per session. Now we just assign them sequentially, starting
412 * at 1 (don't change it to 0 because masterCC uses 0).
414 struct CitContext *CreateNewContext(void) {
415 struct CitContext *me;
416 static int next_pid = 0;
418 me = (struct CitContext *) malloc(sizeof(struct CitContext));
420 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
423 memset(me, 0, sizeof(struct CitContext));
425 /* The new context will be created already in the CON_EXECUTING state
426 * in order to prevent another thread from grabbing it while it's
429 me->state = CON_EXECUTING;
432 * Generate a unique session number and insert this context into
435 begin_critical_section(S_SESSION_TABLE);
436 me->cs_pid = ++next_pid;
438 me->next = ContextList;
440 if (me->next != NULL) {
444 end_critical_section(S_SESSION_TABLE);
450 * The following functions implement output buffering. If the kernel supplies
451 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
452 * user-space buffering.
455 # define HAVE_TCP_BUFFERING
458 # define HAVE_TCP_BUFFERING
459 # define TCP_CORK TCP_NOPUSH
464 #ifdef HAVE_TCP_BUFFERING
465 static unsigned on = 1, off = 0;
466 void buffer_output(void) {
467 struct CitContext *ctx = MyContext();
468 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
472 void unbuffer_output(void) {
473 struct CitContext *ctx = MyContext();
474 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
478 void flush_output(void) {
479 struct CitContext *ctx = MyContext();
480 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
481 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
484 void buffer_output(void) {
485 if (CC->buffering == 0) {
488 CC->output_buffer = malloc(SIZ);
492 void flush_output(void) {
493 if (CC->buffering == 1) {
494 client_write(CC->output_buffer, CC->buffer_len);
499 void unbuffer_output(void) {
500 if (CC->buffering == 1) {
502 /* We don't call flush_output because we can't. */
503 client_write(CC->output_buffer, CC->buffer_len);
505 free(CC->output_buffer);
506 CC->output_buffer = NULL;
514 * client_write() ... Send binary data to the client.
516 void client_write(char *buf, int nbytes)
518 int bytes_written = 0;
520 #ifndef HAVE_TCP_BUFFERING
521 int old_buffer_len = 0;
524 if (CC->redirect_buffer != NULL) {
525 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
526 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
527 CC->redirect_buffer = realloc(CC->redirect_buffer,
530 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
531 CC->redirect_len += nbytes;
532 CC->redirect_buffer[CC->redirect_len] = 0;
536 #ifndef HAVE_TCP_BUFFERING
537 /* If we're buffering for later, do that now. */
539 old_buffer_len = CC->buffer_len;
540 CC->buffer_len += nbytes;
541 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
542 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
547 /* Ok, at this point we're not buffering. Go ahead and write. */
550 if (CC->redirect_ssl) {
551 client_write_ssl(buf, nbytes);
556 while (bytes_written < nbytes) {
557 retval = write(CC->client_socket, &buf[bytes_written],
558 nbytes - bytes_written);
560 lprintf(CTDL_ERR, "client_write() failed: %s\n",
565 bytes_written = bytes_written + retval;
571 * cprintf() ... Send formatted printable data to the client. It is
572 * implemented in terms of client_write() but remains in
573 * sysdep.c in case we port to somewhere without va_args...
575 void cprintf(const char *format, ...) {
579 va_start(arg_ptr, format);
580 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
581 buf[sizeof buf - 2] = '\n';
582 client_write(buf, strlen(buf));
588 * Read data from the client socket.
590 * 1 Requested number of bytes has been read.
591 * 0 Request timed out.
592 * -1 The socket is broken.
593 * If the socket breaks, the session will be terminated.
595 int client_read_to(char *buf, int bytes, int timeout)
603 if (CC->redirect_ssl) {
604 return (client_read_ssl(buf, bytes, timeout));
610 FD_SET(CC->client_socket, &rfds);
614 retval = select( (CC->client_socket)+1,
615 &rfds, NULL, NULL, &tv);
617 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
621 rlen = read(CC->client_socket, &buf[len], bytes-len);
623 /* The socket has been disconnected! */
633 * Read data from the client socket with default timeout.
634 * (This is implemented in terms of client_read_to() and could be
635 * justifiably moved out of sysdep.c)
637 INLINE int client_read(char *buf, int bytes)
639 return(client_read_to(buf, bytes, config.c_sleeping));
644 * client_getln() ... Get a LF-terminated line of text from the client.
645 * (This is implemented in terms of client_read() and could be
646 * justifiably moved out of sysdep.c)
648 int client_getln(char *buf, int bufsize)
652 /* Read one character at a time.
655 retval = client_read(&buf[i], 1);
656 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
660 /* If we got a long line, discard characters until the newline.
662 if (i == (bufsize-1))
663 while (buf[i] != '\n' && retval == 1)
664 retval = client_read(&buf[i], 1);
666 /* Strip the trailing newline and any trailing nonprintables (cr's)
669 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
670 buf[strlen(buf)-1] = 0;
671 if (retval < 0) safestrncpy(buf, "000", bufsize);
678 * The system-dependent part of master_cleanup() - close the master socket.
680 void sysdep_master_cleanup(void) {
681 struct ServiceFunctionHook *serviceptr;
684 * close all protocol master sockets
686 for (serviceptr = ServiceHookTable; serviceptr != NULL;
687 serviceptr = serviceptr->next ) {
689 if (serviceptr->tcp_port > 0)
690 lprintf(CTDL_INFO, "Closing listener on port %d\n",
691 serviceptr->tcp_port);
693 if (serviceptr->sockpath != NULL)
694 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
695 serviceptr->sockpath);
697 close(serviceptr->msock);
699 /* If it's a Unix domain socket, remove the file. */
700 if (serviceptr->sockpath != NULL) {
701 unlink(serviceptr->sockpath);
708 * Terminate another session.
709 * (This could justifiably be moved out of sysdep.c because it
710 * no longer does anything that is system-dependent.)
712 void kill_session(int session_to_kill) {
713 struct CitContext *ptr;
715 begin_critical_section(S_SESSION_TABLE);
716 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
717 if (ptr->cs_pid == session_to_kill) {
721 end_critical_section(S_SESSION_TABLE);
728 * Start running as a daemon.
730 void start_daemon(int unused) {
731 close(0); close(1); close(2);
734 signal(SIGHUP,SIG_IGN);
735 signal(SIGINT,SIG_IGN);
736 signal(SIGQUIT,SIG_IGN);
742 * Generic routine to convert a login name to a full name (gecos)
743 * Returns nonzero if a conversion took place
745 int convert_login(char NameToConvert[]) {
749 pw = getpwnam(NameToConvert);
754 strcpy(NameToConvert, pw->pw_gecos);
755 for (a=0; a<strlen(NameToConvert); ++a) {
756 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
762 struct worker_node *worker_list = NULL;
766 * create a worker thread. this function must always be called from within
767 * an S_WORKER_LIST critical section!
769 void create_worker(void) {
771 struct worker_node *n;
774 n = malloc(sizeof(struct worker_node));
776 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
781 if ((ret = pthread_attr_init(&attr))) {
782 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
787 /* Our per-thread stacks need to be bigger than the default size,
788 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
789 * crashes on 64-bit Linux.
791 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
792 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
795 pthread_attr_destroy(&attr);
799 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
802 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
806 n->next = worker_list;
808 pthread_attr_destroy(&attr);
813 * Create the indexer thread and begin its operation.
814 * Then create the checkpoint thread and begin its operation.
816 void create_maintenance_threads(void) {
820 if ((ret = pthread_attr_init(&attr))) {
821 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
826 /* Our per-thread stacks need to be bigger than the default size,
827 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
828 * crashes on 64-bit Linux.
830 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
831 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
834 pthread_attr_destroy(&attr);
838 if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
839 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
842 if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
843 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
846 pthread_attr_destroy(&attr);
852 * Purge all sessions which have the 'kill_me' flag set.
853 * This function has code to prevent it from running more than once every
854 * few seconds, because running it after every single unbind would waste a lot
855 * of CPU time and keep the context list locked too much. To force it to run
856 * anyway, set "force" to nonzero.
859 * After that's done, we raise the size of the worker thread pool
860 * if such an action is appropriate.
862 void dead_session_purge(int force) {
863 struct CitContext *ptr; /* general-purpose utility pointer */
864 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
867 if ( (time(NULL) - last_purge) < 5 ) {
868 return; /* Too soon, go away */
873 begin_critical_section(S_SESSION_TABLE);
874 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
875 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
877 /* Remove the session from the active list */
879 ptr->prev->next = ptr->next;
882 ContextList = ptr->next;
885 ptr->next->prev = ptr->prev;
890 /* And put it on our to-be-destroyed list */
896 end_critical_section(S_SESSION_TABLE);
898 /* Now that we no longer have the session list locked, we can take
899 * our time and destroy any sessions on the to-be-killed list, which
900 * is allocated privately on this thread's stack.
902 while (rem != NULL) {
903 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
910 /* Raise the size of the worker thread pool if necessary. */
911 if ( (num_sessions > num_threads)
912 && (num_threads < config.c_max_workers) ) {
913 begin_critical_section(S_WORKER_LIST);
915 end_critical_section(S_WORKER_LIST);
924 * masterCC is the context we use when not attached to a session. This
925 * function initializes it.
927 void InitializeMasterCC(void) {
928 memset(&masterCC, 0, sizeof(struct CitContext));
929 masterCC.internal_pgm = 1;
939 * Bind a thread to a context. (It's inline merely to speed things up.)
941 INLINE void become_session(struct CitContext *which_con) {
942 pthread_setspecific(MyConKey, (void *)which_con );
948 * This loop just keeps going and going and going...
950 void *worker_thread(void *arg) {
953 struct CitContext *ptr;
954 struct CitContext *bind_me = NULL;
957 struct CitContext *con= NULL; /* Temporary context pointer */
958 struct ServiceFunctionHook *serviceptr;
959 int ssock; /* Descriptor for client socket */
968 while (!time_to_die) {
970 /* make doubly sure we're not holding any stale db handles
971 * which might cause a deadlock.
974 do_select: force_purge = 0;
975 bind_me = NULL; /* Which session shall we handle? */
977 /* Initialize the fdset. */
981 begin_critical_section(S_SESSION_TABLE);
982 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
983 if (ptr->state == CON_IDLE) {
984 FD_SET(ptr->client_socket, &readfds);
985 if (ptr->client_socket > highest)
986 highest = ptr->client_socket;
988 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
990 ptr->state = CON_EXECUTING;
993 end_critical_section(S_SESSION_TABLE);
999 /* If we got this far, it means that there are no sessions
1000 * which a previous thread marked for attention, so we go
1001 * ahead and get ready to select().
1004 /* First, add the various master sockets to the fdset. */
1005 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1006 serviceptr = serviceptr->next ) {
1007 m = serviceptr->msock;
1008 FD_SET(m, &readfds);
1015 tv.tv_sec = 1; /* wake up every second if no input */
1017 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1020 if (time_to_die) return(NULL);
1022 /* Now figure out who made this select() unblock.
1023 * First, check for an error or exit condition.
1026 if (errno == EBADF) {
1027 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1031 if (errno != EINTR) {
1032 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1034 } else if (!time_to_die)
1038 /* Next, check to see if it's a new client connecting
1039 * on a master socket.
1041 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1042 serviceptr = serviceptr->next ) {
1044 if (FD_ISSET(serviceptr->msock, &readfds)) {
1045 ssock = accept(serviceptr->msock, NULL, 0);
1048 "New client socket %d\n",
1051 /* New context will be created already
1052 * set up in the CON_EXECUTING state.
1054 con = CreateNewContext();
1056 /* Assign new socket number to it. */
1057 con->client_socket = ssock;
1058 con->h_command_function =
1059 serviceptr->h_command_function;
1060 con->h_async_function =
1061 serviceptr->h_async_function;
1063 /* Determine whether local socket */
1064 if (serviceptr->sockpath != NULL)
1065 con->is_local_socket = 1;
1067 /* Set the SO_REUSEADDR socket option */
1069 setsockopt(ssock, SOL_SOCKET,
1073 become_session(con);
1075 serviceptr->h_greeting_function();
1076 become_session(NULL);
1077 con->state = CON_IDLE;
1083 /* It must be a client socket. Find a context that has data
1084 * waiting on its socket *and* is in the CON_IDLE state. Any
1085 * active sockets other than our chosen one are marked as
1086 * CON_READY so the next thread that comes around can just bind
1087 * to one without having to select() again.
1089 begin_critical_section(S_SESSION_TABLE);
1090 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1091 if ( (FD_ISSET(ptr->client_socket, &readfds))
1092 && (ptr->state != CON_EXECUTING) ) {
1093 ptr->input_waiting = 1;
1095 bind_me = ptr; /* I choose you! */
1096 bind_me->state = CON_EXECUTING;
1099 ptr->state = CON_READY;
1103 end_critical_section(S_SESSION_TABLE);
1106 /* We're bound to a session */
1107 if (bind_me != NULL) {
1108 become_session(bind_me);
1110 /* If the client has sent a command, execute it. */
1111 if (CC->input_waiting) {
1112 CC->h_command_function();
1113 CC->input_waiting = 0;
1116 /* If there are asynchronous messages waiting and the
1117 * client supports it, do those now */
1118 if ((CC->is_async) && (CC->async_waiting)
1119 && (CC->h_async_function != NULL)) {
1120 CC->h_async_function();
1121 CC->async_waiting = 0;
1124 force_purge = CC->kill_me;
1125 become_session(NULL);
1126 bind_me->state = CON_IDLE;
1129 dead_session_purge(force_purge);
1131 check_sched_shutdown();
1134 /* If control reaches this point, the server is shutting down */
1143 * Translate text facility name to syslog.h defined value.
1145 int SyslogFacility(char *name)
1154 { LOG_KERN, "kern" },
1155 { LOG_USER, "user" },
1156 { LOG_MAIL, "mail" },
1157 { LOG_DAEMON, "daemon" },
1158 { LOG_AUTH, "auth" },
1159 { LOG_SYSLOG, "syslog" },
1161 { LOG_NEWS, "news" },
1162 { LOG_UUCP, "uucp" },
1163 { LOG_LOCAL0, "local0" },
1164 { LOG_LOCAL1, "local1" },
1165 { LOG_LOCAL2, "local2" },
1166 { LOG_LOCAL3, "local3" },
1167 { LOG_LOCAL4, "local4" },
1168 { LOG_LOCAL5, "local5" },
1169 { LOG_LOCAL6, "local6" },
1170 { LOG_LOCAL7, "local7" },
1173 for(i = 0; facTbl[i].name != NULL; i++) {
1174 if(!strcasecmp(name, facTbl[i].name))
1175 return facTbl[i].facility;
1182 /********** MEM CHEQQER ***********/
1184 #ifdef DEBUG_MEMORY_LEAKS
1191 void *tracked_malloc(size_t size, char *file, int line) {
1192 struct igheap *thisheap;
1195 block = malloc(size);
1196 if (block == NULL) return(block);
1198 thisheap = malloc(sizeof(struct igheap));
1199 if (thisheap == NULL) {
1204 thisheap->block = block;
1205 strcpy(thisheap->file, file);
1206 thisheap->line = line;
1208 begin_critical_section(S_DEBUGMEMLEAKS);
1209 thisheap->next = igheap;
1211 end_critical_section(S_DEBUGMEMLEAKS);
1217 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1218 struct igheap *thisheap;
1221 block = realloc(ptr, size);
1222 if (block == NULL) return(block);
1224 thisheap = malloc(sizeof(struct igheap));
1225 if (thisheap == NULL) {
1230 thisheap->block = block;
1231 strcpy(thisheap->file, file);
1232 thisheap->line = line;
1234 begin_critical_section(S_DEBUGMEMLEAKS);
1235 thisheap->next = igheap;
1237 end_critical_section(S_DEBUGMEMLEAKS);
1244 void tracked_free(void *ptr) {
1245 struct igheap *thisheap;
1246 struct igheap *trash;
1250 if (igheap == NULL) return;
1251 begin_critical_section(S_DEBUGMEMLEAKS);
1252 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1253 if (thisheap->next != NULL) {
1254 if (thisheap->next->block == ptr) {
1255 trash = thisheap->next;
1256 thisheap->next = thisheap->next->next;
1261 if (igheap->block == ptr) {
1263 igheap = igheap->next;
1266 end_critical_section(S_DEBUGMEMLEAKS);
1269 char *tracked_strdup(const char *s, char *file, int line) {
1272 if (s == NULL) return(NULL);
1273 ptr = tracked_malloc(strlen(s) + 1, file, line);
1274 if (ptr == NULL) return(NULL);
1275 strncpy(ptr, s, strlen(s));
1279 void dump_heap(void) {
1280 struct igheap *thisheap;
1282 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1283 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1284 thisheap->file, thisheap->line);
1288 #endif /* DEBUG_MEMORY_LEAKS */