2 * Citadel/UX "system dependent" stuff.
3 * See copyright.txt for copyright information.
5 * Here's where we (hopefully) have all the parts of the Citadel server that
6 * would need to be altered to run the server in a non-POSIX environment.
7 * Wherever possible, we use function wrappers and type definitions to create
8 * abstractions that are platform-independent from the calling side.
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.
20 #include <sys/types.h>
22 #include <sys/socket.h>
24 #include <netinet/in.h>
35 #include "sysdep_decls.h"
36 #include "citserver.h"
39 #include <sys/select.h>
42 extern struct CitContext *ContextList;
43 extern struct config config;
44 extern char bbs_home_directory[];
45 extern int home_specified;
47 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
48 pthread_key_t MyConKey; /* TSD key for MyContext() */
50 int msock; /* master listening socket */
51 int verbosity = 3; /* Logging level */
55 * lprintf() ... Write logging information
57 void lprintf(int loglevel, const char *format, ...) {
62 if (loglevel <= verbosity) {
63 va_start(arg_ptr, format);
64 rc = vsprintf(buf, format, arg_ptr);
67 fprintf(stderr, "%s", buf);
75 * Some initialization stuff...
77 void init_sysdep(void) {
80 /* Set up a bunch of semaphores to be used for critical sections */
81 for (a=0; a<MAX_SEMAPHORES; ++a) {
82 pthread_mutex_init(&Critters[a], NULL);
86 * Set up a place to put thread-specific data.
87 * We only need a single pointer per thread - it points to the
88 * thread's CitContext structure in the ContextList linked list.
90 if (pthread_key_create(&MyConKey, NULL) != 0) {
91 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
95 * The action for unexpected signals and exceptions should be to
96 * call master_cleanup() to gracefully shut down the server.
98 signal(SIGINT, (void(*)(int))master_cleanup);
99 signal(SIGQUIT, (void(*)(int))master_cleanup);
100 signal(SIGHUP, (void(*)(int))master_cleanup);
101 signal(SIGTERM, (void(*)(int))master_cleanup);
106 * Obtain a semaphore lock to begin a critical section.
108 void begin_critical_section(int which_one)
112 lprintf(8, "begin_critical_section(%d)\n", which_one);
113 if (CC != NULL) hook_crit_get(CC->cs_pid, which_one);
115 /* Don't get interrupted during the critical section */
116 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
118 /* Obtain a semaphore */
119 pthread_mutex_lock(&Critters[which_one]);
121 if (CC != NULL) hook_crit_got(CC->cs_pid, which_one);
125 * Release a semaphore lock to end a critical section.
127 void end_critical_section(int which_one)
131 lprintf(8, " end_critical_section(%d)\n", which_one);
132 if (CC != NULL) hook_crit_end(CC->cs_pid, which_one);
134 /* Let go of the semaphore */
135 pthread_mutex_unlock(&Critters[which_one]);
137 /* If a cancel was sent during the critical section, do it now.
138 * Then re-enable thread cancellation.
140 pthread_testcancel();
141 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
142 pthread_testcancel();
149 * This is a generic function to set up a master socket for listening on
150 * a TCP port. The server shuts down if the bind fails.
152 int ig_tcp_server(int port_number, int queue_len)
154 struct sockaddr_in sin;
157 bzero((char *)&sin, sizeof(sin));
158 sin.sin_family = AF_INET;
159 sin.sin_addr.s_addr = INADDR_ANY;
161 if (port_number == 0) {
162 lprintf(1, "citserver: No port number specified. Run setup again.\n");
166 sin.sin_port = htons((u_short)port_number);
168 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
170 lprintf(1, "citserver: Can't create a socket: %s\n",
175 /* Set the SO_REUSEADDR socket option, because it makes sense. */
177 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
179 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
180 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
184 if (listen(s, queue_len) < 0) {
185 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
194 * Return a pointer to a thread's own CitContext structure (old)
195 * NOTE: this version of MyContext() is commented out because it is no longer
196 * in use. It was written before I discovered TSD keys. This
197 * version pounds through the context list until it finds the one matching
198 * the currently running thread. It remains here, commented out, in case it
199 * is needed for future ports to threading libraries which have the equivalent
200 * of pthread_self() but not pthread_key_create() and its ilk.
202 * struct CitContext *MyContext() {
203 * struct CitContext *ptr;
206 * me = pthread_self();
207 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
208 * if (ptr->mythread == me) return(ptr);
215 * Return a pointer to a thread's own CitContext structure (new)
217 struct CitContext *MyContext(void) {
218 return (struct CitContext *) pthread_getspecific(MyConKey);
223 * Wedge our way into the context list.
225 struct CitContext *CreateNewContext(void) {
226 struct CitContext *me;
228 lprintf(9, "CreateNewContext: calling malloc()\n");
229 me = (struct CitContext *) malloc(sizeof(struct CitContext));
231 lprintf(1, "citserver: can't allocate memory!!\n");
234 bzero(me, sizeof(struct CitContext));
236 begin_critical_section(S_SESSION_TABLE);
237 me->next = ContextList;
239 end_critical_section(S_SESSION_TABLE);
244 * Add a thread's thread ID to the context
246 void InitMyContext(struct CitContext *con)
250 con->mythread = pthread_self();
251 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
252 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
253 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
254 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
260 * Remove a context from the context list.
262 void RemoveContext(struct CitContext *con)
264 struct CitContext *ptr;
266 lprintf(7, "Starting RemoveContext()\n");
267 lprintf(9, "session count before RemoveContext is %d\n", session_count());
269 lprintf(7, "WARNING: RemoveContext() called with null!\n");
273 begin_critical_section(S_SESSION_TABLE);
274 lprintf(7, "Closing socket %d\n", con->client_socket);
275 close(con->client_socket);
277 if (ContextList==con) {
278 ContextList = ContextList->next;
281 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
282 if (ptr->next == con) {
283 ptr->next = ptr->next->next;
290 lprintf(9, "session count after RemoveContext is %d\n", session_count());
292 lprintf(7, "Done with RemoveContext\n");
293 end_critical_section(S_SESSION_TABLE);
298 * Return the number of sessions currently running.
299 * (This should probably be moved out of sysdep.c)
301 int session_count(void) {
302 struct CitContext *ptr;
305 lprintf(9, "session_count() starting\n");
306 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
308 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
311 lprintf(9, "session_count() finishing\n");
317 * client_write() ... Send binary data to the client.
319 void client_write(char *buf, int nbytes)
321 int bytes_written = 0;
323 while (bytes_written < nbytes) {
324 retval = write(CC->client_socket, &buf[bytes_written],
325 nbytes - bytes_written);
327 lprintf(2, "client_write() failed: %s\n",
331 bytes_written = bytes_written + retval;
337 * cprintf() ... Send formatted printable data to the client. It is
338 * implemented in terms of client_write() but remains in
339 * sysdep.c in case we port to somewhere without va_args...
341 void cprintf(const char *format, ...) {
346 va_start(arg_ptr, format);
347 rc = vsprintf(buf, format, arg_ptr);
350 client_write(buf, strlen(buf));
355 * Read data from the client socket.
357 * 1 Requested number of bytes has been read.
358 * 0 Request timed out.
359 * If the socket breaks, the session is immediately terminated.
361 int client_read_to(char *buf, int bytes, int timeout)
371 FD_SET(CC->client_socket, &rfds);
375 retval = select( (CC->client_socket)+1,
376 &rfds, NULL, NULL, &tv);
377 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
381 rlen = read(CC->client_socket, &buf[len], bytes-len);
383 lprintf(2, "client_read() failed: %s\n",
393 * Read data from the client socket with default timeout.
394 * (This is implemented in terms of client_read_to() and could be
395 * justifiably moved out of sysdep.c)
397 int client_read(char *buf, int bytes)
399 return(client_read_to(buf, bytes, config.c_sleeping));
404 * client_gets() ... Get a LF-terminated line of text from the client.
405 * (This is implemented in terms of client_read() and could be
406 * justifiably moved out of sysdep.c)
408 int client_gets(char *buf)
412 /* Clear the buffer, and read one character at a time.
416 if (strlen(buf)<255) {
417 buf[strlen(buf) + 1] = 0;
418 retval = client_read(&buf[strlen(buf)], 1);
420 } while ( (buf[strlen(buf)-1] != 10) && (retval==1) );
422 /* Strip the trailing newline.
424 if (strlen(buf) > 0) buf[strlen(buf)-1] = 0;
431 * The system-dependent part of master_cleanup() - close the master socket.
433 void sysdep_master_cleanup(void) {
434 lprintf(7, "Closing master socket %d\n", msock);
439 * Cleanup routine to be called when one thread is shutting down.
441 void cleanup(int exit_code)
443 /* Terminate the thread.
444 * Its cleanup handler will call cleanup_stuff()
446 lprintf(7, "Calling pthread_exit()\n");
451 * Terminate another session.
453 void kill_session(int session_to_kill) {
454 struct CitContext *ptr;
456 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
457 if (ptr->cs_pid == session_to_kill) {
458 pthread_cancel(ptr->mythread);
465 * The system-dependent wrapper around the main context loop.
467 void sd_context_loop(struct CitContext *con) {
468 pthread_cleanup_push(*cleanup_stuff, NULL);
470 pthread_cleanup_pop(0);
475 * Start running as a daemon. Only close stdio if do_close_stdio is set.
477 void start_daemon(int do_close_stdio) {
478 if (do_close_stdio) {
483 signal(SIGHUP,SIG_IGN);
484 signal(SIGINT,SIG_IGN);
485 signal(SIGQUIT,SIG_IGN);
486 if (fork()!=0) exit(0);
492 * Tie in to the 'netsetup' program.
494 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
496 void cmd_nset(char *cmdbuf)
503 char netsetup_args[3][256];
505 if (CC->usersupp.axlevel < 6) {
506 cprintf("%d Higher access required.\n",
507 ERROR + HIGHER_ACCESS_REQUIRED);
511 for (a=1; a<=3; ++a) {
512 if (num_parms(cmdbuf) >= a) {
513 extract(netsetup_args[a-1], cmdbuf, a-1);
514 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
515 if (netsetup_args[a-1][b] == 34) {
516 netsetup_args[a-1][b] = '_';
521 netsetup_args[a-1][0] = 0;
525 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
526 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
527 netsetup = popen(fbuf, "r");
528 if (netsetup == NULL) {
529 cprintf("%d %s\n", ERROR, strerror(errno));
534 while (ch = getc(netsetup), (ch > 0)) {
535 fbuf[strlen(fbuf)+1] = 0;
536 fbuf[strlen(fbuf)] = ch;
539 retcode = pclose(netsetup);
542 for (a=0; a<strlen(fbuf); ++a) {
543 if (fbuf[a] < 32) fbuf[a] = 32;
546 cprintf("%d %s\n", ERROR, fbuf);
550 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
552 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
559 * Generic routine to convert a login name to a full name (gecos)
560 * Returns nonzero if a conversion took place
562 int convert_login(char NameToConvert[]) {
566 pw = getpwnam(NameToConvert);
571 strcpy(NameToConvert, pw->pw_gecos);
572 for (a=0; a<strlen(NameToConvert); ++a) {
573 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
585 * Here's where it all begins.
587 int main(int argc, char **argv)
589 struct sockaddr_in fsin; /* Data for master socket */
590 int alen; /* Data for master socket */
591 int ssock; /* Descriptor for master socket */
592 THREAD SessThread; /* Thread descriptor */
593 pthread_attr_t attr; /* Thread attributes */
594 struct CitContext *con; /* Temporary context pointer */
595 char tracefile[128]; /* Name of file to log traces to */
596 int a, i; /* General-purpose variables */
599 /* specify default port name and trace file */
600 strcpy(tracefile, "");
602 /* parse command-line arguments */
603 for (a=1; a<argc; ++a) {
605 /* -t specifies where to log trace messages to */
606 if (!strncmp(argv[a], "-t", 2)) {
607 strcpy(tracefile, argv[a]);
608 strcpy(tracefile, &tracefile[2]);
609 freopen(tracefile, "r", stdin);
610 freopen(tracefile, "w", stdout);
611 freopen(tracefile, "w", stderr);
614 /* run in the background if -d was specified */
615 else if (!strcmp(argv[a], "-d")) {
616 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
619 /* -x specifies the desired logging level */
620 else if (!strncmp(argv[a], "-x", 2)) {
621 strcpy(convbuf, argv[a]);
622 verbosity = atoi(&convbuf[2]);
625 else if (!strncmp(argv[a], "-h", 2)) {
626 strcpy(convbuf, argv[a]);
627 strcpy(bbs_home_directory, &convbuf[2]);
631 /* any other parameter makes it crash and burn */
633 lprintf(1, "citserver: usage: ");
634 lprintf(1, "citserver [-tTraceFile]");
635 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
641 /* Tell 'em who's in da house */
642 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
643 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
644 lprintf(1, "All rights reserved.\n\n");
648 openlog("citserver",LOG_PID,LOG_USER);
650 /* Load site-specific parameters */
651 lprintf(7, "Loading citadel.config\n");
655 /* Databases must be opened *after* config is loaded, otherwise we might
656 * end up working in the wrong directory.
658 lprintf(7, "Opening databases\n");
661 lprintf(7, "Checking floor reference counts\n");
665 * Bind the server to our favourite port.
666 * There is no need to check for errors, because ig_tcp_server()
667 * exits if it doesn't succeed.
669 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
670 msock = ig_tcp_server(config.c_port_number, 5);
671 lprintf(7, "Listening on socket %d\n", msock);
674 * Now that we've bound the socket, change to the BBS user id
675 lprintf(7, "Changing uid to %d\n", BBSUID);
676 if (setuid(BBSUID) != 0) {
677 lprintf(3, "setuid() failed: %s", strerror(errno));
682 * Endless loop. Listen on the master socket. When a connection
683 * comes in, create a socket, a context, and a thread.
686 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
688 lprintf(2, "citserver: accept() failed: %s\n",
692 lprintf(7, "citserver: Client socket %d\n", ssock);
693 lprintf(9, "creating context\n");
694 con = CreateNewContext();
695 con->client_socket = ssock;
697 /* Set the SO_REUSEADDR socket option */
698 lprintf(9, "setting socket options\n");
700 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
703 /* set attributes for the new thread */
704 lprintf(9, "setting thread attributes\n");
705 pthread_attr_init(&attr);
706 pthread_attr_setdetachstate(&attr,
707 PTHREAD_CREATE_DETACHED);
709 /* now create the thread */
710 lprintf(9, "creating thread\n");
711 if (pthread_create(&SessThread, &attr, (void *)sd_context_loop,
714 "citserver: can't create thread: %s\n",
719 * (defunct -- now done at thread creation time)
720 * if (pthread_detach(&SessThread) != 0) {
722 * "citserver: can't detach thread: %s\n",
726 lprintf(9, "done!\n");