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>
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct TheHeap *heap = NULL;
79 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
80 pthread_key_t MyConKey; /* TSD key for MyContext() */
82 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
84 struct CitContext masterCC;
85 int rescan[2]; /* The Rescan Pipe */
86 time_t last_purge = 0; /* Last dead session purge */
87 static int num_threads = 0; /* Current number of threads */
88 int num_sessions = 0; /* Current number of sessions */
90 fd_set masterfds; /* Master sockets etc. */
93 pthread_t initial_thread; /* tid for main() thread */
95 int syslog_facility = (-1);
99 * lprintf() ... Write logging information
101 * Note: the variable "buf" below needs to be large enough to handle any
102 * log data sent through this function. BE CAREFUL!
104 void lprintf(enum LogLevel loglevel, const char *format, ...) {
108 va_start(arg_ptr, format);
109 vsnprintf(buf, sizeof(buf), format, arg_ptr);
112 if (syslog_facility >= 0) {
113 if (loglevel <= verbosity) {
115 if (CC && CC->cs_pid) {
116 memmove(buf + 6, buf, sizeof(buf) - 6);
117 snprintf(buf, 6, "[%3d]", CC->cs_pid);
120 syslog(loglevel, buf);
123 else 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 tim = localtime(&unixtime);
133 * Log provides millisecond accuracy. If you need
134 * microsecond accuracy and your OS supports it, change
135 * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
137 if (CC && CC->cs_pid) {
139 /* Millisecond display */
141 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%3d] %s",
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 / 1000,
147 /* Microsecond display */
149 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] %s",
150 tim->tm_year + 1900, tim->tm_mon + 1,
151 tim->tm_mday, tim->tm_hour, tim->tm_min,
152 tim->tm_sec, (long)tv.tv_usec,
156 /* Millisecond display */
158 "%04d/%02d/%02d %2d:%02d:%02d.%03ld %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 / 1000, buf);
163 /* Microsecond display */
165 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s",
166 tim->tm_year + 1900, tim->tm_mon + 1,
167 tim->tm_mday, tim->tm_hour, tim->tm_min,
168 tim->tm_sec, (long)tv.tv_usec, buf);
173 PerformLogHooks(loglevel, buf);
178 #ifdef DEBUG_MEMORY_LEAKS
179 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
181 struct TheHeap *hptr;
185 lprintf(CTDL_ALERT, "DANGER! mallok(%d) at %s:%d failed!\n",
186 tsize, tfile, tline);
190 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
191 strcpy(hptr->h_file, tfile);
192 hptr->h_line = tline;
199 char *tracked_strdup(const char *orig, char *tfile, int tline) {
202 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
203 if (s == NULL) return NULL;
209 void tracked_free(void *ptr) {
210 struct TheHeap *hptr, *freeme;
212 if (heap->h_ptr == ptr) {
218 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
219 if (hptr->next->h_ptr == ptr) {
221 hptr->next = hptr->next->next;
230 void *tracked_realloc(void *ptr, size_t size) {
232 struct TheHeap *hptr;
234 newptr = realloc(ptr, size);
236 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
237 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
244 void dump_tracked() {
245 struct TheHeap *hptr;
247 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
248 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
249 cprintf("%20s %5d\n",
250 hptr->h_file, hptr->h_line);
262 * We used to use master_cleanup() as a signal handler to shut down the server.
263 * however, master_cleanup() and the functions it calls do some things that
264 * aren't such a good idea to do from a signal handler: acquiring mutexes,
265 * playing with signal masks on BSDI systems, etc. so instead we install the
266 * following signal handler to set a global variable to inform the main loop
267 * that it's time to call master_cleanup() and exit.
270 volatile int time_to_die = 0;
272 static RETSIGTYPE signal_cleanup(int signum) {
278 * Some initialization stuff...
280 void init_sysdep(void) {
287 /* Set up a bunch of semaphores to be used for critical sections */
288 for (a=0; a<MAX_SEMAPHORES; ++a) {
289 pthread_mutex_init(&Critters[a], NULL);
293 * Set up a place to put thread-specific data.
294 * We only need a single pointer per thread - it points to the
295 * CitContext structure (in the ContextList linked list) of the
296 * session to which the calling thread is currently bound.
298 if (pthread_key_create(&MyConKey, NULL) != 0) {
299 lprintf(CTDL_CRIT, "Can't create TSD key!! %s\n", strerror(errno));
303 * The action for unexpected signals and exceptions should be to
304 * call signal_cleanup() to gracefully shut down the server.
306 signal(SIGINT, signal_cleanup);
307 signal(SIGQUIT, signal_cleanup);
308 signal(SIGHUP, signal_cleanup);
309 signal(SIGTERM, signal_cleanup);
312 * Do not shut down the server on broken pipe signals, otherwise the
313 * whole Citadel service would come down whenever a single client
316 signal(SIGPIPE, SIG_IGN);
321 * Obtain a semaphore lock to begin a critical section.
323 void begin_critical_section(int which_one)
325 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
326 /* ensure nobody ever tries to do a critical section within a
327 transaction; this could lead to deadlock. */
329 pthread_mutex_lock(&Critters[which_one]);
333 * Release a semaphore lock to end a critical section.
335 void end_critical_section(int which_one)
337 /* lprintf(CTDL_DEBUG, "end_critical_section(%d)\n", which_one); */
338 pthread_mutex_unlock(&Critters[which_one]);
344 * This is a generic function to set up a master socket for listening on
345 * a TCP port. The server shuts down if the bind fails.
348 int ig_tcp_server(int port_number, int queue_len)
350 struct sockaddr_in sin;
352 int actual_queue_len;
354 actual_queue_len = queue_len;
355 if (actual_queue_len < 5) actual_queue_len = 5;
357 memset(&sin, 0, sizeof(sin));
358 sin.sin_family = AF_INET;
359 sin.sin_addr.s_addr = INADDR_ANY;
360 sin.sin_port = htons((u_short)port_number);
362 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
365 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
371 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
373 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
374 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
380 if (listen(s, actual_queue_len) < 0) {
381 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
392 * Create a Unix domain socket and listen on it
394 int ig_uds_server(char *sockpath, int queue_len)
396 struct sockaddr_un addr;
399 int actual_queue_len;
401 actual_queue_len = queue_len;
402 if (actual_queue_len < 5) actual_queue_len = 5;
404 i = unlink(sockpath);
405 if (i != 0) if (errno != ENOENT) {
406 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
407 sockpath, strerror(errno));
411 memset(&addr, 0, sizeof(addr));
412 addr.sun_family = AF_UNIX;
413 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
415 s = socket(AF_UNIX, SOCK_STREAM, 0);
417 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
422 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
423 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
428 if (listen(s, actual_queue_len) < 0) {
429 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
433 chmod(sockpath, 0777);
440 * Return a pointer to the CitContext structure bound to the thread which
441 * called this function. If there's no such binding (for example, if it's
442 * called by the housekeeper thread) then a generic 'master' CC is returned.
444 * It's inlined because it's used *VERY* frequently.
446 INLINE struct CitContext *MyContext(void) {
447 return ((pthread_getspecific(MyConKey) == NULL)
449 : (struct CitContext *) pthread_getspecific(MyConKey)
455 * Initialize a new context and place it in the list. The session number
456 * used to be the PID (which is why it's called cs_pid), but that was when we
457 * had one process per session. Now we just assign them sequentially, starting
458 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
459 * sessions terminate.
461 struct CitContext *CreateNewContext(void) {
462 struct CitContext *me, *ptr;
464 me = (struct CitContext *) mallok(sizeof(struct CitContext));
466 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
469 memset(me, 0, sizeof(struct CitContext));
471 /* The new context will be created already in the CON_EXECUTING state
472 * in order to prevent another thread from grabbing it while it's
475 me->state = CON_EXECUTING;
479 * Generate a unique session number and insert this context into
482 begin_critical_section(S_SESSION_TABLE);
484 if (ContextList == NULL) {
490 else if (ContextList->cs_pid > 1) {
491 me->next = ContextList;
497 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
498 if (ptr->next == NULL) {
500 me->cs_pid = ptr->cs_pid + 1;
504 else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
505 me->next = ptr->next;
507 me->cs_pid = ptr->cs_pid + 1;
513 DONE: ++num_sessions;
514 end_critical_section(S_SESSION_TABLE);
520 * buffer_output() ... tell client_write to buffer all output until
521 * instructed to dump it all out later
523 void buffer_output(void) {
524 if (CC->buffering == 0) {
527 CC->output_buffer = mallok(SIZ);
532 * unbuffer_output() ... dump out all that output we've been buffering.
534 void unbuffer_output(void) {
535 if (CC->buffering == 1) {
537 client_write(CC->output_buffer, CC->buffer_len);
538 phree(CC->output_buffer);
539 CC->output_buffer = NULL;
547 * client_write() ... Send binary data to the client.
549 void client_write(char *buf, int nbytes)
551 int bytes_written = 0;
554 int old_buffer_len = 0;
556 if (CC->redirect_fp != NULL) {
557 fwrite(buf, nbytes, 1, CC->redirect_fp);
561 if (CC->redirect_sock > 0) {
562 sock = CC->redirect_sock; /* and continue below... */
565 sock = CC->client_socket;
568 /* If we're buffering for later, do that now. */
570 old_buffer_len = CC->buffer_len;
571 CC->buffer_len += nbytes;
572 CC->output_buffer = reallok(CC->output_buffer, CC->buffer_len);
573 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
577 /* Ok, at this point we're not buffering. Go ahead and write. */
580 if (CC->redirect_ssl) {
581 client_write_ssl(buf, nbytes);
586 while (bytes_written < nbytes) {
587 retval = write(sock, &buf[bytes_written],
588 nbytes - bytes_written);
590 lprintf(CTDL_ERR, "client_write() failed: %s\n",
592 if (sock == CC->client_socket) CC->kill_me = 1;
595 bytes_written = bytes_written + retval;
601 * cprintf() ... Send formatted printable data to the client. It is
602 * implemented in terms of client_write() but remains in
603 * sysdep.c in case we port to somewhere without va_args...
605 void cprintf(const char *format, ...) {
609 va_start(arg_ptr, format);
610 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
611 buf[sizeof buf - 2] = '\n';
612 client_write(buf, strlen(buf));
618 * Read data from the client socket.
620 * 1 Requested number of bytes has been read.
621 * 0 Request timed out.
622 * -1 The socket is broken.
623 * If the socket breaks, the session will be terminated.
625 int client_read_to(char *buf, int bytes, int timeout)
633 if (CC->redirect_ssl) {
634 return (client_read_ssl(buf, bytes, timeout));
640 FD_SET(CC->client_socket, &rfds);
644 retval = select( (CC->client_socket)+1,
645 &rfds, NULL, NULL, &tv);
647 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
651 rlen = read(CC->client_socket, &buf[len], bytes-len);
653 lprintf(CTDL_ERR, "client_read() failed: %s\n",
664 * Read data from the client socket with default timeout.
665 * (This is implemented in terms of client_read_to() and could be
666 * justifiably moved out of sysdep.c)
668 INLINE int client_read(char *buf, int bytes)
670 return(client_read_to(buf, bytes, config.c_sleeping));
675 * client_gets() ... Get a LF-terminated line of text from the client.
676 * (This is implemented in terms of client_read() and could be
677 * justifiably moved out of sysdep.c)
679 int client_gets(char *buf)
683 /* Read one character at a time.
686 retval = client_read(&buf[i], 1);
687 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
691 /* If we got a long line, discard characters until the newline.
694 while (buf[i] != '\n' && retval == 1)
695 retval = client_read(&buf[i], 1);
697 /* Strip the trailing newline and any trailing nonprintables (cr's)
700 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
701 buf[strlen(buf)-1] = 0;
702 if (retval < 0) strcpy(buf, "000");
709 * The system-dependent part of master_cleanup() - close the master socket.
711 void sysdep_master_cleanup(void) {
712 struct ServiceFunctionHook *serviceptr;
715 * close all protocol master sockets
717 for (serviceptr = ServiceHookTable; serviceptr != NULL;
718 serviceptr = serviceptr->next ) {
720 if (serviceptr->tcp_port > 0)
721 lprintf(CTDL_INFO, "Closing listener on port %d\n",
722 serviceptr->tcp_port);
724 if (serviceptr->sockpath != NULL)
725 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
726 serviceptr->sockpath);
728 close(serviceptr->msock);
730 /* If it's a Unix domain socket, remove the file. */
731 if (serviceptr->sockpath != NULL) {
732 unlink(serviceptr->sockpath);
739 * Terminate another session.
740 * (This could justifiably be moved out of sysdep.c because it
741 * no longer does anything that is system-dependent.)
743 void kill_session(int session_to_kill) {
744 struct CitContext *ptr;
746 begin_critical_section(S_SESSION_TABLE);
747 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
748 if (ptr->cs_pid == session_to_kill) {
752 end_critical_section(S_SESSION_TABLE);
759 * Start running as a daemon. Only close stdio if do_close_stdio is set.
761 void start_daemon(int do_close_stdio) {
762 if (do_close_stdio) {
767 signal(SIGHUP,SIG_IGN);
768 signal(SIGINT,SIG_IGN);
769 signal(SIGQUIT,SIG_IGN);
770 if (fork()!=0) exit(0);
776 * Generic routine to convert a login name to a full name (gecos)
777 * Returns nonzero if a conversion took place
779 int convert_login(char NameToConvert[]) {
783 pw = getpwnam(NameToConvert);
788 strcpy(NameToConvert, pw->pw_gecos);
789 for (a=0; a<strlen(NameToConvert); ++a) {
790 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
796 struct worker_node *worker_list = NULL;
800 * create a worker thread. this function must always be called from within
801 * an S_WORKER_LIST critical section!
803 void create_worker(void) {
805 struct worker_node *n;
808 n = mallok(sizeof(struct worker_node));
810 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
815 if ((ret = pthread_attr_init(&attr))) {
816 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
821 /* we seem to need something bigger than FreeBSD's default 64k stack */
823 if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
824 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
829 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
832 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
836 n->next = worker_list;
843 * Purge all sessions which have the 'kill_me' flag set.
844 * This function has code to prevent it from running more than once every
845 * few seconds, because running it after every single unbind would waste a lot
846 * of CPU time and keep the context list locked too much.
848 * After that's done, we raise or lower the size of the worker thread pool
849 * if such an action is appropriate.
851 void dead_session_purge(void) {
852 struct CitContext *ptr, *rem;
853 struct worker_node **node, *tmp;
856 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
861 begin_critical_section(S_SESSION_TABLE);
862 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
863 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
867 end_critical_section(S_SESSION_TABLE);
869 /* RemoveContext() enters its own S_SESSION_TABLE critical
870 * section, so we have to do it like this.
873 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
877 } while (rem != NULL);
880 /* Raise or lower the size of the worker thread pool if such
881 * an action is appropriate.
884 self = pthread_self();
886 if ( (num_sessions > num_threads)
887 && (num_threads < config.c_max_workers) ) {
888 begin_critical_section(S_WORKER_LIST);
890 end_critical_section(S_WORKER_LIST);
893 /* don't let the initial thread die since it's responsible for
894 waiting for all the other threads to terminate. */
895 else if ( (num_sessions < num_threads)
896 && (num_threads > config.c_min_workers)
897 && (self != initial_thread) ) {
899 begin_critical_section(S_WORKER_LIST);
902 /* we're exiting before server shutdown... unlink ourself from
903 the worker list and detach our thread to avoid memory leaks
906 for (node = &worker_list; *node != NULL; node = &(*node)->next)
907 if ((*node)->tid == self) {
909 *node = (*node)->next;
914 pthread_detach(self);
915 end_critical_section(S_WORKER_LIST);
926 * Redirect a session's output to a file or socket.
927 * This function may be called with a file handle *or* a socket (but not
928 * both). Call with neither to return output to its normal client socket.
930 void CtdlRedirectOutput(FILE *fp, int sock) {
932 if (fp != NULL) CC->redirect_fp = fp;
933 else CC->redirect_fp = NULL;
935 if (sock > 0) CC->redirect_sock = sock;
936 else CC->redirect_sock = (-1);
942 * masterCC is the context we use when not attached to a session. This
943 * function initializes it.
945 void InitializeMasterCC(void) {
946 memset(&masterCC, 0, sizeof(struct CitContext));
947 masterCC.internal_pgm = 1;
954 * Set up a fd_set containing all the master sockets to which we
955 * always listen. It's computationally less expensive to just copy
956 * this to a local fd_set when starting a new select() and then add
957 * the client sockets than it is to initialize a new one and then
958 * figure out what to put there.
960 void init_master_fdset(void) {
961 struct ServiceFunctionHook *serviceptr;
964 lprintf(CTDL_DEBUG, "Initializing master fdset\n");
969 lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
970 FD_SET(rescan[0], &masterfds);
971 if (rescan[0] > masterhighest) masterhighest = rescan[0];
973 for (serviceptr = ServiceHookTable; serviceptr != NULL;
974 serviceptr = serviceptr->next ) {
975 m = serviceptr->msock;
976 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
977 FD_SET(m, &masterfds);
978 if (m > masterhighest) {
982 lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
987 * Bind a thread to a context. (It's inline merely to speed things up.)
989 INLINE void become_session(struct CitContext *which_con) {
990 pthread_setspecific(MyConKey, (void *)which_con );
996 * This loop just keeps going and going and going...
998 void *worker_thread(void *arg) {
1002 /* This is synchronized below; it helps implement round robin mode */
1003 static struct CitContext* next_session = NULL;
1004 struct CitContext *ptr;
1005 struct CitContext *bind_me = NULL;
1008 struct CitContext *con= NULL; /* Temporary context pointer */
1009 struct ServiceFunctionHook *serviceptr;
1010 int ssock; /* Descriptor for client socket */
1017 while (!time_to_die) {
1020 * A naive implementation would have all idle threads
1021 * calling select() and then they'd all wake up at once
1022 * (known in computer science as the "thundering herd"
1023 * problem). We solve this problem by putting the select()
1024 * in a critical section, so only one thread has the
1025 * opportunity to wake up. If we wake up on a master
1026 * socket, create a new session context; otherwise, just
1027 * bind the thread to the context we want and go on our
1031 /* make doubly sure we're not holding any stale db handles
1032 * which might cause a deadlock.
1034 cdb_check_handles();
1036 begin_critical_section(S_I_WANNA_SELECT);
1037 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1038 highest = masterhighest;
1039 begin_critical_section(S_SESSION_TABLE);
1040 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1041 if (ptr->state == CON_IDLE) {
1042 FD_SET(ptr->client_socket, &readfds);
1043 if (ptr->client_socket > highest)
1044 highest = ptr->client_socket;
1047 end_critical_section(S_SESSION_TABLE);
1049 tv.tv_sec = 1; /* wake up every second if no input */
1054 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1056 end_critical_section(S_I_WANNA_SELECT);
1060 /* Now figure out who made this select() unblock.
1061 * First, check for an error or exit condition.
1064 if (errno != EINTR) {
1065 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1067 } else if (!time_to_die)
1071 /* Next, check to see if it's a new client connecting
1072 * on a master socket.
1074 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1075 serviceptr = serviceptr->next ) {
1077 if (FD_ISSET(serviceptr->msock, &readfds)) {
1078 ssock = accept(serviceptr->msock, NULL, 0);
1081 "citserver: accept(): %s\n",
1085 lprintf(CTDL_NOTICE,
1086 "New client socket %d\n",
1089 /* New context will be created already
1090 * set up in the CON_EXECUTING state.
1092 con = CreateNewContext();
1094 /* Assign new socket number to it. */
1095 con->client_socket = ssock;
1096 con->h_command_function =
1097 serviceptr->h_command_function;
1099 /* Determine whether local socket */
1100 if (serviceptr->sockpath != NULL)
1101 con->is_local_socket = 1;
1103 /* Set the SO_REUSEADDR socket option */
1105 setsockopt(ssock, SOL_SOCKET,
1109 become_session(con);
1111 serviceptr->h_greeting_function();
1112 become_session(NULL);
1113 con->state = CON_IDLE;
1119 /* If the rescan pipe went active, someone is telling this
1120 * thread that the &readfds needs to be refreshed with more
1124 end_critical_section(S_I_WANNA_SELECT);
1128 if (FD_ISSET(rescan[0], &readfds)) {
1129 read(rescan[0], &junk, 1);
1133 /* It must be a client socket. Find a context that has data
1134 * waiting on its socket *and* is in the CON_IDLE state.
1138 begin_critical_section(S_SESSION_TABLE);
1140 * We start where we left off. If we get to the end
1141 * we'll start from the beginning again, then give up
1142 * if we still don't find anything. This ensures
1143 * that all contexts get a more-or-less equal chance
1144 * to run. And yes, I did add a goto to the code. -IO
1146 find_session: if (next_session == NULL)
1147 next_session = ContextList;
1148 for (ptr = next_session;
1149 ( (ptr != NULL) && (bind_me == NULL) );
1151 if ( (FD_ISSET(ptr->client_socket, &readfds))
1152 && (ptr->state == CON_IDLE) ) {
1156 if (bind_me != NULL) {
1157 /* Found one. Stake a claim to it before
1158 * letting anyone else touch the context list.
1160 bind_me->state = CON_EXECUTING;
1161 next_session = bind_me->next;
1162 } else if (next_session == ContextList) {
1163 next_session = NULL;
1165 if (bind_me == NULL && next_session != NULL) {
1166 next_session = NULL;
1170 end_critical_section(S_SESSION_TABLE);
1171 end_critical_section(S_I_WANNA_SELECT);
1173 /* We're bound to a session, now do *one* command */
1174 if (bind_me != NULL) {
1175 become_session(bind_me);
1176 CC->h_command_function();
1177 become_session(NULL);
1178 bind_me->state = CON_IDLE;
1179 if (bind_me->kill_me == 1) {
1180 RemoveContext(bind_me);
1182 write(rescan[1], &junk, 1);
1186 dead_session_purge();
1188 check_sched_shutdown();
1191 /* If control reaches this point, the server is shutting down */
1201 * Translate text facility name to syslog.h defined value.
1203 int SyslogFacility(char *name)
1212 { LOG_KERN, "kern" },
1213 { LOG_USER, "user" },
1214 { LOG_MAIL, "mail" },
1215 { LOG_DAEMON, "daemon" },
1216 { LOG_AUTH, "auth" },
1217 { LOG_SYSLOG, "syslog" },
1219 { LOG_NEWS, "news" },
1220 { LOG_UUCP, "uucp" },
1221 { LOG_LOCAL0, "local0" },
1222 { LOG_LOCAL1, "local1" },
1223 { LOG_LOCAL2, "local2" },
1224 { LOG_LOCAL3, "local3" },
1225 { LOG_LOCAL4, "local4" },
1226 { LOG_LOCAL5, "local5" },
1227 { LOG_LOCAL6, "local6" },
1228 { LOG_LOCAL7, "local7" },
1231 for(i = 0; facTbl[i].name != NULL; i++) {
1232 if(!strcasecmp(name, facTbl[i].name))
1233 return facTbl[i].facility;