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;
110 char *tracked_strdup(const char *orig, char *tfile, int tline) {
113 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
114 if (s == NULL) return NULL;
120 void tracked_free(void *ptr) {
121 struct TheHeap *hptr, *freeme;
123 if (heap->h_ptr == ptr) {
129 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
130 if (hptr->next->h_ptr == ptr) {
132 hptr->next = hptr->next->next;
141 void *tracked_realloc(void *ptr, size_t size) {
143 struct TheHeap *hptr;
145 newptr = realloc(ptr, size);
147 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
148 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
155 void dump_tracked() {
156 struct TheHeap *hptr;
158 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
159 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
160 cprintf("%20s %5d\n",
161 hptr->h_file, hptr->h_line);
167 static pthread_t main_thread_id;
169 #ifndef HAVE_PTHREAD_CANCEL
171 * signal handler to fake thread cancellation; only required on BSDI as far
174 static RETSIGTYPE cancel_thread(int signum) {
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);
223 signal(SIGPIPE, SIG_IGN);
224 main_thread_id = pthread_self();
225 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
226 signal(SIGUSR1, cancel_thread);
232 * Obtain a semaphore lock to begin a critical section.
234 void begin_critical_section(int which_one)
236 #ifdef HAVE_PTHREAD_CANCEL
242 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
244 if (!pthread_equal(pthread_self(), main_thread_id)) {
245 /* Keep a count of how many critical sections this thread has
246 * open, so that end_critical_section() doesn't enable
247 * cancellation prematurely. */
249 #ifdef HAVE_PTHREAD_CANCEL
250 /* Don't get interrupted during the critical section */
251 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
253 /* We're faking cancellation with signals. Block SIGUSR1 while
254 * we're in the critical section. */
256 sigaddset(&set, SIGUSR1);
257 pthread_sigmask(SIG_BLOCK, &set, NULL);
261 /* Obtain a semaphore */
262 pthread_mutex_lock(&Critters[which_one]);
267 * Release a semaphore lock to end a critical section.
269 void end_critical_section(int which_one)
271 #ifdef HAVE_PTHREAD_CANCEL
277 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
279 /* Let go of the semaphore */
280 pthread_mutex_unlock(&Critters[which_one]);
282 if (!pthread_equal(pthread_self(), main_thread_id))
284 #ifdef HAVE_PTHREAD_CANCEL
285 /* If a cancel was sent during the critical section, do it now.
286 * Then re-enable thread cancellation.
288 pthread_testcancel();
289 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
290 pthread_testcancel();
292 /* We're faking it. Unblock SIGUSR1; signals sent during the
293 * critical section should now be able to kill us. */
295 sigaddset(&set, SIGUSR1);
296 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
305 * This is a generic function to set up a master socket for listening on
306 * a TCP port. The server shuts down if the bind fails.
308 int ig_tcp_server(int port_number, int queue_len)
310 struct sockaddr_in sin;
313 memset(&sin, 0, sizeof(sin));
314 sin.sin_family = AF_INET;
315 sin.sin_addr.s_addr = INADDR_ANY;
317 if (port_number == 0) {
319 "citserver: No port number specified. Run setup.\n");
323 sin.sin_port = htons((u_short)port_number);
325 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
327 lprintf(1, "citserver: Can't create a socket: %s\n",
332 /* Set the SO_REUSEADDR socket option, because it makes sense. */
334 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
336 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
337 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
341 if (listen(s, queue_len) < 0) {
342 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
351 * Return a pointer to a thread's own CitContext structure (old)
352 * NOTE: this version of MyContext() is commented out because it is no longer
353 * in use. It was written before I discovered TSD keys. This
354 * version pounds through the context list until it finds the one matching
355 * the currently running thread. It remains here, commented out, in case it
356 * is needed for future ports to threading libraries which have the equivalent
357 * of pthread_self() but not pthread_key_create() and its ilk.
359 * struct CitContext *MyContext() {
360 * struct CitContext *ptr;
363 * me = pthread_self();
364 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
365 * if (ptr->mythread == me) return(ptr);
372 * Return a pointer to a thread's own CitContext structure (new)
374 struct CitContext *MyContext(void) {
375 struct CitContext *retCC;
376 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
377 if (retCC == NULL) retCC = &masterCC;
383 * Wedge our way into the context list.
385 struct CitContext *CreateNewContext(void) {
386 struct CitContext *me;
388 lprintf(9, "CreateNewContext: calling malloc()\n");
389 me = (struct CitContext *) mallok(sizeof(struct CitContext));
391 lprintf(1, "citserver: can't allocate memory!!\n");
394 memset(me, 0, sizeof(struct CitContext));
396 begin_critical_section(S_SESSION_TABLE);
397 me->next = ContextList;
399 end_critical_section(S_SESSION_TABLE);
404 * Add a thread's thread ID to the context
406 void InitMyContext(struct CitContext *con)
408 #ifdef HAVE_PTHREAD_CANCEL
412 con->mythread = pthread_self();
413 #ifdef HAVE_PTHREAD_CANCEL
414 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
415 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
417 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
418 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
424 * Remove a context from the context list.
426 void RemoveContext(struct CitContext *con)
428 struct CitContext *ptr;
430 lprintf(7, "Starting RemoveContext()\n");
431 lprintf(9, "Session count before RemoveContext is %d\n",
434 lprintf(7, "WARNING: RemoveContext() called with null!\n");
439 * session_count() starts its own S_SESSION_TABLE critical section;
440 * so do not call it from within this loop.
442 begin_critical_section(S_SESSION_TABLE);
443 lprintf(7, "Closing socket %d\n", con->client_socket);
444 close(con->client_socket);
446 lprintf(9, "Dereferencing session context\n");
447 if (ContextList==con) {
448 ContextList = ContextList->next;
451 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
452 if (ptr->next == con) {
453 ptr->next = con->next;
458 lprintf(9, "Freeing session context...\n");
460 lprintf(9, "...done.\n");
461 end_critical_section(S_SESSION_TABLE);
463 lprintf(9, "Session count after RemoveContext is %d\n",
466 lprintf(7, "Done with RemoveContext\n");
471 * Return the number of sessions currently running.
472 * (This should probably be moved out of sysdep.c)
474 int session_count(void) {
475 struct CitContext *ptr;
478 lprintf(9, "session_count() starting\n");
479 begin_critical_section(S_SESSION_TABLE);
480 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
482 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
484 end_critical_section(S_SESSION_TABLE);
486 lprintf(9, "session_count() finishing\n");
492 * client_write() ... Send binary data to the client.
494 void client_write(char *buf, int nbytes)
496 int bytes_written = 0;
498 while (bytes_written < nbytes) {
499 retval = write(CC->client_socket, &buf[bytes_written],
500 nbytes - bytes_written);
502 lprintf(2, "client_write() failed: %s\n",
506 bytes_written = bytes_written + retval;
512 * cprintf() ... Send formatted printable data to the client. It is
513 * implemented in terms of client_write() but remains in
514 * sysdep.c in case we port to somewhere without va_args...
516 void cprintf(const char *format, ...) {
520 va_start(arg_ptr, format);
521 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
522 buf[sizeof buf - 2] = '\n';
523 client_write(buf, strlen(buf));
529 * Read data from the client socket.
531 * 1 Requested number of bytes has been read.
532 * 0 Request timed out.
533 * If the socket breaks, the session is immediately terminated.
535 int client_read_to(char *buf, int bytes, int timeout)
545 FD_SET(CC->client_socket, &rfds);
549 retval = select( (CC->client_socket)+1,
550 &rfds, NULL, NULL, &tv);
551 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
555 rlen = read(CC->client_socket, &buf[len], bytes-len);
557 lprintf(2, "client_read() failed: %s\n",
567 * Read data from the client socket with default timeout.
568 * (This is implemented in terms of client_read_to() and could be
569 * justifiably moved out of sysdep.c)
571 int client_read(char *buf, int bytes)
573 return(client_read_to(buf, bytes, config.c_sleeping));
578 * client_gets() ... Get a LF-terminated line of text from the client.
579 * (This is implemented in terms of client_read() and could be
580 * justifiably moved out of sysdep.c)
582 int client_gets(char *buf)
586 /* Read one character at a time.
589 retval = client_read(&buf[i], 1);
590 if (retval != 1 || buf[i] == '\n' || i == 255)
594 /* If we got a long line, discard characters until the newline.
597 while (buf[i] != '\n' && retval == 1)
598 retval = client_read(&buf[i], 1);
600 /* Strip the trailing newline and any trailing nonprintables (cr's)
603 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
604 buf[strlen(buf)-1] = 0;
611 * The system-dependent part of master_cleanup() - close the master socket.
613 void sysdep_master_cleanup(void) {
614 lprintf(7, "Closing master socket %d\n", msock);
619 * Cleanup routine to be called when one thread is shutting down.
621 void cleanup(int exit_code)
623 /* Terminate the thread.
624 * Its cleanup handler will call cleanup_stuff()
626 lprintf(7, "Calling pthread_exit()\n");
631 * Terminate another session.
633 void kill_session(int session_to_kill) {
634 struct CitContext *ptr;
637 lprintf(9, "kill_session() scanning for thread to cancel...\n");
638 begin_critical_section(S_SESSION_TABLE);
639 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
640 if (ptr->cs_pid == session_to_kill) {
641 killme = ptr->mythread;
644 end_critical_section(S_SESSION_TABLE);
645 lprintf(9, "kill_session() finished scanning.\n");
648 #ifdef HAVE_PTHREAD_CANCEL
649 lprintf(9, "calling pthread_cancel()\n");
650 pthread_cancel(killme);
652 pthread_kill(killme, SIGUSR1);
654 /* there's a very stupid bug in the user threads package on
655 FreeBSD 3.1 which prevents a signal from being properly
656 dispatched to a thread that's in a blocking syscall. the
657 first signal interrupts the syscall, the second one actually
659 pthread_kill(killme, SIGUSR1);
667 * The system-dependent wrapper around the main context loop.
669 void *sd_context_loop(struct CitContext *con) {
670 pthread_cleanup_push(*cleanup_stuff, NULL);
672 pthread_cleanup_pop(0);
678 * Start running as a daemon. Only close stdio if do_close_stdio is set.
680 void start_daemon(int do_close_stdio) {
681 if (do_close_stdio) {
686 signal(SIGHUP,SIG_IGN);
687 signal(SIGINT,SIG_IGN);
688 signal(SIGQUIT,SIG_IGN);
689 if (fork()!=0) exit(0);
695 * Tie in to the 'netsetup' program.
697 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
699 void cmd_nset(char *cmdbuf)
706 char netsetup_args[3][256];
708 if (CC->usersupp.axlevel < 6) {
709 cprintf("%d Higher access required.\n",
710 ERROR + HIGHER_ACCESS_REQUIRED);
714 for (a=1; a<=3; ++a) {
715 if (num_parms(cmdbuf) >= a) {
716 extract(netsetup_args[a-1], cmdbuf, a-1);
717 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
718 if (netsetup_args[a-1][b] == 34) {
719 netsetup_args[a-1][b] = '_';
724 netsetup_args[a-1][0] = 0;
728 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
729 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
730 netsetup = popen(fbuf, "r");
731 if (netsetup == NULL) {
732 cprintf("%d %s\n", ERROR, strerror(errno));
737 while (ch = getc(netsetup), (ch > 0)) {
738 fbuf[strlen(fbuf)+1] = 0;
739 fbuf[strlen(fbuf)] = ch;
742 retcode = pclose(netsetup);
745 for (a=0; a<strlen(fbuf); ++a) {
746 if (fbuf[a] < 32) fbuf[a] = 32;
749 cprintf("%d %s\n", ERROR, fbuf);
753 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
755 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
762 * Generic routine to convert a login name to a full name (gecos)
763 * Returns nonzero if a conversion took place
765 int convert_login(char NameToConvert[]) {
769 pw = getpwnam(NameToConvert);
774 strcpy(NameToConvert, pw->pw_gecos);
775 for (a=0; a<strlen(NameToConvert); ++a) {
776 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
788 * Here's where it all begins.
790 int main(int argc, char **argv)
792 struct sockaddr_in fsin; /* Data for master socket */
793 int alen; /* Data for master socket */
794 int ssock; /* Descriptor for master socket */
795 THREAD SessThread; /* Thread descriptor */
796 pthread_attr_t attr; /* Thread attributes */
797 struct CitContext *con; /* Temporary context pointer */
798 char tracefile[128]; /* Name of file to log traces to */
799 int a, i; /* General-purpose variables */
803 int drop_root_perms = 1;
806 /* specify default port name and trace file */
807 strcpy(tracefile, "");
809 /* parse command-line arguments */
810 for (a=1; a<argc; ++a) {
812 /* -t specifies where to log trace messages to */
813 if (!strncmp(argv[a], "-t", 2)) {
814 strcpy(tracefile, argv[a]);
815 strcpy(tracefile, &tracefile[2]);
816 freopen(tracefile, "r", stdin);
817 freopen(tracefile, "w", stdout);
818 freopen(tracefile, "w", stderr);
821 /* run in the background if -d was specified */
822 else if (!strcmp(argv[a], "-d")) {
823 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
826 /* -x specifies the desired logging level */
827 else if (!strncmp(argv[a], "-x", 2)) {
828 verbosity = atoi(&argv[a][2]);
831 else if (!strncmp(argv[a], "-h", 2)) {
832 safestrncpy(bbs_home_directory, &argv[a][2],
833 sizeof bbs_home_directory);
837 else if (!strncmp(argv[a], "-f", 2)) {
841 /* -r tells the server not to drop root permissions. don't use
842 * this unless you know what you're doing. this should be
843 * removed in the next release if it proves unnecessary. */
844 else if (!strcmp(argv[a], "-r"))
847 /* any other parameter makes it crash and burn */
849 lprintf(1, "citserver: usage: "
850 "citserver [-tTraceFile] [-d] [-f]"
851 " [-xLogLevel] [-hHomeDir]\n");
857 /* Tell 'em who's in da house */
859 "\nMultithreaded message server for Citadel/UX\n"
860 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
861 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
862 "you are welcome to change it and/or distribute copies of it under certain\n"
863 "conditions. There is absolutely no warranty for this software. Please\n"
864 "read the 'COPYING.txt' file for details.\n\n");
868 openlog("citserver",LOG_PID,LOG_USER);
869 /* Load site-specific parameters */
870 lprintf(7, "Loading citadel.config\n");
874 * Bind the server to our favourite port.
875 * There is no need to check for errors, because ig_tcp_server()
876 * exits if it doesn't succeed.
878 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
879 msock = ig_tcp_server(config.c_port_number, 5);
880 lprintf(7, "Listening on socket %d\n", msock);
883 * Now that we've bound the socket, change to the BBS user id and its
884 * corresponding group ids
886 if (drop_root_perms) {
887 if ((pw = getpwuid(BBSUID)) == NULL)
888 lprintf(1, "WARNING: getpwuid(%d): %s\n"
889 "Group IDs will be incorrect.\n", BBSUID,
892 initgroups(pw->pw_name, pw->pw_gid);
893 if (setgid(pw->pw_gid))
894 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
897 lprintf(7, "Changing uid to %d\n", BBSUID);
898 if (setuid(BBSUID) != 0) {
899 lprintf(3, "setuid() failed: %s\n", strerror(errno));
903 lprintf(7, "Initializing loadable modules\n");
904 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
905 sprintf(moddir, "%s/modules", bbs_home_directory);
906 DLoader_Init(moddir);
909 lprintf(9, "Modules done initializing.\n");
912 * Do non system dependent startup functions.
917 * Endless loop. Listen on the master socket. When a connection
918 * comes in, create a socket, a context, and a thread.
920 while (!time_to_die) {
921 /* we need to check if a signal has been delivered. because
922 * syscalls may be restartable across signals, we call
923 * select with a timeout of 1 second and repeatedly check for
926 FD_SET(msock, &readfds);
929 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
932 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
934 lprintf(2, "citserver: accept() failed: %s\n",
938 lprintf(7, "citserver: Client socket %d\n", ssock);
939 lprintf(9, "creating context\n");
940 con = CreateNewContext();
941 con->client_socket = ssock;
943 /* Set the SO_REUSEADDR socket option */
944 lprintf(9, "setting socket options\n");
946 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
949 /* set attributes for the new thread */
950 lprintf(9, "setting thread attributes\n");
951 pthread_attr_init(&attr);
952 pthread_attr_setdetachstate(&attr,
953 PTHREAD_CREATE_DETACHED);
955 /* now create the thread */
956 lprintf(9, "creating thread\n");
957 if (pthread_create(&SessThread, &attr,
958 (void* (*)(void*)) sd_context_loop,
962 "citserver: can't create thread: %s\n",
967 * (defunct -- now done at thread creation time)
968 * if (pthread_detach(&SessThread) != 0) {
970 * "citserver: can't detach thread: %s\n",
974 lprintf(9, "done!\n");