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 vfprintf(stderr, format, arg_ptr);
79 * Some initialization stuff...
81 void init_sysdep(void) {
84 /* Set up a bunch of semaphores to be used for critical sections */
85 for (a=0; a<MAX_SEMAPHORES; ++a) {
86 pthread_mutex_init(&Critters[a], NULL);
90 * Set up a place to put thred-specific data.
91 * We only need a single pointer per thread - it points to the
92 * thread's CitContext structure in the ContextList linked list.
94 if (pthread_key_create(&MyConKey, NULL) != 0) {
95 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
99 * The action for unexpected signals and exceptions should be to
100 * call master_cleanup() to gracefully shut down the server.
102 signal(SIGINT, (void(*)(int))master_cleanup);
103 signal(SIGQUIT, (void(*)(int))master_cleanup);
104 signal(SIGHUP, (void(*)(int))master_cleanup);
105 signal(SIGTERM, (void(*)(int))master_cleanup);
110 * Obtain a semaphore lock to begin a critical section.
112 void begin_critical_section(int which_one)
116 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
118 /* Don't get interrupted during the critical section */
119 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
121 /* Obtain a semaphore */
122 pthread_mutex_lock(&Critters[which_one]);
127 * Release a semaphore lock to end a critical section.
129 void end_critical_section(int which_one)
133 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
135 /* Let go of the semaphore */
136 pthread_mutex_unlock(&Critters[which_one]);
138 /* If a cancel was sent during the critical section, do it now.
139 * Then re-enable thread cancellation.
141 pthread_testcancel();
142 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
143 pthread_testcancel();
150 * This is a generic function to set up a master socket for listening on
151 * a TCP port. The server shuts down if the bind fails.
153 int ig_tcp_server(int port_number, int queue_len)
155 struct sockaddr_in sin;
158 memset(&sin, 0, sizeof(sin));
159 sin.sin_family = AF_INET;
160 sin.sin_addr.s_addr = INADDR_ANY;
162 if (port_number == 0) {
163 lprintf(1, "citserver: No port number specified. Run setup again.\n");
167 sin.sin_port = htons((u_short)port_number);
169 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
171 lprintf(1, "citserver: Can't create a socket: %s\n",
176 /* Set the SO_REUSEADDR socket option, because it makes sense. */
178 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
180 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
181 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
185 if (listen(s, queue_len) < 0) {
186 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
195 * Return a pointer to a thread's own CitContext structure (old)
196 * NOTE: this version of MyContext() is commented out because it is no longer
197 * in use. It was written before I discovered TSD keys. This
198 * version pounds through the context list until it finds the one matching
199 * the currently running thread. It remains here, commented out, in case it
200 * is needed for future ports to threading libraries which have the equivalent
201 * of pthread_self() but not pthread_key_create() and its ilk.
203 * struct CitContext *MyContext() {
204 * struct CitContext *ptr;
207 * me = pthread_self();
208 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
209 * if (ptr->mythread == me) return(ptr);
216 * Return a pointer to a thread's own CitContext structure (new)
218 struct CitContext *MyContext(void) {
219 struct CitContext *retCC;
220 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
221 if (retCC == NULL) retCC = &masterCC;
227 * Wedge our way into the context list.
229 struct CitContext *CreateNewContext(void) {
230 struct CitContext *me;
232 lprintf(9, "CreateNewContext: calling malloc()\n");
233 me = (struct CitContext *) malloc(sizeof(struct CitContext));
235 lprintf(1, "citserver: can't allocate memory!!\n");
238 memset(me, 0, sizeof(struct CitContext));
240 begin_critical_section(S_SESSION_TABLE);
241 me->next = ContextList;
243 end_critical_section(S_SESSION_TABLE);
248 * Add a thread's thread ID to the context
250 void InitMyContext(struct CitContext *con)
254 con->mythread = pthread_self();
255 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
256 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
257 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
258 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
264 * Remove a context from the context list.
266 void RemoveContext(struct CitContext *con)
268 struct CitContext *ptr;
270 lprintf(7, "Starting RemoveContext()\n");
271 lprintf(9, "session count before RemoveContext is %d\n", session_count());
273 lprintf(7, "WARNING: RemoveContext() called with null!\n");
277 begin_critical_section(S_SESSION_TABLE);
278 lprintf(7, "Closing socket %d\n", con->client_socket);
279 close(con->client_socket);
281 if (ContextList==con) {
282 ContextList = ContextList->next;
285 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
286 if (ptr->next == con) {
287 ptr->next = ptr->next->next;
294 lprintf(9, "session count after RemoveContext is %d\n", session_count());
296 lprintf(7, "Done with RemoveContext\n");
297 end_critical_section(S_SESSION_TABLE);
302 * Return the number of sessions currently running.
303 * (This should probably be moved out of sysdep.c)
305 int session_count(void) {
306 struct CitContext *ptr;
309 lprintf(9, "session_count() starting\n");
310 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
312 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
315 lprintf(9, "session_count() finishing\n");
321 * client_write() ... Send binary data to the client.
323 void client_write(char *buf, int nbytes)
325 int bytes_written = 0;
327 while (bytes_written < nbytes) {
328 retval = write(CC->client_socket, &buf[bytes_written],
329 nbytes - bytes_written);
331 lprintf(2, "client_write() failed: %s\n",
335 bytes_written = bytes_written + retval;
341 * cprintf() ... Send formatted printable data to the client. It is
342 * implemented in terms of client_write() but remains in
343 * sysdep.c in case we port to somewhere without va_args...
345 void cprintf(const char *format, ...) {
349 va_start(arg_ptr, format);
350 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
351 buf[sizeof buf - 2] = '\n';
352 client_write(buf, strlen(buf));
358 * Read data from the client socket.
360 * 1 Requested number of bytes has been read.
361 * 0 Request timed out.
362 * If the socket breaks, the session is immediately terminated.
364 int client_read_to(char *buf, int bytes, int timeout)
374 FD_SET(CC->client_socket, &rfds);
378 retval = select( (CC->client_socket)+1,
379 &rfds, NULL, NULL, &tv);
380 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
384 rlen = read(CC->client_socket, &buf[len], bytes-len);
386 lprintf(2, "client_read() failed: %s\n",
396 * Read data from the client socket with default timeout.
397 * (This is implemented in terms of client_read_to() and could be
398 * justifiably moved out of sysdep.c)
400 int client_read(char *buf, int bytes)
402 return(client_read_to(buf, bytes, config.c_sleeping));
407 * client_gets() ... Get a LF-terminated line of text from the client.
408 * (This is implemented in terms of client_read() and could be
409 * justifiably moved out of sysdep.c)
411 int client_gets(char *buf)
415 /* Read one character at a time.
418 retval = client_read(&buf[i], 1);
419 if (retval != 1 || buf[i] == '\n' || i == 255)
423 /* If we got a long line, discard characters until the newline.
426 while (buf[i] != '\n' && retval == 1)
427 retval = client_read(&buf[i], 1);
429 /* Strip the trailing newline.
438 * The system-dependent part of master_cleanup() - close the master socket.
440 void sysdep_master_cleanup(void) {
441 lprintf(7, "Closing master socket %d\n", msock);
446 * Cleanup routine to be called when one thread is shutting down.
448 void cleanup(int exit_code)
450 /* Terminate the thread.
451 * Its cleanup handler will call cleanup_stuff()
453 lprintf(7, "Calling pthread_exit()\n");
458 * Terminate another session.
460 void kill_session(int session_to_kill) {
461 struct CitContext *ptr;
463 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
464 if (ptr->cs_pid == session_to_kill) {
465 pthread_cancel(ptr->mythread);
472 * The system-dependent wrapper around the main context loop.
474 void *sd_context_loop(struct CitContext *con) {
475 pthread_cleanup_push(*cleanup_stuff, NULL);
477 pthread_cleanup_pop(0);
483 * Start running as a daemon. Only close stdio if do_close_stdio is set.
485 void start_daemon(int do_close_stdio) {
486 if (do_close_stdio) {
491 signal(SIGHUP,SIG_IGN);
492 signal(SIGINT,SIG_IGN);
493 signal(SIGQUIT,SIG_IGN);
494 if (fork()!=0) exit(0);
500 * Tie in to the 'netsetup' program.
502 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
504 void cmd_nset(char *cmdbuf)
511 char netsetup_args[3][256];
513 if (CC->usersupp.axlevel < 6) {
514 cprintf("%d Higher access required.\n",
515 ERROR + HIGHER_ACCESS_REQUIRED);
519 for (a=1; a<=3; ++a) {
520 if (num_parms(cmdbuf) >= a) {
521 extract(netsetup_args[a-1], cmdbuf, a-1);
522 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
523 if (netsetup_args[a-1][b] == 34) {
524 netsetup_args[a-1][b] = '_';
529 netsetup_args[a-1][0] = 0;
533 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
534 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
535 netsetup = popen(fbuf, "r");
536 if (netsetup == NULL) {
537 cprintf("%d %s\n", ERROR, strerror(errno));
542 while (ch = getc(netsetup), (ch > 0)) {
543 fbuf[strlen(fbuf)+1] = 0;
544 fbuf[strlen(fbuf)] = ch;
547 retcode = pclose(netsetup);
550 for (a=0; a<strlen(fbuf); ++a) {
551 if (fbuf[a] < 32) fbuf[a] = 32;
554 cprintf("%d %s\n", ERROR, fbuf);
558 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
560 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
567 * Generic routine to convert a login name to a full name (gecos)
568 * Returns nonzero if a conversion took place
570 int convert_login(char NameToConvert[]) {
574 pw = getpwnam(NameToConvert);
579 strcpy(NameToConvert, pw->pw_gecos);
580 for (a=0; a<strlen(NameToConvert); ++a) {
581 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
593 * Here's where it all begins.
595 int main(int argc, char **argv)
597 struct sockaddr_in fsin; /* Data for master socket */
598 int alen; /* Data for master socket */
599 int ssock; /* Descriptor for master socket */
600 THREAD SessThread; /* Thread descriptor */
601 pthread_attr_t attr; /* Thread attributes */
602 struct CitContext *con; /* Temporary context pointer */
603 char tracefile[128]; /* Name of file to log traces to */
604 int a, i; /* General-purpose variables */
608 /* specify default port name and trace file */
609 strcpy(tracefile, "");
611 /* parse command-line arguments */
612 for (a=1; a<argc; ++a) {
614 /* -t specifies where to log trace messages to */
615 if (!strncmp(argv[a], "-t", 2)) {
616 strcpy(tracefile, argv[a]);
617 strcpy(tracefile, &tracefile[2]);
618 freopen(tracefile, "r", stdin);
619 freopen(tracefile, "w", stdout);
620 freopen(tracefile, "w", stderr);
623 /* run in the background if -d was specified */
624 else if (!strcmp(argv[a], "-d")) {
625 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
628 /* -x specifies the desired logging level */
629 else if (!strncmp(argv[a], "-x", 2)) {
630 strcpy(convbuf, argv[a]);
631 verbosity = atoi(&convbuf[2]);
634 else if (!strncmp(argv[a], "-h", 2)) {
635 strcpy(convbuf, argv[a]);
636 strcpy(bbs_home_directory, &convbuf[2]);
640 /* any other parameter makes it crash and burn */
642 lprintf(1, "citserver: usage: ");
643 lprintf(1, "citserver [-tTraceFile]");
644 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
650 /* Tell 'em who's in da house */
651 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
652 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
653 lprintf(1, "All rights reserved.\n\n");
657 openlog("citserver",LOG_PID,LOG_USER);
658 lprintf(1, "Initting modules...\n");
659 snprintf(modpath, 128, "%s/modules", BBSDIR);
660 DLoader_Init(modpath);
661 lprintf(1, "Modules done initializing...\n");
663 lprintf(1, "First symtab item:");
664 lprintf(1, my_symtab->fcn_name);
667 /* Load site-specific parameters */
668 lprintf(7, "Loading citadel.config\n");
671 /* Do non system dependent startup functions */
675 * Bind the server to our favourite port.
676 * There is no need to check for errors, because ig_tcp_server()
677 * exits if it doesn't succeed.
679 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
680 msock = ig_tcp_server(config.c_port_number, 5);
681 lprintf(7, "Listening on socket %d\n", msock);
684 * Now that we've bound the socket, change to the BBS user id
685 lprintf(7, "Changing uid to %d\n", BBSUID);
686 if (setuid(BBSUID) != 0) {
687 lprintf(3, "setuid() failed: %s", strerror(errno));
692 * Endless loop. Listen on the master socket. When a connection
693 * comes in, create a socket, a context, and a thread.
696 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
698 lprintf(2, "citserver: accept() failed: %s\n",
702 lprintf(7, "citserver: Client socket %d\n", ssock);
703 lprintf(9, "creating context\n");
704 con = CreateNewContext();
705 con->client_socket = ssock;
707 /* Set the SO_REUSEADDR socket option */
708 lprintf(9, "setting socket options\n");
710 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
713 /* set attributes for the new thread */
714 lprintf(9, "setting thread attributes\n");
715 pthread_attr_init(&attr);
716 pthread_attr_setdetachstate(&attr,
717 PTHREAD_CREATE_DETACHED);
719 /* now create the thread */
720 lprintf(9, "creating thread\n");
721 if (pthread_create(&SessThread, &attr,
722 (void* (*)(void*)) sd_context_loop,
726 "citserver: can't create thread: %s\n",
731 * (defunct -- now done at thread creation time)
732 * if (pthread_detach(&SessThread) != 0) {
734 * "citserver: can't detach thread: %s\n",
738 lprintf(9, "done!\n");