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>
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
33 # include <sys/time.h>
40 #include <netinet/in.h>
57 #include "sysdep_decls.h"
58 #include "citserver.h"
62 #include "housekeeping.h"
63 #include "dynloader.h"
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
74 #ifdef DEBUG_MEMORY_LEAKS
75 struct TheHeap *heap = NULL;
78 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
79 pthread_key_t MyConKey; /* TSD key for MyContext() */
81 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
83 struct CitContext masterCC;
84 int rescan[2]; /* The Rescan Pipe */
85 time_t last_purge = 0; /* Last dead session purge */
86 static int num_threads = 0; /* Current number of threads */
87 int num_sessions = 0; /* Current number of sessions */
89 fd_set masterfds; /* Master sockets etc. */
92 static pthread_t initial_thread; /* tid for main() thread */
96 * lprintf() ... Write logging information
98 * Note: the variable "buf" below needs to be large enough to handle any
99 * log data sent through this function. BE CAREFUL!
101 void lprintf(int loglevel, const char *format, ...) {
105 va_start(arg_ptr, format);
106 vsprintf(buf, format, arg_ptr);
109 if (loglevel <= verbosity) {
113 gettimeofday(&tv, NULL);
114 tim = localtime(&(tv.tv_sec));
116 * Log provides millisecond accuracy. If you need
117 * microsecond accuracy and your OS supports it, change
118 * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
120 fprintf(stderr, "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
121 tim->tm_year + 1900, tim->tm_mon + 1, tim->tm_mday,
122 tim->tm_hour, tim->tm_min, tim->tm_sec,
123 tv.tv_usec / 1000, buf);
127 PerformLogHooks(loglevel, buf);
132 #ifdef DEBUG_MEMORY_LEAKS
133 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
135 struct TheHeap *hptr;
139 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
140 tsize, tfile, tline);
144 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
145 strcpy(hptr->h_file, tfile);
146 hptr->h_line = tline;
153 char *tracked_strdup(const char *orig, char *tfile, int tline) {
156 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
157 if (s == NULL) return NULL;
163 void tracked_free(void *ptr) {
164 struct TheHeap *hptr, *freeme;
166 if (heap->h_ptr == ptr) {
172 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
173 if (hptr->next->h_ptr == ptr) {
175 hptr->next = hptr->next->next;
184 void *tracked_realloc(void *ptr, size_t size) {
186 struct TheHeap *hptr;
188 newptr = realloc(ptr, size);
190 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
191 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
198 void dump_tracked() {
199 struct TheHeap *hptr;
201 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
202 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
203 cprintf("%20s %5d\n",
204 hptr->h_file, hptr->h_line);
216 * We used to use master_cleanup() as a signal handler to shut down the server.
217 * however, master_cleanup() and the functions it calls do some things that
218 * aren't such a good idea to do from a signal handler: acquiring mutexes,
219 * playing with signal masks on BSDI systems, etc. so instead we install the
220 * following signal handler to set a global variable to inform the main loop
221 * that it's time to call master_cleanup() and exit.
224 volatile int time_to_die = 0;
226 static RETSIGTYPE signal_cleanup(int signum) {
232 * Some initialization stuff...
234 void init_sysdep(void) {
237 /* Set up a bunch of semaphores to be used for critical sections */
238 for (a=0; a<MAX_SEMAPHORES; ++a) {
239 pthread_mutex_init(&Critters[a], NULL);
243 * Set up a place to put thread-specific data.
244 * We only need a single pointer per thread - it points to the
245 * CitContext structure (in the ContextList linked list) of the
246 * session to which the calling thread is currently bound.
248 if (pthread_key_create(&MyConKey, NULL) != 0) {
249 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
253 * The action for unexpected signals and exceptions should be to
254 * call signal_cleanup() to gracefully shut down the server.
256 signal(SIGINT, signal_cleanup);
257 signal(SIGQUIT, signal_cleanup);
258 signal(SIGHUP, signal_cleanup);
259 signal(SIGTERM, signal_cleanup);
262 * Do not shut down the server on broken pipe signals, otherwise the
263 * whole Citadel service would come down whenever a single client
266 signal(SIGPIPE, SIG_IGN);
271 * Obtain a semaphore lock to begin a critical section.
273 void begin_critical_section(int which_one)
275 /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
276 /* ensure nobody ever tries to do a critical section within a
277 transaction; this could lead to deadlock. */
279 pthread_mutex_lock(&Critters[which_one]);
283 * Release a semaphore lock to end a critical section.
285 void end_critical_section(int which_one)
287 /* lprintf(9, "end_critical_section(%d)\n", which_one); */
288 pthread_mutex_unlock(&Critters[which_one]);
294 * This is a generic function to set up a master socket for listening on
295 * a TCP port. The server shuts down if the bind fails.
298 int ig_tcp_server(int port_number, int queue_len)
300 struct sockaddr_in sin;
302 int actual_queue_len;
304 actual_queue_len = queue_len;
305 if (actual_queue_len < 5) actual_queue_len = 5;
307 memset(&sin, 0, sizeof(sin));
308 sin.sin_family = AF_INET;
309 sin.sin_addr.s_addr = INADDR_ANY;
310 sin.sin_port = htons((u_short)port_number);
312 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
315 lprintf(1, "citserver: Can't create a socket: %s\n",
321 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
323 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
324 lprintf(1, "citserver: Can't bind: %s\n",
330 if (listen(s, actual_queue_len) < 0) {
331 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
342 * Create a Unix domain socket and listen on it
344 int ig_uds_server(char *sockpath, int queue_len)
346 struct sockaddr_un addr;
349 int actual_queue_len;
351 actual_queue_len = queue_len;
352 if (actual_queue_len < 5) actual_queue_len = 5;
354 i = unlink(sockpath);
355 if (i != 0) if (errno != ENOENT) {
356 lprintf(1, "citserver: can't unlink %s: %s\n",
357 sockpath, strerror(errno));
361 memset(&addr, 0, sizeof(addr));
362 addr.sun_family = AF_UNIX;
363 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
365 s = socket(AF_UNIX, SOCK_STREAM, 0);
367 lprintf(1, "citserver: Can't create a socket: %s\n",
372 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
373 lprintf(1, "citserver: Can't bind: %s\n",
378 if (listen(s, actual_queue_len) < 0) {
379 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
383 chmod(sockpath, 0777);
390 * Return a pointer to the CitContext structure bound to the thread which
391 * called this function. If there's no such binding (for example, if it's
392 * called by the housekeeper thread) then a generic 'master' CC is returned.
394 struct CitContext *MyContext(void) {
395 struct CitContext *retCC;
396 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
397 if (retCC == NULL) retCC = &masterCC;
403 * Initialize a new context and place it in the list. The session number
404 * used to be the PID (which is why it's called cs_pid), but that was when we
405 * had one process per session. Now we just assign them sequentially, starting
406 * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
407 * sessions terminate.
409 struct CitContext *CreateNewContext(void) {
410 struct CitContext *me, *ptr;
412 me = (struct CitContext *) mallok(sizeof(struct CitContext));
414 lprintf(1, "citserver: can't allocate memory!!\n");
417 memset(me, 0, sizeof(struct CitContext));
419 /* The new context will be created already in the CON_EXECUTING state
420 * in order to prevent another thread from grabbing it while it's
423 me->state = CON_EXECUTING;
427 * Generate a unique session number and insert this context into
430 begin_critical_section(S_SESSION_TABLE);
432 if (ContextList == NULL) {
438 else if (ContextList->cs_pid > 1) {
439 me->next = ContextList;
445 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
446 if (ptr->next == NULL) {
448 me->cs_pid = ptr->cs_pid + 1;
452 else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
453 me->next = ptr->next;
455 me->cs_pid = ptr->cs_pid + 1;
461 DONE: ++num_sessions;
462 end_critical_section(S_SESSION_TABLE);
469 * client_write() ... Send binary data to the client.
471 void client_write(char *buf, int nbytes)
473 int bytes_written = 0;
478 if (CC->redirect_fp != NULL) {
479 fwrite(buf, nbytes, 1, CC->redirect_fp);
483 if (CC->redirect_sock > 0) {
484 sock = CC->redirect_sock; /* and continue below... */
487 sock = CC->client_socket;
490 while (bytes_written < nbytes) {
491 retval = write(sock, &buf[bytes_written],
492 nbytes - bytes_written);
494 lprintf(2, "client_write() failed: %s\n",
496 if (sock == CC->client_socket) CC->kill_me = 1;
499 bytes_written = bytes_written + retval;
505 * cprintf() ... Send formatted printable data to the client. It is
506 * implemented in terms of client_write() but remains in
507 * sysdep.c in case we port to somewhere without va_args...
509 void cprintf(const char *format, ...) {
513 va_start(arg_ptr, format);
514 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
515 buf[sizeof buf - 2] = '\n';
516 client_write(buf, strlen(buf));
522 * Read data from the client socket.
524 * 1 Requested number of bytes has been read.
525 * 0 Request timed out.
526 * -1 The socket is broken.
527 * If the socket breaks, the session will be terminated.
529 int client_read_to(char *buf, int bytes, int timeout)
539 FD_SET(CC->client_socket, &rfds);
543 retval = select( (CC->client_socket)+1,
544 &rfds, NULL, NULL, &tv);
546 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
550 rlen = read(CC->client_socket, &buf[len], bytes-len);
552 lprintf(2, "client_read() failed: %s\n",
563 * Read data from the client socket with default timeout.
564 * (This is implemented in terms of client_read_to() and could be
565 * justifiably moved out of sysdep.c)
567 int client_read(char *buf, int bytes)
569 return(client_read_to(buf, bytes, config.c_sleeping));
574 * client_gets() ... Get a LF-terminated line of text from the client.
575 * (This is implemented in terms of client_read() and could be
576 * justifiably moved out of sysdep.c)
578 int client_gets(char *buf)
582 /* Read one character at a time.
585 retval = client_read(&buf[i], 1);
586 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
590 /* If we got a long line, discard characters until the newline.
593 while (buf[i] != '\n' && retval == 1)
594 retval = client_read(&buf[i], 1);
596 /* Strip the trailing newline and any trailing nonprintables (cr's)
599 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
600 buf[strlen(buf)-1] = 0;
601 if (retval < 0) strcpy(buf, "000");
608 * The system-dependent part of master_cleanup() - close the master socket.
610 void sysdep_master_cleanup(void) {
611 struct ServiceFunctionHook *serviceptr;
614 * close all protocol master sockets
616 for (serviceptr = ServiceHookTable; serviceptr != NULL;
617 serviceptr = serviceptr->next ) {
619 if (serviceptr->tcp_port > 0)
620 lprintf(3, "Closing listener on port %d\n",
621 serviceptr->tcp_port);
623 if (serviceptr->sockpath != NULL)
624 lprintf(3, "Closing listener on '%s'\n",
625 serviceptr->sockpath);
627 close(serviceptr->msock);
629 /* If it's a Unix domain socket, remove the file. */
630 if (serviceptr->sockpath != NULL) {
631 unlink(serviceptr->sockpath);
638 * Terminate another session.
639 * (This could justifiably be moved out of sysdep.c because it
640 * no longer does anything that is system-dependent.)
642 void kill_session(int session_to_kill) {
643 struct CitContext *ptr;
645 begin_critical_section(S_SESSION_TABLE);
646 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
647 if (ptr->cs_pid == session_to_kill) {
651 end_critical_section(S_SESSION_TABLE);
658 * Start running as a daemon. Only close stdio if do_close_stdio is set.
660 void start_daemon(int do_close_stdio) {
661 if (do_close_stdio) {
666 signal(SIGHUP,SIG_IGN);
667 signal(SIGINT,SIG_IGN);
668 signal(SIGQUIT,SIG_IGN);
669 if (fork()!=0) exit(0);
675 * Tie in to the 'netsetup' program.
677 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
679 void cmd_nset(char *cmdbuf)
686 char netsetup_args[3][SIZ];
688 if (CC->usersupp.axlevel < 6) {
689 cprintf("%d Higher access required.\n",
690 ERROR + HIGHER_ACCESS_REQUIRED);
694 for (a=1; a<=3; ++a) {
695 if (num_parms(cmdbuf) >= a) {
696 extract(netsetup_args[a-1], cmdbuf, a-1);
697 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
698 if (netsetup_args[a-1][b] == 34) {
699 netsetup_args[a-1][b] = '_';
704 netsetup_args[a-1][0] = 0;
708 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
709 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
710 netsetup = popen(fbuf, "r");
711 if (netsetup == NULL) {
712 cprintf("%d %s\n", ERROR, strerror(errno));
717 while (ch = getc(netsetup), (ch > 0)) {
718 fbuf[strlen(fbuf)+1] = 0;
719 fbuf[strlen(fbuf)] = ch;
722 retcode = pclose(netsetup);
725 for (a=0; a<strlen(fbuf); ++a) {
726 if (fbuf[a] < 32) fbuf[a] = 32;
729 cprintf("%d %s\n", ERROR, fbuf);
733 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
735 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
742 * Generic routine to convert a login name to a full name (gecos)
743 * Returns nonzero if a conversion took place
745 int convert_login(char NameToConvert[]) {
749 pw = getpwnam(NameToConvert);
754 strcpy(NameToConvert, pw->pw_gecos);
755 for (a=0; a<strlen(NameToConvert); ++a) {
756 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
762 static struct worker_node {
764 struct worker_node *next;
765 } *worker_list = NULL;
769 * create a worker thread. this function must always be called from within
770 * an S_WORKER_LIST critical section!
772 static void create_worker(void) {
774 struct worker_node *n = mallok(sizeof *n);
777 lprintf(1, "can't allocate worker_node, exiting\n");
782 if ((ret = pthread_create(&n->tid, NULL, worker_thread, NULL) != 0))
785 lprintf(1, "Can't create worker thread: %s\n",
789 n->next = worker_list;
796 * Purge all sessions which have the 'kill_me' flag set.
797 * This function has code to prevent it from running more than once every
798 * few seconds, because running it after every single unbind would waste a lot
799 * of CPU time and keep the context list locked too much.
801 * After that's done, we raise or lower the size of the worker thread pool
802 * if such an action is appropriate.
804 void dead_session_purge(void) {
805 struct CitContext *ptr, *rem;
806 struct worker_node **node, *tmp;
809 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
814 begin_critical_section(S_SESSION_TABLE);
815 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
816 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
820 end_critical_section(S_SESSION_TABLE);
822 /* RemoveContext() enters its own S_SESSION_TABLE critical
823 * section, so we have to do it like this.
826 lprintf(9, "Purging session %d\n", rem->cs_pid);
830 } while (rem != NULL);
833 /* Raise or lower the size of the worker thread pool if such
834 * an action is appropriate.
837 self = pthread_self();
839 if ( (num_sessions > num_threads)
840 && (num_threads < config.c_max_workers) ) {
841 begin_critical_section(S_WORKER_LIST);
843 end_critical_section(S_WORKER_LIST);
846 /* don't let the initial thread die since it's responsible for
847 waiting for all the other threads to terminate. */
848 else if ( (num_sessions < num_threads)
849 && (num_threads > config.c_min_workers)
850 && (self != initial_thread) ) {
852 begin_critical_section(S_WORKER_LIST);
855 /* we're exiting before server shutdown... unlink ourself from
856 the worker list and detach our thread to avoid memory leaks
859 for (node = &worker_list; *node != NULL; node = &(*node)->next)
860 if ((*node)->tid == self) {
862 *node = (*node)->next;
867 pthread_detach(self);
868 end_critical_section(S_WORKER_LIST);
879 * Redirect a session's output to a file or socket.
880 * This function may be called with a file handle *or* a socket (but not
881 * both). Call with neither to return output to its normal client socket.
883 void CtdlRedirectOutput(FILE *fp, int sock) {
885 if (fp != NULL) CC->redirect_fp = fp;
886 else CC->redirect_fp = NULL;
888 if (sock > 0) CC->redirect_sock = sock;
889 else CC->redirect_sock = (-1);
895 * masterCC is the context we use when not attached to a session. This
896 * function initializes it.
898 void InitializeMasterCC(void) {
899 memset(&masterCC, 0, sizeof(struct CitContext));
900 masterCC.internal_pgm = 1;
907 * Set up a fd_set containing all the master sockets to which we
908 * always listen. It's computationally less expensive to just copy
909 * this to a local fd_set when starting a new select() and then add
910 * the client sockets than it is to initialize a new one and then
911 * figure out what to put there.
913 void init_master_fdset(void) {
914 struct ServiceFunctionHook *serviceptr;
917 lprintf(9, "Initializing master fdset\n");
922 lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
923 FD_SET(rescan[0], &masterfds);
924 if (rescan[0] > masterhighest) masterhighest = rescan[0];
926 for (serviceptr = ServiceHookTable; serviceptr != NULL;
927 serviceptr = serviceptr->next ) {
928 m = serviceptr->msock;
929 lprintf(9, "Will listen on master socket %d\n", m);
930 FD_SET(m, &masterfds);
931 if (m > masterhighest) {
935 lprintf(9, "masterhighest = %d\n", masterhighest);
941 * Here's where it all begins.
943 int main(int argc, char **argv)
945 char tracefile[128]; /* Name of file to log traces to */
946 int a, i; /* General-purpose variables */
948 int drop_root_perms = 1;
950 struct worker_node *wnp;
952 /* specify default port name and trace file */
953 strcpy(tracefile, "");
955 /* initialize the master context */
956 InitializeMasterCC();
958 /* parse command-line arguments */
959 for (a=1; a<argc; ++a) {
961 /* -t specifies where to log trace messages to */
962 if (!strncmp(argv[a], "-t", 2)) {
963 strcpy(tracefile, argv[a]);
964 strcpy(tracefile, &tracefile[2]);
965 freopen(tracefile, "r", stdin);
966 freopen(tracefile, "w", stdout);
967 freopen(tracefile, "w", stderr);
970 /* run in the background if -d was specified */
971 else if (!strcmp(argv[a], "-d")) {
972 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
975 /* -x specifies the desired logging level */
976 else if (!strncmp(argv[a], "-x", 2)) {
977 verbosity = atoi(&argv[a][2]);
980 else if (!strncmp(argv[a], "-h", 2)) {
981 safestrncpy(bbs_home_directory, &argv[a][2],
982 sizeof bbs_home_directory);
986 else if (!strncmp(argv[a], "-f", 2)) {
990 /* -r tells the server not to drop root permissions. don't use
991 * this unless you know what you're doing. this should be
992 * removed in the next release if it proves unnecessary. */
993 else if (!strcmp(argv[a], "-r"))
996 /* any other parameter makes it crash and burn */
998 lprintf(1, "citserver: usage: "
999 "citserver [-tTraceFile] [-d] [-f]"
1000 " [-xLogLevel] [-hHomeDir]\n");
1006 /* Tell 'em who's in da house */
1008 "\nMultithreaded message server for Citadel/UX\n"
1009 "Copyright (C) 1987-2001 by the Citadel/UX development team.\n"
1010 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
1011 "you are welcome to change it and/or distribute copies of it under certain\n"
1012 "conditions. There is absolutely no warranty for this software. Please\n"
1013 "read the 'COPYING.txt' file for details.\n\n");
1017 openlog("citserver", LOG_PID, LOG_USER);
1019 /* Load site-specific parameters */
1020 lprintf(7, "Loading citadel.config\n");
1025 * Do non system dependent startup functions.
1030 * Bind the server to a Unix-domain socket.
1032 CtdlRegisterServiceHook(0,
1034 citproto_begin_session,
1038 * Bind the server to our favorite TCP port (usually 504).
1040 CtdlRegisterServiceHook(config.c_port_number,
1042 citproto_begin_session,
1046 * Load any server-side modules (plugins) available here.
1048 lprintf(7, "Initializing loadable modules\n");
1049 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
1050 sprintf(moddir, "%s/modules", bbs_home_directory);
1051 DLoader_Init(moddir);
1056 * The rescan pipe exists so that worker threads can be woken up and
1057 * told to re-scan the context list for fd's to listen on. This is
1058 * necessary, for example, when a context is about to go idle and needs
1059 * to get back on that list.
1062 lprintf(1, "Can't create rescan pipe!\n");
1066 init_master_fdset();
1069 * Now that we've bound the sockets, change to the BBS user id and its
1070 * corresponding group ids
1072 if (drop_root_perms) {
1073 if ((pw = getpwuid(BBSUID)) == NULL)
1074 lprintf(1, "WARNING: getpwuid(%d): %s\n"
1075 "Group IDs will be incorrect.\n", BBSUID,
1078 initgroups(pw->pw_name, pw->pw_gid);
1079 if (setgid(pw->pw_gid))
1080 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
1083 lprintf(7, "Changing uid to %d\n", BBSUID);
1084 if (setuid(BBSUID) != 0) {
1085 lprintf(3, "setuid() failed: %s\n", strerror(errno));
1089 /* We want to check for idle sessions once per minute */
1090 CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
1093 * Now create a bunch of worker threads.
1095 lprintf(9, "Starting %d worker threads\n", config.c_min_workers-1);
1096 begin_critical_section(S_WORKER_LIST);
1097 for (i=0; i<(config.c_min_workers-1); ++i) {
1100 end_critical_section(S_WORKER_LIST);
1102 /* Now this thread can become a worker as well. */
1103 initial_thread = pthread_self();
1104 worker_thread(NULL);
1106 /* Server is exiting. Wait for workers to shutdown. */
1107 lprintf(7, "Waiting for worker threads to shut down\n");
1109 begin_critical_section(S_WORKER_LIST);
1110 while (worker_list != NULL) {
1112 worker_list = wnp->next;
1114 /* avoid deadlock with an exiting thread */
1115 end_critical_section(S_WORKER_LIST);
1116 if ((i = pthread_join(wnp->tid, NULL)))
1117 lprintf(1, "pthread_join: %s\n", strerror(i));
1119 begin_critical_section(S_WORKER_LIST);
1121 end_critical_section(S_WORKER_LIST);
1130 * Bind a thread to a context. (It's inline merely to speed things up.)
1132 inline void become_session(struct CitContext *which_con) {
1133 pthread_setspecific(MyConKey, (void *)which_con );
1139 * This loop just keeps going and going and going...
1141 void *worker_thread(void *arg) {
1145 struct CitContext *ptr;
1146 struct CitContext *bind_me = NULL;
1149 struct CitContext *con= NULL; /* Temporary context pointer */
1150 struct ServiceFunctionHook *serviceptr;
1151 struct sockaddr_in fsin; /* Data for master socket */
1152 int alen; /* Data for master socket */
1153 int ssock; /* Descriptor for client socket */
1160 while (!time_to_die) {
1163 * A naive implementation would have all idle threads
1164 * calling select() and then they'd all wake up at once. We
1165 * solve this problem by putting the select() in a critical
1166 * section, so only one thread has the opportunity to wake
1167 * up. If we wake up on a master socket, create a new
1168 * session context; otherwise, just bind the thread to the
1169 * context we want and go on our merry way.
1172 /* make doubly sure we're not holding any stale db handles
1173 * which might cause a deadlock.
1175 cdb_check_handles();
1177 begin_critical_section(S_I_WANNA_SELECT);
1178 SETUP_FD: memcpy(&readfds, &masterfds, sizeof masterfds);
1179 highest = masterhighest;
1180 begin_critical_section(S_SESSION_TABLE);
1181 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1182 if (ptr->state == CON_IDLE) {
1183 FD_SET(ptr->client_socket, &readfds);
1184 if (ptr->client_socket > highest)
1185 highest = ptr->client_socket;
1188 end_critical_section(S_SESSION_TABLE);
1190 tv.tv_sec = 1; /* wake up every second if no input */
1195 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1197 end_critical_section(S_I_WANNA_SELECT);
1201 /* Now figure out who made this select() unblock.
1202 * First, check for an error or exit condition.
1205 if (errno != EINTR) {
1206 lprintf(9, "Exiting (%s)\n", strerror(errno));
1208 } else if (!time_to_die)
1212 /* Next, check to see if it's a new client connecting
1213 * on a master socket.
1215 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1216 serviceptr = serviceptr->next ) {
1218 if (FD_ISSET(serviceptr->msock, &readfds)) {
1220 ssock = accept(serviceptr->msock,
1221 (struct sockaddr *)&fsin, &alen);
1223 lprintf(2, "citserver: accept(): %s\n",
1227 lprintf(7, "citserver: "
1228 "New client socket %d\n",
1231 /* New context will be created already
1232 * set up in the CON_EXECUTING state.
1234 con = CreateNewContext();
1236 /* Assign new socket number to it. */
1237 con->client_socket = ssock;
1238 con->h_command_function =
1239 serviceptr->h_command_function;
1241 /* Determine whether local socket */
1242 if (serviceptr->sockpath != NULL)
1243 con->is_local_socket = 1;
1245 /* Set the SO_REUSEADDR socket option */
1247 setsockopt(ssock, SOL_SOCKET,
1251 become_session(con);
1253 serviceptr->h_greeting_function();
1254 become_session(NULL);
1255 con->state = CON_IDLE;
1261 /* If the rescan pipe went active, someone is telling this
1262 * thread that the &readfds needs to be refreshed with more
1266 end_critical_section(S_I_WANNA_SELECT);
1270 if (FD_ISSET(rescan[0], &readfds)) {
1271 read(rescan[0], &junk, 1);
1275 /* It must be a client socket. Find a context that has data
1276 * waiting on its socket *and* is in the CON_IDLE state.
1280 begin_critical_section(S_SESSION_TABLE);
1281 for (ptr = ContextList;
1282 ( (ptr != NULL) && (bind_me == NULL) );
1284 if ( (FD_ISSET(ptr->client_socket, &readfds))
1285 && (ptr->state == CON_IDLE) ) {
1289 if (bind_me != NULL) {
1290 /* Found one. Stake a claim to it before
1291 * letting anyone else touch the context list.
1293 bind_me->state = CON_EXECUTING;
1296 end_critical_section(S_SESSION_TABLE);
1297 end_critical_section(S_I_WANNA_SELECT);
1299 /* We're bound to a session, now do *one* command */
1300 if (bind_me != NULL) {
1301 become_session(bind_me);
1302 CC->h_command_function();
1303 become_session(NULL);
1304 bind_me->state = CON_IDLE;
1305 if (bind_me->kill_me == 1) {
1306 RemoveContext(bind_me);
1308 write(rescan[1], &junk, 1);
1312 dead_session_purge();
1314 check_sched_shutdown();
1317 /* If control reaches this point, the server is shutting down */