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>
25 #include <netinet/in.h>
35 #include "sysdep_decls.h"
36 #include "citserver.h"
40 #include "housekeeping.h"
41 #include "dynloader.h"
43 #ifdef HAVE_SYS_SELECT_H
44 #include <sys/select.h>
51 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
52 pthread_key_t MyConKey; /* TSD key for MyContext() */
54 int msock; /* master listening socket */
55 int verbosity = 3; /* Logging level */
57 struct CitContext masterCC;
61 * lprintf() ... Write logging information
63 void lprintf(int loglevel, const char *format, ...) {
68 if (loglevel <= verbosity) {
69 va_start(arg_ptr, format);
70 rc = vsprintf(buf, format, arg_ptr);
73 fprintf(stderr, "%s", buf);
81 * Some initialization stuff...
83 void init_sysdep(void) {
86 /* Set up a bunch of semaphores to be used for critical sections */
87 for (a=0; a<MAX_SEMAPHORES; ++a) {
88 pthread_mutex_init(&Critters[a], NULL);
92 * Set up a place to put thred-specific data.
93 * We only need a single pointer per thread - it points to the
94 * thread's CitContext structure in the ContextList linked list.
96 if (pthread_key_create(&MyConKey, NULL) != 0) {
97 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
101 * The action for unexpected signals and exceptions should be to
102 * call master_cleanup() to gracefully shut down the server.
104 signal(SIGINT, (void(*)(int))master_cleanup);
105 signal(SIGQUIT, (void(*)(int))master_cleanup);
106 signal(SIGHUP, (void(*)(int))master_cleanup);
107 signal(SIGTERM, (void(*)(int))master_cleanup);
112 * Obtain a semaphore lock to begin a critical section.
114 void begin_critical_section(int which_one)
118 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
120 /* Don't get interrupted during the critical section */
121 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
123 /* Obtain a semaphore */
124 pthread_mutex_lock(&Critters[which_one]);
129 * Release a semaphore lock to end a critical section.
131 void end_critical_section(int which_one)
135 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
137 /* Let go of the semaphore */
138 pthread_mutex_unlock(&Critters[which_one]);
140 /* If a cancel was sent during the critical section, do it now.
141 * Then re-enable thread cancellation.
143 pthread_testcancel();
144 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
145 pthread_testcancel();
152 * This is a generic function to set up a master socket for listening on
153 * a TCP port. The server shuts down if the bind fails.
155 int ig_tcp_server(int port_number, int queue_len)
157 struct sockaddr_in sin;
160 memset(&sin, 0, sizeof(sin));
161 sin.sin_family = AF_INET;
162 sin.sin_addr.s_addr = INADDR_ANY;
164 if (port_number == 0) {
165 lprintf(1, "citserver: No port number specified. Run setup again.\n");
169 sin.sin_port = htons((u_short)port_number);
171 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
173 lprintf(1, "citserver: Can't create a socket: %s\n",
178 /* Set the SO_REUSEADDR socket option, because it makes sense. */
180 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
182 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
183 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
187 if (listen(s, queue_len) < 0) {
188 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
197 * Return a pointer to a thread's own CitContext structure (old)
198 * NOTE: this version of MyContext() is commented out because it is no longer
199 * in use. It was written before I discovered TSD keys. This
200 * version pounds through the context list until it finds the one matching
201 * the currently running thread. It remains here, commented out, in case it
202 * is needed for future ports to threading libraries which have the equivalent
203 * of pthread_self() but not pthread_key_create() and its ilk.
205 * struct CitContext *MyContext() {
206 * struct CitContext *ptr;
209 * me = pthread_self();
210 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
211 * if (ptr->mythread == me) return(ptr);
218 * Return a pointer to a thread's own CitContext structure (new)
220 struct CitContext *MyContext(void) {
221 struct CitContext *retCC;
222 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
223 if (retCC == NULL) retCC = &masterCC;
229 * Wedge our way into the context list.
231 struct CitContext *CreateNewContext(void) {
232 struct CitContext *me;
234 lprintf(9, "CreateNewContext: calling malloc()\n");
235 me = (struct CitContext *) malloc(sizeof(struct CitContext));
237 lprintf(1, "citserver: can't allocate memory!!\n");
240 memset(me, 0, sizeof(struct CitContext));
242 begin_critical_section(S_SESSION_TABLE);
243 me->next = ContextList;
245 end_critical_section(S_SESSION_TABLE);
250 * Add a thread's thread ID to the context
252 void InitMyContext(struct CitContext *con)
256 con->mythread = pthread_self();
257 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
258 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
259 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
260 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
266 * Remove a context from the context list.
268 void RemoveContext(struct CitContext *con)
270 struct CitContext *ptr;
272 lprintf(7, "Starting RemoveContext()\n");
273 lprintf(9, "session count before RemoveContext is %d\n", session_count());
275 lprintf(7, "WARNING: RemoveContext() called with null!\n");
279 begin_critical_section(S_SESSION_TABLE);
280 lprintf(7, "Closing socket %d\n", con->client_socket);
281 close(con->client_socket);
283 if (ContextList==con) {
284 ContextList = ContextList->next;
287 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
288 if (ptr->next == con) {
289 ptr->next = ptr->next->next;
296 lprintf(9, "session count after RemoveContext is %d\n", session_count());
298 lprintf(7, "Done with RemoveContext\n");
299 end_critical_section(S_SESSION_TABLE);
304 * Return the number of sessions currently running.
305 * (This should probably be moved out of sysdep.c)
307 int session_count(void) {
308 struct CitContext *ptr;
311 lprintf(9, "session_count() starting\n");
312 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
314 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
317 lprintf(9, "session_count() finishing\n");
323 * client_write() ... Send binary data to the client.
325 void client_write(char *buf, int nbytes)
327 int bytes_written = 0;
329 while (bytes_written < nbytes) {
330 retval = write(CC->client_socket, &buf[bytes_written],
331 nbytes - bytes_written);
333 lprintf(2, "client_write() failed: %s\n",
337 bytes_written = bytes_written + retval;
343 * cprintf() ... Send formatted printable data to the client. It is
344 * implemented in terms of client_write() but remains in
345 * sysdep.c in case we port to somewhere without va_args...
347 void cprintf(const char *format, ...) {
351 va_start(arg_ptr, format);
352 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
353 buf[sizeof buf - 2] = '\n';
354 client_write(buf, strlen(buf));
360 * Read data from the client socket.
362 * 1 Requested number of bytes has been read.
363 * 0 Request timed out.
364 * If the socket breaks, the session is immediately terminated.
366 int client_read_to(char *buf, int bytes, int timeout)
376 FD_SET(CC->client_socket, &rfds);
380 retval = select( (CC->client_socket)+1,
381 &rfds, NULL, NULL, &tv);
382 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
386 rlen = read(CC->client_socket, &buf[len], bytes-len);
388 lprintf(2, "client_read() failed: %s\n",
398 * Read data from the client socket with default timeout.
399 * (This is implemented in terms of client_read_to() and could be
400 * justifiably moved out of sysdep.c)
402 int client_read(char *buf, int bytes)
404 return(client_read_to(buf, bytes, config.c_sleeping));
409 * client_gets() ... Get a LF-terminated line of text from the client.
410 * (This is implemented in terms of client_read() and could be
411 * justifiably moved out of sysdep.c)
413 int client_gets(char *buf)
417 /* Read one character at a time.
420 retval = client_read(&buf[i], 1);
421 if (retval != 1 || buf[i] == '\n' || i == 255)
425 /* If we got a long line, discard characters until the newline.
428 while (buf[i] != '\n' && retval == 1)
429 retval = client_read(&buf[i], 1);
431 /* Strip the trailing newline.
440 * The system-dependent part of master_cleanup() - close the master socket.
442 void sysdep_master_cleanup(void) {
443 lprintf(7, "Closing master socket %d\n", msock);
448 * Cleanup routine to be called when one thread is shutting down.
450 void cleanup(int exit_code)
452 /* Terminate the thread.
453 * Its cleanup handler will call cleanup_stuff()
455 lprintf(7, "Calling pthread_exit()\n");
460 * Terminate another session.
462 void kill_session(int session_to_kill) {
463 struct CitContext *ptr;
465 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
466 if (ptr->cs_pid == session_to_kill) {
467 pthread_cancel(ptr->mythread);
474 * The system-dependent wrapper around the main context loop.
476 void *sd_context_loop(struct CitContext *con) {
477 pthread_cleanup_push(*cleanup_stuff, NULL);
479 pthread_cleanup_pop(0);
485 * Start running as a daemon. Only close stdio if do_close_stdio is set.
487 void start_daemon(int do_close_stdio) {
488 if (do_close_stdio) {
493 signal(SIGHUP,SIG_IGN);
494 signal(SIGINT,SIG_IGN);
495 signal(SIGQUIT,SIG_IGN);
496 if (fork()!=0) exit(0);
502 * Tie in to the 'netsetup' program.
504 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
506 void cmd_nset(char *cmdbuf)
513 char netsetup_args[3][256];
515 if (CC->usersupp.axlevel < 6) {
516 cprintf("%d Higher access required.\n",
517 ERROR + HIGHER_ACCESS_REQUIRED);
521 for (a=1; a<=3; ++a) {
522 if (num_parms(cmdbuf) >= a) {
523 extract(netsetup_args[a-1], cmdbuf, a-1);
524 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
525 if (netsetup_args[a-1][b] == 34) {
526 netsetup_args[a-1][b] = '_';
531 netsetup_args[a-1][0] = 0;
535 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
536 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
537 netsetup = popen(fbuf, "r");
538 if (netsetup == NULL) {
539 cprintf("%d %s\n", ERROR, strerror(errno));
544 while (ch = getc(netsetup), (ch > 0)) {
545 fbuf[strlen(fbuf)+1] = 0;
546 fbuf[strlen(fbuf)] = ch;
549 retcode = pclose(netsetup);
552 for (a=0; a<strlen(fbuf); ++a) {
553 if (fbuf[a] < 32) fbuf[a] = 32;
556 cprintf("%d %s\n", ERROR, fbuf);
560 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
562 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
569 * Generic routine to convert a login name to a full name (gecos)
570 * Returns nonzero if a conversion took place
572 int convert_login(char NameToConvert[]) {
576 pw = getpwnam(NameToConvert);
581 strcpy(NameToConvert, pw->pw_gecos);
582 for (a=0; a<strlen(NameToConvert); ++a) {
583 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
595 * Here's where it all begins.
597 int main(int argc, char **argv)
599 struct sockaddr_in fsin; /* Data for master socket */
600 int alen; /* Data for master socket */
601 int ssock; /* Descriptor for master socket */
602 THREAD SessThread; /* Thread descriptor */
603 pthread_attr_t attr; /* Thread attributes */
604 struct CitContext *con; /* Temporary context pointer */
605 char tracefile[128]; /* Name of file to log traces to */
606 int a, i; /* General-purpose variables */
610 /* specify default port name and trace file */
611 strcpy(tracefile, "");
613 /* parse command-line arguments */
614 for (a=1; a<argc; ++a) {
616 /* -t specifies where to log trace messages to */
617 if (!strncmp(argv[a], "-t", 2)) {
618 strcpy(tracefile, argv[a]);
619 strcpy(tracefile, &tracefile[2]);
620 freopen(tracefile, "r", stdin);
621 freopen(tracefile, "w", stdout);
622 freopen(tracefile, "w", stderr);
625 /* run in the background if -d was specified */
626 else if (!strcmp(argv[a], "-d")) {
627 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
630 /* -x specifies the desired logging level */
631 else if (!strncmp(argv[a], "-x", 2)) {
632 strcpy(convbuf, argv[a]);
633 verbosity = atoi(&convbuf[2]);
636 else if (!strncmp(argv[a], "-h", 2)) {
637 strcpy(convbuf, argv[a]);
638 strcpy(bbs_home_directory, &convbuf[2]);
642 /* any other parameter makes it crash and burn */
644 lprintf(1, "citserver: usage: ");
645 lprintf(1, "citserver [-tTraceFile]");
646 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
652 /* Tell 'em who's in da house */
653 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
654 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
655 lprintf(1, "All rights reserved.\n\n");
659 openlog("citserver",LOG_PID,LOG_USER);
660 lprintf(1, "Initting modules...\n");
661 snprintf(modpath, 128, "%s/modules", BBSDIR);
662 DLoader_Init(modpath);
663 lprintf(1, "Modules done initializing...\n");
665 lprintf(1, "First symtab item:");
666 lprintf(1, my_symtab->fcn_name);
669 /* Load site-specific parameters */
670 lprintf(7, "Loading citadel.config\n");
673 /* Do non system dependent startup functions */
677 * Bind the server to our favourite port.
678 * There is no need to check for errors, because ig_tcp_server()
679 * exits if it doesn't succeed.
681 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
682 msock = ig_tcp_server(config.c_port_number, 5);
683 lprintf(7, "Listening on socket %d\n", msock);
686 * Now that we've bound the socket, change to the BBS user id
687 lprintf(7, "Changing uid to %d\n", BBSUID);
688 if (setuid(BBSUID) != 0) {
689 lprintf(3, "setuid() failed: %s", strerror(errno));
694 * Endless loop. Listen on the master socket. When a connection
695 * comes in, create a socket, a context, and a thread.
698 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
700 lprintf(2, "citserver: accept() failed: %s\n",
704 lprintf(7, "citserver: Client socket %d\n", ssock);
705 lprintf(9, "creating context\n");
706 con = CreateNewContext();
707 con->client_socket = ssock;
709 /* Set the SO_REUSEADDR socket option */
710 lprintf(9, "setting socket options\n");
712 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
715 /* set attributes for the new thread */
716 lprintf(9, "setting thread attributes\n");
717 pthread_attr_init(&attr);
718 pthread_attr_setdetachstate(&attr,
719 PTHREAD_CREATE_DETACHED);
721 /* now create the thread */
722 lprintf(9, "creating thread\n");
723 if (pthread_create(&SessThread, &attr,
724 (void* (*)(void*)) sd_context_loop,
728 "citserver: can't create thread: %s\n",
733 * (defunct -- now done at thread creation time)
734 * if (pthread_detach(&SessThread) != 0) {
736 * "citserver: can't detach thread: %s\n",
740 lprintf(9, "done!\n");