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>
24 #include <netinet/in.h>
34 #include "sysdep_decls.h"
35 #include "citserver.h"
40 #include "housekeeping.h"
43 #include <sys/select.h>
46 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
47 pthread_key_t MyConKey; /* TSD key for MyContext() */
49 int msock; /* master listening socket */
50 int verbosity = 3; /* Logging level */
54 * lprintf() ... Write logging information
56 void lprintf(int loglevel, const char *format, ...) {
61 if (loglevel <= verbosity) {
62 va_start(arg_ptr, format);
63 rc = vsprintf(buf, format, arg_ptr);
66 fprintf(stderr, "%s", buf);
74 * Some initialization stuff...
76 void init_sysdep(void) {
79 /* Set up a bunch of semaphores to be used for critical sections */
80 for (a=0; a<MAX_SEMAPHORES; ++a) {
81 pthread_mutex_init(&Critters[a], NULL);
85 * Set up a place to put thread-specific data.
86 * We only need a single pointer per thread - it points to the
87 * thread's CitContext structure in the ContextList linked list.
89 if (pthread_key_create(&MyConKey, NULL) != 0) {
90 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
94 * The action for unexpected signals and exceptions should be to
95 * call master_cleanup() to gracefully shut down the server.
97 signal(SIGINT, (void(*)(int))master_cleanup);
98 signal(SIGQUIT, (void(*)(int))master_cleanup);
99 signal(SIGHUP, (void(*)(int))master_cleanup);
100 signal(SIGTERM, (void(*)(int))master_cleanup);
105 * Obtain a semaphore lock to begin a critical section.
107 void begin_critical_section(int which_one)
111 lprintf(8, "begin_critical_section(%d)\n", which_one);
112 if (CC != NULL) hook_crit_get(CC->cs_pid, which_one);
114 /* Don't get interrupted during the critical section */
115 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
117 /* Obtain a semaphore */
118 pthread_mutex_lock(&Critters[which_one]);
120 if (CC != NULL) hook_crit_got(CC->cs_pid, which_one);
124 * Release a semaphore lock to end a critical section.
126 void end_critical_section(int which_one)
130 lprintf(8, " end_critical_section(%d)\n", which_one);
131 if (CC != NULL) hook_crit_end(CC->cs_pid, which_one);
133 /* Let go of the semaphore */
134 pthread_mutex_unlock(&Critters[which_one]);
136 /* If a cancel was sent during the critical section, do it now.
137 * Then re-enable thread cancellation.
139 pthread_testcancel();
140 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
141 pthread_testcancel();
148 * This is a generic function to set up a master socket for listening on
149 * a TCP port. The server shuts down if the bind fails.
151 int ig_tcp_server(int port_number, int queue_len)
153 struct sockaddr_in sin;
156 bzero((char *)&sin, sizeof(sin));
157 sin.sin_family = AF_INET;
158 sin.sin_addr.s_addr = INADDR_ANY;
160 if (port_number == 0) {
161 lprintf(1, "citserver: No port number specified. Run setup again.\n");
165 sin.sin_port = htons((u_short)port_number);
167 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
169 lprintf(1, "citserver: Can't create a socket: %s\n",
174 /* Set the SO_REUSEADDR socket option, because it makes sense. */
176 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
178 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
179 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
183 if (listen(s, queue_len) < 0) {
184 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
193 * Return a pointer to a thread's own CitContext structure (old)
194 * NOTE: this version of MyContext() is commented out because it is no longer
195 * in use. It was written before I discovered TSD keys. This
196 * version pounds through the context list until it finds the one matching
197 * the currently running thread. It remains here, commented out, in case it
198 * is needed for future ports to threading libraries which have the equivalent
199 * of pthread_self() but not pthread_key_create() and its ilk.
201 * struct CitContext *MyContext() {
202 * struct CitContext *ptr;
205 * me = pthread_self();
206 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
207 * if (ptr->mythread == me) return(ptr);
214 * Return a pointer to a thread's own CitContext structure (new)
216 struct CitContext *MyContext(void) {
217 return (struct CitContext *) pthread_getspecific(MyConKey);
222 * Wedge our way into the context list.
224 struct CitContext *CreateNewContext(void) {
225 struct CitContext *me;
227 lprintf(9, "CreateNewContext: calling malloc()\n");
228 me = (struct CitContext *) malloc(sizeof(struct CitContext));
230 lprintf(1, "citserver: can't allocate memory!!\n");
233 bzero(me, sizeof(struct CitContext));
235 begin_critical_section(S_SESSION_TABLE);
236 me->next = ContextList;
238 end_critical_section(S_SESSION_TABLE);
243 * Add a thread's thread ID to the context
245 void InitMyContext(struct CitContext *con)
249 con->mythread = pthread_self();
250 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
251 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
252 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
253 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
259 * Remove a context from the context list.
261 void RemoveContext(struct CitContext *con)
263 struct CitContext *ptr;
265 lprintf(7, "Starting RemoveContext()\n");
266 lprintf(9, "session count before RemoveContext is %d\n", session_count());
268 lprintf(7, "WARNING: RemoveContext() called with null!\n");
272 begin_critical_section(S_SESSION_TABLE);
273 lprintf(7, "Closing socket %d\n", con->client_socket);
274 close(con->client_socket);
276 if (ContextList==con) {
277 ContextList = ContextList->next;
280 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
281 if (ptr->next == con) {
282 ptr->next = ptr->next->next;
289 lprintf(9, "session count after RemoveContext is %d\n", session_count());
291 lprintf(7, "Done with RemoveContext\n");
292 end_critical_section(S_SESSION_TABLE);
297 * Return the number of sessions currently running.
298 * (This should probably be moved out of sysdep.c)
300 int session_count(void) {
301 struct CitContext *ptr;
304 lprintf(9, "session_count() starting\n");
305 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
307 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
310 lprintf(9, "session_count() finishing\n");
316 * client_write() ... Send binary data to the client.
318 void client_write(char *buf, int nbytes)
320 int bytes_written = 0;
322 while (bytes_written < nbytes) {
323 retval = write(CC->client_socket, &buf[bytes_written],
324 nbytes - bytes_written);
326 lprintf(2, "client_write() failed: %s\n",
330 bytes_written = bytes_written + retval;
336 * cprintf() ... Send formatted printable data to the client. It is
337 * implemented in terms of client_write() but remains in
338 * sysdep.c in case we port to somewhere without va_args...
340 void cprintf(const char *format, ...) {
345 va_start(arg_ptr, format);
346 rc = vsprintf(buf, format, arg_ptr);
349 client_write(buf, strlen(buf));
354 * Read data from the client socket.
356 * 1 Requested number of bytes has been read.
357 * 0 Request timed out.
358 * If the socket breaks, the session is immediately terminated.
360 int client_read_to(char *buf, int bytes, int timeout)
370 FD_SET(CC->client_socket, &rfds);
374 retval = select( (CC->client_socket)+1,
375 &rfds, NULL, NULL, &tv);
376 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
380 rlen = read(CC->client_socket, &buf[len], bytes-len);
382 lprintf(2, "client_read() failed: %s\n",
392 * Read data from the client socket with default timeout.
393 * (This is implemented in terms of client_read_to() and could be
394 * justifiably moved out of sysdep.c)
396 int client_read(char *buf, int bytes)
398 return(client_read_to(buf, bytes, config.c_sleeping));
403 * client_gets() ... Get a LF-terminated line of text from the client.
404 * (This is implemented in terms of client_read() and could be
405 * justifiably moved out of sysdep.c)
407 int client_gets(char *buf)
411 /* Clear the buffer, and read one character at a time.
415 if (strlen(buf)<255) {
416 buf[strlen(buf) + 1] = 0;
417 retval = client_read(&buf[strlen(buf)], 1);
419 } while ( (buf[strlen(buf)-1] != 10) && (retval==1) );
421 /* Strip the trailing newline.
423 if (strlen(buf) > 0) buf[strlen(buf)-1] = 0;
430 * The system-dependent part of master_cleanup() - close the master socket.
432 void sysdep_master_cleanup(void) {
433 lprintf(7, "Closing master socket %d\n", msock);
438 * Cleanup routine to be called when one thread is shutting down.
440 void cleanup(int exit_code)
442 /* Terminate the thread.
443 * Its cleanup handler will call cleanup_stuff()
445 lprintf(7, "Calling pthread_exit()\n");
450 * Terminate another session.
452 void kill_session(int session_to_kill) {
453 struct CitContext *ptr;
455 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
456 if (ptr->cs_pid == session_to_kill) {
457 pthread_cancel(ptr->mythread);
464 * The system-dependent wrapper around the main context loop.
466 void sd_context_loop(struct CitContext *con) {
467 pthread_cleanup_push(*cleanup_stuff, NULL);
469 pthread_cleanup_pop(0);
474 * Start running as a daemon. Only close stdio if do_close_stdio is set.
476 void start_daemon(int do_close_stdio) {
477 if (do_close_stdio) {
482 signal(SIGHUP,SIG_IGN);
483 signal(SIGINT,SIG_IGN);
484 signal(SIGQUIT,SIG_IGN);
485 if (fork()!=0) exit(0);
491 * Tie in to the 'netsetup' program.
493 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
495 void cmd_nset(char *cmdbuf)
502 char netsetup_args[3][256];
504 if (CC->usersupp.axlevel < 6) {
505 cprintf("%d Higher access required.\n",
506 ERROR + HIGHER_ACCESS_REQUIRED);
510 for (a=1; a<=3; ++a) {
511 if (num_parms(cmdbuf) >= a) {
512 extract(netsetup_args[a-1], cmdbuf, a-1);
513 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
514 if (netsetup_args[a-1][b] == 34) {
515 netsetup_args[a-1][b] = '_';
520 netsetup_args[a-1][0] = 0;
524 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
525 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
526 netsetup = popen(fbuf, "r");
527 if (netsetup == NULL) {
528 cprintf("%d %s\n", ERROR, strerror(errno));
533 while (ch = getc(netsetup), (ch > 0)) {
534 fbuf[strlen(fbuf)+1] = 0;
535 fbuf[strlen(fbuf)] = ch;
538 retcode = pclose(netsetup);
541 for (a=0; a<strlen(fbuf); ++a) {
542 if (fbuf[a] < 32) fbuf[a] = 32;
545 cprintf("%d %s\n", ERROR, fbuf);
549 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
551 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
558 * Generic routine to convert a login name to a full name (gecos)
559 * Returns nonzero if a conversion took place
561 int convert_login(char NameToConvert[]) {
565 pw = getpwnam(NameToConvert);
570 strcpy(NameToConvert, pw->pw_gecos);
571 for (a=0; a<strlen(NameToConvert); ++a) {
572 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
584 * Here's where it all begins.
586 int main(int argc, char **argv)
588 struct sockaddr_in fsin; /* Data for master socket */
589 int alen; /* Data for master socket */
590 int ssock; /* Descriptor for master socket */
591 THREAD SessThread; /* Thread descriptor */
592 pthread_attr_t attr; /* Thread attributes */
593 struct CitContext *con; /* Temporary context pointer */
594 char tracefile[128]; /* Name of file to log traces to */
595 int a, i; /* General-purpose variables */
598 /* specify default port name and trace file */
599 strcpy(tracefile, "");
601 /* parse command-line arguments */
602 for (a=1; a<argc; ++a) {
604 /* -t specifies where to log trace messages to */
605 if (!strncmp(argv[a], "-t", 2)) {
606 strcpy(tracefile, argv[a]);
607 strcpy(tracefile, &tracefile[2]);
608 freopen(tracefile, "r", stdin);
609 freopen(tracefile, "w", stdout);
610 freopen(tracefile, "w", stderr);
613 /* run in the background if -d was specified */
614 else if (!strcmp(argv[a], "-d")) {
615 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
618 /* -x specifies the desired logging level */
619 else if (!strncmp(argv[a], "-x", 2)) {
620 strcpy(convbuf, argv[a]);
621 verbosity = atoi(&convbuf[2]);
624 else if (!strncmp(argv[a], "-h", 2)) {
625 strcpy(convbuf, argv[a]);
626 strcpy(bbs_home_directory, &convbuf[2]);
630 /* any other parameter makes it crash and burn */
632 lprintf(1, "citserver: usage: ");
633 lprintf(1, "citserver [-tTraceFile]");
634 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
640 /* Tell 'em who's in da house */
641 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
642 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
643 lprintf(1, "All rights reserved.\n\n");
647 openlog("citserver",LOG_PID,LOG_USER);
649 /* Load site-specific parameters */
650 lprintf(7, "Loading citadel.config\n");
654 /* Databases must be opened *after* config is loaded, otherwise we might
655 * end up working in the wrong directory.
657 lprintf(7, "Opening databases\n");
660 lprintf(7, "Checking floor reference counts\n");
664 * Bind the server to our favourite port.
665 * There is no need to check for errors, because ig_tcp_server()
666 * exits if it doesn't succeed.
668 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
669 msock = ig_tcp_server(config.c_port_number, 5);
670 lprintf(7, "Listening on socket %d\n", msock);
673 * Now that we've bound the socket, change to the BBS user id
674 lprintf(7, "Changing uid to %d\n", BBSUID);
675 if (setuid(BBSUID) != 0) {
676 lprintf(3, "setuid() failed: %s", strerror(errno));
681 * Endless loop. Listen on the master socket. When a connection
682 * comes in, create a socket, a context, and a thread.
685 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
687 lprintf(2, "citserver: accept() failed: %s\n",
691 lprintf(7, "citserver: Client socket %d\n", ssock);
692 lprintf(9, "creating context\n");
693 con = CreateNewContext();
694 con->client_socket = ssock;
696 /* Set the SO_REUSEADDR socket option */
697 lprintf(9, "setting socket options\n");
699 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
702 /* set attributes for the new thread */
703 lprintf(9, "setting thread attributes\n");
704 pthread_attr_init(&attr);
705 pthread_attr_setdetachstate(&attr,
706 PTHREAD_CREATE_DETACHED);
708 /* now create the thread */
709 lprintf(9, "creating thread\n");
710 if (pthread_create(&SessThread, &attr, (void *)sd_context_loop,
713 "citserver: can't create thread: %s\n",
718 * (defunct -- now done at thread creation time)
719 * if (pthread_detach(&SessThread) != 0) {
721 * "citserver: can't detach thread: %s\n",
725 lprintf(9, "done!\n");