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 #ifndef HAVE_PTHREAD_CANCEL
160 * signal handler to fake thread cancellation; only required on BSDI as far
164 static pthread_t main_thread_id;
166 static RETSIGTYPE cancel_thread(int signum) {
172 * we used to use master_cleanup() as a signal handler to shut down the server.
173 * however, master_cleanup() and the functions it calls do some things that
174 * aren't such a good idea to do from a signal handler: acquiring mutexes,
175 * playing with signal masks on BSDI systems, etc. so instead we install the
176 * following signal handler to set a global variable to inform the main loop
177 * that it's time to call master_cleanup() and exit.
180 static volatile int time_to_die = 0;
182 static RETSIGTYPE signal_cleanup(int signum) {
188 * Some initialization stuff...
190 void init_sysdep(void) {
193 /* Set up a bunch of semaphores to be used for critical sections */
194 for (a=0; a<MAX_SEMAPHORES; ++a) {
195 pthread_mutex_init(&Critters[a], NULL);
199 * Set up a place to put thread-specific data.
200 * We only need a single pointer per thread - it points to the
201 * thread's CitContext structure in the ContextList linked list.
203 if (pthread_key_create(&MyConKey, NULL) != 0) {
204 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
208 * The action for unexpected signals and exceptions should be to
209 * call signal_cleanup() to gracefully shut down the server.
211 signal(SIGINT, signal_cleanup);
212 signal(SIGQUIT, signal_cleanup);
213 signal(SIGHUP, signal_cleanup);
214 signal(SIGTERM, signal_cleanup);
215 signal(SIGPIPE, SIG_IGN);
216 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
217 main_thread_id = pthread_self();
218 signal(SIGUSR1, cancel_thread);
224 * Obtain a semaphore lock to begin a critical section.
226 void begin_critical_section(int which_one)
228 #ifdef HAVE_PTHREAD_CANCEL
234 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
236 #ifdef HAVE_PTHREAD_CANCEL
237 /* Don't get interrupted during the critical section */
238 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
240 /* We're faking cancellation with signals. Block SIGUSR1 while we're in
241 * the critical section. */
242 if (!pthread_equal(pthread_self(), main_thread_id)) {
244 sigaddset(&set, SIGUSR1);
245 pthread_sigmask(SIG_BLOCK, &set, NULL);
249 /* Obtain a semaphore */
250 pthread_mutex_lock(&Critters[which_one]);
255 * Release a semaphore lock to end a critical section.
257 void end_critical_section(int which_one)
259 #ifdef HAVE_PTHREAD_CANCEL
265 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
267 /* Let go of the semaphore */
268 pthread_mutex_unlock(&Critters[which_one]);
270 #ifdef HAVE_PTHREAD_CANCEL
271 /* If a cancel was sent during the critical section, do it now.
272 * Then re-enable thread cancellation.
274 pthread_testcancel();
275 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
276 pthread_testcancel();
278 /* We're faking it. Unblock SIGUSR1; signals sent during the critical
279 * section should now be able to kill us. */
280 if (!pthread_equal(pthread_self(), main_thread_id)) {
282 sigaddset(&set, SIGUSR1);
283 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
292 * This is a generic function to set up a master socket for listening on
293 * a TCP port. The server shuts down if the bind fails.
295 int ig_tcp_server(int port_number, int queue_len)
297 struct sockaddr_in sin;
300 memset(&sin, 0, sizeof(sin));
301 sin.sin_family = AF_INET;
302 sin.sin_addr.s_addr = INADDR_ANY;
304 if (port_number == 0) {
306 "citserver: No port number specified. Run setup.\n");
310 sin.sin_port = htons((u_short)port_number);
312 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
314 lprintf(1, "citserver: Can't create a socket: %s\n",
319 /* Set the SO_REUSEADDR socket option, because it makes sense. */
321 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
323 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
324 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
328 if (listen(s, queue_len) < 0) {
329 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
338 * Return a pointer to a thread's own CitContext structure (old)
339 * NOTE: this version of MyContext() is commented out because it is no longer
340 * in use. It was written before I discovered TSD keys. This
341 * version pounds through the context list until it finds the one matching
342 * the currently running thread. It remains here, commented out, in case it
343 * is needed for future ports to threading libraries which have the equivalent
344 * of pthread_self() but not pthread_key_create() and its ilk.
346 * struct CitContext *MyContext() {
347 * struct CitContext *ptr;
350 * me = pthread_self();
351 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
352 * if (ptr->mythread == me) return(ptr);
359 * Return a pointer to a thread's own CitContext structure (new)
361 struct CitContext *MyContext(void) {
362 struct CitContext *retCC;
363 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
364 if (retCC == NULL) retCC = &masterCC;
370 * Wedge our way into the context list.
372 struct CitContext *CreateNewContext(void) {
373 struct CitContext *me;
375 lprintf(9, "CreateNewContext: calling malloc()\n");
376 me = (struct CitContext *) mallok(sizeof(struct CitContext));
378 lprintf(1, "citserver: can't allocate memory!!\n");
381 memset(me, 0, sizeof(struct CitContext));
383 begin_critical_section(S_SESSION_TABLE);
384 me->next = ContextList;
386 end_critical_section(S_SESSION_TABLE);
391 * Add a thread's thread ID to the context
393 void InitMyContext(struct CitContext *con)
395 #ifdef HAVE_PTHREAD_CANCEL
399 con->mythread = pthread_self();
400 #ifdef HAVE_PTHREAD_CANCEL
401 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
402 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
404 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
405 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
411 * Remove a context from the context list.
413 void RemoveContext(struct CitContext *con)
415 struct CitContext *ptr;
417 lprintf(7, "Starting RemoveContext()\n");
418 lprintf(9, "Session count before RemoveContext is %d\n",
421 lprintf(7, "WARNING: RemoveContext() called with null!\n");
426 * session_count() starts its own S_SESSION_TABLE critical section;
427 * so do not call it from within this loop.
429 begin_critical_section(S_SESSION_TABLE);
430 lprintf(7, "Closing socket %d\n", con->client_socket);
431 close(con->client_socket);
433 lprintf(9, "Dereferencing session context\n");
434 if (ContextList==con) {
435 ContextList = ContextList->next;
438 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
439 if (ptr->next == con) {
440 ptr->next = con->next;
445 lprintf(9, "Freeing session context...\n");
447 lprintf(9, "...done.\n");
448 end_critical_section(S_SESSION_TABLE);
450 lprintf(9, "Session count after RemoveContext is %d\n",
453 lprintf(7, "Done with RemoveContext\n");
458 * Return the number of sessions currently running.
459 * (This should probably be moved out of sysdep.c)
461 int session_count(void) {
462 struct CitContext *ptr;
465 lprintf(9, "session_count() starting\n");
466 begin_critical_section(S_SESSION_TABLE);
467 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
469 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
471 end_critical_section(S_SESSION_TABLE);
473 lprintf(9, "session_count() finishing\n");
479 * client_write() ... Send binary data to the client.
481 void client_write(char *buf, int nbytes)
483 int bytes_written = 0;
485 while (bytes_written < nbytes) {
486 retval = write(CC->client_socket, &buf[bytes_written],
487 nbytes - bytes_written);
489 lprintf(2, "client_write() failed: %s\n",
493 bytes_written = bytes_written + retval;
499 * cprintf() ... Send formatted printable data to the client. It is
500 * implemented in terms of client_write() but remains in
501 * sysdep.c in case we port to somewhere without va_args...
503 void cprintf(const char *format, ...) {
507 va_start(arg_ptr, format);
508 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
509 buf[sizeof buf - 2] = '\n';
510 client_write(buf, strlen(buf));
516 * Read data from the client socket.
518 * 1 Requested number of bytes has been read.
519 * 0 Request timed out.
520 * If the socket breaks, the session is immediately terminated.
522 int client_read_to(char *buf, int bytes, int timeout)
532 FD_SET(CC->client_socket, &rfds);
536 retval = select( (CC->client_socket)+1,
537 &rfds, NULL, NULL, &tv);
538 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
542 rlen = read(CC->client_socket, &buf[len], bytes-len);
544 lprintf(2, "client_read() failed: %s\n",
554 * Read data from the client socket with default timeout.
555 * (This is implemented in terms of client_read_to() and could be
556 * justifiably moved out of sysdep.c)
558 int client_read(char *buf, int bytes)
560 return(client_read_to(buf, bytes, config.c_sleeping));
565 * client_gets() ... Get a LF-terminated line of text from the client.
566 * (This is implemented in terms of client_read() and could be
567 * justifiably moved out of sysdep.c)
569 int client_gets(char *buf)
573 /* Read one character at a time.
576 retval = client_read(&buf[i], 1);
577 if (retval != 1 || buf[i] == '\n' || i == 255)
581 /* If we got a long line, discard characters until the newline.
584 while (buf[i] != '\n' && retval == 1)
585 retval = client_read(&buf[i], 1);
587 /* Strip the trailing newline and any trailing nonprintables (cr's)
590 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
591 buf[strlen(buf)-1] = 0;
598 * The system-dependent part of master_cleanup() - close the master socket.
600 void sysdep_master_cleanup(void) {
601 lprintf(7, "Closing master socket %d\n", msock);
606 * Cleanup routine to be called when one thread is shutting down.
608 void cleanup(int exit_code)
610 /* Terminate the thread.
611 * Its cleanup handler will call cleanup_stuff()
613 lprintf(7, "Calling pthread_exit()\n");
618 * Terminate another session.
620 void kill_session(int session_to_kill) {
621 struct CitContext *ptr;
624 lprintf(9, "kill_session() scanning for thread to cancel...\n");
625 begin_critical_section(S_SESSION_TABLE);
626 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
627 if (ptr->cs_pid == session_to_kill) {
628 killme = ptr->mythread;
631 end_critical_section(S_SESSION_TABLE);
632 lprintf(9, "kill_session() finished scanning.\n");
635 #ifdef HAVE_PTHREAD_CANCEL
636 lprintf(9, "calling pthread_cancel()\n");
637 pthread_cancel(killme);
639 pthread_kill(killme, SIGUSR1);
641 /* there's a very stupid bug in the user threads package on
642 FreeBSD 3.1 which prevents a signal from being properly
643 dispatched to a thread that's in a blocking syscall. the
644 first signal interrupts the syscall, the second one actually
646 pthread_kill(killme, SIGUSR1);
654 * The system-dependent wrapper around the main context loop.
656 void *sd_context_loop(struct CitContext *con) {
657 pthread_cleanup_push(*cleanup_stuff, NULL);
659 pthread_cleanup_pop(0);
665 * Start running as a daemon. Only close stdio if do_close_stdio is set.
667 void start_daemon(int do_close_stdio) {
668 if (do_close_stdio) {
673 signal(SIGHUP,SIG_IGN);
674 signal(SIGINT,SIG_IGN);
675 signal(SIGQUIT,SIG_IGN);
676 if (fork()!=0) exit(0);
682 * Tie in to the 'netsetup' program.
684 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
686 void cmd_nset(char *cmdbuf)
693 char netsetup_args[3][256];
695 if (CC->usersupp.axlevel < 6) {
696 cprintf("%d Higher access required.\n",
697 ERROR + HIGHER_ACCESS_REQUIRED);
701 for (a=1; a<=3; ++a) {
702 if (num_parms(cmdbuf) >= a) {
703 extract(netsetup_args[a-1], cmdbuf, a-1);
704 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
705 if (netsetup_args[a-1][b] == 34) {
706 netsetup_args[a-1][b] = '_';
711 netsetup_args[a-1][0] = 0;
715 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
716 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
717 netsetup = popen(fbuf, "r");
718 if (netsetup == NULL) {
719 cprintf("%d %s\n", ERROR, strerror(errno));
724 while (ch = getc(netsetup), (ch > 0)) {
725 fbuf[strlen(fbuf)+1] = 0;
726 fbuf[strlen(fbuf)] = ch;
729 retcode = pclose(netsetup);
732 for (a=0; a<strlen(fbuf); ++a) {
733 if (fbuf[a] < 32) fbuf[a] = 32;
736 cprintf("%d %s\n", ERROR, fbuf);
740 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
742 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
749 * Generic routine to convert a login name to a full name (gecos)
750 * Returns nonzero if a conversion took place
752 int convert_login(char NameToConvert[]) {
756 pw = getpwnam(NameToConvert);
761 strcpy(NameToConvert, pw->pw_gecos);
762 for (a=0; a<strlen(NameToConvert); ++a) {
763 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
775 * Here's where it all begins.
777 int main(int argc, char **argv)
779 struct sockaddr_in fsin; /* Data for master socket */
780 int alen; /* Data for master socket */
781 int ssock; /* Descriptor for master socket */
782 THREAD SessThread; /* Thread descriptor */
783 pthread_attr_t attr; /* Thread attributes */
784 struct CitContext *con; /* Temporary context pointer */
785 char tracefile[128]; /* Name of file to log traces to */
786 int a, i; /* General-purpose variables */
791 int drop_root_perms = 1;
793 /* specify default port name and trace file */
794 strcpy(tracefile, "");
796 /* parse command-line arguments */
797 for (a=1; a<argc; ++a) {
799 /* -t specifies where to log trace messages to */
800 if (!strncmp(argv[a], "-t", 2)) {
801 strcpy(tracefile, argv[a]);
802 strcpy(tracefile, &tracefile[2]);
803 freopen(tracefile, "r", stdin);
804 freopen(tracefile, "w", stdout);
805 freopen(tracefile, "w", stderr);
808 /* run in the background if -d was specified */
809 else if (!strcmp(argv[a], "-d")) {
810 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
813 /* -x specifies the desired logging level */
814 else if (!strncmp(argv[a], "-x", 2)) {
815 strcpy(convbuf, argv[a]);
816 verbosity = atoi(&convbuf[2]);
819 else if (!strncmp(argv[a], "-h", 2)) {
820 strcpy(convbuf, argv[a]);
821 strcpy(bbs_home_directory, &convbuf[2]);
825 /* -r tells the server not to drop root permissions. don't use
826 * this unless you know what you're doing. this should be
827 * removed in the next release if it proves unnecessary. */
828 else if (!strcmp(argv[a], "-r"))
831 /* any other parameter makes it crash and burn */
833 lprintf(1, "citserver: usage: ");
834 lprintf(1, "citserver [-tTraceFile]");
835 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
841 /* Tell 'em who's in da house */
842 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
843 lprintf(1, "Copyright (C) 1987-1999 by Art Cancro. ");
844 lprintf(1, "All rights reserved.\n\n");
848 openlog("citserver",LOG_PID,LOG_USER);
849 /* Load site-specific parameters */
850 lprintf(7, "Loading citadel.config\n");
854 * Bind the server to our favourite port.
855 * There is no need to check for errors, because ig_tcp_server()
856 * exits if it doesn't succeed.
858 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
859 msock = ig_tcp_server(config.c_port_number, 5);
860 lprintf(7, "Listening on socket %d\n", msock);
863 * Now that we've bound the socket, change to the BBS user id and its
864 * corresponding group ids
866 if (drop_root_perms) {
867 if ((pw = getpwuid(BBSUID)) == NULL)
868 lprintf(1, "WARNING: getpwuid(%d): %s\n"
869 "Group IDs will be incorrect.\n", BBSUID,
872 initgroups(pw->pw_name, pw->pw_gid);
873 if (setgid(pw->pw_gid))
874 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
877 lprintf(7, "Changing uid to %d\n", BBSUID);
878 if (setuid(BBSUID) != 0) {
879 lprintf(3, "setuid() failed: %s\n", strerror(errno));
883 lprintf(7, "Initializing loadable modules\n");
884 DLoader_Init(BBSDIR "/modules");
885 lprintf(9, "Modules done initializing.\n");
888 * Do non system dependent startup functions.
893 * Endless loop. Listen on the master socket. When a connection
894 * comes in, create a socket, a context, and a thread.
896 while (!time_to_die) {
897 /* we need to check if a signal has been delivered. because
898 * syscalls may be restartable across signals, we call
899 * select with a timeout of 1 second and repeatedly check for
902 FD_SET(msock, &readfds);
905 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
908 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
910 lprintf(2, "citserver: accept() failed: %s\n",
914 lprintf(7, "citserver: Client socket %d\n", ssock);
915 lprintf(9, "creating context\n");
916 con = CreateNewContext();
917 con->client_socket = ssock;
919 /* Set the SO_REUSEADDR socket option */
920 lprintf(9, "setting socket options\n");
922 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
925 /* set attributes for the new thread */
926 lprintf(9, "setting thread attributes\n");
927 pthread_attr_init(&attr);
928 pthread_attr_setdetachstate(&attr,
929 PTHREAD_CREATE_DETACHED);
931 /* now create the thread */
932 lprintf(9, "creating thread\n");
933 if (pthread_create(&SessThread, &attr,
934 (void* (*)(void*)) sd_context_loop,
938 "citserver: can't create thread: %s\n",
943 * (defunct -- now done at thread creation time)
944 * if (pthread_detach(&SessThread) != 0) {
946 * "citserver: can't detach thread: %s\n",
950 lprintf(9, "done!\n");