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.
9 * Wherever possible, we use function wrappers and type definitions to create
10 * abstractions that are platform-independent from the calling side.
12 * Eventually we'll try porting to a different platform and either have
13 * multiple variants of this file or simply load it up with #ifdefs.
24 #include <sys/types.h>
26 #include <sys/socket.h>
29 #include <netinet/in.h>
45 #include "sysdep_decls.h"
46 #include "citserver.h"
50 #include "housekeeping.h"
51 #include "dynloader.h"
54 #ifdef HAVE_SYS_SELECT_H
55 #include <sys/select.h>
62 #ifdef DEBUG_MEMORY_LEAKS
63 struct TheHeap *heap = NULL;
66 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
67 pthread_key_t MyConKey; /* TSD key for MyContext() */
69 int msock; /* master listening socket */
70 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
72 struct CitContext masterCC;
73 int rescan[2]; /* The Rescan Pipe */
76 * lprintf() ... Write logging information
78 void lprintf(int loglevel, const char *format, ...) {
82 va_start(arg_ptr, format);
83 vsprintf(buf, format, arg_ptr);
86 if (loglevel <= verbosity) {
87 fprintf(stderr, "%s", buf);
91 PerformLogHooks(loglevel, buf);
96 #ifdef DEBUG_MEMORY_LEAKS
97 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
103 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
104 tsize, tfile, tline);
108 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
109 strcpy(hptr->h_file, tfile);
110 hptr->h_line = tline;
117 char *tracked_strdup(const char *orig, char *tfile, int tline) {
120 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
121 if (s == NULL) return NULL;
127 void tracked_free(void *ptr) {
128 struct TheHeap *hptr, *freeme;
130 if (heap->h_ptr == ptr) {
136 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
137 if (hptr->next->h_ptr == ptr) {
139 hptr->next = hptr->next->next;
148 void *tracked_realloc(void *ptr, size_t size) {
150 struct TheHeap *hptr;
152 newptr = realloc(ptr, size);
154 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
155 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
162 void dump_tracked() {
163 struct TheHeap *hptr;
165 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
166 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
167 cprintf("%20s %5d\n",
168 hptr->h_file, hptr->h_line);
180 * we used to use master_cleanup() as a signal handler to shut down the server.
181 * however, master_cleanup() and the functions it calls do some things that
182 * aren't such a good idea to do from a signal handler: acquiring mutexes,
183 * playing with signal masks on BSDI systems, etc. so instead we install the
184 * following signal handler to set a global variable to inform the main loop
185 * that it's time to call master_cleanup() and exit.
188 static volatile int time_to_die = 0;
190 static RETSIGTYPE signal_cleanup(int signum) {
196 * Some initialization stuff...
198 void init_sysdep(void) {
201 /* Set up a bunch of semaphores to be used for critical sections */
202 for (a=0; a<MAX_SEMAPHORES; ++a) {
203 pthread_mutex_init(&Critters[a], NULL);
207 * Set up a place to put thread-specific data.
208 * We only need a single pointer per thread - it points to the
209 * thread's CitContext structure in the ContextList linked list.
211 if (pthread_key_create(&MyConKey, NULL) != 0) {
212 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
216 * The action for unexpected signals and exceptions should be to
217 * call signal_cleanup() to gracefully shut down the server.
219 signal(SIGINT, signal_cleanup);
220 signal(SIGQUIT, signal_cleanup);
221 signal(SIGHUP, signal_cleanup);
222 signal(SIGTERM, signal_cleanup);
225 * Do not shut down the server on broken pipe signals, otherwise the
226 * whole Citadel service would come down whenever a single client
229 signal(SIGPIPE, SIG_IGN);
234 * Obtain a semaphore lock to begin a critical section.
236 void begin_critical_section(int which_one)
238 pthread_mutex_lock(&Critters[which_one]);
242 * Release a semaphore lock to end a critical section.
244 void end_critical_section(int which_one)
246 pthread_mutex_unlock(&Critters[which_one]);
252 * This is a generic function to set up a master socket for listening on
253 * a TCP port. The server shuts down if the bind fails.
255 int ig_tcp_server(int port_number, int queue_len)
257 struct sockaddr_in sin;
260 memset(&sin, 0, sizeof(sin));
261 sin.sin_family = AF_INET;
262 sin.sin_addr.s_addr = INADDR_ANY;
264 if (port_number == 0) {
266 "citserver: No port number specified. Run setup.\n");
270 sin.sin_port = htons((u_short)port_number);
272 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
274 lprintf(1, "citserver: Can't create a socket: %s\n",
279 /* Set the SO_REUSEADDR socket option, because it makes sense. */
281 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
283 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
284 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
288 if (listen(s, queue_len) < 0) {
289 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
299 * Return a pointer to the CitContext structure bound to the thread which
300 * called this function. If there's no such binding (for example, if it's
301 * called by the housekeeper thread) then a generic 'master' CC is returned.
303 struct CitContext *MyContext(void) {
304 struct CitContext *retCC;
305 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
306 if (retCC == NULL) retCC = &masterCC;
312 * Initialize a new context and place it in the list.
314 struct CitContext *CreateNewContext(void) {
315 struct CitContext *me;
317 me = (struct CitContext *) mallok(sizeof(struct CitContext));
319 lprintf(1, "citserver: can't allocate memory!!\n");
322 memset(me, 0, sizeof(struct CitContext));
324 /* The new context will be created already in the CON_EXECUTING state
325 * in order to prevent another thread from grabbing it while it's
328 me->state = CON_EXECUTING;
330 begin_critical_section(S_SESSION_TABLE);
331 me->next = ContextList;
333 end_critical_section(S_SESSION_TABLE);
340 * Return the number of sessions currently running.
341 * (This should probably be moved out of sysdep.c)
343 int session_count(void) {
344 struct CitContext *ptr;
347 begin_critical_section(S_SESSION_TABLE);
348 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
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",
370 CC->state = CON_DYING;
372 bytes_written = bytes_written + retval;
378 * cprintf() ... Send formatted printable data to the client. It is
379 * implemented in terms of client_write() but remains in
380 * sysdep.c in case we port to somewhere without va_args...
382 void cprintf(const char *format, ...) {
386 va_start(arg_ptr, format);
387 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
388 buf[sizeof buf - 2] = '\n';
389 client_write(buf, strlen(buf));
395 * Read data from the client socket.
397 * 1 Requested number of bytes has been read.
398 * 0 Request timed out.
399 * If the socket breaks, the session is immediately terminated.
401 int client_read_to(char *buf, int bytes, int timeout)
411 FD_SET(CC->client_socket, &rfds);
415 retval = select( (CC->client_socket)+1,
416 &rfds, NULL, NULL, &tv);
418 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
422 rlen = read(CC->client_socket, &buf[len], bytes-len);
424 lprintf(2, "client_read() failed: %s\n",
426 CC->state = CON_DYING;
434 * Read data from the client socket with default timeout.
435 * (This is implemented in terms of client_read_to() and could be
436 * justifiably moved out of sysdep.c)
438 int client_read(char *buf, int bytes)
440 return(client_read_to(buf, bytes, config.c_sleeping));
445 * client_gets() ... Get a LF-terminated line of text from the client.
446 * (This is implemented in terms of client_read() and could be
447 * justifiably moved out of sysdep.c)
449 int client_gets(char *buf)
453 /* Read one character at a time.
456 retval = client_read(&buf[i], 1);
457 if (retval != 1 || buf[i] == '\n' || i == 255)
461 /* If we got a long line, discard characters until the newline.
464 while (buf[i] != '\n' && retval == 1)
465 retval = client_read(&buf[i], 1);
467 /* Strip the trailing newline and any trailing nonprintables (cr's)
470 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
471 buf[strlen(buf)-1] = 0;
478 * The system-dependent part of master_cleanup() - close the master socket.
480 void sysdep_master_cleanup(void) {
481 lprintf(7, "Closing master socket %d\n", msock);
487 * Terminate another session.
488 * FIX ... now we need some way to wake that session up so it knows it
489 * needs to terminate.
491 void kill_session(int session_to_kill) {
492 struct CitContext *ptr;
494 begin_critical_section(S_SESSION_TABLE);
495 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
496 if (ptr->cs_pid == session_to_kill) {
497 ptr->state = CON_DYING;
500 end_critical_section(S_SESSION_TABLE);
507 * Start running as a daemon. Only close stdio if do_close_stdio is set.
509 void start_daemon(int do_close_stdio) {
510 if (do_close_stdio) {
515 signal(SIGHUP,SIG_IGN);
516 signal(SIGINT,SIG_IGN);
517 signal(SIGQUIT,SIG_IGN);
518 if (fork()!=0) exit(0);
524 * Tie in to the 'netsetup' program.
526 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
528 void cmd_nset(char *cmdbuf)
535 char netsetup_args[3][256];
537 if (CC->usersupp.axlevel < 6) {
538 cprintf("%d Higher access required.\n",
539 ERROR + HIGHER_ACCESS_REQUIRED);
543 for (a=1; a<=3; ++a) {
544 if (num_parms(cmdbuf) >= a) {
545 extract(netsetup_args[a-1], cmdbuf, a-1);
546 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
547 if (netsetup_args[a-1][b] == 34) {
548 netsetup_args[a-1][b] = '_';
553 netsetup_args[a-1][0] = 0;
557 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
558 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
559 netsetup = popen(fbuf, "r");
560 if (netsetup == NULL) {
561 cprintf("%d %s\n", ERROR, strerror(errno));
566 while (ch = getc(netsetup), (ch > 0)) {
567 fbuf[strlen(fbuf)+1] = 0;
568 fbuf[strlen(fbuf)] = ch;
571 retcode = pclose(netsetup);
574 for (a=0; a<strlen(fbuf); ++a) {
575 if (fbuf[a] < 32) fbuf[a] = 32;
578 cprintf("%d %s\n", ERROR, fbuf);
582 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
584 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
591 * Generic routine to convert a login name to a full name (gecos)
592 * Returns nonzero if a conversion took place
594 int convert_login(char NameToConvert[]) {
598 pw = getpwnam(NameToConvert);
603 strcpy(NameToConvert, pw->pw_gecos);
604 for (a=0; a<strlen(NameToConvert); ++a) {
605 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
617 * Here's where it all begins.
619 int main(int argc, char **argv)
621 pthread_t HousekeepingThread; /* Thread descriptor */
622 pthread_attr_t attr; /* Thread attributes */
623 char tracefile[128]; /* Name of file to log traces to */
624 int a, i; /* General-purpose variables */
626 int drop_root_perms = 1;
629 /* specify default port name and trace file */
630 strcpy(tracefile, "");
632 /* parse command-line arguments */
633 for (a=1; a<argc; ++a) {
635 /* -t specifies where to log trace messages to */
636 if (!strncmp(argv[a], "-t", 2)) {
637 strcpy(tracefile, argv[a]);
638 strcpy(tracefile, &tracefile[2]);
639 freopen(tracefile, "r", stdin);
640 freopen(tracefile, "w", stdout);
641 freopen(tracefile, "w", stderr);
644 /* run in the background if -d was specified */
645 else if (!strcmp(argv[a], "-d")) {
646 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
649 /* -x specifies the desired logging level */
650 else if (!strncmp(argv[a], "-x", 2)) {
651 verbosity = atoi(&argv[a][2]);
654 else if (!strncmp(argv[a], "-h", 2)) {
655 safestrncpy(bbs_home_directory, &argv[a][2],
656 sizeof bbs_home_directory);
660 else if (!strncmp(argv[a], "-f", 2)) {
664 /* -r tells the server not to drop root permissions. don't use
665 * this unless you know what you're doing. this should be
666 * removed in the next release if it proves unnecessary. */
667 else if (!strcmp(argv[a], "-r"))
670 /* any other parameter makes it crash and burn */
672 lprintf(1, "citserver: usage: "
673 "citserver [-tTraceFile] [-d] [-f]"
674 " [-xLogLevel] [-hHomeDir]\n");
680 /* Tell 'em who's in da house */
682 "\nMultithreaded message server for Citadel/UX\n"
683 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
684 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
685 "you are welcome to change it and/or distribute copies of it under certain\n"
686 "conditions. There is absolutely no warranty for this software. Please\n"
687 "read the 'COPYING.txt' file for details.\n\n");
691 openlog("citserver",LOG_PID,LOG_USER);
693 /* Load site-specific parameters */
694 lprintf(7, "Loading citadel.config\n");
698 * Bind the server to our favourite port.
699 * There is no need to check for errors, because ig_tcp_server()
700 * exits if it doesn't succeed.
702 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
703 msock = ig_tcp_server(config.c_port_number, 5);
704 lprintf(7, "Listening on socket %d\n", msock);
707 * Now that we've bound the socket, change to the BBS user id and its
708 * corresponding group ids
710 if (drop_root_perms) {
711 if ((pw = getpwuid(BBSUID)) == NULL)
712 lprintf(1, "WARNING: getpwuid(%d): %s\n"
713 "Group IDs will be incorrect.\n", BBSUID,
716 initgroups(pw->pw_name, pw->pw_gid);
717 if (setgid(pw->pw_gid))
718 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
721 lprintf(7, "Changing uid to %d\n", BBSUID);
722 if (setuid(BBSUID) != 0) {
723 lprintf(3, "setuid() failed: %s\n", strerror(errno));
728 * Do non system dependent startup functions.
733 * Load any server-side modules (plugins) available here.
735 lprintf(7, "Initializing loadable modules\n");
736 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
737 sprintf(moddir, "%s/modules", bbs_home_directory);
738 DLoader_Init(moddir);
742 lprintf(7, "Starting housekeeper thread\n");
743 pthread_attr_init(&attr);
744 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
745 if (pthread_create(&HousekeepingThread, &attr,
746 (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
747 lprintf(1, "Can't create housekeeping thead: %s\n",
753 * The rescan pipe exists so that worker threads can be woken up and
754 * told to re-scan the context list for fd's to listen on. This is
755 * necessary, for example, when a context is about to go idle and needs
756 * to get back on that list.
759 lprintf(1, "Can't create rescan pipe!\n");
764 * Now create a bunch of worker threads.
766 for (i=0; i<(NUM_WORKER_THREADS-1); ++i) {
767 pthread_attr_init(&attr);
768 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
769 if (pthread_create(&HousekeepingThread, &attr,
770 (void* (*)(void*)) worker_thread, NULL) != 0) {
771 lprintf(1, "Can't create worker thead: %s\n",
776 /* Now this thread can become a worker as well. */
789 * This loop just keeps going and going and going...
791 void worker_thread(void) {
796 struct CitContext *ptr;
797 struct CitContext *bind_me = NULL;
800 struct CitContext *con= NULL; /* Temporary context pointer */
801 struct sockaddr_in fsin; /* Data for master socket */
802 int alen; /* Data for master socket */
803 int ssock; /* Descriptor for client socket */
805 while (!time_to_die) {
808 * In a stupid environment, we would have all idle threads
809 * calling select() and then they'd all wake up at once. We
810 * solve this problem by putting the select() in a critical
811 * section, so only one thread has the opportunity to wake
812 * up. If we wake up on the master socket, create a new
813 * session context; otherwise, just bind the thread to the
814 * context we want and go on our merry way.
817 begin_critical_section(S_I_WANNA_SELECT);
818 SETUP_FD: FD_ZERO(&readfds);
819 FD_SET(msock, &readfds);
821 FD_SET(rescan[0], &readfds);
822 if (rescan[0] > highest) highest = rescan[0];
825 begin_critical_section(S_SESSION_TABLE);
826 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
827 if (ptr->state == CON_IDLE) {
828 FD_SET(ptr->client_socket, &readfds);
829 if (ptr->client_socket > highest)
830 highest = ptr->client_socket;
834 end_critical_section(S_SESSION_TABLE);
836 retval = select(highest + 1, &readfds, NULL, NULL, NULL);
838 /* Now figure out who made this select() unblock.
839 * First, check for an error or exit condition.
842 end_critical_section(S_I_WANNA_SELECT);
843 lprintf(9, "Exiting (%s)\n", errno);
847 /* Next, check to see if it's a new client connecting
848 * on the master socket.
850 else if (FD_ISSET(msock, &readfds)) {
852 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
854 lprintf(2, "citserver: accept() failed: %s\n",
858 lprintf(7, "citserver: New client socket %d\n",
861 /* New context will be created already set up
862 * in the CON_EXECUTING state.
864 con = CreateNewContext();
866 /* Assign our new socket number to it. */
867 con->client_socket = ssock;
869 /* Set the SO_REUSEADDR socket option */
871 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
874 pthread_setspecific(MyConKey, (void *)con);
876 /* do_command_loop(); */
877 pthread_setspecific(MyConKey, (void *)NULL);
878 con->state = CON_IDLE;
883 /* If the rescan pipe went active, someone is telling this
884 * thread that the &readfds needs to be refreshed with more
887 else if (FD_ISSET(rescan[0], &readfds)) {
888 read(rescan[0], &junk, 1);
892 /* It must be a client socket. Find a context that has data
893 * waiting on its socket *and* is in the CON_IDLE state.
897 begin_critical_section(S_SESSION_TABLE);
898 for (ptr = ContextList;
899 ( (ptr != NULL) && (bind_me == NULL) );
901 if ( (FD_ISSET(ptr->client_socket, &readfds))
902 && (ptr->state == CON_IDLE) ) {
906 if (bind_me != NULL) {
907 /* Found one. Stake a claim to it before
908 * letting anyone else touch the context list.
910 bind_me->state = CON_EXECUTING;
913 end_critical_section(S_SESSION_TABLE);
914 end_critical_section(S_I_WANNA_SELECT);
916 /* We're bound to a session, now do *one* command */
917 if (bind_me != NULL) {
918 pthread_setspecific(MyConKey, (void *)bind_me);
920 pthread_setspecific(MyConKey, (void *)NULL);
921 if (bind_me->state == CON_DYING) {
925 bind_me->state = CON_IDLE;
927 write(rescan[1], &junk, 1);
930 lprintf(9, "Thread %02d found nothing to do!\n",