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);
439 static void flush_client_inbuf(void)
443 FlushStrBuf(CCC->ReadBuf);
449 * client_write() ... Send binary data to the client.
451 int client_write(const char *buf, int nbytes)
453 int bytes_written = 0;
455 #ifndef HAVE_TCP_BUFFERING
456 int old_buffer_len = 0;
462 // flush_client_inbuf();
464 if (Ctx->redirect_buffer != NULL) {
465 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
466 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
467 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
468 Ctx->redirect_alloc);
470 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
471 Ctx->redirect_len += nbytes;
472 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
477 if (Ctx->redirect_ssl) {
478 client_write_ssl(buf, nbytes);
482 if (Ctx->client_socket == -1) return -1;
484 fdflags = fcntl(Ctx->client_socket, F_GETFL);
486 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
487 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
489 FD_SET(Ctx->client_socket, &wset);
490 if (select(1, NULL, &wset, NULL, NULL) == -1) {
493 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
494 if (CtdlThreadCheckStop()) {
498 /* can't trust fd's and stuff so we need to re-create them */
502 CtdlLogPrintf(CTDL_ERR,
503 "client_write(%d bytes) select failed: %s (%d)\n",
504 nbytes - bytes_written,
505 strerror(errno), errno);
513 retval = write(Ctx->client_socket, &buf[bytes_written],
514 nbytes - bytes_written);
516 CtdlLogPrintf(CTDL_ERR,
517 "client_write(%d bytes) failed: %s (%d)\n",
518 nbytes - bytes_written,
519 strerror(errno), errno);
521 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
525 bytes_written = bytes_written + retval;
530 void cputbuf(const StrBuf *Buf) {
531 client_write(ChrPtr(Buf), StrLength(Buf));
536 * cprintf() Send formatted printable data to the client.
537 * Implemented in terms of client_write() so it's technically not sysdep...
539 void cprintf(const char *format, ...) {
543 va_start(arg_ptr, format);
544 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
545 buf[sizeof buf - 2] = '\n';
546 client_write(buf, strlen(buf));
552 * Read data from the client socket.
554 * sock socket fd to read from
555 * buf buffer to read into
556 * bytes number of bytes to read
557 * timeout Number of seconds to wait before timing out
559 * Possible return values:
560 * 1 Requested number of bytes has been read.
561 * 0 Request timed out.
562 * -1 Connection is broken, or other error.
564 int client_read_blob(StrBuf *Target, int bytes, int timeout)
571 if (CCC->redirect_ssl) {
572 retval = client_read_sslblob(Target, bytes, timeout);
577 retval = StrBufReadBLOBBuffered(Target,
586 CtdlLogPrintf(CTDL_CRIT,
591 return retval == bytes;
594 int client_read_to(char *buf, int bytes, int timeout)
599 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
608 ChrPtr(CCC->MigrateBuf),
609 StrLength(CCC->MigrateBuf) + 1);
610 FlushStrBuf(CCC->MigrateBuf);
616 int HaveMoreLinesWaiting(CitContext *CCC)
618 if ((CCC->Pos == NULL) && (StrLength(CCC->ReadBuf) == 0))
626 * Read data from the client socket with default timeout.
627 * (This is implemented in terms of client_read_to() and could be
628 * justifiably moved out of sysdep.c)
630 INLINE int client_read(char *buf, int bytes)
632 return(client_read_to(buf, bytes, config.c_sleeping));
635 int CtdlClientGetLine(StrBuf *Target)
643 if (CCC->redirect_ssl) {
644 return client_readline_sslbuffer(Target,
653 int len, rlen, nlen, nrlen;
656 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
658 fd = fopen(fn, "a+");
659 pch = ChrPtr(CCC->ReadBuf);
660 len = StrLength(CCC->ReadBuf);
661 if (CCC->Pos != NULL)
662 rlen = CC->Pos - pch;
666 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
669 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
671 rc = StrBufTCP_read_buffered_line_fast(Target,
679 pch = ChrPtr(CCC->ReadBuf);
680 nlen = StrLength(CCC->ReadBuf);
681 if (CCC->Pos != NULL)
682 nrlen = CC->Pos - pch;
686 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
687 len, nlen, rlen, nrlen, pch);
689 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
690 len, nlen, rlen, nrlen);
692 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
693 StrLength(Target), ChrPtr(Target));
696 if ((rc < 0) && (Error != NULL))
697 CtdlLogPrintf(CTDL_CRIT,
707 * client_getln() ... Get a LF-terminated line of text from the client.
708 * (This is implemented in terms of client_read() and could be
709 * justifiably moved out of sysdep.c)
711 int client_getln(char *buf, int bufsize)
717 retval = CtdlClientGetLine(CCC->MigrateBuf);
719 i = StrLength(CCC->MigrateBuf);
720 pCh = ChrPtr(CCC->MigrateBuf);
721 /* Strip the trailing LF, and the trailing CR if present.
726 && ( (pCh[i - 1]==13)
727 || ( pCh[i - 1]==10)) ) {
733 FlushStrBuf(CCC->MigrateBuf);
735 safestrncpy(&buf[i], "000", bufsize - i);
742 * Cleanup any contexts that are left lying around
746 void close_masters (void)
748 struct ServiceFunctionHook *serviceptr;
751 * close all protocol master sockets
753 for (serviceptr = ServiceHookTable; serviceptr != NULL;
754 serviceptr = serviceptr->next ) {
756 if (serviceptr->tcp_port > 0)
758 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
759 serviceptr->tcp_port);
760 serviceptr->tcp_port = 0;
763 if (serviceptr->sockpath != NULL)
764 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
765 serviceptr->sockpath);
767 close(serviceptr->msock);
768 /* If it's a Unix domain socket, remove the file. */
769 if (serviceptr->sockpath != NULL) {
770 unlink(serviceptr->sockpath);
771 serviceptr->sockpath = NULL;
778 * The system-dependent part of master_cleanup() - close the master socket.
780 void sysdep_master_cleanup(void) {
789 CtdlDestroyProtoHooks();
790 CtdlDestroyDeleteHooks();
791 CtdlDestroyXmsgHooks();
792 CtdlDestroyNetprocHooks();
793 CtdlDestroyUserHooks();
794 CtdlDestroyMessageHook();
795 CtdlDestroyCleanupHooks();
796 CtdlDestroyFixedOutputHooks();
797 CtdlDestroySessionHooks();
798 CtdlDestroyServiceHook();
799 CtdlDestroyRoomHooks();
800 #ifdef HAVE_BACKTRACE
808 void graceful_shutdown(int signum) {
809 kill(current_child, signum);
810 unlink(file_pid_file);
815 int nFireUpsNonRestart = 0;
819 * Start running as a daemon.
821 void start_daemon(int unused) {
829 /* Close stdin/stdout/stderr and replace them with /dev/null.
830 * We don't just call close() because we don't want these fd's
831 * to be reused for other files.
833 if (chdir(ctdl_run_dir) != 0)
834 CtdlLogPrintf(CTDL_EMERG,
835 "unable to change into directory [%s]: %s",
836 ctdl_run_dir, strerror(errno));
843 signal(SIGHUP, SIG_IGN);
844 signal(SIGINT, SIG_IGN);
845 signal(SIGQUIT, SIG_IGN);
849 if ((freopen("/dev/null", "r", stdin) != stdin) ||
850 (freopen("/dev/null", "w", stdout) != stdout) ||
851 (freopen("/dev/null", "w", stderr) != stderr))
852 CtdlLogPrintf(CTDL_EMERG,
853 "unable to reopen stdin/out/err %s",
858 current_child = fork();
860 signal(SIGTERM, graceful_shutdown);
862 if (current_child < 0) {
867 else if (current_child == 0) {
868 return; /* continue starting citadel. */
872 fp = fopen(file_pid_file, "w");
874 fprintf(fp, ""F_PID_T"\n", getpid());
877 waitpid(current_child, &status, 0);
880 nFireUpsNonRestart = nFireUps;
882 /* Exit code 0 means the watcher should exit */
883 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
887 /* Exit code 101-109 means the watcher should exit */
888 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
892 /* Any other exit code, or no exit code, means we should restart. */
896 ForkedPid = current_child;
899 } while (do_restart);
901 unlink(file_pid_file);
902 exit(WEXITSTATUS(status));
907 void checkcrash(void)
909 if (nFireUpsNonRestart != nFireUps)
913 CrashMail = NewStrBuf();
914 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
915 StrBufPrintf(CrashMail,
917 " The Citadel server process (citserver) terminated unexpectedly."
919 " This could be the result of a bug in the server program, or some external "
921 " You can obtain more information about this by enabling core dumps.\n \n"
922 " For more information, please see:\n \n"
923 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
926 " If you have already done this, the core dump is likely to be found at %score.%d\n"
928 ctdl_run_dir, ForkedPid);
929 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
930 FreeStrBuf(&CrashMail);
936 * Generic routine to convert a login name to a full name (gecos)
937 * Returns nonzero if a conversion took place
939 int convert_login(char NameToConvert[]) {
943 pw = getpwnam(NameToConvert);
948 strcpy(NameToConvert, pw->pw_gecos);
949 for (a=0; a<strlen(NameToConvert); ++a) {
950 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
959 * This loop just keeps going and going and going...
963 * This current implimentation of worker_thread creates a bottle neck in several situations
964 * The first thing to remember is that a single thread can handle more than one connection at a time.
965 * More threads mean less memory for the system to run in.
966 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
967 * something to happen anywhere.
968 * This current implimentation requires worker threads to wait in other locations, after it has
969 * been committed to a single connection which is very wasteful.
970 * As an extreme case consider this:
971 * A slow client connects and this slow client sends only one character each second.
972 * With this current implimentation a single worker thread is dispatched to handle that connection
973 * until such times as the client timeout expires, an error occurs on the socket or the client
974 * completes its transmission.
975 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
976 * second interval between chars.
978 * It is my intention to re-write this code and the associated client_getln, client_read functions
979 * to allow any thread to read data on behalf of any connection (context).
980 * To do this I intend to have this main loop read chars into a buffer stored in the context.
981 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
983 * This worker thread loop also needs to be able to handle binary data.
986 void *worker_thread(void *arg) {
989 CitContext *bind_me = NULL;
996 while (!CtdlThreadCheckStop()) {
998 /* make doubly sure we're not holding any stale db handles
999 * which might cause a deadlock.
1001 cdb_check_handles();
1002 do_select: force_purge = 0;
1003 bind_me = NULL; /* Which session shall we handle? */
1005 /* Initialize the fdset. */
1009 begin_critical_section(S_SESSION_TABLE);
1010 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1012 client_socket = ptr->client_socket;
1013 /* Dont select on dead sessions only truly idle ones */
1014 if ((ptr->state == CON_IDLE) &&
1015 (CC->kill_me == 0) &&
1016 (client_socket != -1))
1018 FD_SET(client_socket, &readfds);
1019 if (client_socket > highest)
1020 highest = client_socket;
1022 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1024 ptr->state = CON_EXECUTING;
1027 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1029 ptr->state = CON_STARTING;
1033 end_critical_section(S_SESSION_TABLE);
1039 /* If we got this far, it means that there are no sessions
1040 * which a previous thread marked for attention, so we go
1041 * ahead and get ready to select().
1044 if (!CtdlThreadCheckStop()) {
1045 tv.tv_sec = 1; /* wake up every second if no input */
1047 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1052 /* Now figure out who made this select() unblock.
1053 * First, check for an error or exit condition.
1056 if (errno == EBADF) {
1057 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1061 if (errno != EINTR) {
1062 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1063 CtdlThreadStopAll();
1066 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1067 if (CtdlThreadCheckStop()) return(NULL);
1071 else if(retval == 0) {
1072 if (CtdlThreadCheckStop()) return(NULL);
1075 /* It must be a client socket. Find a context that has data
1076 * waiting on its socket *and* is in the CON_IDLE state. Any
1077 * active sockets other than our chosen one are marked as
1078 * CON_READY so the next thread that comes around can just bind
1079 * to one without having to select() again.
1081 begin_critical_section(S_SESSION_TABLE);
1082 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1083 int checkfd = ptr->client_socket;
1084 if ((checkfd != -1) &&
1085 (FD_ISSET(checkfd, &readfds)) &&
1086 (ptr->state == CON_IDLE) )
1088 ptr->input_waiting = 1;
1090 bind_me = ptr; /* I choose you! */
1091 bind_me->state = CON_EXECUTING;
1094 ptr->state = CON_READY;
1098 end_critical_section(S_SESSION_TABLE);
1101 /* We're bound to a session */
1102 if (bind_me != NULL) {
1103 become_session(bind_me);
1105 if (bind_me->state == CON_STARTING) {
1106 bind_me->state = CON_EXECUTING;
1107 begin_session(bind_me);
1108 bind_me->h_greeting_function();
1110 /* If the client has sent a command, execute it. */
1111 if (CC->input_waiting) {
1112 CC->h_command_function();
1114 while (HaveMoreLinesWaiting(CC))
1115 CC->h_command_function();
1117 CC->input_waiting = 0;
1120 /* If there are asynchronous messages waiting and the
1121 * client supports it, do those now */
1122 if ((CC->is_async) && (CC->async_waiting)
1123 && (CC->h_async_function != NULL)) {
1124 CC->h_async_function();
1125 CC->async_waiting = 0;
1128 force_purge = CC->kill_me;
1129 become_session(NULL);
1130 bind_me->state = CON_IDLE;
1133 dead_session_purge(force_purge);
1136 /* If control reaches this point, the server is shutting down */
1144 * A function to handle selecting on master sockets.
1145 * In other words it handles new connections.
1148 void *select_on_master (void *arg)
1150 struct ServiceFunctionHook *serviceptr;
1154 int ssock; /* Descriptor for client socket */
1155 CitContext *con= NULL; /* Temporary context pointer */
1160 while (!CtdlThreadCheckStop()) {
1161 /* Initialize the fdset. */
1162 FD_ZERO(&master_fds);
1165 /* First, add the various master sockets to the fdset. */
1166 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1167 serviceptr = serviceptr->next ) {
1168 m = serviceptr->msock;
1169 FD_SET(m, &master_fds);
1175 if (!CtdlThreadCheckStop()) {
1176 tv.tv_sec = 60; /* wake up every second if no input */
1178 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1183 /* Now figure out who made this select() unblock.
1184 * First, check for an error or exit condition.
1187 if (errno == EBADF) {
1188 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1192 if (errno != EINTR) {
1193 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1194 CtdlThreadStopAll();
1196 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1197 if (CtdlThreadCheckStop()) return(NULL);
1201 else if(retval == 0) {
1202 if (CtdlThreadCheckStop()) return(NULL);
1205 /* Next, check to see if it's a new client connecting
1206 * on a master socket.
1208 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1209 serviceptr = serviceptr->next ) {
1211 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1212 ssock = accept(serviceptr->msock, NULL, 0);
1214 CtdlLogPrintf(CTDL_DEBUG,
1215 "New client socket %d\n",
1218 /* The master socket is non-blocking but the client
1219 * sockets need to be blocking, otherwise certain
1220 * operations barf on FreeBSD. Not a fatal error.
1222 if (fcntl(ssock, F_SETFL, 0) < 0) {
1223 CtdlLogPrintf(CTDL_EMERG,
1224 "citserver: Can't set socket to blocking: %s\n",
1228 /* New context will be created already
1229 * set up in the CON_EXECUTING state.
1231 con = CreateNewContext();
1233 /* Assign our new socket number to it. */
1234 con->client_socket = ssock;
1235 con->h_command_function =
1236 serviceptr->h_command_function;
1237 con->h_async_function =
1238 serviceptr->h_async_function;
1239 con->h_greeting_function = serviceptr->h_greeting_function;
1241 serviceptr->ServiceName;
1243 /* Determine whether it's a local socket */
1244 if (serviceptr->sockpath != NULL)
1245 con->is_local_socket = 1;
1247 /* Set the SO_REUSEADDR socket option */
1249 setsockopt(ssock, SOL_SOCKET,
1253 con->state = CON_GREETING;
1269 * Translate text facility name to syslog.h defined value.
1271 int SyslogFacility(char *name)
1280 { LOG_KERN, "kern" },
1281 { LOG_USER, "user" },
1282 { LOG_MAIL, "mail" },
1283 { LOG_DAEMON, "daemon" },
1284 { LOG_AUTH, "auth" },
1285 { LOG_SYSLOG, "syslog" },
1287 { LOG_NEWS, "news" },
1288 { LOG_UUCP, "uucp" },
1289 { LOG_LOCAL0, "local0" },
1290 { LOG_LOCAL1, "local1" },
1291 { LOG_LOCAL2, "local2" },
1292 { LOG_LOCAL3, "local3" },
1293 { LOG_LOCAL4, "local4" },
1294 { LOG_LOCAL5, "local5" },
1295 { LOG_LOCAL6, "local6" },
1296 { LOG_LOCAL7, "local7" },
1299 for(i = 0; facTbl[i].name != NULL; i++) {
1300 if(!strcasecmp(name, facTbl[i].name))
1301 return facTbl[i].facility;
1308 /********** MEM CHEQQER ***********/
1310 #ifdef DEBUG_MEMORY_LEAKS
1317 void *tracked_malloc(size_t size, char *file, int line) {
1318 struct igheap *thisheap;
1321 block = malloc(size);
1322 if (block == NULL) return(block);
1324 thisheap = malloc(sizeof(struct igheap));
1325 if (thisheap == NULL) {
1330 thisheap->block = block;
1331 strcpy(thisheap->file, file);
1332 thisheap->line = line;
1334 begin_critical_section(S_DEBUGMEMLEAKS);
1335 thisheap->next = igheap;
1337 end_critical_section(S_DEBUGMEMLEAKS);
1343 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1344 struct igheap *thisheap;
1347 block = realloc(ptr, size);
1348 if (block == NULL) return(block);
1350 thisheap = malloc(sizeof(struct igheap));
1351 if (thisheap == NULL) {
1356 thisheap->block = block;
1357 strcpy(thisheap->file, file);
1358 thisheap->line = line;
1360 begin_critical_section(S_DEBUGMEMLEAKS);
1361 thisheap->next = igheap;
1363 end_critical_section(S_DEBUGMEMLEAKS);
1370 void tracked_free(void *ptr) {
1371 struct igheap *thisheap;
1372 struct igheap *trash;
1376 if (igheap == NULL) return;
1377 begin_critical_section(S_DEBUGMEMLEAKS);
1378 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1379 if (thisheap->next != NULL) {
1380 if (thisheap->next->block == ptr) {
1381 trash = thisheap->next;
1382 thisheap->next = thisheap->next->next;
1387 if (igheap->block == ptr) {
1389 igheap = igheap->next;
1392 end_critical_section(S_DEBUGMEMLEAKS);
1395 char *tracked_strdup(const char *s, char *file, int line) {
1398 if (s == NULL) return(NULL);
1399 ptr = tracked_malloc(strlen(s) + 1, file, line);
1400 if (ptr == NULL) return(NULL);
1401 strncpy(ptr, s, strlen(s));
1405 void dump_heap(void) {
1406 struct igheap *thisheap;
1408 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1409 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1410 thisheap->file, thisheap->line);
1414 #endif /* DEBUG_MEMORY_LEAKS */