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) {
102 if (ptr == NULL) return(NULL);
104 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
105 strcpy(hptr->h_file, tfile);
106 hptr->h_line = tline;
113 char *tracked_strdup(const char *orig, char *tfile, int tline) {
116 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
117 if (s == NULL) return NULL;
123 void tracked_free(void *ptr) {
124 struct TheHeap *hptr, *freeme;
126 if (heap->h_ptr == ptr) {
132 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
133 if (hptr->next->h_ptr == ptr) {
135 hptr->next = hptr->next->next;
144 void *tracked_realloc(void *ptr, size_t size) {
146 struct TheHeap *hptr;
148 newptr = realloc(ptr, size);
150 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
151 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
158 void dump_tracked() {
159 struct TheHeap *hptr;
161 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
162 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
163 cprintf("%20s %5d\n",
164 hptr->h_file, hptr->h_line);
174 static pthread_t main_thread_id;
176 #ifndef HAVE_PTHREAD_CANCEL
178 * signal handler to fake thread cancellation; only required on BSDI as far
181 static RETSIGTYPE cancel_thread(int signum) {
187 * we used to use master_cleanup() as a signal handler to shut down the server.
188 * however, master_cleanup() and the functions it calls do some things that
189 * aren't such a good idea to do from a signal handler: acquiring mutexes,
190 * playing with signal masks on BSDI systems, etc. so instead we install the
191 * following signal handler to set a global variable to inform the main loop
192 * that it's time to call master_cleanup() and exit.
195 static volatile int time_to_die = 0;
197 static RETSIGTYPE signal_cleanup(int signum) {
203 * Some initialization stuff...
205 void init_sysdep(void) {
208 /* Set up a bunch of semaphores to be used for critical sections */
209 for (a=0; a<MAX_SEMAPHORES; ++a) {
210 pthread_mutex_init(&Critters[a], NULL);
214 * Set up a place to put thread-specific data.
215 * We only need a single pointer per thread - it points to the
216 * thread's CitContext structure in the ContextList linked list.
218 if (pthread_key_create(&MyConKey, NULL) != 0) {
219 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
223 * The action for unexpected signals and exceptions should be to
224 * call signal_cleanup() to gracefully shut down the server.
226 signal(SIGINT, signal_cleanup);
227 signal(SIGQUIT, signal_cleanup);
228 signal(SIGHUP, signal_cleanup);
229 signal(SIGTERM, signal_cleanup);
230 signal(SIGPIPE, SIG_IGN);
231 main_thread_id = pthread_self();
232 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
233 signal(SIGUSR1, cancel_thread);
239 * Obtain a semaphore lock to begin a critical section.
241 void begin_critical_section(int which_one)
243 #ifdef HAVE_PTHREAD_CANCEL
249 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
251 if (!pthread_equal(pthread_self(), main_thread_id)) {
252 /* Keep a count of how many critical sections this thread has
253 * open, so that end_critical_section() doesn't enable
254 * cancellation prematurely. */
256 #ifdef HAVE_PTHREAD_CANCEL
257 /* Don't get interrupted during the critical section */
258 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
260 /* We're faking cancellation with signals. Block SIGUSR1 while
261 * we're in the critical section. */
263 sigaddset(&set, SIGUSR1);
264 pthread_sigmask(SIG_BLOCK, &set, NULL);
268 /* Obtain a semaphore */
269 pthread_mutex_lock(&Critters[which_one]);
274 * Release a semaphore lock to end a critical section.
276 void end_critical_section(int which_one)
278 #ifdef HAVE_PTHREAD_CANCEL
284 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
286 /* Let go of the semaphore */
287 pthread_mutex_unlock(&Critters[which_one]);
289 if (!pthread_equal(pthread_self(), main_thread_id))
291 #ifdef HAVE_PTHREAD_CANCEL
292 /* If a cancel was sent during the critical section, do it now.
293 * Then re-enable thread cancellation.
295 pthread_testcancel();
296 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
297 pthread_testcancel();
299 /* We're faking it. Unblock SIGUSR1; signals sent during the
300 * critical section should now be able to kill us. */
302 sigaddset(&set, SIGUSR1);
303 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
312 * This is a generic function to set up a master socket for listening on
313 * a TCP port. The server shuts down if the bind fails.
315 int ig_tcp_server(int port_number, int queue_len)
317 struct sockaddr_in sin;
320 memset(&sin, 0, sizeof(sin));
321 sin.sin_family = AF_INET;
322 sin.sin_addr.s_addr = INADDR_ANY;
324 if (port_number == 0) {
326 "citserver: No port number specified. Run setup.\n");
330 sin.sin_port = htons((u_short)port_number);
332 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
334 lprintf(1, "citserver: Can't create a socket: %s\n",
339 /* Set the SO_REUSEADDR socket option, because it makes sense. */
341 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
343 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
344 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
348 if (listen(s, queue_len) < 0) {
349 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
358 * Return a pointer to a thread's own CitContext structure (old)
359 * NOTE: this version of MyContext() is commented out because it is no longer
360 * in use. It was written before I discovered TSD keys. This
361 * version pounds through the context list until it finds the one matching
362 * the currently running thread. It remains here, commented out, in case it
363 * is needed for future ports to threading libraries which have the equivalent
364 * of pthread_self() but not pthread_key_create() and its ilk.
366 * struct CitContext *MyContext() {
367 * struct CitContext *ptr;
370 * me = pthread_self();
371 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
372 * if (ptr->mythread == me) return(ptr);
379 * Return a pointer to a thread's own CitContext structure (new)
381 struct CitContext *MyContext(void) {
382 struct CitContext *retCC;
383 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
384 if (retCC == NULL) retCC = &masterCC;
390 * Wedge our way into the context list.
392 struct CitContext *CreateNewContext(void) {
393 struct CitContext *me;
395 lprintf(9, "CreateNewContext: calling malloc()\n");
396 me = (struct CitContext *) mallok(sizeof(struct CitContext));
398 lprintf(1, "citserver: can't allocate memory!!\n");
401 memset(me, 0, sizeof(struct CitContext));
403 begin_critical_section(S_SESSION_TABLE);
404 me->next = ContextList;
406 end_critical_section(S_SESSION_TABLE);
411 * Add a thread's thread ID to the context
413 void InitMyContext(struct CitContext *con)
415 #ifdef HAVE_PTHREAD_CANCEL
419 con->mythread = pthread_self();
420 #ifdef HAVE_PTHREAD_CANCEL
421 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
422 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
424 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
425 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
431 * Remove a context from the context list.
433 void RemoveContext(struct CitContext *con)
435 struct CitContext *ptr;
437 lprintf(7, "Starting RemoveContext()\n");
438 lprintf(9, "Session count before RemoveContext is %d\n",
441 lprintf(7, "WARNING: RemoveContext() called with null!\n");
446 * session_count() starts its own S_SESSION_TABLE critical section;
447 * so do not call it from within this loop.
449 begin_critical_section(S_SESSION_TABLE);
450 lprintf(7, "Closing socket %d\n", con->client_socket);
451 close(con->client_socket);
453 lprintf(9, "Dereferencing session context\n");
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;
465 lprintf(9, "Freeing session context...\n");
467 lprintf(9, "...done.\n");
468 end_critical_section(S_SESSION_TABLE);
470 lprintf(9, "Session count after RemoveContext is %d\n",
473 lprintf(7, "Done with RemoveContext\n");
478 * Return the number of sessions currently running.
479 * (This should probably be moved out of sysdep.c)
481 int session_count(void) {
482 struct CitContext *ptr;
485 lprintf(9, "session_count() starting\n");
486 begin_critical_section(S_SESSION_TABLE);
487 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
489 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
491 end_critical_section(S_SESSION_TABLE);
493 lprintf(9, "session_count() finishing\n");
499 * client_write() ... Send binary data to the client.
501 void client_write(char *buf, int nbytes)
503 int bytes_written = 0;
505 while (bytes_written < nbytes) {
506 retval = write(CC->client_socket, &buf[bytes_written],
507 nbytes - bytes_written);
509 lprintf(2, "client_write() failed: %s\n",
513 bytes_written = bytes_written + retval;
519 * cprintf() ... Send formatted printable data to the client. It is
520 * implemented in terms of client_write() but remains in
521 * sysdep.c in case we port to somewhere without va_args...
523 void cprintf(const char *format, ...) {
527 va_start(arg_ptr, format);
528 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
529 buf[sizeof buf - 2] = '\n';
530 client_write(buf, strlen(buf));
536 * Read data from the client socket.
538 * 1 Requested number of bytes has been read.
539 * 0 Request timed out.
540 * If the socket breaks, the session is immediately terminated.
542 int client_read_to(char *buf, int bytes, int timeout)
552 FD_SET(CC->client_socket, &rfds);
556 retval = select( (CC->client_socket)+1,
557 &rfds, NULL, NULL, &tv);
558 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
562 rlen = read(CC->client_socket, &buf[len], bytes-len);
564 lprintf(2, "client_read() failed: %s\n",
574 * Read data from the client socket with default timeout.
575 * (This is implemented in terms of client_read_to() and could be
576 * justifiably moved out of sysdep.c)
578 int client_read(char *buf, int bytes)
580 return(client_read_to(buf, bytes, config.c_sleeping));
585 * client_gets() ... Get a LF-terminated line of text from the client.
586 * (This is implemented in terms of client_read() and could be
587 * justifiably moved out of sysdep.c)
589 int client_gets(char *buf)
593 /* Read one character at a time.
596 retval = client_read(&buf[i], 1);
597 if (retval != 1 || buf[i] == '\n' || i == 255)
601 /* If we got a long line, discard characters until the newline.
604 while (buf[i] != '\n' && retval == 1)
605 retval = client_read(&buf[i], 1);
607 /* Strip the trailing newline and any trailing nonprintables (cr's)
610 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
611 buf[strlen(buf)-1] = 0;
618 * The system-dependent part of master_cleanup() - close the master socket.
620 void sysdep_master_cleanup(void) {
621 lprintf(7, "Closing master socket %d\n", msock);
626 * Cleanup routine to be called when one thread is shutting down.
628 void cleanup(int exit_code)
630 /* Terminate the thread.
631 * Its cleanup handler will call cleanup_stuff()
633 lprintf(7, "Calling pthread_exit()\n");
638 * Terminate another session.
640 void kill_session(int session_to_kill) {
641 struct CitContext *ptr;
644 lprintf(9, "kill_session() scanning for thread to cancel...\n");
645 begin_critical_section(S_SESSION_TABLE);
646 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
647 if (ptr->cs_pid == session_to_kill) {
648 killme = ptr->mythread;
651 end_critical_section(S_SESSION_TABLE);
652 lprintf(9, "kill_session() finished scanning.\n");
655 #ifdef HAVE_PTHREAD_CANCEL
656 lprintf(9, "calling pthread_cancel()\n");
657 pthread_cancel(killme);
659 pthread_kill(killme, SIGUSR1);
661 /* there's a very stupid bug in the user threads package on
662 FreeBSD 3.1 which prevents a signal from being properly
663 dispatched to a thread that's in a blocking syscall. the
664 first signal interrupts the syscall, the second one actually
666 pthread_kill(killme, SIGUSR1);
674 * The system-dependent wrapper around the main context loop.
676 void *sd_context_loop(struct CitContext *con) {
677 pthread_cleanup_push(*cleanup_stuff, NULL);
679 pthread_cleanup_pop(0);
685 * Start running as a daemon. Only close stdio if do_close_stdio is set.
687 void start_daemon(int do_close_stdio) {
688 if (do_close_stdio) {
693 signal(SIGHUP,SIG_IGN);
694 signal(SIGINT,SIG_IGN);
695 signal(SIGQUIT,SIG_IGN);
696 if (fork()!=0) exit(0);
702 * Tie in to the 'netsetup' program.
704 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
706 void cmd_nset(char *cmdbuf)
713 char netsetup_args[3][256];
715 if (CC->usersupp.axlevel < 6) {
716 cprintf("%d Higher access required.\n",
717 ERROR + HIGHER_ACCESS_REQUIRED);
721 for (a=1; a<=3; ++a) {
722 if (num_parms(cmdbuf) >= a) {
723 extract(netsetup_args[a-1], cmdbuf, a-1);
724 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
725 if (netsetup_args[a-1][b] == 34) {
726 netsetup_args[a-1][b] = '_';
731 netsetup_args[a-1][0] = 0;
735 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
736 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
737 netsetup = popen(fbuf, "r");
738 if (netsetup == NULL) {
739 cprintf("%d %s\n", ERROR, strerror(errno));
744 while (ch = getc(netsetup), (ch > 0)) {
745 fbuf[strlen(fbuf)+1] = 0;
746 fbuf[strlen(fbuf)] = ch;
749 retcode = pclose(netsetup);
752 for (a=0; a<strlen(fbuf); ++a) {
753 if (fbuf[a] < 32) fbuf[a] = 32;
756 cprintf("%d %s\n", ERROR, fbuf);
760 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
762 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
769 * Generic routine to convert a login name to a full name (gecos)
770 * Returns nonzero if a conversion took place
772 int convert_login(char NameToConvert[]) {
776 pw = getpwnam(NameToConvert);
781 strcpy(NameToConvert, pw->pw_gecos);
782 for (a=0; a<strlen(NameToConvert); ++a) {
783 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
795 * Here's where it all begins.
797 int main(int argc, char **argv)
799 struct sockaddr_in fsin; /* Data for master socket */
800 int alen; /* Data for master socket */
801 int ssock; /* Descriptor for master socket */
802 THREAD SessThread; /* Thread descriptor */
803 pthread_attr_t attr; /* Thread attributes */
804 struct CitContext *con; /* Temporary context pointer */
805 char tracefile[128]; /* Name of file to log traces to */
806 int a, i; /* General-purpose variables */
810 int drop_root_perms = 1;
813 /* specify default port name and trace file */
814 strcpy(tracefile, "");
816 /* parse command-line arguments */
817 for (a=1; a<argc; ++a) {
819 /* -t specifies where to log trace messages to */
820 if (!strncmp(argv[a], "-t", 2)) {
821 strcpy(tracefile, argv[a]);
822 strcpy(tracefile, &tracefile[2]);
823 freopen(tracefile, "r", stdin);
824 freopen(tracefile, "w", stdout);
825 freopen(tracefile, "w", stderr);
828 /* run in the background if -d was specified */
829 else if (!strcmp(argv[a], "-d")) {
830 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
833 /* -x specifies the desired logging level */
834 else if (!strncmp(argv[a], "-x", 2)) {
835 verbosity = atoi(&argv[a][2]);
838 else if (!strncmp(argv[a], "-h", 2)) {
839 safestrncpy(bbs_home_directory, &argv[a][2],
840 sizeof bbs_home_directory);
844 else if (!strncmp(argv[a], "-f", 2)) {
848 /* -r tells the server not to drop root permissions. don't use
849 * this unless you know what you're doing. this should be
850 * removed in the next release if it proves unnecessary. */
851 else if (!strcmp(argv[a], "-r"))
854 /* any other parameter makes it crash and burn */
856 lprintf(1, "citserver: usage: "
857 "citserver [-tTraceFile] [-d] [-f]"
858 " [-xLogLevel] [-hHomeDir]\n");
864 /* Tell 'em who's in da house */
866 "\nMultithreaded message server for Citadel/UX\n"
867 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
868 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
869 "you are welcome to change it and/or distribute copies of it under certain\n"
870 "conditions. There is absolutely no warranty for this software. Please\n"
871 "read the 'COPYING.txt' file for details.\n\n");
875 openlog("citserver",LOG_PID,LOG_USER);
876 /* Load site-specific parameters */
877 lprintf(7, "Loading citadel.config\n");
881 * Bind the server to our favourite port.
882 * There is no need to check for errors, because ig_tcp_server()
883 * exits if it doesn't succeed.
885 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
886 msock = ig_tcp_server(config.c_port_number, 5);
887 lprintf(7, "Listening on socket %d\n", msock);
890 * Now that we've bound the socket, change to the BBS user id and its
891 * corresponding group ids
893 if (drop_root_perms) {
894 if ((pw = getpwuid(BBSUID)) == NULL)
895 lprintf(1, "WARNING: getpwuid(%d): %s\n"
896 "Group IDs will be incorrect.\n", BBSUID,
899 initgroups(pw->pw_name, pw->pw_gid);
900 if (setgid(pw->pw_gid))
901 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
904 lprintf(7, "Changing uid to %d\n", BBSUID);
905 if (setuid(BBSUID) != 0) {
906 lprintf(3, "setuid() failed: %s\n", strerror(errno));
911 * Do non system dependent startup functions.
916 * Load any server-side modules (plugins) available here.
918 lprintf(7, "Initializing loadable modules\n");
919 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
920 sprintf(moddir, "%s/modules", bbs_home_directory);
921 DLoader_Init(moddir);
924 lprintf(9, "Modules done initializing.\n");
927 * Endless loop. Listen on the master socket. When a connection
928 * comes in, create a socket, a context, and a thread.
930 while (!time_to_die) {
931 /* we need to check if a signal has been delivered. because
932 * syscalls may be restartable across signals, we call
933 * select with a timeout of 1 second and repeatedly check for
936 FD_SET(msock, &readfds);
939 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
942 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
944 lprintf(2, "citserver: accept() failed: %s\n",
948 lprintf(7, "citserver: Client socket %d\n", ssock);
949 lprintf(9, "creating context\n");
950 con = CreateNewContext();
951 con->client_socket = ssock;
953 /* Set the SO_REUSEADDR socket option */
954 lprintf(9, "setting socket options\n");
956 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
959 /* set attributes for the new thread */
960 lprintf(9, "setting thread attributes\n");
961 pthread_attr_init(&attr);
962 pthread_attr_setdetachstate(&attr,
963 PTHREAD_CREATE_DETACHED);
965 /* now create the thread */
966 lprintf(9, "creating thread\n");
967 if (pthread_create(&SessThread, &attr,
968 (void* (*)(void*)) sd_context_loop,
972 "citserver: can't create thread: %s\n",
977 * (defunct -- now done at thread creation time)
978 * if (pthread_detach(&SessThread) != 0) {
980 * "citserver: can't detach thread: %s\n",
984 lprintf(9, "done!\n");