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>
42 #include "sysdep_decls.h"
43 #include "citserver.h"
47 #include "housekeeping.h"
48 #include "dynloader.h"
51 #ifdef HAVE_SYS_SELECT_H
52 #include <sys/select.h>
59 #ifdef DEBUG_MEMORY_LEAKS
60 struct TheHeap *heap = NULL;
63 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
64 pthread_key_t MyConKey; /* TSD key for MyContext() */
66 int msock; /* master listening socket */
67 int verbosity = 3; /* Logging level */
69 struct CitContext masterCC;
73 * lprintf() ... Write logging information
75 void lprintf(int loglevel, const char *format, ...) {
79 va_start(arg_ptr, format);
80 vsprintf(buf, format, arg_ptr);
83 if (loglevel <= verbosity) {
84 fprintf(stderr, "%s", buf);
88 PerformLogHooks(loglevel, buf);
93 #ifdef DEBUG_MEMORY_LEAKS
94 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
99 if (ptr == NULL) return(NULL);
101 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
102 strcpy(hptr->h_file, tfile);
103 hptr->h_line = tline;
111 void tracked_free(void *ptr) {
112 struct TheHeap *hptr, *freeme;
114 if (heap->h_ptr == ptr) {
120 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
121 if (hptr->next->h_ptr == ptr) {
123 hptr->next = hptr->next->next;
132 void *tracked_realloc(void *ptr, size_t size) {
134 struct TheHeap *hptr;
136 newptr = realloc(ptr, size);
138 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
139 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
146 void dump_tracked() {
147 struct TheHeap *hptr;
149 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
150 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
151 cprintf("%20s %5d\n",
152 hptr->h_file, hptr->h_line);
158 static pthread_t main_thread_id;
160 #ifndef HAVE_PTHREAD_CANCEL
162 * signal handler to fake thread cancellation; only required on BSDI as far
165 static RETSIGTYPE cancel_thread(int signum) {
171 * we used to use master_cleanup() as a signal handler to shut down the server.
172 * however, master_cleanup() and the functions it calls do some things that
173 * aren't such a good idea to do from a signal handler: acquiring mutexes,
174 * playing with signal masks on BSDI systems, etc. so instead we install the
175 * following signal handler to set a global variable to inform the main loop
176 * that it's time to call master_cleanup() and exit.
179 static volatile int time_to_die = 0;
181 static RETSIGTYPE signal_cleanup(int signum) {
187 * Some initialization stuff...
189 void init_sysdep(void) {
192 /* Set up a bunch of semaphores to be used for critical sections */
193 for (a=0; a<MAX_SEMAPHORES; ++a) {
194 pthread_mutex_init(&Critters[a], NULL);
198 * Set up a place to put thread-specific data.
199 * We only need a single pointer per thread - it points to the
200 * thread's CitContext structure in the ContextList linked list.
202 if (pthread_key_create(&MyConKey, NULL) != 0) {
203 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
207 * The action for unexpected signals and exceptions should be to
208 * call signal_cleanup() to gracefully shut down the server.
210 signal(SIGINT, signal_cleanup);
211 signal(SIGQUIT, signal_cleanup);
212 signal(SIGHUP, signal_cleanup);
213 signal(SIGTERM, signal_cleanup);
214 signal(SIGPIPE, SIG_IGN);
215 main_thread_id = pthread_self();
216 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
217 signal(SIGUSR1, cancel_thread);
223 * Obtain a semaphore lock to begin a critical section.
225 void begin_critical_section(int which_one)
227 #ifdef HAVE_PTHREAD_CANCEL
233 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
235 if (!pthread_equal(pthread_self(), main_thread_id)) {
236 /* Keep a count of how many critical sections this thread has
237 * open, so that end_critical_section() doesn't enable
238 * cancellation prematurely. */
240 #ifdef HAVE_PTHREAD_CANCEL
241 /* Don't get interrupted during the critical section */
242 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
244 /* We're faking cancellation with signals. Block SIGUSR1 while
245 * we're in the critical section. */
247 sigaddset(&set, SIGUSR1);
248 pthread_sigmask(SIG_BLOCK, &set, NULL);
252 /* Obtain a semaphore */
253 pthread_mutex_lock(&Critters[which_one]);
258 * Release a semaphore lock to end a critical section.
260 void end_critical_section(int which_one)
262 #ifdef HAVE_PTHREAD_CANCEL
268 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
270 /* Let go of the semaphore */
271 pthread_mutex_unlock(&Critters[which_one]);
273 if (!pthread_equal(pthread_self(), main_thread_id))
275 #ifdef HAVE_PTHREAD_CANCEL
276 /* If a cancel was sent during the critical section, do it now.
277 * Then re-enable thread cancellation.
279 pthread_testcancel();
280 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
281 pthread_testcancel();
283 /* We're faking it. Unblock SIGUSR1; signals sent during the
284 * critical section should now be able to kill us. */
286 sigaddset(&set, SIGUSR1);
287 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
296 * This is a generic function to set up a master socket for listening on
297 * a TCP port. The server shuts down if the bind fails.
299 int ig_tcp_server(int port_number, int queue_len)
301 struct sockaddr_in sin;
304 memset(&sin, 0, sizeof(sin));
305 sin.sin_family = AF_INET;
306 sin.sin_addr.s_addr = INADDR_ANY;
308 if (port_number == 0) {
310 "citserver: No port number specified. Run setup.\n");
314 sin.sin_port = htons((u_short)port_number);
316 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
318 lprintf(1, "citserver: Can't create a socket: %s\n",
323 /* Set the SO_REUSEADDR socket option, because it makes sense. */
325 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
327 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
328 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
332 if (listen(s, queue_len) < 0) {
333 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
342 * Return a pointer to a thread's own CitContext structure (old)
343 * NOTE: this version of MyContext() is commented out because it is no longer
344 * in use. It was written before I discovered TSD keys. This
345 * version pounds through the context list until it finds the one matching
346 * the currently running thread. It remains here, commented out, in case it
347 * is needed for future ports to threading libraries which have the equivalent
348 * of pthread_self() but not pthread_key_create() and its ilk.
350 * struct CitContext *MyContext() {
351 * struct CitContext *ptr;
354 * me = pthread_self();
355 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
356 * if (ptr->mythread == me) return(ptr);
363 * Return a pointer to a thread's own CitContext structure (new)
365 struct CitContext *MyContext(void) {
366 struct CitContext *retCC;
367 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
368 if (retCC == NULL) retCC = &masterCC;
374 * Wedge our way into the context list.
376 struct CitContext *CreateNewContext(void) {
377 struct CitContext *me;
379 lprintf(9, "CreateNewContext: calling malloc()\n");
380 me = (struct CitContext *) mallok(sizeof(struct CitContext));
382 lprintf(1, "citserver: can't allocate memory!!\n");
385 memset(me, 0, sizeof(struct CitContext));
387 begin_critical_section(S_SESSION_TABLE);
388 me->next = ContextList;
390 end_critical_section(S_SESSION_TABLE);
395 * Add a thread's thread ID to the context
397 void InitMyContext(struct CitContext *con)
399 #ifdef HAVE_PTHREAD_CANCEL
403 con->mythread = pthread_self();
404 #ifdef HAVE_PTHREAD_CANCEL
405 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
406 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
408 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
409 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
415 * Remove a context from the context list.
417 void RemoveContext(struct CitContext *con)
419 struct CitContext *ptr;
421 lprintf(7, "Starting RemoveContext()\n");
422 lprintf(9, "Session count before RemoveContext is %d\n",
425 lprintf(7, "WARNING: RemoveContext() called with null!\n");
430 * session_count() starts its own S_SESSION_TABLE critical section;
431 * so do not call it from within this loop.
433 begin_critical_section(S_SESSION_TABLE);
434 lprintf(7, "Closing socket %d\n", con->client_socket);
435 close(con->client_socket);
437 lprintf(9, "Dereferencing session context\n");
438 if (ContextList==con) {
439 ContextList = ContextList->next;
442 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
443 if (ptr->next == con) {
444 ptr->next = con->next;
449 lprintf(9, "Freeing session context...\n");
451 lprintf(9, "...done.\n");
452 end_critical_section(S_SESSION_TABLE);
454 lprintf(9, "Session count after RemoveContext is %d\n",
457 lprintf(7, "Done with RemoveContext\n");
462 * Return the number of sessions currently running.
463 * (This should probably be moved out of sysdep.c)
465 int session_count(void) {
466 struct CitContext *ptr;
469 lprintf(9, "session_count() starting\n");
470 begin_critical_section(S_SESSION_TABLE);
471 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
473 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
475 end_critical_section(S_SESSION_TABLE);
477 lprintf(9, "session_count() finishing\n");
483 * client_write() ... Send binary data to the client.
485 void client_write(char *buf, int nbytes)
487 int bytes_written = 0;
489 while (bytes_written < nbytes) {
490 retval = write(CC->client_socket, &buf[bytes_written],
491 nbytes - bytes_written);
493 lprintf(2, "client_write() failed: %s\n",
497 bytes_written = bytes_written + retval;
503 * cprintf() ... Send formatted printable data to the client. It is
504 * implemented in terms of client_write() but remains in
505 * sysdep.c in case we port to somewhere without va_args...
507 void cprintf(const char *format, ...) {
511 va_start(arg_ptr, format);
512 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
513 buf[sizeof buf - 2] = '\n';
514 client_write(buf, strlen(buf));
520 * Read data from the client socket.
522 * 1 Requested number of bytes has been read.
523 * 0 Request timed out.
524 * If the socket breaks, the session is immediately terminated.
526 int client_read_to(char *buf, int bytes, int timeout)
536 FD_SET(CC->client_socket, &rfds);
540 retval = select( (CC->client_socket)+1,
541 &rfds, NULL, NULL, &tv);
542 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
546 rlen = read(CC->client_socket, &buf[len], bytes-len);
548 lprintf(2, "client_read() failed: %s\n",
558 * Read data from the client socket with default timeout.
559 * (This is implemented in terms of client_read_to() and could be
560 * justifiably moved out of sysdep.c)
562 int client_read(char *buf, int bytes)
564 return(client_read_to(buf, bytes, config.c_sleeping));
569 * client_gets() ... Get a LF-terminated line of text from the client.
570 * (This is implemented in terms of client_read() and could be
571 * justifiably moved out of sysdep.c)
573 int client_gets(char *buf)
577 /* Read one character at a time.
580 retval = client_read(&buf[i], 1);
581 if (retval != 1 || buf[i] == '\n' || i == 255)
585 /* If we got a long line, discard characters until the newline.
588 while (buf[i] != '\n' && retval == 1)
589 retval = client_read(&buf[i], 1);
591 /* Strip the trailing newline and any trailing nonprintables (cr's)
594 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
595 buf[strlen(buf)-1] = 0;
602 * The system-dependent part of master_cleanup() - close the master socket.
604 void sysdep_master_cleanup(void) {
605 lprintf(7, "Closing master socket %d\n", msock);
610 * Cleanup routine to be called when one thread is shutting down.
612 void cleanup(int exit_code)
614 /* Terminate the thread.
615 * Its cleanup handler will call cleanup_stuff()
617 lprintf(7, "Calling pthread_exit()\n");
622 * Terminate another session.
624 void kill_session(int session_to_kill) {
625 struct CitContext *ptr;
628 lprintf(9, "kill_session() scanning for thread to cancel...\n");
629 begin_critical_section(S_SESSION_TABLE);
630 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
631 if (ptr->cs_pid == session_to_kill) {
632 killme = ptr->mythread;
635 end_critical_section(S_SESSION_TABLE);
636 lprintf(9, "kill_session() finished scanning.\n");
639 #ifdef HAVE_PTHREAD_CANCEL
640 lprintf(9, "calling pthread_cancel()\n");
641 pthread_cancel(killme);
643 pthread_kill(killme, SIGUSR1);
645 /* there's a very stupid bug in the user threads package on
646 FreeBSD 3.1 which prevents a signal from being properly
647 dispatched to a thread that's in a blocking syscall. the
648 first signal interrupts the syscall, the second one actually
650 pthread_kill(killme, SIGUSR1);
658 * The system-dependent wrapper around the main context loop.
660 void *sd_context_loop(struct CitContext *con) {
661 pthread_cleanup_push(*cleanup_stuff, NULL);
663 pthread_cleanup_pop(0);
669 * Start running as a daemon. Only close stdio if do_close_stdio is set.
671 void start_daemon(int do_close_stdio) {
672 if (do_close_stdio) {
677 signal(SIGHUP,SIG_IGN);
678 signal(SIGINT,SIG_IGN);
679 signal(SIGQUIT,SIG_IGN);
680 if (fork()!=0) exit(0);
686 * Tie in to the 'netsetup' program.
688 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
690 void cmd_nset(char *cmdbuf)
697 char netsetup_args[3][256];
699 if (CC->usersupp.axlevel < 6) {
700 cprintf("%d Higher access required.\n",
701 ERROR + HIGHER_ACCESS_REQUIRED);
705 for (a=1; a<=3; ++a) {
706 if (num_parms(cmdbuf) >= a) {
707 extract(netsetup_args[a-1], cmdbuf, a-1);
708 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
709 if (netsetup_args[a-1][b] == 34) {
710 netsetup_args[a-1][b] = '_';
715 netsetup_args[a-1][0] = 0;
719 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
720 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
721 netsetup = popen(fbuf, "r");
722 if (netsetup == NULL) {
723 cprintf("%d %s\n", ERROR, strerror(errno));
728 while (ch = getc(netsetup), (ch > 0)) {
729 fbuf[strlen(fbuf)+1] = 0;
730 fbuf[strlen(fbuf)] = ch;
733 retcode = pclose(netsetup);
736 for (a=0; a<strlen(fbuf); ++a) {
737 if (fbuf[a] < 32) fbuf[a] = 32;
740 cprintf("%d %s\n", ERROR, fbuf);
744 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
746 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
753 * Generic routine to convert a login name to a full name (gecos)
754 * Returns nonzero if a conversion took place
756 int convert_login(char NameToConvert[]) {
760 pw = getpwnam(NameToConvert);
765 strcpy(NameToConvert, pw->pw_gecos);
766 for (a=0; a<strlen(NameToConvert); ++a) {
767 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
779 * Here's where it all begins.
781 int main(int argc, char **argv)
783 struct sockaddr_in fsin; /* Data for master socket */
784 int alen; /* Data for master socket */
785 int ssock; /* Descriptor for master socket */
786 THREAD SessThread; /* Thread descriptor */
787 pthread_attr_t attr; /* Thread attributes */
788 struct CitContext *con; /* Temporary context pointer */
789 char tracefile[128]; /* Name of file to log traces to */
790 int a, i; /* General-purpose variables */
794 int drop_root_perms = 1;
797 /* specify default port name and trace file */
798 strcpy(tracefile, "");
800 /* parse command-line arguments */
801 for (a=1; a<argc; ++a) {
803 /* -t specifies where to log trace messages to */
804 if (!strncmp(argv[a], "-t", 2)) {
805 strcpy(tracefile, argv[a]);
806 strcpy(tracefile, &tracefile[2]);
807 freopen(tracefile, "r", stdin);
808 freopen(tracefile, "w", stdout);
809 freopen(tracefile, "w", stderr);
812 /* run in the background if -d was specified */
813 else if (!strcmp(argv[a], "-d")) {
814 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
817 /* -x specifies the desired logging level */
818 else if (!strncmp(argv[a], "-x", 2)) {
819 verbosity = atoi(&argv[a][2]);
822 else if (!strncmp(argv[a], "-h", 2)) {
823 safestrncpy(bbs_home_directory, &argv[a][2],
824 sizeof bbs_home_directory);
828 else if (!strncmp(argv[a], "-f", 2)) {
832 /* -r tells the server not to drop root permissions. don't use
833 * this unless you know what you're doing. this should be
834 * removed in the next release if it proves unnecessary. */
835 else if (!strcmp(argv[a], "-r"))
838 /* any other parameter makes it crash and burn */
840 lprintf(1, "citserver: usage: "
841 "citserver [-tTraceFile] [-d] [-f]"
842 " [-xLogLevel] [-hHomeDir]\n");
848 /* Tell 'em who's in da house */
850 "\nMultithreaded message server for Citadel/UX\n"
851 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
853 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
854 "you are welcome to change it and/or distribute copies of it under certain\n"
855 "conditions. There is absolutely no warranty for this software. Please\n"
856 "read the 'COPYING.txt' file for details.\n\n");
860 openlog("citserver",LOG_PID,LOG_USER);
861 /* Load site-specific parameters */
862 lprintf(7, "Loading citadel.config\n");
866 * Bind the server to our favourite port.
867 * There is no need to check for errors, because ig_tcp_server()
868 * exits if it doesn't succeed.
870 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
871 msock = ig_tcp_server(config.c_port_number, 5);
872 lprintf(7, "Listening on socket %d\n", msock);
875 * Now that we've bound the socket, change to the BBS user id and its
876 * corresponding group ids
878 if (drop_root_perms) {
879 if ((pw = getpwuid(BBSUID)) == NULL)
880 lprintf(1, "WARNING: getpwuid(%d): %s\n"
881 "Group IDs will be incorrect.\n", BBSUID,
884 initgroups(pw->pw_name, pw->pw_gid);
885 if (setgid(pw->pw_gid))
886 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
889 lprintf(7, "Changing uid to %d\n", BBSUID);
890 if (setuid(BBSUID) != 0) {
891 lprintf(3, "setuid() failed: %s\n", strerror(errno));
895 lprintf(7, "Initializing loadable modules\n");
896 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
897 sprintf(moddir, "%s/modules", bbs_home_directory);
898 DLoader_Init(moddir);
901 lprintf(9, "Modules done initializing.\n");
904 * Do non system dependent startup functions.
909 * Endless loop. Listen on the master socket. When a connection
910 * comes in, create a socket, a context, and a thread.
912 while (!time_to_die) {
913 /* we need to check if a signal has been delivered. because
914 * syscalls may be restartable across signals, we call
915 * select with a timeout of 1 second and repeatedly check for
918 FD_SET(msock, &readfds);
921 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
924 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
926 lprintf(2, "citserver: accept() failed: %s\n",
930 lprintf(7, "citserver: Client socket %d\n", ssock);
931 lprintf(9, "creating context\n");
932 con = CreateNewContext();
933 con->client_socket = ssock;
935 /* Set the SO_REUSEADDR socket option */
936 lprintf(9, "setting socket options\n");
938 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
941 /* set attributes for the new thread */
942 lprintf(9, "setting thread attributes\n");
943 pthread_attr_init(&attr);
944 pthread_attr_setdetachstate(&attr,
945 PTHREAD_CREATE_DETACHED);
947 /* now create the thread */
948 lprintf(9, "creating thread\n");
949 if (pthread_create(&SessThread, &attr,
950 (void* (*)(void*)) sd_context_loop,
954 "citserver: can't create thread: %s\n",
959 * (defunct -- now done at thread creation time)
960 * if (pthread_detach(&SessThread) != 0) {
962 * "citserver: can't detach thread: %s\n",
966 lprintf(9, "done!\n");