2 * Citadel/UX "system dependent" stuff.
3 * See copyright.txt for copyright information.
7 * Here's where we (hopefully) have all the parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * Eventually we'll try porting to a different platform and either have
11 * multiple variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
24 #include <sys/socket.h>
27 #include <netinet/in.h>
43 #include "sysdep_decls.h"
44 #include "citserver.h"
48 #include "housekeeping.h"
49 #include "dynloader.h"
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
60 #ifdef DEBUG_MEMORY_LEAKS
61 struct TheHeap *heap = NULL;
64 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
65 pthread_key_t MyConKey; /* TSD key for MyContext() */
67 int msock; /* master listening socket */
68 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
70 struct CitContext masterCC;
71 int rescan[2]; /* The Rescan Pipe */
72 time_t last_purge = 0; /* Last dead session purge */
73 int num_threads = 0; /* Current number of threads */
74 int num_sessions = 0; /* Current number of sessions */
77 * lprintf() ... Write logging information
79 void lprintf(int loglevel, const char *format, ...) {
83 va_start(arg_ptr, format);
84 vsprintf(buf, format, arg_ptr);
87 if (loglevel <= verbosity) {
88 fprintf(stderr, "%s", buf);
92 PerformLogHooks(loglevel, buf);
97 #ifdef DEBUG_MEMORY_LEAKS
98 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
100 struct TheHeap *hptr;
104 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
105 tsize, tfile, tline);
109 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
110 strcpy(hptr->h_file, tfile);
111 hptr->h_line = tline;
118 char *tracked_strdup(const char *orig, char *tfile, int tline) {
121 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
122 if (s == NULL) return NULL;
128 void tracked_free(void *ptr) {
129 struct TheHeap *hptr, *freeme;
131 if (heap->h_ptr == ptr) {
137 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
138 if (hptr->next->h_ptr == ptr) {
140 hptr->next = hptr->next->next;
149 void *tracked_realloc(void *ptr, size_t size) {
151 struct TheHeap *hptr;
153 newptr = realloc(ptr, size);
155 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
156 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
163 void dump_tracked() {
164 struct TheHeap *hptr;
166 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
167 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
168 cprintf("%20s %5d\n",
169 hptr->h_file, hptr->h_line);
181 * we used to use master_cleanup() as a signal handler to shut down the server.
182 * however, master_cleanup() and the functions it calls do some things that
183 * aren't such a good idea to do from a signal handler: acquiring mutexes,
184 * playing with signal masks on BSDI systems, etc. so instead we install the
185 * following signal handler to set a global variable to inform the main loop
186 * that it's time to call master_cleanup() and exit.
189 static volatile int time_to_die = 0;
191 static RETSIGTYPE signal_cleanup(int signum) {
197 * Some initialization stuff...
199 void init_sysdep(void) {
202 /* Set up a bunch of semaphores to be used for critical sections */
203 for (a=0; a<MAX_SEMAPHORES; ++a) {
204 pthread_mutex_init(&Critters[a], NULL);
208 * Set up a place to put thread-specific data.
209 * We only need a single pointer per thread - it points to the
210 * thread's CitContext structure in the ContextList linked list.
212 if (pthread_key_create(&MyConKey, NULL) != 0) {
213 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
217 * The action for unexpected signals and exceptions should be to
218 * call signal_cleanup() to gracefully shut down the server.
220 signal(SIGINT, signal_cleanup);
221 signal(SIGQUIT, signal_cleanup);
222 signal(SIGHUP, signal_cleanup);
223 signal(SIGTERM, signal_cleanup);
226 * Do not shut down the server on broken pipe signals, otherwise the
227 * whole Citadel service would come down whenever a single client
230 signal(SIGPIPE, SIG_IGN);
235 * Obtain a semaphore lock to begin a critical section.
237 void begin_critical_section(int which_one)
239 pthread_mutex_lock(&Critters[which_one]);
243 * Release a semaphore lock to end a critical section.
245 void end_critical_section(int which_one)
247 pthread_mutex_unlock(&Critters[which_one]);
253 * This is a generic function to set up a master socket for listening on
254 * a TCP port. The server shuts down if the bind fails.
256 int ig_tcp_server(int port_number, int queue_len)
258 struct sockaddr_in sin;
261 memset(&sin, 0, sizeof(sin));
262 sin.sin_family = AF_INET;
263 sin.sin_addr.s_addr = INADDR_ANY;
265 if (port_number == 0) {
267 "citserver: No port number specified. Run setup.\n");
271 sin.sin_port = htons((u_short)port_number);
273 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
275 lprintf(1, "citserver: Can't create a socket: %s\n",
280 /* Set the SO_REUSEADDR socket option, because it makes sense. */
282 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
284 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
285 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
289 if (listen(s, queue_len) < 0) {
290 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
300 * Return a pointer to the CitContext structure bound to the thread which
301 * called this function. If there's no such binding (for example, if it's
302 * called by the housekeeper thread) then a generic 'master' CC is returned.
304 struct CitContext *MyContext(void) {
305 struct CitContext *retCC;
306 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
307 if (retCC == NULL) retCC = &masterCC;
313 * Initialize a new context and place it in the list.
315 struct CitContext *CreateNewContext(void) {
316 struct CitContext *me, *ptr;
320 me = (struct CitContext *) mallok(sizeof(struct CitContext));
322 lprintf(1, "citserver: can't allocate memory!!\n");
325 memset(me, 0, sizeof(struct CitContext));
327 /* The new context will be created already in the CON_EXECUTING state
328 * in order to prevent another thread from grabbing it while it's
331 me->state = CON_EXECUTING;
333 begin_critical_section(S_SESSION_TABLE);
335 /* obtain a unique session number */
338 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
339 if (ptr->cs_pid == num) {
344 } while (startover == 1);
347 me->next = ContextList;
351 end_critical_section(S_SESSION_TABLE);
358 * client_write() ... Send binary data to the client.
360 void client_write(char *buf, int nbytes)
362 int bytes_written = 0;
364 while (bytes_written < nbytes) {
365 retval = write(CC->client_socket, &buf[bytes_written],
366 nbytes - bytes_written);
368 lprintf(2, "client_write() failed: %s\n",
373 bytes_written = bytes_written + retval;
379 * cprintf() ... Send formatted printable data to the client. It is
380 * implemented in terms of client_write() but remains in
381 * sysdep.c in case we port to somewhere without va_args...
383 void cprintf(const char *format, ...) {
387 va_start(arg_ptr, format);
388 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
389 buf[sizeof buf - 2] = '\n';
390 client_write(buf, strlen(buf));
396 * Read data from the client socket.
398 * 1 Requested number of bytes has been read.
399 * 0 Request timed out.
400 * If the socket breaks, the session is immediately terminated.
402 int client_read_to(char *buf, int bytes, int timeout)
412 FD_SET(CC->client_socket, &rfds);
416 retval = select( (CC->client_socket)+1,
417 &rfds, NULL, NULL, &tv);
419 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
423 rlen = read(CC->client_socket, &buf[len], bytes-len);
425 lprintf(2, "client_read() failed: %s\n",
436 * Read data from the client socket with default timeout.
437 * (This is implemented in terms of client_read_to() and could be
438 * justifiably moved out of sysdep.c)
440 int client_read(char *buf, int bytes)
442 return(client_read_to(buf, bytes, config.c_sleeping));
447 * client_gets() ... Get a LF-terminated line of text from the client.
448 * (This is implemented in terms of client_read() and could be
449 * justifiably moved out of sysdep.c)
451 int client_gets(char *buf)
455 /* Read one character at a time.
458 retval = client_read(&buf[i], 1);
459 if (retval != 1 || buf[i] == '\n' || i == 255)
463 /* If we got a long line, discard characters until the newline.
466 while (buf[i] != '\n' && retval == 1)
467 retval = client_read(&buf[i], 1);
469 /* Strip the trailing newline and any trailing nonprintables (cr's)
472 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
473 buf[strlen(buf)-1] = 0;
480 * The system-dependent part of master_cleanup() - close the master socket.
482 void sysdep_master_cleanup(void) {
483 lprintf(7, "Closing master socket %d\n", msock);
489 * Terminate another session.
490 * (This could justifiably be moved out of sysdep.c because it
491 * no longer does anything that is system-dependent.)
493 void kill_session(int session_to_kill) {
494 struct CitContext *ptr;
496 begin_critical_section(S_SESSION_TABLE);
497 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
498 if (ptr->cs_pid == session_to_kill) {
502 end_critical_section(S_SESSION_TABLE);
509 * Start running as a daemon. Only close stdio if do_close_stdio is set.
511 void start_daemon(int do_close_stdio) {
512 if (do_close_stdio) {
517 signal(SIGHUP,SIG_IGN);
518 signal(SIGINT,SIG_IGN);
519 signal(SIGQUIT,SIG_IGN);
520 if (fork()!=0) exit(0);
526 * Tie in to the 'netsetup' program.
528 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
530 void cmd_nset(char *cmdbuf)
537 char netsetup_args[3][256];
539 if (CC->usersupp.axlevel < 6) {
540 cprintf("%d Higher access required.\n",
541 ERROR + HIGHER_ACCESS_REQUIRED);
545 for (a=1; a<=3; ++a) {
546 if (num_parms(cmdbuf) >= a) {
547 extract(netsetup_args[a-1], cmdbuf, a-1);
548 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
549 if (netsetup_args[a-1][b] == 34) {
550 netsetup_args[a-1][b] = '_';
555 netsetup_args[a-1][0] = 0;
559 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
560 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
561 netsetup = popen(fbuf, "r");
562 if (netsetup == NULL) {
563 cprintf("%d %s\n", ERROR, strerror(errno));
568 while (ch = getc(netsetup), (ch > 0)) {
569 fbuf[strlen(fbuf)+1] = 0;
570 fbuf[strlen(fbuf)] = ch;
573 retcode = pclose(netsetup);
576 for (a=0; a<strlen(fbuf); ++a) {
577 if (fbuf[a] < 32) fbuf[a] = 32;
580 cprintf("%d %s\n", ERROR, fbuf);
584 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
586 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
593 * Generic routine to convert a login name to a full name (gecos)
594 * Returns nonzero if a conversion took place
596 int convert_login(char NameToConvert[]) {
600 pw = getpwnam(NameToConvert);
605 strcpy(NameToConvert, pw->pw_gecos);
606 for (a=0; a<strlen(NameToConvert); ++a) {
607 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
616 * Purge all sessions which have the 'kill_me' flag set.
617 * This function has code to prevent it from running more than once every
618 * few seconds, because running it after every single unbind would waste a lot
619 * of CPU time and keep the context list locked too much.
621 * After that's done, we raise or lower the size of the worker thread pool
622 * if such an action is appropriate.
624 void dead_session_purge(void) {
625 struct CitContext *ptr, *rem;
629 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
634 begin_critical_section(S_SESSION_TABLE);
635 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
636 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
640 end_critical_section(S_SESSION_TABLE);
642 /* RemoveContext() enters its own S_SESSION_TABLE critical
643 * section, so we have to do it like this.
646 lprintf(9, "Purging session %d\n", rem->cs_pid);
650 } while (rem != NULL);
653 /* Raise or lower the size of the worker thread pool if such
654 * an action is appropriate.
657 if ( (num_sessions > num_threads)
658 && (num_threads < config.c_max_workers) ) {
660 pthread_attr_init(&attr);
661 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
662 if (pthread_create(&newthread, &attr,
663 (void* (*)(void*)) worker_thread, NULL) != 0) {
664 lprintf(1, "Can't create worker thead: %s\n",
670 else if ( (num_sessions < num_threads)
671 && (num_threads > config.c_min_workers) ) {
682 * Here's where it all begins.
684 int main(int argc, char **argv)
686 pthread_t HousekeepingThread; /* Thread descriptor */
687 pthread_attr_t attr; /* Thread attributes */
688 char tracefile[128]; /* Name of file to log traces to */
689 int a, i; /* General-purpose variables */
691 int drop_root_perms = 1;
694 /* specify default port name and trace file */
695 strcpy(tracefile, "");
697 /* parse command-line arguments */
698 for (a=1; a<argc; ++a) {
700 /* -t specifies where to log trace messages to */
701 if (!strncmp(argv[a], "-t", 2)) {
702 strcpy(tracefile, argv[a]);
703 strcpy(tracefile, &tracefile[2]);
704 freopen(tracefile, "r", stdin);
705 freopen(tracefile, "w", stdout);
706 freopen(tracefile, "w", stderr);
709 /* run in the background if -d was specified */
710 else if (!strcmp(argv[a], "-d")) {
711 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
714 /* -x specifies the desired logging level */
715 else if (!strncmp(argv[a], "-x", 2)) {
716 verbosity = atoi(&argv[a][2]);
719 else if (!strncmp(argv[a], "-h", 2)) {
720 safestrncpy(bbs_home_directory, &argv[a][2],
721 sizeof bbs_home_directory);
725 else if (!strncmp(argv[a], "-f", 2)) {
729 /* -r tells the server not to drop root permissions. don't use
730 * this unless you know what you're doing. this should be
731 * removed in the next release if it proves unnecessary. */
732 else if (!strcmp(argv[a], "-r"))
735 /* any other parameter makes it crash and burn */
737 lprintf(1, "citserver: usage: "
738 "citserver [-tTraceFile] [-d] [-f]"
739 " [-xLogLevel] [-hHomeDir]\n");
745 /* Tell 'em who's in da house */
747 "\nMultithreaded message server for Citadel/UX\n"
748 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
749 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
750 "you are welcome to change it and/or distribute copies of it under certain\n"
751 "conditions. There is absolutely no warranty for this software. Please\n"
752 "read the 'COPYING.txt' file for details.\n\n");
756 openlog("citserver",LOG_PID,LOG_USER);
758 /* Load site-specific parameters */
759 lprintf(7, "Loading citadel.config\n");
763 * Bind the server to our favourite port.
764 * There is no need to check for errors, because ig_tcp_server()
765 * exits if it doesn't succeed.
767 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
768 msock = ig_tcp_server(config.c_port_number, 5);
769 lprintf(7, "Listening on socket %d\n", msock);
772 * Now that we've bound the socket, change to the BBS user id and its
773 * corresponding group ids
775 if (drop_root_perms) {
776 if ((pw = getpwuid(BBSUID)) == NULL)
777 lprintf(1, "WARNING: getpwuid(%d): %s\n"
778 "Group IDs will be incorrect.\n", BBSUID,
781 initgroups(pw->pw_name, pw->pw_gid);
782 if (setgid(pw->pw_gid))
783 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
786 lprintf(7, "Changing uid to %d\n", BBSUID);
787 if (setuid(BBSUID) != 0) {
788 lprintf(3, "setuid() failed: %s\n", strerror(errno));
793 * Do non system dependent startup functions.
798 * Load any server-side modules (plugins) available here.
800 lprintf(7, "Initializing loadable modules\n");
801 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
802 sprintf(moddir, "%s/modules", bbs_home_directory);
803 DLoader_Init(moddir);
807 lprintf(7, "Starting housekeeper thread\n");
808 pthread_attr_init(&attr);
809 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
810 if (pthread_create(&HousekeepingThread, &attr,
811 (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
812 lprintf(1, "Can't create housekeeping thead: %s\n",
818 * The rescan pipe exists so that worker threads can be woken up and
819 * told to re-scan the context list for fd's to listen on. This is
820 * necessary, for example, when a context is about to go idle and needs
821 * to get back on that list.
824 lprintf(1, "Can't create rescan pipe!\n");
829 * Now create a bunch of worker threads.
831 for (i=0; i<(config.c_min_workers-1); ++i) {
832 pthread_attr_init(&attr);
833 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
834 if (pthread_create(&HousekeepingThread, &attr,
835 (void* (*)(void*)) worker_thread, NULL) != 0) {
836 lprintf(1, "Can't create worker thead: %s\n",
841 /* Now this thread can become a worker as well. */
854 * This loop just keeps going and going and going...
856 void worker_thread(void) {
861 struct CitContext *ptr;
862 struct CitContext *bind_me = NULL;
865 struct CitContext *con= NULL; /* Temporary context pointer */
866 struct sockaddr_in fsin; /* Data for master socket */
867 int alen; /* Data for master socket */
868 int ssock; /* Descriptor for client socket */
871 while (!time_to_die) {
874 * A naive implementation would have all idle threads
875 * calling select() and then they'd all wake up at once. We
876 * solve this problem by putting the select() in a critical
877 * section, so only one thread has the opportunity to wake
878 * up. If we wake up on the master socket, create a new
879 * session context; otherwise, just bind the thread to the
880 * context we want and go on our merry way.
883 begin_critical_section(S_I_WANNA_SELECT);
884 SETUP_FD: FD_ZERO(&readfds);
885 FD_SET(msock, &readfds);
887 FD_SET(rescan[0], &readfds);
888 if (rescan[0] > highest) highest = rescan[0];
891 begin_critical_section(S_SESSION_TABLE);
892 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
893 if (ptr->state == CON_IDLE) {
894 FD_SET(ptr->client_socket, &readfds);
895 if (ptr->client_socket > highest)
896 highest = ptr->client_socket;
900 end_critical_section(S_SESSION_TABLE);
902 retval = select(highest + 1, &readfds, NULL, NULL, NULL);
904 /* Now figure out who made this select() unblock.
905 * First, check for an error or exit condition.
908 end_critical_section(S_I_WANNA_SELECT);
909 lprintf(9, "Exiting (%s)\n", strerror(errno));
913 /* Next, check to see if it's a new client connecting
914 * on the master socket.
916 else if (FD_ISSET(msock, &readfds)) {
918 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
920 lprintf(2, "citserver: accept() failed: %s\n",
924 lprintf(7, "citserver: New client socket %d\n",
927 /* New context will be created already set up
928 * in the CON_EXECUTING state.
930 con = CreateNewContext();
932 /* Assign our new socket number to it. */
933 con->client_socket = ssock;
935 /* Set the SO_REUSEADDR socket option */
937 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
940 pthread_setspecific(MyConKey, (void *)con);
942 /* do_command_loop(); */
943 pthread_setspecific(MyConKey, (void *)NULL);
944 con->state = CON_IDLE;
949 /* If the rescan pipe went active, someone is telling this
950 * thread that the &readfds needs to be refreshed with more
953 else if (FD_ISSET(rescan[0], &readfds)) {
954 read(rescan[0], &junk, 1);
958 /* It must be a client socket. Find a context that has data
959 * waiting on its socket *and* is in the CON_IDLE state.
963 begin_critical_section(S_SESSION_TABLE);
964 for (ptr = ContextList;
965 ( (ptr != NULL) && (bind_me == NULL) );
967 if ( (FD_ISSET(ptr->client_socket, &readfds))
968 && (ptr->state == CON_IDLE) ) {
972 if (bind_me != NULL) {
973 /* Found one. Stake a claim to it before
974 * letting anyone else touch the context list.
976 bind_me->state = CON_EXECUTING;
979 end_critical_section(S_SESSION_TABLE);
980 end_critical_section(S_I_WANNA_SELECT);
982 /* We're bound to a session, now do *one* command */
983 if (bind_me != NULL) {
984 pthread_setspecific(MyConKey, (void *)bind_me);
986 pthread_setspecific(MyConKey, (void *)NULL);
987 bind_me->state = CON_IDLE;
988 if (bind_me->kill_me == 1) {
989 RemoveContext(bind_me);
991 write(rescan[1], &junk, 1);
994 lprintf(9, "Thread found nothing to do!\n");
998 dead_session_purge();
1001 /* If control reaches this point, the server is shutting down */