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);
112 signal(SIGPIPE, SIG_IGN);
117 * Obtain a semaphore lock to begin a critical section.
119 void begin_critical_section(int which_one)
123 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
125 /* Don't get interrupted during the critical section */
126 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
128 /* Obtain a semaphore */
129 pthread_mutex_lock(&Critters[which_one]);
134 * Release a semaphore lock to end a critical section.
136 void end_critical_section(int which_one)
140 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
142 /* Let go of the semaphore */
143 pthread_mutex_unlock(&Critters[which_one]);
145 /* If a cancel was sent during the critical section, do it now.
146 * Then re-enable thread cancellation.
148 pthread_testcancel();
149 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
150 pthread_testcancel();
157 * This is a generic function to set up a master socket for listening on
158 * a TCP port. The server shuts down if the bind fails.
160 int ig_tcp_server(int port_number, int queue_len)
162 struct sockaddr_in sin;
165 memset(&sin, 0, sizeof(sin));
166 sin.sin_family = AF_INET;
167 sin.sin_addr.s_addr = INADDR_ANY;
169 if (port_number == 0) {
171 "citserver: No port number specified. Run setup.\n");
175 sin.sin_port = htons((u_short)port_number);
177 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
179 lprintf(1, "citserver: Can't create a socket: %s\n",
184 /* Set the SO_REUSEADDR socket option, because it makes sense. */
186 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
188 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
189 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
193 if (listen(s, queue_len) < 0) {
194 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
203 * Return a pointer to a thread's own CitContext structure (old)
204 * NOTE: this version of MyContext() is commented out because it is no longer
205 * in use. It was written before I discovered TSD keys. This
206 * version pounds through the context list until it finds the one matching
207 * the currently running thread. It remains here, commented out, in case it
208 * is needed for future ports to threading libraries which have the equivalent
209 * of pthread_self() but not pthread_key_create() and its ilk.
211 * struct CitContext *MyContext() {
212 * struct CitContext *ptr;
215 * me = pthread_self();
216 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
217 * if (ptr->mythread == me) return(ptr);
224 * Return a pointer to a thread's own CitContext structure (new)
226 struct CitContext *MyContext(void) {
227 struct CitContext *retCC;
228 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
229 if (retCC == NULL) retCC = &masterCC;
235 * Wedge our way into the context list.
237 struct CitContext *CreateNewContext(void) {
238 struct CitContext *me;
240 lprintf(9, "CreateNewContext: calling malloc()\n");
241 me = (struct CitContext *) malloc(sizeof(struct CitContext));
243 lprintf(1, "citserver: can't allocate memory!!\n");
246 memset(me, 0, sizeof(struct CitContext));
248 begin_critical_section(S_SESSION_TABLE);
249 me->next = ContextList;
251 end_critical_section(S_SESSION_TABLE);
256 * Add a thread's thread ID to the context
258 void InitMyContext(struct CitContext *con)
262 con->mythread = pthread_self();
263 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
264 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
265 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
266 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
272 * Remove a context from the context list.
274 void RemoveContext(struct CitContext *con)
276 struct CitContext *ptr;
278 lprintf(7, "Starting RemoveContext()\n");
279 lprintf(9, "Session count before RemoveContext is %d\n",
282 lprintf(7, "WARNING: RemoveContext() called with null!\n");
287 * session_count() starts its own S_SESSION_TABLE critical section;
288 * so do not call it from within this loop.
290 begin_critical_section(S_SESSION_TABLE);
291 lprintf(7, "Closing socket %d\n", con->client_socket);
292 close(con->client_socket);
294 lprintf(9, "Dereferencing session context\n");
295 if (ContextList==con) {
296 ContextList = ContextList->next;
299 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
300 if (ptr->next == con) {
301 ptr->next = con->next;
306 lprintf(9, "Freeing session context...\n");
308 lprintf(9, "...done.\n");
309 end_critical_section(S_SESSION_TABLE);
311 lprintf(9, "Session count after RemoveContext is %d\n",
314 lprintf(7, "Done with RemoveContext\n");
319 * Return the number of sessions currently running.
320 * (This should probably be moved out of sysdep.c)
322 int session_count(void) {
323 struct CitContext *ptr;
326 lprintf(9, "session_count() starting\n");
327 begin_critical_section(S_SESSION_TABLE);
328 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
330 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
332 end_critical_section(S_SESSION_TABLE);
334 lprintf(9, "session_count() finishing\n");
340 * client_write() ... Send binary data to the client.
342 void client_write(char *buf, int nbytes)
344 int bytes_written = 0;
346 while (bytes_written < nbytes) {
347 retval = write(CC->client_socket, &buf[bytes_written],
348 nbytes - bytes_written);
350 lprintf(2, "client_write() failed: %s\n",
354 bytes_written = bytes_written + retval;
360 * cprintf() ... Send formatted printable data to the client. It is
361 * implemented in terms of client_write() but remains in
362 * sysdep.c in case we port to somewhere without va_args...
364 void cprintf(const char *format, ...) {
368 va_start(arg_ptr, format);
369 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
370 buf[sizeof buf - 2] = '\n';
371 client_write(buf, strlen(buf));
377 * Read data from the client socket.
379 * 1 Requested number of bytes has been read.
380 * 0 Request timed out.
381 * If the socket breaks, the session is immediately terminated.
383 int client_read_to(char *buf, int bytes, int timeout)
393 FD_SET(CC->client_socket, &rfds);
397 retval = select( (CC->client_socket)+1,
398 &rfds, NULL, NULL, &tv);
399 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
403 rlen = read(CC->client_socket, &buf[len], bytes-len);
405 lprintf(2, "client_read() failed: %s\n",
415 * Read data from the client socket with default timeout.
416 * (This is implemented in terms of client_read_to() and could be
417 * justifiably moved out of sysdep.c)
419 int client_read(char *buf, int bytes)
421 return(client_read_to(buf, bytes, config.c_sleeping));
426 * client_gets() ... Get a LF-terminated line of text from the client.
427 * (This is implemented in terms of client_read() and could be
428 * justifiably moved out of sysdep.c)
430 int client_gets(char *buf)
434 /* Read one character at a time.
437 retval = client_read(&buf[i], 1);
438 if (retval != 1 || buf[i] == '\n' || i == 255)
442 /* If we got a long line, discard characters until the newline.
445 while (buf[i] != '\n' && retval == 1)
446 retval = client_read(&buf[i], 1);
448 /* Strip the trailing newline and any trailing nonprintables (cr's)
451 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
452 buf[strlen(buf)-1] = 0;
459 * The system-dependent part of master_cleanup() - close the master socket.
461 void sysdep_master_cleanup(void) {
462 lprintf(7, "Closing master socket %d\n", msock);
467 * Cleanup routine to be called when one thread is shutting down.
469 void cleanup(int exit_code)
471 /* Terminate the thread.
472 * Its cleanup handler will call cleanup_stuff()
474 lprintf(7, "Calling pthread_exit()\n");
479 * Terminate another session.
481 void kill_session(int session_to_kill) {
482 struct CitContext *ptr;
485 lprintf(9, "kill_session() scanning for thread to cancel...\n");
486 begin_critical_section(S_SESSION_TABLE);
487 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
488 if (ptr->cs_pid == session_to_kill) {
489 killme = ptr->mythread;
492 end_critical_section(S_SESSION_TABLE);
493 lprintf(9, "kill_session() finished scanning.\n");
496 lprintf(9, "calling pthread_cancel()\n");
497 pthread_cancel(killme);
503 * The system-dependent wrapper around the main context loop.
505 void *sd_context_loop(struct CitContext *con) {
506 pthread_cleanup_push(*cleanup_stuff, NULL);
508 pthread_cleanup_pop(0);
514 * Start running as a daemon. Only close stdio if do_close_stdio is set.
516 void start_daemon(int do_close_stdio) {
517 if (do_close_stdio) {
522 signal(SIGHUP,SIG_IGN);
523 signal(SIGINT,SIG_IGN);
524 signal(SIGQUIT,SIG_IGN);
525 if (fork()!=0) exit(0);
531 * Tie in to the 'netsetup' program.
533 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
535 void cmd_nset(char *cmdbuf)
542 char netsetup_args[3][256];
544 if (CC->usersupp.axlevel < 6) {
545 cprintf("%d Higher access required.\n",
546 ERROR + HIGHER_ACCESS_REQUIRED);
550 for (a=1; a<=3; ++a) {
551 if (num_parms(cmdbuf) >= a) {
552 extract(netsetup_args[a-1], cmdbuf, a-1);
553 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
554 if (netsetup_args[a-1][b] == 34) {
555 netsetup_args[a-1][b] = '_';
560 netsetup_args[a-1][0] = 0;
564 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
565 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
566 netsetup = popen(fbuf, "r");
567 if (netsetup == NULL) {
568 cprintf("%d %s\n", ERROR, strerror(errno));
573 while (ch = getc(netsetup), (ch > 0)) {
574 fbuf[strlen(fbuf)+1] = 0;
575 fbuf[strlen(fbuf)] = ch;
578 retcode = pclose(netsetup);
581 for (a=0; a<strlen(fbuf); ++a) {
582 if (fbuf[a] < 32) fbuf[a] = 32;
585 cprintf("%d %s\n", ERROR, fbuf);
589 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
591 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
598 * Generic routine to convert a login name to a full name (gecos)
599 * Returns nonzero if a conversion took place
601 int convert_login(char NameToConvert[]) {
605 pw = getpwnam(NameToConvert);
610 strcpy(NameToConvert, pw->pw_gecos);
611 for (a=0; a<strlen(NameToConvert); ++a) {
612 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
624 * Here's where it all begins.
626 int main(int argc, char **argv)
628 struct sockaddr_in fsin; /* Data for master socket */
629 int alen; /* Data for master socket */
630 int ssock; /* Descriptor for master socket */
631 THREAD SessThread; /* Thread descriptor */
632 pthread_attr_t attr; /* Thread attributes */
633 struct CitContext *con; /* Temporary context pointer */
634 char tracefile[128]; /* Name of file to log traces to */
635 int a, i; /* General-purpose variables */
639 /* specify default port name and trace file */
640 strcpy(tracefile, "");
642 /* parse command-line arguments */
643 for (a=1; a<argc; ++a) {
645 /* -t specifies where to log trace messages to */
646 if (!strncmp(argv[a], "-t", 2)) {
647 strcpy(tracefile, argv[a]);
648 strcpy(tracefile, &tracefile[2]);
649 freopen(tracefile, "r", stdin);
650 freopen(tracefile, "w", stdout);
651 freopen(tracefile, "w", stderr);
654 /* run in the background if -d was specified */
655 else if (!strcmp(argv[a], "-d")) {
656 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
659 /* -x specifies the desired logging level */
660 else if (!strncmp(argv[a], "-x", 2)) {
661 strcpy(convbuf, argv[a]);
662 verbosity = atoi(&convbuf[2]);
665 else if (!strncmp(argv[a], "-h", 2)) {
666 strcpy(convbuf, argv[a]);
667 strcpy(bbs_home_directory, &convbuf[2]);
671 /* any other parameter makes it crash and burn */
673 lprintf(1, "citserver: usage: ");
674 lprintf(1, "citserver [-tTraceFile]");
675 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
681 /* Tell 'em who's in da house */
682 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
683 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
684 lprintf(1, "All rights reserved.\n\n");
688 openlog("citserver",LOG_PID,LOG_USER);
689 /* Load site-specific parameters */
690 lprintf(7, "Loading citadel.config\n");
693 lprintf(7, "Initializing loadable modules\n");
694 snprintf(modpath, 128, "%s/modules", BBSDIR);
695 DLoader_Init(modpath);
696 lprintf(9, "Modules done initializing.\n");
698 /* Do non system dependent startup functions */
702 * Bind the server to our favourite port.
703 * There is no need to check for errors, because ig_tcp_server()
704 * exits if it doesn't succeed.
706 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
707 msock = ig_tcp_server(config.c_port_number, 5);
708 lprintf(7, "Listening on socket %d\n", msock);
711 * Now that we've bound the socket, change to the BBS user id
712 lprintf(7, "Changing uid to %d\n", BBSUID);
713 if (setuid(BBSUID) != 0) {
714 lprintf(3, "setuid() failed: %s", strerror(errno));
719 * Endless loop. Listen on the master socket. When a connection
720 * comes in, create a socket, a context, and a thread.
723 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
725 lprintf(2, "citserver: accept() failed: %s\n",
729 lprintf(7, "citserver: Client socket %d\n", ssock);
730 lprintf(9, "creating context\n");
731 con = CreateNewContext();
732 con->client_socket = ssock;
734 /* Set the SO_REUSEADDR socket option */
735 lprintf(9, "setting socket options\n");
737 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
740 /* set attributes for the new thread */
741 lprintf(9, "setting thread attributes\n");
742 pthread_attr_init(&attr);
743 pthread_attr_setdetachstate(&attr,
744 PTHREAD_CREATE_DETACHED);
746 /* now create the thread */
747 lprintf(9, "creating thread\n");
748 if (pthread_create(&SessThread, &attr,
749 (void* (*)(void*)) sd_context_loop,
753 "citserver: can't create thread: %s\n",
758 * (defunct -- now done at thread creation time)
759 * if (pthread_detach(&SessThread) != 0) {
761 * "citserver: can't detach thread: %s\n",
765 lprintf(9, "done!\n");