4 * Citadel "system dependent" stuff.
5 * See copyright.txt 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 */
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
72 #include "ctdl_module.h"
75 #ifdef DEBUG_MEMORY_LEAKS
83 struct igheap *igheap = NULL;
87 citthread_key_t MyConKey; /* TSD key for MyContext() */
89 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
91 struct CitContext masterCC;
92 time_t last_purge = 0; /* Last dead session purge */
93 int num_sessions = 0; /* Current number of sessions */
95 int syslog_facility = LOG_DAEMON;
96 int enable_syslog = 0;
100 * CtdlLogPrintf() ... Write logging information
102 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
104 va_start(arg_ptr, format);
105 vCtdlLogPrintf(loglevel, format, arg_ptr);
109 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
111 char buf[SIZ], buf2[SIZ];
114 vsyslog((syslog_facility | loglevel), format, arg_ptr);
117 /* stderr output code */
118 if (enable_syslog || running_as_daemon) return;
120 /* if we run in forground and syslog is disabled, log to terminal */
121 if (loglevel <= verbosity) {
126 gettimeofday(&tv, NULL);
127 /* Promote to time_t; types differ on some OSes (like darwin) */
128 unixtime = tv.tv_sec;
129 localtime_r(&unixtime, &tim);
130 if (CC->cs_pid != 0) {
132 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
133 tim.tm_year + 1900, tim.tm_mon + 1,
134 tim.tm_mday, tim.tm_hour, tim.tm_min,
135 tim.tm_sec, (long)tv.tv_usec,
139 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
140 tim.tm_year + 1900, tim.tm_mon + 1,
141 tim.tm_mday, tim.tm_hour, tim.tm_min,
142 tim.tm_sec, (long)tv.tv_usec);
144 vsnprintf(buf2, SIZ, format, arg_ptr);
146 fprintf(stderr, "%s%s", buf, buf2);
154 * Signal handler to shut down the server.
157 volatile int exit_signal = 0;
158 volatile int shutdown_and_halt = 0;
159 volatile int restart_server = 0;
160 volatile int running_as_daemon = 0;
162 static RETSIGTYPE signal_cleanup(int signum) {
163 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
164 #ifdef THREADS_USESIGNALS
167 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, signum);
172 exit_signal = signum;
178 * Some initialization stuff...
180 void init_sysdep(void) {
183 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
187 getrlimit(RLIMIT_NOFILE, &rl);
188 rl.rlim_cur = FD_SETSIZE;
189 rl.rlim_max = FD_SETSIZE;
190 setrlimit(RLIMIT_NOFILE, &rl);
194 /* If we've got OpenSSL, we're going to use it. */
200 * Set up a place to put thread-specific data.
201 * We only need a single pointer per thread - it points to the
202 * CitContext structure (in the ContextList linked list) of the
203 * session to which the calling thread is currently bound.
205 if (citthread_key_create(&MyConKey, NULL) != 0) {
206 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
211 * The action for unexpected signals and exceptions should be to
212 * call signal_cleanup() to gracefully shut down the server.
215 sigaddset(&set, SIGINT);
216 sigaddset(&set, SIGQUIT);
217 sigaddset(&set, SIGHUP);
218 sigaddset(&set, SIGTERM);
219 // sigaddset(&set, SIGSEGV); commented out because
220 // sigaddset(&set, SIGILL); we want core dumps
221 // sigaddset(&set, SIGBUS);
222 sigprocmask(SIG_UNBLOCK, &set, NULL);
224 signal(SIGINT, signal_cleanup);
225 signal(SIGQUIT, signal_cleanup);
226 signal(SIGHUP, signal_cleanup);
227 signal(SIGTERM, signal_cleanup);
228 // signal(SIGSEGV, signal_cleanup); commented out because
229 // signal(SIGILL, signal_cleanup); we want core dumps
230 // signal(SIGBUS, signal_cleanup);
233 * Do not shut down the server on broken pipe signals, otherwise the
234 * whole Citadel service would come down whenever a single client
237 signal(SIGPIPE, SIG_IGN);
244 * This is a generic function to set up a master socket for listening on
245 * a TCP port. The server shuts down if the bind fails.
248 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
250 struct sockaddr_in sin;
252 int actual_queue_len;
254 actual_queue_len = queue_len;
255 if (actual_queue_len < 5) actual_queue_len = 5;
257 memset(&sin, 0, sizeof(sin));
258 sin.sin_family = AF_INET;
259 sin.sin_port = htons((u_short)port_number);
260 if (ip_addr == NULL) {
261 sin.sin_addr.s_addr = INADDR_ANY;
264 sin.sin_addr.s_addr = inet_addr(ip_addr);
267 if (sin.sin_addr.s_addr == !INADDR_ANY) {
268 sin.sin_addr.s_addr = INADDR_ANY;
271 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
274 *errormessage = (char*) malloc(SIZ + 1);
275 snprintf(*errormessage, SIZ,
276 "citserver: Can't create a socket: %s",
278 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
283 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
285 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
286 *errormessage = (char*) malloc(SIZ + 1);
287 snprintf(*errormessage, SIZ,
288 "citserver: Can't bind: %s",
290 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
295 /* set to nonblock - we need this for some obscure situations */
296 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
297 *errormessage = (char*) malloc(SIZ + 1);
298 snprintf(*errormessage, SIZ,
299 "citserver: Can't set socket to non-blocking: %s",
301 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
306 if (listen(s, actual_queue_len) < 0) {
307 *errormessage = (char*) malloc(SIZ + 1);
308 snprintf(*errormessage, SIZ,
309 "citserver: Can't listen: %s",
311 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
322 * Create a Unix domain socket and listen on it
324 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
326 struct sockaddr_un addr;
329 int actual_queue_len;
331 actual_queue_len = queue_len;
332 if (actual_queue_len < 5) actual_queue_len = 5;
334 i = unlink(sockpath);
335 if (i != 0) if (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 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
393 * Return a pointer to the CitContext structure bound to the thread which
394 * called this function. If there's no such binding (for example, if it's
395 * called by the housekeeper thread) then a generic 'master' CC is returned.
397 * This function is used *VERY* frequently and must be kept small.
399 struct CitContext *MyContext(void) {
401 register struct CitContext *c;
403 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
404 c == NULL) ? &masterCC : c
410 * Initialize a new context and place it in the list. The session number
411 * used to be the PID (which is why it's called cs_pid), but that was when we
412 * had one process per session. Now we just assign them sequentially, starting
413 * at 1 (don't change it to 0 because masterCC uses 0).
415 struct CitContext *CreateNewContext(void) {
416 struct CitContext *me;
417 static int next_pid = 0;
419 me = (struct CitContext *) malloc(sizeof(struct CitContext));
421 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
424 memset(me, 0, sizeof(struct CitContext));
426 /* The new context will be created already in the CON_EXECUTING state
427 * in order to prevent another thread from grabbing it while it's
430 me->state = CON_EXECUTING;
432 * Generate a unique session number and insert this context into
435 begin_critical_section(S_SESSION_TABLE);
436 me->cs_pid = ++next_pid;
438 me->next = ContextList;
440 if (me->next != NULL) {
444 end_critical_section(S_SESSION_TABLE);
449 struct CitContext *CtdlGetContextArray(int *count)
452 struct CitContext *nptr, *cptr;
454 nContexts = num_sessions;
455 nptr = malloc(sizeof(struct CitContext) * nContexts);
458 begin_critical_section(S_SESSION_TABLE);
459 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
460 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
461 end_critical_section (S_SESSION_TABLE);
468 * The following functions implement output buffering. If the kernel supplies
469 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
470 * user-space buffering.
474 # define HAVE_TCP_BUFFERING
477 # define HAVE_TCP_BUFFERING
478 # define TCP_CORK TCP_NOPUSH
480 #endif /* TCP_CORK */
481 #endif /* HAVE_DARWIN */
483 #ifdef HAVE_TCP_BUFFERING
484 static unsigned on = 1, off = 0;
485 void buffer_output(void) {
486 struct CitContext *ctx = MyContext();
487 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
491 void unbuffer_output(void) {
492 struct CitContext *ctx = MyContext();
493 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
497 void flush_output(void) {
498 struct CitContext *ctx = MyContext();
499 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
500 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
504 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
505 void buffer_output(void) {
508 void unbuffer_output(void) {
511 void flush_output(void) {
514 void buffer_output(void) {
515 if (CC->buffering == 0) {
518 CC->output_buffer = malloc(SIZ);
522 void flush_output(void) {
523 if (CC->buffering == 1) {
524 client_write(CC->output_buffer, CC->buffer_len);
529 void unbuffer_output(void) {
530 if (CC->buffering == 1) {
532 /* We don't call flush_output because we can't. */
533 client_write(CC->output_buffer, CC->buffer_len);
535 free(CC->output_buffer);
536 CC->output_buffer = NULL;
539 #endif /* HAVE_DARWIN */
540 #endif /* HAVE_TCP_BUFFERING */
545 * client_write() ... Send binary data to the client.
547 void client_write(char *buf, int nbytes)
549 int bytes_written = 0;
551 #ifndef HAVE_TCP_BUFFERING
552 int old_buffer_len = 0;
559 if (Ctx->redirect_buffer != NULL) {
560 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
561 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
562 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
563 Ctx->redirect_alloc);
565 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
566 Ctx->redirect_len += nbytes;
567 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
571 #ifndef HAVE_TCP_BUFFERING
572 /* If we're buffering for later, do that now. */
573 if (Ctx->buffering) {
574 old_buffer_len = Ctx->buffer_len;
575 Ctx->buffer_len += nbytes;
576 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
577 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
582 /* Ok, at this point we're not buffering. Go ahead and write. */
585 if (Ctx->redirect_ssl) {
586 client_write_ssl(buf, nbytes);
591 fdflags = fcntl(Ctx->client_socket, F_GETFL);
593 while (bytes_written < nbytes) {
594 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
596 FD_SET(Ctx->client_socket, &wset);
597 if (select(1, NULL, &wset, NULL, NULL) == -1) {
598 CtdlLogPrintf(CTDL_ERR,
599 "client_write(%d bytes) select failed: %s (%d)\n",
600 nbytes - bytes_written,
601 strerror(errno), errno);
608 retval = write(Ctx->client_socket, &buf[bytes_written],
609 nbytes - bytes_written);
611 CtdlLogPrintf(CTDL_ERR,
612 "client_write(%d bytes) failed: %s (%d)\n",
613 nbytes - bytes_written,
614 strerror(errno), errno);
616 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
620 bytes_written = bytes_written + retval;
626 * cprintf() ... Send formatted printable data to the client. It is
627 * implemented in terms of client_write() but remains in
628 * sysdep.c in case we port to somewhere without va_args...
630 void cprintf(const char *format, ...) {
634 va_start(arg_ptr, format);
635 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
636 buf[sizeof buf - 2] = '\n';
637 client_write(buf, strlen(buf));
643 * Read data from the client socket.
645 * 1 Requested number of bytes has been read.
646 * 0 Request timed out.
647 * -1 The socket is broken.
648 * If the socket breaks, the session will be terminated.
650 int client_read_to(char *buf, int bytes, int timeout)
659 if (CC->redirect_ssl) {
660 return (client_read_ssl(buf, bytes, timeout));
664 fd = CC->client_socket;
671 retval = select( (fd)+1,
672 &rfds, NULL, NULL, &tv);
674 if (FD_ISSET(fd, &rfds) == 0) {
678 rlen = read(fd, &buf[len], bytes-len);
680 /* The socket has been disconnected! */
690 * Read data from the client socket with default timeout.
691 * (This is implemented in terms of client_read_to() and could be
692 * justifiably moved out of sysdep.c)
694 INLINE int client_read(char *buf, int bytes)
696 return(client_read_to(buf, bytes, config.c_sleeping));
701 * client_getln() ... Get a LF-terminated line of text from the client.
702 * (This is implemented in terms of client_read() and could be
703 * justifiably moved out of sysdep.c)
705 int client_getln(char *buf, int bufsize)
709 /* Read one character at a time.
712 retval = client_read(&buf[i], 1);
713 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
717 /* If we got a long line, discard characters until the newline.
719 if (i == (bufsize-1))
720 while (buf[i] != '\n' && retval == 1)
721 retval = client_read(&buf[i], 1);
723 /* Strip the trailing LF, and the trailing CR if present.
727 && ( (buf[i - 1]==13)
728 || ( buf[i - 1]==10)) ) {
732 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
738 * Cleanup any contexts that are left lying around
740 void context_cleanup(void)
742 struct CitContext *ptr = NULL;
743 struct CitContext *rem = NULL;
746 * Clean up the contexts.
747 * There are no threads so no critical_section stuff is needed.
751 /* We need to update the ContextList because some modules may want to itterate it
752 * Question is should we NULL it before iterating here or should we just keep updating it
753 * as we remove items?
755 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
759 /* Remove the session from the active list */
763 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
772 void close_masters (void)
774 struct ServiceFunctionHook *serviceptr;
777 * close all protocol master sockets
779 for (serviceptr = ServiceHookTable; serviceptr != NULL;
780 serviceptr = serviceptr->next ) {
782 if (serviceptr->tcp_port > 0)
784 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
785 serviceptr->tcp_port);
786 serviceptr->tcp_port = 0;
789 if (serviceptr->sockpath != NULL)
790 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
791 serviceptr->sockpath);
793 close(serviceptr->msock);
794 /* If it's a Unix domain socket, remove the file. */
795 if (serviceptr->sockpath != NULL) {
796 unlink(serviceptr->sockpath);
797 serviceptr->sockpath = NULL;
804 * The system-dependent part of master_cleanup() - close the master socket.
806 void sysdep_master_cleanup(void) {
815 CtdlDestroyProtoHooks();
816 CtdlDestroyDeleteHooks();
817 CtdlDestroyXmsgHooks();
818 CtdlDestroyNetprocHooks();
819 CtdlDestroyUserHooks();
820 CtdlDestroyMessageHook();
821 CtdlDestroyCleanupHooks();
822 CtdlDestroyFixedOutputHooks();
823 CtdlDestroySessionHooks();
824 CtdlDestroyServiceHook();
825 CtdlDestroyRoomHooks();
826 CtdlDestroyDirectoryServiceFuncs();
827 #ifdef HAVE_BACKTRACE
835 * Terminate another session.
836 * (This could justifiably be moved out of sysdep.c because it
837 * no longer does anything that is system-dependent.)
839 void kill_session(int session_to_kill) {
840 struct CitContext *ptr;
842 begin_critical_section(S_SESSION_TABLE);
843 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
844 if (ptr->cs_pid == session_to_kill) {
848 end_critical_section(S_SESSION_TABLE);
852 void graceful_shutdown(int signum) {
853 kill(current_child, signum);
854 unlink(file_pid_file);
860 * Start running as a daemon.
862 void start_daemon(int unused) {
870 /* Close stdin/stdout/stderr and replace them with /dev/null.
871 * We don't just call close() because we don't want these fd's
872 * to be reused for other files.
881 signal(SIGHUP, SIG_IGN);
882 signal(SIGINT, SIG_IGN);
883 signal(SIGQUIT, SIG_IGN);
887 freopen("/dev/null", "r", stdin);
888 freopen("/dev/null", "w", stdout);
889 freopen("/dev/null", "w", stderr);
892 current_child = fork();
894 signal(SIGTERM, graceful_shutdown);
896 if (current_child < 0) {
901 else if (current_child == 0) {
902 return; /* continue starting citadel. */
906 fp = fopen(file_pid_file, "w");
908 fprintf(fp, ""F_PID_T"\n", getpid());
911 waitpid(current_child, &status, 0);
916 /* Did the main process exit with an actual exit code? */
917 if (WIFEXITED(status)) {
919 /* Exit code 0 means the watcher should exit */
920 if (WEXITSTATUS(status) == 0) {
924 /* Exit code 101-109 means the watcher should exit */
925 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
929 /* Any other exit code means we should restart. */
935 /* Any other type of termination (signals, etc.) should also restart. */
940 } while (do_restart);
942 unlink(file_pid_file);
943 exit(WEXITSTATUS(status));
949 * Generic routine to convert a login name to a full name (gecos)
950 * Returns nonzero if a conversion took place
952 int convert_login(char NameToConvert[]) {
956 pw = getpwnam(NameToConvert);
961 strcpy(NameToConvert, pw->pw_gecos);
962 for (a=0; a<strlen(NameToConvert); ++a) {
963 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
970 * Purge all sessions which have the 'kill_me' flag set.
971 * This function has code to prevent it from running more than once every
972 * few seconds, because running it after every single unbind would waste a lot
973 * of CPU time and keep the context list locked too much. To force it to run
974 * anyway, set "force" to nonzero.
976 void dead_session_purge(int force) {
977 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
978 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
981 if ( (time(NULL) - last_purge) < 5 ) {
982 return; /* Too soon, go away */
987 if (try_critical_section(S_SESSION_TABLE))
995 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
996 /* Remove the session from the active list */
998 ptr2->prev->next = ptr2->next;
1001 ContextList = ptr2->next;
1004 ptr2->next->prev = ptr2->prev;
1008 /* And put it on our to-be-destroyed list */
1013 end_critical_section(S_SESSION_TABLE);
1015 /* Now that we no longer have the session list locked, we can take
1016 * our time and destroy any sessions on the to-be-killed list, which
1017 * is allocated privately on this thread's stack.
1019 while (rem != NULL) {
1020 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1033 * masterCC is the context we use when not attached to a session. This
1034 * function initializes it.
1036 void InitializeMasterCC(void) {
1037 memset(&masterCC, 0, sizeof(struct CitContext));
1038 masterCC.internal_pgm = 1;
1039 masterCC.cs_pid = 0;
1048 * Bind a thread to a context. (It's inline merely to speed things up.)
1050 INLINE void become_session(struct CitContext *which_con) {
1051 citthread_setspecific(MyConKey, (void *)which_con );
1057 * This loop just keeps going and going and going...
1061 * This current implimentation of worker_thread creates a bottle neck in several situations
1062 * The first thing to remember is that a single thread can handle more than one connection at a time.
1063 * More threads mean less memory for the system to run in.
1064 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1065 * something to happen anywhere.
1066 * This current implimentation requires worker threads to wait in other locations, after it has
1067 * been committed to a single connection which is very wasteful.
1068 * As an extreme case consider this:
1069 * A slow client connects and this slow client sends only one character each second.
1070 * With this current implimentation a single worker thread is dispatched to handle that connection
1071 * until such times as the client timeout expires, an error occurs on the socket or the client
1072 * completes its transmission.
1073 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1074 * second interval between chars.
1076 * It is my intention to re-write this code and the associated client_getln, client_read functions
1077 * to allow any thread to read data on behalf of any connection (context).
1078 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1079 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1081 * This worker thread loop also needs to be able to handle binary data.
1084 void *worker_thread(void *arg) {
1087 struct CitContext *ptr;
1088 struct CitContext *bind_me = NULL;
1091 struct CitContext *con= NULL; /* Temporary context pointer */
1092 struct ServiceFunctionHook *serviceptr;
1093 int ssock; /* Descriptor for client socket */
1095 int force_purge = 0;
1099 while (!CtdlThreadCheckStop()) {
1101 /* make doubly sure we're not holding any stale db handles
1102 * which might cause a deadlock.
1104 cdb_check_handles();
1105 do_select: force_purge = 0;
1106 bind_me = NULL; /* Which session shall we handle? */
1108 /* Initialize the fdset. */
1112 begin_critical_section(S_SESSION_TABLE);
1113 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1114 if (ptr->state == CON_IDLE) {
1115 FD_SET(ptr->client_socket, &readfds);
1116 if (ptr->client_socket > highest)
1117 highest = ptr->client_socket;
1119 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1121 ptr->state = CON_EXECUTING;
1124 end_critical_section(S_SESSION_TABLE);
1130 /* If we got this far, it means that there are no sessions
1131 * which a previous thread marked for attention, so we go
1132 * ahead and get ready to select().
1135 /* First, add the various master sockets to the fdset. */
1136 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1137 serviceptr = serviceptr->next ) {
1138 m = serviceptr->msock;
1139 FD_SET(m, &readfds);
1145 if (!CtdlThreadCheckStop()) {
1146 tv.tv_sec = 1; /* wake up every second if no input */
1148 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1153 /* Now figure out who made this select() unblock.
1154 * First, check for an error or exit condition.
1157 if (errno == EBADF) {
1158 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1162 if (errno != EINTR) {
1163 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1164 CtdlThreadStopAll();
1165 } else if (!CtdlThreadCheckStop()) {
1166 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select.\n");
1170 else if(retval == 0) {
1171 if (CtdlThreadCheckStop()) return(NULL);
1174 /* Next, check to see if it's a new client connecting
1175 * on a master socket.
1177 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1178 serviceptr = serviceptr->next ) {
1180 if (FD_ISSET(serviceptr->msock, &readfds)) {
1181 ssock = accept(serviceptr->msock, NULL, 0);
1183 CtdlLogPrintf(CTDL_DEBUG,
1184 "New client socket %d\n",
1187 /* The master socket is non-blocking but the client
1188 * sockets need to be blocking, otherwise certain
1189 * operations barf on FreeBSD. Not a fatal error.
1191 if (fcntl(ssock, F_SETFL, 0) < 0) {
1192 CtdlLogPrintf(CTDL_EMERG,
1193 "citserver: Can't set socket to blocking: %s\n",
1197 /* New context will be created already
1198 * set up in the CON_EXECUTING state.
1200 con = CreateNewContext();
1202 /* Assign our new socket number to it. */
1203 con->client_socket = ssock;
1204 con->h_command_function =
1205 serviceptr->h_command_function;
1206 con->h_async_function =
1207 serviceptr->h_async_function;
1209 serviceptr->ServiceName;
1211 /* Determine whether it's a local socket */
1212 if (serviceptr->sockpath != NULL)
1213 con->is_local_socket = 1;
1215 /* Set the SO_REUSEADDR socket option */
1217 setsockopt(ssock, SOL_SOCKET,
1221 become_session(con);
1223 serviceptr->h_greeting_function();
1224 become_session(NULL);
1225 con->state = CON_IDLE;
1231 /* It must be a client socket. Find a context that has data
1232 * waiting on its socket *and* is in the CON_IDLE state. Any
1233 * active sockets other than our chosen one are marked as
1234 * CON_READY so the next thread that comes around can just bind
1235 * to one without having to select() again.
1237 begin_critical_section(S_SESSION_TABLE);
1238 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1239 if ( (FD_ISSET(ptr->client_socket, &readfds))
1240 && (ptr->state != CON_EXECUTING) ) {
1241 ptr->input_waiting = 1;
1243 bind_me = ptr; /* I choose you! */
1244 bind_me->state = CON_EXECUTING;
1247 ptr->state = CON_READY;
1251 end_critical_section(S_SESSION_TABLE);
1254 /* We're bound to a session */
1255 if (bind_me != NULL) {
1256 become_session(bind_me);
1258 /* If the client has sent a command, execute it. */
1259 if (CC->input_waiting) {
1260 CC->h_command_function();
1261 CC->input_waiting = 0;
1264 /* If there are asynchronous messages waiting and the
1265 * client supports it, do those now */
1266 if ((CC->is_async) && (CC->async_waiting)
1267 && (CC->h_async_function != NULL)) {
1268 CC->h_async_function();
1269 CC->async_waiting = 0;
1272 force_purge = CC->kill_me;
1273 become_session(NULL);
1274 bind_me->state = CON_IDLE;
1277 dead_session_purge(force_purge);
1280 /* If control reaches this point, the server is shutting down */
1289 * Translate text facility name to syslog.h defined value.
1291 int SyslogFacility(char *name)
1300 { LOG_KERN, "kern" },
1301 { LOG_USER, "user" },
1302 { LOG_MAIL, "mail" },
1303 { LOG_DAEMON, "daemon" },
1304 { LOG_AUTH, "auth" },
1305 { LOG_SYSLOG, "syslog" },
1307 { LOG_NEWS, "news" },
1308 { LOG_UUCP, "uucp" },
1309 { LOG_LOCAL0, "local0" },
1310 { LOG_LOCAL1, "local1" },
1311 { LOG_LOCAL2, "local2" },
1312 { LOG_LOCAL3, "local3" },
1313 { LOG_LOCAL4, "local4" },
1314 { LOG_LOCAL5, "local5" },
1315 { LOG_LOCAL6, "local6" },
1316 { LOG_LOCAL7, "local7" },
1319 for(i = 0; facTbl[i].name != NULL; i++) {
1320 if(!strcasecmp(name, facTbl[i].name))
1321 return facTbl[i].facility;
1328 /********** MEM CHEQQER ***********/
1330 #ifdef DEBUG_MEMORY_LEAKS
1337 void *tracked_malloc(size_t size, char *file, int line) {
1338 struct igheap *thisheap;
1341 block = malloc(size);
1342 if (block == NULL) return(block);
1344 thisheap = malloc(sizeof(struct igheap));
1345 if (thisheap == NULL) {
1350 thisheap->block = block;
1351 strcpy(thisheap->file, file);
1352 thisheap->line = line;
1354 begin_critical_section(S_DEBUGMEMLEAKS);
1355 thisheap->next = igheap;
1357 end_critical_section(S_DEBUGMEMLEAKS);
1363 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1364 struct igheap *thisheap;
1367 block = realloc(ptr, size);
1368 if (block == NULL) return(block);
1370 thisheap = malloc(sizeof(struct igheap));
1371 if (thisheap == NULL) {
1376 thisheap->block = block;
1377 strcpy(thisheap->file, file);
1378 thisheap->line = line;
1380 begin_critical_section(S_DEBUGMEMLEAKS);
1381 thisheap->next = igheap;
1383 end_critical_section(S_DEBUGMEMLEAKS);
1390 void tracked_free(void *ptr) {
1391 struct igheap *thisheap;
1392 struct igheap *trash;
1396 if (igheap == NULL) return;
1397 begin_critical_section(S_DEBUGMEMLEAKS);
1398 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1399 if (thisheap->next != NULL) {
1400 if (thisheap->next->block == ptr) {
1401 trash = thisheap->next;
1402 thisheap->next = thisheap->next->next;
1407 if (igheap->block == ptr) {
1409 igheap = igheap->next;
1412 end_critical_section(S_DEBUGMEMLEAKS);
1415 char *tracked_strdup(const char *s, char *file, int line) {
1418 if (s == NULL) return(NULL);
1419 ptr = tracked_malloc(strlen(s) + 1, file, line);
1420 if (ptr == NULL) return(NULL);
1421 strncpy(ptr, s, strlen(s));
1425 void dump_heap(void) {
1426 struct igheap *thisheap;
1428 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1429 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1430 thisheap->file, thisheap->line);
1434 #endif /* DEBUG_MEMORY_LEAKS */