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 = 3; /* Logging level */
72 struct CitContext masterCC;
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);
178 static pthread_t main_thread_id;
180 #ifndef HAVE_PTHREAD_CANCEL
182 * signal handler to fake thread cancellation; only required on BSDI as far
185 static RETSIGTYPE cancel_thread(int signum) {
191 * we used to use master_cleanup() as a signal handler to shut down the server.
192 * however, master_cleanup() and the functions it calls do some things that
193 * aren't such a good idea to do from a signal handler: acquiring mutexes,
194 * playing with signal masks on BSDI systems, etc. so instead we install the
195 * following signal handler to set a global variable to inform the main loop
196 * that it's time to call master_cleanup() and exit.
199 static volatile int time_to_die = 0;
201 static RETSIGTYPE signal_cleanup(int signum) {
207 * Some initialization stuff...
209 void init_sysdep(void) {
212 /* Set up a bunch of semaphores to be used for critical sections */
213 for (a=0; a<MAX_SEMAPHORES; ++a) {
214 pthread_mutex_init(&Critters[a], NULL);
218 * Set up a place to put thread-specific data.
219 * We only need a single pointer per thread - it points to the
220 * thread's CitContext structure in the ContextList linked list.
222 if (pthread_key_create(&MyConKey, NULL) != 0) {
223 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
227 * The action for unexpected signals and exceptions should be to
228 * call signal_cleanup() to gracefully shut down the server.
230 signal(SIGINT, signal_cleanup);
231 signal(SIGQUIT, signal_cleanup);
232 signal(SIGHUP, signal_cleanup);
233 signal(SIGTERM, signal_cleanup);
234 signal(SIGPIPE, SIG_IGN);
235 main_thread_id = pthread_self();
236 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
237 signal(SIGUSR1, cancel_thread);
243 * Obtain a semaphore lock to begin a critical section.
245 void begin_critical_section(int which_one)
247 #ifdef HAVE_PTHREAD_CANCEL
253 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
255 if (!pthread_equal(pthread_self(), main_thread_id)) {
256 /* Keep a count of how many critical sections this thread has
257 * open, so that end_critical_section() doesn't enable
258 * cancellation prematurely. */
260 #ifdef HAVE_PTHREAD_CANCEL
261 /* Don't get interrupted during the critical section */
262 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
264 /* We're faking cancellation with signals. Block SIGUSR1 while
265 * we're in the critical section. */
267 sigaddset(&set, SIGUSR1);
268 pthread_sigmask(SIG_BLOCK, &set, NULL);
272 /* Obtain a semaphore */
273 pthread_mutex_lock(&Critters[which_one]);
278 * Release a semaphore lock to end a critical section.
280 void end_critical_section(int which_one)
282 #ifdef HAVE_PTHREAD_CANCEL
288 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
290 /* Let go of the semaphore */
291 pthread_mutex_unlock(&Critters[which_one]);
293 if (!pthread_equal(pthread_self(), main_thread_id))
295 #ifdef HAVE_PTHREAD_CANCEL
296 /* If a cancel was sent during the critical section, do it now.
297 * Then re-enable thread cancellation.
299 pthread_testcancel();
300 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
301 pthread_testcancel();
303 /* We're faking it. Unblock SIGUSR1; signals sent during the
304 * critical section should now be able to kill us. */
306 sigaddset(&set, SIGUSR1);
307 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
316 * This is a generic function to set up a master socket for listening on
317 * a TCP port. The server shuts down if the bind fails.
319 int ig_tcp_server(int port_number, int queue_len)
321 struct sockaddr_in sin;
324 memset(&sin, 0, sizeof(sin));
325 sin.sin_family = AF_INET;
326 sin.sin_addr.s_addr = INADDR_ANY;
328 if (port_number == 0) {
330 "citserver: No port number specified. Run setup.\n");
334 sin.sin_port = htons((u_short)port_number);
336 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
338 lprintf(1, "citserver: Can't create a socket: %s\n",
343 /* Set the SO_REUSEADDR socket option, because it makes sense. */
345 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
347 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
348 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
352 if (listen(s, queue_len) < 0) {
353 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
362 * Return a pointer to a thread's own CitContext structure (old)
363 * NOTE: this version of MyContext() is commented out because it is no longer
364 * in use. It was written before I discovered TSD keys. This
365 * version pounds through the context list until it finds the one matching
366 * the currently running thread. It remains here, commented out, in case it
367 * is needed for future ports to threading libraries which have the equivalent
368 * of pthread_self() but not pthread_key_create() and its ilk.
370 * struct CitContext *MyContext() {
371 * struct CitContext *ptr;
374 * me = pthread_self();
375 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
376 * if (ptr->mythread == me) return(ptr);
383 * Return a pointer to a thread's own CitContext structure (new)
385 struct CitContext *MyContext(void) {
386 struct CitContext *retCC;
387 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
388 if (retCC == NULL) retCC = &masterCC;
394 * Wedge our way into the context list.
396 struct CitContext *CreateNewContext(void) {
397 struct CitContext *me;
399 me = (struct CitContext *) mallok(sizeof(struct CitContext));
401 lprintf(1, "citserver: can't allocate memory!!\n");
404 memset(me, 0, sizeof(struct CitContext));
406 begin_critical_section(S_SESSION_TABLE);
407 me->next = ContextList;
409 end_critical_section(S_SESSION_TABLE);
414 * Add a thread's thread ID to the context
416 void InitMyContext(struct CitContext *con)
418 #ifdef HAVE_PTHREAD_CANCEL
422 con->mythread = pthread_self();
423 #ifdef HAVE_PTHREAD_CANCEL
424 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
425 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
427 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
428 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
434 * Remove a context from the context list.
436 void RemoveContext(struct CitContext *con)
438 struct CitContext *ptr;
440 lprintf(7, "Starting RemoveContext()\n");
442 lprintf(7, "WARNING: RemoveContext() called with null!\n");
447 * session_count() starts its own S_SESSION_TABLE critical section;
448 * so do not call it from within this loop.
450 begin_critical_section(S_SESSION_TABLE);
451 lprintf(7, "Closing socket %d\n", con->client_socket);
452 close(con->client_socket);
454 if (ContextList==con) {
455 ContextList = ContextList->next;
458 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
459 if (ptr->next == con) {
460 ptr->next = con->next;
466 end_critical_section(S_SESSION_TABLE);
467 lprintf(7, "Done with RemoveContext\n");
472 * Return the number of sessions currently running.
473 * (This should probably be moved out of sysdep.c)
475 int session_count(void) {
476 struct CitContext *ptr;
479 begin_critical_section(S_SESSION_TABLE);
480 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
483 end_critical_section(S_SESSION_TABLE);
490 * client_write() ... Send binary data to the client.
492 void client_write(char *buf, int nbytes)
494 int bytes_written = 0;
496 while (bytes_written < nbytes) {
497 retval = write(CC->client_socket, &buf[bytes_written],
498 nbytes - bytes_written);
500 lprintf(2, "client_write() failed: %s\n",
504 bytes_written = bytes_written + retval;
510 * cprintf() ... Send formatted printable data to the client. It is
511 * implemented in terms of client_write() but remains in
512 * sysdep.c in case we port to somewhere without va_args...
514 void cprintf(const char *format, ...) {
518 va_start(arg_ptr, format);
519 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
520 buf[sizeof buf - 2] = '\n';
521 client_write(buf, strlen(buf));
527 * Read data from the client socket.
529 * 1 Requested number of bytes has been read.
530 * 0 Request timed out.
531 * If the socket breaks, the session is immediately terminated.
533 int client_read_to(char *buf, int bytes, int timeout)
543 FD_SET(CC->client_socket, &rfds);
547 retval = select( (CC->client_socket)+1,
548 &rfds, NULL, NULL, &tv);
549 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
553 rlen = read(CC->client_socket, &buf[len], bytes-len);
555 lprintf(2, "client_read() failed: %s\n",
565 * Read data from the client socket with default timeout.
566 * (This is implemented in terms of client_read_to() and could be
567 * justifiably moved out of sysdep.c)
569 int client_read(char *buf, int bytes)
571 return(client_read_to(buf, bytes, config.c_sleeping));
576 * client_gets() ... Get a LF-terminated line of text from the client.
577 * (This is implemented in terms of client_read() and could be
578 * justifiably moved out of sysdep.c)
580 int client_gets(char *buf)
584 /* Read one character at a time.
587 retval = client_read(&buf[i], 1);
588 if (retval != 1 || buf[i] == '\n' || i == 255)
592 /* If we got a long line, discard characters until the newline.
595 while (buf[i] != '\n' && retval == 1)
596 retval = client_read(&buf[i], 1);
598 /* Strip the trailing newline and any trailing nonprintables (cr's)
601 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
602 buf[strlen(buf)-1] = 0;
609 * The system-dependent part of master_cleanup() - close the master socket.
611 void sysdep_master_cleanup(void) {
612 lprintf(7, "Closing master socket %d\n", msock);
617 * Cleanup routine to be called when one thread is shutting down.
619 void cleanup(int exit_code)
621 /* Terminate the thread.
622 * Its cleanup handler will call cleanup_stuff()
624 lprintf(7, "Calling pthread_exit()\n");
629 * Terminate another session.
631 void kill_session(int session_to_kill) {
632 struct CitContext *ptr;
635 begin_critical_section(S_SESSION_TABLE);
636 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
637 if (ptr->cs_pid == session_to_kill) {
638 killme = ptr->mythread;
641 end_critical_section(S_SESSION_TABLE);
644 #ifdef HAVE_PTHREAD_CANCEL
645 pthread_cancel(killme);
647 pthread_kill(killme, SIGUSR1);
649 /* there's a very stupid bug in the user threads package on
650 FreeBSD 3.1 which prevents a signal from being properly
651 dispatched to a thread that's in a blocking syscall. the
652 first signal interrupts the syscall, the second one actually
654 pthread_kill(killme, SIGUSR1);
662 * The system-dependent wrapper around the main context loop.
664 void *sd_context_loop(struct CitContext *con) {
665 pthread_cleanup_push(*cleanup_stuff, NULL);
667 pthread_cleanup_pop(0);
673 * Start running as a daemon. Only close stdio if do_close_stdio is set.
675 void start_daemon(int do_close_stdio) {
676 if (do_close_stdio) {
681 signal(SIGHUP,SIG_IGN);
682 signal(SIGINT,SIG_IGN);
683 signal(SIGQUIT,SIG_IGN);
684 if (fork()!=0) exit(0);
690 * Tie in to the 'netsetup' program.
692 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
694 void cmd_nset(char *cmdbuf)
701 char netsetup_args[3][256];
703 if (CC->usersupp.axlevel < 6) {
704 cprintf("%d Higher access required.\n",
705 ERROR + HIGHER_ACCESS_REQUIRED);
709 for (a=1; a<=3; ++a) {
710 if (num_parms(cmdbuf) >= a) {
711 extract(netsetup_args[a-1], cmdbuf, a-1);
712 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
713 if (netsetup_args[a-1][b] == 34) {
714 netsetup_args[a-1][b] = '_';
719 netsetup_args[a-1][0] = 0;
723 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
724 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
725 netsetup = popen(fbuf, "r");
726 if (netsetup == NULL) {
727 cprintf("%d %s\n", ERROR, strerror(errno));
732 while (ch = getc(netsetup), (ch > 0)) {
733 fbuf[strlen(fbuf)+1] = 0;
734 fbuf[strlen(fbuf)] = ch;
737 retcode = pclose(netsetup);
740 for (a=0; a<strlen(fbuf); ++a) {
741 if (fbuf[a] < 32) fbuf[a] = 32;
744 cprintf("%d %s\n", ERROR, fbuf);
748 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
750 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
757 * Generic routine to convert a login name to a full name (gecos)
758 * Returns nonzero if a conversion took place
760 int convert_login(char NameToConvert[]) {
764 pw = getpwnam(NameToConvert);
769 strcpy(NameToConvert, pw->pw_gecos);
770 for (a=0; a<strlen(NameToConvert); ++a) {
771 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
783 * Here's where it all begins.
785 int main(int argc, char **argv)
787 struct sockaddr_in fsin; /* Data for master socket */
788 int alen; /* Data for master socket */
789 int ssock; /* Descriptor for master socket */
790 THREAD SessThread; /* Thread descriptor */
791 THREAD HousekeepingThread; /* Thread descriptor */
792 pthread_attr_t attr; /* Thread attributes */
793 struct CitContext *con; /* Temporary context pointer */
794 char tracefile[128]; /* Name of file to log traces to */
795 int a, i; /* General-purpose variables */
799 int drop_root_perms = 1;
802 /* specify default port name and trace file */
803 strcpy(tracefile, "");
805 /* parse command-line arguments */
806 for (a=1; a<argc; ++a) {
808 /* -t specifies where to log trace messages to */
809 if (!strncmp(argv[a], "-t", 2)) {
810 strcpy(tracefile, argv[a]);
811 strcpy(tracefile, &tracefile[2]);
812 freopen(tracefile, "r", stdin);
813 freopen(tracefile, "w", stdout);
814 freopen(tracefile, "w", stderr);
817 /* run in the background if -d was specified */
818 else if (!strcmp(argv[a], "-d")) {
819 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
822 /* -x specifies the desired logging level */
823 else if (!strncmp(argv[a], "-x", 2)) {
824 verbosity = atoi(&argv[a][2]);
827 else if (!strncmp(argv[a], "-h", 2)) {
828 safestrncpy(bbs_home_directory, &argv[a][2],
829 sizeof bbs_home_directory);
833 else if (!strncmp(argv[a], "-f", 2)) {
837 /* -r tells the server not to drop root permissions. don't use
838 * this unless you know what you're doing. this should be
839 * removed in the next release if it proves unnecessary. */
840 else if (!strcmp(argv[a], "-r"))
843 /* any other parameter makes it crash and burn */
845 lprintf(1, "citserver: usage: "
846 "citserver [-tTraceFile] [-d] [-f]"
847 " [-xLogLevel] [-hHomeDir]\n");
853 /* Tell 'em who's in da house */
855 "\nMultithreaded message server for Citadel/UX\n"
856 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
857 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
858 "you are welcome to change it and/or distribute copies of it under certain\n"
859 "conditions. There is absolutely no warranty for this software. Please\n"
860 "read the 'COPYING.txt' file for details.\n\n");
864 openlog("citserver",LOG_PID,LOG_USER);
865 /* Load site-specific parameters */
866 lprintf(7, "Loading citadel.config\n");
870 * Bind the server to our favourite port.
871 * There is no need to check for errors, because ig_tcp_server()
872 * exits if it doesn't succeed.
874 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
875 msock = ig_tcp_server(config.c_port_number, 5);
876 lprintf(7, "Listening on socket %d\n", msock);
879 * Now that we've bound the socket, change to the BBS user id and its
880 * corresponding group ids
882 if (drop_root_perms) {
883 if ((pw = getpwuid(BBSUID)) == NULL)
884 lprintf(1, "WARNING: getpwuid(%d): %s\n"
885 "Group IDs will be incorrect.\n", BBSUID,
888 initgroups(pw->pw_name, pw->pw_gid);
889 if (setgid(pw->pw_gid))
890 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
893 lprintf(7, "Changing uid to %d\n", BBSUID);
894 if (setuid(BBSUID) != 0) {
895 lprintf(3, "setuid() failed: %s\n", strerror(errno));
900 * Do non system dependent startup functions.
905 * Load any server-side modules (plugins) available here.
907 lprintf(7, "Initializing loadable modules\n");
908 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
909 sprintf(moddir, "%s/modules", bbs_home_directory);
910 DLoader_Init(moddir);
914 lprintf(7, "Starting housekeeper thread\n");
915 pthread_attr_init(&attr);
916 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
917 if (pthread_create(&HousekeepingThread, &attr,
918 (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
919 lprintf(1, "Can't create housekeeping thead: %s\n",
924 * Endless loop. Listen on the master socket. When a connection
925 * comes in, create a socket, a context, and a thread.
927 while (!time_to_die) {
928 /* we need to check if a signal has been delivered. because
929 * syscalls may be restartable across signals, we call
930 * select with a timeout of 1 second and repeatedly check for
933 FD_SET(msock, &readfds);
936 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
939 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
941 lprintf(2, "citserver: accept() failed: %s\n",
945 lprintf(7, "citserver: Client socket %d\n", ssock);
946 con = CreateNewContext();
947 con->client_socket = ssock;
949 /* Set the SO_REUSEADDR socket option */
951 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
954 /* set attributes for the new thread */
955 pthread_attr_init(&attr);
956 pthread_attr_setdetachstate(&attr,
957 PTHREAD_CREATE_DETACHED);
959 /* now create the thread */
960 if (pthread_create(&SessThread, &attr,
961 (void* (*)(void*)) sd_context_loop,
965 "citserver: can't create thread: %s\n",