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 rc = vfprintf(stderr, format, arg_ptr);
78 * Some initialization stuff...
80 void init_sysdep(void) {
83 /* Set up a bunch of semaphores to be used for critical sections */
84 for (a=0; a<MAX_SEMAPHORES; ++a) {
85 pthread_mutex_init(&Critters[a], NULL);
89 * Set up a place to put thred-specific data.
90 * We only need a single pointer per thread - it points to the
91 * thread's CitContext structure in the ContextList linked list.
93 if (pthread_key_create(&MyConKey, NULL) != 0) {
94 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
98 * The action for unexpected signals and exceptions should be to
99 * call master_cleanup() to gracefully shut down the server.
101 signal(SIGINT, (void(*)(int))master_cleanup);
102 signal(SIGQUIT, (void(*)(int))master_cleanup);
103 signal(SIGHUP, (void(*)(int))master_cleanup);
104 signal(SIGTERM, (void(*)(int))master_cleanup);
109 * Obtain a semaphore lock to begin a critical section.
111 void begin_critical_section(int which_one)
115 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
117 /* Don't get interrupted during the critical section */
118 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
120 /* Obtain a semaphore */
121 pthread_mutex_lock(&Critters[which_one]);
126 * Release a semaphore lock to end a critical section.
128 void end_critical_section(int which_one)
132 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
134 /* Let go of the semaphore */
135 pthread_mutex_unlock(&Critters[which_one]);
137 /* If a cancel was sent during the critical section, do it now.
138 * Then re-enable thread cancellation.
140 pthread_testcancel();
141 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
142 pthread_testcancel();
149 * This is a generic function to set up a master socket for listening on
150 * a TCP port. The server shuts down if the bind fails.
152 int ig_tcp_server(int port_number, int queue_len)
154 struct sockaddr_in sin;
157 memset(&sin, 0, sizeof(sin));
158 sin.sin_family = AF_INET;
159 sin.sin_addr.s_addr = INADDR_ANY;
161 if (port_number == 0) {
162 lprintf(1, "citserver: No port number specified. Run setup again.\n");
166 sin.sin_port = htons((u_short)port_number);
168 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
170 lprintf(1, "citserver: Can't create a socket: %s\n",
175 /* Set the SO_REUSEADDR socket option, because it makes sense. */
177 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
179 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
180 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
184 if (listen(s, queue_len) < 0) {
185 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
194 * Return a pointer to a thread's own CitContext structure (old)
195 * NOTE: this version of MyContext() is commented out because it is no longer
196 * in use. It was written before I discovered TSD keys. This
197 * version pounds through the context list until it finds the one matching
198 * the currently running thread. It remains here, commented out, in case it
199 * is needed for future ports to threading libraries which have the equivalent
200 * of pthread_self() but not pthread_key_create() and its ilk.
202 * struct CitContext *MyContext() {
203 * struct CitContext *ptr;
206 * me = pthread_self();
207 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
208 * if (ptr->mythread == me) return(ptr);
215 * Return a pointer to a thread's own CitContext structure (new)
217 struct CitContext *MyContext(void) {
218 struct CitContext *retCC;
219 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
220 if (retCC == NULL) retCC = &masterCC;
226 * Wedge our way into the context list.
228 struct CitContext *CreateNewContext(void) {
229 struct CitContext *me;
231 lprintf(9, "CreateNewContext: calling malloc()\n");
232 me = (struct CitContext *) malloc(sizeof(struct CitContext));
234 lprintf(1, "citserver: can't allocate memory!!\n");
237 memset(me, 0, sizeof(struct CitContext));
239 begin_critical_section(S_SESSION_TABLE);
240 me->next = ContextList;
242 end_critical_section(S_SESSION_TABLE);
247 * Add a thread's thread ID to the context
249 void InitMyContext(struct CitContext *con)
253 con->mythread = pthread_self();
254 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
255 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
256 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
257 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
263 * Remove a context from the context list.
265 void RemoveContext(struct CitContext *con)
267 struct CitContext *ptr;
269 lprintf(7, "Starting RemoveContext()\n");
270 lprintf(9, "session count before RemoveContext is %d\n", session_count());
272 lprintf(7, "WARNING: RemoveContext() called with null!\n");
276 begin_critical_section(S_SESSION_TABLE);
277 lprintf(7, "Closing socket %d\n", con->client_socket);
278 close(con->client_socket);
280 if (ContextList==con) {
281 ContextList = ContextList->next;
284 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
285 if (ptr->next == con) {
286 ptr->next = ptr->next->next;
293 lprintf(9, "session count after RemoveContext is %d\n", session_count());
295 lprintf(7, "Done with RemoveContext\n");
296 end_critical_section(S_SESSION_TABLE);
301 * Return the number of sessions currently running.
302 * (This should probably be moved out of sysdep.c)
304 int session_count(void) {
305 struct CitContext *ptr;
308 lprintf(9, "session_count() starting\n");
309 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
311 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
314 lprintf(9, "session_count() finishing\n");
320 * client_write() ... Send binary data to the client.
322 void client_write(char *buf, int nbytes)
324 int bytes_written = 0;
326 while (bytes_written < nbytes) {
327 retval = write(CC->client_socket, &buf[bytes_written],
328 nbytes - bytes_written);
330 lprintf(2, "client_write() failed: %s\n",
334 bytes_written = bytes_written + retval;
340 * cprintf() ... Send formatted printable data to the client. It is
341 * implemented in terms of client_write() but remains in
342 * sysdep.c in case we port to somewhere without va_args...
344 void cprintf(const char *format, ...) {
348 va_start(arg_ptr, format);
349 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
350 buf[sizeof buf - 2] = '\n';
351 client_write(buf, strlen(buf));
357 * Read data from the client socket.
359 * 1 Requested number of bytes has been read.
360 * 0 Request timed out.
361 * If the socket breaks, the session is immediately terminated.
363 int client_read_to(char *buf, int bytes, int timeout)
373 FD_SET(CC->client_socket, &rfds);
377 retval = select( (CC->client_socket)+1,
378 &rfds, NULL, NULL, &tv);
379 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
383 rlen = read(CC->client_socket, &buf[len], bytes-len);
385 lprintf(2, "client_read() failed: %s\n",
395 * Read data from the client socket with default timeout.
396 * (This is implemented in terms of client_read_to() and could be
397 * justifiably moved out of sysdep.c)
399 int client_read(char *buf, int bytes)
401 return(client_read_to(buf, bytes, config.c_sleeping));
406 * client_gets() ... Get a LF-terminated line of text from the client.
407 * (This is implemented in terms of client_read() and could be
408 * justifiably moved out of sysdep.c)
410 int client_gets(char *buf)
414 /* Read one character at a time.
417 retval = client_read(&buf[i], 1);
418 if (retval != 1 || buf[i] == '\n' || i == 255)
422 /* If we got a long line, discard characters until the newline.
425 while (buf[i] != '\n' && retval == 1)
426 retval = client_read(&buf[i], 1);
428 /* Strip the trailing newline.
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");