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, ...) {
70 if (loglevel <= verbosity) {
71 va_start(arg_ptr, format);
72 rc = vsprintf(buf, format, arg_ptr);
75 fprintf(stderr, "%s", buf);
83 * Some initialization stuff...
85 void init_sysdep(void) {
88 /* Set up a bunch of semaphores to be used for critical sections */
89 for (a=0; a<MAX_SEMAPHORES; ++a) {
90 pthread_mutex_init(&Critters[a], NULL);
94 * Set up a place to put thred-specific data.
95 * We only need a single pointer per thread - it points to the
96 * thread's CitContext structure in the ContextList linked list.
98 if (pthread_key_create(&MyConKey, NULL) != 0) {
99 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
103 * The action for unexpected signals and exceptions should be to
104 * call master_cleanup() to gracefully shut down the server.
106 signal(SIGINT, (void(*)(int))master_cleanup);
107 signal(SIGQUIT, (void(*)(int))master_cleanup);
108 signal(SIGHUP, (void(*)(int))master_cleanup);
109 signal(SIGTERM, (void(*)(int))master_cleanup);
114 * Obtain a semaphore lock to begin a critical section.
116 void begin_critical_section(int which_one)
120 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
122 /* Don't get interrupted during the critical section */
123 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
125 /* Obtain a semaphore */
126 pthread_mutex_lock(&Critters[which_one]);
131 * Release a semaphore lock to end a critical section.
133 void end_critical_section(int which_one)
137 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
139 /* Let go of the semaphore */
140 pthread_mutex_unlock(&Critters[which_one]);
142 /* If a cancel was sent during the critical section, do it now.
143 * Then re-enable thread cancellation.
145 pthread_testcancel();
146 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
147 pthread_testcancel();
154 * This is a generic function to set up a master socket for listening on
155 * a TCP port. The server shuts down if the bind fails.
157 int ig_tcp_server(int port_number, int queue_len)
159 struct sockaddr_in sin;
162 memset(&sin, 0, sizeof(sin));
163 sin.sin_family = AF_INET;
164 sin.sin_addr.s_addr = INADDR_ANY;
166 if (port_number == 0) {
167 lprintf(1, "citserver: No port number specified. Run setup again.\n");
171 sin.sin_port = htons((u_short)port_number);
173 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
175 lprintf(1, "citserver: Can't create a socket: %s\n",
180 /* Set the SO_REUSEADDR socket option, because it makes sense. */
182 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
184 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
185 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
189 if (listen(s, queue_len) < 0) {
190 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
199 * Return a pointer to a thread's own CitContext structure (old)
200 * NOTE: this version of MyContext() is commented out because it is no longer
201 * in use. It was written before I discovered TSD keys. This
202 * version pounds through the context list until it finds the one matching
203 * the currently running thread. It remains here, commented out, in case it
204 * is needed for future ports to threading libraries which have the equivalent
205 * of pthread_self() but not pthread_key_create() and its ilk.
207 * struct CitContext *MyContext() {
208 * struct CitContext *ptr;
211 * me = pthread_self();
212 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
213 * if (ptr->mythread == me) return(ptr);
220 * Return a pointer to a thread's own CitContext structure (new)
222 struct CitContext *MyContext(void) {
223 struct CitContext *retCC;
224 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
225 if (retCC == NULL) retCC = &masterCC;
231 * Wedge our way into the context list.
233 struct CitContext *CreateNewContext(void) {
234 struct CitContext *me;
236 lprintf(9, "CreateNewContext: calling malloc()\n");
237 me = (struct CitContext *) malloc(sizeof(struct CitContext));
239 lprintf(1, "citserver: can't allocate memory!!\n");
242 memset(me, 0, sizeof(struct CitContext));
244 begin_critical_section(S_SESSION_TABLE);
245 me->next = ContextList;
247 end_critical_section(S_SESSION_TABLE);
252 * Add a thread's thread ID to the context
254 void InitMyContext(struct CitContext *con)
258 con->mythread = pthread_self();
259 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
260 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
261 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
262 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
268 * Remove a context from the context list.
270 void RemoveContext(struct CitContext *con)
272 struct CitContext *ptr;
274 lprintf(7, "Starting RemoveContext()\n");
275 lprintf(9, "session count before RemoveContext is %d\n", session_count());
277 lprintf(7, "WARNING: RemoveContext() called with null!\n");
281 begin_critical_section(S_SESSION_TABLE);
282 lprintf(7, "Closing socket %d\n", con->client_socket);
283 close(con->client_socket);
285 if (ContextList==con) {
286 ContextList = ContextList->next;
289 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
290 if (ptr->next == con) {
291 ptr->next = ptr->next->next;
298 lprintf(9, "session count after RemoveContext is %d\n", session_count());
300 lprintf(7, "Done with RemoveContext\n");
301 end_critical_section(S_SESSION_TABLE);
306 * Return the number of sessions currently running.
307 * (This should probably be moved out of sysdep.c)
309 int session_count(void) {
310 struct CitContext *ptr;
313 lprintf(9, "session_count() starting\n");
314 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
316 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
319 lprintf(9, "session_count() finishing\n");
325 * client_write() ... Send binary data to the client.
327 void client_write(char *buf, int nbytes)
329 int bytes_written = 0;
331 while (bytes_written < nbytes) {
332 retval = write(CC->client_socket, &buf[bytes_written],
333 nbytes - bytes_written);
335 lprintf(2, "client_write() failed: %s\n",
339 bytes_written = bytes_written + retval;
345 * cprintf() ... Send formatted printable data to the client. It is
346 * implemented in terms of client_write() but remains in
347 * sysdep.c in case we port to somewhere without va_args...
349 void cprintf(const char *format, ...) {
353 va_start(arg_ptr, format);
354 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
355 buf[sizeof buf - 2] = '\n';
356 client_write(buf, strlen(buf));
362 * Read data from the client socket.
364 * 1 Requested number of bytes has been read.
365 * 0 Request timed out.
366 * If the socket breaks, the session is immediately terminated.
368 int client_read_to(char *buf, int bytes, int timeout)
378 FD_SET(CC->client_socket, &rfds);
382 retval = select( (CC->client_socket)+1,
383 &rfds, NULL, NULL, &tv);
384 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
388 rlen = read(CC->client_socket, &buf[len], bytes-len);
390 lprintf(2, "client_read() failed: %s\n",
400 * Read data from the client socket with default timeout.
401 * (This is implemented in terms of client_read_to() and could be
402 * justifiably moved out of sysdep.c)
404 int client_read(char *buf, int bytes)
406 return(client_read_to(buf, bytes, config.c_sleeping));
411 * client_gets() ... Get a LF-terminated line of text from the client.
412 * (This is implemented in terms of client_read() and could be
413 * justifiably moved out of sysdep.c)
415 int client_gets(char *buf)
419 /* Read one character at a time.
422 retval = client_read(&buf[i], 1);
423 if (retval != 1 || buf[i] == '\n' || i == 255)
427 /* If we got a long line, discard characters until the newline.
430 while (buf[i] != '\n' && retval == 1)
431 retval = client_read(&buf[i], 1);
433 /* Strip the trailing newline.
442 * The system-dependent part of master_cleanup() - close the master socket.
444 void sysdep_master_cleanup(void) {
445 lprintf(7, "Closing master socket %d\n", msock);
450 * Cleanup routine to be called when one thread is shutting down.
452 void cleanup(int exit_code)
454 /* Terminate the thread.
455 * Its cleanup handler will call cleanup_stuff()
457 lprintf(7, "Calling pthread_exit()\n");
462 * Terminate another session.
464 void kill_session(int session_to_kill) {
465 struct CitContext *ptr;
467 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
468 if (ptr->cs_pid == session_to_kill) {
469 pthread_cancel(ptr->mythread);
476 * The system-dependent wrapper around the main context loop.
478 void *sd_context_loop(struct CitContext *con) {
479 pthread_cleanup_push(*cleanup_stuff, NULL);
481 pthread_cleanup_pop(0);
487 * Start running as a daemon. Only close stdio if do_close_stdio is set.
489 void start_daemon(int do_close_stdio) {
490 if (do_close_stdio) {
495 signal(SIGHUP,SIG_IGN);
496 signal(SIGINT,SIG_IGN);
497 signal(SIGQUIT,SIG_IGN);
498 if (fork()!=0) exit(0);
504 * Tie in to the 'netsetup' program.
506 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
508 void cmd_nset(char *cmdbuf)
515 char netsetup_args[3][256];
517 if (CC->usersupp.axlevel < 6) {
518 cprintf("%d Higher access required.\n",
519 ERROR + HIGHER_ACCESS_REQUIRED);
523 for (a=1; a<=3; ++a) {
524 if (num_parms(cmdbuf) >= a) {
525 extract(netsetup_args[a-1], cmdbuf, a-1);
526 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
527 if (netsetup_args[a-1][b] == 34) {
528 netsetup_args[a-1][b] = '_';
533 netsetup_args[a-1][0] = 0;
537 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
538 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
539 netsetup = popen(fbuf, "r");
540 if (netsetup == NULL) {
541 cprintf("%d %s\n", ERROR, strerror(errno));
546 while (ch = getc(netsetup), (ch > 0)) {
547 fbuf[strlen(fbuf)+1] = 0;
548 fbuf[strlen(fbuf)] = ch;
551 retcode = pclose(netsetup);
554 for (a=0; a<strlen(fbuf); ++a) {
555 if (fbuf[a] < 32) fbuf[a] = 32;
558 cprintf("%d %s\n", ERROR, fbuf);
562 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
564 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
571 * Generic routine to convert a login name to a full name (gecos)
572 * Returns nonzero if a conversion took place
574 int convert_login(char NameToConvert[]) {
578 pw = getpwnam(NameToConvert);
583 strcpy(NameToConvert, pw->pw_gecos);
584 for (a=0; a<strlen(NameToConvert); ++a) {
585 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
597 * Here's where it all begins.
599 int main(int argc, char **argv)
601 struct sockaddr_in fsin; /* Data for master socket */
602 int alen; /* Data for master socket */
603 int ssock; /* Descriptor for master socket */
604 THREAD SessThread; /* Thread descriptor */
605 pthread_attr_t attr; /* Thread attributes */
606 struct CitContext *con; /* Temporary context pointer */
607 char tracefile[128]; /* Name of file to log traces to */
608 int a, i; /* General-purpose variables */
612 /* specify default port name and trace file */
613 strcpy(tracefile, "");
615 /* parse command-line arguments */
616 for (a=1; a<argc; ++a) {
618 /* -t specifies where to log trace messages to */
619 if (!strncmp(argv[a], "-t", 2)) {
620 strcpy(tracefile, argv[a]);
621 strcpy(tracefile, &tracefile[2]);
622 freopen(tracefile, "r", stdin);
623 freopen(tracefile, "w", stdout);
624 freopen(tracefile, "w", stderr);
627 /* run in the background if -d was specified */
628 else if (!strcmp(argv[a], "-d")) {
629 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
632 /* -x specifies the desired logging level */
633 else if (!strncmp(argv[a], "-x", 2)) {
634 strcpy(convbuf, argv[a]);
635 verbosity = atoi(&convbuf[2]);
638 else if (!strncmp(argv[a], "-h", 2)) {
639 strcpy(convbuf, argv[a]);
640 strcpy(bbs_home_directory, &convbuf[2]);
644 /* any other parameter makes it crash and burn */
646 lprintf(1, "citserver: usage: ");
647 lprintf(1, "citserver [-tTraceFile]");
648 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
654 /* Tell 'em who's in da house */
655 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
656 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
657 lprintf(1, "All rights reserved.\n\n");
661 openlog("citserver",LOG_PID,LOG_USER);
662 lprintf(1, "Initting modules...\n");
663 snprintf(modpath, 128, "%s/modules", BBSDIR);
664 DLoader_Init(modpath);
665 lprintf(1, "Modules done initializing...\n");
667 lprintf(1, "First symtab item:");
668 lprintf(1, my_symtab->fcn_name);
671 /* Load site-specific parameters */
672 lprintf(7, "Loading citadel.config\n");
675 /* Do non system dependent startup functions */
679 * Bind the server to our favourite port.
680 * There is no need to check for errors, because ig_tcp_server()
681 * exits if it doesn't succeed.
683 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
684 msock = ig_tcp_server(config.c_port_number, 5);
685 lprintf(7, "Listening on socket %d\n", msock);
688 * Now that we've bound the socket, change to the BBS user id
689 lprintf(7, "Changing uid to %d\n", BBSUID);
690 if (setuid(BBSUID) != 0) {
691 lprintf(3, "setuid() failed: %s", strerror(errno));
696 * Endless loop. Listen on the master socket. When a connection
697 * comes in, create a socket, a context, and a thread.
700 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
702 lprintf(2, "citserver: accept() failed: %s\n",
706 lprintf(7, "citserver: Client socket %d\n", ssock);
707 lprintf(9, "creating context\n");
708 con = CreateNewContext();
709 con->client_socket = ssock;
711 /* Set the SO_REUSEADDR socket option */
712 lprintf(9, "setting socket options\n");
714 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
717 /* set attributes for the new thread */
718 lprintf(9, "setting thread attributes\n");
719 pthread_attr_init(&attr);
720 pthread_attr_setdetachstate(&attr,
721 PTHREAD_CREATE_DETACHED);
723 /* now create the thread */
724 lprintf(9, "creating thread\n");
725 if (pthread_create(&SessThread, &attr,
726 (void* (*)(void*)) sd_context_loop,
730 "citserver: can't create thread: %s\n",
735 * (defunct -- now done at thread creation time)
736 * if (pthread_detach(&SessThread) != 0) {
738 * "citserver: can't detach thread: %s\n",
742 lprintf(9, "done!\n");