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.
22 #include <sys/types.h>
24 #include <sys/socket.h>
27 #include <netinet/in.h>
37 #include "sysdep_decls.h"
38 #include "citserver.h"
42 #include "housekeeping.h"
43 #include "dynloader.h"
45 #ifdef HAVE_SYS_SELECT_H
46 #include <sys/select.h>
53 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
54 pthread_key_t MyConKey; /* TSD key for MyContext() */
56 int msock; /* master listening socket */
57 int verbosity = 3; /* Logging level */
59 struct CitContext masterCC;
63 * lprintf() ... Write logging information
65 void lprintf(int loglevel, const char *format, ...) {
68 if (loglevel <= verbosity) {
69 va_start(arg_ptr, format);
70 vfprintf(stderr, format, arg_ptr);
79 * Some initialization stuff...
81 void init_sysdep(void) {
84 /* Set up a bunch of semaphores to be used for critical sections */
85 for (a=0; a<MAX_SEMAPHORES; ++a) {
86 pthread_mutex_init(&Critters[a], NULL);
90 * Set up a place to put thread-specific data.
91 * We only need a single pointer per thread - it points to the
92 * thread's CitContext structure in the ContextList linked list.
94 if (pthread_key_create(&MyConKey, NULL) != 0) {
95 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
99 * The action for unexpected signals and exceptions should be to
100 * call master_cleanup() to gracefully shut down the server.
102 signal(SIGINT, (void(*)(int))master_cleanup);
103 signal(SIGQUIT, (void(*)(int))master_cleanup);
104 signal(SIGHUP, (void(*)(int))master_cleanup);
105 signal(SIGTERM, (void(*)(int))master_cleanup);
110 * Obtain a semaphore lock to begin a critical section.
112 void begin_critical_section(int which_one)
116 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
118 /* Don't get interrupted during the critical section */
119 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
121 /* Obtain a semaphore */
122 pthread_mutex_lock(&Critters[which_one]);
127 * Release a semaphore lock to end a critical section.
129 void end_critical_section(int which_one)
133 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
135 /* Let go of the semaphore */
136 pthread_mutex_unlock(&Critters[which_one]);
138 /* If a cancel was sent during the critical section, do it now.
139 * Then re-enable thread cancellation.
141 pthread_testcancel();
142 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
143 pthread_testcancel();
150 * This is a generic function to set up a master socket for listening on
151 * a TCP port. The server shuts down if the bind fails.
153 int ig_tcp_server(int port_number, int queue_len)
155 struct sockaddr_in sin;
158 memset(&sin, 0, sizeof(sin));
159 sin.sin_family = AF_INET;
160 sin.sin_addr.s_addr = INADDR_ANY;
162 if (port_number == 0) {
164 "citserver: No port number specified. Run setup.\n");
168 sin.sin_port = htons((u_short)port_number);
170 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
172 lprintf(1, "citserver: Can't create a socket: %s\n",
177 /* Set the SO_REUSEADDR socket option, because it makes sense. */
179 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
181 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
182 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
186 if (listen(s, queue_len) < 0) {
187 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
196 * Return a pointer to a thread's own CitContext structure (old)
197 * NOTE: this version of MyContext() is commented out because it is no longer
198 * in use. It was written before I discovered TSD keys. This
199 * version pounds through the context list until it finds the one matching
200 * the currently running thread. It remains here, commented out, in case it
201 * is needed for future ports to threading libraries which have the equivalent
202 * of pthread_self() but not pthread_key_create() and its ilk.
204 * struct CitContext *MyContext() {
205 * struct CitContext *ptr;
208 * me = pthread_self();
209 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
210 * if (ptr->mythread == me) return(ptr);
217 * Return a pointer to a thread's own CitContext structure (new)
219 struct CitContext *MyContext(void) {
220 struct CitContext *retCC;
221 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
222 if (retCC == NULL) retCC = &masterCC;
228 * Wedge our way into the context list.
230 struct CitContext *CreateNewContext(void) {
231 struct CitContext *me;
233 lprintf(9, "CreateNewContext: calling malloc()\n");
234 me = (struct CitContext *) malloc(sizeof(struct CitContext));
236 lprintf(1, "citserver: can't allocate memory!!\n");
239 memset(me, 0, sizeof(struct CitContext));
241 begin_critical_section(S_SESSION_TABLE);
242 me->next = ContextList;
244 end_critical_section(S_SESSION_TABLE);
249 * Add a thread's thread ID to the context
251 void InitMyContext(struct CitContext *con)
255 con->mythread = pthread_self();
256 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
257 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
258 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
259 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
265 * Remove a context from the context list.
267 void RemoveContext(struct CitContext *con)
269 struct CitContext *ptr;
271 lprintf(7, "Starting RemoveContext()\n");
272 lprintf(9, "Session count before RemoveContext is %d\n",
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 lprintf(9, "Dereferencing session context\n");
284 if (ContextList==con) {
285 ContextList = ContextList->next;
288 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
289 if (ptr->next == con) {
290 ptr->next = con->next;
295 lprintf(9, "Freeing session context...\n");
297 lprintf(9, "...done.\n");
299 lprintf(9, "Session count after RemoveContext is %d\n",
302 lprintf(7, "Done with RemoveContext\n");
303 end_critical_section(S_SESSION_TABLE);
308 * Return the number of sessions currently running.
309 * (This should probably be moved out of sysdep.c)
311 int session_count(void) {
312 struct CitContext *ptr;
315 lprintf(9, "session_count() starting\n");
316 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
318 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
321 lprintf(9, "session_count() finishing\n");
327 * client_write() ... Send binary data to the client.
329 void client_write(char *buf, int nbytes)
331 int bytes_written = 0;
333 while (bytes_written < nbytes) {
334 retval = write(CC->client_socket, &buf[bytes_written],
335 nbytes - bytes_written);
337 lprintf(2, "client_write() failed: %s\n",
341 bytes_written = bytes_written + retval;
347 * cprintf() ... Send formatted printable data to the client. It is
348 * implemented in terms of client_write() but remains in
349 * sysdep.c in case we port to somewhere without va_args...
351 void cprintf(const char *format, ...) {
355 va_start(arg_ptr, format);
356 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
357 buf[sizeof buf - 2] = '\n';
358 client_write(buf, strlen(buf));
364 * Read data from the client socket.
366 * 1 Requested number of bytes has been read.
367 * 0 Request timed out.
368 * If the socket breaks, the session is immediately terminated.
370 int client_read_to(char *buf, int bytes, int timeout)
380 FD_SET(CC->client_socket, &rfds);
384 retval = select( (CC->client_socket)+1,
385 &rfds, NULL, NULL, &tv);
386 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
390 rlen = read(CC->client_socket, &buf[len], bytes-len);
392 lprintf(2, "client_read() failed: %s\n",
402 * Read data from the client socket with default timeout.
403 * (This is implemented in terms of client_read_to() and could be
404 * justifiably moved out of sysdep.c)
406 int client_read(char *buf, int bytes)
408 return(client_read_to(buf, bytes, config.c_sleeping));
413 * client_gets() ... Get a LF-terminated line of text from the client.
414 * (This is implemented in terms of client_read() and could be
415 * justifiably moved out of sysdep.c)
417 int client_gets(char *buf)
421 /* Read one character at a time.
424 retval = client_read(&buf[i], 1);
425 if (retval != 1 || buf[i] == '\n' || i == 255)
429 /* If we got a long line, discard characters until the newline.
432 while (buf[i] != '\n' && retval == 1)
433 retval = client_read(&buf[i], 1);
435 /* Strip the trailing newline.
444 * The system-dependent part of master_cleanup() - close the master socket.
446 void sysdep_master_cleanup(void) {
447 lprintf(7, "Closing master socket %d\n", msock);
452 * Cleanup routine to be called when one thread is shutting down.
454 void cleanup(int exit_code)
456 /* Terminate the thread.
457 * Its cleanup handler will call cleanup_stuff()
459 lprintf(7, "Calling pthread_exit()\n");
464 * Terminate another session.
466 void kill_session(int session_to_kill) {
467 struct CitContext *ptr;
469 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
470 if (ptr->cs_pid == session_to_kill) {
471 pthread_cancel(ptr->mythread);
478 * The system-dependent wrapper around the main context loop.
480 void *sd_context_loop(struct CitContext *con) {
481 pthread_cleanup_push(*cleanup_stuff, NULL);
483 pthread_cleanup_pop(0);
489 * Start running as a daemon. Only close stdio if do_close_stdio is set.
491 void start_daemon(int do_close_stdio) {
492 if (do_close_stdio) {
497 signal(SIGHUP,SIG_IGN);
498 signal(SIGINT,SIG_IGN);
499 signal(SIGQUIT,SIG_IGN);
500 if (fork()!=0) exit(0);
506 * Tie in to the 'netsetup' program.
508 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
510 void cmd_nset(char *cmdbuf)
517 char netsetup_args[3][256];
519 if (CC->usersupp.axlevel < 6) {
520 cprintf("%d Higher access required.\n",
521 ERROR + HIGHER_ACCESS_REQUIRED);
525 for (a=1; a<=3; ++a) {
526 if (num_parms(cmdbuf) >= a) {
527 extract(netsetup_args[a-1], cmdbuf, a-1);
528 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
529 if (netsetup_args[a-1][b] == 34) {
530 netsetup_args[a-1][b] = '_';
535 netsetup_args[a-1][0] = 0;
539 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
540 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
541 netsetup = popen(fbuf, "r");
542 if (netsetup == NULL) {
543 cprintf("%d %s\n", ERROR, strerror(errno));
548 while (ch = getc(netsetup), (ch > 0)) {
549 fbuf[strlen(fbuf)+1] = 0;
550 fbuf[strlen(fbuf)] = ch;
553 retcode = pclose(netsetup);
556 for (a=0; a<strlen(fbuf); ++a) {
557 if (fbuf[a] < 32) fbuf[a] = 32;
560 cprintf("%d %s\n", ERROR, fbuf);
564 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
566 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
573 * Generic routine to convert a login name to a full name (gecos)
574 * Returns nonzero if a conversion took place
576 int convert_login(char NameToConvert[]) {
580 pw = getpwnam(NameToConvert);
585 strcpy(NameToConvert, pw->pw_gecos);
586 for (a=0; a<strlen(NameToConvert); ++a) {
587 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
599 * Here's where it all begins.
601 int main(int argc, char **argv)
603 struct sockaddr_in fsin; /* Data for master socket */
604 int alen; /* Data for master socket */
605 int ssock; /* Descriptor for master socket */
606 THREAD SessThread; /* Thread descriptor */
607 pthread_attr_t attr; /* Thread attributes */
608 struct CitContext *con; /* Temporary context pointer */
609 char tracefile[128]; /* Name of file to log traces to */
610 int a, i; /* General-purpose variables */
614 /* specify default port name and trace file */
615 strcpy(tracefile, "");
617 /* parse command-line arguments */
618 for (a=1; a<argc; ++a) {
620 /* -t specifies where to log trace messages to */
621 if (!strncmp(argv[a], "-t", 2)) {
622 strcpy(tracefile, argv[a]);
623 strcpy(tracefile, &tracefile[2]);
624 freopen(tracefile, "r", stdin);
625 freopen(tracefile, "w", stdout);
626 freopen(tracefile, "w", stderr);
629 /* run in the background if -d was specified */
630 else if (!strcmp(argv[a], "-d")) {
631 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
634 /* -x specifies the desired logging level */
635 else if (!strncmp(argv[a], "-x", 2)) {
636 strcpy(convbuf, argv[a]);
637 verbosity = atoi(&convbuf[2]);
640 else if (!strncmp(argv[a], "-h", 2)) {
641 strcpy(convbuf, argv[a]);
642 strcpy(bbs_home_directory, &convbuf[2]);
646 /* any other parameter makes it crash and burn */
648 lprintf(1, "citserver: usage: ");
649 lprintf(1, "citserver [-tTraceFile]");
650 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
656 /* Tell 'em who's in da house */
657 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
658 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
659 lprintf(1, "All rights reserved.\n\n");
663 openlog("citserver",LOG_PID,LOG_USER);
664 lprintf(1, "Initting modules...\n");
665 snprintf(modpath, 128, "%s/modules", BBSDIR);
666 DLoader_Init(modpath);
667 lprintf(1, "Modules done initializing...\n");
669 lprintf(1, "First symtab item:");
670 lprintf(1, my_symtab->fcn_name);
673 /* Load site-specific parameters */
674 lprintf(7, "Loading citadel.config\n");
677 /* Do non system dependent startup functions */
681 * Bind the server to our favourite port.
682 * There is no need to check for errors, because ig_tcp_server()
683 * exits if it doesn't succeed.
685 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
686 msock = ig_tcp_server(config.c_port_number, 5);
687 lprintf(7, "Listening on socket %d\n", msock);
690 * Now that we've bound the socket, change to the BBS user id
691 lprintf(7, "Changing uid to %d\n", BBSUID);
692 if (setuid(BBSUID) != 0) {
693 lprintf(3, "setuid() failed: %s", strerror(errno));
698 * Endless loop. Listen on the master socket. When a connection
699 * comes in, create a socket, a context, and a thread.
702 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
704 lprintf(2, "citserver: accept() failed: %s\n",
708 lprintf(7, "citserver: Client socket %d\n", ssock);
709 lprintf(9, "creating context\n");
710 con = CreateNewContext();
711 con->client_socket = ssock;
713 /* Set the SO_REUSEADDR socket option */
714 lprintf(9, "setting socket options\n");
716 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
719 /* set attributes for the new thread */
720 lprintf(9, "setting thread attributes\n");
721 pthread_attr_init(&attr);
722 pthread_attr_setdetachstate(&attr,
723 PTHREAD_CREATE_DETACHED);
725 /* now create the thread */
726 lprintf(9, "creating thread\n");
727 if (pthread_create(&SessThread, &attr,
728 (void* (*)(void*)) sd_context_loop,
732 "citserver: can't create thread: %s\n",
737 * (defunct -- now done at thread creation time)
738 * if (pthread_detach(&SessThread) != 0) {
740 * "citserver: can't detach thread: %s\n",
744 lprintf(9, "done!\n");