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.
24 #include <sys/types.h>
26 #include <sys/socket.h>
29 #include <netinet/in.h>
41 #include "sysdep_decls.h"
42 #include "citserver.h"
46 #include "housekeeping.h"
47 #include "dynloader.h"
50 #ifdef HAVE_SYS_SELECT_H
51 #include <sys/select.h>
58 #ifdef DEBUG_MEMORY_LEAKS
59 struct TheHeap *heap = NULL;
62 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
63 pthread_key_t MyConKey; /* TSD key for MyContext() */
65 int msock; /* master listening socket */
66 int verbosity = 3; /* Logging level */
68 struct CitContext masterCC;
72 * lprintf() ... Write logging information
74 void lprintf(int loglevel, const char *format, ...) {
78 va_start(arg_ptr, format);
79 vsprintf(buf, format, arg_ptr);
82 if (loglevel <= verbosity) {
83 fprintf(stderr, "%s", buf);
87 PerformLogHooks(loglevel, buf);
92 #ifdef DEBUG_MEMORY_LEAKS
93 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
98 if (ptr == NULL) return(NULL);
100 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
101 strcpy(hptr->h_file, tfile);
102 hptr->h_line = tline;
110 void tracked_free(void *ptr) {
111 struct TheHeap *hptr, *freeme;
113 if (heap->h_ptr == ptr) {
119 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
120 if (hptr->next->h_ptr == ptr) {
122 hptr->next = hptr->next->next;
131 void *tracked_realloc(void *ptr, size_t size) {
133 struct TheHeap *hptr;
135 newptr = realloc(ptr, size);
137 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
138 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
145 void dump_tracked() {
146 struct TheHeap *hptr;
148 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
149 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
150 cprintf("%20s %5d\n",
151 hptr->h_file, hptr->h_line);
160 * Some initialization stuff...
162 void init_sysdep(void) {
165 /* Set up a bunch of semaphores to be used for critical sections */
166 for (a=0; a<MAX_SEMAPHORES; ++a) {
167 pthread_mutex_init(&Critters[a], NULL);
171 * Set up a place to put thread-specific data.
172 * We only need a single pointer per thread - it points to the
173 * thread's CitContext structure in the ContextList linked list.
175 if (pthread_key_create(&MyConKey, NULL) != 0) {
176 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
180 * The action for unexpected signals and exceptions should be to
181 * call master_cleanup() to gracefully shut down the server.
183 signal(SIGINT, (void(*)(int))master_cleanup);
184 signal(SIGQUIT, (void(*)(int))master_cleanup);
185 signal(SIGHUP, (void(*)(int))master_cleanup);
186 signal(SIGTERM, (void(*)(int))master_cleanup);
187 signal(SIGPIPE, SIG_IGN);
192 * Obtain a semaphore lock to begin a critical section.
194 void begin_critical_section(int which_one)
198 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
200 /* Don't get interrupted during the critical section */
201 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
203 /* Obtain a semaphore */
204 pthread_mutex_lock(&Critters[which_one]);
209 * Release a semaphore lock to end a critical section.
211 void end_critical_section(int which_one)
215 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
217 /* Let go of the semaphore */
218 pthread_mutex_unlock(&Critters[which_one]);
220 /* If a cancel was sent during the critical section, do it now.
221 * Then re-enable thread cancellation.
223 pthread_testcancel();
224 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
225 pthread_testcancel();
232 * This is a generic function to set up a master socket for listening on
233 * a TCP port. The server shuts down if the bind fails.
235 int ig_tcp_server(int port_number, int queue_len)
237 struct sockaddr_in sin;
240 memset(&sin, 0, sizeof(sin));
241 sin.sin_family = AF_INET;
242 sin.sin_addr.s_addr = INADDR_ANY;
244 if (port_number == 0) {
246 "citserver: No port number specified. Run setup.\n");
250 sin.sin_port = htons((u_short)port_number);
252 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
254 lprintf(1, "citserver: Can't create a socket: %s\n",
259 /* Set the SO_REUSEADDR socket option, because it makes sense. */
261 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
263 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
264 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
268 if (listen(s, queue_len) < 0) {
269 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
278 * Return a pointer to a thread's own CitContext structure (old)
279 * NOTE: this version of MyContext() is commented out because it is no longer
280 * in use. It was written before I discovered TSD keys. This
281 * version pounds through the context list until it finds the one matching
282 * the currently running thread. It remains here, commented out, in case it
283 * is needed for future ports to threading libraries which have the equivalent
284 * of pthread_self() but not pthread_key_create() and its ilk.
286 * struct CitContext *MyContext() {
287 * struct CitContext *ptr;
290 * me = pthread_self();
291 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
292 * if (ptr->mythread == me) return(ptr);
299 * Return a pointer to a thread's own CitContext structure (new)
301 struct CitContext *MyContext(void) {
302 struct CitContext *retCC;
303 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
304 if (retCC == NULL) retCC = &masterCC;
310 * Wedge our way into the context list.
312 struct CitContext *CreateNewContext(void) {
313 struct CitContext *me;
315 lprintf(9, "CreateNewContext: calling malloc()\n");
316 me = (struct CitContext *) mallok(sizeof(struct CitContext));
318 lprintf(1, "citserver: can't allocate memory!!\n");
321 memset(me, 0, sizeof(struct CitContext));
323 begin_critical_section(S_SESSION_TABLE);
324 me->next = ContextList;
326 end_critical_section(S_SESSION_TABLE);
331 * Add a thread's thread ID to the context
333 void InitMyContext(struct CitContext *con)
337 con->mythread = pthread_self();
338 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
339 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
340 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
341 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
347 * Remove a context from the context list.
349 void RemoveContext(struct CitContext *con)
351 struct CitContext *ptr;
353 lprintf(7, "Starting RemoveContext()\n");
354 lprintf(9, "Session count before RemoveContext is %d\n",
357 lprintf(7, "WARNING: RemoveContext() called with null!\n");
362 * session_count() starts its own S_SESSION_TABLE critical section;
363 * so do not call it from within this loop.
365 begin_critical_section(S_SESSION_TABLE);
366 lprintf(7, "Closing socket %d\n", con->client_socket);
367 close(con->client_socket);
369 lprintf(9, "Dereferencing session context\n");
370 if (ContextList==con) {
371 ContextList = ContextList->next;
374 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
375 if (ptr->next == con) {
376 ptr->next = con->next;
381 lprintf(9, "Freeing session context...\n");
383 lprintf(9, "...done.\n");
384 end_critical_section(S_SESSION_TABLE);
386 lprintf(9, "Session count after RemoveContext is %d\n",
389 lprintf(7, "Done with RemoveContext\n");
394 * Return the number of sessions currently running.
395 * (This should probably be moved out of sysdep.c)
397 int session_count(void) {
398 struct CitContext *ptr;
401 lprintf(9, "session_count() starting\n");
402 begin_critical_section(S_SESSION_TABLE);
403 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
405 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
407 end_critical_section(S_SESSION_TABLE);
409 lprintf(9, "session_count() finishing\n");
415 * client_write() ... Send binary data to the client.
417 void client_write(char *buf, int nbytes)
419 int bytes_written = 0;
421 while (bytes_written < nbytes) {
422 retval = write(CC->client_socket, &buf[bytes_written],
423 nbytes - bytes_written);
425 lprintf(2, "client_write() failed: %s\n",
429 bytes_written = bytes_written + retval;
435 * cprintf() ... Send formatted printable data to the client. It is
436 * implemented in terms of client_write() but remains in
437 * sysdep.c in case we port to somewhere without va_args...
439 void cprintf(const char *format, ...) {
443 va_start(arg_ptr, format);
444 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
445 buf[sizeof buf - 2] = '\n';
446 client_write(buf, strlen(buf));
452 * Read data from the client socket.
454 * 1 Requested number of bytes has been read.
455 * 0 Request timed out.
456 * If the socket breaks, the session is immediately terminated.
458 int client_read_to(char *buf, int bytes, int timeout)
468 FD_SET(CC->client_socket, &rfds);
472 retval = select( (CC->client_socket)+1,
473 &rfds, NULL, NULL, &tv);
474 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
478 rlen = read(CC->client_socket, &buf[len], bytes-len);
480 lprintf(2, "client_read() failed: %s\n",
490 * Read data from the client socket with default timeout.
491 * (This is implemented in terms of client_read_to() and could be
492 * justifiably moved out of sysdep.c)
494 int client_read(char *buf, int bytes)
496 return(client_read_to(buf, bytes, config.c_sleeping));
501 * client_gets() ... Get a LF-terminated line of text from the client.
502 * (This is implemented in terms of client_read() and could be
503 * justifiably moved out of sysdep.c)
505 int client_gets(char *buf)
509 /* Read one character at a time.
512 retval = client_read(&buf[i], 1);
513 if (retval != 1 || buf[i] == '\n' || i == 255)
517 /* If we got a long line, discard characters until the newline.
520 while (buf[i] != '\n' && retval == 1)
521 retval = client_read(&buf[i], 1);
523 /* Strip the trailing newline and any trailing nonprintables (cr's)
526 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
527 buf[strlen(buf)-1] = 0;
534 * The system-dependent part of master_cleanup() - close the master socket.
536 void sysdep_master_cleanup(void) {
537 lprintf(7, "Closing master socket %d\n", msock);
542 * Cleanup routine to be called when one thread is shutting down.
544 void cleanup(int exit_code)
546 /* Terminate the thread.
547 * Its cleanup handler will call cleanup_stuff()
549 lprintf(7, "Calling pthread_exit()\n");
554 * Terminate another session.
556 void kill_session(int session_to_kill) {
557 struct CitContext *ptr;
560 lprintf(9, "kill_session() scanning for thread to cancel...\n");
561 begin_critical_section(S_SESSION_TABLE);
562 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
563 if (ptr->cs_pid == session_to_kill) {
564 killme = ptr->mythread;
567 end_critical_section(S_SESSION_TABLE);
568 lprintf(9, "kill_session() finished scanning.\n");
571 lprintf(9, "calling pthread_cancel()\n");
572 pthread_cancel(killme);
578 * The system-dependent wrapper around the main context loop.
580 void *sd_context_loop(struct CitContext *con) {
581 pthread_cleanup_push(*cleanup_stuff, NULL);
583 pthread_cleanup_pop(0);
589 * Start running as a daemon. Only close stdio if do_close_stdio is set.
591 void start_daemon(int do_close_stdio) {
592 if (do_close_stdio) {
597 signal(SIGHUP,SIG_IGN);
598 signal(SIGINT,SIG_IGN);
599 signal(SIGQUIT,SIG_IGN);
600 if (fork()!=0) exit(0);
606 * Tie in to the 'netsetup' program.
608 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
610 void cmd_nset(char *cmdbuf)
617 char netsetup_args[3][256];
619 if (CC->usersupp.axlevel < 6) {
620 cprintf("%d Higher access required.\n",
621 ERROR + HIGHER_ACCESS_REQUIRED);
625 for (a=1; a<=3; ++a) {
626 if (num_parms(cmdbuf) >= a) {
627 extract(netsetup_args[a-1], cmdbuf, a-1);
628 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
629 if (netsetup_args[a-1][b] == 34) {
630 netsetup_args[a-1][b] = '_';
635 netsetup_args[a-1][0] = 0;
639 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
640 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
641 netsetup = popen(fbuf, "r");
642 if (netsetup == NULL) {
643 cprintf("%d %s\n", ERROR, strerror(errno));
648 while (ch = getc(netsetup), (ch > 0)) {
649 fbuf[strlen(fbuf)+1] = 0;
650 fbuf[strlen(fbuf)] = ch;
653 retcode = pclose(netsetup);
656 for (a=0; a<strlen(fbuf); ++a) {
657 if (fbuf[a] < 32) fbuf[a] = 32;
660 cprintf("%d %s\n", ERROR, fbuf);
664 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
666 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
673 * Generic routine to convert a login name to a full name (gecos)
674 * Returns nonzero if a conversion took place
676 int convert_login(char NameToConvert[]) {
680 pw = getpwnam(NameToConvert);
685 strcpy(NameToConvert, pw->pw_gecos);
686 for (a=0; a<strlen(NameToConvert); ++a) {
687 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
699 * Here's where it all begins.
701 int main(int argc, char **argv)
703 struct sockaddr_in fsin; /* Data for master socket */
704 int alen; /* Data for master socket */
705 int ssock; /* Descriptor for master socket */
706 THREAD SessThread; /* Thread descriptor */
707 pthread_attr_t attr; /* Thread attributes */
708 struct CitContext *con; /* Temporary context pointer */
709 char tracefile[128]; /* Name of file to log traces to */
710 int a, i; /* General-purpose variables */
713 /* specify default port name and trace file */
714 strcpy(tracefile, "");
716 /* parse command-line arguments */
717 for (a=1; a<argc; ++a) {
719 /* -t specifies where to log trace messages to */
720 if (!strncmp(argv[a], "-t", 2)) {
721 strcpy(tracefile, argv[a]);
722 strcpy(tracefile, &tracefile[2]);
723 freopen(tracefile, "r", stdin);
724 freopen(tracefile, "w", stdout);
725 freopen(tracefile, "w", stderr);
728 /* run in the background if -d was specified */
729 else if (!strcmp(argv[a], "-d")) {
730 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
733 /* -x specifies the desired logging level */
734 else if (!strncmp(argv[a], "-x", 2)) {
735 strcpy(convbuf, argv[a]);
736 verbosity = atoi(&convbuf[2]);
739 else if (!strncmp(argv[a], "-h", 2)) {
740 strcpy(convbuf, argv[a]);
741 strcpy(bbs_home_directory, &convbuf[2]);
745 /* any other parameter makes it crash and burn */
747 lprintf(1, "citserver: usage: ");
748 lprintf(1, "citserver [-tTraceFile]");
749 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
755 /* Tell 'em who's in da house */
756 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
757 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
758 lprintf(1, "All rights reserved.\n\n");
762 openlog("citserver",LOG_PID,LOG_USER);
763 /* Load site-specific parameters */
764 lprintf(7, "Loading citadel.config\n");
767 lprintf(7, "Initializing loadable modules\n");
768 DLoader_Init("./modules");
769 lprintf(9, "Modules done initializing.\n");
771 /* Do non system dependent startup functions */
775 * Bind the server to our favourite port.
776 * There is no need to check for errors, because ig_tcp_server()
777 * exits if it doesn't succeed.
779 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
780 msock = ig_tcp_server(config.c_port_number, 5);
781 lprintf(7, "Listening on socket %d\n", msock);
784 * Now that we've bound the socket, change to the BBS user id
785 lprintf(7, "Changing uid to %d\n", BBSUID);
786 if (setuid(BBSUID) != 0) {
787 lprintf(3, "setuid() failed: %s", strerror(errno));
792 * Endless loop. Listen on the master socket. When a connection
793 * comes in, create a socket, a context, and a thread.
797 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
799 lprintf(2, "citserver: accept() failed: %s\n",
803 lprintf(7, "citserver: Client socket %d\n", ssock);
804 lprintf(9, "creating context\n");
805 con = CreateNewContext();
806 con->client_socket = ssock;
808 /* Set the SO_REUSEADDR socket option */
809 lprintf(9, "setting socket options\n");
811 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
814 /* set attributes for the new thread */
815 lprintf(9, "setting thread attributes\n");
816 pthread_attr_init(&attr);
817 pthread_attr_setdetachstate(&attr,
818 PTHREAD_CREATE_DETACHED);
820 /* now create the thread */
821 lprintf(9, "creating thread\n");
822 if (pthread_create(&SessThread, &attr,
823 (void* (*)(void*)) sd_context_loop,
827 "citserver: can't create thread: %s\n",
832 * (defunct -- now done at thread creation time)
833 * if (pthread_detach(&SessThread) != 0) {
835 * "citserver: can't detach thread: %s\n",
839 lprintf(9, "done!\n");