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.
23 #include <sys/types.h>
25 #include <sys/socket.h>
28 #include <netinet/in.h>
38 #include "sysdep_decls.h"
39 #include "citserver.h"
43 #include "housekeeping.h"
44 #include "dynloader.h"
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
55 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
56 pthread_key_t MyConKey; /* TSD key for MyContext() */
58 int msock; /* master listening socket */
59 int verbosity = 3; /* Logging level */
61 struct CitContext masterCC;
65 * lprintf() ... Write logging information
67 void lprintf(int loglevel, const char *format, ...) {
71 va_start(arg_ptr, format);
72 vsprintf(buf, format, arg_ptr);
75 if (loglevel <= verbosity) {
76 fprintf(stderr, "%s", buf);
80 PerformLogHooks(loglevel, buf);
85 * Some initialization stuff...
87 void init_sysdep(void) {
90 /* Set up a bunch of semaphores to be used for critical sections */
91 for (a=0; a<MAX_SEMAPHORES; ++a) {
92 pthread_mutex_init(&Critters[a], NULL);
96 * Set up a place to put thread-specific data.
97 * We only need a single pointer per thread - it points to the
98 * thread's CitContext structure in the ContextList linked list.
100 if (pthread_key_create(&MyConKey, NULL) != 0) {
101 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
105 * The action for unexpected signals and exceptions should be to
106 * call master_cleanup() to gracefully shut down the server.
108 signal(SIGINT, (void(*)(int))master_cleanup);
109 signal(SIGQUIT, (void(*)(int))master_cleanup);
110 signal(SIGHUP, (void(*)(int))master_cleanup);
111 signal(SIGTERM, (void(*)(int))master_cleanup);
116 * Obtain a semaphore lock to begin a critical section.
118 void begin_critical_section(int which_one)
122 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
124 /* Don't get interrupted during the critical section */
125 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
127 /* Obtain a semaphore */
128 pthread_mutex_lock(&Critters[which_one]);
133 * Release a semaphore lock to end a critical section.
135 void end_critical_section(int which_one)
139 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
141 /* Let go of the semaphore */
142 pthread_mutex_unlock(&Critters[which_one]);
144 /* If a cancel was sent during the critical section, do it now.
145 * Then re-enable thread cancellation.
147 pthread_testcancel();
148 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
149 pthread_testcancel();
156 * This is a generic function to set up a master socket for listening on
157 * a TCP port. The server shuts down if the bind fails.
159 int ig_tcp_server(int port_number, int queue_len)
161 struct sockaddr_in sin;
164 memset(&sin, 0, sizeof(sin));
165 sin.sin_family = AF_INET;
166 sin.sin_addr.s_addr = INADDR_ANY;
168 if (port_number == 0) {
170 "citserver: No port number specified. Run setup.\n");
174 sin.sin_port = htons((u_short)port_number);
176 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
178 lprintf(1, "citserver: Can't create a socket: %s\n",
183 /* Set the SO_REUSEADDR socket option, because it makes sense. */
185 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
187 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
188 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
192 if (listen(s, queue_len) < 0) {
193 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
202 * Return a pointer to a thread's own CitContext structure (old)
203 * NOTE: this version of MyContext() is commented out because it is no longer
204 * in use. It was written before I discovered TSD keys. This
205 * version pounds through the context list until it finds the one matching
206 * the currently running thread. It remains here, commented out, in case it
207 * is needed for future ports to threading libraries which have the equivalent
208 * of pthread_self() but not pthread_key_create() and its ilk.
210 * struct CitContext *MyContext() {
211 * struct CitContext *ptr;
214 * me = pthread_self();
215 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
216 * if (ptr->mythread == me) return(ptr);
223 * Return a pointer to a thread's own CitContext structure (new)
225 struct CitContext *MyContext(void) {
226 struct CitContext *retCC;
227 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
228 if (retCC == NULL) retCC = &masterCC;
234 * Wedge our way into the context list.
236 struct CitContext *CreateNewContext(void) {
237 struct CitContext *me;
239 lprintf(9, "CreateNewContext: calling malloc()\n");
240 me = (struct CitContext *) malloc(sizeof(struct CitContext));
242 lprintf(1, "citserver: can't allocate memory!!\n");
245 memset(me, 0, sizeof(struct CitContext));
247 begin_critical_section(S_SESSION_TABLE);
248 me->next = ContextList;
250 end_critical_section(S_SESSION_TABLE);
255 * Add a thread's thread ID to the context
257 void InitMyContext(struct CitContext *con)
261 con->mythread = pthread_self();
262 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
263 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
264 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
265 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
271 * Remove a context from the context list.
273 void RemoveContext(struct CitContext *con)
275 struct CitContext *ptr;
277 lprintf(7, "Starting RemoveContext()\n");
278 lprintf(9, "Session count before RemoveContext is %d\n",
281 lprintf(7, "WARNING: RemoveContext() called with null!\n");
285 begin_critical_section(S_SESSION_TABLE);
286 lprintf(7, "Closing socket %d\n", con->client_socket);
287 close(con->client_socket);
289 lprintf(9, "Dereferencing session context\n");
290 if (ContextList==con) {
291 ContextList = ContextList->next;
294 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
295 if (ptr->next == con) {
296 ptr->next = con->next;
301 lprintf(9, "Freeing session context...\n");
303 lprintf(9, "...done.\n");
305 lprintf(9, "Session count after RemoveContext is %d\n",
308 lprintf(7, "Done with RemoveContext\n");
309 end_critical_section(S_SESSION_TABLE);
314 * Return the number of sessions currently running.
315 * (This should probably be moved out of sysdep.c)
317 int session_count(void) {
318 struct CitContext *ptr;
321 lprintf(9, "session_count() starting\n");
322 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
324 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
327 lprintf(9, "session_count() finishing\n");
333 * client_write() ... Send binary data to the client.
335 void client_write(char *buf, int nbytes)
337 int bytes_written = 0;
339 while (bytes_written < nbytes) {
340 retval = write(CC->client_socket, &buf[bytes_written],
341 nbytes - bytes_written);
343 lprintf(2, "client_write() failed: %s\n",
347 bytes_written = bytes_written + retval;
353 * cprintf() ... Send formatted printable data to the client. It is
354 * implemented in terms of client_write() but remains in
355 * sysdep.c in case we port to somewhere without va_args...
357 void cprintf(const char *format, ...) {
361 va_start(arg_ptr, format);
362 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
363 buf[sizeof buf - 2] = '\n';
364 client_write(buf, strlen(buf));
370 * Read data from the client socket.
372 * 1 Requested number of bytes has been read.
373 * 0 Request timed out.
374 * If the socket breaks, the session is immediately terminated.
376 int client_read_to(char *buf, int bytes, int timeout)
386 FD_SET(CC->client_socket, &rfds);
390 retval = select( (CC->client_socket)+1,
391 &rfds, NULL, NULL, &tv);
392 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
396 rlen = read(CC->client_socket, &buf[len], bytes-len);
398 lprintf(2, "client_read() failed: %s\n",
408 * Read data from the client socket with default timeout.
409 * (This is implemented in terms of client_read_to() and could be
410 * justifiably moved out of sysdep.c)
412 int client_read(char *buf, int bytes)
414 return(client_read_to(buf, bytes, config.c_sleeping));
419 * client_gets() ... Get a LF-terminated line of text from the client.
420 * (This is implemented in terms of client_read() and could be
421 * justifiably moved out of sysdep.c)
423 int client_gets(char *buf)
427 /* Read one character at a time.
430 retval = client_read(&buf[i], 1);
431 if (retval != 1 || buf[i] == '\n' || i == 255)
435 /* If we got a long line, discard characters until the newline.
438 while (buf[i] != '\n' && retval == 1)
439 retval = client_read(&buf[i], 1);
441 /* Strip the trailing newline and any trailing nonprintables (cr's)
444 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
445 buf[strlen(buf)-1] = 0;
452 * The system-dependent part of master_cleanup() - close the master socket.
454 void sysdep_master_cleanup(void) {
455 lprintf(7, "Closing master socket %d\n", msock);
460 * Cleanup routine to be called when one thread is shutting down.
462 void cleanup(int exit_code)
464 /* Terminate the thread.
465 * Its cleanup handler will call cleanup_stuff()
467 lprintf(7, "Calling pthread_exit()\n");
472 * Terminate another session.
474 void kill_session(int session_to_kill) {
475 struct CitContext *ptr;
477 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
478 if (ptr->cs_pid == session_to_kill) {
479 pthread_cancel(ptr->mythread);
486 * The system-dependent wrapper around the main context loop.
488 void *sd_context_loop(struct CitContext *con) {
489 pthread_cleanup_push(*cleanup_stuff, NULL);
491 pthread_cleanup_pop(0);
497 * Start running as a daemon. Only close stdio if do_close_stdio is set.
499 void start_daemon(int do_close_stdio) {
500 if (do_close_stdio) {
505 signal(SIGHUP,SIG_IGN);
506 signal(SIGINT,SIG_IGN);
507 signal(SIGQUIT,SIG_IGN);
508 if (fork()!=0) exit(0);
514 * Tie in to the 'netsetup' program.
516 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
518 void cmd_nset(char *cmdbuf)
525 char netsetup_args[3][256];
527 if (CC->usersupp.axlevel < 6) {
528 cprintf("%d Higher access required.\n",
529 ERROR + HIGHER_ACCESS_REQUIRED);
533 for (a=1; a<=3; ++a) {
534 if (num_parms(cmdbuf) >= a) {
535 extract(netsetup_args[a-1], cmdbuf, a-1);
536 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
537 if (netsetup_args[a-1][b] == 34) {
538 netsetup_args[a-1][b] = '_';
543 netsetup_args[a-1][0] = 0;
547 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
548 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
549 netsetup = popen(fbuf, "r");
550 if (netsetup == NULL) {
551 cprintf("%d %s\n", ERROR, strerror(errno));
556 while (ch = getc(netsetup), (ch > 0)) {
557 fbuf[strlen(fbuf)+1] = 0;
558 fbuf[strlen(fbuf)] = ch;
561 retcode = pclose(netsetup);
564 for (a=0; a<strlen(fbuf); ++a) {
565 if (fbuf[a] < 32) fbuf[a] = 32;
568 cprintf("%d %s\n", ERROR, fbuf);
572 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
574 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
581 * Generic routine to convert a login name to a full name (gecos)
582 * Returns nonzero if a conversion took place
584 int convert_login(char NameToConvert[]) {
588 pw = getpwnam(NameToConvert);
593 strcpy(NameToConvert, pw->pw_gecos);
594 for (a=0; a<strlen(NameToConvert); ++a) {
595 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
607 * Here's where it all begins.
609 int main(int argc, char **argv)
611 struct sockaddr_in fsin; /* Data for master socket */
612 int alen; /* Data for master socket */
613 int ssock; /* Descriptor for master socket */
614 THREAD SessThread; /* Thread descriptor */
615 pthread_attr_t attr; /* Thread attributes */
616 struct CitContext *con; /* Temporary context pointer */
617 char tracefile[128]; /* Name of file to log traces to */
618 int a, i; /* General-purpose variables */
622 /* specify default port name and trace file */
623 strcpy(tracefile, "");
625 /* parse command-line arguments */
626 for (a=1; a<argc; ++a) {
628 /* -t specifies where to log trace messages to */
629 if (!strncmp(argv[a], "-t", 2)) {
630 strcpy(tracefile, argv[a]);
631 strcpy(tracefile, &tracefile[2]);
632 freopen(tracefile, "r", stdin);
633 freopen(tracefile, "w", stdout);
634 freopen(tracefile, "w", stderr);
637 /* run in the background if -d was specified */
638 else if (!strcmp(argv[a], "-d")) {
639 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
642 /* -x specifies the desired logging level */
643 else if (!strncmp(argv[a], "-x", 2)) {
644 strcpy(convbuf, argv[a]);
645 verbosity = atoi(&convbuf[2]);
648 else if (!strncmp(argv[a], "-h", 2)) {
649 strcpy(convbuf, argv[a]);
650 strcpy(bbs_home_directory, &convbuf[2]);
654 /* any other parameter makes it crash and burn */
656 lprintf(1, "citserver: usage: ");
657 lprintf(1, "citserver [-tTraceFile]");
658 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
664 /* Tell 'em who's in da house */
665 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
666 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
667 lprintf(1, "All rights reserved.\n\n");
671 openlog("citserver",LOG_PID,LOG_USER);
672 /* Load site-specific parameters */
673 lprintf(7, "Loading citadel.config\n");
676 lprintf(7, "Initializing loadable modules\n");
677 snprintf(modpath, 128, "%s/modules", BBSDIR);
678 DLoader_Init(modpath);
679 lprintf(9, "Modules done initializing.\n");
681 /* Do non system dependent startup functions */
685 * Bind the server to our favourite port.
686 * There is no need to check for errors, because ig_tcp_server()
687 * exits if it doesn't succeed.
689 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
690 msock = ig_tcp_server(config.c_port_number, 5);
691 lprintf(7, "Listening on socket %d\n", msock);
694 * Now that we've bound the socket, change to the BBS user id
695 lprintf(7, "Changing uid to %d\n", BBSUID);
696 if (setuid(BBSUID) != 0) {
697 lprintf(3, "setuid() failed: %s", strerror(errno));
702 * Endless loop. Listen on the master socket. When a connection
703 * comes in, create a socket, a context, and a thread.
706 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
708 lprintf(2, "citserver: accept() failed: %s\n",
712 lprintf(7, "citserver: Client socket %d\n", ssock);
713 lprintf(9, "creating context\n");
714 con = CreateNewContext();
715 con->client_socket = ssock;
717 /* Set the SO_REUSEADDR socket option */
718 lprintf(9, "setting socket options\n");
720 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
723 /* set attributes for the new thread */
724 lprintf(9, "setting thread attributes\n");
725 pthread_attr_init(&attr);
726 pthread_attr_setdetachstate(&attr,
727 PTHREAD_CREATE_DETACHED);
729 /* now create the thread */
730 lprintf(9, "creating thread\n");
731 if (pthread_create(&SessThread, &attr,
732 (void* (*)(void*)) sd_context_loop,
736 "citserver: can't create thread: %s\n",
741 * (defunct -- now done at thread creation time)
742 * if (pthread_detach(&SessThread) != 0) {
744 * "citserver: can't detach thread: %s\n",
748 lprintf(9, "done!\n");