4 * Citadel/UX "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 <netinet/in.h>
57 #include "serv_extensions.h"
58 #include "sysdep_decls.h"
59 #include "citserver.h"
63 #include "housekeeping.h"
65 #include "serv_crypto.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 int rescan[2]; /* The Rescan Pipe */
95 time_t last_purge = 0; /* Last dead session purge */
96 static int num_threads = 0; /* Current number of threads */
97 int num_sessions = 0; /* Current number of sessions */
99 fd_set masterfds; /* Master sockets etc. */
102 pthread_t initial_thread; /* tid for main() thread */
104 int syslog_facility = (-1);
108 * lprintf() ... Write logging information
110 * Note: the variable "buf" below needs to be large enough to handle any
111 * log data sent through this function. BE CAREFUL!
113 void lprintf(enum LogLevel loglevel, const char *format, ...) {
117 va_start(arg_ptr, format);
118 vsnprintf(buf, sizeof(buf), format, arg_ptr);
121 if (syslog_facility >= 0) {
122 if (loglevel <= verbosity) {
124 if (CC && CC->cs_pid) {
125 memmove(buf + 6, buf, sizeof(buf) - 6);
126 snprintf(buf, 6, "[%3d]", CC->cs_pid);
129 syslog(loglevel, buf);
132 else if (loglevel <= verbosity) {
137 gettimeofday(&tv, NULL);
138 /* Promote to time_t; types differ on some OSes (like darwin) */
139 unixtime = tv.tv_sec;
140 tim = localtime(&unixtime);
142 * Log provides millisecond accuracy. If you need
143 * microsecond accuracy and your OS supports it, change
144 * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
146 if (CC && CC->cs_pid) {
148 /* Millisecond display */
150 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%3d] %s",
151 tim->tm_year + 1900, tim->tm_mon + 1,
152 tim->tm_mday, tim->tm_hour, tim->tm_min,
153 tim->tm_sec, (long)tv.tv_usec / 1000,
156 /* Microsecond display */
158 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] %s",
159 tim->tm_year + 1900, tim->tm_mon + 1,
160 tim->tm_mday, tim->tm_hour, tim->tm_min,
161 tim->tm_sec, (long)tv.tv_usec,
165 /* Millisecond display */
167 "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
168 tim->tm_year + 1900, tim->tm_mon + 1,
169 tim->tm_mday, tim->tm_hour, tim->tm_min,
170 tim->tm_sec, (long)tv.tv_usec / 1000, buf);
172 /* Microsecond display */
174 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s",
175 tim->tm_year + 1900, tim->tm_mon + 1,
176 tim->tm_mday, tim->tm_hour, tim->tm_min,
177 tim->tm_sec, (long)tv.tv_usec, buf);
182 PerformLogHooks(loglevel, buf);
188 * We used to use master_cleanup() as a signal handler to shut down the server.
189 * however, master_cleanup() and the functions it calls do some things that
190 * aren't such a good idea to do from a signal handler: acquiring mutexes,
191 * playing with signal masks on BSDI systems, etc. so instead we install the
192 * following signal handler to set a global variable to inform the main loop
193 * that it's time to call master_cleanup() and exit.
196 volatile int time_to_die = 0;
198 static RETSIGTYPE signal_cleanup(int signum) {
204 * Some initialization stuff...
206 void init_sysdep(void) {
209 /* Enable core dumps */
210 struct rlimit lim = { RLIM_INFINITY, RLIM_INFINITY };
211 setrlimit(RLIMIT_CORE, &lim);
217 /* Set up a bunch of semaphores to be used for critical sections */
218 for (a=0; a<MAX_SEMAPHORES; ++a) {
219 pthread_mutex_init(&Critters[a], NULL);
223 * Set up a place to put thread-specific data.
224 * We only need a single pointer per thread - it points to the
225 * CitContext structure (in the ContextList linked list) of the
226 * session to which the calling thread is currently bound.
228 if (pthread_key_create(&MyConKey, NULL) != 0) {
229 lprintf(CTDL_CRIT, "Can't create TSD key!! %s\n", strerror(errno));
233 * The action for unexpected signals and exceptions should be to
234 * call signal_cleanup() to gracefully shut down the server.
236 signal(SIGINT, signal_cleanup);
237 signal(SIGQUIT, signal_cleanup);
238 signal(SIGHUP, signal_cleanup);
239 signal(SIGTERM, signal_cleanup);
242 * Do not shut down the server on broken pipe signals, otherwise the
243 * whole Citadel service would come down whenever a single client
246 signal(SIGPIPE, SIG_IGN);
251 * Obtain a semaphore lock to begin a critical section.
253 void begin_critical_section(int which_one)
255 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
257 /* For all types of critical sections except those listed here,
258 * ensure nobody ever tries to do a critical section within a
259 * transaction; this could lead to deadlock.
261 if ( (which_one != S_FLOORCACHE)
262 #ifdef DEBUG_MEMORY_LEAKS
263 && (which_one != S_DEBUGMEMLEAKS)
268 pthread_mutex_lock(&Critters[which_one]);
272 * Release a semaphore lock to end a critical section.
274 void end_critical_section(int which_one)
276 pthread_mutex_unlock(&Critters[which_one]);
282 * This is a generic function to set up a master socket for listening on
283 * a TCP port. The server shuts down if the bind fails.
286 int ig_tcp_server(int port_number, int queue_len)
288 struct sockaddr_in sin;
290 int actual_queue_len;
292 actual_queue_len = queue_len;
293 if (actual_queue_len < 5) actual_queue_len = 5;
295 memset(&sin, 0, sizeof(sin));
296 sin.sin_family = AF_INET;
297 sin.sin_addr.s_addr = INADDR_ANY;
298 sin.sin_port = htons((u_short)port_number);
300 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
303 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
309 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
311 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
312 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
318 if (listen(s, actual_queue_len) < 0) {
319 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
330 * Create a Unix domain socket and listen on it
332 int ig_uds_server(char *sockpath, int queue_len)
334 struct sockaddr_un addr;
337 int actual_queue_len;
339 actual_queue_len = queue_len;
340 if (actual_queue_len < 5) actual_queue_len = 5;
342 i = unlink(sockpath);
343 if (i != 0) if (errno != ENOENT) {
344 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
345 sockpath, strerror(errno));
349 memset(&addr, 0, sizeof(addr));
350 addr.sun_family = AF_UNIX;
351 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
353 s = socket(AF_UNIX, SOCK_STREAM, 0);
355 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
360 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
361 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
366 if (listen(s, actual_queue_len) < 0) {
367 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
371 chmod(sockpath, 0777);
378 * Return a pointer to the CitContext structure bound to the thread which
379 * called this function. If there's no such binding (for example, if it's
380 * called by the housekeeper thread) then a generic 'master' CC is returned.
382 * It's inlined because it's used *VERY* frequently.
384 INLINE struct CitContext *MyContext(void) {
385 return ((pthread_getspecific(MyConKey) == NULL)
387 : (struct CitContext *) pthread_getspecific(MyConKey)
393 * Initialize a new context and place it in the list. The session number
394 * used to be the PID (which is why it's called cs_pid), but that was when we
395 * had one process per session. Now we just assign them sequentially, starting
396 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
397 * sessions terminate.
399 struct CitContext *CreateNewContext(void) {
400 struct CitContext *me, *ptr;
402 me = (struct CitContext *) malloc(sizeof(struct CitContext));
404 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
407 memset(me, 0, sizeof(struct CitContext));
409 /* The new context will be created already in the CON_EXECUTING state
410 * in order to prevent another thread from grabbing it while it's
413 me->state = CON_EXECUTING;
417 * Generate a unique session number and insert this context into
420 begin_critical_section(S_SESSION_TABLE);
422 if (ContextList == NULL) {
428 else if (ContextList->cs_pid > 1) {
429 me->next = ContextList;
435 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
436 if (ptr->next == NULL) {
438 me->cs_pid = ptr->cs_pid + 1;
442 else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
443 me->next = ptr->next;
445 me->cs_pid = ptr->cs_pid + 1;
451 DONE: ++num_sessions;
452 end_critical_section(S_SESSION_TABLE);
458 * buffer_output() ... tell client_write to buffer all output until
459 * instructed to dump it all out later
461 void buffer_output(void) {
462 if (CC->buffering == 0) {
465 CC->output_buffer = malloc(SIZ);
470 * unbuffer_output() ... dump out all that output we've been buffering.
472 void unbuffer_output(void) {
473 if (CC->buffering == 1) {
475 client_write(CC->output_buffer, CC->buffer_len);
476 free(CC->output_buffer);
477 CC->output_buffer = NULL;
485 * client_write() ... Send binary data to the client.
487 void client_write(char *buf, int nbytes)
489 int bytes_written = 0;
492 int old_buffer_len = 0;
494 if (CC->redirect_fp != NULL) {
495 fwrite(buf, nbytes, 1, CC->redirect_fp);
499 if (CC->redirect_sock > 0) {
500 sock = CC->redirect_sock; /* and continue below... */
503 sock = CC->client_socket;
506 /* If we're buffering for later, do that now. */
508 old_buffer_len = CC->buffer_len;
509 CC->buffer_len += nbytes;
510 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
511 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
515 /* Ok, at this point we're not buffering. Go ahead and write. */
518 if (CC->redirect_ssl) {
519 client_write_ssl(buf, nbytes);
524 while (bytes_written < nbytes) {
525 retval = write(sock, &buf[bytes_written],
526 nbytes - bytes_written);
528 lprintf(CTDL_ERR, "client_write() failed: %s\n",
530 if (sock == CC->client_socket) CC->kill_me = 1;
533 bytes_written = bytes_written + retval;
539 * cprintf() ... Send formatted printable data to the client. It is
540 * implemented in terms of client_write() but remains in
541 * sysdep.c in case we port to somewhere without va_args...
543 void cprintf(const char *format, ...) {
547 va_start(arg_ptr, format);
548 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
549 buf[sizeof buf - 2] = '\n';
550 client_write(buf, strlen(buf));
556 * Read data from the client socket.
558 * 1 Requested number of bytes has been read.
559 * 0 Request timed out.
560 * -1 The socket is broken.
561 * If the socket breaks, the session will be terminated.
563 int client_read_to(char *buf, int bytes, int timeout)
571 if (CC->redirect_ssl) {
572 return (client_read_ssl(buf, bytes, timeout));
578 FD_SET(CC->client_socket, &rfds);
582 retval = select( (CC->client_socket)+1,
583 &rfds, NULL, NULL, &tv);
585 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
589 rlen = read(CC->client_socket, &buf[len], bytes-len);
591 lprintf(CTDL_ERR, "client_read() failed: %s\n",
602 * Read data from the client socket with default timeout.
603 * (This is implemented in terms of client_read_to() and could be
604 * justifiably moved out of sysdep.c)
606 INLINE int client_read(char *buf, int bytes)
608 return(client_read_to(buf, bytes, config.c_sleeping));
613 * client_gets() ... Get a LF-terminated line of text from the client.
614 * (This is implemented in terms of client_read() and could be
615 * justifiably moved out of sysdep.c)
617 int client_gets(char *buf)
621 /* Read one character at a time.
624 retval = client_read(&buf[i], 1);
625 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
629 /* If we got a long line, discard characters until the newline.
632 while (buf[i] != '\n' && retval == 1)
633 retval = client_read(&buf[i], 1);
635 /* Strip the trailing newline and any trailing nonprintables (cr's)
638 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
639 buf[strlen(buf)-1] = 0;
640 if (retval < 0) strcpy(buf, "000");
647 * The system-dependent part of master_cleanup() - close the master socket.
649 void sysdep_master_cleanup(void) {
650 struct ServiceFunctionHook *serviceptr;
653 * close all protocol master sockets
655 for (serviceptr = ServiceHookTable; serviceptr != NULL;
656 serviceptr = serviceptr->next ) {
658 if (serviceptr->tcp_port > 0)
659 lprintf(CTDL_INFO, "Closing listener on port %d\n",
660 serviceptr->tcp_port);
662 if (serviceptr->sockpath != NULL)
663 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
664 serviceptr->sockpath);
666 close(serviceptr->msock);
668 /* If it's a Unix domain socket, remove the file. */
669 if (serviceptr->sockpath != NULL) {
670 unlink(serviceptr->sockpath);
677 * Terminate another session.
678 * (This could justifiably be moved out of sysdep.c because it
679 * no longer does anything that is system-dependent.)
681 void kill_session(int session_to_kill) {
682 struct CitContext *ptr;
684 begin_critical_section(S_SESSION_TABLE);
685 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
686 if (ptr->cs_pid == session_to_kill) {
690 end_critical_section(S_SESSION_TABLE);
697 * Start running as a daemon. Only close stdio if do_close_stdio is set.
699 void start_daemon(int do_close_stdio) {
700 if (do_close_stdio) {
705 signal(SIGHUP,SIG_IGN);
706 signal(SIGINT,SIG_IGN);
707 signal(SIGQUIT,SIG_IGN);
708 if (fork()!=0) exit(0);
714 * Generic routine to convert a login name to a full name (gecos)
715 * Returns nonzero if a conversion took place
717 int convert_login(char NameToConvert[]) {
721 pw = getpwnam(NameToConvert);
726 strcpy(NameToConvert, pw->pw_gecos);
727 for (a=0; a<strlen(NameToConvert); ++a) {
728 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
734 struct worker_node *worker_list = NULL;
738 * create a worker thread. this function must always be called from within
739 * an S_WORKER_LIST critical section!
741 void create_worker(void) {
743 struct worker_node *n;
746 n = malloc(sizeof(struct worker_node));
748 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
753 if ((ret = pthread_attr_init(&attr))) {
754 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
759 /* we seem to need something bigger than FreeBSD's default 64k stack */
761 if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
762 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
767 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
770 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
774 n->next = worker_list;
781 * Purge all sessions which have the 'kill_me' flag set.
782 * This function has code to prevent it from running more than once every
783 * few seconds, because running it after every single unbind would waste a lot
784 * of CPU time and keep the context list locked too much.
786 * After that's done, we raise or lower the size of the worker thread pool
787 * if such an action is appropriate.
789 void dead_session_purge(void) {
790 struct CitContext *ptr, *rem;
791 struct worker_node **node, *tmp;
794 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
799 begin_critical_section(S_SESSION_TABLE);
800 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
801 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
805 end_critical_section(S_SESSION_TABLE);
807 /* RemoveContext() enters its own S_SESSION_TABLE critical
808 * section, so we have to do it like this.
811 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
815 } while (rem != NULL);
818 /* Raise or lower the size of the worker thread pool if such
819 * an action is appropriate.
822 self = pthread_self();
824 if ( (num_sessions > num_threads)
825 && (num_threads < config.c_max_workers) ) {
826 begin_critical_section(S_WORKER_LIST);
828 end_critical_section(S_WORKER_LIST);
831 /* don't let the initial thread die since it's responsible for
832 waiting for all the other threads to terminate. */
833 else if ( (num_sessions < num_threads)
834 && (num_threads > config.c_min_workers)
835 && (self != initial_thread) ) {
837 begin_critical_section(S_WORKER_LIST);
840 /* we're exiting before server shutdown... unlink ourself from
841 the worker list and detach our thread to avoid memory leaks
844 for (node = &worker_list; *node != NULL; node = &(*node)->next)
845 if ((*node)->tid == self) {
847 *node = (*node)->next;
852 pthread_detach(self);
853 end_critical_section(S_WORKER_LIST);
864 * Redirect a session's output to a file or socket.
865 * This function may be called with a file handle *or* a socket (but not
866 * both). Call with neither to return output to its normal client socket.
868 void CtdlRedirectOutput(FILE *fp, int sock) {
870 if (fp != NULL) CC->redirect_fp = fp;
871 else CC->redirect_fp = NULL;
873 if (sock > 0) CC->redirect_sock = sock;
874 else CC->redirect_sock = (-1);
880 * masterCC is the context we use when not attached to a session. This
881 * function initializes it.
883 void InitializeMasterCC(void) {
884 memset(&masterCC, 0, sizeof(struct CitContext));
885 masterCC.internal_pgm = 1;
892 * Set up a fd_set containing all the master sockets to which we
893 * always listen. It's computationally less expensive to just copy
894 * this to a local fd_set when starting a new select() and then add
895 * the client sockets than it is to initialize a new one and then
896 * figure out what to put there.
898 void init_master_fdset(void) {
899 struct ServiceFunctionHook *serviceptr;
902 lprintf(CTDL_DEBUG, "Initializing master fdset\n");
907 lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
908 FD_SET(rescan[0], &masterfds);
909 if (rescan[0] > masterhighest) masterhighest = rescan[0];
911 for (serviceptr = ServiceHookTable; serviceptr != NULL;
912 serviceptr = serviceptr->next ) {
913 m = serviceptr->msock;
914 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
915 FD_SET(m, &masterfds);
916 if (m > masterhighest) {
920 lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
925 * Bind a thread to a context. (It's inline merely to speed things up.)
927 INLINE void become_session(struct CitContext *which_con) {
928 pthread_setspecific(MyConKey, (void *)which_con );
934 * This loop just keeps going and going and going...
936 void *worker_thread(void *arg) {
940 /* This is synchronized below; it helps implement round robin mode */
941 static struct CitContext* next_session = NULL;
942 struct CitContext *ptr;
943 struct CitContext *bind_me = NULL;
946 struct CitContext *con= NULL; /* Temporary context pointer */
947 struct ServiceFunctionHook *serviceptr;
948 int ssock; /* Descriptor for client socket */
955 while (!time_to_die) {
958 * A naive implementation would have all idle threads
959 * calling select() and then they'd all wake up at once
960 * (known in computer science as the "thundering herd"
961 * problem). We solve this problem by putting the select()
962 * in a critical section, so only one thread has the
963 * opportunity to wake up. If we wake up on a master
964 * socket, create a new session context; otherwise, just
965 * bind the thread to the context we want and go on our
969 /* make doubly sure we're not holding any stale db handles
970 * which might cause a deadlock.
974 begin_critical_section(S_I_WANNA_SELECT);
975 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
976 highest = masterhighest;
977 begin_critical_section(S_SESSION_TABLE);
978 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
979 if (ptr->state == CON_IDLE) {
980 FD_SET(ptr->client_socket, &readfds);
981 if (ptr->client_socket > highest)
982 highest = ptr->client_socket;
985 end_critical_section(S_SESSION_TABLE);
987 tv.tv_sec = 1; /* wake up every second if no input */
992 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
994 end_critical_section(S_I_WANNA_SELECT);
998 /* Now figure out who made this select() unblock.
999 * First, check for an error or exit condition.
1002 if (errno != EINTR) {
1003 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1005 } else if (!time_to_die)
1009 /* Next, check to see if it's a new client connecting
1010 * on a master socket.
1012 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1013 serviceptr = serviceptr->next ) {
1015 if (FD_ISSET(serviceptr->msock, &readfds)) {
1016 ssock = accept(serviceptr->msock, NULL, 0);
1019 "citserver: accept(): %s\n",
1023 lprintf(CTDL_NOTICE,
1024 "New client socket %d\n",
1027 /* New context will be created already
1028 * set up in the CON_EXECUTING state.
1030 con = CreateNewContext();
1032 /* Assign new socket number to it. */
1033 con->client_socket = ssock;
1034 con->h_command_function =
1035 serviceptr->h_command_function;
1037 /* Determine whether local socket */
1038 if (serviceptr->sockpath != NULL)
1039 con->is_local_socket = 1;
1041 /* Set the SO_REUSEADDR socket option */
1043 setsockopt(ssock, SOL_SOCKET,
1047 become_session(con);
1049 serviceptr->h_greeting_function();
1050 become_session(NULL);
1051 con->state = CON_IDLE;
1057 /* If the rescan pipe went active, someone is telling this
1058 * thread that the &readfds needs to be refreshed with more
1062 end_critical_section(S_I_WANNA_SELECT);
1066 if (FD_ISSET(rescan[0], &readfds)) {
1067 read(rescan[0], &junk, 1);
1071 /* It must be a client socket. Find a context that has data
1072 * waiting on its socket *and* is in the CON_IDLE state.
1076 begin_critical_section(S_SESSION_TABLE);
1078 * We start where we left off. If we get to the end
1079 * we'll start from the beginning again, then give up
1080 * if we still don't find anything. This ensures
1081 * that all contexts get a more-or-less equal chance
1082 * to run. And yes, I did add a goto to the code. -IO
1084 find_session: if (next_session == NULL)
1085 next_session = ContextList;
1086 for (ptr = next_session;
1087 ( (ptr != NULL) && (bind_me == NULL) );
1089 if ( (FD_ISSET(ptr->client_socket, &readfds))
1090 && (ptr->state == CON_IDLE) ) {
1094 if (bind_me != NULL) {
1095 /* Found one. Stake a claim to it before
1096 * letting anyone else touch the context list.
1098 bind_me->state = CON_EXECUTING;
1099 next_session = bind_me->next;
1100 } else if (next_session == ContextList) {
1101 next_session = NULL;
1103 if (bind_me == NULL && next_session != NULL) {
1104 next_session = NULL;
1108 end_critical_section(S_SESSION_TABLE);
1109 end_critical_section(S_I_WANNA_SELECT);
1111 /* We're bound to a session, now do *one* command */
1112 if (bind_me != NULL) {
1113 become_session(bind_me);
1114 CC->h_command_function();
1115 become_session(NULL);
1116 bind_me->state = CON_IDLE;
1117 if (bind_me->kill_me == 1) {
1118 RemoveContext(bind_me);
1120 write(rescan[1], &junk, 1);
1124 dead_session_purge();
1126 check_sched_shutdown();
1129 /* If control reaches this point, the server is shutting down */
1139 * Translate text facility name to syslog.h defined value.
1141 int SyslogFacility(char *name)
1150 { LOG_KERN, "kern" },
1151 { LOG_USER, "user" },
1152 { LOG_MAIL, "mail" },
1153 { LOG_DAEMON, "daemon" },
1154 { LOG_AUTH, "auth" },
1155 { LOG_SYSLOG, "syslog" },
1157 { LOG_NEWS, "news" },
1158 { LOG_UUCP, "uucp" },
1159 { LOG_LOCAL0, "local0" },
1160 { LOG_LOCAL1, "local1" },
1161 { LOG_LOCAL2, "local2" },
1162 { LOG_LOCAL3, "local3" },
1163 { LOG_LOCAL4, "local4" },
1164 { LOG_LOCAL5, "local5" },
1165 { LOG_LOCAL6, "local6" },
1166 { LOG_LOCAL7, "local7" },
1169 for(i = 0; facTbl[i].name != NULL; i++) {
1170 if(!strcasecmp(name, facTbl[i].name))
1171 return facTbl[i].facility;
1177 /********** MEM CHEQQER ***********/
1179 #ifdef DEBUG_MEMORY_LEAKS
1186 void *tracked_malloc(size_t size, char *file, int line) {
1187 struct igheap *thisheap;
1190 block = malloc(size);
1191 if (block == NULL) return(block);
1193 thisheap = malloc(sizeof(struct igheap));
1194 if (thisheap == NULL) {
1199 thisheap->block = block;
1200 strcpy(thisheap->file, file);
1201 thisheap->line = line;
1203 begin_critical_section(S_DEBUGMEMLEAKS);
1204 thisheap->next = igheap;
1206 end_critical_section(S_DEBUGMEMLEAKS);
1212 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1213 struct igheap *thisheap;
1216 block = realloc(ptr, size);
1217 if (block == NULL) return(block);
1219 thisheap = malloc(sizeof(struct igheap));
1220 if (thisheap == NULL) {
1225 thisheap->block = block;
1226 strcpy(thisheap->file, file);
1227 thisheap->line = line;
1229 begin_critical_section(S_DEBUGMEMLEAKS);
1230 thisheap->next = igheap;
1232 end_critical_section(S_DEBUGMEMLEAKS);
1239 void tracked_free(void *ptr) {
1240 struct igheap *thisheap;
1241 struct igheap *trash;
1245 if (igheap == NULL) return;
1246 begin_critical_section(S_DEBUGMEMLEAKS);
1247 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1248 if (thisheap->next != NULL) {
1249 if (thisheap->next->block == ptr) {
1250 trash = thisheap->next;
1251 thisheap->next = thisheap->next->next;
1256 if (igheap->block == ptr) {
1258 igheap = igheap->next;
1261 end_critical_section(S_DEBUGMEMLEAKS);
1264 char *tracked_strdup(const char *s, char *file, int line) {
1267 if (s == NULL) return(NULL);
1268 ptr = tracked_malloc(strlen(s) + 1, file, line);
1269 if (ptr == NULL) return(NULL);
1270 strncpy(ptr, s, strlen(s));
1274 void dump_heap(void) {
1275 struct igheap *thisheap;
1277 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1278 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1279 thisheap->file, thisheap->line);
1283 #endif /* DEBUG_MEMORY_LEAKS */