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 static 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 */
83 static pthread_t initial_thread; /* tid for main() thread */
87 * lprintf() ... Write logging information
89 void lprintf(int loglevel, const char *format, ...) {
93 va_start(arg_ptr, format);
94 vsprintf(buf, format, arg_ptr);
97 if (loglevel <= verbosity) {
98 fprintf(stderr, "%s", buf);
102 PerformLogHooks(loglevel, buf);
107 #ifdef DEBUG_MEMORY_LEAKS
108 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
110 struct TheHeap *hptr;
114 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
115 tsize, tfile, tline);
119 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
120 strcpy(hptr->h_file, tfile);
121 hptr->h_line = tline;
128 char *tracked_strdup(const char *orig, char *tfile, int tline) {
131 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
132 if (s == NULL) return NULL;
138 void tracked_free(void *ptr) {
139 struct TheHeap *hptr, *freeme;
141 if (heap->h_ptr == ptr) {
147 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
148 if (hptr->next->h_ptr == ptr) {
150 hptr->next = hptr->next->next;
159 void *tracked_realloc(void *ptr, size_t size) {
161 struct TheHeap *hptr;
163 newptr = realloc(ptr, size);
165 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
166 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
173 void dump_tracked() {
174 struct TheHeap *hptr;
176 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
177 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
178 cprintf("%20s %5d\n",
179 hptr->h_file, hptr->h_line);
191 * We used to use master_cleanup() as a signal handler to shut down the server.
192 * however, master_cleanup() and the functions it calls do some things that
193 * aren't such a good idea to do from a signal handler: acquiring mutexes,
194 * playing with signal masks on BSDI systems, etc. so instead we install the
195 * following signal handler to set a global variable to inform the main loop
196 * that it's time to call master_cleanup() and exit.
199 volatile int time_to_die = 0;
201 static RETSIGTYPE signal_cleanup(int signum) {
207 * Some initialization stuff...
209 void init_sysdep(void) {
212 /* Set up a bunch of semaphores to be used for critical sections */
213 for (a=0; a<MAX_SEMAPHORES; ++a) {
214 pthread_mutex_init(&Critters[a], NULL);
218 * Set up a place to put thread-specific data.
219 * We only need a single pointer per thread - it points to the
220 * CitContext structure (in the ContextList linked list) of the
221 * session to which the calling thread is currently bound.
223 if (pthread_key_create(&MyConKey, NULL) != 0) {
224 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
228 * The action for unexpected signals and exceptions should be to
229 * call signal_cleanup() to gracefully shut down the server.
231 signal(SIGINT, signal_cleanup);
232 signal(SIGQUIT, signal_cleanup);
233 signal(SIGHUP, signal_cleanup);
234 signal(SIGTERM, signal_cleanup);
237 * Do not shut down the server on broken pipe signals, otherwise the
238 * whole Citadel service would come down whenever a single client
241 signal(SIGPIPE, SIG_IGN);
246 * Obtain a semaphore lock to begin a critical section.
248 void begin_critical_section(int which_one)
250 /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
251 pthread_mutex_lock(&Critters[which_one]);
255 * Release a semaphore lock to end a critical section.
257 void end_critical_section(int which_one)
259 /* lprintf(9, "end_critical_section(%d)\n", which_one); */
260 pthread_mutex_unlock(&Critters[which_one]);
266 * This is a generic function to set up a master socket for listening on
267 * a TCP port. The server shuts down if the bind fails.
270 int ig_tcp_server(int port_number, int queue_len)
272 struct sockaddr_in sin;
274 int actual_queue_len;
276 actual_queue_len = queue_len;
277 if (actual_queue_len < 5) actual_queue_len = 5;
279 memset(&sin, 0, sizeof(sin));
280 sin.sin_family = AF_INET;
281 sin.sin_addr.s_addr = INADDR_ANY;
282 sin.sin_port = htons((u_short)port_number);
284 s = socket(PF_INET, SOCK_STREAM,
285 (getprotobyname("tcp")->p_proto));
288 lprintf(1, "citserver: Can't create a socket: %s\n",
294 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
296 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
297 lprintf(1, "citserver: Can't bind: %s\n",
303 if (listen(s, actual_queue_len) < 0) {
304 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
315 * Create a Unix domain socket and listen on it
317 int ig_uds_server(char *sockpath, int queue_len)
319 struct sockaddr_un addr;
322 int actual_queue_len;
324 actual_queue_len = queue_len;
325 if (actual_queue_len < 5) actual_queue_len = 5;
327 i = unlink(sockpath);
328 if (i != 0) if (errno != ENOENT) {
329 lprintf(1, "citserver: can't unlink %s: %s\n",
330 sockpath, strerror(errno));
334 memset(&addr, 0, sizeof(addr));
335 addr.sun_family = AF_UNIX;
336 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
338 s = socket(AF_UNIX, SOCK_STREAM, 0);
340 lprintf(1, "citserver: Can't create a socket: %s\n",
345 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
346 lprintf(1, "citserver: Can't bind: %s\n",
351 if (listen(s, actual_queue_len) < 0) {
352 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
356 chmod(sockpath, 0777);
363 * Return a pointer to the CitContext structure bound to the thread which
364 * called this function. If there's no such binding (for example, if it's
365 * called by the housekeeper thread) then a generic 'master' CC is returned.
367 struct CitContext *MyContext(void) {
368 struct CitContext *retCC;
369 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
370 if (retCC == NULL) retCC = &masterCC;
376 * Initialize a new context and place it in the list. The session number
377 * used to be the PID (which is why it's called cs_pid), but that was when we
378 * had one process per session. Now we just assign them sequentially, starting
379 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
380 * sessions terminate.
382 struct CitContext *CreateNewContext(void) {
383 struct CitContext *me, *ptr;
387 me = (struct CitContext *) mallok(sizeof(struct CitContext));
389 lprintf(1, "citserver: can't allocate memory!!\n");
392 memset(me, 0, sizeof(struct CitContext));
394 /* The new context will be created already in the CON_EXECUTING state
395 * in order to prevent another thread from grabbing it while it's
398 me->state = CON_EXECUTING;
400 begin_critical_section(S_SESSION_TABLE);
402 /* obtain a unique session number */
405 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
406 if (ptr->cs_pid == num) {
411 } while (startover == 1);
414 me->next = ContextList;
418 end_critical_section(S_SESSION_TABLE);
425 * client_write() ... Send binary data to the client.
427 void client_write(char *buf, int nbytes)
429 int bytes_written = 0;
433 if (CC->redirect_fp != NULL) {
434 fwrite(buf, nbytes, 1, CC->redirect_fp);
438 if (CC->redirect_sock > 0) {
439 sock = CC->redirect_sock; /* and continue below... */
442 sock = CC->client_socket;
445 while (bytes_written < nbytes) {
446 retval = write(sock, &buf[bytes_written],
447 nbytes - bytes_written);
449 lprintf(2, "client_write() failed: %s\n",
451 if (sock == CC->client_socket) CC->kill_me = 1;
454 bytes_written = bytes_written + retval;
460 * cprintf() ... Send formatted printable data to the client. It is
461 * implemented in terms of client_write() but remains in
462 * sysdep.c in case we port to somewhere without va_args...
464 void cprintf(const char *format, ...) {
468 va_start(arg_ptr, format);
469 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
470 buf[sizeof buf - 2] = '\n';
471 client_write(buf, strlen(buf));
477 * Read data from the client socket.
479 * 1 Requested number of bytes has been read.
480 * 0 Request timed out.
481 * -1 The socket is broken.
482 * If the socket breaks, the session will be terminated.
484 int client_read_to(char *buf, int bytes, int timeout)
494 FD_SET(CC->client_socket, &rfds);
498 retval = select( (CC->client_socket)+1,
499 &rfds, NULL, NULL, &tv);
501 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
505 rlen = read(CC->client_socket, &buf[len], bytes-len);
507 lprintf(2, "client_read() failed: %s\n",
518 * Read data from the client socket with default timeout.
519 * (This is implemented in terms of client_read_to() and could be
520 * justifiably moved out of sysdep.c)
522 int client_read(char *buf, int bytes)
524 return(client_read_to(buf, bytes, config.c_sleeping));
529 * client_gets() ... Get a LF-terminated line of text from the client.
530 * (This is implemented in terms of client_read() and could be
531 * justifiably moved out of sysdep.c)
533 int client_gets(char *buf)
537 /* Read one character at a time.
540 retval = client_read(&buf[i], 1);
541 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
545 /* If we got a long line, discard characters until the newline.
548 while (buf[i] != '\n' && retval == 1)
549 retval = client_read(&buf[i], 1);
551 /* Strip the trailing newline and any trailing nonprintables (cr's)
554 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
555 buf[strlen(buf)-1] = 0;
556 if (retval < 0) strcpy(buf, "000");
563 * The system-dependent part of master_cleanup() - close the master socket.
565 void sysdep_master_cleanup(void) {
566 struct ServiceFunctionHook *serviceptr;
569 * close all protocol master sockets
571 for (serviceptr = ServiceHookTable; serviceptr != NULL;
572 serviceptr = serviceptr->next ) {
574 if (serviceptr->tcp_port > 0)
575 lprintf(3, "Closing listener on port %d\n",
576 serviceptr->tcp_port);
578 if (serviceptr->sockpath != NULL)
579 lprintf(3, "Closing listener on '%s'\n",
580 serviceptr->sockpath);
582 close(serviceptr->msock);
584 /* If it's a Unix domain socket, remove the file. */
585 if (serviceptr->sockpath != NULL) {
586 unlink(serviceptr->sockpath);
593 * Terminate another session.
594 * (This could justifiably be moved out of sysdep.c because it
595 * no longer does anything that is system-dependent.)
597 void kill_session(int session_to_kill) {
598 struct CitContext *ptr;
600 begin_critical_section(S_SESSION_TABLE);
601 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
602 if (ptr->cs_pid == session_to_kill) {
606 end_critical_section(S_SESSION_TABLE);
613 * Start running as a daemon. Only close stdio if do_close_stdio is set.
615 void start_daemon(int do_close_stdio) {
616 if (do_close_stdio) {
621 signal(SIGHUP,SIG_IGN);
622 signal(SIGINT,SIG_IGN);
623 signal(SIGQUIT,SIG_IGN);
624 if (fork()!=0) exit(0);
630 * Tie in to the 'netsetup' program.
632 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
634 void cmd_nset(char *cmdbuf)
641 char netsetup_args[3][SIZ];
643 if (CC->usersupp.axlevel < 6) {
644 cprintf("%d Higher access required.\n",
645 ERROR + HIGHER_ACCESS_REQUIRED);
649 for (a=1; a<=3; ++a) {
650 if (num_parms(cmdbuf) >= a) {
651 extract(netsetup_args[a-1], cmdbuf, a-1);
652 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
653 if (netsetup_args[a-1][b] == 34) {
654 netsetup_args[a-1][b] = '_';
659 netsetup_args[a-1][0] = 0;
663 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
664 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
665 netsetup = popen(fbuf, "r");
666 if (netsetup == NULL) {
667 cprintf("%d %s\n", ERROR, strerror(errno));
672 while (ch = getc(netsetup), (ch > 0)) {
673 fbuf[strlen(fbuf)+1] = 0;
674 fbuf[strlen(fbuf)] = ch;
677 retcode = pclose(netsetup);
680 for (a=0; a<strlen(fbuf); ++a) {
681 if (fbuf[a] < 32) fbuf[a] = 32;
684 cprintf("%d %s\n", ERROR, fbuf);
688 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
690 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
697 * Generic routine to convert a login name to a full name (gecos)
698 * Returns nonzero if a conversion took place
700 int convert_login(char NameToConvert[]) {
704 pw = getpwnam(NameToConvert);
709 strcpy(NameToConvert, pw->pw_gecos);
710 for (a=0; a<strlen(NameToConvert); ++a) {
711 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
717 static struct worker_node {
719 struct worker_node *next;
720 } *worker_list = NULL;
724 * create a worker thread. this function must always be called from within
725 * an S_WORKER_LIST critical section!
727 static void create_worker(void) {
729 struct worker_node *n = mallok(sizeof *n);
732 lprintf(1, "can't allocate worker_node, exiting\n");
737 if ((ret = pthread_create(&n->tid, NULL, worker_thread, NULL) != 0))
740 lprintf(1, "Can't create worker thread: %s\n",
744 n->next = worker_list;
751 * Purge all sessions which have the 'kill_me' flag set.
752 * This function has code to prevent it from running more than once every
753 * few seconds, because running it after every single unbind would waste a lot
754 * of CPU time and keep the context list locked too much.
756 * After that's done, we raise or lower the size of the worker thread pool
757 * if such an action is appropriate.
759 void dead_session_purge(void) {
760 struct CitContext *ptr, *rem;
761 struct worker_node **node, *tmp;
764 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
769 begin_critical_section(S_SESSION_TABLE);
770 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
771 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
775 end_critical_section(S_SESSION_TABLE);
777 /* RemoveContext() enters its own S_SESSION_TABLE critical
778 * section, so we have to do it like this.
781 lprintf(9, "Purging session %d\n", rem->cs_pid);
785 } while (rem != NULL);
788 /* Raise or lower the size of the worker thread pool if such
789 * an action is appropriate.
792 self = pthread_self();
794 if ( (num_sessions > num_threads)
795 && (num_threads < config.c_max_workers) ) {
796 begin_critical_section(S_WORKER_LIST);
798 end_critical_section(S_WORKER_LIST);
801 /* don't let the initial thread die since it's responsible for
802 waiting for all the other threads to terminate. */
803 else if ( (num_sessions < num_threads)
804 && (num_threads > config.c_min_workers)
805 && (self != initial_thread) ) {
807 begin_critical_section(S_WORKER_LIST);
810 /* we're exiting before server shutdown... unlink ourself from
811 the worker list and detach our thread to avoid memory leaks
814 for (node = &worker_list; *node != NULL; node = &(*node)->next)
815 if ((*node)->tid == self) {
817 *node = (*node)->next;
822 pthread_detach(self);
823 end_critical_section(S_WORKER_LIST);
834 * Redirect a session's output to a file or socket.
835 * This function may be called with a file handle *or* a socket (but not
836 * both). Call with neither to return output to its normal client socket.
838 void CtdlRedirectOutput(FILE *fp, int sock) {
840 if (fp != NULL) CC->redirect_fp = fp;
841 else CC->redirect_fp = NULL;
843 if (sock > 0) CC->redirect_sock = sock;
844 else CC->redirect_sock = (-1);
850 * masterCC is the context we use when not attached to a session. This
851 * function initializes it.
853 void InitializeMasterCC(void) {
854 memset(&masterCC, 0, sizeof(struct CitContext));
855 masterCC.internal_pgm = 1;
862 * Set up a fd_set containing all the master sockets to which we
863 * always listen. It's computationally less expensive to just copy
864 * this to a local fd_set when starting a new select() and then add
865 * the client sockets than it is to initialize a new one and then
866 * figure out what to put there.
868 void init_master_fdset(void) {
869 struct ServiceFunctionHook *serviceptr;
872 lprintf(9, "Initializing master fdset\n");
877 lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
878 FD_SET(rescan[0], &masterfds);
879 if (rescan[0] > masterhighest) masterhighest = rescan[0];
881 for (serviceptr = ServiceHookTable; serviceptr != NULL;
882 serviceptr = serviceptr->next ) {
883 m = serviceptr->msock;
884 lprintf(9, "Will listen on master socket %d\n", m);
885 FD_SET(m, &masterfds);
886 if (m > masterhighest) {
890 lprintf(9, "masterhighest = %d\n", masterhighest);
896 * Here's where it all begins.
898 int main(int argc, char **argv)
900 char tracefile[128]; /* Name of file to log traces to */
901 int a, i; /* General-purpose variables */
903 int drop_root_perms = 1;
905 struct worker_node *wnp;
907 /* specify default port name and trace file */
908 strcpy(tracefile, "");
910 /* initialize the master context */
911 InitializeMasterCC();
913 /* parse command-line arguments */
914 for (a=1; a<argc; ++a) {
916 /* -t specifies where to log trace messages to */
917 if (!strncmp(argv[a], "-t", 2)) {
918 strcpy(tracefile, argv[a]);
919 strcpy(tracefile, &tracefile[2]);
920 freopen(tracefile, "r", stdin);
921 freopen(tracefile, "w", stdout);
922 freopen(tracefile, "w", stderr);
925 /* run in the background if -d was specified */
926 else if (!strcmp(argv[a], "-d")) {
927 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
930 /* -x specifies the desired logging level */
931 else if (!strncmp(argv[a], "-x", 2)) {
932 verbosity = atoi(&argv[a][2]);
935 else if (!strncmp(argv[a], "-h", 2)) {
936 safestrncpy(bbs_home_directory, &argv[a][2],
937 sizeof bbs_home_directory);
941 else if (!strncmp(argv[a], "-f", 2)) {
945 /* -r tells the server not to drop root permissions. don't use
946 * this unless you know what you're doing. this should be
947 * removed in the next release if it proves unnecessary. */
948 else if (!strcmp(argv[a], "-r"))
951 /* any other parameter makes it crash and burn */
953 lprintf(1, "citserver: usage: "
954 "citserver [-tTraceFile] [-d] [-f]"
955 " [-xLogLevel] [-hHomeDir]\n");
961 /* Tell 'em who's in da house */
963 "\nMultithreaded message server for Citadel/UX\n"
964 "Copyright (C) 1987-2000 by the Citadel/UX development team.\n"
965 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
966 "you are welcome to change it and/or distribute copies of it under certain\n"
967 "conditions. There is absolutely no warranty for this software. Please\n"
968 "read the 'COPYING.txt' file for details.\n\n");
972 openlog("citserver", LOG_PID, LOG_USER);
974 /* Load site-specific parameters */
975 lprintf(7, "Loading citadel.config\n");
980 * Do non system dependent startup functions.
985 * Bind the server to a Unix-domain socket.
987 CtdlRegisterServiceHook(0,
989 citproto_begin_session,
993 * Bind the server to our favorite TCP port (usually 504).
995 CtdlRegisterServiceHook(config.c_port_number,
997 citproto_begin_session,
1001 * Load any server-side modules (plugins) available here.
1003 lprintf(7, "Initializing loadable modules\n");
1004 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
1005 sprintf(moddir, "%s/modules", bbs_home_directory);
1006 DLoader_Init(moddir);
1011 * The rescan pipe exists so that worker threads can be woken up and
1012 * told to re-scan the context list for fd's to listen on. This is
1013 * necessary, for example, when a context is about to go idle and needs
1014 * to get back on that list.
1017 lprintf(1, "Can't create rescan pipe!\n");
1021 init_master_fdset();
1024 * Now that we've bound the sockets, change to the BBS user id and its
1025 * corresponding group ids
1027 if (drop_root_perms) {
1028 if ((pw = getpwuid(BBSUID)) == NULL)
1029 lprintf(1, "WARNING: getpwuid(%d): %s\n"
1030 "Group IDs will be incorrect.\n", BBSUID,
1033 initgroups(pw->pw_name, pw->pw_gid);
1034 if (setgid(pw->pw_gid))
1035 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
1038 lprintf(7, "Changing uid to %d\n", BBSUID);
1039 if (setuid(BBSUID) != 0) {
1040 lprintf(3, "setuid() failed: %s\n", strerror(errno));
1044 /* We want to check for idle sessions once per minute */
1045 CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
1048 * Now create a bunch of worker threads.
1050 lprintf(9, "Starting %d worker threads\n", config.c_min_workers-1);
1051 begin_critical_section(S_WORKER_LIST);
1052 for (i=0; i<(config.c_min_workers-1); ++i) {
1055 end_critical_section(S_WORKER_LIST);
1057 /* Now this thread can become a worker as well. */
1058 initial_thread = pthread_self();
1059 worker_thread(NULL);
1061 /* Server is exiting. Wait for workers to shutdown. */
1062 lprintf(7, "Waiting for worker threads to shut down\n");
1064 begin_critical_section(S_WORKER_LIST);
1065 while (worker_list != NULL) {
1067 worker_list = wnp->next;
1069 /* avoid deadlock with an exiting thread */
1070 end_critical_section(S_WORKER_LIST);
1071 if ((i = pthread_join(wnp->tid, NULL)))
1072 lprintf(1, "pthread_join: %s\n", strerror(i));
1074 begin_critical_section(S_WORKER_LIST);
1076 end_critical_section(S_WORKER_LIST);
1085 * Bind a thread to a context. (It's inline merely to speed things up.)
1087 inline void become_session(struct CitContext *which_con) {
1088 pthread_setspecific(MyConKey, (void *)which_con );
1094 * This loop just keeps going and going and going...
1096 void *worker_thread(void *arg) {
1100 struct CitContext *ptr;
1101 struct CitContext *bind_me = NULL;
1104 struct CitContext *con= NULL; /* Temporary context pointer */
1105 struct ServiceFunctionHook *serviceptr;
1106 struct sockaddr_in fsin; /* Data for master socket */
1107 int alen; /* Data for master socket */
1108 int ssock; /* Descriptor for client socket */
1115 while (!time_to_die) {
1118 * A naive implementation would have all idle threads
1119 * calling select() and then they'd all wake up at once. We
1120 * solve this problem by putting the select() in a critical
1121 * section, so only one thread has the opportunity to wake
1122 * up. If we wake up on a master socket, create a new
1123 * session context; otherwise, just bind the thread to the
1124 * context we want and go on our merry way.
1127 /* make doubly sure we're not holding any stale db handles
1128 * which might cause a deadlock.
1130 cdb_release_handles();
1132 begin_critical_section(S_I_WANNA_SELECT);
1133 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1134 highest = masterhighest;
1135 begin_critical_section(S_SESSION_TABLE);
1136 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1137 if (ptr->state == CON_IDLE) {
1138 FD_SET(ptr->client_socket, &readfds);
1139 if (ptr->client_socket > highest)
1140 highest = ptr->client_socket;
1143 end_critical_section(S_SESSION_TABLE);
1145 tv.tv_sec = 1; /* wake up every second if no input */
1150 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1152 end_critical_section(S_I_WANNA_SELECT);
1156 /* Now figure out who made this select() unblock.
1157 * First, check for an error or exit condition.
1160 if (errno != EINTR) {
1161 lprintf(9, "Exiting (%s)\n", strerror(errno));
1163 } else if (!time_to_die)
1167 /* Next, check to see if it's a new client connecting
1168 * on a master socket.
1170 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1171 serviceptr = serviceptr->next ) {
1173 if (FD_ISSET(serviceptr->msock, &readfds)) {
1175 ssock = accept(serviceptr->msock,
1176 (struct sockaddr *)&fsin, &alen);
1178 lprintf(2, "citserver: accept(): %s\n",
1182 lprintf(7, "citserver: "
1183 "New client socket %d\n",
1186 /* New context will be created already
1187 * set up in the CON_EXECUTING state.
1189 con = CreateNewContext();
1191 /* Assign new socket number to it. */
1192 con->client_socket = ssock;
1193 con->h_command_function =
1194 serviceptr->h_command_function;
1196 /* Determine whether local socket */
1197 if (serviceptr->sockpath != NULL)
1198 con->is_local_socket = 1;
1200 /* Set the SO_REUSEADDR socket option */
1202 setsockopt(ssock, SOL_SOCKET,
1206 become_session(con);
1208 serviceptr->h_greeting_function();
1209 become_session(NULL);
1210 con->state = CON_IDLE;
1216 /* If the rescan pipe went active, someone is telling this
1217 * thread that the &readfds needs to be refreshed with more
1221 end_critical_section(S_I_WANNA_SELECT);
1225 if (FD_ISSET(rescan[0], &readfds)) {
1226 read(rescan[0], &junk, 1);
1230 /* It must be a client socket. Find a context that has data
1231 * waiting on its socket *and* is in the CON_IDLE state.
1235 begin_critical_section(S_SESSION_TABLE);
1236 for (ptr = ContextList;
1237 ( (ptr != NULL) && (bind_me == NULL) );
1239 if ( (FD_ISSET(ptr->client_socket, &readfds))
1240 && (ptr->state == CON_IDLE) ) {
1244 if (bind_me != NULL) {
1245 /* Found one. Stake a claim to it before
1246 * letting anyone else touch the context list.
1248 bind_me->state = CON_EXECUTING;
1251 end_critical_section(S_SESSION_TABLE);
1252 end_critical_section(S_I_WANNA_SELECT);
1254 /* We're bound to a session, now do *one* command */
1255 if (bind_me != NULL) {
1256 become_session(bind_me);
1257 CC->h_command_function();
1258 become_session(NULL);
1259 bind_me->state = CON_IDLE;
1260 if (bind_me->kill_me == 1) {
1261 RemoveContext(bind_me);
1263 write(rescan[1], &junk, 1);
1267 dead_session_purge();
1268 if ((time(NULL) - last_timer) > 60L) {
1269 last_timer = time(NULL);
1270 cdb_release_handles(); /* suggested by Justin Case */
1271 PerformSessionHooks(EVT_TIMER);
1274 check_sched_shutdown();
1277 /* If control reaches this point, the server is shutting down */