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, ...) {
352 va_start(arg_ptr, format);
353 rc = vsprintf(buf, format, arg_ptr);
356 client_write(buf, strlen(buf));
361 * Read data from the client socket.
363 * 1 Requested number of bytes has been read.
364 * 0 Request timed out.
365 * If the socket breaks, the session is immediately terminated.
367 int client_read_to(char *buf, int bytes, int timeout)
377 FD_SET(CC->client_socket, &rfds);
381 retval = select( (CC->client_socket)+1,
382 &rfds, NULL, NULL, &tv);
383 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
387 rlen = read(CC->client_socket, &buf[len], bytes-len);
389 lprintf(2, "client_read() failed: %s\n",
399 * Read data from the client socket with default timeout.
400 * (This is implemented in terms of client_read_to() and could be
401 * justifiably moved out of sysdep.c)
403 int client_read(char *buf, int bytes)
405 return(client_read_to(buf, bytes, config.c_sleeping));
410 * client_gets() ... Get a LF-terminated line of text from the client.
411 * (This is implemented in terms of client_read() and could be
412 * justifiably moved out of sysdep.c)
414 int client_gets(char *buf)
418 /* Clear the buffer, and read one character at a time.
422 if (strlen(buf)<255) {
423 buf[strlen(buf) + 1] = 0;
424 retval = client_read(&buf[strlen(buf)], 1);
426 } while ( (buf[strlen(buf)-1] != 10) && (retval==1) );
428 /* Strip the trailing newline.
430 if (strlen(buf) > 0) buf[strlen(buf)-1] = 0;
437 * The system-dependent part of master_cleanup() - close the master socket.
439 void sysdep_master_cleanup(void) {
440 lprintf(7, "Closing master socket %d\n", msock);
445 * Cleanup routine to be called when one thread is shutting down.
447 void cleanup(int exit_code)
449 /* Terminate the thread.
450 * Its cleanup handler will call cleanup_stuff()
452 lprintf(7, "Calling pthread_exit()\n");
457 * Terminate another session.
459 void kill_session(int session_to_kill) {
460 struct CitContext *ptr;
462 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
463 if (ptr->cs_pid == session_to_kill) {
464 pthread_cancel(ptr->mythread);
471 * The system-dependent wrapper around the main context loop.
473 void *sd_context_loop(struct CitContext *con) {
474 pthread_cleanup_push(*cleanup_stuff, NULL);
476 pthread_cleanup_pop(0);
482 * Start running as a daemon. Only close stdio if do_close_stdio is set.
484 void start_daemon(int do_close_stdio) {
485 if (do_close_stdio) {
490 signal(SIGHUP,SIG_IGN);
491 signal(SIGINT,SIG_IGN);
492 signal(SIGQUIT,SIG_IGN);
493 if (fork()!=0) exit(0);
499 * Tie in to the 'netsetup' program.
501 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
503 void cmd_nset(char *cmdbuf)
510 char netsetup_args[3][256];
512 if (CC->usersupp.axlevel < 6) {
513 cprintf("%d Higher access required.\n",
514 ERROR + HIGHER_ACCESS_REQUIRED);
518 for (a=1; a<=3; ++a) {
519 if (num_parms(cmdbuf) >= a) {
520 extract(netsetup_args[a-1], cmdbuf, a-1);
521 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
522 if (netsetup_args[a-1][b] == 34) {
523 netsetup_args[a-1][b] = '_';
528 netsetup_args[a-1][0] = 0;
532 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
533 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
534 netsetup = popen(fbuf, "r");
535 if (netsetup == NULL) {
536 cprintf("%d %s\n", ERROR, strerror(errno));
541 while (ch = getc(netsetup), (ch > 0)) {
542 fbuf[strlen(fbuf)+1] = 0;
543 fbuf[strlen(fbuf)] = ch;
546 retcode = pclose(netsetup);
549 for (a=0; a<strlen(fbuf); ++a) {
550 if (fbuf[a] < 32) fbuf[a] = 32;
553 cprintf("%d %s\n", ERROR, fbuf);
557 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
559 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
566 * Generic routine to convert a login name to a full name (gecos)
567 * Returns nonzero if a conversion took place
569 int convert_login(char NameToConvert[]) {
573 pw = getpwnam(NameToConvert);
578 strcpy(NameToConvert, pw->pw_gecos);
579 for (a=0; a<strlen(NameToConvert); ++a) {
580 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
592 * Here's where it all begins.
594 int main(int argc, char **argv)
596 struct sockaddr_in fsin; /* Data for master socket */
597 int alen; /* Data for master socket */
598 int ssock; /* Descriptor for master socket */
599 THREAD SessThread; /* Thread descriptor */
600 pthread_attr_t attr; /* Thread attributes */
601 struct CitContext *con; /* Temporary context pointer */
602 char tracefile[128]; /* Name of file to log traces to */
603 int a, i; /* General-purpose variables */
607 /* specify default port name and trace file */
608 strcpy(tracefile, "");
610 /* parse command-line arguments */
611 for (a=1; a<argc; ++a) {
613 /* -t specifies where to log trace messages to */
614 if (!strncmp(argv[a], "-t", 2)) {
615 strcpy(tracefile, argv[a]);
616 strcpy(tracefile, &tracefile[2]);
617 freopen(tracefile, "r", stdin);
618 freopen(tracefile, "w", stdout);
619 freopen(tracefile, "w", stderr);
622 /* run in the background if -d was specified */
623 else if (!strcmp(argv[a], "-d")) {
624 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
627 /* -x specifies the desired logging level */
628 else if (!strncmp(argv[a], "-x", 2)) {
629 strcpy(convbuf, argv[a]);
630 verbosity = atoi(&convbuf[2]);
633 else if (!strncmp(argv[a], "-h", 2)) {
634 strcpy(convbuf, argv[a]);
635 strcpy(bbs_home_directory, &convbuf[2]);
639 /* any other parameter makes it crash and burn */
641 lprintf(1, "citserver: usage: ");
642 lprintf(1, "citserver [-tTraceFile]");
643 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
649 /* Tell 'em who's in da house */
650 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
651 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
652 lprintf(1, "All rights reserved.\n\n");
656 openlog("citserver",LOG_PID,LOG_USER);
657 lprintf(1, "Initting modules...\n");
658 snprintf(modpath, 128, "%s/modules", BBSDIR);
659 DLoader_Init(modpath);
660 lprintf(1, "Modules done initializing...\n");
662 lprintf(1, "First symtab item:");
663 lprintf(1, my_symtab->fcn_name);
666 /* Load site-specific parameters */
667 lprintf(7, "Loading citadel.config\n");
670 /* Do non system dependent startup functions */
674 * Bind the server to our favourite port.
675 * There is no need to check for errors, because ig_tcp_server()
676 * exits if it doesn't succeed.
678 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
679 msock = ig_tcp_server(config.c_port_number, 5);
680 lprintf(7, "Listening on socket %d\n", msock);
683 * Now that we've bound the socket, change to the BBS user id
684 lprintf(7, "Changing uid to %d\n", BBSUID);
685 if (setuid(BBSUID) != 0) {
686 lprintf(3, "setuid() failed: %s", strerror(errno));
691 * Endless loop. Listen on the master socket. When a connection
692 * comes in, create a socket, a context, and a thread.
695 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
697 lprintf(2, "citserver: accept() failed: %s\n",
701 lprintf(7, "citserver: Client socket %d\n", ssock);
702 lprintf(9, "creating context\n");
703 con = CreateNewContext();
704 con->client_socket = ssock;
706 /* Set the SO_REUSEADDR socket option */
707 lprintf(9, "setting socket options\n");
709 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
712 /* set attributes for the new thread */
713 lprintf(9, "setting thread attributes\n");
714 pthread_attr_init(&attr);
715 pthread_attr_setdetachstate(&attr,
716 PTHREAD_CREATE_DETACHED);
718 /* now create the thread */
719 lprintf(9, "creating thread\n");
720 if (pthread_create(&SessThread, &attr,
721 (void* (*)(void*)) sd_context_loop,
725 "citserver: can't create thread: %s\n",
730 * (defunct -- now done at thread creation time)
731 * if (pthread_detach(&SessThread) != 0) {
733 * "citserver: can't detach thread: %s\n",
737 lprintf(9, "done!\n");