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>
34 #include "sysdep_decls.h"
35 #include "citserver.h"
39 #include "housekeeping.h"
40 #include "dynloader.h"
43 #include <sys/select.h>
46 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
47 pthread_key_t MyConKey; /* TSD key for MyContext() */
49 int msock; /* master listening socket */
50 int verbosity = 3; /* Logging level */
52 struct CitContext masterCC;
56 * lprintf() ... Write logging information
58 void lprintf(int loglevel, const char *format, ...) {
63 if (loglevel <= verbosity) {
64 va_start(arg_ptr, format);
65 rc = vsprintf(buf, format, arg_ptr);
68 fprintf(stderr, "%s", buf);
76 * Some initialization stuff...
78 void init_sysdep(void) {
81 /* Set up a bunch of semaphores to be used for critical sections */
82 for (a=0; a<MAX_SEMAPHORES; ++a) {
83 pthread_mutex_init(&Critters[a], NULL);
87 * Set up a place to put thred-specific data.
88 * We only need a single pointer per thread - it points to the
89 * thread's CitContext structure in the ContextList linked list.
91 if (pthread_key_create(&MyConKey, NULL) != 0) {
92 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
96 * The action for unexpected signals and exceptions should be to
97 * call master_cleanup() to gracefully shut down the server.
99 signal(SIGINT, (void(*)(int))master_cleanup);
100 signal(SIGQUIT, (void(*)(int))master_cleanup);
101 signal(SIGHUP, (void(*)(int))master_cleanup);
102 signal(SIGTERM, (void(*)(int))master_cleanup);
107 * Obtain a semaphore lock to begin a critical section.
109 void begin_critical_section(int which_one)
113 lprintf(8, "begin_critical_section(%d)\n", 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]);
124 * Release a semaphore lock to end a critical section.
126 void end_critical_section(int which_one)
130 lprintf(8, " end_critical_section(%d)\n", which_one);
132 /* Let go of the semaphore */
133 pthread_mutex_unlock(&Critters[which_one]);
135 /* If a cancel was sent during the critical section, do it now.
136 * Then re-enable thread cancellation.
138 pthread_testcancel();
139 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
140 pthread_testcancel();
147 * This is a generic function to set up a master socket for listening on
148 * a TCP port. The server shuts down if the bind fails.
150 int ig_tcp_server(int port_number, int queue_len)
152 struct sockaddr_in sin;
155 bzero((char *)&sin, sizeof(sin));
156 sin.sin_family = AF_INET;
157 sin.sin_addr.s_addr = INADDR_ANY;
159 if (port_number == 0) {
160 lprintf(1, "citserver: No port number specified. Run setup again.\n");
164 sin.sin_port = htons((u_short)port_number);
166 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
168 lprintf(1, "citserver: Can't create a socket: %s\n",
173 /* Set the SO_REUSEADDR socket option, because it makes sense. */
175 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
177 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
178 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
182 if (listen(s, queue_len) < 0) {
183 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
192 * Return a pointer to a thread's own CitContext structure (old)
193 * NOTE: this version of MyContext() is commented out because it is no longer
194 * in use. It was written before I discovered TSD keys. This
195 * version pounds through the context list until it finds the one matching
196 * the currently running thread. It remains here, commented out, in case it
197 * is needed for future ports to threading libraries which have the equivalent
198 * of pthread_self() but not pthread_key_create() and its ilk.
200 * struct CitContext *MyContext() {
201 * struct CitContext *ptr;
204 * me = pthread_self();
205 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
206 * if (ptr->mythread == me) return(ptr);
213 * Return a pointer to a thread's own CitContext structure (new)
215 struct CitContext *MyContext(void) {
216 struct CitContext *retCC;
217 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
218 if (retCC == NULL) retCC = &masterCC;
224 * Wedge our way into the context list.
226 struct CitContext *CreateNewContext(void) {
227 struct CitContext *me;
229 lprintf(9, "CreateNewContext: calling malloc()\n");
230 me = (struct CitContext *) malloc(sizeof(struct CitContext));
232 lprintf(1, "citserver: can't allocate memory!!\n");
235 bzero(me, sizeof(struct CitContext));
237 begin_critical_section(S_SESSION_TABLE);
238 me->next = ContextList;
240 end_critical_section(S_SESSION_TABLE);
245 * Add a thread's thread ID to the context
247 void InitMyContext(struct CitContext *con)
251 con->mythread = pthread_self();
252 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
253 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
254 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
255 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
261 * Remove a context from the context list.
263 void RemoveContext(struct CitContext *con)
265 struct CitContext *ptr;
267 lprintf(7, "Starting RemoveContext()\n");
268 lprintf(9, "session count before RemoveContext is %d\n", session_count());
270 lprintf(7, "WARNING: RemoveContext() called with null!\n");
274 begin_critical_section(S_SESSION_TABLE);
275 lprintf(7, "Closing socket %d\n", con->client_socket);
276 close(con->client_socket);
278 if (ContextList==con) {
279 ContextList = ContextList->next;
282 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
283 if (ptr->next == con) {
284 ptr->next = ptr->next->next;
291 lprintf(9, "session count after RemoveContext is %d\n", session_count());
293 lprintf(7, "Done with RemoveContext\n");
294 end_critical_section(S_SESSION_TABLE);
299 * Return the number of sessions currently running.
300 * (This should probably be moved out of sysdep.c)
302 int session_count(void) {
303 struct CitContext *ptr;
306 lprintf(9, "session_count() starting\n");
307 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
309 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
312 lprintf(9, "session_count() finishing\n");
318 * client_write() ... Send binary data to the client.
320 void client_write(char *buf, int nbytes)
322 int bytes_written = 0;
324 while (bytes_written < nbytes) {
325 retval = write(CC->client_socket, &buf[bytes_written],
326 nbytes - bytes_written);
328 lprintf(2, "client_write() failed: %s\n",
332 bytes_written = bytes_written + retval;
338 * cprintf() ... Send formatted printable data to the client. It is
339 * implemented in terms of client_write() but remains in
340 * sysdep.c in case we port to somewhere without va_args...
342 void cprintf(const char *format, ...) {
347 va_start(arg_ptr, format);
348 rc = vsprintf(buf, format, arg_ptr);
351 client_write(buf, strlen(buf));
356 * Read data from the client socket.
358 * 1 Requested number of bytes has been read.
359 * 0 Request timed out.
360 * If the socket breaks, the session is immediately terminated.
362 int client_read_to(char *buf, int bytes, int timeout)
372 FD_SET(CC->client_socket, &rfds);
376 retval = select( (CC->client_socket)+1,
377 &rfds, NULL, NULL, &tv);
378 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
382 rlen = read(CC->client_socket, &buf[len], bytes-len);
384 lprintf(2, "client_read() failed: %s\n",
394 * Read data from the client socket with default timeout.
395 * (This is implemented in terms of client_read_to() and could be
396 * justifiably moved out of sysdep.c)
398 int client_read(char *buf, int bytes)
400 return(client_read_to(buf, bytes, config.c_sleeping));
405 * client_gets() ... Get a LF-terminated line of text from the client.
406 * (This is implemented in terms of client_read() and could be
407 * justifiably moved out of sysdep.c)
409 int client_gets(char *buf)
413 /* Clear the buffer, and read one character at a time.
417 if (strlen(buf)<255) {
418 buf[strlen(buf) + 1] = 0;
419 retval = client_read(&buf[strlen(buf)], 1);
421 } while ( (buf[strlen(buf)-1] != 10) && (retval==1) );
423 /* Strip the trailing newline.
425 if (strlen(buf) > 0) buf[strlen(buf)-1] = 0;
432 * The system-dependent part of master_cleanup() - close the master socket.
434 void sysdep_master_cleanup(void) {
435 lprintf(7, "Closing master socket %d\n", msock);
440 * Cleanup routine to be called when one thread is shutting down.
442 void cleanup(int exit_code)
444 /* Terminate the thread.
445 * Its cleanup handler will call cleanup_stuff()
447 lprintf(7, "Calling pthread_exit()\n");
452 * Terminate another session.
454 void kill_session(int session_to_kill) {
455 struct CitContext *ptr;
457 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
458 if (ptr->cs_pid == session_to_kill) {
459 pthread_cancel(ptr->mythread);
466 * The system-dependent wrapper around the main context loop.
468 void sd_context_loop(struct CitContext *con) {
469 pthread_cleanup_push(*cleanup_stuff, NULL);
471 pthread_cleanup_pop(0);
476 * Start running as a daemon. Only close stdio if do_close_stdio is set.
478 void start_daemon(int do_close_stdio) {
479 if (do_close_stdio) {
484 signal(SIGHUP,SIG_IGN);
485 signal(SIGINT,SIG_IGN);
486 signal(SIGQUIT,SIG_IGN);
487 if (fork()!=0) exit(0);
493 * Tie in to the 'netsetup' program.
495 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
497 void cmd_nset(char *cmdbuf)
504 char netsetup_args[3][256];
506 if (CC->usersupp.axlevel < 6) {
507 cprintf("%d Higher access required.\n",
508 ERROR + HIGHER_ACCESS_REQUIRED);
512 for (a=1; a<=3; ++a) {
513 if (num_parms(cmdbuf) >= a) {
514 extract(netsetup_args[a-1], cmdbuf, a-1);
515 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
516 if (netsetup_args[a-1][b] == 34) {
517 netsetup_args[a-1][b] = '_';
522 netsetup_args[a-1][0] = 0;
526 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
527 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
528 netsetup = popen(fbuf, "r");
529 if (netsetup == NULL) {
530 cprintf("%d %s\n", ERROR, strerror(errno));
535 while (ch = getc(netsetup), (ch > 0)) {
536 fbuf[strlen(fbuf)+1] = 0;
537 fbuf[strlen(fbuf)] = ch;
540 retcode = pclose(netsetup);
543 for (a=0; a<strlen(fbuf); ++a) {
544 if (fbuf[a] < 32) fbuf[a] = 32;
547 cprintf("%d %s\n", ERROR, fbuf);
551 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
553 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
560 * Generic routine to convert a login name to a full name (gecos)
561 * Returns nonzero if a conversion took place
563 int convert_login(char NameToConvert[]) {
567 pw = getpwnam(NameToConvert);
572 strcpy(NameToConvert, pw->pw_gecos);
573 for (a=0; a<strlen(NameToConvert); ++a) {
574 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
586 * Here's where it all begins.
588 int main(int argc, char **argv)
590 struct sockaddr_in fsin; /* Data for master socket */
591 int alen; /* Data for master socket */
592 int ssock; /* Descriptor for master socket */
593 THREAD SessThread; /* Thread descriptor */
594 pthread_attr_t attr; /* Thread attributes */
595 struct CitContext *con; /* Temporary context pointer */
596 char tracefile[128]; /* Name of file to log traces to */
597 int a, i; /* General-purpose variables */
601 /* specify default port name and trace file */
602 strcpy(tracefile, "");
604 /* parse command-line arguments */
605 for (a=1; a<argc; ++a) {
607 /* -t specifies where to log trace messages to */
608 if (!strncmp(argv[a], "-t", 2)) {
609 strcpy(tracefile, argv[a]);
610 strcpy(tracefile, &tracefile[2]);
611 freopen(tracefile, "r", stdin);
612 freopen(tracefile, "w", stdout);
613 freopen(tracefile, "w", stderr);
616 /* run in the background if -d was specified */
617 else if (!strcmp(argv[a], "-d")) {
618 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
621 /* -x specifies the desired logging level */
622 else if (!strncmp(argv[a], "-x", 2)) {
623 strcpy(convbuf, argv[a]);
624 verbosity = atoi(&convbuf[2]);
627 else if (!strncmp(argv[a], "-h", 2)) {
628 strcpy(convbuf, argv[a]);
629 strcpy(bbs_home_directory, &convbuf[2]);
633 /* any other parameter makes it crash and burn */
635 lprintf(1, "citserver: usage: ");
636 lprintf(1, "citserver [-tTraceFile]");
637 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
643 /* Tell 'em who's in da house */
644 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
645 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
646 lprintf(1, "All rights reserved.\n\n");
650 openlog("citserver",LOG_PID,LOG_USER);
651 lprintf(1, "Initting modules...\n");
652 snprintf(modpath, 128, "%s/modules", BBSDIR);
653 DLoader_Init(modpath);
654 lprintf(1, "Modules done initializing...\n");
656 lprintf(1, "First symtab item:");
657 lprintf(1, my_symtab->fcn_name);
660 /* Load site-specific parameters */
661 lprintf(7, "Loading citadel.config\n");
664 /* Do non system dependent startup functions */
668 * Bind the server to our favourite port.
669 * There is no need to check for errors, because ig_tcp_server()
670 * exits if it doesn't succeed.
672 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
673 msock = ig_tcp_server(config.c_port_number, 5);
674 lprintf(7, "Listening on socket %d\n", msock);
677 * Now that we've bound the socket, change to the BBS user id
678 lprintf(7, "Changing uid to %d\n", BBSUID);
679 if (setuid(BBSUID) != 0) {
680 lprintf(3, "setuid() failed: %s", strerror(errno));
685 * Endless loop. Listen on the master socket. When a connection
686 * comes in, create a socket, a context, and a thread.
689 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
691 lprintf(2, "citserver: accept() failed: %s\n",
695 lprintf(7, "citserver: Client socket %d\n", ssock);
696 lprintf(9, "creating context\n");
697 con = CreateNewContext();
698 con->client_socket = ssock;
700 /* Set the SO_REUSEADDR socket option */
701 lprintf(9, "setting socket options\n");
703 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
706 /* set attributes for the new thread */
707 lprintf(9, "setting thread attributes\n");
708 pthread_attr_init(&attr);
709 pthread_attr_setdetachstate(&attr,
710 PTHREAD_CREATE_DETACHED);
712 /* now create the thread */
713 lprintf(9, "creating thread\n");
714 if (pthread_create(&SessThread, &attr, (void *)sd_context_loop,
717 "citserver: can't create thread: %s\n",
722 * (defunct -- now done at thread creation time)
723 * if (pthread_detach(&SessThread) != 0) {
725 * "citserver: can't detach thread: %s\n",
729 lprintf(9, "done!\n");