4 * Citadel "system dependent" stuff.
5 * See COPYING for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syslog.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
52 #include <libcitadel.h>
55 #include "sysdep_decls.h"
56 #include "citserver.h"
60 #include "housekeeping.h"
61 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
65 #ifdef HAVE_SYS_SELECT_H
66 #include <sys/select.h>
73 #include "ctdl_module.h"
79 #ifdef DEBUG_MEMORY_LEAKS
87 struct igheap *igheap = NULL;
91 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
93 int syslog_facility = LOG_DAEMON;
94 int enable_syslog = 0;
98 * CtdlLogPrintf() ... Write logging information
100 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
102 va_start(arg_ptr, format);
103 vCtdlLogPrintf(loglevel, format, arg_ptr);
107 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
109 char buf[SIZ], buf2[SIZ];
112 vsyslog((syslog_facility | loglevel), format, arg_ptr);
115 /* stderr output code */
116 if (enable_syslog || running_as_daemon) return;
118 /* if we run in forground and syslog is disabled, log to terminal */
119 if (loglevel <= verbosity) {
123 CitContext *CCC = CC;
125 gettimeofday(&tv, NULL);
126 /* Promote to time_t; types differ on some OSes (like darwin) */
127 unixtime = tv.tv_sec;
128 localtime_r(&unixtime, &tim);
129 if ((CCC != NULL) && (CCC->cs_pid != 0)) {
131 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
132 tim.tm_year + 1900, tim.tm_mon + 1,
133 tim.tm_mday, tim.tm_hour, tim.tm_min,
134 tim.tm_sec, (long)tv.tv_usec,
138 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
139 tim.tm_year + 1900, tim.tm_mon + 1,
140 tim.tm_mday, tim.tm_hour, tim.tm_min,
141 tim.tm_sec, (long)tv.tv_usec);
143 vsnprintf(buf2, SIZ, format, arg_ptr);
145 fprintf(stderr, "%s%s", buf, buf2);
153 * Signal handler to shut down the server.
156 volatile int exit_signal = 0;
157 volatile int shutdown_and_halt = 0;
158 volatile int restart_server = 0;
159 volatile int running_as_daemon = 0;
161 static RETSIGTYPE signal_cleanup(int signum) {
167 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
168 exit_signal = signum;
175 * Some initialization stuff...
177 void init_sysdep(void) {
180 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
184 getrlimit(RLIMIT_NOFILE, &rl);
185 rl.rlim_cur = FD_SETSIZE;
186 rl.rlim_max = FD_SETSIZE;
187 setrlimit(RLIMIT_NOFILE, &rl);
191 /* If we've got OpenSSL, we're going to use it. */
197 * Set up a place to put thread-specific data.
198 * We only need a single pointer per thread - it points to the
199 * CitContext structure (in the ContextList linked list) of the
200 * session to which the calling thread is currently bound.
202 if (citthread_key_create(&MyConKey, NULL) != 0) {
203 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
208 * The action for unexpected signals and exceptions should be to
209 * call signal_cleanup() to gracefully shut down the server.
212 sigaddset(&set, SIGINT);
213 sigaddset(&set, SIGQUIT);
214 sigaddset(&set, SIGHUP);
215 sigaddset(&set, SIGTERM);
216 // sigaddset(&set, SIGSEGV); commented out because
217 // sigaddset(&set, SIGILL); we want core dumps
218 // sigaddset(&set, SIGBUS);
219 sigprocmask(SIG_UNBLOCK, &set, NULL);
221 signal(SIGINT, signal_cleanup);
222 signal(SIGQUIT, signal_cleanup);
223 signal(SIGHUP, signal_cleanup);
224 signal(SIGTERM, signal_cleanup);
225 // signal(SIGSEGV, signal_cleanup); commented out because
226 // signal(SIGILL, signal_cleanup); we want core dumps
227 // signal(SIGBUS, signal_cleanup);
230 * Do not shut down the server on broken pipe signals, otherwise the
231 * whole Citadel service would come down whenever a single client
234 signal(SIGPIPE, SIG_IGN);
241 * This is a generic function to set up a master socket for listening on
242 * a TCP port. The server shuts down if the bind fails.
245 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
247 struct sockaddr_in sin;
249 int actual_queue_len;
251 actual_queue_len = queue_len;
252 if (actual_queue_len < 5) actual_queue_len = 5;
254 memset(&sin, 0, sizeof(sin));
255 sin.sin_family = AF_INET;
256 sin.sin_port = htons((u_short)port_number);
257 if (ip_addr == NULL) {
258 sin.sin_addr.s_addr = INADDR_ANY;
261 sin.sin_addr.s_addr = inet_addr(ip_addr);
264 if (sin.sin_addr.s_addr == !INADDR_ANY) {
265 sin.sin_addr.s_addr = INADDR_ANY;
268 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
271 *errormessage = (char*) malloc(SIZ + 1);
272 snprintf(*errormessage, SIZ,
273 "citserver: Can't create a socket: %s",
275 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
280 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
282 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
283 *errormessage = (char*) malloc(SIZ + 1);
284 snprintf(*errormessage, SIZ,
285 "citserver: Can't bind: %s",
287 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
292 /* set to nonblock - we need this for some obscure situations */
293 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
294 *errormessage = (char*) malloc(SIZ + 1);
295 snprintf(*errormessage, SIZ,
296 "citserver: Can't set socket to non-blocking: %s",
298 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
303 if (listen(s, actual_queue_len) < 0) {
304 *errormessage = (char*) malloc(SIZ + 1);
305 snprintf(*errormessage, SIZ,
306 "citserver: Can't listen: %s",
308 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
319 * Create a Unix domain socket and listen on it
321 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
323 struct sockaddr_un addr;
326 int actual_queue_len;
327 #ifdef HAVE_STRUCT_UCRED
331 actual_queue_len = queue_len;
332 if (actual_queue_len < 5) actual_queue_len = 5;
334 i = unlink(sockpath);
335 if ((i != 0) && (errno != ENOENT)) {
336 *errormessage = (char*) malloc(SIZ + 1);
337 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
338 sockpath, strerror(errno));
339 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
343 memset(&addr, 0, sizeof(addr));
344 addr.sun_family = AF_UNIX;
345 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
347 s = socket(AF_UNIX, SOCK_STREAM, 0);
349 *errormessage = (char*) malloc(SIZ + 1);
350 snprintf(*errormessage, SIZ,
351 "citserver: Can't create a socket: %s",
353 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
357 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
358 *errormessage = (char*) malloc(SIZ + 1);
359 snprintf(*errormessage, SIZ,
360 "citserver: Can't bind: %s",
362 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
366 /* set to nonblock - we need this for some obscure situations */
367 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
368 *errormessage = (char*) malloc(SIZ + 1);
369 snprintf(*errormessage, SIZ,
370 "citserver: Can't set socket to non-blocking: %s",
372 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
377 if (listen(s, actual_queue_len) < 0) {
378 *errormessage = (char*) malloc(SIZ + 1);
379 snprintf(*errormessage, SIZ,
380 "citserver: Can't listen: %s",
382 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
386 #ifdef HAVE_STRUCT_UCRED
387 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
390 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
397 * The following functions implement output buffering on operating systems which
398 * support it (such as Linux and various BSD flavors).
402 # define HAVE_TCP_BUFFERING
405 # define HAVE_TCP_BUFFERING
406 # define TCP_CORK TCP_NOPUSH
408 #endif /* TCP_CORK */
409 #endif /* HAVE_DARWIN */
411 static unsigned on = 1, off = 0;
413 void buffer_output(void) {
414 #ifdef HAVE_TCP_BUFFERING
416 if (!CC->redirect_ssl)
418 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
422 void unbuffer_output(void) {
423 #ifdef HAVE_TCP_BUFFERING
425 if (!CC->redirect_ssl)
427 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
431 void flush_output(void) {
432 #ifdef HAVE_TCP_BUFFERING
433 struct CitContext *CCC = CC;
434 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
435 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
442 * client_write() ... Send binary data to the client.
444 int client_write(char *buf, int nbytes)
446 int bytes_written = 0;
448 #ifndef HAVE_TCP_BUFFERING
449 int old_buffer_len = 0;
456 if (Ctx->redirect_buffer != NULL) {
457 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
458 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
459 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
460 Ctx->redirect_alloc);
462 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
463 Ctx->redirect_len += nbytes;
464 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
469 if (Ctx->redirect_ssl) {
470 client_write_ssl(buf, nbytes);
475 fdflags = fcntl(Ctx->client_socket, F_GETFL);
477 while (bytes_written < nbytes) {
478 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
480 FD_SET(Ctx->client_socket, &wset);
481 if (select(1, NULL, &wset, NULL, NULL) == -1) {
484 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
485 if (CtdlThreadCheckStop()) {
489 /* can't trust fd's and stuff so we need to re-create them */
493 CtdlLogPrintf(CTDL_ERR,
494 "client_write(%d bytes) select failed: %s (%d)\n",
495 nbytes - bytes_written,
496 strerror(errno), errno);
504 retval = write(Ctx->client_socket, &buf[bytes_written],
505 nbytes - bytes_written);
507 CtdlLogPrintf(CTDL_ERR,
508 "client_write(%d bytes) failed: %s (%d)\n",
509 nbytes - bytes_written,
510 strerror(errno), errno);
512 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
516 bytes_written = bytes_written + retval;
521 void cputbuf(const StrBuf *Buf) {
522 client_write(ChrPtr(Buf), StrLength(Buf));
527 * cprintf() Send formatted printable data to the client.
528 * Implemented in terms of client_write() so it's technically not sysdep...
530 void cprintf(const char *format, ...) {
534 va_start(arg_ptr, format);
535 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
536 buf[sizeof buf - 2] = '\n';
537 client_write(buf, strlen(buf));
543 * Read data from the client socket.
545 * 1 Requested number of bytes has been read.
546 * 0 Request timed out.
547 * -1 The socket is broken.
548 * If the socket breaks, the session will be terminated.
550 int client_read_to(char *buf, int bytes, int timeout)
559 if (CC->redirect_ssl) {
560 return (client_read_ssl(buf, bytes, timeout));
564 fd = CC->client_socket;
571 retval = select( (fd)+1,
572 &rfds, NULL, NULL, &tv);
577 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select() in client_read_to().\n");
578 if (CtdlThreadCheckStop()) {
582 /* can't trust fd's and stuff so we need to re-create them */
587 CtdlLogPrintf(CTDL_DEBUG, "Failed select() in client_read_to().\n");
593 if (FD_ISSET(fd, &rfds) == 0) {
597 rlen = read(fd, &buf[len], bytes-len);
599 /* The socket has been disconnected! */
609 * Read data from the client socket with default timeout.
610 * (This is implemented in terms of client_read_to() and could be
611 * justifiably moved out of sysdep.c)
613 INLINE int client_read(char *buf, int bytes)
615 return(client_read_to(buf, bytes, config.c_sleeping));
620 * client_getln() ... Get a LF-terminated line of text from the client.
621 * (This is implemented in terms of client_read() and could be
622 * justifiably moved out of sysdep.c)
624 int client_getln(char *buf, int bufsize)
628 /* Read one character at a time.
631 retval = client_read(&buf[i], 1);
632 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
636 /* If we got a long line, discard characters until the newline.
638 if (i == (bufsize-1))
639 while (buf[i] != '\n' && retval == 1)
640 retval = client_read(&buf[i], 1);
642 /* Strip the trailing LF, and the trailing CR if present.
646 && ( (buf[i - 1]==13)
647 || ( buf[i - 1]==10)) ) {
651 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
657 * Cleanup any contexts that are left lying around
661 void close_masters (void)
663 struct ServiceFunctionHook *serviceptr;
666 * close all protocol master sockets
668 for (serviceptr = ServiceHookTable; serviceptr != NULL;
669 serviceptr = serviceptr->next ) {
671 if (serviceptr->tcp_port > 0)
673 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
674 serviceptr->tcp_port);
675 serviceptr->tcp_port = 0;
678 if (serviceptr->sockpath != NULL)
679 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
680 serviceptr->sockpath);
682 close(serviceptr->msock);
683 /* If it's a Unix domain socket, remove the file. */
684 if (serviceptr->sockpath != NULL) {
685 unlink(serviceptr->sockpath);
686 serviceptr->sockpath = NULL;
693 * The system-dependent part of master_cleanup() - close the master socket.
695 void sysdep_master_cleanup(void) {
704 CtdlDestroyProtoHooks();
705 CtdlDestroyDeleteHooks();
706 CtdlDestroyXmsgHooks();
707 CtdlDestroyNetprocHooks();
708 CtdlDestroyUserHooks();
709 CtdlDestroyMessageHook();
710 CtdlDestroyCleanupHooks();
711 CtdlDestroyFixedOutputHooks();
712 CtdlDestroySessionHooks();
713 CtdlDestroyServiceHook();
714 CtdlDestroyRoomHooks();
715 #ifdef HAVE_BACKTRACE
723 void graceful_shutdown(int signum) {
724 kill(current_child, signum);
725 unlink(file_pid_file);
730 int nFireUpsNonRestart = 0;
734 * Start running as a daemon.
736 void start_daemon(int unused) {
744 /* Close stdin/stdout/stderr and replace them with /dev/null.
745 * We don't just call close() because we don't want these fd's
746 * to be reused for other files.
755 signal(SIGHUP, SIG_IGN);
756 signal(SIGINT, SIG_IGN);
757 signal(SIGQUIT, SIG_IGN);
761 freopen("/dev/null", "r", stdin);
762 freopen("/dev/null", "w", stdout);
763 freopen("/dev/null", "w", stderr);
766 current_child = fork();
768 signal(SIGTERM, graceful_shutdown);
770 if (current_child < 0) {
775 else if (current_child == 0) {
776 return; /* continue starting citadel. */
780 fp = fopen(file_pid_file, "w");
782 fprintf(fp, ""F_PID_T"\n", getpid());
785 waitpid(current_child, &status, 0);
788 nFireUpsNonRestart = nFireUps;
790 /* Exit code 0 means the watcher should exit */
791 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
795 /* Exit code 101-109 means the watcher should exit */
796 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
800 /* Any other exit code, or no exit code, means we should restart. */
804 ForkedPid = current_child;
807 } while (do_restart);
809 unlink(file_pid_file);
810 exit(WEXITSTATUS(status));
815 void checkcrash(void)
817 if (nFireUpsNonRestart != nFireUps)
821 CrashMail = NewStrBuf();
822 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
823 StrBufPrintf(CrashMail,
825 " The Citadel server process (citserver) terminated unexpectedly."
827 " This could be the result of a bug in the server program, or some external "
829 " You can obtain more information about this by enabling core dumps.\n \n"
830 " For more information, please see:\n \n"
831 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
833 "http://www.4players.de/4players.php/walkthrough/Wii/9298/24733/Die_Chroniken_von_Narnia_Prinz_Kaspian_von_Narnia.html"
835 " If you have already done this, the core dump is likely to be found at %score.%d\n"
837 ctdl_run_dir, ForkedPid);
838 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
839 FreeStrBuf(&CrashMail);
845 * Generic routine to convert a login name to a full name (gecos)
846 * Returns nonzero if a conversion took place
848 int convert_login(char NameToConvert[]) {
852 pw = getpwnam(NameToConvert);
857 strcpy(NameToConvert, pw->pw_gecos);
858 for (a=0; a<strlen(NameToConvert); ++a) {
859 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
868 * This loop just keeps going and going and going...
872 * This current implimentation of worker_thread creates a bottle neck in several situations
873 * The first thing to remember is that a single thread can handle more than one connection at a time.
874 * More threads mean less memory for the system to run in.
875 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
876 * something to happen anywhere.
877 * This current implimentation requires worker threads to wait in other locations, after it has
878 * been committed to a single connection which is very wasteful.
879 * As an extreme case consider this:
880 * A slow client connects and this slow client sends only one character each second.
881 * With this current implimentation a single worker thread is dispatched to handle that connection
882 * until such times as the client timeout expires, an error occurs on the socket or the client
883 * completes its transmission.
884 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
885 * second interval between chars.
887 * It is my intention to re-write this code and the associated client_getln, client_read functions
888 * to allow any thread to read data on behalf of any connection (context).
889 * To do this I intend to have this main loop read chars into a buffer stored in the context.
890 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
892 * This worker thread loop also needs to be able to handle binary data.
895 void *worker_thread(void *arg) {
898 CitContext *bind_me = NULL;
905 while (!CtdlThreadCheckStop()) {
907 /* make doubly sure we're not holding any stale db handles
908 * which might cause a deadlock.
911 do_select: force_purge = 0;
912 bind_me = NULL; /* Which session shall we handle? */
914 /* Initialize the fdset. */
918 begin_critical_section(S_SESSION_TABLE);
919 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
920 /* Dont select on dead sessions only truly idle ones */
921 if ((ptr->state == CON_IDLE)) {
922 FD_SET(ptr->client_socket, &readfds);
923 if (ptr->client_socket > highest)
924 highest = ptr->client_socket;
926 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
928 ptr->state = CON_EXECUTING;
931 if ((bind_me == NULL) && (ptr->state == CON_STARTING)) {
936 end_critical_section(S_SESSION_TABLE);
942 /* If we got this far, it means that there are no sessions
943 * which a previous thread marked for attention, so we go
944 * ahead and get ready to select().
947 if (!CtdlThreadCheckStop()) {
948 tv.tv_sec = 1; /* wake up every second if no input */
950 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
955 /* Now figure out who made this select() unblock.
956 * First, check for an error or exit condition.
959 if (errno == EBADF) {
960 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
964 if (errno != EINTR) {
965 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
969 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
970 if (CtdlThreadCheckStop()) return(NULL);
974 else if(retval == 0) {
975 if (CtdlThreadCheckStop()) return(NULL);
978 /* It must be a client socket. Find a context that has data
979 * waiting on its socket *and* is in the CON_IDLE state. Any
980 * active sockets other than our chosen one are marked as
981 * CON_READY so the next thread that comes around can just bind
982 * to one without having to select() again.
984 begin_critical_section(S_SESSION_TABLE);
985 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
986 if ( (FD_ISSET(ptr->client_socket, &readfds))
987 && (ptr->state != CON_EXECUTING) ) {
988 ptr->input_waiting = 1;
990 bind_me = ptr; /* I choose you! */
991 bind_me->state = CON_EXECUTING;
994 ptr->state = CON_READY;
998 end_critical_section(S_SESSION_TABLE);
1001 /* We're bound to a session */
1002 if (bind_me != NULL) {
1003 become_session(bind_me);
1005 if (bind_me->state == CON_STARTING) {
1006 bind_me->state = CON_EXECUTING;
1007 begin_session(bind_me);
1008 bind_me->h_greeting_function();
1010 /* If the client has sent a command, execute it. */
1011 if (CC->input_waiting) {
1012 CC->h_command_function();
1013 CC->input_waiting = 0;
1016 /* If there are asynchronous messages waiting and the
1017 * client supports it, do those now */
1018 if ((CC->is_async) && (CC->async_waiting)
1019 && (CC->h_async_function != NULL)) {
1020 CC->h_async_function();
1021 CC->async_waiting = 0;
1024 force_purge = CC->kill_me;
1025 become_session(NULL);
1026 bind_me->state = CON_IDLE;
1029 dead_session_purge(force_purge);
1032 /* If control reaches this point, the server is shutting down */
1040 * A function to handle selecting on master sockets.
1041 * In other words it handles new connections.
1044 void *select_on_master (void *arg)
1046 struct ServiceFunctionHook *serviceptr;
1050 int ssock; /* Descriptor for client socket */
1051 CitContext *con= NULL; /* Temporary context pointer */
1056 while (!CtdlThreadCheckStop()) {
1057 /* Initialize the fdset. */
1058 FD_ZERO(&master_fds);
1061 /* First, add the various master sockets to the fdset. */
1062 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1063 serviceptr = serviceptr->next ) {
1064 m = serviceptr->msock;
1065 FD_SET(m, &master_fds);
1071 if (!CtdlThreadCheckStop()) {
1072 tv.tv_sec = 60; /* wake up every second if no input */
1074 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1079 /* Now figure out who made this select() unblock.
1080 * First, check for an error or exit condition.
1083 if (errno == EBADF) {
1084 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1088 if (errno != EINTR) {
1089 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1090 CtdlThreadStopAll();
1092 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1093 if (CtdlThreadCheckStop()) return(NULL);
1097 else if(retval == 0) {
1098 if (CtdlThreadCheckStop()) return(NULL);
1101 /* Next, check to see if it's a new client connecting
1102 * on a master socket.
1104 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1105 serviceptr = serviceptr->next ) {
1107 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1108 ssock = accept(serviceptr->msock, NULL, 0);
1110 CtdlLogPrintf(CTDL_DEBUG,
1111 "New client socket %d\n",
1114 /* The master socket is non-blocking but the client
1115 * sockets need to be blocking, otherwise certain
1116 * operations barf on FreeBSD. Not a fatal error.
1118 if (fcntl(ssock, F_SETFL, 0) < 0) {
1119 CtdlLogPrintf(CTDL_EMERG,
1120 "citserver: Can't set socket to blocking: %s\n",
1124 /* New context will be created already
1125 * set up in the CON_EXECUTING state.
1127 con = CreateNewContext();
1129 /* Assign our new socket number to it. */
1130 con->client_socket = ssock;
1131 con->h_command_function =
1132 serviceptr->h_command_function;
1133 con->h_async_function =
1134 serviceptr->h_async_function;
1135 con->h_greeting_function = serviceptr->h_greeting_function;
1137 serviceptr->ServiceName;
1139 /* Determine whether it's a local socket */
1140 if (serviceptr->sockpath != NULL)
1141 con->is_local_socket = 1;
1143 /* Set the SO_REUSEADDR socket option */
1145 setsockopt(ssock, SOL_SOCKET,
1149 con->state = CON_STARTING;
1165 * Translate text facility name to syslog.h defined value.
1167 int SyslogFacility(char *name)
1176 { LOG_KERN, "kern" },
1177 { LOG_USER, "user" },
1178 { LOG_MAIL, "mail" },
1179 { LOG_DAEMON, "daemon" },
1180 { LOG_AUTH, "auth" },
1181 { LOG_SYSLOG, "syslog" },
1183 { LOG_NEWS, "news" },
1184 { LOG_UUCP, "uucp" },
1185 { LOG_LOCAL0, "local0" },
1186 { LOG_LOCAL1, "local1" },
1187 { LOG_LOCAL2, "local2" },
1188 { LOG_LOCAL3, "local3" },
1189 { LOG_LOCAL4, "local4" },
1190 { LOG_LOCAL5, "local5" },
1191 { LOG_LOCAL6, "local6" },
1192 { LOG_LOCAL7, "local7" },
1195 for(i = 0; facTbl[i].name != NULL; i++) {
1196 if(!strcasecmp(name, facTbl[i].name))
1197 return facTbl[i].facility;
1204 /********** MEM CHEQQER ***********/
1206 #ifdef DEBUG_MEMORY_LEAKS
1213 void *tracked_malloc(size_t size, char *file, int line) {
1214 struct igheap *thisheap;
1217 block = malloc(size);
1218 if (block == NULL) return(block);
1220 thisheap = malloc(sizeof(struct igheap));
1221 if (thisheap == NULL) {
1226 thisheap->block = block;
1227 strcpy(thisheap->file, file);
1228 thisheap->line = line;
1230 begin_critical_section(S_DEBUGMEMLEAKS);
1231 thisheap->next = igheap;
1233 end_critical_section(S_DEBUGMEMLEAKS);
1239 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1240 struct igheap *thisheap;
1243 block = realloc(ptr, size);
1244 if (block == NULL) return(block);
1246 thisheap = malloc(sizeof(struct igheap));
1247 if (thisheap == NULL) {
1252 thisheap->block = block;
1253 strcpy(thisheap->file, file);
1254 thisheap->line = line;
1256 begin_critical_section(S_DEBUGMEMLEAKS);
1257 thisheap->next = igheap;
1259 end_critical_section(S_DEBUGMEMLEAKS);
1266 void tracked_free(void *ptr) {
1267 struct igheap *thisheap;
1268 struct igheap *trash;
1272 if (igheap == NULL) return;
1273 begin_critical_section(S_DEBUGMEMLEAKS);
1274 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1275 if (thisheap->next != NULL) {
1276 if (thisheap->next->block == ptr) {
1277 trash = thisheap->next;
1278 thisheap->next = thisheap->next->next;
1283 if (igheap->block == ptr) {
1285 igheap = igheap->next;
1288 end_critical_section(S_DEBUGMEMLEAKS);
1291 char *tracked_strdup(const char *s, char *file, int line) {
1294 if (s == NULL) return(NULL);
1295 ptr = tracked_malloc(strlen(s) + 1, file, line);
1296 if (ptr == NULL) return(NULL);
1297 strncpy(ptr, s, strlen(s));
1301 void dump_heap(void) {
1302 struct igheap *thisheap;
1304 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1305 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1306 thisheap->file, thisheap->line);
1310 #endif /* DEBUG_MEMORY_LEAKS */