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 #ifdef THREADS_USESIGNALS
169 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
170 exit_signal = signum;
177 * Some initialization stuff...
179 void init_sysdep(void) {
182 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
186 getrlimit(RLIMIT_NOFILE, &rl);
187 rl.rlim_cur = FD_SETSIZE;
188 rl.rlim_max = FD_SETSIZE;
189 setrlimit(RLIMIT_NOFILE, &rl);
193 /* If we've got OpenSSL, we're going to use it. */
199 * Set up a place to put thread-specific data.
200 * We only need a single pointer per thread - it points to the
201 * CitContext structure (in the ContextList linked list) of the
202 * session to which the calling thread is currently bound.
204 if (citthread_key_create(&MyConKey, NULL) != 0) {
205 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
210 * The action for unexpected signals and exceptions should be to
211 * call signal_cleanup() to gracefully shut down the server.
214 sigaddset(&set, SIGINT);
215 sigaddset(&set, SIGQUIT);
216 sigaddset(&set, SIGHUP);
217 sigaddset(&set, SIGTERM);
218 // sigaddset(&set, SIGSEGV); commented out because
219 // sigaddset(&set, SIGILL); we want core dumps
220 // sigaddset(&set, SIGBUS);
221 sigprocmask(SIG_UNBLOCK, &set, NULL);
223 signal(SIGINT, signal_cleanup);
224 signal(SIGQUIT, signal_cleanup);
225 signal(SIGHUP, signal_cleanup);
226 signal(SIGTERM, signal_cleanup);
227 // signal(SIGSEGV, signal_cleanup); commented out because
228 // signal(SIGILL, signal_cleanup); we want core dumps
229 // signal(SIGBUS, signal_cleanup);
232 * Do not shut down the server on broken pipe signals, otherwise the
233 * whole Citadel service would come down whenever a single client
236 signal(SIGPIPE, SIG_IGN);
243 * This is a generic function to set up a master socket for listening on
244 * a TCP port. The server shuts down if the bind fails.
247 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
249 struct sockaddr_in sin;
251 int actual_queue_len;
253 actual_queue_len = queue_len;
254 if (actual_queue_len < 5) actual_queue_len = 5;
256 memset(&sin, 0, sizeof(sin));
257 sin.sin_family = AF_INET;
258 sin.sin_port = htons((u_short)port_number);
259 if (ip_addr == NULL) {
260 sin.sin_addr.s_addr = INADDR_ANY;
263 sin.sin_addr.s_addr = inet_addr(ip_addr);
266 if (sin.sin_addr.s_addr == !INADDR_ANY) {
267 sin.sin_addr.s_addr = INADDR_ANY;
270 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
273 *errormessage = (char*) malloc(SIZ + 1);
274 snprintf(*errormessage, SIZ,
275 "citserver: Can't create a socket: %s",
277 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
282 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
284 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
285 *errormessage = (char*) malloc(SIZ + 1);
286 snprintf(*errormessage, SIZ,
287 "citserver: Can't bind: %s",
289 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
294 /* set to nonblock - we need this for some obscure situations */
295 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
296 *errormessage = (char*) malloc(SIZ + 1);
297 snprintf(*errormessage, SIZ,
298 "citserver: Can't set socket to non-blocking: %s",
300 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
305 if (listen(s, actual_queue_len) < 0) {
306 *errormessage = (char*) malloc(SIZ + 1);
307 snprintf(*errormessage, SIZ,
308 "citserver: Can't listen: %s",
310 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
321 * Create a Unix domain socket and listen on it
323 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
325 struct sockaddr_un addr;
328 int actual_queue_len;
330 actual_queue_len = queue_len;
331 if (actual_queue_len < 5) actual_queue_len = 5;
333 i = unlink(sockpath);
334 if (i != 0) if (errno != ENOENT) {
335 *errormessage = (char*) malloc(SIZ + 1);
336 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
337 sockpath, strerror(errno));
338 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
342 memset(&addr, 0, sizeof(addr));
343 addr.sun_family = AF_UNIX;
344 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
346 s = socket(AF_UNIX, SOCK_STREAM, 0);
348 *errormessage = (char*) malloc(SIZ + 1);
349 snprintf(*errormessage, SIZ,
350 "citserver: Can't create a socket: %s",
352 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
356 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
357 *errormessage = (char*) malloc(SIZ + 1);
358 snprintf(*errormessage, SIZ,
359 "citserver: Can't bind: %s",
361 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
365 /* set to nonblock - we need this for some obscure situations */
366 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
367 *errormessage = (char*) malloc(SIZ + 1);
368 snprintf(*errormessage, SIZ,
369 "citserver: Can't set socket to non-blocking: %s",
371 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
376 if (listen(s, actual_queue_len) < 0) {
377 *errormessage = (char*) malloc(SIZ + 1);
378 snprintf(*errormessage, SIZ,
379 "citserver: Can't listen: %s",
381 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
385 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
392 * Return a pointer to the CitContext structure bound to the thread which
393 * called this function. If there's no such binding (for example, if it's
394 * called by the housekeeper thread) then a generic 'master' CC is returned.
396 * This function is used *VERY* frequently and must be kept small.
398 struct CitContext *MyContext(void) {
400 register struct CitContext *c;
402 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
403 c == NULL) ? &masterCC : c
409 * Initialize a new context and place it in the list. The session number
410 * used to be the PID (which is why it's called cs_pid), but that was when we
411 * had one process per session. Now we just assign them sequentially, starting
412 * at 1 (don't change it to 0 because masterCC uses 0).
414 struct CitContext *CreateNewContext(void) {
415 struct CitContext *me;
416 static int next_pid = 0;
418 me = (struct CitContext *) malloc(sizeof(struct CitContext));
420 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
423 memset(me, 0, sizeof(struct CitContext));
425 /* The new context will be created already in the CON_EXECUTING state
426 * in order to prevent another thread from grabbing it while it's
429 me->state = CON_EXECUTING;
431 * Generate a unique session number and insert this context into
434 begin_critical_section(S_SESSION_TABLE);
435 me->cs_pid = ++next_pid;
437 me->next = ContextList;
439 if (me->next != NULL) {
443 end_critical_section(S_SESSION_TABLE);
448 struct CitContext *CtdlGetContextArray(int *count)
451 struct CitContext *nptr, *cptr;
453 nContexts = num_sessions;
454 nptr = malloc(sizeof(struct CitContext) * nContexts);
457 begin_critical_section(S_SESSION_TABLE);
458 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
459 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
460 end_critical_section (S_SESSION_TABLE);
467 * The following functions implement output buffering. If the kernel supplies
468 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
469 * user-space buffering.
473 # define HAVE_TCP_BUFFERING
476 # define HAVE_TCP_BUFFERING
477 # define TCP_CORK TCP_NOPUSH
479 #endif /* TCP_CORK */
480 #endif /* HAVE_DARWIN */
482 #ifdef HAVE_TCP_BUFFERING
483 static unsigned on = 1, off = 0;
484 void buffer_output(void) {
485 struct CitContext *ctx = MyContext();
486 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
490 void unbuffer_output(void) {
491 struct CitContext *ctx = MyContext();
492 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
496 void flush_output(void) {
497 struct CitContext *ctx = MyContext();
498 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
499 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
503 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
504 void buffer_output(void) {
507 void unbuffer_output(void) {
510 void flush_output(void) {
513 void buffer_output(void) {
514 if (CC->buffering == 0) {
517 CC->output_buffer = malloc(SIZ);
521 void flush_output(void) {
522 if (CC->buffering == 1) {
523 client_write(CC->output_buffer, CC->buffer_len);
528 void unbuffer_output(void) {
529 if (CC->buffering == 1) {
531 /* We don't call flush_output because we can't. */
532 client_write(CC->output_buffer, CC->buffer_len);
534 free(CC->output_buffer);
535 CC->output_buffer = NULL;
538 #endif /* HAVE_DARWIN */
539 #endif /* HAVE_TCP_BUFFERING */
544 * client_write() ... Send binary data to the client.
546 int client_write(char *buf, int nbytes)
548 int bytes_written = 0;
550 #ifndef HAVE_TCP_BUFFERING
551 int old_buffer_len = 0;
558 if (Ctx->redirect_buffer != NULL) {
559 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
560 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
561 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
562 Ctx->redirect_alloc);
564 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
565 Ctx->redirect_len += nbytes;
566 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
570 #ifndef HAVE_TCP_BUFFERING
571 /* If we're buffering for later, do that now. */
572 if (Ctx->buffering) {
573 old_buffer_len = Ctx->buffer_len;
574 Ctx->buffer_len += nbytes;
575 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
576 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
581 /* Ok, at this point we're not buffering. Go ahead and write. */
584 if (Ctx->redirect_ssl) {
585 client_write_ssl(buf, nbytes);
590 fdflags = fcntl(Ctx->client_socket, F_GETFL);
592 while (bytes_written < nbytes) {
593 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
595 FD_SET(Ctx->client_socket, &wset);
596 if (select(1, NULL, &wset, NULL, NULL) == -1) {
597 CtdlLogPrintf(CTDL_ERR,
598 "client_write(%d bytes) select failed: %s (%d)\n",
599 nbytes - bytes_written,
600 strerror(errno), errno);
607 retval = write(Ctx->client_socket, &buf[bytes_written],
608 nbytes - bytes_written);
610 CtdlLogPrintf(CTDL_ERR,
611 "client_write(%d bytes) failed: %s (%d)\n",
612 nbytes - bytes_written,
613 strerror(errno), errno);
615 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
619 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);
677 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
683 if (FD_ISSET(fd, &rfds) == 0) {
687 rlen = read(fd, &buf[len], bytes-len);
689 /* The socket has been disconnected! */
699 * Read data from the client socket with default timeout.
700 * (This is implemented in terms of client_read_to() and could be
701 * justifiably moved out of sysdep.c)
703 INLINE int client_read(char *buf, int bytes)
705 return(client_read_to(buf, bytes, config.c_sleeping));
710 * client_getln() ... Get a LF-terminated line of text from the client.
711 * (This is implemented in terms of client_read() and could be
712 * justifiably moved out of sysdep.c)
714 int client_getln(char *buf, int bufsize)
718 /* Read one character at a time.
721 retval = client_read(&buf[i], 1);
722 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
726 /* If we got a long line, discard characters until the newline.
728 if (i == (bufsize-1))
729 while (buf[i] != '\n' && retval == 1)
730 retval = client_read(&buf[i], 1);
732 /* Strip the trailing LF, and the trailing CR if present.
736 && ( (buf[i - 1]==13)
737 || ( buf[i - 1]==10)) ) {
741 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
747 * Cleanup any contexts that are left lying around
749 void context_cleanup(void)
751 struct CitContext *ptr = NULL;
752 struct CitContext *rem = NULL;
755 * Clean up the contexts.
756 * There are no threads so no critical_section stuff is needed.
760 /* We need to update the ContextList because some modules may want to itterate it
761 * Question is should we NULL it before iterating here or should we just keep updating it
762 * as we remove items?
764 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
768 /* Remove the session from the active list */
772 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
781 void close_masters (void)
783 struct ServiceFunctionHook *serviceptr;
786 * close all protocol master sockets
788 for (serviceptr = ServiceHookTable; serviceptr != NULL;
789 serviceptr = serviceptr->next ) {
791 if (serviceptr->tcp_port > 0)
793 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
794 serviceptr->tcp_port);
795 serviceptr->tcp_port = 0;
798 if (serviceptr->sockpath != NULL)
799 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
800 serviceptr->sockpath);
802 close(serviceptr->msock);
803 /* If it's a Unix domain socket, remove the file. */
804 if (serviceptr->sockpath != NULL) {
805 unlink(serviceptr->sockpath);
806 serviceptr->sockpath = NULL;
813 * The system-dependent part of master_cleanup() - close the master socket.
815 void sysdep_master_cleanup(void) {
824 CtdlDestroyProtoHooks();
825 CtdlDestroyDeleteHooks();
826 CtdlDestroyXmsgHooks();
827 CtdlDestroyNetprocHooks();
828 CtdlDestroyUserHooks();
829 CtdlDestroyMessageHook();
830 CtdlDestroyCleanupHooks();
831 CtdlDestroyFixedOutputHooks();
832 CtdlDestroySessionHooks();
833 CtdlDestroyServiceHook();
834 CtdlDestroyRoomHooks();
835 CtdlDestroyDirectoryServiceFuncs();
836 #ifdef HAVE_BACKTRACE
844 * Terminate another session.
845 * (This could justifiably be moved out of sysdep.c because it
846 * no longer does anything that is system-dependent.)
848 void kill_session(int session_to_kill) {
849 struct CitContext *ptr;
851 begin_critical_section(S_SESSION_TABLE);
852 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
853 if (ptr->cs_pid == session_to_kill) {
857 end_critical_section(S_SESSION_TABLE);
861 void graceful_shutdown(int signum) {
862 kill(current_child, signum);
863 unlink(file_pid_file);
869 * Start running as a daemon.
871 void start_daemon(int unused) {
879 /* Close stdin/stdout/stderr and replace them with /dev/null.
880 * We don't just call close() because we don't want these fd's
881 * to be reused for other files.
890 signal(SIGHUP, SIG_IGN);
891 signal(SIGINT, SIG_IGN);
892 signal(SIGQUIT, SIG_IGN);
896 freopen("/dev/null", "r", stdin);
897 freopen("/dev/null", "w", stdout);
898 freopen("/dev/null", "w", stderr);
901 current_child = fork();
903 signal(SIGTERM, graceful_shutdown);
905 if (current_child < 0) {
910 else if (current_child == 0) {
911 return; /* continue starting citadel. */
915 fp = fopen(file_pid_file, "w");
917 fprintf(fp, ""F_PID_T"\n", getpid());
920 waitpid(current_child, &status, 0);
925 /* Did the main process exit with an actual exit code? */
926 if (WIFEXITED(status)) {
928 /* Exit code 0 means the watcher should exit */
929 if (WEXITSTATUS(status) == 0) {
933 /* Exit code 101-109 means the watcher should exit */
934 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
938 /* Any other exit code means we should restart. */
944 /* Any other type of termination (signals, etc.) should also restart. */
949 } while (do_restart);
951 unlink(file_pid_file);
952 exit(WEXITSTATUS(status));
958 * Generic routine to convert a login name to a full name (gecos)
959 * Returns nonzero if a conversion took place
961 int convert_login(char NameToConvert[]) {
965 pw = getpwnam(NameToConvert);
970 strcpy(NameToConvert, pw->pw_gecos);
971 for (a=0; a<strlen(NameToConvert); ++a) {
972 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
979 * Purge all sessions which have the 'kill_me' flag set.
980 * This function has code to prevent it from running more than once every
981 * few seconds, because running it after every single unbind would waste a lot
982 * of CPU time and keep the context list locked too much. To force it to run
983 * anyway, set "force" to nonzero.
985 void dead_session_purge(int force) {
986 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
987 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
990 if ( (time(NULL) - last_purge) < 5 ) {
991 return; /* Too soon, go away */
996 if (try_critical_section(S_SESSION_TABLE))
1004 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1005 /* Remove the session from the active list */
1007 ptr2->prev->next = ptr2->next;
1010 ContextList = ptr2->next;
1013 ptr2->next->prev = ptr2->prev;
1017 /* And put it on our to-be-destroyed list */
1022 end_critical_section(S_SESSION_TABLE);
1024 /* Now that we no longer have the session list locked, we can take
1025 * our time and destroy any sessions on the to-be-killed list, which
1026 * is allocated privately on this thread's stack.
1028 while (rem != NULL) {
1029 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1042 * masterCC is the context we use when not attached to a session. This
1043 * function initializes it.
1045 void InitializeMasterCC(void) {
1046 memset(&masterCC, 0, sizeof(struct CitContext));
1047 masterCC.internal_pgm = 1;
1048 masterCC.cs_pid = 0;
1055 * Bind a thread to a context. (It's inline merely to speed things up.)
1057 INLINE void become_session(struct CitContext *which_con) {
1058 citthread_setspecific(MyConKey, (void *)which_con );
1064 * This loop just keeps going and going and going...
1068 * This current implimentation of worker_thread creates a bottle neck in several situations
1069 * The first thing to remember is that a single thread can handle more than one connection at a time.
1070 * More threads mean less memory for the system to run in.
1071 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1072 * something to happen anywhere.
1073 * This current implimentation requires worker threads to wait in other locations, after it has
1074 * been committed to a single connection which is very wasteful.
1075 * As an extreme case consider this:
1076 * A slow client connects and this slow client sends only one character each second.
1077 * With this current implimentation a single worker thread is dispatched to handle that connection
1078 * until such times as the client timeout expires, an error occurs on the socket or the client
1079 * completes its transmission.
1080 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1081 * second interval between chars.
1083 * It is my intention to re-write this code and the associated client_getln, client_read functions
1084 * to allow any thread to read data on behalf of any connection (context).
1085 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1086 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1088 * This worker thread loop also needs to be able to handle binary data.
1091 void *worker_thread(void *arg) {
1094 struct CitContext *ptr;
1095 struct CitContext *bind_me = NULL;
1098 struct CitContext *con= NULL; /* Temporary context pointer */
1099 struct ServiceFunctionHook *serviceptr;
1100 int ssock; /* Descriptor for client socket */
1102 int force_purge = 0;
1106 while (!CtdlThreadCheckStop()) {
1108 /* make doubly sure we're not holding any stale db handles
1109 * which might cause a deadlock.
1111 cdb_check_handles();
1112 do_select: force_purge = 0;
1113 bind_me = NULL; /* Which session shall we handle? */
1115 /* Initialize the fdset. */
1119 begin_critical_section(S_SESSION_TABLE);
1120 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1121 if (ptr->state == CON_IDLE) {
1122 FD_SET(ptr->client_socket, &readfds);
1123 if (ptr->client_socket > highest)
1124 highest = ptr->client_socket;
1126 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1128 ptr->state = CON_EXECUTING;
1131 end_critical_section(S_SESSION_TABLE);
1137 /* If we got this far, it means that there are no sessions
1138 * which a previous thread marked for attention, so we go
1139 * ahead and get ready to select().
1142 /* First, add the various master sockets to the fdset. */
1143 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1144 serviceptr = serviceptr->next ) {
1145 m = serviceptr->msock;
1146 FD_SET(m, &readfds);
1152 if (!CtdlThreadCheckStop()) {
1153 tv.tv_sec = 1; /* wake up every second if no input */
1155 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1160 /* Now figure out who made this select() unblock.
1161 * First, check for an error or exit condition.
1164 if (errno == EBADF) {
1165 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1169 if (errno != EINTR) {
1170 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1171 CtdlThreadStopAll();
1173 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1174 if (CtdlThreadCheckStop()) return(NULL);
1178 else if(retval == 0) {
1179 if (CtdlThreadCheckStop()) return(NULL);
1182 /* Next, check to see if it's a new client connecting
1183 * on a master socket.
1185 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1186 serviceptr = serviceptr->next ) {
1188 if (FD_ISSET(serviceptr->msock, &readfds)) {
1189 ssock = accept(serviceptr->msock, NULL, 0);
1191 CtdlLogPrintf(CTDL_DEBUG,
1192 "New client socket %d\n",
1195 /* The master socket is non-blocking but the client
1196 * sockets need to be blocking, otherwise certain
1197 * operations barf on FreeBSD. Not a fatal error.
1199 if (fcntl(ssock, F_SETFL, 0) < 0) {
1200 CtdlLogPrintf(CTDL_EMERG,
1201 "citserver: Can't set socket to blocking: %s\n",
1205 /* New context will be created already
1206 * set up in the CON_EXECUTING state.
1208 con = CreateNewContext();
1210 /* Assign our new socket number to it. */
1211 con->client_socket = ssock;
1212 con->h_command_function =
1213 serviceptr->h_command_function;
1214 con->h_async_function =
1215 serviceptr->h_async_function;
1217 serviceptr->ServiceName;
1219 /* Determine whether it's a local socket */
1220 if (serviceptr->sockpath != NULL)
1221 con->is_local_socket = 1;
1223 /* Set the SO_REUSEADDR socket option */
1225 setsockopt(ssock, SOL_SOCKET,
1229 become_session(con);
1231 serviceptr->h_greeting_function();
1232 become_session(NULL);
1233 con->state = CON_IDLE;
1239 /* It must be a client socket. Find a context that has data
1240 * waiting on its socket *and* is in the CON_IDLE state. Any
1241 * active sockets other than our chosen one are marked as
1242 * CON_READY so the next thread that comes around can just bind
1243 * to one without having to select() again.
1245 begin_critical_section(S_SESSION_TABLE);
1246 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1247 if ( (FD_ISSET(ptr->client_socket, &readfds))
1248 && (ptr->state != CON_EXECUTING) ) {
1249 ptr->input_waiting = 1;
1251 bind_me = ptr; /* I choose you! */
1252 bind_me->state = CON_EXECUTING;
1255 ptr->state = CON_READY;
1259 end_critical_section(S_SESSION_TABLE);
1262 /* We're bound to a session */
1263 if (bind_me != NULL) {
1264 become_session(bind_me);
1266 /* If the client has sent a command, execute it. */
1267 if (CC->input_waiting) {
1268 CC->h_command_function();
1269 CC->input_waiting = 0;
1272 /* If there are asynchronous messages waiting and the
1273 * client supports it, do those now */
1274 if ((CC->is_async) && (CC->async_waiting)
1275 && (CC->h_async_function != NULL)) {
1276 CC->h_async_function();
1277 CC->async_waiting = 0;
1280 force_purge = CC->kill_me;
1281 become_session(NULL);
1282 bind_me->state = CON_IDLE;
1285 dead_session_purge(force_purge);
1288 /* If control reaches this point, the server is shutting down */
1297 * Translate text facility name to syslog.h defined value.
1299 int SyslogFacility(char *name)
1308 { LOG_KERN, "kern" },
1309 { LOG_USER, "user" },
1310 { LOG_MAIL, "mail" },
1311 { LOG_DAEMON, "daemon" },
1312 { LOG_AUTH, "auth" },
1313 { LOG_SYSLOG, "syslog" },
1315 { LOG_NEWS, "news" },
1316 { LOG_UUCP, "uucp" },
1317 { LOG_LOCAL0, "local0" },
1318 { LOG_LOCAL1, "local1" },
1319 { LOG_LOCAL2, "local2" },
1320 { LOG_LOCAL3, "local3" },
1321 { LOG_LOCAL4, "local4" },
1322 { LOG_LOCAL5, "local5" },
1323 { LOG_LOCAL6, "local6" },
1324 { LOG_LOCAL7, "local7" },
1327 for(i = 0; facTbl[i].name != NULL; i++) {
1328 if(!strcasecmp(name, facTbl[i].name))
1329 return facTbl[i].facility;
1336 /********** MEM CHEQQER ***********/
1338 #ifdef DEBUG_MEMORY_LEAKS
1345 void *tracked_malloc(size_t size, char *file, int line) {
1346 struct igheap *thisheap;
1349 block = malloc(size);
1350 if (block == NULL) return(block);
1352 thisheap = malloc(sizeof(struct igheap));
1353 if (thisheap == NULL) {
1358 thisheap->block = block;
1359 strcpy(thisheap->file, file);
1360 thisheap->line = line;
1362 begin_critical_section(S_DEBUGMEMLEAKS);
1363 thisheap->next = igheap;
1365 end_critical_section(S_DEBUGMEMLEAKS);
1371 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1372 struct igheap *thisheap;
1375 block = realloc(ptr, size);
1376 if (block == NULL) return(block);
1378 thisheap = malloc(sizeof(struct igheap));
1379 if (thisheap == NULL) {
1384 thisheap->block = block;
1385 strcpy(thisheap->file, file);
1386 thisheap->line = line;
1388 begin_critical_section(S_DEBUGMEMLEAKS);
1389 thisheap->next = igheap;
1391 end_critical_section(S_DEBUGMEMLEAKS);
1398 void tracked_free(void *ptr) {
1399 struct igheap *thisheap;
1400 struct igheap *trash;
1404 if (igheap == NULL) return;
1405 begin_critical_section(S_DEBUGMEMLEAKS);
1406 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1407 if (thisheap->next != NULL) {
1408 if (thisheap->next->block == ptr) {
1409 trash = thisheap->next;
1410 thisheap->next = thisheap->next->next;
1415 if (igheap->block == ptr) {
1417 igheap = igheap->next;
1420 end_critical_section(S_DEBUGMEMLEAKS);
1423 char *tracked_strdup(const char *s, char *file, int line) {
1426 if (s == NULL) return(NULL);
1427 ptr = tracked_malloc(strlen(s) + 1, file, line);
1428 if (ptr == NULL) return(NULL);
1429 strncpy(ptr, s, strlen(s));
1433 void dump_heap(void) {
1434 struct igheap *thisheap;
1436 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1437 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1438 thisheap->file, thisheap->line);
1442 #endif /* DEBUG_MEMORY_LEAKS */