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"
77 #ifdef DEBUG_MEMORY_LEAKS
85 struct igheap *igheap = NULL;
89 citthread_key_t MyConKey; /* TSD key for MyContext() */
91 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
93 struct CitContext masterCC;
94 time_t last_purge = 0; /* Last dead session purge */
95 int num_sessions = 0; /* Current number of sessions */
97 int syslog_facility = LOG_DAEMON;
98 int enable_syslog = 0;
102 * CtdlLogPrintf() ... Write logging information
104 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
106 va_start(arg_ptr, format);
107 vCtdlLogPrintf(loglevel, format, arg_ptr);
111 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
113 char buf[SIZ], buf2[SIZ];
116 vsyslog((syslog_facility | loglevel), format, arg_ptr);
119 /* stderr output code */
120 if (enable_syslog || running_as_daemon) return;
122 /* if we run in forground and syslog is disabled, log to terminal */
123 if (loglevel <= verbosity) {
128 gettimeofday(&tv, NULL);
129 /* Promote to time_t; types differ on some OSes (like darwin) */
130 unixtime = tv.tv_sec;
131 localtime_r(&unixtime, &tim);
132 if (CC->cs_pid != 0) {
134 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
135 tim.tm_year + 1900, tim.tm_mon + 1,
136 tim.tm_mday, tim.tm_hour, tim.tm_min,
137 tim.tm_sec, (long)tv.tv_usec,
141 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
142 tim.tm_year + 1900, tim.tm_mon + 1,
143 tim.tm_mday, tim.tm_hour, tim.tm_min,
144 tim.tm_sec, (long)tv.tv_usec);
146 vsnprintf(buf2, SIZ, format, arg_ptr);
148 fprintf(stderr, "%s%s", buf, buf2);
156 * Signal handler to shut down the server.
159 volatile int exit_signal = 0;
160 volatile int shutdown_and_halt = 0;
161 volatile int restart_server = 0;
162 volatile int running_as_daemon = 0;
164 static RETSIGTYPE signal_cleanup(int signum) {
165 #ifdef THREADS_USESIGNALS
171 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
172 exit_signal = 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(SIGSEGV, signal_cleanup); commented out because
230 // signal(SIGILL, signal_cleanup); we want core dumps
231 // signal(SIGBUS, signal_cleanup);
234 * Do not shut down the server on broken pipe signals, otherwise the
235 * whole Citadel service would come down whenever a single client
238 signal(SIGPIPE, SIG_IGN);
245 * This is a generic function to set up a master socket for listening on
246 * a TCP port. The server shuts down if the bind fails.
249 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
251 struct sockaddr_in sin;
253 int actual_queue_len;
255 actual_queue_len = queue_len;
256 if (actual_queue_len < 5) actual_queue_len = 5;
258 memset(&sin, 0, sizeof(sin));
259 sin.sin_family = AF_INET;
260 sin.sin_port = htons((u_short)port_number);
261 if (ip_addr == NULL) {
262 sin.sin_addr.s_addr = INADDR_ANY;
265 sin.sin_addr.s_addr = inet_addr(ip_addr);
268 if (sin.sin_addr.s_addr == !INADDR_ANY) {
269 sin.sin_addr.s_addr = INADDR_ANY;
272 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
275 *errormessage = (char*) malloc(SIZ + 1);
276 snprintf(*errormessage, SIZ,
277 "citserver: Can't create a socket: %s",
279 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
284 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
286 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
287 *errormessage = (char*) malloc(SIZ + 1);
288 snprintf(*errormessage, SIZ,
289 "citserver: Can't bind: %s",
291 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
296 /* set to nonblock - we need this for some obscure situations */
297 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
298 *errormessage = (char*) malloc(SIZ + 1);
299 snprintf(*errormessage, SIZ,
300 "citserver: Can't set socket to non-blocking: %s",
302 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
307 if (listen(s, actual_queue_len) < 0) {
308 *errormessage = (char*) malloc(SIZ + 1);
309 snprintf(*errormessage, SIZ,
310 "citserver: Can't listen: %s",
312 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
323 * Create a Unix domain socket and listen on it
325 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
327 struct sockaddr_un addr;
330 int actual_queue_len;
332 actual_queue_len = queue_len;
333 if (actual_queue_len < 5) actual_queue_len = 5;
335 i = unlink(sockpath);
336 if (i != 0) if (errno != ENOENT) {
337 *errormessage = (char*) malloc(SIZ + 1);
338 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
339 sockpath, strerror(errno));
340 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
344 memset(&addr, 0, sizeof(addr));
345 addr.sun_family = AF_UNIX;
346 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
348 s = socket(AF_UNIX, SOCK_STREAM, 0);
350 *errormessage = (char*) malloc(SIZ + 1);
351 snprintf(*errormessage, SIZ,
352 "citserver: Can't create a socket: %s",
354 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
358 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
359 *errormessage = (char*) malloc(SIZ + 1);
360 snprintf(*errormessage, SIZ,
361 "citserver: Can't bind: %s",
363 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
367 /* set to nonblock - we need this for some obscure situations */
368 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
369 *errormessage = (char*) malloc(SIZ + 1);
370 snprintf(*errormessage, SIZ,
371 "citserver: Can't set socket to non-blocking: %s",
373 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
378 if (listen(s, actual_queue_len) < 0) {
379 *errormessage = (char*) malloc(SIZ + 1);
380 snprintf(*errormessage, SIZ,
381 "citserver: Can't listen: %s",
383 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
387 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
394 * Return a pointer to the CitContext structure bound to the thread which
395 * called this function. If there's no such binding (for example, if it's
396 * called by the housekeeper thread) then a generic 'master' CC is returned.
398 * This function is used *VERY* frequently and must be kept small.
400 struct CitContext *MyContext(void) {
402 register struct CitContext *c;
404 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
405 c == NULL) ? &masterCC : c
411 * Initialize a new context and place it in the list. The session number
412 * used to be the PID (which is why it's called cs_pid), but that was when we
413 * had one process per session. Now we just assign them sequentially, starting
414 * at 1 (don't change it to 0 because masterCC uses 0).
416 struct CitContext *CreateNewContext(void) {
417 struct CitContext *me;
418 static int next_pid = 0;
420 me = (struct CitContext *) malloc(sizeof(struct CitContext));
422 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
426 /* We can fill this as though its a private context but we must clear the internal_pgm flag
427 * to keep things correct. Watch out for the cs_pid field, that gets set further down,
428 * make sure you don't try to do it first.
430 CtdlFillPrivateContext(me, "notauth");
431 me->internal_pgm = 0;
433 /* The new context will be created already in the CON_EXECUTING state
434 * in order to prevent another thread from grabbing it while it's
437 me->state = CON_EXECUTING;
439 * Generate a unique session number and insert this context into
442 begin_critical_section(S_SESSION_TABLE);
443 me->cs_pid = ++next_pid;
445 me->next = ContextList;
447 if (me->next != NULL) {
451 end_critical_section(S_SESSION_TABLE);
456 struct CitContext *CtdlGetContextArray(int *count)
459 struct CitContext *nptr, *cptr;
461 nContexts = num_sessions;
462 nptr = malloc(sizeof(struct CitContext) * nContexts);
465 begin_critical_section(S_SESSION_TABLE);
466 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
467 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
468 end_critical_section (S_SESSION_TABLE);
477 * This function fille in a context and its user field correctly
479 void CtdlFillPrivateContext(struct CitContext *context, char *name)
481 char sysname[USERNAME_SIZE];
483 memset(context, 0, sizeof(struct CitContext));
484 context->internal_pgm = 1;
486 strcpy (sysname, "SYS_");
487 strcat (sysname, name);
488 if (getuser(&(context->user), sysname))
490 strcpy(context->user.fullname, sysname);
491 putuser(&(context->user));
496 * The following functions implement output buffering. If the kernel supplies
497 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
498 * user-space buffering.
502 # define HAVE_TCP_BUFFERING
505 # define HAVE_TCP_BUFFERING
506 # define TCP_CORK TCP_NOPUSH
508 #endif /* TCP_CORK */
509 #endif /* HAVE_DARWIN */
511 #ifdef HAVE_TCP_BUFFERING
512 static unsigned on = 1, off = 0;
513 void buffer_output(void) {
514 struct CitContext *ctx = MyContext();
515 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
519 void unbuffer_output(void) {
520 struct CitContext *ctx = MyContext();
521 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
525 void flush_output(void) {
526 struct CitContext *ctx = MyContext();
527 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
528 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
532 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
533 void buffer_output(void) {
536 void unbuffer_output(void) {
539 void flush_output(void) {
542 void buffer_output(void) {
543 if (CC->buffering == 0) {
546 CC->output_buffer = malloc(SIZ);
550 void flush_output(void) {
551 if (CC->buffering == 1) {
552 client_write(CC->output_buffer, CC->buffer_len);
557 void unbuffer_output(void) {
558 if (CC->buffering == 1) {
560 /* We don't call flush_output because we can't. */
561 client_write(CC->output_buffer, CC->buffer_len);
563 free(CC->output_buffer);
564 CC->output_buffer = NULL;
567 #endif /* HAVE_DARWIN */
568 #endif /* HAVE_TCP_BUFFERING */
573 * client_write() ... Send binary data to the client.
575 int client_write(char *buf, int nbytes)
577 int bytes_written = 0;
579 #ifndef HAVE_TCP_BUFFERING
580 int old_buffer_len = 0;
587 if (Ctx->redirect_buffer != NULL) {
588 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
589 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
590 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
591 Ctx->redirect_alloc);
593 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
594 Ctx->redirect_len += nbytes;
595 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
599 #ifndef HAVE_TCP_BUFFERING
600 /* If we're buffering for later, do that now. */
601 if (Ctx->buffering) {
602 old_buffer_len = Ctx->buffer_len;
603 Ctx->buffer_len += nbytes;
604 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
605 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
610 /* Ok, at this point we're not buffering. Go ahead and write. */
613 if (Ctx->redirect_ssl) {
614 client_write_ssl(buf, nbytes);
619 fdflags = fcntl(Ctx->client_socket, F_GETFL);
621 while (bytes_written < nbytes) {
622 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
624 FD_SET(Ctx->client_socket, &wset);
625 if (select(1, NULL, &wset, NULL, NULL) == -1) {
626 CtdlLogPrintf(CTDL_ERR,
627 "client_write(%d bytes) select failed: %s (%d)\n",
628 nbytes - bytes_written,
629 strerror(errno), errno);
636 retval = write(Ctx->client_socket, &buf[bytes_written],
637 nbytes - bytes_written);
639 CtdlLogPrintf(CTDL_ERR,
640 "client_write(%d bytes) failed: %s (%d)\n",
641 nbytes - bytes_written,
642 strerror(errno), errno);
644 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
648 bytes_written = bytes_written + retval;
655 * cprintf() ... Send formatted printable data to the client. It is
656 * implemented in terms of client_write() but remains in
657 * sysdep.c in case we port to somewhere without va_args...
659 void cprintf(const char *format, ...) {
663 va_start(arg_ptr, format);
664 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
665 buf[sizeof buf - 2] = '\n';
666 client_write(buf, strlen(buf));
672 * Read data from the client socket.
674 * 1 Requested number of bytes has been read.
675 * 0 Request timed out.
676 * -1 The socket is broken.
677 * If the socket breaks, the session will be terminated.
679 int client_read_to(char *buf, int bytes, int timeout)
688 if (CC->redirect_ssl) {
689 return (client_read_ssl(buf, bytes, timeout));
693 fd = CC->client_socket;
700 retval = select( (fd)+1,
701 &rfds, NULL, NULL, &tv);
706 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
712 if (FD_ISSET(fd, &rfds) == 0) {
716 rlen = read(fd, &buf[len], bytes-len);
718 /* The socket has been disconnected! */
728 * Read data from the client socket with default timeout.
729 * (This is implemented in terms of client_read_to() and could be
730 * justifiably moved out of sysdep.c)
732 INLINE int client_read(char *buf, int bytes)
734 return(client_read_to(buf, bytes, config.c_sleeping));
739 * client_getln() ... Get a LF-terminated line of text from the client.
740 * (This is implemented in terms of client_read() and could be
741 * justifiably moved out of sysdep.c)
743 int client_getln(char *buf, int bufsize)
747 /* Read one character at a time.
750 retval = client_read(&buf[i], 1);
751 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
755 /* If we got a long line, discard characters until the newline.
757 if (i == (bufsize-1))
758 while (buf[i] != '\n' && retval == 1)
759 retval = client_read(&buf[i], 1);
761 /* Strip the trailing LF, and the trailing CR if present.
765 && ( (buf[i - 1]==13)
766 || ( buf[i - 1]==10)) ) {
770 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
776 * Cleanup any contexts that are left lying around
778 void context_cleanup(void)
780 struct CitContext *ptr = NULL;
781 struct CitContext *rem = NULL;
784 * Clean up the contexts.
785 * There are no threads so no critical_section stuff is needed.
789 /* We need to update the ContextList because some modules may want to itterate it
790 * Question is should we NULL it before iterating here or should we just keep updating it
791 * as we remove items?
793 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
797 /* Remove the session from the active list */
801 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
810 void close_masters (void)
812 struct ServiceFunctionHook *serviceptr;
815 * close all protocol master sockets
817 for (serviceptr = ServiceHookTable; serviceptr != NULL;
818 serviceptr = serviceptr->next ) {
820 if (serviceptr->tcp_port > 0)
822 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
823 serviceptr->tcp_port);
824 serviceptr->tcp_port = 0;
827 if (serviceptr->sockpath != NULL)
828 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
829 serviceptr->sockpath);
831 close(serviceptr->msock);
832 /* If it's a Unix domain socket, remove the file. */
833 if (serviceptr->sockpath != NULL) {
834 unlink(serviceptr->sockpath);
835 serviceptr->sockpath = NULL;
842 * The system-dependent part of master_cleanup() - close the master socket.
844 void sysdep_master_cleanup(void) {
853 CtdlDestroyProtoHooks();
854 CtdlDestroyDeleteHooks();
855 CtdlDestroyXmsgHooks();
856 CtdlDestroyNetprocHooks();
857 CtdlDestroyUserHooks();
858 CtdlDestroyMessageHook();
859 CtdlDestroyCleanupHooks();
860 CtdlDestroyFixedOutputHooks();
861 CtdlDestroySessionHooks();
862 CtdlDestroyServiceHook();
863 CtdlDestroyRoomHooks();
864 CtdlDestroyDirectoryServiceFuncs();
865 #ifdef HAVE_BACKTRACE
873 * Terminate another session.
874 * (This could justifiably be moved out of sysdep.c because it
875 * no longer does anything that is system-dependent.)
877 void kill_session(int session_to_kill) {
878 struct CitContext *ptr;
880 begin_critical_section(S_SESSION_TABLE);
881 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
882 if (ptr->cs_pid == session_to_kill) {
886 end_critical_section(S_SESSION_TABLE);
890 void graceful_shutdown(int signum) {
891 kill(current_child, signum);
892 unlink(file_pid_file);
898 * Start running as a daemon.
900 void start_daemon(int unused) {
908 /* Close stdin/stdout/stderr and replace them with /dev/null.
909 * We don't just call close() because we don't want these fd's
910 * to be reused for other files.
919 signal(SIGHUP, SIG_IGN);
920 signal(SIGINT, SIG_IGN);
921 signal(SIGQUIT, SIG_IGN);
925 freopen("/dev/null", "r", stdin);
926 freopen("/dev/null", "w", stdout);
927 freopen("/dev/null", "w", stderr);
930 current_child = fork();
932 signal(SIGTERM, graceful_shutdown);
934 if (current_child < 0) {
939 else if (current_child == 0) {
940 return; /* continue starting citadel. */
944 fp = fopen(file_pid_file, "w");
946 fprintf(fp, ""F_PID_T"\n", getpid());
949 waitpid(current_child, &status, 0);
954 /* Did the main process exit with an actual exit code? */
955 if (WIFEXITED(status)) {
957 /* Exit code 0 means the watcher should exit */
958 if (WEXITSTATUS(status) == 0) {
962 /* Exit code 101-109 means the watcher should exit */
963 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
967 /* Any other exit code means we should restart. */
973 /* Any other type of termination (signals, etc.) should also restart. */
978 } while (do_restart);
980 unlink(file_pid_file);
981 exit(WEXITSTATUS(status));
987 * Generic routine to convert a login name to a full name (gecos)
988 * Returns nonzero if a conversion took place
990 int convert_login(char NameToConvert[]) {
994 pw = getpwnam(NameToConvert);
999 strcpy(NameToConvert, pw->pw_gecos);
1000 for (a=0; a<strlen(NameToConvert); ++a) {
1001 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1008 * Purge all sessions which have the 'kill_me' flag set.
1009 * This function has code to prevent it from running more than once every
1010 * few seconds, because running it after every single unbind would waste a lot
1011 * of CPU time and keep the context list locked too much. To force it to run
1012 * anyway, set "force" to nonzero.
1014 void dead_session_purge(int force) {
1015 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1016 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1019 if ( (time(NULL) - last_purge) < 5 ) {
1020 return; /* Too soon, go away */
1025 if (try_critical_section(S_SESSION_TABLE))
1033 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1034 /* Remove the session from the active list */
1036 ptr2->prev->next = ptr2->next;
1039 ContextList = ptr2->next;
1042 ptr2->next->prev = ptr2->prev;
1046 /* And put it on our to-be-destroyed list */
1051 end_critical_section(S_SESSION_TABLE);
1053 /* Now that we no longer have the session list locked, we can take
1054 * our time and destroy any sessions on the to-be-killed list, which
1055 * is allocated privately on this thread's stack.
1057 while (rem != NULL) {
1058 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1071 * masterCC is the context we use when not attached to a session. This
1072 * function initializes it.
1074 void InitializeMasterCC(void) {
1075 memset(&masterCC, 0, sizeof(struct CitContext));
1076 masterCC.internal_pgm = 1;
1077 masterCC.cs_pid = 0;
1084 * Bind a thread to a context. (It's inline merely to speed things up.)
1086 INLINE void become_session(struct CitContext *which_con) {
1087 citthread_setspecific(MyConKey, (void *)which_con );
1093 * This loop just keeps going and going and going...
1097 * This current implimentation of worker_thread creates a bottle neck in several situations
1098 * The first thing to remember is that a single thread can handle more than one connection at a time.
1099 * More threads mean less memory for the system to run in.
1100 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1101 * something to happen anywhere.
1102 * This current implimentation requires worker threads to wait in other locations, after it has
1103 * been committed to a single connection which is very wasteful.
1104 * As an extreme case consider this:
1105 * A slow client connects and this slow client sends only one character each second.
1106 * With this current implimentation a single worker thread is dispatched to handle that connection
1107 * until such times as the client timeout expires, an error occurs on the socket or the client
1108 * completes its transmission.
1109 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1110 * second interval between chars.
1112 * It is my intention to re-write this code and the associated client_getln, client_read functions
1113 * to allow any thread to read data on behalf of any connection (context).
1114 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1115 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1117 * This worker thread loop also needs to be able to handle binary data.
1120 void *worker_thread(void *arg) {
1123 struct CitContext *ptr;
1124 struct CitContext *bind_me = NULL;
1127 struct CitContext *con= NULL; /* Temporary context pointer */
1128 struct ServiceFunctionHook *serviceptr;
1129 int ssock; /* Descriptor for client socket */
1131 int force_purge = 0;
1135 while (!CtdlThreadCheckStop()) {
1137 /* make doubly sure we're not holding any stale db handles
1138 * which might cause a deadlock.
1140 cdb_check_handles();
1141 do_select: force_purge = 0;
1142 bind_me = NULL; /* Which session shall we handle? */
1144 /* Initialize the fdset. */
1148 begin_critical_section(S_SESSION_TABLE);
1149 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1150 if (ptr->state == CON_IDLE) {
1151 FD_SET(ptr->client_socket, &readfds);
1152 if (ptr->client_socket > highest)
1153 highest = ptr->client_socket;
1155 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1157 ptr->state = CON_EXECUTING;
1160 end_critical_section(S_SESSION_TABLE);
1166 /* If we got this far, it means that there are no sessions
1167 * which a previous thread marked for attention, so we go
1168 * ahead and get ready to select().
1171 /* First, add the various master sockets to the fdset. */
1172 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1173 serviceptr = serviceptr->next ) {
1174 m = serviceptr->msock;
1175 FD_SET(m, &readfds);
1181 if (!CtdlThreadCheckStop()) {
1182 tv.tv_sec = 1; /* wake up every second if no input */
1184 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1189 /* Now figure out who made this select() unblock.
1190 * First, check for an error or exit condition.
1193 if (errno == EBADF) {
1194 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1198 if (errno != EINTR) {
1199 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1200 CtdlThreadStopAll();
1202 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1203 if (CtdlThreadCheckStop()) return(NULL);
1207 else if(retval == 0) {
1208 if (CtdlThreadCheckStop()) return(NULL);
1211 /* Next, check to see if it's a new client connecting
1212 * on a master socket.
1214 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1215 serviceptr = serviceptr->next ) {
1217 if (FD_ISSET(serviceptr->msock, &readfds)) {
1218 ssock = accept(serviceptr->msock, NULL, 0);
1220 CtdlLogPrintf(CTDL_DEBUG,
1221 "New client socket %d\n",
1224 /* The master socket is non-blocking but the client
1225 * sockets need to be blocking, otherwise certain
1226 * operations barf on FreeBSD. Not a fatal error.
1228 if (fcntl(ssock, F_SETFL, 0) < 0) {
1229 CtdlLogPrintf(CTDL_EMERG,
1230 "citserver: Can't set socket to blocking: %s\n",
1234 /* New context will be created already
1235 * set up in the CON_EXECUTING state.
1237 con = CreateNewContext();
1239 /* Assign our new socket number to it. */
1240 con->client_socket = ssock;
1241 con->h_command_function =
1242 serviceptr->h_command_function;
1243 con->h_async_function =
1244 serviceptr->h_async_function;
1246 serviceptr->ServiceName;
1248 /* Determine whether it's a local socket */
1249 if (serviceptr->sockpath != NULL)
1250 con->is_local_socket = 1;
1252 /* Set the SO_REUSEADDR socket option */
1254 setsockopt(ssock, SOL_SOCKET,
1258 become_session(con);
1260 serviceptr->h_greeting_function();
1261 become_session(NULL);
1262 con->state = CON_IDLE;
1268 /* It must be a client socket. Find a context that has data
1269 * waiting on its socket *and* is in the CON_IDLE state. Any
1270 * active sockets other than our chosen one are marked as
1271 * CON_READY so the next thread that comes around can just bind
1272 * to one without having to select() again.
1274 begin_critical_section(S_SESSION_TABLE);
1275 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1276 if ( (FD_ISSET(ptr->client_socket, &readfds))
1277 && (ptr->state != CON_EXECUTING) ) {
1278 ptr->input_waiting = 1;
1280 bind_me = ptr; /* I choose you! */
1281 bind_me->state = CON_EXECUTING;
1284 ptr->state = CON_READY;
1288 end_critical_section(S_SESSION_TABLE);
1291 /* We're bound to a session */
1292 if (bind_me != NULL) {
1293 become_session(bind_me);
1295 /* If the client has sent a command, execute it. */
1296 if (CC->input_waiting) {
1297 CC->h_command_function();
1298 CC->input_waiting = 0;
1301 /* If there are asynchronous messages waiting and the
1302 * client supports it, do those now */
1303 if ((CC->is_async) && (CC->async_waiting)
1304 && (CC->h_async_function != NULL)) {
1305 CC->h_async_function();
1306 CC->async_waiting = 0;
1309 force_purge = CC->kill_me;
1310 become_session(NULL);
1311 bind_me->state = CON_IDLE;
1314 dead_session_purge(force_purge);
1317 /* If control reaches this point, the server is shutting down */
1326 * Translate text facility name to syslog.h defined value.
1328 int SyslogFacility(char *name)
1337 { LOG_KERN, "kern" },
1338 { LOG_USER, "user" },
1339 { LOG_MAIL, "mail" },
1340 { LOG_DAEMON, "daemon" },
1341 { LOG_AUTH, "auth" },
1342 { LOG_SYSLOG, "syslog" },
1344 { LOG_NEWS, "news" },
1345 { LOG_UUCP, "uucp" },
1346 { LOG_LOCAL0, "local0" },
1347 { LOG_LOCAL1, "local1" },
1348 { LOG_LOCAL2, "local2" },
1349 { LOG_LOCAL3, "local3" },
1350 { LOG_LOCAL4, "local4" },
1351 { LOG_LOCAL5, "local5" },
1352 { LOG_LOCAL6, "local6" },
1353 { LOG_LOCAL7, "local7" },
1356 for(i = 0; facTbl[i].name != NULL; i++) {
1357 if(!strcasecmp(name, facTbl[i].name))
1358 return facTbl[i].facility;
1365 /********** MEM CHEQQER ***********/
1367 #ifdef DEBUG_MEMORY_LEAKS
1374 void *tracked_malloc(size_t size, char *file, int line) {
1375 struct igheap *thisheap;
1378 block = malloc(size);
1379 if (block == NULL) return(block);
1381 thisheap = malloc(sizeof(struct igheap));
1382 if (thisheap == NULL) {
1387 thisheap->block = block;
1388 strcpy(thisheap->file, file);
1389 thisheap->line = line;
1391 begin_critical_section(S_DEBUGMEMLEAKS);
1392 thisheap->next = igheap;
1394 end_critical_section(S_DEBUGMEMLEAKS);
1400 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1401 struct igheap *thisheap;
1404 block = realloc(ptr, size);
1405 if (block == NULL) return(block);
1407 thisheap = malloc(sizeof(struct igheap));
1408 if (thisheap == NULL) {
1413 thisheap->block = block;
1414 strcpy(thisheap->file, file);
1415 thisheap->line = line;
1417 begin_critical_section(S_DEBUGMEMLEAKS);
1418 thisheap->next = igheap;
1420 end_critical_section(S_DEBUGMEMLEAKS);
1427 void tracked_free(void *ptr) {
1428 struct igheap *thisheap;
1429 struct igheap *trash;
1433 if (igheap == NULL) return;
1434 begin_critical_section(S_DEBUGMEMLEAKS);
1435 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1436 if (thisheap->next != NULL) {
1437 if (thisheap->next->block == ptr) {
1438 trash = thisheap->next;
1439 thisheap->next = thisheap->next->next;
1444 if (igheap->block == ptr) {
1446 igheap = igheap->next;
1449 end_critical_section(S_DEBUGMEMLEAKS);
1452 char *tracked_strdup(const char *s, char *file, int line) {
1455 if (s == NULL) return(NULL);
1456 ptr = tracked_malloc(strlen(s) + 1, file, line);
1457 if (ptr == NULL) return(NULL);
1458 strncpy(ptr, s, strlen(s));
1462 void dump_heap(void) {
1463 struct igheap *thisheap;
1465 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1466 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1467 thisheap->file, thisheap->line);
1471 #endif /* DEBUG_MEMORY_LEAKS */