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 * Note: the variable "buf" below needs to be large enough to handle any
90 * log data sent through this function. BE CAREFUL!
92 void lprintf(int loglevel, const char *format, ...) {
96 va_start(arg_ptr, format);
97 vsprintf(buf, format, arg_ptr);
100 if (loglevel <= verbosity) {
104 gettimeofday(&tv, NULL);
105 tim = localtime(&(tv.tv_sec));
107 * Log provides millisecond accuracy. If you need
108 * microsecond accuracy and your OS supports it, change
109 * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
111 fprintf(stderr, "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
112 tim->tm_year + 1900, tim->tm_mon + 1, tim->tm_mday,
113 tim->tm_hour, tim->tm_min, tim->tm_sec,
114 tv.tv_usec / 1000, buf);
118 PerformLogHooks(loglevel, buf);
123 #ifdef DEBUG_MEMORY_LEAKS
124 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
126 struct TheHeap *hptr;
130 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
131 tsize, tfile, tline);
135 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
136 strcpy(hptr->h_file, tfile);
137 hptr->h_line = tline;
144 char *tracked_strdup(const char *orig, char *tfile, int tline) {
147 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
148 if (s == NULL) return NULL;
154 void tracked_free(void *ptr) {
155 struct TheHeap *hptr, *freeme;
157 if (heap->h_ptr == ptr) {
163 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
164 if (hptr->next->h_ptr == ptr) {
166 hptr->next = hptr->next->next;
175 void *tracked_realloc(void *ptr, size_t size) {
177 struct TheHeap *hptr;
179 newptr = realloc(ptr, size);
181 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
182 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
189 void dump_tracked() {
190 struct TheHeap *hptr;
192 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
193 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
194 cprintf("%20s %5d\n",
195 hptr->h_file, hptr->h_line);
207 * We used to use master_cleanup() as a signal handler to shut down the server.
208 * however, master_cleanup() and the functions it calls do some things that
209 * aren't such a good idea to do from a signal handler: acquiring mutexes,
210 * playing with signal masks on BSDI systems, etc. so instead we install the
211 * following signal handler to set a global variable to inform the main loop
212 * that it's time to call master_cleanup() and exit.
215 volatile int time_to_die = 0;
217 static RETSIGTYPE signal_cleanup(int signum) {
223 * Some initialization stuff...
225 void init_sysdep(void) {
228 /* Set up a bunch of semaphores to be used for critical sections */
229 for (a=0; a<MAX_SEMAPHORES; ++a) {
230 pthread_mutex_init(&Critters[a], NULL);
234 * Set up a place to put thread-specific data.
235 * We only need a single pointer per thread - it points to the
236 * CitContext structure (in the ContextList linked list) of the
237 * session to which the calling thread is currently bound.
239 if (pthread_key_create(&MyConKey, NULL) != 0) {
240 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
244 * The action for unexpected signals and exceptions should be to
245 * call signal_cleanup() to gracefully shut down the server.
247 signal(SIGINT, signal_cleanup);
248 signal(SIGQUIT, signal_cleanup);
249 signal(SIGHUP, signal_cleanup);
250 signal(SIGTERM, signal_cleanup);
253 * Do not shut down the server on broken pipe signals, otherwise the
254 * whole Citadel service would come down whenever a single client
257 signal(SIGPIPE, SIG_IGN);
262 * Obtain a semaphore lock to begin a critical section.
264 void begin_critical_section(int which_one)
266 /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
267 pthread_mutex_lock(&Critters[which_one]);
271 * Release a semaphore lock to end a critical section.
273 void end_critical_section(int which_one)
275 /* lprintf(9, "end_critical_section(%d)\n", 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(1, "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(1, "citserver: Can't bind: %s\n",
318 if (listen(s, actual_queue_len) < 0) {
319 lprintf(1, "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(1, "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(1, "citserver: Can't create a socket: %s\n",
360 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
361 lprintf(1, "citserver: Can't bind: %s\n",
366 if (listen(s, actual_queue_len) < 0) {
367 lprintf(1, "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 struct CitContext *MyContext(void) {
383 struct CitContext *retCC;
384 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
385 if (retCC == NULL) retCC = &masterCC;
391 * Initialize a new context and place it in the list. The session number
392 * used to be the PID (which is why it's called cs_pid), but that was when we
393 * had one process per session. Now we just assign them sequentially, starting
394 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
395 * sessions terminate.
397 struct CitContext *CreateNewContext(void) {
398 struct CitContext *me, *ptr;
402 me = (struct CitContext *) mallok(sizeof(struct CitContext));
404 lprintf(1, "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;
415 begin_critical_section(S_SESSION_TABLE);
417 /* obtain a unique session number */
420 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
421 if (ptr->cs_pid == num) {
426 } while (startover == 1);
429 me->next = ContextList;
433 end_critical_section(S_SESSION_TABLE);
440 * client_write() ... Send binary data to the client.
442 void client_write(char *buf, int nbytes)
444 int bytes_written = 0;
449 if (CC->redirect_fp != NULL) {
450 fwrite(buf, nbytes, 1, CC->redirect_fp);
454 if (CC->redirect_sock > 0) {
455 sock = CC->redirect_sock; /* and continue below... */
458 sock = CC->client_socket;
461 while (bytes_written < nbytes) {
462 signal(SIGPIPE, SIG_IGN);
463 retval = write(sock, &buf[bytes_written],
464 nbytes - bytes_written);
466 lprintf(2, "client_write() failed: %s\n",
468 if (sock == CC->client_socket) CC->kill_me = 1;
471 bytes_written = bytes_written + retval;
477 * cprintf() ... Send formatted printable data to the client. It is
478 * implemented in terms of client_write() but remains in
479 * sysdep.c in case we port to somewhere without va_args...
481 void cprintf(const char *format, ...) {
485 va_start(arg_ptr, format);
486 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
487 buf[sizeof buf - 2] = '\n';
488 client_write(buf, strlen(buf));
494 * Read data from the client socket.
496 * 1 Requested number of bytes has been read.
497 * 0 Request timed out.
498 * -1 The socket is broken.
499 * If the socket breaks, the session will be terminated.
501 int client_read_to(char *buf, int bytes, int timeout)
511 FD_SET(CC->client_socket, &rfds);
515 retval = select( (CC->client_socket)+1,
516 &rfds, NULL, NULL, &tv);
518 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
522 rlen = read(CC->client_socket, &buf[len], bytes-len);
524 lprintf(2, "client_read() failed: %s\n",
535 * Read data from the client socket with default timeout.
536 * (This is implemented in terms of client_read_to() and could be
537 * justifiably moved out of sysdep.c)
539 int client_read(char *buf, int bytes)
541 return(client_read_to(buf, bytes, config.c_sleeping));
546 * client_gets() ... Get a LF-terminated line of text from the client.
547 * (This is implemented in terms of client_read() and could be
548 * justifiably moved out of sysdep.c)
550 int client_gets(char *buf)
554 /* Read one character at a time.
557 retval = client_read(&buf[i], 1);
558 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
562 /* If we got a long line, discard characters until the newline.
565 while (buf[i] != '\n' && retval == 1)
566 retval = client_read(&buf[i], 1);
568 /* Strip the trailing newline and any trailing nonprintables (cr's)
571 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
572 buf[strlen(buf)-1] = 0;
573 if (retval < 0) strcpy(buf, "000");
580 * The system-dependent part of master_cleanup() - close the master socket.
582 void sysdep_master_cleanup(void) {
583 struct ServiceFunctionHook *serviceptr;
586 * close all protocol master sockets
588 for (serviceptr = ServiceHookTable; serviceptr != NULL;
589 serviceptr = serviceptr->next ) {
591 if (serviceptr->tcp_port > 0)
592 lprintf(3, "Closing listener on port %d\n",
593 serviceptr->tcp_port);
595 if (serviceptr->sockpath != NULL)
596 lprintf(3, "Closing listener on '%s'\n",
597 serviceptr->sockpath);
599 close(serviceptr->msock);
601 /* If it's a Unix domain socket, remove the file. */
602 if (serviceptr->sockpath != NULL) {
603 unlink(serviceptr->sockpath);
610 * Terminate another session.
611 * (This could justifiably be moved out of sysdep.c because it
612 * no longer does anything that is system-dependent.)
614 void kill_session(int session_to_kill) {
615 struct CitContext *ptr;
617 begin_critical_section(S_SESSION_TABLE);
618 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
619 if (ptr->cs_pid == session_to_kill) {
623 end_critical_section(S_SESSION_TABLE);
630 * Start running as a daemon. Only close stdio if do_close_stdio is set.
632 void start_daemon(int do_close_stdio) {
633 if (do_close_stdio) {
638 signal(SIGHUP,SIG_IGN);
639 signal(SIGINT,SIG_IGN);
640 signal(SIGQUIT,SIG_IGN);
641 if (fork()!=0) exit(0);
647 * Tie in to the 'netsetup' program.
649 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
651 void cmd_nset(char *cmdbuf)
658 char netsetup_args[3][SIZ];
660 if (CC->usersupp.axlevel < 6) {
661 cprintf("%d Higher access required.\n",
662 ERROR + HIGHER_ACCESS_REQUIRED);
666 for (a=1; a<=3; ++a) {
667 if (num_parms(cmdbuf) >= a) {
668 extract(netsetup_args[a-1], cmdbuf, a-1);
669 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
670 if (netsetup_args[a-1][b] == 34) {
671 netsetup_args[a-1][b] = '_';
676 netsetup_args[a-1][0] = 0;
680 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
681 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
682 netsetup = popen(fbuf, "r");
683 if (netsetup == NULL) {
684 cprintf("%d %s\n", ERROR, strerror(errno));
689 while (ch = getc(netsetup), (ch > 0)) {
690 fbuf[strlen(fbuf)+1] = 0;
691 fbuf[strlen(fbuf)] = ch;
694 retcode = pclose(netsetup);
697 for (a=0; a<strlen(fbuf); ++a) {
698 if (fbuf[a] < 32) fbuf[a] = 32;
701 cprintf("%d %s\n", ERROR, fbuf);
705 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
707 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
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 static struct worker_node {
736 struct worker_node *next;
737 } *worker_list = NULL;
741 * create a worker thread. this function must always be called from within
742 * an S_WORKER_LIST critical section!
744 static void create_worker(void) {
746 struct worker_node *n = mallok(sizeof *n);
749 lprintf(1, "can't allocate worker_node, exiting\n");
754 if ((ret = pthread_create(&n->tid, NULL, worker_thread, NULL) != 0))
757 lprintf(1, "Can't create worker thread: %s\n",
761 n->next = worker_list;
768 * Purge all sessions which have the 'kill_me' flag set.
769 * This function has code to prevent it from running more than once every
770 * few seconds, because running it after every single unbind would waste a lot
771 * of CPU time and keep the context list locked too much.
773 * After that's done, we raise or lower the size of the worker thread pool
774 * if such an action is appropriate.
776 void dead_session_purge(void) {
777 struct CitContext *ptr, *rem;
778 struct worker_node **node, *tmp;
781 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
786 begin_critical_section(S_SESSION_TABLE);
787 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
788 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
792 end_critical_section(S_SESSION_TABLE);
794 /* RemoveContext() enters its own S_SESSION_TABLE critical
795 * section, so we have to do it like this.
798 lprintf(9, "Purging session %d\n", rem->cs_pid);
802 } while (rem != NULL);
805 /* Raise or lower the size of the worker thread pool if such
806 * an action is appropriate.
809 self = pthread_self();
811 if ( (num_sessions > num_threads)
812 && (num_threads < config.c_max_workers) ) {
813 begin_critical_section(S_WORKER_LIST);
815 end_critical_section(S_WORKER_LIST);
818 /* don't let the initial thread die since it's responsible for
819 waiting for all the other threads to terminate. */
820 else if ( (num_sessions < num_threads)
821 && (num_threads > config.c_min_workers)
822 && (self != initial_thread) ) {
824 begin_critical_section(S_WORKER_LIST);
827 /* we're exiting before server shutdown... unlink ourself from
828 the worker list and detach our thread to avoid memory leaks
831 for (node = &worker_list; *node != NULL; node = &(*node)->next)
832 if ((*node)->tid == self) {
834 *node = (*node)->next;
839 pthread_detach(self);
840 end_critical_section(S_WORKER_LIST);
851 * Redirect a session's output to a file or socket.
852 * This function may be called with a file handle *or* a socket (but not
853 * both). Call with neither to return output to its normal client socket.
855 void CtdlRedirectOutput(FILE *fp, int sock) {
857 if (fp != NULL) CC->redirect_fp = fp;
858 else CC->redirect_fp = NULL;
860 if (sock > 0) CC->redirect_sock = sock;
861 else CC->redirect_sock = (-1);
867 * masterCC is the context we use when not attached to a session. This
868 * function initializes it.
870 void InitializeMasterCC(void) {
871 memset(&masterCC, 0, sizeof(struct CitContext));
872 masterCC.internal_pgm = 1;
879 * Set up a fd_set containing all the master sockets to which we
880 * always listen. It's computationally less expensive to just copy
881 * this to a local fd_set when starting a new select() and then add
882 * the client sockets than it is to initialize a new one and then
883 * figure out what to put there.
885 void init_master_fdset(void) {
886 struct ServiceFunctionHook *serviceptr;
889 lprintf(9, "Initializing master fdset\n");
894 lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
895 FD_SET(rescan[0], &masterfds);
896 if (rescan[0] > masterhighest) masterhighest = rescan[0];
898 for (serviceptr = ServiceHookTable; serviceptr != NULL;
899 serviceptr = serviceptr->next ) {
900 m = serviceptr->msock;
901 lprintf(9, "Will listen on master socket %d\n", m);
902 FD_SET(m, &masterfds);
903 if (m > masterhighest) {
907 lprintf(9, "masterhighest = %d\n", masterhighest);
913 * Here's where it all begins.
915 int main(int argc, char **argv)
917 char tracefile[128]; /* Name of file to log traces to */
918 int a, i; /* General-purpose variables */
920 int drop_root_perms = 1;
922 struct worker_node *wnp;
924 /* specify default port name and trace file */
925 strcpy(tracefile, "");
927 /* initialize the master context */
928 InitializeMasterCC();
930 /* parse command-line arguments */
931 for (a=1; a<argc; ++a) {
933 /* -t specifies where to log trace messages to */
934 if (!strncmp(argv[a], "-t", 2)) {
935 strcpy(tracefile, argv[a]);
936 strcpy(tracefile, &tracefile[2]);
937 freopen(tracefile, "r", stdin);
938 freopen(tracefile, "w", stdout);
939 freopen(tracefile, "w", stderr);
942 /* run in the background if -d was specified */
943 else if (!strcmp(argv[a], "-d")) {
944 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
947 /* -x specifies the desired logging level */
948 else if (!strncmp(argv[a], "-x", 2)) {
949 verbosity = atoi(&argv[a][2]);
952 else if (!strncmp(argv[a], "-h", 2)) {
953 safestrncpy(bbs_home_directory, &argv[a][2],
954 sizeof bbs_home_directory);
958 else if (!strncmp(argv[a], "-f", 2)) {
962 /* -r tells the server not to drop root permissions. don't use
963 * this unless you know what you're doing. this should be
964 * removed in the next release if it proves unnecessary. */
965 else if (!strcmp(argv[a], "-r"))
968 /* any other parameter makes it crash and burn */
970 lprintf(1, "citserver: usage: "
971 "citserver [-tTraceFile] [-d] [-f]"
972 " [-xLogLevel] [-hHomeDir]\n");
978 /* Tell 'em who's in da house */
980 "\nMultithreaded message server for Citadel/UX\n"
981 "Copyright (C) 1987-2000 by the Citadel/UX development team.\n"
982 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
983 "you are welcome to change it and/or distribute copies of it under certain\n"
984 "conditions. There is absolutely no warranty for this software. Please\n"
985 "read the 'COPYING.txt' file for details.\n\n");
989 openlog("citserver", LOG_PID, LOG_USER);
991 /* Load site-specific parameters */
992 lprintf(7, "Loading citadel.config\n");
997 * Do non system dependent startup functions.
1002 * Bind the server to a Unix-domain socket.
1004 CtdlRegisterServiceHook(0,
1006 citproto_begin_session,
1010 * Bind the server to our favorite TCP port (usually 504).
1012 CtdlRegisterServiceHook(config.c_port_number,
1014 citproto_begin_session,
1018 * Load any server-side modules (plugins) available here.
1020 lprintf(7, "Initializing loadable modules\n");
1021 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
1022 sprintf(moddir, "%s/modules", bbs_home_directory);
1023 DLoader_Init(moddir);
1028 * The rescan pipe exists so that worker threads can be woken up and
1029 * told to re-scan the context list for fd's to listen on. This is
1030 * necessary, for example, when a context is about to go idle and needs
1031 * to get back on that list.
1034 lprintf(1, "Can't create rescan pipe!\n");
1038 init_master_fdset();
1041 * Now that we've bound the sockets, change to the BBS user id and its
1042 * corresponding group ids
1044 if (drop_root_perms) {
1045 if ((pw = getpwuid(BBSUID)) == NULL)
1046 lprintf(1, "WARNING: getpwuid(%d): %s\n"
1047 "Group IDs will be incorrect.\n", BBSUID,
1050 initgroups(pw->pw_name, pw->pw_gid);
1051 if (setgid(pw->pw_gid))
1052 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
1055 lprintf(7, "Changing uid to %d\n", BBSUID);
1056 if (setuid(BBSUID) != 0) {
1057 lprintf(3, "setuid() failed: %s\n", strerror(errno));
1061 /* We want to check for idle sessions once per minute */
1062 CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
1065 * Now create a bunch of worker threads.
1067 lprintf(9, "Starting %d worker threads\n", config.c_min_workers-1);
1068 begin_critical_section(S_WORKER_LIST);
1069 for (i=0; i<(config.c_min_workers-1); ++i) {
1072 end_critical_section(S_WORKER_LIST);
1074 /* Now this thread can become a worker as well. */
1075 initial_thread = pthread_self();
1076 worker_thread(NULL);
1078 /* Server is exiting. Wait for workers to shutdown. */
1079 lprintf(7, "Waiting for worker threads to shut down\n");
1081 begin_critical_section(S_WORKER_LIST);
1082 while (worker_list != NULL) {
1084 worker_list = wnp->next;
1086 /* avoid deadlock with an exiting thread */
1087 end_critical_section(S_WORKER_LIST);
1088 if ((i = pthread_join(wnp->tid, NULL)))
1089 lprintf(1, "pthread_join: %s\n", strerror(i));
1091 begin_critical_section(S_WORKER_LIST);
1093 end_critical_section(S_WORKER_LIST);
1102 * Bind a thread to a context. (It's inline merely to speed things up.)
1104 inline void become_session(struct CitContext *which_con) {
1105 pthread_setspecific(MyConKey, (void *)which_con );
1111 * This loop just keeps going and going and going...
1113 void *worker_thread(void *arg) {
1117 struct CitContext *ptr;
1118 struct CitContext *bind_me = NULL;
1121 struct CitContext *con= NULL; /* Temporary context pointer */
1122 struct ServiceFunctionHook *serviceptr;
1123 struct sockaddr_in fsin; /* Data for master socket */
1124 int alen; /* Data for master socket */
1125 int ssock; /* Descriptor for client socket */
1132 while (!time_to_die) {
1135 * A naive implementation would have all idle threads
1136 * calling select() and then they'd all wake up at once. We
1137 * solve this problem by putting the select() in a critical
1138 * section, so only one thread has the opportunity to wake
1139 * up. If we wake up on a master socket, create a new
1140 * session context; otherwise, just bind the thread to the
1141 * context we want and go on our merry way.
1144 /* make doubly sure we're not holding any stale db handles
1145 * which might cause a deadlock.
1147 cdb_release_handles();
1149 begin_critical_section(S_I_WANNA_SELECT);
1150 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1151 highest = masterhighest;
1152 begin_critical_section(S_SESSION_TABLE);
1153 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1154 if (ptr->state == CON_IDLE) {
1155 FD_SET(ptr->client_socket, &readfds);
1156 if (ptr->client_socket > highest)
1157 highest = ptr->client_socket;
1160 end_critical_section(S_SESSION_TABLE);
1162 tv.tv_sec = 1; /* wake up every second if no input */
1167 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1169 end_critical_section(S_I_WANNA_SELECT);
1173 /* Now figure out who made this select() unblock.
1174 * First, check for an error or exit condition.
1177 if (errno != EINTR) {
1178 lprintf(9, "Exiting (%s)\n", strerror(errno));
1180 } else if (!time_to_die)
1184 /* Next, check to see if it's a new client connecting
1185 * on a master socket.
1187 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1188 serviceptr = serviceptr->next ) {
1190 if (FD_ISSET(serviceptr->msock, &readfds)) {
1192 ssock = accept(serviceptr->msock,
1193 (struct sockaddr *)&fsin, &alen);
1195 lprintf(2, "citserver: accept(): %s\n",
1199 lprintf(7, "citserver: "
1200 "New client socket %d\n",
1203 /* New context will be created already
1204 * set up in the CON_EXECUTING state.
1206 con = CreateNewContext();
1208 /* Assign new socket number to it. */
1209 con->client_socket = ssock;
1210 con->h_command_function =
1211 serviceptr->h_command_function;
1213 /* Determine whether local socket */
1214 if (serviceptr->sockpath != NULL)
1215 con->is_local_socket = 1;
1217 /* Set the SO_REUSEADDR socket option */
1219 setsockopt(ssock, SOL_SOCKET,
1223 become_session(con);
1225 serviceptr->h_greeting_function();
1226 become_session(NULL);
1227 con->state = CON_IDLE;
1233 /* If the rescan pipe went active, someone is telling this
1234 * thread that the &readfds needs to be refreshed with more
1238 end_critical_section(S_I_WANNA_SELECT);
1242 if (FD_ISSET(rescan[0], &readfds)) {
1243 read(rescan[0], &junk, 1);
1247 /* It must be a client socket. Find a context that has data
1248 * waiting on its socket *and* is in the CON_IDLE state.
1252 begin_critical_section(S_SESSION_TABLE);
1253 for (ptr = ContextList;
1254 ( (ptr != NULL) && (bind_me == NULL) );
1256 if ( (FD_ISSET(ptr->client_socket, &readfds))
1257 && (ptr->state == CON_IDLE) ) {
1261 if (bind_me != NULL) {
1262 /* Found one. Stake a claim to it before
1263 * letting anyone else touch the context list.
1265 bind_me->state = CON_EXECUTING;
1268 end_critical_section(S_SESSION_TABLE);
1269 end_critical_section(S_I_WANNA_SELECT);
1271 /* We're bound to a session, now do *one* command */
1272 if (bind_me != NULL) {
1273 become_session(bind_me);
1274 CC->h_command_function();
1275 become_session(NULL);
1276 bind_me->state = CON_IDLE;
1277 if (bind_me->kill_me == 1) {
1278 RemoveContext(bind_me);
1280 write(rescan[1], &junk, 1);
1284 dead_session_purge();
1285 if ((time(NULL) - last_timer) > 60L) {
1286 last_timer = time(NULL);
1287 cdb_release_handles(); /* suggested by Justin Case */
1288 PerformSessionHooks(EVT_TIMER);
1291 check_sched_shutdown();
1294 /* If control reaches this point, the server is shutting down */