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;
172 static RETSIGTYPE signal_exit(int signum) {
179 * Some initialization stuff...
181 void init_sysdep(void) {
184 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
188 getrlimit(RLIMIT_NOFILE, &rl);
189 rl.rlim_cur = FD_SETSIZE;
190 rl.rlim_max = FD_SETSIZE;
191 setrlimit(RLIMIT_NOFILE, &rl);
195 /* If we've got OpenSSL, we're going to use it. */
201 * Set up a place to put thread-specific data.
202 * We only need a single pointer per thread - it points to the
203 * CitContext structure (in the ContextList linked list) of the
204 * session to which the calling thread is currently bound.
206 if (citthread_key_create(&MyConKey, NULL) != 0) {
207 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
212 * The action for unexpected signals and exceptions should be to
213 * call signal_cleanup() to gracefully shut down the server.
216 sigaddset(&set, SIGINT);
217 sigaddset(&set, SIGQUIT);
218 sigaddset(&set, SIGHUP);
219 sigaddset(&set, SIGTERM);
220 // sigaddset(&set, SIGSEGV); commented out because
221 // sigaddset(&set, SIGILL); we want core dumps
222 // sigaddset(&set, SIGBUS);
223 sigprocmask(SIG_UNBLOCK, &set, NULL);
225 signal(SIGINT, signal_cleanup);
226 signal(SIGQUIT, signal_cleanup);
227 signal(SIGHUP, signal_cleanup);
228 signal(SIGTERM, signal_cleanup);
229 signal(SIGUSR2, signal_exit);
230 // signal(SIGSEGV, signal_cleanup); commented out because
231 // signal(SIGILL, signal_cleanup); we want core dumps
232 // signal(SIGBUS, signal_cleanup);
235 * Do not shut down the server on broken pipe signals, otherwise the
236 * whole Citadel service would come down whenever a single client
239 signal(SIGPIPE, SIG_IGN);
246 * This is a generic function to set up a master socket for listening on
247 * a TCP port. The server shuts down if the bind fails.
250 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
252 struct sockaddr_in sin;
254 int actual_queue_len;
256 actual_queue_len = queue_len;
257 if (actual_queue_len < 5) actual_queue_len = 5;
259 memset(&sin, 0, sizeof(sin));
260 sin.sin_family = AF_INET;
261 sin.sin_port = htons((u_short)port_number);
262 if (ip_addr == NULL) {
263 sin.sin_addr.s_addr = INADDR_ANY;
266 sin.sin_addr.s_addr = inet_addr(ip_addr);
269 if (sin.sin_addr.s_addr == !INADDR_ANY) {
270 sin.sin_addr.s_addr = INADDR_ANY;
273 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
276 *errormessage = (char*) malloc(SIZ + 1);
277 snprintf(*errormessage, SIZ,
278 "citserver: Can't create a socket: %s",
280 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
285 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
287 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
288 *errormessage = (char*) malloc(SIZ + 1);
289 snprintf(*errormessage, SIZ,
290 "citserver: Can't bind: %s",
292 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
297 /* set to nonblock - we need this for some obscure situations */
298 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
299 *errormessage = (char*) malloc(SIZ + 1);
300 snprintf(*errormessage, SIZ,
301 "citserver: Can't set socket to non-blocking: %s",
303 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
308 if (listen(s, actual_queue_len) < 0) {
309 *errormessage = (char*) malloc(SIZ + 1);
310 snprintf(*errormessage, SIZ,
311 "citserver: Can't listen: %s",
313 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
324 * Create a Unix domain socket and listen on it
326 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
328 struct sockaddr_un addr;
331 int actual_queue_len;
332 #ifdef HAVE_STRUCT_UCRED
336 actual_queue_len = queue_len;
337 if (actual_queue_len < 5) actual_queue_len = 5;
339 i = unlink(sockpath);
340 if ((i != 0) && (errno != ENOENT)) {
341 *errormessage = (char*) malloc(SIZ + 1);
342 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
343 sockpath, strerror(errno));
344 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
348 memset(&addr, 0, sizeof(addr));
349 addr.sun_family = AF_UNIX;
350 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
352 s = socket(AF_UNIX, SOCK_STREAM, 0);
354 *errormessage = (char*) malloc(SIZ + 1);
355 snprintf(*errormessage, SIZ,
356 "citserver: Can't create a socket: %s",
358 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
362 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
363 *errormessage = (char*) malloc(SIZ + 1);
364 snprintf(*errormessage, SIZ,
365 "citserver: Can't bind: %s",
367 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
371 /* set to nonblock - we need this for some obscure situations */
372 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
373 *errormessage = (char*) malloc(SIZ + 1);
374 snprintf(*errormessage, SIZ,
375 "citserver: Can't set socket to non-blocking: %s",
377 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
382 if (listen(s, actual_queue_len) < 0) {
383 *errormessage = (char*) malloc(SIZ + 1);
384 snprintf(*errormessage, SIZ,
385 "citserver: Can't listen: %s",
387 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
391 #ifdef HAVE_STRUCT_UCRED
392 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
395 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
402 * The following functions implement output buffering on operating systems which
403 * support it (such as Linux and various BSD flavors).
407 # define HAVE_TCP_BUFFERING
410 # define HAVE_TCP_BUFFERING
411 # define TCP_CORK TCP_NOPUSH
413 #endif /* TCP_CORK */
414 #endif /* HAVE_DARWIN */
416 static unsigned on = 1, off = 0;
418 void buffer_output(void) {
419 #ifdef HAVE_TCP_BUFFERING
421 if (!CC->redirect_ssl)
423 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
427 void unbuffer_output(void) {
428 #ifdef HAVE_TCP_BUFFERING
430 if (!CC->redirect_ssl)
432 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
436 void flush_output(void) {
437 #ifdef HAVE_TCP_BUFFERING
438 struct CitContext *CCC = CC;
439 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
440 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
445 static void flush_client_inbuf(void)
449 FlushStrBuf(CCC->ReadBuf);
456 * client_write() ... Send binary data to the client.
458 int client_write(const char *buf, int nbytes)
460 int bytes_written = 0;
462 #ifndef HAVE_TCP_BUFFERING
463 int old_buffer_len = 0;
469 if (nbytes < 1) return(0);
471 // flush_client_inbuf();
473 if (Ctx->redirect_buffer != NULL) {
474 StrBufAppendBufPlain(Ctx->redirect_buffer,
480 if (Ctx->redirect_ssl) {
481 client_write_ssl(buf, nbytes);
485 if (Ctx->client_socket == -1) return -1;
487 fdflags = fcntl(Ctx->client_socket, F_GETFL);
489 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
490 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
492 FD_SET(Ctx->client_socket, &wset);
493 if (select(1, NULL, &wset, NULL, NULL) == -1) {
496 CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
497 if (CtdlThreadCheckStop()) {
501 /* can't trust fd's and stuff so we need to re-create them */
505 CtdlLogPrintf(CTDL_ERR,
506 "client_write(%d bytes) select failed: %s (%d)\n",
507 nbytes - bytes_written,
508 strerror(errno), errno);
516 retval = write(Ctx->client_socket, &buf[bytes_written],
517 nbytes - bytes_written);
519 CtdlLogPrintf(CTDL_ERR,
520 "client_write(%d bytes) failed: %s (%d)\n",
521 nbytes - bytes_written,
522 strerror(errno), errno);
524 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
528 bytes_written = bytes_written + retval;
533 void cputbuf(const StrBuf *Buf) {
534 client_write(ChrPtr(Buf), StrLength(Buf));
539 * cprintf() Send formatted printable data to the client.
540 * Implemented in terms of client_write() so it's technically not sysdep...
542 void cprintf(const char *format, ...) {
546 va_start(arg_ptr, format);
547 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
548 buf[sizeof buf - 2] = '\n';
549 client_write(buf, strlen(buf));
555 * Read data from the client socket.
557 * sock socket fd to read from
558 * buf buffer to read into
559 * bytes number of bytes to read
560 * timeout Number of seconds to wait before timing out
562 * Possible return values:
563 * 1 Requested number of bytes has been read.
564 * 0 Request timed out.
565 * -1 Connection is broken, or other error.
567 int client_read_blob(StrBuf *Target, int bytes, int timeout)
574 if (CCC->redirect_ssl) {
575 retval = client_read_sslblob(Target, bytes, timeout);
580 retval = StrBufReadBLOBBuffered(Target,
589 CtdlLogPrintf(CTDL_CRIT,
601 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
603 fd = fopen(fn, "a+");
604 fprintf(fd, "Read: BufSize: %d BufContent: [",
606 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
614 return retval == bytes;
617 int client_read_to(char *buf, int bytes, int timeout)
622 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
631 ChrPtr(CCC->MigrateBuf),
632 StrLength(CCC->MigrateBuf) + 1);
633 FlushStrBuf(CCC->MigrateBuf);
639 int HaveMoreLinesWaiting(CitContext *CCC)
641 if ((CCC->kill_me == 1) || (
642 (CCC->Pos == NULL) &&
643 (StrLength(CCC->ReadBuf) == 0) &&
644 (CCC->client_socket != -1)) )
652 * Read data from the client socket with default timeout.
653 * (This is implemented in terms of client_read_to() and could be
654 * justifiably moved out of sysdep.c)
656 INLINE int client_read(char *buf, int bytes)
658 return(client_read_to(buf, bytes, config.c_sleeping));
661 int CtdlClientGetLine(StrBuf *Target)
669 if (CCC->redirect_ssl) {
679 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
681 fd = fopen(fn, "a+");
682 pch = ChrPtr(CCC->ReadBuf);
683 len = StrLength(CCC->ReadBuf);
684 if (CCC->Pos != NULL)
685 rlen = CC->Pos - pch;
689 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
692 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
695 rc = client_readline_sslbuffer(Target,
700 pch = ChrPtr(CCC->ReadBuf);
701 nlen = StrLength(CCC->ReadBuf);
702 if (CCC->Pos != NULL)
703 nrlen = CC->Pos - pch;
707 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
708 len, nlen, rlen, nrlen, pch);
710 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
711 len, nlen, rlen, nrlen);
713 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
714 StrLength(Target), ChrPtr(Target));
718 CtdlLogPrintf(CTDL_CRIT,
730 int len, rlen, nlen, nrlen;
733 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
735 fd = fopen(fn, "a+");
736 pch = ChrPtr(CCC->ReadBuf);
737 len = StrLength(CCC->ReadBuf);
738 if (CCC->Pos != NULL)
739 rlen = CC->Pos - pch;
743 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
746 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
749 rc = StrBufTCP_read_buffered_line_fast(Target,
758 pch = ChrPtr(CCC->ReadBuf);
759 nlen = StrLength(CCC->ReadBuf);
760 if (CCC->Pos != NULL)
761 nrlen = CC->Pos - pch;
765 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
766 len, nlen, rlen, nrlen, pch);
768 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
769 len, nlen, rlen, nrlen);
771 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
772 StrLength(Target), ChrPtr(Target));
775 if ((rc < 0) && (Error != NULL))
776 CtdlLogPrintf(CTDL_CRIT,
787 * client_getln() ... Get a LF-terminated line of text from the client.
788 * (This is implemented in terms of client_read() and could be
789 * justifiably moved out of sysdep.c)
791 int client_getln(char *buf, int bufsize)
797 retval = CtdlClientGetLine(CCC->MigrateBuf);
802 i = StrLength(CCC->MigrateBuf);
803 pCh = ChrPtr(CCC->MigrateBuf);
804 /* Strip the trailing LF, and the trailing CR if present.
809 && ( (pCh[i - 1]==13)
810 || ( pCh[i - 1]==10)) ) {
816 FlushStrBuf(CCC->MigrateBuf);
818 safestrncpy(&buf[i], "000", bufsize - i);
825 * Cleanup any contexts that are left lying around
829 void close_masters (void)
831 struct ServiceFunctionHook *serviceptr;
834 * close all protocol master sockets
836 for (serviceptr = ServiceHookTable; serviceptr != NULL;
837 serviceptr = serviceptr->next ) {
839 if (serviceptr->tcp_port > 0)
841 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
842 serviceptr->tcp_port);
843 serviceptr->tcp_port = 0;
846 if (serviceptr->sockpath != NULL)
847 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
848 serviceptr->sockpath);
850 close(serviceptr->msock);
851 /* If it's a Unix domain socket, remove the file. */
852 if (serviceptr->sockpath != NULL) {
853 unlink(serviceptr->sockpath);
854 serviceptr->sockpath = NULL;
861 * The system-dependent part of master_cleanup() - close the master socket.
863 void sysdep_master_cleanup(void) {
872 CtdlDestroyProtoHooks();
873 CtdlDestroyDeleteHooks();
874 CtdlDestroyXmsgHooks();
875 CtdlDestroyNetprocHooks();
876 CtdlDestroyUserHooks();
877 CtdlDestroyMessageHook();
878 CtdlDestroyCleanupHooks();
879 CtdlDestroyFixedOutputHooks();
880 CtdlDestroySessionHooks();
881 CtdlDestroyServiceHook();
882 CtdlDestroyRoomHooks();
883 #ifdef HAVE_BACKTRACE
891 void graceful_shutdown(int signum) {
892 kill(current_child, signum);
893 unlink(file_pid_file);
898 int nFireUpsNonRestart = 0;
902 * Start running as a daemon.
904 void start_daemon(int unused) {
912 /* Close stdin/stdout/stderr and replace them with /dev/null.
913 * We don't just call close() because we don't want these fd's
914 * to be reused for other files.
916 if (chdir(ctdl_run_dir) != 0)
917 CtdlLogPrintf(CTDL_EMERG,
918 "unable to change into directory [%s]: %s",
919 ctdl_run_dir, strerror(errno));
926 signal(SIGHUP, SIG_IGN);
927 signal(SIGINT, SIG_IGN);
928 signal(SIGQUIT, SIG_IGN);
932 if ((freopen("/dev/null", "r", stdin) != stdin) ||
933 (freopen("/dev/null", "w", stdout) != stdout) ||
934 (freopen("/dev/null", "w", stderr) != stderr))
935 CtdlLogPrintf(CTDL_EMERG,
936 "unable to reopen stdin/out/err %s",
941 current_child = fork();
943 signal(SIGTERM, graceful_shutdown);
945 if (current_child < 0) {
950 else if (current_child == 0) {
951 return; /* continue starting citadel. */
955 fp = fopen(file_pid_file, "w");
957 fprintf(fp, ""F_PID_T"\n", getpid());
960 waitpid(current_child, &status, 0);
963 nFireUpsNonRestart = nFireUps;
965 /* Exit code 0 means the watcher should exit */
966 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
970 /* Exit code 101-109 means the watcher should exit */
971 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
975 /* Any other exit code, or no exit code, means we should restart. */
979 ForkedPid = current_child;
982 } while (do_restart);
984 unlink(file_pid_file);
985 exit(WEXITSTATUS(status));
990 void checkcrash(void)
992 if (nFireUpsNonRestart != nFireUps)
996 CrashMail = NewStrBuf();
997 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
998 StrBufPrintf(CrashMail,
1000 " The Citadel server process (citserver) terminated unexpectedly."
1002 " This could be the result of a bug in the server program, or some external "
1004 " You can obtain more information about this by enabling core dumps.\n \n"
1005 " For more information, please see:\n \n"
1006 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1009 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1011 ctdl_run_dir, ForkedPid);
1012 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1013 FreeStrBuf(&CrashMail);
1019 * Generic routine to convert a login name to a full name (gecos)
1020 * Returns nonzero if a conversion took place
1022 int convert_login(char NameToConvert[]) {
1026 pw = getpwnam(NameToConvert);
1031 strcpy(NameToConvert, pw->pw_gecos);
1032 for (a=0; a<strlen(NameToConvert); ++a) {
1033 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1042 * This loop just keeps going and going and going...
1046 * This current implimentation of worker_thread creates a bottle neck in several situations
1047 * The first thing to remember is that a single thread can handle more than one connection at a time.
1048 * More threads mean less memory for the system to run in.
1049 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1050 * something to happen anywhere.
1051 * This current implimentation requires worker threads to wait in other locations, after it has
1052 * been committed to a single connection which is very wasteful.
1053 * As an extreme case consider this:
1054 * A slow client connects and this slow client sends only one character each second.
1055 * With this current implimentation a single worker thread is dispatched to handle that connection
1056 * until such times as the client timeout expires, an error occurs on the socket or the client
1057 * completes its transmission.
1058 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1059 * second interval between chars.
1061 * It is my intention to re-write this code and the associated client_getln, client_read functions
1062 * to allow any thread to read data on behalf of any connection (context).
1063 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1064 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1066 * This worker thread loop also needs to be able to handle binary data.
1069 void *worker_thread(void *arg) {
1072 CitContext *bind_me = NULL;
1076 int force_purge = 0;
1079 while (!CtdlThreadCheckStop()) {
1081 /* make doubly sure we're not holding any stale db handles
1082 * which might cause a deadlock.
1084 cdb_check_handles();
1085 do_select: force_purge = 0;
1086 bind_me = NULL; /* Which session shall we handle? */
1088 /* Initialize the fdset. */
1092 begin_critical_section(S_SESSION_TABLE);
1093 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1095 client_socket = ptr->client_socket;
1096 /* Dont select on dead sessions only truly idle ones */
1097 if ((ptr->state == CON_IDLE) &&
1098 (CC->kill_me == 0) &&
1099 (client_socket != -1))
1101 FD_SET(client_socket, &readfds);
1102 if (client_socket > highest)
1103 highest = client_socket;
1105 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1107 ptr->state = CON_EXECUTING;
1110 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1112 ptr->state = CON_STARTING;
1116 end_critical_section(S_SESSION_TABLE);
1122 /* If we got this far, it means that there are no sessions
1123 * which a previous thread marked for attention, so we go
1124 * ahead and get ready to select().
1127 if (!CtdlThreadCheckStop()) {
1128 tv.tv_sec = 1; /* wake up every second if no input */
1130 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1135 /* Now figure out who made this select() unblock.
1136 * First, check for an error or exit condition.
1139 if (errno == EBADF) {
1140 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1144 if (errno != EINTR) {
1145 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1146 CtdlThreadStopAll();
1149 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1150 if (CtdlThreadCheckStop()) return(NULL);
1154 else if(retval == 0) {
1155 if (CtdlThreadCheckStop()) return(NULL);
1158 /* It must be a client socket. Find a context that has data
1159 * waiting on its socket *and* is in the CON_IDLE state. Any
1160 * active sockets other than our chosen one are marked as
1161 * CON_READY so the next thread that comes around can just bind
1162 * to one without having to select() again.
1164 begin_critical_section(S_SESSION_TABLE);
1165 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1166 int checkfd = ptr->client_socket;
1167 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1168 if (FD_ISSET(checkfd, &readfds)) {
1169 ptr->input_waiting = 1;
1171 bind_me = ptr; /* I choose you! */
1172 bind_me->state = CON_EXECUTING;
1175 ptr->state = CON_READY;
1177 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1179 bind_me = ptr; /* I choose you! */
1180 bind_me->state = CON_EXECUTING;
1183 ptr->state = CON_READY;
1188 end_critical_section(S_SESSION_TABLE);
1191 /* We're bound to a session */
1192 if (bind_me != NULL) {
1193 become_session(bind_me);
1195 if (bind_me->state == CON_STARTING) {
1196 bind_me->state = CON_EXECUTING;
1197 begin_session(bind_me);
1198 bind_me->h_greeting_function();
1200 /* If the client has sent a command, execute it. */
1201 if (CC->input_waiting) {
1202 CC->h_command_function();
1204 while (HaveMoreLinesWaiting(CC))
1205 CC->h_command_function();
1207 CC->input_waiting = 0;
1210 /* If there are asynchronous messages waiting and the
1211 * client supports it, do those now */
1212 if ((CC->is_async) && (CC->async_waiting)
1213 && (CC->h_async_function != NULL)) {
1214 CC->h_async_function();
1215 CC->async_waiting = 0;
1218 force_purge = CC->kill_me;
1219 become_session(NULL);
1220 bind_me->state = CON_IDLE;
1223 dead_session_purge(force_purge);
1226 /* If control reaches this point, the server is shutting down */
1234 * A function to handle selecting on master sockets.
1235 * In other words it handles new connections.
1238 void *select_on_master (void *arg)
1240 struct ServiceFunctionHook *serviceptr;
1244 int ssock; /* Descriptor for client socket */
1245 CitContext *con= NULL; /* Temporary context pointer */
1250 while (!CtdlThreadCheckStop()) {
1251 /* Initialize the fdset. */
1252 FD_ZERO(&master_fds);
1255 /* First, add the various master sockets to the fdset. */
1256 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1257 serviceptr = serviceptr->next ) {
1258 m = serviceptr->msock;
1259 FD_SET(m, &master_fds);
1265 if (!CtdlThreadCheckStop()) {
1266 tv.tv_sec = 60; /* wake up every second if no input */
1268 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1273 /* Now figure out who made this select() unblock.
1274 * First, check for an error or exit condition.
1277 if (errno == EBADF) {
1278 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1282 if (errno != EINTR) {
1283 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1284 CtdlThreadStopAll();
1286 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1287 if (CtdlThreadCheckStop()) return(NULL);
1291 else if(retval == 0) {
1292 if (CtdlThreadCheckStop()) return(NULL);
1295 /* Next, check to see if it's a new client connecting
1296 * on a master socket.
1298 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1299 serviceptr = serviceptr->next ) {
1301 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1302 ssock = accept(serviceptr->msock, NULL, 0);
1304 CtdlLogPrintf(CTDL_DEBUG,
1305 "New client socket %d\n",
1308 /* The master socket is non-blocking but the client
1309 * sockets need to be blocking, otherwise certain
1310 * operations barf on FreeBSD. Not a fatal error.
1312 if (fcntl(ssock, F_SETFL, 0) < 0) {
1313 CtdlLogPrintf(CTDL_EMERG,
1314 "citserver: Can't set socket to blocking: %s\n",
1318 /* New context will be created already
1319 * set up in the CON_EXECUTING state.
1321 con = CreateNewContext();
1323 /* Assign our new socket number to it. */
1324 con->client_socket = ssock;
1325 con->h_command_function =
1326 serviceptr->h_command_function;
1327 con->h_async_function =
1328 serviceptr->h_async_function;
1329 con->h_greeting_function = serviceptr->h_greeting_function;
1331 serviceptr->ServiceName;
1333 /* Determine whether it's a local socket */
1334 if (serviceptr->sockpath != NULL)
1335 con->is_local_socket = 1;
1337 /* Set the SO_REUSEADDR socket option */
1339 setsockopt(ssock, SOL_SOCKET,
1343 con->state = CON_GREETING;
1359 * Translate text facility name to syslog.h defined value.
1361 int SyslogFacility(char *name)
1370 { LOG_KERN, "kern" },
1371 { LOG_USER, "user" },
1372 { LOG_MAIL, "mail" },
1373 { LOG_DAEMON, "daemon" },
1374 { LOG_AUTH, "auth" },
1375 { LOG_SYSLOG, "syslog" },
1377 { LOG_NEWS, "news" },
1378 { LOG_UUCP, "uucp" },
1379 { LOG_LOCAL0, "local0" },
1380 { LOG_LOCAL1, "local1" },
1381 { LOG_LOCAL2, "local2" },
1382 { LOG_LOCAL3, "local3" },
1383 { LOG_LOCAL4, "local4" },
1384 { LOG_LOCAL5, "local5" },
1385 { LOG_LOCAL6, "local6" },
1386 { LOG_LOCAL7, "local7" },
1389 for(i = 0; facTbl[i].name != NULL; i++) {
1390 if(!strcasecmp(name, facTbl[i].name))
1391 return facTbl[i].facility;
1398 /********** MEM CHEQQER ***********/
1400 #ifdef DEBUG_MEMORY_LEAKS
1407 void *tracked_malloc(size_t size, char *file, int line) {
1408 struct igheap *thisheap;
1411 block = malloc(size);
1412 if (block == NULL) return(block);
1414 thisheap = malloc(sizeof(struct igheap));
1415 if (thisheap == NULL) {
1420 thisheap->block = block;
1421 strcpy(thisheap->file, file);
1422 thisheap->line = line;
1424 begin_critical_section(S_DEBUGMEMLEAKS);
1425 thisheap->next = igheap;
1427 end_critical_section(S_DEBUGMEMLEAKS);
1433 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1434 struct igheap *thisheap;
1437 block = realloc(ptr, size);
1438 if (block == NULL) return(block);
1440 thisheap = malloc(sizeof(struct igheap));
1441 if (thisheap == NULL) {
1446 thisheap->block = block;
1447 strcpy(thisheap->file, file);
1448 thisheap->line = line;
1450 begin_critical_section(S_DEBUGMEMLEAKS);
1451 thisheap->next = igheap;
1453 end_critical_section(S_DEBUGMEMLEAKS);
1460 void tracked_free(void *ptr) {
1461 struct igheap *thisheap;
1462 struct igheap *trash;
1466 if (igheap == NULL) return;
1467 begin_critical_section(S_DEBUGMEMLEAKS);
1468 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1469 if (thisheap->next != NULL) {
1470 if (thisheap->next->block == ptr) {
1471 trash = thisheap->next;
1472 thisheap->next = thisheap->next->next;
1477 if (igheap->block == ptr) {
1479 igheap = igheap->next;
1482 end_critical_section(S_DEBUGMEMLEAKS);
1485 char *tracked_strdup(const char *s, char *file, int line) {
1488 if (s == NULL) return(NULL);
1489 ptr = tracked_malloc(strlen(s) + 1, file, line);
1490 if (ptr == NULL) return(NULL);
1491 strncpy(ptr, s, strlen(s));
1495 void dump_heap(void) {
1496 struct igheap *thisheap;
1498 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1499 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1500 thisheap->file, thisheap->line);
1504 #endif /* DEBUG_MEMORY_LEAKS */