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 verbosity = DEFAULT_VERBOSITY; /* Logging level */
69 struct CitContext masterCC;
70 int rescan[2]; /* The Rescan Pipe */
71 time_t last_purge = 0; /* Last dead session purge */
72 int num_threads = 0; /* Current number of threads */
73 int num_sessions = 0; /* Current number of sessions */
75 fd_set masterfds; /* Master sockets etc. */
80 * lprintf() ... Write logging information
82 void lprintf(int loglevel, const char *format, ...) {
86 va_start(arg_ptr, format);
87 vsprintf(buf, format, arg_ptr);
90 if (loglevel <= verbosity) {
91 fprintf(stderr, "%s", buf);
95 PerformLogHooks(loglevel, buf);
100 #ifdef DEBUG_MEMORY_LEAKS
101 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
103 struct TheHeap *hptr;
107 lprintf(3, "DANGER! mallok(%d) at %s:%d failed!\n",
108 tsize, tfile, tline);
112 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
113 strcpy(hptr->h_file, tfile);
114 hptr->h_line = tline;
121 char *tracked_strdup(const char *orig, char *tfile, int tline) {
124 s = tracked_malloc( (strlen(orig)+1), tfile, tline);
125 if (s == NULL) return NULL;
131 void tracked_free(void *ptr) {
132 struct TheHeap *hptr, *freeme;
134 if (heap->h_ptr == ptr) {
140 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
141 if (hptr->next->h_ptr == ptr) {
143 hptr->next = hptr->next->next;
152 void *tracked_realloc(void *ptr, size_t size) {
154 struct TheHeap *hptr;
156 newptr = realloc(ptr, size);
158 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
159 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
166 void dump_tracked() {
167 struct TheHeap *hptr;
169 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
170 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
171 cprintf("%20s %5d\n",
172 hptr->h_file, hptr->h_line);
184 * we used to use master_cleanup() as a signal handler to shut down the server.
185 * however, master_cleanup() and the functions it calls do some things that
186 * aren't such a good idea to do from a signal handler: acquiring mutexes,
187 * playing with signal masks on BSDI systems, etc. so instead we install the
188 * following signal handler to set a global variable to inform the main loop
189 * that it's time to call master_cleanup() and exit.
192 static volatile int time_to_die = 0;
194 static RETSIGTYPE signal_cleanup(int signum) {
200 * Some initialization stuff...
202 void init_sysdep(void) {
205 /* Set up a bunch of semaphores to be used for critical sections */
206 for (a=0; a<MAX_SEMAPHORES; ++a) {
207 pthread_mutex_init(&Critters[a], NULL);
211 * Set up a place to put thread-specific data.
212 * We only need a single pointer per thread - it points to the
213 * thread's CitContext structure in the ContextList linked list.
215 if (pthread_key_create(&MyConKey, NULL) != 0) {
216 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
220 * The action for unexpected signals and exceptions should be to
221 * call signal_cleanup() to gracefully shut down the server.
223 signal(SIGINT, signal_cleanup);
224 signal(SIGQUIT, signal_cleanup);
225 signal(SIGHUP, signal_cleanup);
226 signal(SIGTERM, signal_cleanup);
229 * Do not shut down the server on broken pipe signals, otherwise the
230 * whole Citadel service would come down whenever a single client
233 signal(SIGPIPE, SIG_IGN);
238 * Obtain a semaphore lock to begin a critical section.
240 void begin_critical_section(int which_one)
242 pthread_mutex_lock(&Critters[which_one]);
246 * Release a semaphore lock to end a critical section.
248 void end_critical_section(int which_one)
250 pthread_mutex_unlock(&Critters[which_one]);
256 * This is a generic function to set up a master socket for listening on
257 * a TCP port. The server shuts down if the bind fails.
259 int ig_tcp_server(int port_number, int queue_len)
261 struct sockaddr_in sin;
264 memset(&sin, 0, sizeof(sin));
265 sin.sin_family = AF_INET;
266 sin.sin_addr.s_addr = INADDR_ANY;
268 if (port_number == 0) {
269 lprintf(1, "citserver: illegal port number specified\n");
273 sin.sin_port = htons((u_short)port_number);
275 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
277 lprintf(1, "citserver: Can't create a socket: %s\n",
282 /* Set the SO_REUSEADDR socket option, because it makes sense. */
284 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
286 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
287 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
291 if (listen(s, queue_len) < 0) {
292 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
302 * Return a pointer to the CitContext structure bound to the thread which
303 * called this function. If there's no such binding (for example, if it's
304 * called by the housekeeper thread) then a generic 'master' CC is returned.
306 struct CitContext *MyContext(void) {
307 struct CitContext *retCC;
308 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
309 if (retCC == NULL) retCC = &masterCC;
315 * Initialize a new context and place it in the list.
317 struct CitContext *CreateNewContext(void) {
318 struct CitContext *me, *ptr;
322 me = (struct CitContext *) mallok(sizeof(struct CitContext));
324 lprintf(1, "citserver: can't allocate memory!!\n");
327 memset(me, 0, sizeof(struct CitContext));
329 /* The new context will be created already in the CON_EXECUTING state
330 * in order to prevent another thread from grabbing it while it's
333 me->state = CON_EXECUTING;
335 begin_critical_section(S_SESSION_TABLE);
337 /* obtain a unique session number */
340 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
341 if (ptr->cs_pid == num) {
346 } while (startover == 1);
349 me->next = ContextList;
353 end_critical_section(S_SESSION_TABLE);
360 * client_write() ... Send binary data to the client.
362 void client_write(char *buf, int nbytes)
364 int bytes_written = 0;
366 while (bytes_written < nbytes) {
367 retval = write(CC->client_socket, &buf[bytes_written],
368 nbytes - bytes_written);
370 lprintf(2, "client_write() failed: %s\n",
375 bytes_written = bytes_written + retval;
381 * cprintf() ... Send formatted printable data to the client. It is
382 * implemented in terms of client_write() but remains in
383 * sysdep.c in case we port to somewhere without va_args...
385 void cprintf(const char *format, ...) {
389 va_start(arg_ptr, format);
390 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
391 buf[sizeof buf - 2] = '\n';
392 client_write(buf, strlen(buf));
398 * Read data from the client socket.
400 * 1 Requested number of bytes has been read.
401 * 0 Request timed out.
402 * -1 The socket is broken.
403 * If the socket breaks, the session will be terminated.
405 int client_read_to(char *buf, int bytes, int timeout)
415 FD_SET(CC->client_socket, &rfds);
419 retval = select( (CC->client_socket)+1,
420 &rfds, NULL, NULL, &tv);
422 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
426 rlen = read(CC->client_socket, &buf[len], bytes-len);
428 lprintf(2, "client_read() failed: %s\n",
439 * Read data from the client socket with default timeout.
440 * (This is implemented in terms of client_read_to() and could be
441 * justifiably moved out of sysdep.c)
443 int client_read(char *buf, int bytes)
445 return(client_read_to(buf, bytes, config.c_sleeping));
450 * client_gets() ... Get a LF-terminated line of text from the client.
451 * (This is implemented in terms of client_read() and could be
452 * justifiably moved out of sysdep.c)
454 int client_gets(char *buf)
458 /* Read one character at a time.
461 retval = client_read(&buf[i], 1);
462 if (retval != 1 || buf[i] == '\n' || i == 255)
466 /* If we got a long line, discard characters until the newline.
469 while (buf[i] != '\n' && retval == 1)
470 retval = client_read(&buf[i], 1);
472 /* Strip the trailing newline and any trailing nonprintables (cr's)
475 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
476 buf[strlen(buf)-1] = 0;
483 * The system-dependent part of master_cleanup() - close the master socket.
485 void sysdep_master_cleanup(void) {
486 /* FIX close all protocol master sockets here */
491 * Terminate another session.
492 * (This could justifiably be moved out of sysdep.c because it
493 * no longer does anything that is system-dependent.)
495 void kill_session(int session_to_kill) {
496 struct CitContext *ptr;
498 begin_critical_section(S_SESSION_TABLE);
499 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
500 if (ptr->cs_pid == session_to_kill) {
504 end_critical_section(S_SESSION_TABLE);
511 * Start running as a daemon. Only close stdio if do_close_stdio is set.
513 void start_daemon(int do_close_stdio) {
514 if (do_close_stdio) {
519 signal(SIGHUP,SIG_IGN);
520 signal(SIGINT,SIG_IGN);
521 signal(SIGQUIT,SIG_IGN);
522 if (fork()!=0) exit(0);
528 * Tie in to the 'netsetup' program.
530 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
532 void cmd_nset(char *cmdbuf)
539 char netsetup_args[3][256];
541 if (CC->usersupp.axlevel < 6) {
542 cprintf("%d Higher access required.\n",
543 ERROR + HIGHER_ACCESS_REQUIRED);
547 for (a=1; a<=3; ++a) {
548 if (num_parms(cmdbuf) >= a) {
549 extract(netsetup_args[a-1], cmdbuf, a-1);
550 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
551 if (netsetup_args[a-1][b] == 34) {
552 netsetup_args[a-1][b] = '_';
557 netsetup_args[a-1][0] = 0;
561 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
562 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
563 netsetup = popen(fbuf, "r");
564 if (netsetup == NULL) {
565 cprintf("%d %s\n", ERROR, strerror(errno));
570 while (ch = getc(netsetup), (ch > 0)) {
571 fbuf[strlen(fbuf)+1] = 0;
572 fbuf[strlen(fbuf)] = ch;
575 retcode = pclose(netsetup);
578 for (a=0; a<strlen(fbuf); ++a) {
579 if (fbuf[a] < 32) fbuf[a] = 32;
582 cprintf("%d %s\n", ERROR, fbuf);
586 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
588 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
595 * Generic routine to convert a login name to a full name (gecos)
596 * Returns nonzero if a conversion took place
598 int convert_login(char NameToConvert[]) {
602 pw = getpwnam(NameToConvert);
607 strcpy(NameToConvert, pw->pw_gecos);
608 for (a=0; a<strlen(NameToConvert); ++a) {
609 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
618 * Purge all sessions which have the 'kill_me' flag set.
619 * This function has code to prevent it from running more than once every
620 * few seconds, because running it after every single unbind would waste a lot
621 * of CPU time and keep the context list locked too much.
623 * After that's done, we raise or lower the size of the worker thread pool
624 * if such an action is appropriate.
626 void dead_session_purge(void) {
627 struct CitContext *ptr, *rem;
631 if ( (time(NULL) - last_purge) < 5 ) return; /* Too soon, go away */
636 begin_critical_section(S_SESSION_TABLE);
637 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
638 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
642 end_critical_section(S_SESSION_TABLE);
644 /* RemoveContext() enters its own S_SESSION_TABLE critical
645 * section, so we have to do it like this.
648 lprintf(9, "Purging session %d\n", rem->cs_pid);
652 } while (rem != NULL);
655 /* Raise or lower the size of the worker thread pool if such
656 * an action is appropriate.
659 if ( (num_sessions > num_threads)
660 && (num_threads < config.c_max_workers) ) {
662 pthread_attr_init(&attr);
663 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
664 if (pthread_create(&newthread, &attr,
665 (void* (*)(void*)) worker_thread, NULL) != 0) {
666 lprintf(1, "Can't create worker thead: %s\n",
672 else if ( (num_sessions < num_threads)
673 && (num_threads > config.c_min_workers) ) {
684 * Here's where it all begins.
686 int main(int argc, char **argv)
688 pthread_t HousekeepingThread; /* Thread descriptor */
689 pthread_attr_t attr; /* Thread attributes */
690 char tracefile[128]; /* Name of file to log traces to */
691 int a, i; /* General-purpose variables */
693 int drop_root_perms = 1;
695 struct ServiceFunctionHook *serviceptr;
697 /* specify default port name and trace file */
698 strcpy(tracefile, "");
700 /* parse command-line arguments */
701 for (a=1; a<argc; ++a) {
703 /* -t specifies where to log trace messages to */
704 if (!strncmp(argv[a], "-t", 2)) {
705 strcpy(tracefile, argv[a]);
706 strcpy(tracefile, &tracefile[2]);
707 freopen(tracefile, "r", stdin);
708 freopen(tracefile, "w", stdout);
709 freopen(tracefile, "w", stderr);
712 /* run in the background if -d was specified */
713 else if (!strcmp(argv[a], "-d")) {
714 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
717 /* -x specifies the desired logging level */
718 else if (!strncmp(argv[a], "-x", 2)) {
719 verbosity = atoi(&argv[a][2]);
722 else if (!strncmp(argv[a], "-h", 2)) {
723 safestrncpy(bbs_home_directory, &argv[a][2],
724 sizeof bbs_home_directory);
728 else if (!strncmp(argv[a], "-f", 2)) {
732 /* -r tells the server not to drop root permissions. don't use
733 * this unless you know what you're doing. this should be
734 * removed in the next release if it proves unnecessary. */
735 else if (!strcmp(argv[a], "-r"))
738 /* any other parameter makes it crash and burn */
740 lprintf(1, "citserver: usage: "
741 "citserver [-tTraceFile] [-d] [-f]"
742 " [-xLogLevel] [-hHomeDir]\n");
748 /* Tell 'em who's in da house */
750 "\nMultithreaded message server for Citadel/UX\n"
751 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
752 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
753 "you are welcome to change it and/or distribute copies of it under certain\n"
754 "conditions. There is absolutely no warranty for this software. Please\n"
755 "read the 'COPYING.txt' file for details.\n\n");
759 openlog("citserver",LOG_PID,LOG_USER);
761 /* Load site-specific parameters */
762 lprintf(7, "Loading citadel.config\n");
766 * Do non system dependent startup functions.
771 * Bind the server to our favorite ports.
773 CtdlRegisterServiceHook(config.c_port_number,
774 citproto_begin_session,
778 * Load any server-side modules (plugins) available here.
780 lprintf(7, "Initializing loadable modules\n");
781 if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
782 sprintf(moddir, "%s/modules", bbs_home_directory);
783 DLoader_Init(moddir);
788 * The rescan pipe exists so that worker threads can be woken up and
789 * told to re-scan the context list for fd's to listen on. This is
790 * necessary, for example, when a context is about to go idle and needs
791 * to get back on that list.
794 lprintf(1, "Can't create rescan pipe!\n");
799 * Set up a fd_set containing all the master sockets to which we
800 * always listen. It's computationally less expensive to just copy
801 * this to a local fd_set when starting a new select() and then add
802 * the client sockets than it is to initialize a new one and then
803 * figure out what to put there.
807 FD_SET(rescan[0], &masterfds);
808 if (rescan[0] > masterhighest) masterhighest = rescan[0];
810 for (serviceptr = ServiceHookTable; serviceptr != NULL;
811 serviceptr = serviceptr->next ) {
812 serviceptr->msock = ig_tcp_server(
813 serviceptr->tcp_port, config.c_maxsessions);
814 if (serviceptr->msock >= 0) {
815 FD_SET(serviceptr->msock, &masterfds);
816 if (serviceptr->msock > masterhighest)
817 masterhighest = serviceptr->msock;
818 lprintf(7, "Bound to port %-5d (socket %d)\n",
819 serviceptr->tcp_port,
823 lprintf(1, "Unable to bind to port %d\n",
824 serviceptr->tcp_port);
830 * Now that we've bound the sockets, change to the BBS user id and its
831 * corresponding group ids
833 if (drop_root_perms) {
834 if ((pw = getpwuid(BBSUID)) == NULL)
835 lprintf(1, "WARNING: getpwuid(%d): %s\n"
836 "Group IDs will be incorrect.\n", BBSUID,
839 initgroups(pw->pw_name, pw->pw_gid);
840 if (setgid(pw->pw_gid))
841 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
844 lprintf(7, "Changing uid to %d\n", BBSUID);
845 if (setuid(BBSUID) != 0) {
846 lprintf(3, "setuid() failed: %s\n", strerror(errno));
851 * Create the housekeeper thread
853 lprintf(7, "Starting housekeeper thread\n");
854 pthread_attr_init(&attr);
855 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
856 if (pthread_create(&HousekeepingThread, &attr,
857 (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
858 lprintf(1, "Can't create housekeeping thead: %s\n",
864 * Now create a bunch of worker threads.
866 for (i=0; i<(config.c_min_workers-1); ++i) {
867 pthread_attr_init(&attr);
868 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
869 if (pthread_create(&HousekeepingThread, &attr,
870 (void* (*)(void*)) worker_thread, NULL) != 0) {
871 lprintf(1, "Can't create worker thead: %s\n",
876 /* Now this thread can become a worker as well. */
884 * Bind a thread to a context.
886 inline void become_session(struct CitContext *which_con) {
887 pthread_setspecific(MyConKey, (void *)which_con );
893 * This loop just keeps going and going and going...
895 void worker_thread(void) {
899 struct CitContext *ptr;
900 struct CitContext *bind_me = NULL;
903 struct CitContext *con= NULL; /* Temporary context pointer */
904 struct ServiceFunctionHook *serviceptr;
905 struct sockaddr_in fsin; /* Data for master socket */
906 int alen; /* Data for master socket */
907 int ssock; /* Descriptor for client socket */
910 while (!time_to_die) {
913 * A naive implementation would have all idle threads
914 * calling select() and then they'd all wake up at once. We
915 * solve this problem by putting the select() in a critical
916 * section, so only one thread has the opportunity to wake
917 * up. If we wake up on the master socket, create a new
918 * session context; otherwise, just bind the thread to the
919 * context we want and go on our merry way.
922 begin_critical_section(S_I_WANNA_SELECT);
923 SETUP_FD: memcpy(&readfds, &masterfds, sizeof(fd_set) );
924 highest = masterhighest;
925 begin_critical_section(S_SESSION_TABLE);
926 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
927 if (ptr->state == CON_IDLE) {
928 FD_SET(ptr->client_socket, &readfds);
929 if (ptr->client_socket > highest)
930 highest = ptr->client_socket;
933 end_critical_section(S_SESSION_TABLE);
935 retval = select(highest + 1, &readfds, NULL, NULL, NULL);
937 /* Now figure out who made this select() unblock.
938 * First, check for an error or exit condition.
941 end_critical_section(S_I_WANNA_SELECT);
942 lprintf(9, "Exiting (%s)\n", strerror(errno));
946 /* Next, check to see if it's a new client connecting
947 * on the master socket.
949 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
950 serviceptr = serviceptr->next ) {
952 if (FD_ISSET(serviceptr->msock, &readfds)) {
954 ssock = accept(serviceptr->msock,
955 (struct sockaddr *)&fsin, &alen);
957 lprintf(2, "citserver: accept(): %s\n",
961 lprintf(7, "citserver: "
962 "New client socket %d\n",
965 /* New context will be created already
966 * set up in the CON_EXECUTING state.
968 con = CreateNewContext();
970 /* Assign new socket number to it. */
971 con->client_socket = ssock;
972 con->h_command_function =
973 serviceptr->h_command_function;
975 /* Set the SO_REUSEADDR socket option */
977 setsockopt(ssock, SOL_SOCKET,
983 serviceptr->h_greeting_function();
984 become_session(NULL);
985 con->state = CON_IDLE;
991 /* If the rescan pipe went active, someone is telling this
992 * thread that the &readfds needs to be refreshed with more
995 if (!time_to_die) if (FD_ISSET(rescan[0], &readfds)) {
996 read(rescan[0], &junk, 1);
1000 /* It must be a client socket. Find a context that has data
1001 * waiting on its socket *and* is in the CON_IDLE state.
1005 begin_critical_section(S_SESSION_TABLE);
1006 for (ptr = ContextList;
1007 ( (ptr != NULL) && (bind_me == NULL) );
1009 if ( (FD_ISSET(ptr->client_socket, &readfds))
1010 && (ptr->state == CON_IDLE) ) {
1014 if (bind_me != NULL) {
1015 /* Found one. Stake a claim to it before
1016 * letting anyone else touch the context list.
1018 bind_me->state = CON_EXECUTING;
1021 end_critical_section(S_SESSION_TABLE);
1022 end_critical_section(S_I_WANNA_SELECT);
1024 /* We're bound to a session, now do *one* command */
1025 if (bind_me != NULL) {
1026 become_session(bind_me);
1027 CC->h_command_function();
1028 become_session(NULL);
1029 bind_me->state = CON_IDLE;
1030 if (bind_me->kill_me == 1) {
1031 RemoveContext(bind_me);
1033 write(rescan[1], &junk, 1);
1036 lprintf(9, "Thread found nothing to do!\n");
1040 dead_session_purge();
1043 /* If control reaches this point, the server is shutting down */