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>
37 #include <sys/select.h>
40 extern struct CitContext *ContextList;
41 extern struct config config;
42 extern char bbs_home_directory[];
43 extern int home_specified;
45 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
46 pthread_key_t MyConKey; /* TSD key for MyContext() */
48 int msock; /* master listening socket */
49 int verbosity = 3; /* Logging level */
53 * lprintf() ... Write logging information
55 void lprintf(int loglevel, const char *format, ...) {
60 if (loglevel <= verbosity) {
61 va_start(arg_ptr, format);
62 rc = vsprintf(buf, format, arg_ptr);
65 fprintf(stderr, "%s", buf);
73 * Some initialization stuff...
75 void init_sysdep(void) {
78 /* Set up a bunch of semaphores to be used for critical sections */
79 for (a=0; a<MAX_SEMAPHORES; ++a) {
80 pthread_mutex_init(&Critters[a], NULL);
84 * Set up a place to put thread-specific data.
85 * We only need a single pointer per thread - it points to the
86 * thread's CitContext structure in the ContextList linked list.
88 if (pthread_key_create(&MyConKey, NULL) != 0) {
89 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
93 * The action for unexpected signals and exceptions should be to
94 * call master_cleanup() to gracefully shut down the server.
96 signal(SIGINT, master_cleanup);
97 signal(SIGQUIT, master_cleanup);
98 signal(SIGHUP, master_cleanup);
99 signal(SIGTERM, master_cleanup);
104 * Obtain a semaphore lock to begin a critical section.
106 void begin_critical_section(int which_one)
110 lprintf(8, "begin_critical_section(%d)\n", which_one);
111 if (CC != NULL) hook_crit_get(CC->cs_pid, which_one);
113 /* Don't get interrupted during the critical section */
114 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
116 /* Obtain a semaphore */
117 pthread_mutex_lock(&Critters[which_one]);
119 if (CC != NULL) hook_crit_got(CC->cs_pid, which_one);
123 * Release a semaphore lock to end a critical section.
125 void end_critical_section(int which_one)
129 lprintf(8, " end_critical_section(%d)\n", which_one);
130 if (CC != NULL) hook_crit_end(CC->cs_pid, which_one);
132 /* Let go of the semaphore */
133 pthread_mutex_unlock(&Critters[which_one]);
135 /* If a cancel was sent during the critical section, do it now.
136 * Then re-enable thread cancellation.
138 pthread_testcancel();
139 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
140 pthread_testcancel();
147 * This is a generic function to set up a master socket for listening on
148 * a TCP port. The server shuts down if the bind fails.
150 int ig_tcp_server(int port_number, int queue_len)
152 struct sockaddr_in sin;
155 bzero((char *)&sin, sizeof(sin));
156 sin.sin_family = AF_INET;
157 sin.sin_addr.s_addr = INADDR_ANY;
159 if (port_number == 0) {
160 lprintf(1, "citserver: No port number specified. Run setup again.\n");
164 sin.sin_port = htons((u_short)port_number);
166 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
168 lprintf(1, "citserver: Can't create a socket: %s\n",
173 /* Set the SO_REUSEADDR socket option, because it makes sense. */
175 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
177 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
178 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
182 if (listen(s, queue_len) < 0) {
183 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
192 * Return a pointer to a thread's own CitContext structure (old)
193 * NOTE: this version of MyContext() is commented out because it is no longer
194 * in use. It was written before I discovered TSD keys. This
195 * version pounds through the context list until it finds the one matching
196 * the currently running thread. It remains here, commented out, in case it
197 * is needed for future ports to threading libraries which have the equivalent
198 * of pthread_self() but not pthread_key_create() and its ilk.
200 * struct CitContext *MyContext() {
201 * struct CitContext *ptr;
204 * me = pthread_self();
205 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
206 * if (ptr->mythread == me) return(ptr);
213 * Return a pointer to a thread's own CitContext structure (new)
215 struct CitContext *MyContext(void) {
216 return (struct CitContext *) pthread_getspecific(MyConKey);
221 * Wedge our way into the context list.
223 struct CitContext *CreateNewContext(void) {
224 struct CitContext *me;
226 lprintf(9, "CreateNewContext: calling malloc()\n");
227 me = (struct CitContext *) malloc(sizeof(struct CitContext));
229 lprintf(1, "citserver: can't allocate memory!!\n");
233 begin_critical_section(S_SESSION_TABLE);
234 me->next = ContextList;
236 end_critical_section(S_SESSION_TABLE);
241 * Add a thread's thread ID to the context
243 void InitMyContext(struct CitContext *con)
247 con->mythread = pthread_self();
248 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
249 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
250 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
251 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
257 * Remove a context from the context list.
259 void RemoveContext(struct CitContext *con)
261 struct CitContext *ptr;
263 lprintf(7, "Starting RemoveContext()\n");
264 lprintf(9, "session count before RemoveContext is %d\n", session_count());
266 lprintf(7, "WARNING: RemoveContext() called with null!\n");
270 begin_critical_section(S_SESSION_TABLE);
271 lprintf(7, "Closing socket %d\n", con->client_socket);
272 close(con->client_socket);
274 if (ContextList==con) {
275 ContextList = ContextList->next;
278 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
279 if (ptr->next == con) {
280 ptr->next = ptr->next->next;
287 lprintf(9, "session count after RemoveContext is %d\n", session_count());
289 lprintf(7, "Done with RemoveContext\n");
290 end_critical_section(S_SESSION_TABLE);
295 * Return the number of sessions currently running.
296 * (This should probably be moved out of sysdep.c)
298 int session_count(void) {
299 struct CitContext *ptr;
302 lprintf(9, "session_count() starting\n");
303 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
305 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
308 lprintf(9, "session_count() finishing\n");
314 * client_write() ... Send binary data to the client.
316 void client_write(char *buf, int nbytes)
318 int bytes_written = 0;
320 while (bytes_written < nbytes) {
321 retval = write(CC->client_socket, &buf[bytes_written],
322 nbytes - bytes_written);
324 lprintf(2, "client_write() failed: %s\n",
328 bytes_written = bytes_written + retval;
334 * cprintf() ... Send formatted printable data to the client. It is
335 * implemented in terms of client_write() but remains in
336 * sysdep.c in case we port to somewhere without va_args...
338 void cprintf(const char *format, ...) {
343 va_start(arg_ptr, format);
344 rc = vsprintf(buf, format, arg_ptr);
347 client_write(buf, strlen(buf));
352 * Read data from the client socket.
354 * 1 Requested number of bytes has been read.
355 * 0 Request timed out.
356 * If the socket breaks, the session is immediately terminated.
358 int client_read_to(char *buf, int bytes, int timeout)
368 FD_SET(CC->client_socket, &rfds);
372 retval = select( (CC->client_socket)+1,
373 &rfds, NULL, NULL, &tv);
374 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
378 rlen = read(CC->client_socket, &buf[len], bytes-len);
380 lprintf(2, "client_read() failed: %s\n",
390 * Read data from the client socket with default timeout.
391 * (This is implemented in terms of client_read_to() and could be
392 * justifiably moved out of sysdep.c)
394 int client_read(char *buf, int bytes)
396 return(client_read_to(buf, bytes, config.c_sleeping));
401 * client_gets() ... Get a LF-terminated line of text from the client.
402 * (This is implemented in terms of client_read() and could be
403 * justifiably moved out of sysdep.c)
405 int client_gets(char *buf)
409 /* Clear the buffer, and read one character at a time.
413 if (strlen(buf)<255) {
414 buf[strlen(buf) + 1] = 0;
415 retval = client_read(&buf[strlen(buf)], 1);
417 } while ( (buf[strlen(buf)-1] != 10) && (retval==1) );
419 /* Strip the trailing newline.
421 if (strlen(buf) > 0) buf[strlen(buf)-1] = 0;
428 * The system-dependent part of master_cleanup() - close the master socket.
430 void sysdep_master_cleanup(void) {
431 lprintf(3, "Closing master socket %d\n", msock);
436 * Cleanup routine to be called when one thread is shutting down.
438 void cleanup(int exit_code)
440 /* Terminate the thread.
441 * Its cleanup handler will call cleanup_stuff()
443 lprintf(7, "Calling pthread_exit()\n");
448 * Terminate another session.
450 void kill_session(int session_to_kill) {
451 struct CitContext *ptr;
453 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
454 if (ptr->cs_pid == session_to_kill) {
455 pthread_cancel(ptr->mythread);
462 * The system-dependent wrapper around the main context loop.
464 void sd_context_loop(struct CitContext *con) {
465 pthread_cleanup_push(*cleanup_stuff, NULL);
467 pthread_cleanup_pop(0);
472 * Start running as a daemon. Only close stdio if do_close_stdio is set.
474 void start_daemon(int do_close_stdio) {
475 if (do_close_stdio) {
480 signal(SIGHUP,SIG_IGN);
481 signal(SIGINT,SIG_IGN);
482 signal(SIGQUIT,SIG_IGN);
483 if (fork()!=0) exit(0);
489 * Tie in to the 'netsetup' program.
491 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
493 void cmd_nset(char *cmdbuf)
500 char netsetup_args[3][256];
502 if (CC->usersupp.axlevel < 6) {
503 cprintf("%d Higher access required.\n",
504 ERROR + HIGHER_ACCESS_REQUIRED);
508 for (a=1; a<=3; ++a) {
509 if (num_parms(cmdbuf) >= a) {
510 extract(netsetup_args[a-1], cmdbuf, a-1);
511 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
512 if (netsetup_args[a-1][b] == 34) {
513 netsetup_args[a-1][b] = '_';
518 netsetup_args[a-1][0] = 0;
522 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
523 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
524 netsetup = popen(fbuf, "r");
525 if (netsetup == NULL) {
526 cprintf("%d %s\n", ERROR, strerror(errno));
531 while (ch = getc(netsetup), (ch > 0)) {
532 fbuf[strlen(fbuf)+1] = 0;
533 fbuf[strlen(fbuf)] = ch;
536 retcode = pclose(netsetup);
539 for (a=0; a<strlen(fbuf); ++a) {
540 if (fbuf[a] < 32) fbuf[a] = 32;
543 cprintf("%d %s\n", ERROR, fbuf);
547 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
549 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
556 * Generic routine to convert a login name to a full name (gecos)
557 * Returns nonzero if a conversion took place
559 int convert_login(char NameToConvert[]) {
563 pw = getpwnam(NameToConvert);
568 strcpy(NameToConvert, pw->pw_gecos);
569 for (a=0; a<strlen(NameToConvert); ++a) {
570 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
582 * Here's where it all begins.
584 int main(int argc, char **argv)
586 struct sockaddr_in fsin; /* Data for master socket */
587 int alen; /* Data for master socket */
588 int ssock; /* Descriptor for master socket */
589 THREAD SessThread; /* Thread descriptor */
590 pthread_attr_t attr; /* Thread attributes */
591 struct CitContext *con; /* Temporary context pointer */
592 char tracefile[128]; /* Name of file to log traces to */
593 int a, i; /* General-purpose variables */
596 /* specify default port name and trace file */
597 strcpy(tracefile, "");
599 /* parse command-line arguments */
600 for (a=1; a<argc; ++a) {
602 /* -t specifies where to log trace messages to */
603 if (!strncmp(argv[a], "-t", 2)) {
604 strcpy(tracefile, argv[a]);
605 strcpy(tracefile, &tracefile[2]);
606 freopen(tracefile, "r", stdin);
607 freopen(tracefile, "w", stdout);
608 freopen(tracefile, "w", stderr);
611 /* run in the background if -d was specified */
612 else if (!strcmp(argv[a], "-d")) {
613 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
616 /* -x specifies the desired logging level */
617 else if (!strncmp(argv[a], "-x", 2)) {
618 strcpy(convbuf, argv[a]);
619 verbosity = atoi(&convbuf[2]);
622 else if (!strncmp(argv[a], "-h", 2)) {
623 strcpy(convbuf, argv[a]);
624 strcpy(bbs_home_directory, &convbuf[2]);
628 /* any other parameter makes it crash and burn */
630 lprintf(1, "citserver: usage: ");
631 lprintf(1, "citserver [-tTraceFile]");
632 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
638 /* Tell 'em who's in da house */
639 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
640 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
641 lprintf(1, "All rights reserved.\n\n");
645 openlog("citserver",LOG_PID,LOG_USER);
647 /* Load site-specific parameters */
648 lprintf(7, "Loading citadel.config\n");
652 /* Databases must be opened *after* config is loaded, otherwise we might
653 * end up working in the wrong directory.
655 lprintf(7, "Opening databases\n");
658 lprintf(7, "Checking floor reference counts\n");
662 * Bind the server to our favourite port.
663 * There is no need to check for errors, because ig_tcp_server()
664 * exits if it doesn't succeed.
666 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
667 msock = ig_tcp_server(config.c_port_number, 5);
668 lprintf(7, "Listening on socket %d\n", msock);
671 * Now that we've bound the socket, change to the BBS user id
672 lprintf(7, "Changing uid to %d\n", BBSUID);
673 if (setuid(BBSUID) != 0) {
674 lprintf(3, "setuid() failed: %s", strerror(errno));
679 * Endless loop. Listen on the master socket. When a connection
680 * comes in, create a socket, a context, and a thread.
683 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
685 lprintf(2, "citserver: accept() failed: %s\n",
689 lprintf(7, "citserver: Client socket %d\n", ssock);
690 lprintf(9, "creating context\n");
691 con = CreateNewContext();
692 con->client_socket = ssock;
694 /* Set the SO_REUSEADDR socket option */
695 lprintf(9, "setting socket options\n");
697 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
700 /* set attributes for the new thread */
701 lprintf(9, "setting thread attributes\n");
702 pthread_attr_init(&attr);
703 pthread_attr_setdetachstate(&attr,
704 PTHREAD_CREATE_DETACHED);
706 /* now create the thread */
707 lprintf(9, "creating thread\n");
708 if (pthread_create(&SessThread, &attr, (void *)sd_context_loop,
711 "citserver: can't create thread: %s\n",
716 * (defunct -- now done at thread creation time)
717 * if (pthread_detach(&SessThread) != 0) {
719 * "citserver: can't detach thread: %s\n",
723 lprintf(9, "done!\n");