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.
23 #include <sys/types.h>
26 #include <sys/socket.h>
29 #include <netinet/in.h>
46 #include "sysdep_decls.h"
47 #include "citserver.h"
51 #include "housekeeping.h"
52 #include "dynloader.h"
55 #ifdef HAVE_SYS_SELECT_H
56 #include <sys/select.h>
63 #ifdef DEBUG_MEMORY_LEAKS
64 struct TheHeap *heap = NULL;
67 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
68 pthread_key_t MyConKey; /* TSD key for MyContext() */
70 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
72 struct CitContext masterCC;
73 int rescan[2]; /* The Rescan Pipe */
74 time_t last_purge = 0; /* Last dead session purge */
75 int num_threads = 0; /* Current number of threads */
76 int num_sessions = 0; /* Current number of sessions */
78 fd_set masterfds; /* Master sockets etc. */
81 time_t last_timer = 0L; /* Last timer hook processing */
85 * lprintf() ... Write logging information
87 void lprintf(int loglevel, const char *format, ...) {
91 va_start(arg_ptr, format);
92 vsprintf(buf, format, arg_ptr);
95 if (loglevel <= verbosity) {
96 fprintf(stderr, "%s", buf);
100 PerformLogHooks(loglevel, buf);
105 #ifdef DEBUG_MEMORY_LEAKS
106 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
108 struct TheHeap *hptr;
112 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
113 tsize, tfile, tline);
117 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
118 strcpy(hptr->h_file, tfile);
119 hptr->h_line = tline;
126 char *tracked_strdup(const char *orig, char *tfile, int tline) {
129 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
130 if (s == NULL) return NULL;
136 void tracked_free(void *ptr) {
137 struct TheHeap *hptr, *freeme;
139 if (heap->h_ptr == ptr) {
145 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
146 if (hptr->next->h_ptr == ptr) {
148 hptr->next = hptr->next->next;
157 void *tracked_realloc(void *ptr, size_t size) {
159 struct TheHeap *hptr;
161 newptr = realloc(ptr, size);
163 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
164 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
171 void dump_tracked() {
172 struct TheHeap *hptr;
174 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
175 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
176 cprintf("%20s %5d\n",
177 hptr->h_file, hptr->h_line);
189 * We used to use master_cleanup() as a signal handler to shut down the server.
190 * however, master_cleanup() and the functions it calls do some things that
191 * aren't such a good idea to do from a signal handler: acquiring mutexes,
192 * playing with signal masks on BSDI systems, etc. so instead we install the
193 * following signal handler to set a global variable to inform the main loop
194 * that it's time to call master_cleanup() and exit.
197 static volatile int time_to_die = 0;
199 static RETSIGTYPE signal_cleanup(int signum) {
205 * Some initialization stuff...
207 void init_sysdep(void) {
210 /* Set up a bunch of semaphores to be used for critical sections */
211 for (a=0; a<MAX_SEMAPHORES; ++a) {
212 pthread_mutex_init(&Critters[a], NULL);
216 * Set up a place to put thread-specific data.
217 * We only need a single pointer per thread - it points to the
218 * CitContext structure (in the ContextList linked list) of the
219 * session to which the calling thread is currently bound.
221 if (pthread_key_create(&MyConKey, NULL) != 0) {
222 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
226 * The action for unexpected signals and exceptions should be to
227 * call signal_cleanup() to gracefully shut down the server.
229 signal(SIGINT, signal_cleanup);
230 signal(SIGQUIT, signal_cleanup);
231 signal(SIGHUP, signal_cleanup);
232 signal(SIGTERM, signal_cleanup);
235 * Do not shut down the server on broken pipe signals, otherwise the
236 * whole Citadel service would come down whenever a single client
239 signal(SIGPIPE, SIG_IGN);
244 * Obtain a semaphore lock to begin a critical section.
246 void begin_critical_section(int which_one)
248 /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
249 pthread_mutex_lock(&Critters[which_one]);
253 * Release a semaphore lock to end a critical section.
255 void end_critical_section(int which_one)
257 /* lprintf(9, "end_critical_section(%d)\n", which_one); */
258 pthread_mutex_unlock(&Critters[which_one]);
264 * This is a generic function to set up a master socket for listening on
265 * a TCP port. The server shuts down if the bind fails.
268 int ig_tcp_server(int port_number, int queue_len)
270 struct sockaddr_in sin;
272 int actual_queue_len;
274 actual_queue_len = queue_len;
275 if (actual_queue_len < 5) actual_queue_len = 5;
277 memset(&sin, 0, sizeof(sin));
278 sin.sin_family = AF_INET;
279 sin.sin_addr.s_addr = INADDR_ANY;
280 sin.sin_port = htons((u_short)port_number);
282 s = socket(PF_INET, SOCK_STREAM,
283 (getprotobyname("tcp")->p_proto));
286 lprintf(1, "citserver: Can't create a socket: %s\n",
292 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
294 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
295 lprintf(1, "citserver: Can't bind: %s\n",
301 if (listen(s, actual_queue_len) < 0) {
302 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
313 * Create a Unix domain socket and listen on it
315 int ig_uds_server(char *sockpath, int queue_len)
317 struct sockaddr_un addr;
320 int actual_queue_len;
322 actual_queue_len = queue_len;
323 if (actual_queue_len < 5) actual_queue_len = 5;
325 i = unlink(sockpath);
326 if (i != 0) if (errno != ENOENT) {
327 lprintf(1, "citserver: can't unlink %s: %s\n",
328 sockpath, strerror(errno));
332 memset(&addr, 0, sizeof(addr));
333 addr.sun_family = AF_UNIX;
334 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
336 s = socket(AF_UNIX, SOCK_STREAM, 0);
338 lprintf(1, "citserver: Can't create a socket: %s\n",
343 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
344 lprintf(1, "citserver: Can't bind: %s\n",
349 if (listen(s, actual_queue_len) < 0) {
350 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
354 chmod(sockpath, 0777);
361 * Return a pointer to the CitContext structure bound to the thread which
362 * called this function. If there's no such binding (for example, if it's
363 * called by the housekeeper thread) then a generic 'master' CC is returned.
365 struct CitContext *MyContext(void) {
366 struct CitContext *retCC;
367 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
368 if (retCC == NULL) retCC = &masterCC;
374 * Initialize a new context and place it in the list. The session number
375 * used to be the PID (which is why it's called cs_pid), but that was when we
376 * had one process per session. Now we just assign them sequentially, starting
377 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
378 * sessions terminate.
380 struct CitContext *CreateNewContext(void) {
381 struct CitContext *me, *ptr;
385 me = (struct CitContext *) mallok(sizeof(struct CitContext));
387 lprintf(1, "citserver: can't allocate memory!!\n");
390 memset(me, 0, sizeof(struct CitContext));
392 /* The new context will be created already in the CON_EXECUTING state
393 * in order to prevent another thread from grabbing it while it's
396 me->state = CON_EXECUTING;
398 begin_critical_section(S_SESSION_TABLE);
400 /* obtain a unique session number */
403 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
404 if (ptr->cs_pid == num) {
409 } while (startover == 1);
412 me->next = ContextList;
416 end_critical_section(S_SESSION_TABLE);
423 * client_write() ... Send binary data to the client.
425 void client_write(char *buf, int nbytes)
427 int bytes_written = 0;
431 if (CC->redirect_fp != NULL) {
432 fwrite(buf, nbytes, 1, CC->redirect_fp);
436 if (CC->redirect_sock > 0) {
437 sock = CC->redirect_sock; /* and continue below... */
440 sock = CC->client_socket;
443 while (bytes_written < nbytes) {
444 retval = write(sock, &buf[bytes_written],
445 nbytes - bytes_written);
447 lprintf(2, "client_write() failed: %s\n",
449 if (sock == CC->client_socket) CC->kill_me = 1;
452 bytes_written = bytes_written + retval;
458 * cprintf() ... Send formatted printable data to the client. It is
459 * implemented in terms of client_write() but remains in
460 * sysdep.c in case we port to somewhere without va_args...
462 void cprintf(const char *format, ...) {
466 va_start(arg_ptr, format);
467 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
468 buf[sizeof buf - 2] = '\n';
469 client_write(buf, strlen(buf));
475 * Read data from the client socket.
477 * 1 Requested number of bytes has been read.
478 * 0 Request timed out.
479 * -1 The socket is broken.
480 * If the socket breaks, the session will be terminated.
482 int client_read_to(char *buf, int bytes, int timeout)
492 FD_SET(CC->client_socket, &rfds);
496 retval = select( (CC->client_socket)+1,
497 &rfds, NULL, NULL, &tv);
499 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
503 rlen = read(CC->client_socket, &buf[len], bytes-len);
505 lprintf(2, "client_read() failed: %s\n",
516 * Read data from the client socket with default timeout.
517 * (This is implemented in terms of client_read_to() and could be
518 * justifiably moved out of sysdep.c)
520 int client_read(char *buf, int bytes)
522 return(client_read_to(buf, bytes, config.c_sleeping));
527 * client_gets() ... Get a LF-terminated line of text from the client.
528 * (This is implemented in terms of client_read() and could be
529 * justifiably moved out of sysdep.c)
531 int client_gets(char *buf)
535 /* Read one character at a time.
538 retval = client_read(&buf[i], 1);
539 if (retval != 1 || buf[i] == '\n' || i == 255)
543 /* If we got a long line, discard characters until the newline.
546 while (buf[i] != '\n' && retval == 1)
547 retval = client_read(&buf[i], 1);
549 /* Strip the trailing newline and any trailing nonprintables (cr's)
552 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
553 buf[strlen(buf)-1] = 0;
554 if (retval < 0) strcpy(buf, "000");
561 * The system-dependent part of master_cleanup() - close the master socket.
563 void sysdep_master_cleanup(void) {
564 struct ServiceFunctionHook *serviceptr;
567 * close all protocol master sockets
569 for (serviceptr = ServiceHookTable; serviceptr != NULL;
570 serviceptr = serviceptr->next ) {
572 if (serviceptr->tcp_port > 0)
573 lprintf(3, "Closing listener on port %d\n",
574 serviceptr->tcp_port);
576 if (serviceptr->sockpath != NULL)
577 lprintf(3, "Closing listener on '%s'\n",
578 serviceptr->sockpath);
580 close(serviceptr->msock);
582 /* If it's a Unix domain socket, remove the file. */
583 if (serviceptr->sockpath != NULL) {
584 unlink(serviceptr->sockpath);
591 * Terminate another session.
592 * (This could justifiably be moved out of sysdep.c because it
593 * no longer does anything that is system-dependent.)
595 void kill_session(int session_to_kill) {
596 struct CitContext *ptr;
598 begin_critical_section(S_SESSION_TABLE);
599 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
600 if (ptr->cs_pid == session_to_kill) {
604 end_critical_section(S_SESSION_TABLE);
611 * Start running as a daemon. Only close stdio if do_close_stdio is set.
613 void start_daemon(int do_close_stdio) {
614 if (do_close_stdio) {
619 signal(SIGHUP,SIG_IGN);
620 signal(SIGINT,SIG_IGN);
621 signal(SIGQUIT,SIG_IGN);
622 if (fork()!=0) exit(0);
628 * Tie in to the 'netsetup' program.
630 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
632 void cmd_nset(char *cmdbuf)
639 char netsetup_args[3][256];
641 if (CC->usersupp.axlevel < 6) {
642 cprintf("%d Higher access required.\n",
643 ERROR + HIGHER_ACCESS_REQUIRED);
647 for (a=1; a<=3; ++a) {
648 if (num_parms(cmdbuf) >= a) {
649 extract(netsetup_args[a-1], cmdbuf, a-1);
650 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
651 if (netsetup_args[a-1][b] == 34) {
652 netsetup_args[a-1][b] = '_';
657 netsetup_args[a-1][0] = 0;
661 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
662 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
663 netsetup = popen(fbuf, "r");
664 if (netsetup == NULL) {
665 cprintf("%d %s\n", ERROR, strerror(errno));
670 while (ch = getc(netsetup), (ch > 0)) {
671 fbuf[strlen(fbuf)+1] = 0;
672 fbuf[strlen(fbuf)] = ch;
675 retcode = pclose(netsetup);
678 for (a=0; a<strlen(fbuf); ++a) {
679 if (fbuf[a] < 32) fbuf[a] = 32;
682 cprintf("%d %s\n", ERROR, fbuf);
686 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
688 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
695 * Generic routine to convert a login name to a full name (gecos)
696 * Returns nonzero if a conversion took place
698 int convert_login(char NameToConvert[]) {
702 pw = getpwnam(NameToConvert);
707 strcpy(NameToConvert, pw->pw_gecos);
708 for (a=0; a<strlen(NameToConvert); ++a) {
709 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
718 * Purge all sessions which have the 'kill_me' flag set.
719 * This function has code to prevent it from running more than once every
720 * few seconds, because running it after every single unbind would waste a lot
721 * of CPU time and keep the context list locked too much.
723 * After that's done, we raise or lower the size of the worker thread pool
724 * if such an action is appropriate.
726 void dead_session_purge(void) {
727 struct CitContext *ptr, *rem;
731 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
736 begin_critical_section(S_SESSION_TABLE);
737 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
738 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
742 end_critical_section(S_SESSION_TABLE);
744 /* RemoveContext() enters its own S_SESSION_TABLE critical
745 * section, so we have to do it like this.
748 lprintf(9, "Purging session %d\n", rem->cs_pid);
752 } while (rem != NULL);
755 /* Raise or lower the size of the worker thread pool if such
756 * an action is appropriate.
759 if ( (num_sessions > num_threads)
760 && (num_threads < config.c_max_workers) ) {
762 pthread_attr_init(&attr);
763 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
764 if (pthread_create(&newthread, &attr,
765 (void* (*)(void*)) worker_thread, NULL) != 0) {
766 lprintf(1, "Can't create worker thead: %s\n",
772 else if ( (num_sessions < num_threads)
773 && (num_threads > config.c_min_workers) ) {
785 * Redirect a session's output to a file or socket.
786 * This function may be called with a file handle *or* a socket (but not
787 * both). Call with neither to return output to its normal client socket.
789 void CtdlRedirectOutput(FILE *fp, int sock) {
791 if (fp != NULL) CC->redirect_fp = fp;
792 else CC->redirect_fp = NULL;
794 if (sock > 0) CC->redirect_sock = sock;
795 else CC->redirect_sock = (-1);
801 * masterCC is the context we use when not attached to a session. This
802 * function initializes it.
804 void InitializeMasterCC(void) {
805 memset(&masterCC, 0, sizeof(struct CitContext));
806 masterCC.internal_pgm = 1;
813 * Set up a fd_set containing all the master sockets to which we
814 * always listen. It's computationally less expensive to just copy
815 * this to a local fd_set when starting a new select() and then add
816 * the client sockets than it is to initialize a new one and then
817 * figure out what to put there.
819 void init_master_fdset(void) {
820 struct ServiceFunctionHook *serviceptr;
823 lprintf(9, "Initializing master fdset\n");
828 lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
829 FD_SET(rescan[0], &masterfds);
830 if (rescan[0] > masterhighest) masterhighest = rescan[0];
832 for (serviceptr = ServiceHookTable; serviceptr != NULL;
833 serviceptr = serviceptr->next ) {
834 m = serviceptr->msock;
835 lprintf(9, "Will listen on master socket %d\n", m);
836 FD_SET(m, &masterfds);
837 if (m > masterhighest) {
841 lprintf(9, "masterhighest = %d\n", masterhighest);
847 * Here's where it all begins.
849 int main(int argc, char **argv)
851 pthread_t WorkerThread; /* Thread descriptor */
852 pthread_attr_t attr; /* Thread attributes */
853 char tracefile[128]; /* Name of file to log traces to */
854 int a, i; /* General-purpose variables */
856 int drop_root_perms = 1;
859 /* specify default port name and trace file */
860 strcpy(tracefile, "");
862 /* initialize the master context */
863 InitializeMasterCC();
865 /* parse command-line arguments */
866 for (a=1; a<argc; ++a) {
868 /* -t specifies where to log trace messages to */
869 if (!strncmp(argv[a], "-t", 2)) {
870 strcpy(tracefile, argv[a]);
871 strcpy(tracefile, &tracefile[2]);
872 freopen(tracefile, "r", stdin);
873 freopen(tracefile, "w", stdout);
874 freopen(tracefile, "w", stderr);
877 /* run in the background if -d was specified */
878 else if (!strcmp(argv[a], "-d")) {
879 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
882 /* -x specifies the desired logging level */
883 else if (!strncmp(argv[a], "-x", 2)) {
884 verbosity = atoi(&argv[a][2]);
887 else if (!strncmp(argv[a], "-h", 2)) {
888 safestrncpy(bbs_home_directory, &argv[a][2],
889 sizeof bbs_home_directory);
893 else if (!strncmp(argv[a], "-f", 2)) {
897 /* -r tells the server not to drop root permissions. don't use
898 * this unless you know what you're doing. this should be
899 * removed in the next release if it proves unnecessary. */
900 else if (!strcmp(argv[a], "-r"))
903 /* any other parameter makes it crash and burn */
905 lprintf(1, "citserver: usage: "
906 "citserver [-tTraceFile] [-d] [-f]"
907 " [-xLogLevel] [-hHomeDir]\n");
913 /* Tell 'em who's in da house */
915 "\nMultithreaded message server for Citadel/UX\n"
916 "Copyright (C) 1987-2000 by the Citadel/UX development team.\n"
917 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
918 "you are welcome to change it and/or distribute copies of it under certain\n"
919 "conditions. There is absolutely no warranty for this software. Please\n"
920 "read the 'COPYING.txt' file for details.\n\n");
924 openlog("citserver", LOG_PID, LOG_USER);
926 /* Load site-specific parameters */
927 lprintf(7, "Loading citadel.config\n");
932 * Do non system dependent startup functions.
937 * Bind the server to a Unix-domain socket.
939 CtdlRegisterServiceHook(0,
941 citproto_begin_session,
945 * Bind the server to our favorite TCP port (usually 504).
947 CtdlRegisterServiceHook(config.c_port_number,
949 citproto_begin_session,
953 * Load any server-side modules (plugins) available here.
955 lprintf(7, "Initializing loadable modules\n");
956 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
957 sprintf(moddir, "%s/modules", bbs_home_directory);
958 DLoader_Init(moddir);
963 * The rescan pipe exists so that worker threads can be woken up and
964 * told to re-scan the context list for fd's to listen on. This is
965 * necessary, for example, when a context is about to go idle and needs
966 * to get back on that list.
969 lprintf(1, "Can't create rescan pipe!\n");
976 * Now that we've bound the sockets, change to the BBS user id and its
977 * corresponding group ids
979 if (drop_root_perms) {
980 if ((pw = getpwuid(BBSUID)) == NULL)
981 lprintf(1, "WARNING: getpwuid(%d): %s\n"
982 "Group IDs will be incorrect.\n", BBSUID,
985 initgroups(pw->pw_name, pw->pw_gid);
986 if (setgid(pw->pw_gid))
987 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
990 lprintf(7, "Changing uid to %d\n", BBSUID);
991 if (setuid(BBSUID) != 0) {
992 lprintf(3, "setuid() failed: %s\n", strerror(errno));
996 /* We want to check for idle sessions once per minute */
997 CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
1000 * Now create a bunch of worker threads.
1002 for (i=0; i<(config.c_min_workers-1); ++i) {
1003 pthread_attr_init(&attr);
1004 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1005 if (pthread_create(&WorkerThread, &attr,
1006 (void* (*)(void*)) worker_thread, NULL) != 0) {
1007 lprintf(1, "Can't create worker thead: %s\n",
1013 /* Now this thread can become a worker as well. */
1021 * Bind a thread to a context. (It's inline merely to speed things up.)
1023 inline void become_session(struct CitContext *which_con) {
1024 pthread_setspecific(MyConKey, (void *)which_con );
1030 * This loop just keeps going and going and going...
1032 void worker_thread(void) {
1036 struct CitContext *ptr;
1037 struct CitContext *bind_me = NULL;
1040 struct CitContext *con= NULL; /* Temporary context pointer */
1041 struct ServiceFunctionHook *serviceptr;
1042 struct sockaddr_in fsin; /* Data for master socket */
1043 int alen; /* Data for master socket */
1044 int ssock; /* Descriptor for client socket */
1049 while (!time_to_die) {
1053 * A naive implementation would have all idle threads
1054 * calling select() and then they'd all wake up at once. We
1055 * solve this problem by putting the select() in a critical
1056 * section, so only one thread has the opportunity to wake
1057 * up. If we wake up on a master socket, create a new
1058 * session context; otherwise, just bind the thread to the
1059 * context we want and go on our merry way.
1062 begin_critical_section(S_I_WANNA_SELECT);
1063 cdb_end_transaction();
1064 cdb_begin_transaction();
1065 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1066 highest = masterhighest;
1067 begin_critical_section(S_SESSION_TABLE);
1068 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1069 if (ptr->state == CON_IDLE) {
1070 FD_SET(ptr->client_socket, &readfds);
1071 if (ptr->client_socket > highest)
1072 highest = ptr->client_socket;
1075 end_critical_section(S_SESSION_TABLE);
1077 tv.tv_sec = 60; /* wake up every minute if no input */
1079 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1081 /* Now figure out who made this select() unblock.
1082 * First, check for an error or exit condition.
1085 end_critical_section(S_I_WANNA_SELECT);
1086 lprintf(9, "Exiting (%s)\n", strerror(errno));
1090 /* Next, check to see if it's a new client connecting
1091 * on a master socket.
1093 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1094 serviceptr = serviceptr->next ) {
1096 if (FD_ISSET(serviceptr->msock, &readfds)) {
1098 ssock = accept(serviceptr->msock,
1099 (struct sockaddr *)&fsin, &alen);
1101 lprintf(2, "citserver: accept(): %s\n",
1105 lprintf(7, "citserver: "
1106 "New client socket %d\n",
1109 /* New context will be created already
1110 * set up in the CON_EXECUTING state.
1112 con = CreateNewContext();
1114 /* Assign new socket number to it. */
1115 con->client_socket = ssock;
1116 con->h_command_function =
1117 serviceptr->h_command_function;
1119 /* Determine whether local socket */
1120 if (serviceptr->sockpath != NULL)
1121 con->is_local_socket = 1;
1123 /* Set the SO_REUSEADDR socket option */
1125 setsockopt(ssock, SOL_SOCKET,
1129 become_session(con);
1131 serviceptr->h_greeting_function();
1132 become_session(NULL);
1133 con->state = CON_IDLE;
1139 /* If the rescan pipe went active, someone is telling this
1140 * thread that the &readfds needs to be refreshed with more
1146 if (FD_ISSET(rescan[0], &readfds)) {
1147 read(rescan[0], &junk, 1);
1151 /* It must be a client socket. Find a context that has data
1152 * waiting on its socket *and* is in the CON_IDLE state.
1156 begin_critical_section(S_SESSION_TABLE);
1157 for (ptr = ContextList;
1158 ( (ptr != NULL) && (bind_me == NULL) );
1160 if ( (FD_ISSET(ptr->client_socket, &readfds))
1161 && (ptr->state == CON_IDLE) ) {
1165 if (bind_me != NULL) {
1166 /* Found one. Stake a claim to it before
1167 * letting anyone else touch the context list.
1169 bind_me->state = CON_EXECUTING;
1172 end_critical_section(S_SESSION_TABLE);
1173 end_critical_section(S_I_WANNA_SELECT);
1175 /* We're bound to a session, now do *one* command */
1176 if (bind_me != NULL) {
1177 become_session(bind_me);
1178 CC->h_command_function();
1179 become_session(NULL);
1180 bind_me->state = CON_IDLE;
1181 if (bind_me->kill_me == 1) {
1182 RemoveContext(bind_me);
1184 write(rescan[1], &junk, 1);
1188 dead_session_purge();
1189 if ((time(NULL) - last_timer) > 60L) {
1190 last_timer = time(NULL);
1191 PerformSessionHooks(EVT_TIMER);
1194 check_sched_shutdown();
1197 /* If control reaches this point, the server is shutting down */