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 struct 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) {
162 #ifdef THREADS_USESIGNALS
168 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
169 exit_signal = signum;
176 * Some initialization stuff...
178 void init_sysdep(void) {
181 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
185 getrlimit(RLIMIT_NOFILE, &rl);
186 rl.rlim_cur = FD_SETSIZE;
187 rl.rlim_max = FD_SETSIZE;
188 setrlimit(RLIMIT_NOFILE, &rl);
192 /* If we've got OpenSSL, we're going to use it. */
198 * Set up a place to put thread-specific data.
199 * We only need a single pointer per thread - it points to the
200 * CitContext structure (in the ContextList linked list) of the
201 * session to which the calling thread is currently bound.
203 if (citthread_key_create(&MyConKey, NULL) != 0) {
204 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
209 * The action for unexpected signals and exceptions should be to
210 * call signal_cleanup() to gracefully shut down the server.
213 sigaddset(&set, SIGINT);
214 sigaddset(&set, SIGQUIT);
215 sigaddset(&set, SIGHUP);
216 sigaddset(&set, SIGTERM);
217 // sigaddset(&set, SIGSEGV); commented out because
218 // sigaddset(&set, SIGILL); we want core dumps
219 // sigaddset(&set, SIGBUS);
220 sigprocmask(SIG_UNBLOCK, &set, NULL);
222 signal(SIGINT, signal_cleanup);
223 signal(SIGQUIT, signal_cleanup);
224 signal(SIGHUP, signal_cleanup);
225 signal(SIGTERM, signal_cleanup);
226 // signal(SIGSEGV, signal_cleanup); commented out because
227 // signal(SIGILL, signal_cleanup); we want core dumps
228 // signal(SIGBUS, signal_cleanup);
231 * Do not shut down the server on broken pipe signals, otherwise the
232 * whole Citadel service would come down whenever a single client
235 signal(SIGPIPE, SIG_IGN);
242 * This is a generic function to set up a master socket for listening on
243 * a TCP port. The server shuts down if the bind fails.
246 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
248 struct sockaddr_in sin;
250 int actual_queue_len;
252 actual_queue_len = queue_len;
253 if (actual_queue_len < 5) actual_queue_len = 5;
255 memset(&sin, 0, sizeof(sin));
256 sin.sin_family = AF_INET;
257 sin.sin_port = htons((u_short)port_number);
258 if (ip_addr == NULL) {
259 sin.sin_addr.s_addr = INADDR_ANY;
262 sin.sin_addr.s_addr = inet_addr(ip_addr);
265 if (sin.sin_addr.s_addr == !INADDR_ANY) {
266 sin.sin_addr.s_addr = INADDR_ANY;
269 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
272 *errormessage = (char*) malloc(SIZ + 1);
273 snprintf(*errormessage, SIZ,
274 "citserver: Can't create a socket: %s",
276 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
281 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
283 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
284 *errormessage = (char*) malloc(SIZ + 1);
285 snprintf(*errormessage, SIZ,
286 "citserver: Can't bind: %s",
288 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
293 /* set to nonblock - we need this for some obscure situations */
294 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
295 *errormessage = (char*) malloc(SIZ + 1);
296 snprintf(*errormessage, SIZ,
297 "citserver: Can't set socket to non-blocking: %s",
299 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
304 if (listen(s, actual_queue_len) < 0) {
305 *errormessage = (char*) malloc(SIZ + 1);
306 snprintf(*errormessage, SIZ,
307 "citserver: Can't listen: %s",
309 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
320 * Create a Unix domain socket and listen on it
322 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
324 struct sockaddr_un addr;
327 int actual_queue_len;
328 #ifdef HAVE_STRUCT_UCRED
332 actual_queue_len = queue_len;
333 if (actual_queue_len < 5) actual_queue_len = 5;
335 i = unlink(sockpath);
336 if ((i != 0) && (errno != ENOENT)) {
337 *errormessage = (char*) malloc(SIZ + 1);
338 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
339 sockpath, strerror(errno));
340 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
344 memset(&addr, 0, sizeof(addr));
345 addr.sun_family = AF_UNIX;
346 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
348 s = socket(AF_UNIX, SOCK_STREAM, 0);
350 *errormessage = (char*) malloc(SIZ + 1);
351 snprintf(*errormessage, SIZ,
352 "citserver: Can't create a socket: %s",
354 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
358 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
359 *errormessage = (char*) malloc(SIZ + 1);
360 snprintf(*errormessage, SIZ,
361 "citserver: Can't bind: %s",
363 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
367 /* set to nonblock - we need this for some obscure situations */
368 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
369 *errormessage = (char*) malloc(SIZ + 1);
370 snprintf(*errormessage, SIZ,
371 "citserver: Can't set socket to non-blocking: %s",
373 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
378 if (listen(s, actual_queue_len) < 0) {
379 *errormessage = (char*) malloc(SIZ + 1);
380 snprintf(*errormessage, SIZ,
381 "citserver: Can't listen: %s",
383 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
387 #ifdef HAVE_STRUCT_UCRED
388 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
391 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
398 * The following functions implement output buffering on operating systems which
399 * support it (such as Linux and various BSD flavors).
403 # define HAVE_TCP_BUFFERING
406 # define HAVE_TCP_BUFFERING
407 # define TCP_CORK TCP_NOPUSH
409 #endif /* TCP_CORK */
410 #endif /* HAVE_DARWIN */
412 static unsigned on = 1, off = 0;
414 void buffer_output(void) {
415 #ifdef HAVE_TCP_BUFFERING
417 if (!CC->redirect_ssl)
419 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
423 void unbuffer_output(void) {
424 #ifdef HAVE_TCP_BUFFERING
426 if (!CC->redirect_ssl)
428 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
432 void flush_output(void) {
433 #ifdef HAVE_TCP_BUFFERING
434 struct CitContext *CCC = CC;
435 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
436 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
443 * client_write() ... Send binary data to the client.
445 int client_write(char *buf, int nbytes)
447 int bytes_written = 0;
449 #ifndef HAVE_TCP_BUFFERING
450 int old_buffer_len = 0;
457 if (Ctx->redirect_buffer != NULL) {
458 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
459 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
460 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
461 Ctx->redirect_alloc);
463 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
464 Ctx->redirect_len += nbytes;
465 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
470 if (Ctx->redirect_ssl) {
471 client_write_ssl(buf, nbytes);
476 fdflags = fcntl(Ctx->client_socket, F_GETFL);
478 while (bytes_written < nbytes) {
479 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
481 FD_SET(Ctx->client_socket, &wset);
482 if (select(1, NULL, &wset, NULL, NULL) == -1) {
483 CtdlLogPrintf(CTDL_ERR,
484 "client_write(%d bytes) select failed: %s (%d)\n",
485 nbytes - bytes_written,
486 strerror(errno), errno);
493 retval = write(Ctx->client_socket, &buf[bytes_written],
494 nbytes - bytes_written);
496 CtdlLogPrintf(CTDL_ERR,
497 "client_write(%d bytes) failed: %s (%d)\n",
498 nbytes - bytes_written,
499 strerror(errno), errno);
501 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
505 bytes_written = bytes_written + retval;
512 * cprintf() Send formatted printable data to the client.
513 * Implemented in terms of client_write() so it's technically not sysdep...
515 void cprintf(const char *format, ...) {
519 va_start(arg_ptr, format);
520 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
521 buf[sizeof buf - 2] = '\n';
522 client_write(buf, strlen(buf));
528 * Read data from the client socket.
530 * 1 Requested number of bytes has been read.
531 * 0 Request timed out.
532 * -1 The socket is broken.
533 * If the socket breaks, the session will be terminated.
535 int client_read_to(char *buf, int bytes, int timeout)
544 if (CC->redirect_ssl) {
545 return (client_read_ssl(buf, bytes, timeout));
549 fd = CC->client_socket;
556 retval = select( (fd)+1,
557 &rfds, NULL, NULL, &tv);
562 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
568 if (FD_ISSET(fd, &rfds) == 0) {
572 rlen = read(fd, &buf[len], bytes-len);
574 /* The socket has been disconnected! */
584 * Read data from the client socket with default timeout.
585 * (This is implemented in terms of client_read_to() and could be
586 * justifiably moved out of sysdep.c)
588 INLINE int client_read(char *buf, int bytes)
590 return(client_read_to(buf, bytes, config.c_sleeping));
595 * client_getln() ... Get a LF-terminated line of text from the client.
596 * (This is implemented in terms of client_read() and could be
597 * justifiably moved out of sysdep.c)
599 int client_getln(char *buf, int bufsize)
603 /* Read one character at a time.
606 retval = client_read(&buf[i], 1);
607 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
611 /* If we got a long line, discard characters until the newline.
613 if (i == (bufsize-1))
614 while (buf[i] != '\n' && retval == 1)
615 retval = client_read(&buf[i], 1);
617 /* Strip the trailing LF, and the trailing CR if present.
621 && ( (buf[i - 1]==13)
622 || ( buf[i - 1]==10)) ) {
626 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
632 * Cleanup any contexts that are left lying around
636 void close_masters (void)
638 struct ServiceFunctionHook *serviceptr;
641 * close all protocol master sockets
643 for (serviceptr = ServiceHookTable; serviceptr != NULL;
644 serviceptr = serviceptr->next ) {
646 if (serviceptr->tcp_port > 0)
648 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
649 serviceptr->tcp_port);
650 serviceptr->tcp_port = 0;
653 if (serviceptr->sockpath != NULL)
654 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
655 serviceptr->sockpath);
657 close(serviceptr->msock);
658 /* If it's a Unix domain socket, remove the file. */
659 if (serviceptr->sockpath != NULL) {
660 unlink(serviceptr->sockpath);
661 serviceptr->sockpath = NULL;
668 * The system-dependent part of master_cleanup() - close the master socket.
670 void sysdep_master_cleanup(void) {
679 CtdlDestroyProtoHooks();
680 CtdlDestroyDeleteHooks();
681 CtdlDestroyXmsgHooks();
682 CtdlDestroyNetprocHooks();
683 CtdlDestroyUserHooks();
684 CtdlDestroyMessageHook();
685 CtdlDestroyCleanupHooks();
686 CtdlDestroyFixedOutputHooks();
687 CtdlDestroySessionHooks();
688 CtdlDestroyServiceHook();
689 CtdlDestroyRoomHooks();
690 #ifdef HAVE_BACKTRACE
698 void graceful_shutdown(int signum) {
699 kill(current_child, signum);
700 unlink(file_pid_file);
705 int nFireUpsNonRestart = 0;
709 * Start running as a daemon.
711 void start_daemon(int unused) {
719 /* Close stdin/stdout/stderr and replace them with /dev/null.
720 * We don't just call close() because we don't want these fd's
721 * to be reused for other files.
730 signal(SIGHUP, SIG_IGN);
731 signal(SIGINT, SIG_IGN);
732 signal(SIGQUIT, SIG_IGN);
736 freopen("/dev/null", "r", stdin);
737 freopen("/dev/null", "w", stdout);
738 freopen("/dev/null", "w", stderr);
741 current_child = fork();
743 signal(SIGTERM, graceful_shutdown);
745 if (current_child < 0) {
750 else if (current_child == 0) {
751 return; /* continue starting citadel. */
755 fp = fopen(file_pid_file, "w");
757 fprintf(fp, ""F_PID_T"\n", getpid());
760 waitpid(current_child, &status, 0);
763 nFireUpsNonRestart = nFireUps;
765 /* Exit code 0 means the watcher should exit */
766 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
770 /* Exit code 101-109 means the watcher should exit */
771 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
775 /* Any other exit code, or no exit code, means we should restart. */
779 ForkedPid = current_child;
782 } while (do_restart);
784 unlink(file_pid_file);
785 exit(WEXITSTATUS(status));
790 void checkcrash(void)
792 if (nFireUpsNonRestart != nFireUps)
796 CrashMail = NewStrBuf();
797 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
798 StrBufPrintf(CrashMail,
800 " The Citadel server process (citserver) terminated unexpectedly."
802 " This could be the result of a bug in the server program, or some external "
804 " You can obtain more information about this by enabling core dumps.\n \n"
805 " For more information, please see:\n \n"
806 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
808 " If you have already done this, the core dump is likely to be found at %score.%d\n"
810 ctdl_run_dir, ForkedPid);
811 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
812 FreeStrBuf(&CrashMail);
818 * Generic routine to convert a login name to a full name (gecos)
819 * Returns nonzero if a conversion took place
821 int convert_login(char NameToConvert[]) {
825 pw = getpwnam(NameToConvert);
830 strcpy(NameToConvert, pw->pw_gecos);
831 for (a=0; a<strlen(NameToConvert); ++a) {
832 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
841 * This loop just keeps going and going and going...
845 * This current implimentation of worker_thread creates a bottle neck in several situations
846 * The first thing to remember is that a single thread can handle more than one connection at a time.
847 * More threads mean less memory for the system to run in.
848 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
849 * something to happen anywhere.
850 * This current implimentation requires worker threads to wait in other locations, after it has
851 * been committed to a single connection which is very wasteful.
852 * As an extreme case consider this:
853 * A slow client connects and this slow client sends only one character each second.
854 * With this current implimentation a single worker thread is dispatched to handle that connection
855 * until such times as the client timeout expires, an error occurs on the socket or the client
856 * completes its transmission.
857 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
858 * second interval between chars.
860 * It is my intention to re-write this code and the associated client_getln, client_read functions
861 * to allow any thread to read data on behalf of any connection (context).
862 * To do this I intend to have this main loop read chars into a buffer stored in the context.
863 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
865 * This worker thread loop also needs to be able to handle binary data.
868 void *worker_thread(void *arg) {
871 struct CitContext *ptr;
872 struct CitContext *bind_me = NULL;
875 struct CitContext *con= NULL; /* Temporary context pointer */
876 struct ServiceFunctionHook *serviceptr;
877 int ssock; /* Descriptor for client socket */
883 while (!CtdlThreadCheckStop()) {
885 /* make doubly sure we're not holding any stale db handles
886 * which might cause a deadlock.
889 do_select: force_purge = 0;
890 bind_me = NULL; /* Which session shall we handle? */
892 /* Initialize the fdset. */
896 begin_critical_section(S_SESSION_TABLE);
897 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
898 /* Dont select on dead sessions only truly idle ones */
899 if ((ptr->state == CON_IDLE)) {
900 FD_SET(ptr->client_socket, &readfds);
901 if (ptr->client_socket > highest)
902 highest = ptr->client_socket;
904 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
906 ptr->state = CON_EXECUTING;
909 end_critical_section(S_SESSION_TABLE);
915 /* If we got this far, it means that there are no sessions
916 * which a previous thread marked for attention, so we go
917 * ahead and get ready to select().
920 /* First, add the various master sockets to the fdset. */
921 for (serviceptr = ServiceHookTable; serviceptr != NULL;
922 serviceptr = serviceptr->next ) {
923 m = serviceptr->msock;
930 if (!CtdlThreadCheckStop()) {
931 tv.tv_sec = 1; /* wake up every second if no input */
933 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
938 /* Now figure out who made this select() unblock.
939 * First, check for an error or exit condition.
942 if (errno == EBADF) {
943 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
947 if (errno != EINTR) {
948 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
951 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
952 if (CtdlThreadCheckStop()) return(NULL);
956 else if(retval == 0) {
957 if (CtdlThreadCheckStop()) return(NULL);
960 /* Next, check to see if it's a new client connecting
961 * on a master socket.
963 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
964 serviceptr = serviceptr->next ) {
966 if (FD_ISSET(serviceptr->msock, &readfds)) {
967 ssock = accept(serviceptr->msock, NULL, 0);
969 CtdlLogPrintf(CTDL_DEBUG,
970 "New client socket %d\n",
973 /* The master socket is non-blocking but the client
974 * sockets need to be blocking, otherwise certain
975 * operations barf on FreeBSD. Not a fatal error.
977 if (fcntl(ssock, F_SETFL, 0) < 0) {
978 CtdlLogPrintf(CTDL_EMERG,
979 "citserver: Can't set socket to blocking: %s\n",
983 /* New context will be created already
984 * set up in the CON_EXECUTING state.
986 con = CreateNewContext();
988 /* Assign our new socket number to it. */
989 con->client_socket = ssock;
990 con->h_command_function =
991 serviceptr->h_command_function;
992 con->h_async_function =
993 serviceptr->h_async_function;
995 serviceptr->ServiceName;
997 /* Determine whether it's a local socket */
998 if (serviceptr->sockpath != NULL)
999 con->is_local_socket = 1;
1001 /* Set the SO_REUSEADDR socket option */
1003 setsockopt(ssock, SOL_SOCKET,
1007 become_session(con);
1009 serviceptr->h_greeting_function();
1010 become_session(NULL);
1011 con->state = CON_IDLE;
1017 /* It must be a client socket. Find a context that has data
1018 * waiting on its socket *and* is in the CON_IDLE state. Any
1019 * active sockets other than our chosen one are marked as
1020 * CON_READY so the next thread that comes around can just bind
1021 * to one without having to select() again.
1023 begin_critical_section(S_SESSION_TABLE);
1024 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1025 if ( (FD_ISSET(ptr->client_socket, &readfds))
1026 && (ptr->state != CON_EXECUTING) ) {
1027 ptr->input_waiting = 1;
1029 bind_me = ptr; /* I choose you! */
1030 bind_me->state = CON_EXECUTING;
1033 ptr->state = CON_READY;
1037 end_critical_section(S_SESSION_TABLE);
1040 /* We're bound to a session */
1041 if (bind_me != NULL) {
1042 become_session(bind_me);
1044 /* If the client has sent a command, execute it. */
1045 if (CC->input_waiting) {
1046 CC->h_command_function();
1047 CC->input_waiting = 0;
1050 /* If there are asynchronous messages waiting and the
1051 * client supports it, do those now */
1052 if ((CC->is_async) && (CC->async_waiting)
1053 && (CC->h_async_function != NULL)) {
1054 CC->h_async_function();
1055 CC->async_waiting = 0;
1058 force_purge = CC->kill_me;
1059 become_session(NULL);
1060 bind_me->state = CON_IDLE;
1063 dead_session_purge(force_purge);
1066 /* If control reaches this point, the server is shutting down */
1075 * Translate text facility name to syslog.h defined value.
1077 int SyslogFacility(char *name)
1086 { LOG_KERN, "kern" },
1087 { LOG_USER, "user" },
1088 { LOG_MAIL, "mail" },
1089 { LOG_DAEMON, "daemon" },
1090 { LOG_AUTH, "auth" },
1091 { LOG_SYSLOG, "syslog" },
1093 { LOG_NEWS, "news" },
1094 { LOG_UUCP, "uucp" },
1095 { LOG_LOCAL0, "local0" },
1096 { LOG_LOCAL1, "local1" },
1097 { LOG_LOCAL2, "local2" },
1098 { LOG_LOCAL3, "local3" },
1099 { LOG_LOCAL4, "local4" },
1100 { LOG_LOCAL5, "local5" },
1101 { LOG_LOCAL6, "local6" },
1102 { LOG_LOCAL7, "local7" },
1105 for(i = 0; facTbl[i].name != NULL; i++) {
1106 if(!strcasecmp(name, facTbl[i].name))
1107 return facTbl[i].facility;
1114 /********** MEM CHEQQER ***********/
1116 #ifdef DEBUG_MEMORY_LEAKS
1123 void *tracked_malloc(size_t size, char *file, int line) {
1124 struct igheap *thisheap;
1127 block = malloc(size);
1128 if (block == NULL) return(block);
1130 thisheap = malloc(sizeof(struct igheap));
1131 if (thisheap == NULL) {
1136 thisheap->block = block;
1137 strcpy(thisheap->file, file);
1138 thisheap->line = line;
1140 begin_critical_section(S_DEBUGMEMLEAKS);
1141 thisheap->next = igheap;
1143 end_critical_section(S_DEBUGMEMLEAKS);
1149 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1150 struct igheap *thisheap;
1153 block = realloc(ptr, size);
1154 if (block == NULL) return(block);
1156 thisheap = malloc(sizeof(struct igheap));
1157 if (thisheap == NULL) {
1162 thisheap->block = block;
1163 strcpy(thisheap->file, file);
1164 thisheap->line = line;
1166 begin_critical_section(S_DEBUGMEMLEAKS);
1167 thisheap->next = igheap;
1169 end_critical_section(S_DEBUGMEMLEAKS);
1176 void tracked_free(void *ptr) {
1177 struct igheap *thisheap;
1178 struct igheap *trash;
1182 if (igheap == NULL) return;
1183 begin_critical_section(S_DEBUGMEMLEAKS);
1184 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1185 if (thisheap->next != NULL) {
1186 if (thisheap->next->block == ptr) {
1187 trash = thisheap->next;
1188 thisheap->next = thisheap->next->next;
1193 if (igheap->block == ptr) {
1195 igheap = igheap->next;
1198 end_critical_section(S_DEBUGMEMLEAKS);
1201 char *tracked_strdup(const char *s, char *file, int line) {
1204 if (s == NULL) return(NULL);
1205 ptr = tracked_malloc(strlen(s) + 1, file, line);
1206 if (ptr == NULL) return(NULL);
1207 strncpy(ptr, s, strlen(s));
1211 void dump_heap(void) {
1212 struct igheap *thisheap;
1214 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1215 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1216 thisheap->file, thisheap->line);
1220 #endif /* DEBUG_MEMORY_LEAKS */