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"
78 #ifdef DEBUG_MEMORY_LEAKS
86 struct igheap *igheap = NULL;
90 citthread_key_t MyConKey; /* TSD key for MyContext() */
92 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
94 struct CitContext masterCC;
95 time_t last_purge = 0; /* Last dead session purge */
96 int num_sessions = 0; /* Current number of sessions */
98 int syslog_facility = LOG_DAEMON;
99 int enable_syslog = 0;
103 * CtdlLogPrintf() ... Write logging information
105 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
107 va_start(arg_ptr, format);
108 vCtdlLogPrintf(loglevel, format, arg_ptr);
112 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
114 char buf[SIZ], buf2[SIZ];
117 vsyslog((syslog_facility | loglevel), format, arg_ptr);
120 /* stderr output code */
121 if (enable_syslog || running_as_daemon) return;
123 /* if we run in forground and syslog is disabled, log to terminal */
124 if (loglevel <= verbosity) {
129 gettimeofday(&tv, NULL);
130 /* Promote to time_t; types differ on some OSes (like darwin) */
131 unixtime = tv.tv_sec;
132 localtime_r(&unixtime, &tim);
133 if (CC->cs_pid != 0) {
135 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
136 tim.tm_year + 1900, tim.tm_mon + 1,
137 tim.tm_mday, tim.tm_hour, tim.tm_min,
138 tim.tm_sec, (long)tv.tv_usec,
142 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
143 tim.tm_year + 1900, tim.tm_mon + 1,
144 tim.tm_mday, tim.tm_hour, tim.tm_min,
145 tim.tm_sec, (long)tv.tv_usec);
147 vsnprintf(buf2, SIZ, format, arg_ptr);
149 fprintf(stderr, "%s%s", buf, buf2);
157 * Signal handler to shut down the server.
160 volatile int exit_signal = 0;
161 volatile int shutdown_and_halt = 0;
162 volatile int restart_server = 0;
163 volatile int running_as_daemon = 0;
165 static RETSIGTYPE signal_cleanup(int signum) {
166 #ifdef THREADS_USESIGNALS
172 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
173 exit_signal = signum;
180 * Some initialization stuff...
182 void init_sysdep(void) {
185 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
189 getrlimit(RLIMIT_NOFILE, &rl);
190 rl.rlim_cur = FD_SETSIZE;
191 rl.rlim_max = FD_SETSIZE;
192 setrlimit(RLIMIT_NOFILE, &rl);
196 /* If we've got OpenSSL, we're going to use it. */
202 * Set up a place to put thread-specific data.
203 * We only need a single pointer per thread - it points to the
204 * CitContext structure (in the ContextList linked list) of the
205 * session to which the calling thread is currently bound.
207 if (citthread_key_create(&MyConKey, NULL) != 0) {
208 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
213 * The action for unexpected signals and exceptions should be to
214 * call signal_cleanup() to gracefully shut down the server.
217 sigaddset(&set, SIGINT);
218 sigaddset(&set, SIGQUIT);
219 sigaddset(&set, SIGHUP);
220 sigaddset(&set, SIGTERM);
221 // sigaddset(&set, SIGSEGV); commented out because
222 // sigaddset(&set, SIGILL); we want core dumps
223 // sigaddset(&set, SIGBUS);
224 sigprocmask(SIG_UNBLOCK, &set, NULL);
226 signal(SIGINT, signal_cleanup);
227 signal(SIGQUIT, signal_cleanup);
228 signal(SIGHUP, signal_cleanup);
229 signal(SIGTERM, signal_cleanup);
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;
333 actual_queue_len = queue_len;
334 if (actual_queue_len < 5) actual_queue_len = 5;
336 i = unlink(sockpath);
337 if (i != 0) if (errno != ENOENT) {
338 *errormessage = (char*) malloc(SIZ + 1);
339 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
340 sockpath, strerror(errno));
341 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
345 memset(&addr, 0, sizeof(addr));
346 addr.sun_family = AF_UNIX;
347 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
349 s = socket(AF_UNIX, SOCK_STREAM, 0);
351 *errormessage = (char*) malloc(SIZ + 1);
352 snprintf(*errormessage, SIZ,
353 "citserver: Can't create a socket: %s",
355 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
359 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
360 *errormessage = (char*) malloc(SIZ + 1);
361 snprintf(*errormessage, SIZ,
362 "citserver: Can't bind: %s",
364 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
368 /* set to nonblock - we need this for some obscure situations */
369 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
370 *errormessage = (char*) malloc(SIZ + 1);
371 snprintf(*errormessage, SIZ,
372 "citserver: Can't set socket to non-blocking: %s",
374 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
379 if (listen(s, actual_queue_len) < 0) {
380 *errormessage = (char*) malloc(SIZ + 1);
381 snprintf(*errormessage, SIZ,
382 "citserver: Can't listen: %s",
384 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
388 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
395 * Return a pointer to the CitContext structure bound to the thread which
396 * called this function. If there's no such binding (for example, if it's
397 * called by the housekeeper thread) then a generic 'master' CC is returned.
399 * This function is used *VERY* frequently and must be kept small.
401 struct CitContext *MyContext(void) {
403 register struct CitContext *c;
405 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
406 c == NULL) ? &masterCC : c
412 * Initialize a new context and place it in the list. The session number
413 * used to be the PID (which is why it's called cs_pid), but that was when we
414 * had one process per session. Now we just assign them sequentially, starting
415 * at 1 (don't change it to 0 because masterCC uses 0).
417 struct CitContext *CreateNewContext(void) {
418 struct CitContext *me;
419 static int next_pid = 0;
421 me = (struct CitContext *) malloc(sizeof(struct CitContext));
423 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
427 memset(me, 0, sizeof(struct CitContext));
429 /* Give the contaxt a name. Hopefully makes it easier to track */
430 strcpy (me->user.fullname, "SYS_notauth");
432 /* The new context will be created already in the CON_EXECUTING state
433 * in order to prevent another thread from grabbing it while it's
436 me->state = CON_EXECUTING;
438 * Generate a unique session number and insert this context into
441 begin_critical_section(S_SESSION_TABLE);
442 me->cs_pid = ++next_pid;
444 me->next = ContextList;
446 if (me->next != NULL) {
450 end_critical_section(S_SESSION_TABLE);
455 struct CitContext *CtdlGetContextArray(int *count)
458 struct CitContext *nptr, *cptr;
460 nContexts = num_sessions;
461 nptr = malloc(sizeof(struct CitContext) * nContexts);
464 begin_critical_section(S_SESSION_TABLE);
465 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
466 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
467 end_critical_section (S_SESSION_TABLE);
476 * This function fills in a context and its user field correctly
477 * Then creates/loads that user
479 void CtdlFillSystemContext(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 /* internal_create_user has the side effect of loading the user regardless of wether they
489 * already existed or needed to be created
491 internal_create_user (sysname, &(context->user), -1) ;
493 /* Check to see if the system user needs upgrading */
494 if (context->user.usernum == 0)
495 { /* old system user with number 0, upgrade it */
496 context->user.usernum = get_new_user_number();
497 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
498 /* add user to the database */
499 putuser(&(context->user));
500 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
505 * The following functions implement output buffering. If the kernel supplies
506 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
507 * user-space buffering.
511 # define HAVE_TCP_BUFFERING
514 # define HAVE_TCP_BUFFERING
515 # define TCP_CORK TCP_NOPUSH
517 #endif /* TCP_CORK */
518 #endif /* HAVE_DARWIN */
520 #ifdef HAVE_TCP_BUFFERING
521 static unsigned on = 1, off = 0;
522 void buffer_output(void) {
523 struct CitContext *ctx = MyContext();
524 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
528 void unbuffer_output(void) {
529 struct CitContext *ctx = MyContext();
530 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
534 void flush_output(void) {
535 struct CitContext *ctx = MyContext();
536 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
537 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
541 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
542 void buffer_output(void) {
545 void unbuffer_output(void) {
548 void flush_output(void) {
551 void buffer_output(void) {
552 if (CC->buffering == 0) {
555 CC->output_buffer = malloc(SIZ);
559 void flush_output(void) {
560 if (CC->buffering == 1) {
561 client_write(CC->output_buffer, CC->buffer_len);
566 void unbuffer_output(void) {
567 if (CC->buffering == 1) {
569 /* We don't call flush_output because we can't. */
570 client_write(CC->output_buffer, CC->buffer_len);
572 free(CC->output_buffer);
573 CC->output_buffer = NULL;
576 #endif /* HAVE_DARWIN */
577 #endif /* HAVE_TCP_BUFFERING */
582 * client_write() ... Send binary data to the client.
584 int client_write(char *buf, int nbytes)
586 int bytes_written = 0;
588 #ifndef HAVE_TCP_BUFFERING
589 int old_buffer_len = 0;
596 if (Ctx->redirect_buffer != NULL) {
597 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
598 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
599 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
600 Ctx->redirect_alloc);
602 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
603 Ctx->redirect_len += nbytes;
604 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
608 #ifndef HAVE_TCP_BUFFERING
609 /* If we're buffering for later, do that now. */
610 if (Ctx->buffering) {
611 old_buffer_len = Ctx->buffer_len;
612 Ctx->buffer_len += nbytes;
613 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
614 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
619 /* Ok, at this point we're not buffering. Go ahead and write. */
622 if (Ctx->redirect_ssl) {
623 client_write_ssl(buf, nbytes);
628 fdflags = fcntl(Ctx->client_socket, F_GETFL);
630 while (bytes_written < nbytes) {
631 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
633 FD_SET(Ctx->client_socket, &wset);
634 if (select(1, NULL, &wset, NULL, NULL) == -1) {
635 CtdlLogPrintf(CTDL_ERR,
636 "client_write(%d bytes) select failed: %s (%d)\n",
637 nbytes - bytes_written,
638 strerror(errno), errno);
645 retval = write(Ctx->client_socket, &buf[bytes_written],
646 nbytes - bytes_written);
648 CtdlLogPrintf(CTDL_ERR,
649 "client_write(%d bytes) failed: %s (%d)\n",
650 nbytes - bytes_written,
651 strerror(errno), errno);
653 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
657 bytes_written = bytes_written + retval;
664 * cprintf() ... Send formatted printable data to the client. It is
665 * implemented in terms of client_write() but remains in
666 * sysdep.c in case we port to somewhere without va_args...
668 void cprintf(const char *format, ...) {
672 va_start(arg_ptr, format);
673 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
674 buf[sizeof buf - 2] = '\n';
675 client_write(buf, strlen(buf));
681 * Read data from the client socket.
683 * 1 Requested number of bytes has been read.
684 * 0 Request timed out.
685 * -1 The socket is broken.
686 * If the socket breaks, the session will be terminated.
688 int client_read_to(char *buf, int bytes, int timeout)
697 if (CC->redirect_ssl) {
698 return (client_read_ssl(buf, bytes, timeout));
702 fd = CC->client_socket;
709 retval = select( (fd)+1,
710 &rfds, NULL, NULL, &tv);
715 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
721 if (FD_ISSET(fd, &rfds) == 0) {
725 rlen = read(fd, &buf[len], bytes-len);
727 /* The socket has been disconnected! */
737 * Read data from the client socket with default timeout.
738 * (This is implemented in terms of client_read_to() and could be
739 * justifiably moved out of sysdep.c)
741 INLINE int client_read(char *buf, int bytes)
743 return(client_read_to(buf, bytes, config.c_sleeping));
748 * client_getln() ... Get a LF-terminated line of text from the client.
749 * (This is implemented in terms of client_read() and could be
750 * justifiably moved out of sysdep.c)
752 int client_getln(char *buf, int bufsize)
756 /* Read one character at a time.
759 retval = client_read(&buf[i], 1);
760 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
764 /* If we got a long line, discard characters until the newline.
766 if (i == (bufsize-1))
767 while (buf[i] != '\n' && retval == 1)
768 retval = client_read(&buf[i], 1);
770 /* Strip the trailing LF, and the trailing CR if present.
774 && ( (buf[i - 1]==13)
775 || ( buf[i - 1]==10)) ) {
779 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
785 * Cleanup any contexts that are left lying around
787 void context_cleanup(void)
789 struct CitContext *ptr = NULL;
790 struct CitContext *rem = NULL;
793 * Clean up the contexts.
794 * There are no threads so no critical_section stuff is needed.
798 /* We need to update the ContextList because some modules may want to itterate it
799 * Question is should we NULL it before iterating here or should we just keep updating it
800 * as we remove items?
802 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
806 /* Remove the session from the active list */
810 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
819 void close_masters (void)
821 struct ServiceFunctionHook *serviceptr;
824 * close all protocol master sockets
826 for (serviceptr = ServiceHookTable; serviceptr != NULL;
827 serviceptr = serviceptr->next ) {
829 if (serviceptr->tcp_port > 0)
831 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
832 serviceptr->tcp_port);
833 serviceptr->tcp_port = 0;
836 if (serviceptr->sockpath != NULL)
837 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
838 serviceptr->sockpath);
840 close(serviceptr->msock);
841 /* If it's a Unix domain socket, remove the file. */
842 if (serviceptr->sockpath != NULL) {
843 unlink(serviceptr->sockpath);
844 serviceptr->sockpath = NULL;
851 * The system-dependent part of master_cleanup() - close the master socket.
853 void sysdep_master_cleanup(void) {
862 CtdlDestroyProtoHooks();
863 CtdlDestroyDeleteHooks();
864 CtdlDestroyXmsgHooks();
865 CtdlDestroyNetprocHooks();
866 CtdlDestroyUserHooks();
867 CtdlDestroyMessageHook();
868 CtdlDestroyCleanupHooks();
869 CtdlDestroyFixedOutputHooks();
870 CtdlDestroySessionHooks();
871 CtdlDestroyServiceHook();
872 CtdlDestroyRoomHooks();
873 CtdlDestroyDirectoryServiceFuncs();
874 #ifdef HAVE_BACKTRACE
882 * Terminate another session.
883 * (This could justifiably be moved out of sysdep.c because it
884 * no longer does anything that is system-dependent.)
886 void kill_session(int session_to_kill) {
887 struct CitContext *ptr;
889 begin_critical_section(S_SESSION_TABLE);
890 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
891 if (ptr->cs_pid == session_to_kill) {
895 end_critical_section(S_SESSION_TABLE);
899 void graceful_shutdown(int signum) {
900 kill(current_child, signum);
901 unlink(file_pid_file);
907 * Start running as a daemon.
909 void start_daemon(int unused) {
917 /* Close stdin/stdout/stderr and replace them with /dev/null.
918 * We don't just call close() because we don't want these fd's
919 * to be reused for other files.
928 signal(SIGHUP, SIG_IGN);
929 signal(SIGINT, SIG_IGN);
930 signal(SIGQUIT, SIG_IGN);
934 freopen("/dev/null", "r", stdin);
935 freopen("/dev/null", "w", stdout);
936 freopen("/dev/null", "w", stderr);
939 current_child = fork();
941 signal(SIGTERM, graceful_shutdown);
943 if (current_child < 0) {
948 else if (current_child == 0) {
949 return; /* continue starting citadel. */
953 fp = fopen(file_pid_file, "w");
955 fprintf(fp, ""F_PID_T"\n", getpid());
958 waitpid(current_child, &status, 0);
963 /* Did the main process exit with an actual exit code? */
964 if (WIFEXITED(status)) {
966 /* Exit code 0 means the watcher should exit */
967 if (WEXITSTATUS(status) == 0) {
971 /* Exit code 101-109 means the watcher should exit */
972 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
976 /* Any other exit code means we should restart. */
982 /* Any other type of termination (signals, etc.) should also restart. */
987 } while (do_restart);
989 unlink(file_pid_file);
990 exit(WEXITSTATUS(status));
996 * Generic routine to convert a login name to a full name (gecos)
997 * Returns nonzero if a conversion took place
999 int convert_login(char NameToConvert[]) {
1003 pw = getpwnam(NameToConvert);
1008 strcpy(NameToConvert, pw->pw_gecos);
1009 for (a=0; a<strlen(NameToConvert); ++a) {
1010 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1017 * Purge all sessions which have the 'kill_me' flag set.
1018 * This function has code to prevent it from running more than once every
1019 * few seconds, because running it after every single unbind would waste a lot
1020 * of CPU time and keep the context list locked too much. To force it to run
1021 * anyway, set "force" to nonzero.
1023 void dead_session_purge(int force) {
1024 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1025 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1028 if ( (time(NULL) - last_purge) < 5 ) {
1029 return; /* Too soon, go away */
1034 if (try_critical_section(S_SESSION_TABLE))
1042 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1043 /* Remove the session from the active list */
1045 ptr2->prev->next = ptr2->next;
1048 ContextList = ptr2->next;
1051 ptr2->next->prev = ptr2->prev;
1055 /* And put it on our to-be-destroyed list */
1060 end_critical_section(S_SESSION_TABLE);
1062 /* Now that we no longer have the session list locked, we can take
1063 * our time and destroy any sessions on the to-be-killed list, which
1064 * is allocated privately on this thread's stack.
1066 while (rem != NULL) {
1067 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1080 * masterCC is the context we use when not attached to a session. This
1081 * function initializes it.
1083 void InitializeMasterCC(void) {
1084 memset(&masterCC, 0, sizeof(struct CitContext));
1085 masterCC.internal_pgm = 1;
1086 masterCC.cs_pid = 0;
1093 * Bind a thread to a context. (It's inline merely to speed things up.)
1095 INLINE void become_session(struct CitContext *which_con) {
1096 citthread_setspecific(MyConKey, (void *)which_con );
1102 * This loop just keeps going and going and going...
1106 * This current implimentation of worker_thread creates a bottle neck in several situations
1107 * The first thing to remember is that a single thread can handle more than one connection at a time.
1108 * More threads mean less memory for the system to run in.
1109 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1110 * something to happen anywhere.
1111 * This current implimentation requires worker threads to wait in other locations, after it has
1112 * been committed to a single connection which is very wasteful.
1113 * As an extreme case consider this:
1114 * A slow client connects and this slow client sends only one character each second.
1115 * With this current implimentation a single worker thread is dispatched to handle that connection
1116 * until such times as the client timeout expires, an error occurs on the socket or the client
1117 * completes its transmission.
1118 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1119 * second interval between chars.
1121 * It is my intention to re-write this code and the associated client_getln, client_read functions
1122 * to allow any thread to read data on behalf of any connection (context).
1123 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1124 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1126 * This worker thread loop also needs to be able to handle binary data.
1129 void *worker_thread(void *arg) {
1132 struct CitContext *ptr;
1133 struct CitContext *bind_me = NULL;
1136 struct CitContext *con= NULL; /* Temporary context pointer */
1137 struct ServiceFunctionHook *serviceptr;
1138 int ssock; /* Descriptor for client socket */
1140 int force_purge = 0;
1144 while (!CtdlThreadCheckStop()) {
1146 /* make doubly sure we're not holding any stale db handles
1147 * which might cause a deadlock.
1149 cdb_check_handles();
1150 do_select: force_purge = 0;
1151 bind_me = NULL; /* Which session shall we handle? */
1153 /* Initialize the fdset. */
1157 begin_critical_section(S_SESSION_TABLE);
1158 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1159 if (ptr->state == CON_IDLE) {
1160 FD_SET(ptr->client_socket, &readfds);
1161 if (ptr->client_socket > highest)
1162 highest = ptr->client_socket;
1164 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1166 ptr->state = CON_EXECUTING;
1169 end_critical_section(S_SESSION_TABLE);
1175 /* If we got this far, it means that there are no sessions
1176 * which a previous thread marked for attention, so we go
1177 * ahead and get ready to select().
1180 /* First, add the various master sockets to the fdset. */
1181 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1182 serviceptr = serviceptr->next ) {
1183 m = serviceptr->msock;
1184 FD_SET(m, &readfds);
1190 if (!CtdlThreadCheckStop()) {
1191 tv.tv_sec = 1; /* wake up every second if no input */
1193 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1198 /* Now figure out who made this select() unblock.
1199 * First, check for an error or exit condition.
1202 if (errno == EBADF) {
1203 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1207 if (errno != EINTR) {
1208 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1209 CtdlThreadStopAll();
1211 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1212 if (CtdlThreadCheckStop()) return(NULL);
1216 else if(retval == 0) {
1217 if (CtdlThreadCheckStop()) return(NULL);
1220 /* Next, check to see if it's a new client connecting
1221 * on a master socket.
1223 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1224 serviceptr = serviceptr->next ) {
1226 if (FD_ISSET(serviceptr->msock, &readfds)) {
1227 ssock = accept(serviceptr->msock, NULL, 0);
1229 CtdlLogPrintf(CTDL_DEBUG,
1230 "New client socket %d\n",
1233 /* The master socket is non-blocking but the client
1234 * sockets need to be blocking, otherwise certain
1235 * operations barf on FreeBSD. Not a fatal error.
1237 if (fcntl(ssock, F_SETFL, 0) < 0) {
1238 CtdlLogPrintf(CTDL_EMERG,
1239 "citserver: Can't set socket to blocking: %s\n",
1243 /* New context will be created already
1244 * set up in the CON_EXECUTING state.
1246 con = CreateNewContext();
1248 /* Assign our new socket number to it. */
1249 con->client_socket = ssock;
1250 con->h_command_function =
1251 serviceptr->h_command_function;
1252 con->h_async_function =
1253 serviceptr->h_async_function;
1255 serviceptr->ServiceName;
1257 /* Determine whether it's a local socket */
1258 if (serviceptr->sockpath != NULL)
1259 con->is_local_socket = 1;
1261 /* Set the SO_REUSEADDR socket option */
1263 setsockopt(ssock, SOL_SOCKET,
1267 become_session(con);
1269 serviceptr->h_greeting_function();
1270 become_session(NULL);
1271 con->state = CON_IDLE;
1277 /* It must be a client socket. Find a context that has data
1278 * waiting on its socket *and* is in the CON_IDLE state. Any
1279 * active sockets other than our chosen one are marked as
1280 * CON_READY so the next thread that comes around can just bind
1281 * to one without having to select() again.
1283 begin_critical_section(S_SESSION_TABLE);
1284 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1285 if ( (FD_ISSET(ptr->client_socket, &readfds))
1286 && (ptr->state != CON_EXECUTING) ) {
1287 ptr->input_waiting = 1;
1289 bind_me = ptr; /* I choose you! */
1290 bind_me->state = CON_EXECUTING;
1293 ptr->state = CON_READY;
1297 end_critical_section(S_SESSION_TABLE);
1300 /* We're bound to a session */
1301 if (bind_me != NULL) {
1302 become_session(bind_me);
1304 /* If the client has sent a command, execute it. */
1305 if (CC->input_waiting) {
1306 CC->h_command_function();
1307 CC->input_waiting = 0;
1310 /* If there are asynchronous messages waiting and the
1311 * client supports it, do those now */
1312 if ((CC->is_async) && (CC->async_waiting)
1313 && (CC->h_async_function != NULL)) {
1314 CC->h_async_function();
1315 CC->async_waiting = 0;
1318 force_purge = CC->kill_me;
1319 become_session(NULL);
1320 bind_me->state = CON_IDLE;
1323 dead_session_purge(force_purge);
1326 /* If control reaches this point, the server is shutting down */
1335 * Translate text facility name to syslog.h defined value.
1337 int SyslogFacility(char *name)
1346 { LOG_KERN, "kern" },
1347 { LOG_USER, "user" },
1348 { LOG_MAIL, "mail" },
1349 { LOG_DAEMON, "daemon" },
1350 { LOG_AUTH, "auth" },
1351 { LOG_SYSLOG, "syslog" },
1353 { LOG_NEWS, "news" },
1354 { LOG_UUCP, "uucp" },
1355 { LOG_LOCAL0, "local0" },
1356 { LOG_LOCAL1, "local1" },
1357 { LOG_LOCAL2, "local2" },
1358 { LOG_LOCAL3, "local3" },
1359 { LOG_LOCAL4, "local4" },
1360 { LOG_LOCAL5, "local5" },
1361 { LOG_LOCAL6, "local6" },
1362 { LOG_LOCAL7, "local7" },
1365 for(i = 0; facTbl[i].name != NULL; i++) {
1366 if(!strcasecmp(name, facTbl[i].name))
1367 return facTbl[i].facility;
1374 /********** MEM CHEQQER ***********/
1376 #ifdef DEBUG_MEMORY_LEAKS
1383 void *tracked_malloc(size_t size, char *file, int line) {
1384 struct igheap *thisheap;
1387 block = malloc(size);
1388 if (block == NULL) return(block);
1390 thisheap = malloc(sizeof(struct igheap));
1391 if (thisheap == NULL) {
1396 thisheap->block = block;
1397 strcpy(thisheap->file, file);
1398 thisheap->line = line;
1400 begin_critical_section(S_DEBUGMEMLEAKS);
1401 thisheap->next = igheap;
1403 end_critical_section(S_DEBUGMEMLEAKS);
1409 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1410 struct igheap *thisheap;
1413 block = realloc(ptr, size);
1414 if (block == NULL) return(block);
1416 thisheap = malloc(sizeof(struct igheap));
1417 if (thisheap == NULL) {
1422 thisheap->block = block;
1423 strcpy(thisheap->file, file);
1424 thisheap->line = line;
1426 begin_critical_section(S_DEBUGMEMLEAKS);
1427 thisheap->next = igheap;
1429 end_critical_section(S_DEBUGMEMLEAKS);
1436 void tracked_free(void *ptr) {
1437 struct igheap *thisheap;
1438 struct igheap *trash;
1442 if (igheap == NULL) return;
1443 begin_critical_section(S_DEBUGMEMLEAKS);
1444 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1445 if (thisheap->next != NULL) {
1446 if (thisheap->next->block == ptr) {
1447 trash = thisheap->next;
1448 thisheap->next = thisheap->next->next;
1453 if (igheap->block == ptr) {
1455 igheap = igheap->next;
1458 end_critical_section(S_DEBUGMEMLEAKS);
1461 char *tracked_strdup(const char *s, char *file, int line) {
1464 if (s == NULL) return(NULL);
1465 ptr = tracked_malloc(strlen(s) + 1, file, line);
1466 if (ptr == NULL) return(NULL);
1467 strncpy(ptr, s, strlen(s));
1471 void dump_heap(void) {
1472 struct igheap *thisheap;
1474 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1475 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1476 thisheap->file, thisheap->line);
1480 #endif /* DEBUG_MEMORY_LEAKS */