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;
102 pthread_t checkpoint_thread_tid;
104 int syslog_facility = (-1);
105 int enable_syslog = 0;
106 extern int running_as_daemon;
109 * lprintf() ... Write logging information
111 void lprintf(enum LogLevel loglevel, const char *format, ...) {
115 va_start(arg_ptr, format);
116 vsyslog(loglevel, format, arg_ptr);
120 /* stderr output code */
121 if (enable_syslog || running_as_daemon) return;
123 /* if we run in forground and syslog is disabled, log to terminal */
124 if (loglevel <= verbosity) {
129 gettimeofday(&tv, NULL);
130 /* Promote to time_t; types differ on some OSes (like darwin) */
131 unixtime = tv.tv_sec;
132 localtime_r(&unixtime, &tim);
133 if (CC->cs_pid != 0) {
135 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
136 tim.tm_year + 1900, tim.tm_mon + 1,
137 tim.tm_mday, tim.tm_hour, tim.tm_min,
138 tim.tm_sec, (long)tv.tv_usec,
142 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
143 tim.tm_year + 1900, tim.tm_mon + 1,
144 tim.tm_mday, tim.tm_hour, tim.tm_min,
145 tim.tm_sec, (long)tv.tv_usec);
147 va_start(arg_ptr, format);
148 vfprintf(stderr, format, arg_ptr);
157 * Signal handler to shut down the server.
160 volatile int time_to_die = 0;
162 static RETSIGTYPE signal_cleanup(int signum) {
163 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
165 master_cleanup(signum);
170 * Some initialization stuff...
172 void init_sysdep(void) {
176 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
180 getrlimit(RLIMIT_NOFILE, &rl);
181 rl.rlim_cur = FD_SETSIZE;
182 rl.rlim_max = FD_SETSIZE;
183 setrlimit(RLIMIT_NOFILE, &rl);
187 /* If we've got OpenSSL, we're going to use it. */
192 /* Set up a bunch of semaphores to be used for critical sections */
193 for (i=0; i<MAX_SEMAPHORES; ++i) {
194 pthread_mutex_init(&Critters[i], NULL);
198 * Set up a place to put thread-specific data.
199 * We only need a single pointer per thread - it points to the
200 * CitContext structure (in the ContextList linked list) of the
201 * session to which the calling thread is currently bound.
203 if (pthread_key_create(&MyConKey, NULL) != 0) {
204 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
209 * The action for unexpected signals and exceptions should be to
210 * call signal_cleanup() to gracefully shut down the server.
213 sigaddset(&set, SIGINT);
214 sigaddset(&set, SIGQUIT);
215 sigaddset(&set, SIGHUP);
216 sigaddset(&set, SIGTERM);
217 // sigaddset(&set, SIGSEGV); commented out because
218 // sigaddset(&set, SIGILL); we want core dumps
219 // sigaddset(&set, SIGBUS);
220 sigprocmask(SIG_UNBLOCK, &set, NULL);
222 signal(SIGINT, signal_cleanup);
223 signal(SIGQUIT, signal_cleanup);
224 signal(SIGHUP, signal_cleanup);
225 signal(SIGTERM, signal_cleanup);
226 // signal(SIGSEGV, signal_cleanup); commented out because
227 // signal(SIGILL, signal_cleanup); we want core dumps
228 // signal(SIGBUS, signal_cleanup);
231 * Do not shut down the server on broken pipe signals, otherwise the
232 * whole Citadel service would come down whenever a single client
235 signal(SIGPIPE, SIG_IGN);
240 * Obtain a semaphore lock to begin a critical section.
242 void begin_critical_section(int which_one)
244 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
246 /* For all types of critical sections except those listed here,
247 * ensure nobody ever tries to do a critical section within a
248 * transaction; this could lead to deadlock.
250 if ( (which_one != S_FLOORCACHE)
251 #ifdef DEBUG_MEMORY_LEAKS
252 && (which_one != S_DEBUGMEMLEAKS)
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)
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_NONE) {
295 sin.sin_addr.s_addr = INADDR_ANY;
298 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
301 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
307 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
309 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
310 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
316 /* set to nonblock - we need this for some obscure situations */
317 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
319 "citserver: Can't set socket to non-blocking: %s\n",
325 if (listen(s, actual_queue_len) < 0) {
326 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
338 * Create a Unix domain socket and listen on it
340 int ig_uds_server(char *sockpath, int queue_len)
342 struct sockaddr_un addr;
345 int actual_queue_len;
347 actual_queue_len = queue_len;
348 if (actual_queue_len < 5) actual_queue_len = 5;
350 i = unlink(sockpath);
351 if (i != 0) if (errno != ENOENT) {
352 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
353 sockpath, strerror(errno));
357 memset(&addr, 0, sizeof(addr));
358 addr.sun_family = AF_UNIX;
359 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
361 s = socket(AF_UNIX, SOCK_STREAM, 0);
363 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
368 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
369 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
374 /* set to nonblock - we need this for some obscure situations */
375 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
377 "citserver: Can't set socket to non-blocking: %s\n",
383 if (listen(s, actual_queue_len) < 0) {
384 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
389 chmod(sockpath, 0777);
396 * Return a pointer to the CitContext structure bound to the thread which
397 * called this function. If there's no such binding (for example, if it's
398 * called by the housekeeper thread) then a generic 'master' CC is returned.
400 * This function is used *VERY* frequently and must be kept small.
402 struct CitContext *MyContext(void) {
404 register struct CitContext *c;
406 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
407 c == NULL) ? &masterCC : c
413 * Initialize a new context and place it in the list. The session number
414 * used to be the PID (which is why it's called cs_pid), but that was when we
415 * had one process per session. Now we just assign them sequentially, starting
416 * at 1 (don't change it to 0 because masterCC uses 0).
418 struct CitContext *CreateNewContext(void) {
419 struct CitContext *me;
420 static int next_pid = 0;
422 me = (struct CitContext *) malloc(sizeof(struct CitContext));
424 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
427 memset(me, 0, sizeof(struct CitContext));
429 /* The new context will be created already in the CON_EXECUTING state
430 * in order to prevent another thread from grabbing it while it's
433 me->state = CON_EXECUTING;
436 * Generate a unique session number and insert this context into
439 begin_critical_section(S_SESSION_TABLE);
440 me->cs_pid = ++next_pid;
442 me->next = ContextList;
444 if (me->next != NULL) {
448 end_critical_section(S_SESSION_TABLE);
454 * The following functions implement output buffering. If the kernel supplies
455 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
456 * user-space buffering.
459 # define HAVE_TCP_BUFFERING
462 # define HAVE_TCP_BUFFERING
463 # define TCP_CORK TCP_NOPUSH
468 #ifdef HAVE_TCP_BUFFERING
469 static unsigned on = 1, off = 0;
470 void buffer_output(void) {
471 struct CitContext *ctx = MyContext();
472 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
476 void unbuffer_output(void) {
477 struct CitContext *ctx = MyContext();
478 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
482 void flush_output(void) {
483 struct CitContext *ctx = MyContext();
484 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
485 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
488 void buffer_output(void) {
489 if (CC->buffering == 0) {
492 CC->output_buffer = malloc(SIZ);
496 void flush_output(void) {
497 if (CC->buffering == 1) {
498 client_write(CC->output_buffer, CC->buffer_len);
503 void unbuffer_output(void) {
504 if (CC->buffering == 1) {
506 /* We don't call flush_output because we can't. */
507 client_write(CC->output_buffer, CC->buffer_len);
509 free(CC->output_buffer);
510 CC->output_buffer = NULL;
518 * client_write() ... Send binary data to the client.
520 void client_write(char *buf, int nbytes)
522 int bytes_written = 0;
524 #ifndef HAVE_TCP_BUFFERING
525 int old_buffer_len = 0;
528 if (CC->redirect_buffer != NULL) {
529 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
530 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
531 CC->redirect_buffer = realloc(CC->redirect_buffer,
534 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
535 CC->redirect_len += nbytes;
536 CC->redirect_buffer[CC->redirect_len] = 0;
540 #ifndef HAVE_TCP_BUFFERING
541 /* If we're buffering for later, do that now. */
543 old_buffer_len = CC->buffer_len;
544 CC->buffer_len += nbytes;
545 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
546 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
551 /* Ok, at this point we're not buffering. Go ahead and write. */
554 if (CC->redirect_ssl) {
555 client_write_ssl(buf, nbytes);
560 while (bytes_written < nbytes) {
561 retval = write(CC->client_socket, &buf[bytes_written],
562 nbytes - bytes_written);
564 lprintf(CTDL_ERR, "client_write() failed: %s\n",
569 bytes_written = bytes_written + retval;
575 * cprintf() ... Send formatted printable data to the client. It is
576 * implemented in terms of client_write() but remains in
577 * sysdep.c in case we port to somewhere without va_args...
579 void cprintf(const char *format, ...) {
583 va_start(arg_ptr, format);
584 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
585 buf[sizeof buf - 2] = '\n';
586 client_write(buf, strlen(buf));
592 * Read data from the client socket.
594 * 1 Requested number of bytes has been read.
595 * 0 Request timed out.
596 * -1 The socket is broken.
597 * If the socket breaks, the session will be terminated.
599 int client_read_to(char *buf, int bytes, int timeout)
607 if (CC->redirect_ssl) {
608 return (client_read_ssl(buf, bytes, timeout));
614 FD_SET(CC->client_socket, &rfds);
618 retval = select( (CC->client_socket)+1,
619 &rfds, NULL, NULL, &tv);
621 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
625 rlen = read(CC->client_socket, &buf[len], bytes-len);
627 lprintf(CTDL_ERR, "client_read() failed: %s\n",
638 * Read data from the client socket with default timeout.
639 * (This is implemented in terms of client_read_to() and could be
640 * justifiably moved out of sysdep.c)
642 INLINE int client_read(char *buf, int bytes)
644 return(client_read_to(buf, bytes, config.c_sleeping));
649 * client_getln() ... Get a LF-terminated line of text from the client.
650 * (This is implemented in terms of client_read() and could be
651 * justifiably moved out of sysdep.c)
653 int client_getln(char *buf, int bufsize)
657 /* Read one character at a time.
660 retval = client_read(&buf[i], 1);
661 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
665 /* If we got a long line, discard characters until the newline.
667 if (i == (bufsize-1))
668 while (buf[i] != '\n' && retval == 1)
669 retval = client_read(&buf[i], 1);
671 /* Strip the trailing newline and any trailing nonprintables (cr's)
674 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
675 buf[strlen(buf)-1] = 0;
676 if (retval < 0) safestrncpy(buf, "000", bufsize);
683 * The system-dependent part of master_cleanup() - close the master socket.
685 void sysdep_master_cleanup(void) {
686 struct ServiceFunctionHook *serviceptr;
689 * close all protocol master sockets
691 for (serviceptr = ServiceHookTable; serviceptr != NULL;
692 serviceptr = serviceptr->next ) {
694 if (serviceptr->tcp_port > 0)
695 lprintf(CTDL_INFO, "Closing listener on port %d\n",
696 serviceptr->tcp_port);
698 if (serviceptr->sockpath != NULL)
699 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
700 serviceptr->sockpath);
702 close(serviceptr->msock);
704 /* If it's a Unix domain socket, remove the file. */
705 if (serviceptr->sockpath != NULL) {
706 unlink(serviceptr->sockpath);
713 * Terminate another session.
714 * (This could justifiably be moved out of sysdep.c because it
715 * no longer does anything that is system-dependent.)
717 void kill_session(int session_to_kill) {
718 struct CitContext *ptr;
720 begin_critical_section(S_SESSION_TABLE);
721 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
722 if (ptr->cs_pid == session_to_kill) {
726 end_critical_section(S_SESSION_TABLE);
733 * Start running as a daemon.
735 void start_daemon(int unused) {
736 close(0); close(1); close(2);
739 signal(SIGHUP,SIG_IGN);
740 signal(SIGINT,SIG_IGN);
741 signal(SIGQUIT,SIG_IGN);
747 * Generic routine to convert a login name to a full name (gecos)
748 * Returns nonzero if a conversion took place
750 int convert_login(char NameToConvert[]) {
754 pw = getpwnam(NameToConvert);
759 strcpy(NameToConvert, pw->pw_gecos);
760 for (a=0; a<strlen(NameToConvert); ++a) {
761 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
767 struct worker_node *worker_list = NULL;
771 * create a worker thread. this function must always be called from within
772 * an S_WORKER_LIST critical section!
774 void create_worker(void) {
776 struct worker_node *n;
779 n = malloc(sizeof(struct worker_node));
781 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
786 if ((ret = pthread_attr_init(&attr))) {
787 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
792 /* Our per-thread stacks need to be bigger than the default size,
793 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
794 * crashes on 64-bit Linux.
796 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
797 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
800 pthread_attr_destroy(&attr);
804 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
807 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
811 n->next = worker_list;
813 pthread_attr_destroy(&attr);
818 * Create the indexer thread and begin its operation.
819 * Then create the checkpoint thread and begin its operation.
821 void create_maintenance_threads(void) {
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(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
844 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
847 if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
848 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
851 pthread_attr_destroy(&attr);
857 * Purge all sessions which have the 'kill_me' flag set.
858 * This function has code to prevent it from running more than once every
859 * few seconds, because running it after every single unbind would waste a lot
860 * of CPU time and keep the context list locked too much. To force it to run
861 * anyway, set "force" to nonzero.
864 * After that's done, we raise the size of the worker thread pool
865 * if such an action is appropriate.
867 void dead_session_purge(int force) {
868 struct CitContext *ptr; /* general-purpose utility pointer */
869 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
872 if ( (time(NULL) - last_purge) < 5 ) {
873 return; /* Too soon, go away */
878 begin_critical_section(S_SESSION_TABLE);
879 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
880 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
882 /* Remove the session from the active list */
884 ptr->prev->next = ptr->next;
887 ContextList = ptr->next;
890 ptr->next->prev = ptr->prev;
895 /* And put it on our to-be-destroyed list */
901 end_critical_section(S_SESSION_TABLE);
903 /* Now that we no longer have the session list locked, we can take
904 * our time and destroy any sessions on the to-be-killed list, which
905 * is allocated privately on this thread's stack.
907 while (rem != NULL) {
908 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
915 /* Raise the size of the worker thread pool if necessary. */
916 if ( (num_sessions > num_threads)
917 && (num_threads < config.c_max_workers) ) {
918 begin_critical_section(S_WORKER_LIST);
920 end_critical_section(S_WORKER_LIST);
929 * masterCC is the context we use when not attached to a session. This
930 * function initializes it.
932 void InitializeMasterCC(void) {
933 memset(&masterCC, 0, sizeof(struct CitContext));
934 masterCC.internal_pgm = 1;
944 * Bind a thread to a context. (It's inline merely to speed things up.)
946 INLINE void become_session(struct CitContext *which_con) {
947 pthread_setspecific(MyConKey, (void *)which_con );
953 * This loop just keeps going and going and going...
955 void *worker_thread(void *arg) {
958 struct CitContext *ptr;
959 struct CitContext *bind_me = NULL;
962 struct CitContext *con= NULL; /* Temporary context pointer */
963 struct ServiceFunctionHook *serviceptr;
964 int ssock; /* Descriptor for client socket */
973 while (!time_to_die) {
975 /* make doubly sure we're not holding any stale db handles
976 * which might cause a deadlock.
979 do_select: force_purge = 0;
980 bind_me = NULL; /* Which session shall we handle? */
982 /* Initialize the fdset. */
986 begin_critical_section(S_SESSION_TABLE);
987 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
988 if (ptr->state == CON_IDLE) {
989 FD_SET(ptr->client_socket, &readfds);
990 if (ptr->client_socket > highest)
991 highest = ptr->client_socket;
993 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
995 ptr->state = CON_EXECUTING;
998 end_critical_section(S_SESSION_TABLE);
1004 /* If we got this far, it means that there are no sessions
1005 * which a previous thread marked for attention, so we go
1006 * ahead and get ready to select().
1009 /* First, add the various master sockets to the fdset. */
1010 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1011 serviceptr = serviceptr->next ) {
1012 m = serviceptr->msock;
1013 FD_SET(m, &readfds);
1020 tv.tv_sec = 1; /* wake up every second if no input */
1022 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1025 if (time_to_die) return(NULL);
1027 /* Now figure out who made this select() unblock.
1028 * First, check for an error or exit condition.
1031 if (errno == EBADF) {
1032 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1036 if (errno != EINTR) {
1037 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1039 } else if (!time_to_die)
1043 /* Next, check to see if it's a new client connecting
1044 * on a master socket.
1046 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1047 serviceptr = serviceptr->next ) {
1049 if (FD_ISSET(serviceptr->msock, &readfds)) {
1050 ssock = accept(serviceptr->msock, NULL, 0);
1053 "New client socket %d\n",
1056 /* New context will be created already
1057 * set up in the CON_EXECUTING state.
1059 con = CreateNewContext();
1061 /* Assign new socket number to it. */
1062 con->client_socket = ssock;
1063 con->h_command_function =
1064 serviceptr->h_command_function;
1065 con->h_async_function =
1066 serviceptr->h_async_function;
1068 /* Determine whether local socket */
1069 if (serviceptr->sockpath != NULL)
1070 con->is_local_socket = 1;
1072 /* Set the SO_REUSEADDR socket option */
1074 setsockopt(ssock, SOL_SOCKET,
1078 become_session(con);
1080 serviceptr->h_greeting_function();
1081 become_session(NULL);
1082 con->state = CON_IDLE;
1088 /* It must be a client socket. Find a context that has data
1089 * waiting on its socket *and* is in the CON_IDLE state. Any
1090 * active sockets other than our chosen one are marked as
1091 * CON_READY so the next thread that comes around can just bind
1092 * to one without having to select() again.
1094 begin_critical_section(S_SESSION_TABLE);
1095 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1096 if ( (FD_ISSET(ptr->client_socket, &readfds))
1097 && (ptr->state != CON_EXECUTING) ) {
1098 ptr->input_waiting = 1;
1100 bind_me = ptr; /* I choose you! */
1101 bind_me->state = CON_EXECUTING;
1104 ptr->state = CON_READY;
1108 end_critical_section(S_SESSION_TABLE);
1111 /* We're bound to a session */
1112 if (bind_me != NULL) {
1113 become_session(bind_me);
1115 /* If the client has sent a command, execute it. */
1116 if (CC->input_waiting) {
1117 CC->h_command_function();
1118 CC->input_waiting = 0;
1121 /* If there are asynchronous messages waiting and the
1122 * client supports it, do those now */
1123 if ((CC->is_async) && (CC->async_waiting)
1124 && (CC->h_async_function != NULL)) {
1125 CC->h_async_function();
1126 CC->async_waiting = 0;
1129 force_purge = CC->kill_me;
1130 become_session(NULL);
1131 bind_me->state = CON_IDLE;
1134 dead_session_purge(force_purge);
1136 check_sched_shutdown();
1139 /* If control reaches this point, the server is shutting down */
1148 * Translate text facility name to syslog.h defined value.
1150 int SyslogFacility(char *name)
1159 { LOG_KERN, "kern" },
1160 { LOG_USER, "user" },
1161 { LOG_MAIL, "mail" },
1162 { LOG_DAEMON, "daemon" },
1163 { LOG_AUTH, "auth" },
1164 { LOG_SYSLOG, "syslog" },
1166 { LOG_NEWS, "news" },
1167 { LOG_UUCP, "uucp" },
1168 { LOG_LOCAL0, "local0" },
1169 { LOG_LOCAL1, "local1" },
1170 { LOG_LOCAL2, "local2" },
1171 { LOG_LOCAL3, "local3" },
1172 { LOG_LOCAL4, "local4" },
1173 { LOG_LOCAL5, "local5" },
1174 { LOG_LOCAL6, "local6" },
1175 { LOG_LOCAL7, "local7" },
1178 for(i = 0; facTbl[i].name != NULL; i++) {
1179 if(!strcasecmp(name, facTbl[i].name))
1180 return facTbl[i].facility;
1187 /********** MEM CHEQQER ***********/
1189 #ifdef DEBUG_MEMORY_LEAKS
1196 void *tracked_malloc(size_t size, char *file, int line) {
1197 struct igheap *thisheap;
1200 block = malloc(size);
1201 if (block == NULL) return(block);
1203 thisheap = malloc(sizeof(struct igheap));
1204 if (thisheap == NULL) {
1209 thisheap->block = block;
1210 strcpy(thisheap->file, file);
1211 thisheap->line = line;
1213 begin_critical_section(S_DEBUGMEMLEAKS);
1214 thisheap->next = igheap;
1216 end_critical_section(S_DEBUGMEMLEAKS);
1222 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1223 struct igheap *thisheap;
1226 block = realloc(ptr, size);
1227 if (block == NULL) return(block);
1229 thisheap = malloc(sizeof(struct igheap));
1230 if (thisheap == NULL) {
1235 thisheap->block = block;
1236 strcpy(thisheap->file, file);
1237 thisheap->line = line;
1239 begin_critical_section(S_DEBUGMEMLEAKS);
1240 thisheap->next = igheap;
1242 end_critical_section(S_DEBUGMEMLEAKS);
1249 void tracked_free(void *ptr) {
1250 struct igheap *thisheap;
1251 struct igheap *trash;
1255 if (igheap == NULL) return;
1256 begin_critical_section(S_DEBUGMEMLEAKS);
1257 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1258 if (thisheap->next != NULL) {
1259 if (thisheap->next->block == ptr) {
1260 trash = thisheap->next;
1261 thisheap->next = thisheap->next->next;
1266 if (igheap->block == ptr) {
1268 igheap = igheap->next;
1271 end_critical_section(S_DEBUGMEMLEAKS);
1274 char *tracked_strdup(const char *s, char *file, int line) {
1277 if (s == NULL) return(NULL);
1278 ptr = tracked_malloc(strlen(s) + 1, file, line);
1279 if (ptr == NULL) return(NULL);
1280 strncpy(ptr, s, strlen(s));
1284 void dump_heap(void) {
1285 struct igheap *thisheap;
1287 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1288 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1289 thisheap->file, thisheap->line);
1293 #endif /* DEBUG_MEMORY_LEAKS */