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,
301 (getprotobyname("tcp")->p_proto));
304 lprintf(1, "citserver: Can't create a socket: %s\n",
310 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
312 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
313 lprintf(1, "citserver: Can't bind: %s\n",
319 if (listen(s, actual_queue_len) < 0) {
320 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
331 * Create a Unix domain socket and listen on it
333 int ig_uds_server(char *sockpath, int queue_len)
335 struct sockaddr_un addr;
338 int actual_queue_len;
340 actual_queue_len = queue_len;
341 if (actual_queue_len < 5) actual_queue_len = 5;
343 i = unlink(sockpath);
344 if (i != 0) if (errno != ENOENT) {
345 lprintf(1, "citserver: can't unlink %s: %s\n",
346 sockpath, strerror(errno));
350 memset(&addr, 0, sizeof(addr));
351 addr.sun_family = AF_UNIX;
352 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
354 s = socket(AF_UNIX, SOCK_STREAM, 0);
356 lprintf(1, "citserver: Can't create a socket: %s\n",
361 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
362 lprintf(1, "citserver: Can't bind: %s\n",
367 if (listen(s, actual_queue_len) < 0) {
368 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
372 chmod(sockpath, 0777);
379 * Return a pointer to the CitContext structure bound to the thread which
380 * called this function. If there's no such binding (for example, if it's
381 * called by the housekeeper thread) then a generic 'master' CC is returned.
383 struct CitContext *MyContext(void) {
384 struct CitContext *retCC;
385 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
386 if (retCC == NULL) retCC = &masterCC;
392 * Initialize a new context and place it in the list. The session number
393 * used to be the PID (which is why it's called cs_pid), but that was when we
394 * had one process per session. Now we just assign them sequentially, starting
395 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
396 * sessions terminate.
398 struct CitContext *CreateNewContext(void) {
399 struct CitContext *me, *ptr;
403 me = (struct CitContext *) mallok(sizeof(struct CitContext));
405 lprintf(1, "citserver: can't allocate memory!!\n");
408 memset(me, 0, sizeof(struct CitContext));
410 /* The new context will be created already in the CON_EXECUTING state
411 * in order to prevent another thread from grabbing it while it's
414 me->state = CON_EXECUTING;
416 begin_critical_section(S_SESSION_TABLE);
418 /* obtain a unique session number */
421 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
422 if (ptr->cs_pid == num) {
427 } while (startover == 1);
430 me->next = ContextList;
434 end_critical_section(S_SESSION_TABLE);
441 * client_write() ... Send binary data to the client.
443 void client_write(char *buf, int nbytes)
445 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 retval = write(sock, &buf[bytes_written],
463 nbytes - bytes_written);
465 lprintf(2, "client_write() failed: %s\n",
467 if (sock == CC->client_socket) CC->kill_me = 1;
470 bytes_written = bytes_written + retval;
476 * cprintf() ... Send formatted printable data to the client. It is
477 * implemented in terms of client_write() but remains in
478 * sysdep.c in case we port to somewhere without va_args...
480 void cprintf(const char *format, ...) {
484 va_start(arg_ptr, format);
485 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
486 buf[sizeof buf - 2] = '\n';
487 client_write(buf, strlen(buf));
493 * Read data from the client socket.
495 * 1 Requested number of bytes has been read.
496 * 0 Request timed out.
497 * -1 The socket is broken.
498 * If the socket breaks, the session will be terminated.
500 int client_read_to(char *buf, int bytes, int timeout)
510 FD_SET(CC->client_socket, &rfds);
514 retval = select( (CC->client_socket)+1,
515 &rfds, NULL, NULL, &tv);
517 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
521 rlen = read(CC->client_socket, &buf[len], bytes-len);
523 lprintf(2, "client_read() failed: %s\n",
534 * Read data from the client socket with default timeout.
535 * (This is implemented in terms of client_read_to() and could be
536 * justifiably moved out of sysdep.c)
538 int client_read(char *buf, int bytes)
540 return(client_read_to(buf, bytes, config.c_sleeping));
545 * client_gets() ... Get a LF-terminated line of text from the client.
546 * (This is implemented in terms of client_read() and could be
547 * justifiably moved out of sysdep.c)
549 int client_gets(char *buf)
553 /* Read one character at a time.
556 retval = client_read(&buf[i], 1);
557 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
561 /* If we got a long line, discard characters until the newline.
564 while (buf[i] != '\n' && retval == 1)
565 retval = client_read(&buf[i], 1);
567 /* Strip the trailing newline and any trailing nonprintables (cr's)
570 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
571 buf[strlen(buf)-1] = 0;
572 if (retval < 0) strcpy(buf, "000");
579 * The system-dependent part of master_cleanup() - close the master socket.
581 void sysdep_master_cleanup(void) {
582 struct ServiceFunctionHook *serviceptr;
585 * close all protocol master sockets
587 for (serviceptr = ServiceHookTable; serviceptr != NULL;
588 serviceptr = serviceptr->next ) {
590 if (serviceptr->tcp_port > 0)
591 lprintf(3, "Closing listener on port %d\n",
592 serviceptr->tcp_port);
594 if (serviceptr->sockpath != NULL)
595 lprintf(3, "Closing listener on '%s'\n",
596 serviceptr->sockpath);
598 close(serviceptr->msock);
600 /* If it's a Unix domain socket, remove the file. */
601 if (serviceptr->sockpath != NULL) {
602 unlink(serviceptr->sockpath);
609 * Terminate another session.
610 * (This could justifiably be moved out of sysdep.c because it
611 * no longer does anything that is system-dependent.)
613 void kill_session(int session_to_kill) {
614 struct CitContext *ptr;
616 begin_critical_section(S_SESSION_TABLE);
617 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
618 if (ptr->cs_pid == session_to_kill) {
622 end_critical_section(S_SESSION_TABLE);
629 * Start running as a daemon. Only close stdio if do_close_stdio is set.
631 void start_daemon(int do_close_stdio) {
632 if (do_close_stdio) {
637 signal(SIGHUP,SIG_IGN);
638 signal(SIGINT,SIG_IGN);
639 signal(SIGQUIT,SIG_IGN);
640 if (fork()!=0) exit(0);
646 * Tie in to the 'netsetup' program.
648 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
650 void cmd_nset(char *cmdbuf)
657 char netsetup_args[3][SIZ];
659 if (CC->usersupp.axlevel < 6) {
660 cprintf("%d Higher access required.\n",
661 ERROR + HIGHER_ACCESS_REQUIRED);
665 for (a=1; a<=3; ++a) {
666 if (num_parms(cmdbuf) >= a) {
667 extract(netsetup_args[a-1], cmdbuf, a-1);
668 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
669 if (netsetup_args[a-1][b] == 34) {
670 netsetup_args[a-1][b] = '_';
675 netsetup_args[a-1][0] = 0;
679 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
680 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
681 netsetup = popen(fbuf, "r");
682 if (netsetup == NULL) {
683 cprintf("%d %s\n", ERROR, strerror(errno));
688 while (ch = getc(netsetup), (ch > 0)) {
689 fbuf[strlen(fbuf)+1] = 0;
690 fbuf[strlen(fbuf)] = ch;
693 retcode = pclose(netsetup);
696 for (a=0; a<strlen(fbuf); ++a) {
697 if (fbuf[a] < 32) fbuf[a] = 32;
700 cprintf("%d %s\n", ERROR, fbuf);
704 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
706 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
713 * Generic routine to convert a login name to a full name (gecos)
714 * Returns nonzero if a conversion took place
716 int convert_login(char NameToConvert[]) {
720 pw = getpwnam(NameToConvert);
725 strcpy(NameToConvert, pw->pw_gecos);
726 for (a=0; a<strlen(NameToConvert); ++a) {
727 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
733 static struct worker_node {
735 struct worker_node *next;
736 } *worker_list = NULL;
740 * create a worker thread. this function must always be called from within
741 * an S_WORKER_LIST critical section!
743 static void create_worker(void) {
745 struct worker_node *n = mallok(sizeof *n);
748 lprintf(1, "can't allocate worker_node, exiting\n");
753 if ((ret = pthread_create(&n->tid, NULL, worker_thread, NULL) != 0))
756 lprintf(1, "Can't create worker thread: %s\n",
760 n->next = worker_list;
767 * Purge all sessions which have the 'kill_me' flag set.
768 * This function has code to prevent it from running more than once every
769 * few seconds, because running it after every single unbind would waste a lot
770 * of CPU time and keep the context list locked too much.
772 * After that's done, we raise or lower the size of the worker thread pool
773 * if such an action is appropriate.
775 void dead_session_purge(void) {
776 struct CitContext *ptr, *rem;
777 struct worker_node **node, *tmp;
780 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
785 begin_critical_section(S_SESSION_TABLE);
786 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
787 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
791 end_critical_section(S_SESSION_TABLE);
793 /* RemoveContext() enters its own S_SESSION_TABLE critical
794 * section, so we have to do it like this.
797 lprintf(9, "Purging session %d\n", rem->cs_pid);
801 } while (rem != NULL);
804 /* Raise or lower the size of the worker thread pool if such
805 * an action is appropriate.
808 self = pthread_self();
810 if ( (num_sessions > num_threads)
811 && (num_threads < config.c_max_workers) ) {
812 begin_critical_section(S_WORKER_LIST);
814 end_critical_section(S_WORKER_LIST);
817 /* don't let the initial thread die since it's responsible for
818 waiting for all the other threads to terminate. */
819 else if ( (num_sessions < num_threads)
820 && (num_threads > config.c_min_workers)
821 && (self != initial_thread) ) {
823 begin_critical_section(S_WORKER_LIST);
826 /* we're exiting before server shutdown... unlink ourself from
827 the worker list and detach our thread to avoid memory leaks
830 for (node = &worker_list; *node != NULL; node = &(*node)->next)
831 if ((*node)->tid == self) {
833 *node = (*node)->next;
838 pthread_detach(self);
839 end_critical_section(S_WORKER_LIST);
850 * Redirect a session's output to a file or socket.
851 * This function may be called with a file handle *or* a socket (but not
852 * both). Call with neither to return output to its normal client socket.
854 void CtdlRedirectOutput(FILE *fp, int sock) {
856 if (fp != NULL) CC->redirect_fp = fp;
857 else CC->redirect_fp = NULL;
859 if (sock > 0) CC->redirect_sock = sock;
860 else CC->redirect_sock = (-1);
866 * masterCC is the context we use when not attached to a session. This
867 * function initializes it.
869 void InitializeMasterCC(void) {
870 memset(&masterCC, 0, sizeof(struct CitContext));
871 masterCC.internal_pgm = 1;
878 * Set up a fd_set containing all the master sockets to which we
879 * always listen. It's computationally less expensive to just copy
880 * this to a local fd_set when starting a new select() and then add
881 * the client sockets than it is to initialize a new one and then
882 * figure out what to put there.
884 void init_master_fdset(void) {
885 struct ServiceFunctionHook *serviceptr;
888 lprintf(9, "Initializing master fdset\n");
893 lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
894 FD_SET(rescan[0], &masterfds);
895 if (rescan[0] > masterhighest) masterhighest = rescan[0];
897 for (serviceptr = ServiceHookTable; serviceptr != NULL;
898 serviceptr = serviceptr->next ) {
899 m = serviceptr->msock;
900 lprintf(9, "Will listen on master socket %d\n", m);
901 FD_SET(m, &masterfds);
902 if (m > masterhighest) {
906 lprintf(9, "masterhighest = %d\n", masterhighest);
912 * Here's where it all begins.
914 int main(int argc, char **argv)
916 char tracefile[128]; /* Name of file to log traces to */
917 int a, i; /* General-purpose variables */
919 int drop_root_perms = 1;
921 struct worker_node *wnp;
923 /* specify default port name and trace file */
924 strcpy(tracefile, "");
926 /* initialize the master context */
927 InitializeMasterCC();
929 /* parse command-line arguments */
930 for (a=1; a<argc; ++a) {
932 /* -t specifies where to log trace messages to */
933 if (!strncmp(argv[a], "-t", 2)) {
934 strcpy(tracefile, argv[a]);
935 strcpy(tracefile, &tracefile[2]);
936 freopen(tracefile, "r", stdin);
937 freopen(tracefile, "w", stdout);
938 freopen(tracefile, "w", stderr);
941 /* run in the background if -d was specified */
942 else if (!strcmp(argv[a], "-d")) {
943 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
946 /* -x specifies the desired logging level */
947 else if (!strncmp(argv[a], "-x", 2)) {
948 verbosity = atoi(&argv[a][2]);
951 else if (!strncmp(argv[a], "-h", 2)) {
952 safestrncpy(bbs_home_directory, &argv[a][2],
953 sizeof bbs_home_directory);
957 else if (!strncmp(argv[a], "-f", 2)) {
961 /* -r tells the server not to drop root permissions. don't use
962 * this unless you know what you're doing. this should be
963 * removed in the next release if it proves unnecessary. */
964 else if (!strcmp(argv[a], "-r"))
967 /* any other parameter makes it crash and burn */
969 lprintf(1, "citserver: usage: "
970 "citserver [-tTraceFile] [-d] [-f]"
971 " [-xLogLevel] [-hHomeDir]\n");
977 /* Tell 'em who's in da house */
979 "\nMultithreaded message server for Citadel/UX\n"
980 "Copyright (C) 1987-2000 by the Citadel/UX development team.\n"
981 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
982 "you are welcome to change it and/or distribute copies of it under certain\n"
983 "conditions. There is absolutely no warranty for this software. Please\n"
984 "read the 'COPYING.txt' file for details.\n\n");
988 openlog("citserver", LOG_PID, LOG_USER);
990 /* Load site-specific parameters */
991 lprintf(7, "Loading citadel.config\n");
996 * Do non system dependent startup functions.
1001 * Bind the server to a Unix-domain socket.
1003 CtdlRegisterServiceHook(0,
1005 citproto_begin_session,
1009 * Bind the server to our favorite TCP port (usually 504).
1011 CtdlRegisterServiceHook(config.c_port_number,
1013 citproto_begin_session,
1017 * Load any server-side modules (plugins) available here.
1019 lprintf(7, "Initializing loadable modules\n");
1020 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
1021 sprintf(moddir, "%s/modules", bbs_home_directory);
1022 DLoader_Init(moddir);
1027 * The rescan pipe exists so that worker threads can be woken up and
1028 * told to re-scan the context list for fd's to listen on. This is
1029 * necessary, for example, when a context is about to go idle and needs
1030 * to get back on that list.
1033 lprintf(1, "Can't create rescan pipe!\n");
1037 init_master_fdset();
1040 * Now that we've bound the sockets, change to the BBS user id and its
1041 * corresponding group ids
1043 if (drop_root_perms) {
1044 if ((pw = getpwuid(BBSUID)) == NULL)
1045 lprintf(1, "WARNING: getpwuid(%d): %s\n"
1046 "Group IDs will be incorrect.\n", BBSUID,
1049 initgroups(pw->pw_name, pw->pw_gid);
1050 if (setgid(pw->pw_gid))
1051 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
1054 lprintf(7, "Changing uid to %d\n", BBSUID);
1055 if (setuid(BBSUID) != 0) {
1056 lprintf(3, "setuid() failed: %s\n", strerror(errno));
1060 /* We want to check for idle sessions once per minute */
1061 CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
1064 * Now create a bunch of worker threads.
1066 lprintf(9, "Starting %d worker threads\n", config.c_min_workers-1);
1067 begin_critical_section(S_WORKER_LIST);
1068 for (i=0; i<(config.c_min_workers-1); ++i) {
1071 end_critical_section(S_WORKER_LIST);
1073 /* Now this thread can become a worker as well. */
1074 initial_thread = pthread_self();
1075 worker_thread(NULL);
1077 /* Server is exiting. Wait for workers to shutdown. */
1078 lprintf(7, "Waiting for worker threads to shut down\n");
1080 begin_critical_section(S_WORKER_LIST);
1081 while (worker_list != NULL) {
1083 worker_list = wnp->next;
1085 /* avoid deadlock with an exiting thread */
1086 end_critical_section(S_WORKER_LIST);
1087 if ((i = pthread_join(wnp->tid, NULL)))
1088 lprintf(1, "pthread_join: %s\n", strerror(i));
1090 begin_critical_section(S_WORKER_LIST);
1092 end_critical_section(S_WORKER_LIST);
1101 * Bind a thread to a context. (It's inline merely to speed things up.)
1103 inline void become_session(struct CitContext *which_con) {
1104 pthread_setspecific(MyConKey, (void *)which_con );
1110 * This loop just keeps going and going and going...
1112 void *worker_thread(void *arg) {
1116 struct CitContext *ptr;
1117 struct CitContext *bind_me = NULL;
1120 struct CitContext *con= NULL; /* Temporary context pointer */
1121 struct ServiceFunctionHook *serviceptr;
1122 struct sockaddr_in fsin; /* Data for master socket */
1123 int alen; /* Data for master socket */
1124 int ssock; /* Descriptor for client socket */
1131 while (!time_to_die) {
1134 * A naive implementation would have all idle threads
1135 * calling select() and then they'd all wake up at once. We
1136 * solve this problem by putting the select() in a critical
1137 * section, so only one thread has the opportunity to wake
1138 * up. If we wake up on a master socket, create a new
1139 * session context; otherwise, just bind the thread to the
1140 * context we want and go on our merry way.
1143 /* make doubly sure we're not holding any stale db handles
1144 * which might cause a deadlock.
1146 cdb_release_handles();
1148 begin_critical_section(S_I_WANNA_SELECT);
1149 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1150 highest = masterhighest;
1151 begin_critical_section(S_SESSION_TABLE);
1152 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1153 if (ptr->state == CON_IDLE) {
1154 FD_SET(ptr->client_socket, &readfds);
1155 if (ptr->client_socket > highest)
1156 highest = ptr->client_socket;
1159 end_critical_section(S_SESSION_TABLE);
1161 tv.tv_sec = 1; /* wake up every second if no input */
1166 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1168 end_critical_section(S_I_WANNA_SELECT);
1172 /* Now figure out who made this select() unblock.
1173 * First, check for an error or exit condition.
1176 if (errno != EINTR) {
1177 lprintf(9, "Exiting (%s)\n", strerror(errno));
1179 } else if (!time_to_die)
1183 /* Next, check to see if it's a new client connecting
1184 * on a master socket.
1186 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1187 serviceptr = serviceptr->next ) {
1189 if (FD_ISSET(serviceptr->msock, &readfds)) {
1191 ssock = accept(serviceptr->msock,
1192 (struct sockaddr *)&fsin, &alen);
1194 lprintf(2, "citserver: accept(): %s\n",
1198 lprintf(7, "citserver: "
1199 "New client socket %d\n",
1202 /* New context will be created already
1203 * set up in the CON_EXECUTING state.
1205 con = CreateNewContext();
1207 /* Assign new socket number to it. */
1208 con->client_socket = ssock;
1209 con->h_command_function =
1210 serviceptr->h_command_function;
1212 /* Determine whether local socket */
1213 if (serviceptr->sockpath != NULL)
1214 con->is_local_socket = 1;
1216 /* Set the SO_REUSEADDR socket option */
1218 setsockopt(ssock, SOL_SOCKET,
1222 become_session(con);
1224 serviceptr->h_greeting_function();
1225 become_session(NULL);
1226 con->state = CON_IDLE;
1232 /* If the rescan pipe went active, someone is telling this
1233 * thread that the &readfds needs to be refreshed with more
1237 end_critical_section(S_I_WANNA_SELECT);
1241 if (FD_ISSET(rescan[0], &readfds)) {
1242 read(rescan[0], &junk, 1);
1246 /* It must be a client socket. Find a context that has data
1247 * waiting on its socket *and* is in the CON_IDLE state.
1251 begin_critical_section(S_SESSION_TABLE);
1252 for (ptr = ContextList;
1253 ( (ptr != NULL) && (bind_me == NULL) );
1255 if ( (FD_ISSET(ptr->client_socket, &readfds))
1256 && (ptr->state == CON_IDLE) ) {
1260 if (bind_me != NULL) {
1261 /* Found one. Stake a claim to it before
1262 * letting anyone else touch the context list.
1264 bind_me->state = CON_EXECUTING;
1267 end_critical_section(S_SESSION_TABLE);
1268 end_critical_section(S_I_WANNA_SELECT);
1270 /* We're bound to a session, now do *one* command */
1271 if (bind_me != NULL) {
1272 become_session(bind_me);
1273 CC->h_command_function();
1274 become_session(NULL);
1275 bind_me->state = CON_IDLE;
1276 if (bind_me->kill_me == 1) {
1277 RemoveContext(bind_me);
1279 write(rescan[1], &junk, 1);
1283 dead_session_purge();
1284 if ((time(NULL) - last_timer) > 60L) {
1285 last_timer = time(NULL);
1286 cdb_release_handles(); /* suggested by Justin Case */
1287 PerformSessionHooks(EVT_TIMER);
1290 check_sched_shutdown();
1293 /* If control reaches this point, the server is shutting down */