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.
10 * Eventually we'll try porting to a different platform and either have
11 * multiple variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
24 #include <sys/socket.h>
27 #include <netinet/in.h>
43 #include "sysdep_decls.h"
44 #include "citserver.h"
48 #include "housekeeping.h"
49 #include "dynloader.h"
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
60 #ifdef DEBUG_MEMORY_LEAKS
61 struct TheHeap *heap = NULL;
64 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
65 pthread_key_t MyConKey; /* TSD key for MyContext() */
67 int msock; /* master listening socket */
68 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
70 struct CitContext masterCC;
71 int rescan[2]; /* The Rescan Pipe */
72 time_t last_purge = 0; /* Last dead session purge */
75 * lprintf() ... Write logging information
77 void lprintf(int loglevel, const char *format, ...) {
81 va_start(arg_ptr, format);
82 vsprintf(buf, format, arg_ptr);
85 if (loglevel <= verbosity) {
86 fprintf(stderr, "%s", buf);
90 PerformLogHooks(loglevel, buf);
95 #ifdef DEBUG_MEMORY_LEAKS
96 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
102 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
103 tsize, tfile, tline);
107 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
108 strcpy(hptr->h_file, tfile);
109 hptr->h_line = tline;
116 char *tracked_strdup(const char *orig, char *tfile, int tline) {
119 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
120 if (s == NULL) return NULL;
126 void tracked_free(void *ptr) {
127 struct TheHeap *hptr, *freeme;
129 if (heap->h_ptr == ptr) {
135 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
136 if (hptr->next->h_ptr == ptr) {
138 hptr->next = hptr->next->next;
147 void *tracked_realloc(void *ptr, size_t size) {
149 struct TheHeap *hptr;
151 newptr = realloc(ptr, size);
153 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
154 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
161 void dump_tracked() {
162 struct TheHeap *hptr;
164 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
165 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
166 cprintf("%20s %5d\n",
167 hptr->h_file, hptr->h_line);
179 * we used to use master_cleanup() as a signal handler to shut down the server.
180 * however, master_cleanup() and the functions it calls do some things that
181 * aren't such a good idea to do from a signal handler: acquiring mutexes,
182 * playing with signal masks on BSDI systems, etc. so instead we install the
183 * following signal handler to set a global variable to inform the main loop
184 * that it's time to call master_cleanup() and exit.
187 static volatile int time_to_die = 0;
189 static RETSIGTYPE signal_cleanup(int signum) {
195 * Some initialization stuff...
197 void init_sysdep(void) {
200 /* Set up a bunch of semaphores to be used for critical sections */
201 for (a=0; a<MAX_SEMAPHORES; ++a) {
202 pthread_mutex_init(&Critters[a], NULL);
206 * Set up a place to put thread-specific data.
207 * We only need a single pointer per thread - it points to the
208 * thread's CitContext structure in the ContextList linked list.
210 if (pthread_key_create(&MyConKey, NULL) != 0) {
211 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
215 * The action for unexpected signals and exceptions should be to
216 * call signal_cleanup() to gracefully shut down the server.
218 signal(SIGINT, signal_cleanup);
219 signal(SIGQUIT, signal_cleanup);
220 signal(SIGHUP, signal_cleanup);
221 signal(SIGTERM, signal_cleanup);
224 * Do not shut down the server on broken pipe signals, otherwise the
225 * whole Citadel service would come down whenever a single client
228 signal(SIGPIPE, SIG_IGN);
233 * Obtain a semaphore lock to begin a critical section.
235 void begin_critical_section(int which_one)
237 pthread_mutex_lock(&Critters[which_one]);
241 * Release a semaphore lock to end a critical section.
243 void end_critical_section(int which_one)
245 pthread_mutex_unlock(&Critters[which_one]);
251 * This is a generic function to set up a master socket for listening on
252 * a TCP port. The server shuts down if the bind fails.
254 int ig_tcp_server(int port_number, int queue_len)
256 struct sockaddr_in sin;
259 memset(&sin, 0, sizeof(sin));
260 sin.sin_family = AF_INET;
261 sin.sin_addr.s_addr = INADDR_ANY;
263 if (port_number == 0) {
265 "citserver: No port number specified. Run setup.\n");
269 sin.sin_port = htons((u_short)port_number);
271 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
273 lprintf(1, "citserver: Can't create a socket: %s\n",
278 /* Set the SO_REUSEADDR socket option, because it makes sense. */
280 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
282 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
283 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
287 if (listen(s, queue_len) < 0) {
288 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
298 * Return a pointer to the CitContext structure bound to the thread which
299 * called this function. If there's no such binding (for example, if it's
300 * called by the housekeeper thread) then a generic 'master' CC is returned.
302 struct CitContext *MyContext(void) {
303 struct CitContext *retCC;
304 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
305 if (retCC == NULL) retCC = &masterCC;
311 * Initialize a new context and place it in the list.
313 struct CitContext *CreateNewContext(void) {
314 struct CitContext *me, *ptr;
318 me = (struct CitContext *) mallok(sizeof(struct CitContext));
320 lprintf(1, "citserver: can't allocate memory!!\n");
323 memset(me, 0, sizeof(struct CitContext));
325 /* The new context will be created already in the CON_EXECUTING state
326 * in order to prevent another thread from grabbing it while it's
329 me->state = CON_EXECUTING;
331 begin_critical_section(S_SESSION_TABLE);
333 /* obtain a unique session number */
336 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
337 if (ptr->cs_pid == num) {
342 } while (startover == 1);
345 me->next = ContextList;
348 end_critical_section(S_SESSION_TABLE);
355 * Return the number of sessions currently running.
356 * (This should probably be moved out of sysdep.c)
358 int session_count(void) {
359 struct CitContext *ptr;
362 begin_critical_section(S_SESSION_TABLE);
363 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
366 end_critical_section(S_SESSION_TABLE);
373 * client_write() ... Send binary data to the client.
375 void client_write(char *buf, int nbytes)
377 int bytes_written = 0;
379 while (bytes_written < nbytes) {
380 retval = write(CC->client_socket, &buf[bytes_written],
381 nbytes - bytes_written);
383 lprintf(2, "client_write() failed: %s\n",
388 bytes_written = bytes_written + retval;
394 * cprintf() ... Send formatted printable data to the client. It is
395 * implemented in terms of client_write() but remains in
396 * sysdep.c in case we port to somewhere without va_args...
398 void cprintf(const char *format, ...) {
402 va_start(arg_ptr, format);
403 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
404 buf[sizeof buf - 2] = '\n';
405 client_write(buf, strlen(buf));
411 * Read data from the client socket.
413 * 1 Requested number of bytes has been read.
414 * 0 Request timed out.
415 * If the socket breaks, the session is immediately terminated.
417 int client_read_to(char *buf, int bytes, int timeout)
427 FD_SET(CC->client_socket, &rfds);
431 retval = select( (CC->client_socket)+1,
432 &rfds, NULL, NULL, &tv);
434 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
438 rlen = read(CC->client_socket, &buf[len], bytes-len);
440 lprintf(2, "client_read() failed: %s\n",
451 * Read data from the client socket with default timeout.
452 * (This is implemented in terms of client_read_to() and could be
453 * justifiably moved out of sysdep.c)
455 int client_read(char *buf, int bytes)
457 return(client_read_to(buf, bytes, config.c_sleeping));
462 * client_gets() ... Get a LF-terminated line of text from the client.
463 * (This is implemented in terms of client_read() and could be
464 * justifiably moved out of sysdep.c)
466 int client_gets(char *buf)
470 /* Read one character at a time.
473 retval = client_read(&buf[i], 1);
474 if (retval != 1 || buf[i] == '\n' || i == 255)
478 /* If we got a long line, discard characters until the newline.
481 while (buf[i] != '\n' && retval == 1)
482 retval = client_read(&buf[i], 1);
484 /* Strip the trailing newline and any trailing nonprintables (cr's)
487 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
488 buf[strlen(buf)-1] = 0;
495 * The system-dependent part of master_cleanup() - close the master socket.
497 void sysdep_master_cleanup(void) {
498 lprintf(7, "Closing master socket %d\n", msock);
504 * Terminate another session.
505 * (This could justifiably be moved out of sysdep.c because it
506 * no longer does anything that is system-dependent.)
508 void kill_session(int session_to_kill) {
509 struct CitContext *ptr;
511 begin_critical_section(S_SESSION_TABLE);
512 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
513 if (ptr->cs_pid == session_to_kill) {
517 end_critical_section(S_SESSION_TABLE);
524 * Start running as a daemon. Only close stdio if do_close_stdio is set.
526 void start_daemon(int do_close_stdio) {
527 if (do_close_stdio) {
532 signal(SIGHUP,SIG_IGN);
533 signal(SIGINT,SIG_IGN);
534 signal(SIGQUIT,SIG_IGN);
535 if (fork()!=0) exit(0);
541 * Tie in to the 'netsetup' program.
543 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
545 void cmd_nset(char *cmdbuf)
552 char netsetup_args[3][256];
554 if (CC->usersupp.axlevel < 6) {
555 cprintf("%d Higher access required.\n",
556 ERROR + HIGHER_ACCESS_REQUIRED);
560 for (a=1; a<=3; ++a) {
561 if (num_parms(cmdbuf) >= a) {
562 extract(netsetup_args[a-1], cmdbuf, a-1);
563 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
564 if (netsetup_args[a-1][b] == 34) {
565 netsetup_args[a-1][b] = '_';
570 netsetup_args[a-1][0] = 0;
574 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
575 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
576 netsetup = popen(fbuf, "r");
577 if (netsetup == NULL) {
578 cprintf("%d %s\n", ERROR, strerror(errno));
583 while (ch = getc(netsetup), (ch > 0)) {
584 fbuf[strlen(fbuf)+1] = 0;
585 fbuf[strlen(fbuf)] = ch;
588 retcode = pclose(netsetup);
591 for (a=0; a<strlen(fbuf); ++a) {
592 if (fbuf[a] < 32) fbuf[a] = 32;
595 cprintf("%d %s\n", ERROR, fbuf);
599 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
601 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
608 * Generic routine to convert a login name to a full name (gecos)
609 * Returns nonzero if a conversion took place
611 int convert_login(char NameToConvert[]) {
615 pw = getpwnam(NameToConvert);
620 strcpy(NameToConvert, pw->pw_gecos);
621 for (a=0; a<strlen(NameToConvert); ++a) {
622 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
631 * Purge all sessions which have the 'kill_me' flag set.
632 * This function has code to prevent it from running more than once every
633 * few seconds, because running it after every single unbind would waste a lot
634 * of CPU time and keep the context list locked too much.
636 void dead_session_purge(void) {
637 struct CitContext *ptr, *rem;
639 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
644 begin_critical_section(S_SESSION_TABLE);
645 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
646 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
650 end_critical_section(S_SESSION_TABLE);
652 /* RemoveContext() enters its own S_SESSION_TABLE critical
653 * section, so we have to do it like this.
656 lprintf(9, "Purging session %d\n", rem->cs_pid);
660 } while (rem != NULL);
667 * Here's where it all begins.
669 int main(int argc, char **argv)
671 pthread_t HousekeepingThread; /* Thread descriptor */
672 pthread_attr_t attr; /* Thread attributes */
673 char tracefile[128]; /* Name of file to log traces to */
674 int a, i; /* General-purpose variables */
676 int drop_root_perms = 1;
679 /* specify default port name and trace file */
680 strcpy(tracefile, "");
682 /* parse command-line arguments */
683 for (a=1; a<argc; ++a) {
685 /* -t specifies where to log trace messages to */
686 if (!strncmp(argv[a], "-t", 2)) {
687 strcpy(tracefile, argv[a]);
688 strcpy(tracefile, &tracefile[2]);
689 freopen(tracefile, "r", stdin);
690 freopen(tracefile, "w", stdout);
691 freopen(tracefile, "w", stderr);
694 /* run in the background if -d was specified */
695 else if (!strcmp(argv[a], "-d")) {
696 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
699 /* -x specifies the desired logging level */
700 else if (!strncmp(argv[a], "-x", 2)) {
701 verbosity = atoi(&argv[a][2]);
704 else if (!strncmp(argv[a], "-h", 2)) {
705 safestrncpy(bbs_home_directory, &argv[a][2],
706 sizeof bbs_home_directory);
710 else if (!strncmp(argv[a], "-f", 2)) {
714 /* -r tells the server not to drop root permissions. don't use
715 * this unless you know what you're doing. this should be
716 * removed in the next release if it proves unnecessary. */
717 else if (!strcmp(argv[a], "-r"))
720 /* any other parameter makes it crash and burn */
722 lprintf(1, "citserver: usage: "
723 "citserver [-tTraceFile] [-d] [-f]"
724 " [-xLogLevel] [-hHomeDir]\n");
730 /* Tell 'em who's in da house */
732 "\nMultithreaded message server for Citadel/UX\n"
733 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
734 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
735 "you are welcome to change it and/or distribute copies of it under certain\n"
736 "conditions. There is absolutely no warranty for this software. Please\n"
737 "read the 'COPYING.txt' file for details.\n\n");
741 openlog("citserver",LOG_PID,LOG_USER);
743 /* Load site-specific parameters */
744 lprintf(7, "Loading citadel.config\n");
748 * Bind the server to our favourite port.
749 * There is no need to check for errors, because ig_tcp_server()
750 * exits if it doesn't succeed.
752 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
753 msock = ig_tcp_server(config.c_port_number, 5);
754 lprintf(7, "Listening on socket %d\n", msock);
757 * Now that we've bound the socket, change to the BBS user id and its
758 * corresponding group ids
760 if (drop_root_perms) {
761 if ((pw = getpwuid(BBSUID)) == NULL)
762 lprintf(1, "WARNING: getpwuid(%d): %s\n"
763 "Group IDs will be incorrect.\n", BBSUID,
766 initgroups(pw->pw_name, pw->pw_gid);
767 if (setgid(pw->pw_gid))
768 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
771 lprintf(7, "Changing uid to %d\n", BBSUID);
772 if (setuid(BBSUID) != 0) {
773 lprintf(3, "setuid() failed: %s\n", strerror(errno));
778 * Do non system dependent startup functions.
783 * Load any server-side modules (plugins) available here.
785 lprintf(7, "Initializing loadable modules\n");
786 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
787 sprintf(moddir, "%s/modules", bbs_home_directory);
788 DLoader_Init(moddir);
792 lprintf(7, "Starting housekeeper thread\n");
793 pthread_attr_init(&attr);
794 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
795 if (pthread_create(&HousekeepingThread, &attr,
796 (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
797 lprintf(1, "Can't create housekeeping thead: %s\n",
803 * The rescan pipe exists so that worker threads can be woken up and
804 * told to re-scan the context list for fd's to listen on. This is
805 * necessary, for example, when a context is about to go idle and needs
806 * to get back on that list.
809 lprintf(1, "Can't create rescan pipe!\n");
814 * Now create a bunch of worker threads.
816 for (i=0; i<(config.c_worker_threads-1); ++i) {
817 pthread_attr_init(&attr);
818 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
819 if (pthread_create(&HousekeepingThread, &attr,
820 (void* (*)(void*)) worker_thread, NULL) != 0) {
821 lprintf(1, "Can't create worker thead: %s\n",
826 /* Now this thread can become a worker as well. */
839 * This loop just keeps going and going and going...
841 void worker_thread(void) {
846 struct CitContext *ptr;
847 struct CitContext *bind_me = NULL;
850 struct CitContext *con= NULL; /* Temporary context pointer */
851 struct sockaddr_in fsin; /* Data for master socket */
852 int alen; /* Data for master socket */
853 int ssock; /* Descriptor for client socket */
855 while (!time_to_die) {
858 * In a stupid environment, we would have all idle threads
859 * calling select() and then they'd all wake up at once. We
860 * solve this problem by putting the select() in a critical
861 * section, so only one thread has the opportunity to wake
862 * up. If we wake up on the master socket, create a new
863 * session context; otherwise, just bind the thread to the
864 * context we want and go on our merry way.
867 begin_critical_section(S_I_WANNA_SELECT);
868 SETUP_FD: FD_ZERO(&readfds);
869 FD_SET(msock, &readfds);
871 FD_SET(rescan[0], &readfds);
872 if (rescan[0] > highest) highest = rescan[0];
875 begin_critical_section(S_SESSION_TABLE);
876 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
877 if (ptr->state == CON_IDLE) {
878 FD_SET(ptr->client_socket, &readfds);
879 if (ptr->client_socket > highest)
880 highest = ptr->client_socket;
884 end_critical_section(S_SESSION_TABLE);
886 retval = select(highest + 1, &readfds, NULL, NULL, NULL);
888 /* Now figure out who made this select() unblock.
889 * First, check for an error or exit condition.
892 end_critical_section(S_I_WANNA_SELECT);
893 lprintf(9, "Exiting (%s)\n", strerror(errno));
897 /* Next, check to see if it's a new client connecting
898 * on the master socket.
900 else if (FD_ISSET(msock, &readfds)) {
902 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
904 lprintf(2, "citserver: accept() failed: %s\n",
908 lprintf(7, "citserver: New client socket %d\n",
911 /* New context will be created already set up
912 * in the CON_EXECUTING state.
914 con = CreateNewContext();
916 /* Assign our new socket number to it. */
917 con->client_socket = ssock;
919 /* Set the SO_REUSEADDR socket option */
921 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
924 pthread_setspecific(MyConKey, (void *)con);
926 /* do_command_loop(); */
927 pthread_setspecific(MyConKey, (void *)NULL);
928 con->state = CON_IDLE;
933 /* If the rescan pipe went active, someone is telling this
934 * thread that the &readfds needs to be refreshed with more
937 else if (FD_ISSET(rescan[0], &readfds)) {
938 read(rescan[0], &junk, 1);
942 /* It must be a client socket. Find a context that has data
943 * waiting on its socket *and* is in the CON_IDLE state.
947 begin_critical_section(S_SESSION_TABLE);
948 for (ptr = ContextList;
949 ( (ptr != NULL) && (bind_me == NULL) );
951 if ( (FD_ISSET(ptr->client_socket, &readfds))
952 && (ptr->state == CON_IDLE) ) {
956 if (bind_me != NULL) {
957 /* Found one. Stake a claim to it before
958 * letting anyone else touch the context list.
960 bind_me->state = CON_EXECUTING;
963 end_critical_section(S_SESSION_TABLE);
964 end_critical_section(S_I_WANNA_SELECT);
966 /* We're bound to a session, now do *one* command */
967 if (bind_me != NULL) {
968 pthread_setspecific(MyConKey, (void *)bind_me);
970 pthread_setspecific(MyConKey, (void *)NULL);
971 bind_me->state = CON_IDLE;
972 if (bind_me->kill_me == 1) {
973 RemoveContext(bind_me);
975 write(rescan[1], &junk, 1);
978 lprintf(9, "Thread found nothing to do!\n");
982 dead_session_purge();
985 /* If control reaches this point, the server is shutting down */