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 #ifdef DEBUG_MEMORY_LEAKS
56 struct TheHeap *heap = NULL;
59 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
60 pthread_key_t MyConKey; /* TSD key for MyContext() */
62 int msock; /* master listening socket */
63 int verbosity = 3; /* Logging level */
65 struct CitContext masterCC;
69 * lprintf() ... Write logging information
71 void lprintf(int loglevel, const char *format, ...) {
75 va_start(arg_ptr, format);
76 vsprintf(buf, format, arg_ptr);
79 if (loglevel <= verbosity) {
80 fprintf(stderr, "%s", buf);
84 PerformLogHooks(loglevel, buf);
89 #ifdef DEBUG_MEMORY_LEAKS
90 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
95 if (ptr == NULL) return(NULL);
97 hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
98 strcpy(hptr->h_file, tfile);
107 void tracked_free(void *ptr) {
108 struct TheHeap *hptr, *freeme;
110 if (heap->h_ptr == ptr) {
116 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
117 if (hptr->next->h_ptr == ptr) {
119 hptr->next = hptr->next->next;
128 void *tracked_realloc(void *ptr, size_t size) {
130 struct TheHeap *hptr;
132 newptr = realloc(ptr, size);
134 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
135 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
142 void dump_tracked() {
143 struct TheHeap *hptr;
145 cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);
146 for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
147 cprintf("%20s %5d\n",
148 hptr->h_file, hptr->h_line);
157 * Some initialization stuff...
159 void init_sysdep(void) {
162 /* Set up a bunch of semaphores to be used for critical sections */
163 for (a=0; a<MAX_SEMAPHORES; ++a) {
164 pthread_mutex_init(&Critters[a], NULL);
168 * Set up a place to put thread-specific data.
169 * We only need a single pointer per thread - it points to the
170 * thread's CitContext structure in the ContextList linked list.
172 if (pthread_key_create(&MyConKey, NULL) != 0) {
173 lprintf(1, "Can't create TSD key!! %s\n", strerror(errno));
177 * The action for unexpected signals and exceptions should be to
178 * call master_cleanup() to gracefully shut down the server.
180 signal(SIGINT, (void(*)(int))master_cleanup);
181 signal(SIGQUIT, (void(*)(int))master_cleanup);
182 signal(SIGHUP, (void(*)(int))master_cleanup);
183 signal(SIGTERM, (void(*)(int))master_cleanup);
184 signal(SIGPIPE, SIG_IGN);
189 * Obtain a semaphore lock to begin a critical section.
191 void begin_critical_section(int which_one)
195 /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
197 /* Don't get interrupted during the critical section */
198 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
200 /* Obtain a semaphore */
201 pthread_mutex_lock(&Critters[which_one]);
206 * Release a semaphore lock to end a critical section.
208 void end_critical_section(int which_one)
212 /* lprintf(8, " end_critical_section(%d)\n", which_one); */
214 /* Let go of the semaphore */
215 pthread_mutex_unlock(&Critters[which_one]);
217 /* If a cancel was sent during the critical section, do it now.
218 * Then re-enable thread cancellation.
220 pthread_testcancel();
221 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
222 pthread_testcancel();
229 * This is a generic function to set up a master socket for listening on
230 * a TCP port. The server shuts down if the bind fails.
232 int ig_tcp_server(int port_number, int queue_len)
234 struct sockaddr_in sin;
237 memset(&sin, 0, sizeof(sin));
238 sin.sin_family = AF_INET;
239 sin.sin_addr.s_addr = INADDR_ANY;
241 if (port_number == 0) {
243 "citserver: No port number specified. Run setup.\n");
247 sin.sin_port = htons((u_short)port_number);
249 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
251 lprintf(1, "citserver: Can't create a socket: %s\n",
256 /* Set the SO_REUSEADDR socket option, because it makes sense. */
258 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
260 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
261 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
265 if (listen(s, queue_len) < 0) {
266 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
275 * Return a pointer to a thread's own CitContext structure (old)
276 * NOTE: this version of MyContext() is commented out because it is no longer
277 * in use. It was written before I discovered TSD keys. This
278 * version pounds through the context list until it finds the one matching
279 * the currently running thread. It remains here, commented out, in case it
280 * is needed for future ports to threading libraries which have the equivalent
281 * of pthread_self() but not pthread_key_create() and its ilk.
283 * struct CitContext *MyContext() {
284 * struct CitContext *ptr;
287 * me = pthread_self();
288 * for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
289 * if (ptr->mythread == me) return(ptr);
296 * Return a pointer to a thread's own CitContext structure (new)
298 struct CitContext *MyContext(void) {
299 struct CitContext *retCC;
300 retCC = (struct CitContext *) pthread_getspecific(MyConKey);
301 if (retCC == NULL) retCC = &masterCC;
307 * Wedge our way into the context list.
309 struct CitContext *CreateNewContext(void) {
310 struct CitContext *me;
312 lprintf(9, "CreateNewContext: calling malloc()\n");
313 me = (struct CitContext *) mallok(sizeof(struct CitContext));
315 lprintf(1, "citserver: can't allocate memory!!\n");
318 memset(me, 0, sizeof(struct CitContext));
320 begin_critical_section(S_SESSION_TABLE);
321 me->next = ContextList;
323 end_critical_section(S_SESSION_TABLE);
328 * Add a thread's thread ID to the context
330 void InitMyContext(struct CitContext *con)
334 con->mythread = pthread_self();
335 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
336 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
337 if (pthread_setspecific(MyConKey, (void *)con) != 0) {
338 lprintf(1, "ERROR! pthread_setspecific() failed: %s\n",
344 * Remove a context from the context list.
346 void RemoveContext(struct CitContext *con)
348 struct CitContext *ptr;
350 lprintf(7, "Starting RemoveContext()\n");
351 lprintf(9, "Session count before RemoveContext is %d\n",
354 lprintf(7, "WARNING: RemoveContext() called with null!\n");
359 * session_count() starts its own S_SESSION_TABLE critical section;
360 * so do not call it from within this loop.
362 begin_critical_section(S_SESSION_TABLE);
363 lprintf(7, "Closing socket %d\n", con->client_socket);
364 close(con->client_socket);
366 lprintf(9, "Dereferencing session context\n");
367 if (ContextList==con) {
368 ContextList = ContextList->next;
371 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
372 if (ptr->next == con) {
373 ptr->next = con->next;
378 lprintf(9, "Freeing session context...\n");
380 lprintf(9, "...done.\n");
381 end_critical_section(S_SESSION_TABLE);
383 lprintf(9, "Session count after RemoveContext is %d\n",
386 lprintf(7, "Done with RemoveContext\n");
391 * Return the number of sessions currently running.
392 * (This should probably be moved out of sysdep.c)
394 int session_count(void) {
395 struct CitContext *ptr;
398 lprintf(9, "session_count() starting\n");
399 begin_critical_section(S_SESSION_TABLE);
400 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
402 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
404 end_critical_section(S_SESSION_TABLE);
406 lprintf(9, "session_count() finishing\n");
412 * client_write() ... Send binary data to the client.
414 void client_write(char *buf, int nbytes)
416 int bytes_written = 0;
418 while (bytes_written < nbytes) {
419 retval = write(CC->client_socket, &buf[bytes_written],
420 nbytes - bytes_written);
422 lprintf(2, "client_write() failed: %s\n",
426 bytes_written = bytes_written + retval;
432 * cprintf() ... Send formatted printable data to the client. It is
433 * implemented in terms of client_write() but remains in
434 * sysdep.c in case we port to somewhere without va_args...
436 void cprintf(const char *format, ...) {
440 va_start(arg_ptr, format);
441 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
442 buf[sizeof buf - 2] = '\n';
443 client_write(buf, strlen(buf));
449 * Read data from the client socket.
451 * 1 Requested number of bytes has been read.
452 * 0 Request timed out.
453 * If the socket breaks, the session is immediately terminated.
455 int client_read_to(char *buf, int bytes, int timeout)
465 FD_SET(CC->client_socket, &rfds);
469 retval = select( (CC->client_socket)+1,
470 &rfds, NULL, NULL, &tv);
471 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
475 rlen = read(CC->client_socket, &buf[len], bytes-len);
477 lprintf(2, "client_read() failed: %s\n",
487 * Read data from the client socket with default timeout.
488 * (This is implemented in terms of client_read_to() and could be
489 * justifiably moved out of sysdep.c)
491 int client_read(char *buf, int bytes)
493 return(client_read_to(buf, bytes, config.c_sleeping));
498 * client_gets() ... Get a LF-terminated line of text from the client.
499 * (This is implemented in terms of client_read() and could be
500 * justifiably moved out of sysdep.c)
502 int client_gets(char *buf)
506 /* Read one character at a time.
509 retval = client_read(&buf[i], 1);
510 if (retval != 1 || buf[i] == '\n' || i == 255)
514 /* If we got a long line, discard characters until the newline.
517 while (buf[i] != '\n' && retval == 1)
518 retval = client_read(&buf[i], 1);
520 /* Strip the trailing newline and any trailing nonprintables (cr's)
523 while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
524 buf[strlen(buf)-1] = 0;
531 * The system-dependent part of master_cleanup() - close the master socket.
533 void sysdep_master_cleanup(void) {
534 lprintf(7, "Closing master socket %d\n", msock);
539 * Cleanup routine to be called when one thread is shutting down.
541 void cleanup(int exit_code)
543 /* Terminate the thread.
544 * Its cleanup handler will call cleanup_stuff()
546 lprintf(7, "Calling pthread_exit()\n");
551 * Terminate another session.
553 void kill_session(int session_to_kill) {
554 struct CitContext *ptr;
557 lprintf(9, "kill_session() scanning for thread to cancel...\n");
558 begin_critical_section(S_SESSION_TABLE);
559 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
560 if (ptr->cs_pid == session_to_kill) {
561 killme = ptr->mythread;
564 end_critical_section(S_SESSION_TABLE);
565 lprintf(9, "kill_session() finished scanning.\n");
568 lprintf(9, "calling pthread_cancel()\n");
569 pthread_cancel(killme);
575 * The system-dependent wrapper around the main context loop.
577 void *sd_context_loop(struct CitContext *con) {
578 pthread_cleanup_push(*cleanup_stuff, NULL);
580 pthread_cleanup_pop(0);
586 * Start running as a daemon. Only close stdio if do_close_stdio is set.
588 void start_daemon(int do_close_stdio) {
589 if (do_close_stdio) {
594 signal(SIGHUP,SIG_IGN);
595 signal(SIGINT,SIG_IGN);
596 signal(SIGQUIT,SIG_IGN);
597 if (fork()!=0) exit(0);
603 * Tie in to the 'netsetup' program.
605 * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
607 void cmd_nset(char *cmdbuf)
614 char netsetup_args[3][256];
616 if (CC->usersupp.axlevel < 6) {
617 cprintf("%d Higher access required.\n",
618 ERROR + HIGHER_ACCESS_REQUIRED);
622 for (a=1; a<=3; ++a) {
623 if (num_parms(cmdbuf) >= a) {
624 extract(netsetup_args[a-1], cmdbuf, a-1);
625 for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
626 if (netsetup_args[a-1][b] == 34) {
627 netsetup_args[a-1][b] = '_';
632 netsetup_args[a-1][0] = 0;
636 sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
637 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
638 netsetup = popen(fbuf, "r");
639 if (netsetup == NULL) {
640 cprintf("%d %s\n", ERROR, strerror(errno));
645 while (ch = getc(netsetup), (ch > 0)) {
646 fbuf[strlen(fbuf)+1] = 0;
647 fbuf[strlen(fbuf)] = ch;
650 retcode = pclose(netsetup);
653 for (a=0; a<strlen(fbuf); ++a) {
654 if (fbuf[a] < 32) fbuf[a] = 32;
657 cprintf("%d %s\n", ERROR, fbuf);
661 cprintf("%d Command succeeded. Output follows:\n", LISTING_FOLLOWS);
663 if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
670 * Generic routine to convert a login name to a full name (gecos)
671 * Returns nonzero if a conversion took place
673 int convert_login(char NameToConvert[]) {
677 pw = getpwnam(NameToConvert);
682 strcpy(NameToConvert, pw->pw_gecos);
683 for (a=0; a<strlen(NameToConvert); ++a) {
684 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
696 * Here's where it all begins.
698 int main(int argc, char **argv)
700 struct sockaddr_in fsin; /* Data for master socket */
701 int alen; /* Data for master socket */
702 int ssock; /* Descriptor for master socket */
703 THREAD SessThread; /* Thread descriptor */
704 pthread_attr_t attr; /* Thread attributes */
705 struct CitContext *con; /* Temporary context pointer */
706 char tracefile[128]; /* Name of file to log traces to */
707 int a, i; /* General-purpose variables */
711 /* specify default port name and trace file */
712 strcpy(tracefile, "");
714 /* parse command-line arguments */
715 for (a=1; a<argc; ++a) {
717 /* -t specifies where to log trace messages to */
718 if (!strncmp(argv[a], "-t", 2)) {
719 strcpy(tracefile, argv[a]);
720 strcpy(tracefile, &tracefile[2]);
721 freopen(tracefile, "r", stdin);
722 freopen(tracefile, "w", stdout);
723 freopen(tracefile, "w", stderr);
726 /* run in the background if -d was specified */
727 else if (!strcmp(argv[a], "-d")) {
728 start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
731 /* -x specifies the desired logging level */
732 else if (!strncmp(argv[a], "-x", 2)) {
733 strcpy(convbuf, argv[a]);
734 verbosity = atoi(&convbuf[2]);
737 else if (!strncmp(argv[a], "-h", 2)) {
738 strcpy(convbuf, argv[a]);
739 strcpy(bbs_home_directory, &convbuf[2]);
743 /* any other parameter makes it crash and burn */
745 lprintf(1, "citserver: usage: ");
746 lprintf(1, "citserver [-tTraceFile]");
747 lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
753 /* Tell 'em who's in da house */
754 lprintf(1, "Multithreaded message server for %s\n", CITADEL);
755 lprintf(1, "Copyright (C) 1987-1998 by Art Cancro. ");
756 lprintf(1, "All rights reserved.\n\n");
760 openlog("citserver",LOG_PID,LOG_USER);
761 /* Load site-specific parameters */
762 lprintf(7, "Loading citadel.config\n");
765 lprintf(7, "Initializing loadable modules\n");
766 snprintf(modpath, 128, "%s/modules", BBSDIR);
767 DLoader_Init(modpath);
768 lprintf(9, "Modules done initializing.\n");
770 /* Do non system dependent startup functions */
774 * Bind the server to our favourite port.
775 * There is no need to check for errors, because ig_tcp_server()
776 * exits if it doesn't succeed.
778 lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
779 msock = ig_tcp_server(config.c_port_number, 5);
780 lprintf(7, "Listening on socket %d\n", msock);
783 * Now that we've bound the socket, change to the BBS user id
784 lprintf(7, "Changing uid to %d\n", BBSUID);
785 if (setuid(BBSUID) != 0) {
786 lprintf(3, "setuid() failed: %s", strerror(errno));
791 * Endless loop. Listen on the master socket. When a connection
792 * comes in, create a socket, a context, and a thread.
795 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
797 lprintf(2, "citserver: accept() failed: %s\n",
801 lprintf(7, "citserver: Client socket %d\n", ssock);
802 lprintf(9, "creating context\n");
803 con = CreateNewContext();
804 con->client_socket = ssock;
806 /* Set the SO_REUSEADDR socket option */
807 lprintf(9, "setting socket options\n");
809 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
812 /* set attributes for the new thread */
813 lprintf(9, "setting thread attributes\n");
814 pthread_attr_init(&attr);
815 pthread_attr_setdetachstate(&attr,
816 PTHREAD_CREATE_DETACHED);
818 /* now create the thread */
819 lprintf(9, "creating thread\n");
820 if (pthread_create(&SessThread, &attr,
821 (void* (*)(void*)) sd_context_loop,
825 "citserver: can't create thread: %s\n",
830 * (defunct -- now done at thread creation time)
831 * if (pthread_detach(&SessThread) != 0) {
833 * "citserver: can't detach thread: %s\n",
837 lprintf(9, "done!\n");