4 * Citadel "system dependent" stuff.
5 * See COPYING for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
22 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syslog.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
52 #include <libcitadel.h>
55 #include "sysdep_decls.h"
56 #include "citserver.h"
60 #include "housekeeping.h"
61 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
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;
102 /* Flag for single user mode */
103 static int want_single_user = 0;
105 /* Try to go single user */
107 int CtdlTrySingleUser(void)
111 begin_critical_section(S_SINGLE_USER);
112 if (want_single_user)
117 want_single_user = 1;
119 end_critical_section(S_SINGLE_USER);
123 void CtdlEndSingleUser(void)
125 begin_critical_section(S_SINGLE_USER);
126 want_single_user = 0;
127 end_critical_section(S_SINGLE_USER);
131 int CtdlWantSingleUser(void)
133 return want_single_user;
136 int CtdlIsSingleUser(void)
138 if (want_single_user)
140 /* check for only one context here */
141 if (num_sessions == 1)
149 * CtdlLogPrintf() ... Write logging information
151 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
153 va_start(arg_ptr, format);
154 vCtdlLogPrintf(loglevel, format, arg_ptr);
158 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
160 char buf[SIZ], buf2[SIZ];
163 vsyslog((syslog_facility | loglevel), format, arg_ptr);
166 /* stderr output code */
167 if (enable_syslog || running_as_daemon) return;
169 /* if we run in forground and syslog is disabled, log to terminal */
170 if (loglevel <= verbosity) {
175 gettimeofday(&tv, NULL);
176 /* Promote to time_t; types differ on some OSes (like darwin) */
177 unixtime = tv.tv_sec;
178 localtime_r(&unixtime, &tim);
179 if (CC->cs_pid != 0) {
181 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
182 tim.tm_year + 1900, tim.tm_mon + 1,
183 tim.tm_mday, tim.tm_hour, tim.tm_min,
184 tim.tm_sec, (long)tv.tv_usec,
188 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
189 tim.tm_year + 1900, tim.tm_mon + 1,
190 tim.tm_mday, tim.tm_hour, tim.tm_min,
191 tim.tm_sec, (long)tv.tv_usec);
193 vsnprintf(buf2, SIZ, format, arg_ptr);
195 fprintf(stderr, "%s%s", buf, buf2);
203 * Signal handler to shut down the server.
206 volatile int exit_signal = 0;
207 volatile int shutdown_and_halt = 0;
208 volatile int restart_server = 0;
209 volatile int running_as_daemon = 0;
211 static RETSIGTYPE signal_cleanup(int signum) {
212 #ifdef THREADS_USESIGNALS
218 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
219 exit_signal = signum;
226 * Some initialization stuff...
228 void init_sysdep(void) {
231 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
235 getrlimit(RLIMIT_NOFILE, &rl);
236 rl.rlim_cur = FD_SETSIZE;
237 rl.rlim_max = FD_SETSIZE;
238 setrlimit(RLIMIT_NOFILE, &rl);
242 /* If we've got OpenSSL, we're going to use it. */
248 * Set up a place to put thread-specific data.
249 * We only need a single pointer per thread - it points to the
250 * CitContext structure (in the ContextList linked list) of the
251 * session to which the calling thread is currently bound.
253 if (citthread_key_create(&MyConKey, NULL) != 0) {
254 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
259 * The action for unexpected signals and exceptions should be to
260 * call signal_cleanup() to gracefully shut down the server.
263 sigaddset(&set, SIGINT);
264 sigaddset(&set, SIGQUIT);
265 sigaddset(&set, SIGHUP);
266 sigaddset(&set, SIGTERM);
267 // sigaddset(&set, SIGSEGV); commented out because
268 // sigaddset(&set, SIGILL); we want core dumps
269 // sigaddset(&set, SIGBUS);
270 sigprocmask(SIG_UNBLOCK, &set, NULL);
272 signal(SIGINT, signal_cleanup);
273 signal(SIGQUIT, signal_cleanup);
274 signal(SIGHUP, signal_cleanup);
275 signal(SIGTERM, signal_cleanup);
276 // signal(SIGSEGV, signal_cleanup); commented out because
277 // signal(SIGILL, signal_cleanup); we want core dumps
278 // signal(SIGBUS, signal_cleanup);
281 * Do not shut down the server on broken pipe signals, otherwise the
282 * whole Citadel service would come down whenever a single client
285 signal(SIGPIPE, SIG_IGN);
292 * This is a generic function to set up a master socket for listening on
293 * a TCP port. The server shuts down if the bind fails.
296 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
298 struct sockaddr_in sin;
300 int actual_queue_len;
302 actual_queue_len = queue_len;
303 if (actual_queue_len < 5) actual_queue_len = 5;
305 memset(&sin, 0, sizeof(sin));
306 sin.sin_family = AF_INET;
307 sin.sin_port = htons((u_short)port_number);
308 if (ip_addr == NULL) {
309 sin.sin_addr.s_addr = INADDR_ANY;
312 sin.sin_addr.s_addr = inet_addr(ip_addr);
315 if (sin.sin_addr.s_addr == !INADDR_ANY) {
316 sin.sin_addr.s_addr = INADDR_ANY;
319 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
322 *errormessage = (char*) malloc(SIZ + 1);
323 snprintf(*errormessage, SIZ,
324 "citserver: Can't create a socket: %s",
326 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
331 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
333 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
334 *errormessage = (char*) malloc(SIZ + 1);
335 snprintf(*errormessage, SIZ,
336 "citserver: Can't bind: %s",
338 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
343 /* set to nonblock - we need this for some obscure situations */
344 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
345 *errormessage = (char*) malloc(SIZ + 1);
346 snprintf(*errormessage, SIZ,
347 "citserver: Can't set socket to non-blocking: %s",
349 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
354 if (listen(s, actual_queue_len) < 0) {
355 *errormessage = (char*) malloc(SIZ + 1);
356 snprintf(*errormessage, SIZ,
357 "citserver: Can't listen: %s",
359 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
370 * Create a Unix domain socket and listen on it
372 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
374 struct sockaddr_un addr;
377 int actual_queue_len;
379 actual_queue_len = queue_len;
380 if (actual_queue_len < 5) actual_queue_len = 5;
382 i = unlink(sockpath);
383 if ((i != 0) && (errno != ENOENT)) {
384 *errormessage = (char*) malloc(SIZ + 1);
385 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
386 sockpath, strerror(errno));
387 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
391 memset(&addr, 0, sizeof(addr));
392 addr.sun_family = AF_UNIX;
393 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
395 s = socket(AF_UNIX, SOCK_STREAM, 0);
397 *errormessage = (char*) malloc(SIZ + 1);
398 snprintf(*errormessage, SIZ,
399 "citserver: Can't create a socket: %s",
401 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
405 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
406 *errormessage = (char*) malloc(SIZ + 1);
407 snprintf(*errormessage, SIZ,
408 "citserver: Can't bind: %s",
410 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
414 /* set to nonblock - we need this for some obscure situations */
415 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
416 *errormessage = (char*) malloc(SIZ + 1);
417 snprintf(*errormessage, SIZ,
418 "citserver: Can't set socket to non-blocking: %s",
420 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
425 if (listen(s, actual_queue_len) < 0) {
426 *errormessage = (char*) malloc(SIZ + 1);
427 snprintf(*errormessage, SIZ,
428 "citserver: Can't listen: %s",
430 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
434 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
441 * Return a pointer to the CitContext structure bound to the thread which
442 * called this function. If there's no such binding (for example, if it's
443 * called by the housekeeper thread) then a generic 'master' CC is returned.
445 * This function is used *VERY* frequently and must be kept small.
447 struct CitContext *MyContext(void) {
449 register struct CitContext *c;
451 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
452 c == NULL) ? &masterCC : c
458 * Initialize a new context and place it in the list. The session number
459 * used to be the PID (which is why it's called cs_pid), but that was when we
460 * had one process per session. Now we just assign them sequentially, starting
461 * at 1 (don't change it to 0 because masterCC uses 0).
463 struct CitContext *CreateNewContext(void) {
464 struct CitContext *me;
465 static int next_pid = 0;
467 me = (struct CitContext *) malloc(sizeof(struct CitContext));
469 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
473 memset(me, 0, sizeof(struct CitContext));
475 /* Give the contaxt a name. Hopefully makes it easier to track */
476 strcpy (me->user.fullname, "SYS_notauth");
478 /* The new context will be created already in the CON_EXECUTING state
479 * in order to prevent another thread from grabbing it while it's
482 me->state = CON_EXECUTING;
484 * Generate a unique session number and insert this context into
487 begin_critical_section(S_SESSION_TABLE);
488 me->cs_pid = ++next_pid;
490 me->next = ContextList;
492 if (me->next != NULL) {
496 end_critical_section(S_SESSION_TABLE);
501 struct CitContext *CtdlGetContextArray(int *count)
504 struct CitContext *nptr, *cptr;
506 nContexts = num_sessions;
507 nptr = malloc(sizeof(struct CitContext) * nContexts);
510 begin_critical_section(S_SESSION_TABLE);
511 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
512 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
513 end_critical_section (S_SESSION_TABLE);
522 * This function fills in a context and its user field correctly
523 * Then creates/loads that user
525 void CtdlFillSystemContext(struct CitContext *context, char *name)
527 char sysname[USERNAME_SIZE];
529 memset(context, 0, sizeof(struct CitContext));
530 context->internal_pgm = 1;
532 strcpy (sysname, "SYS_");
533 strcat (sysname, name);
534 /* internal_create_user has the side effect of loading the user regardless of wether they
535 * already existed or needed to be created
537 internal_create_user (sysname, &(context->user), -1) ;
539 /* Check to see if the system user needs upgrading */
540 if (context->user.usernum == 0)
541 { /* old system user with number 0, upgrade it */
542 context->user.usernum = get_new_user_number();
543 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
544 /* add user to the database */
545 putuser(&(context->user));
546 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
551 * The following functions implement output buffering on operating systems which
552 * support it (such as Linux and various BSD flavors).
556 # define HAVE_TCP_BUFFERING
559 # define HAVE_TCP_BUFFERING
560 # define TCP_CORK TCP_NOPUSH
562 #endif /* TCP_CORK */
563 #endif /* HAVE_DARWIN */
565 static unsigned on = 1, off = 0;
567 void buffer_output(void) {
568 #ifdef HAVE_TCP_BUFFERING
569 if (!CC->redirect_ssl) {
570 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
575 void unbuffer_output(void) {
576 #ifdef HAVE_TCP_BUFFERING
577 if (!CC->redirect_ssl) {
578 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
583 void flush_output(void) {
584 #ifdef HAVE_TCP_BUFFERING
585 struct CitContext *CCC = CC;
586 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
587 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
594 * client_write() ... Send binary data to the client.
596 int client_write(char *buf, int nbytes)
598 int bytes_written = 0;
600 #ifndef HAVE_TCP_BUFFERING
601 int old_buffer_len = 0;
608 if (Ctx->redirect_buffer != NULL) {
609 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
610 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
611 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
612 Ctx->redirect_alloc);
614 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
615 Ctx->redirect_len += nbytes;
616 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
621 if (Ctx->redirect_ssl) {
622 client_write_ssl(buf, nbytes);
627 fdflags = fcntl(Ctx->client_socket, F_GETFL);
629 while (bytes_written < nbytes) {
630 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
632 FD_SET(Ctx->client_socket, &wset);
633 if (select(1, NULL, &wset, NULL, NULL) == -1) {
634 CtdlLogPrintf(CTDL_ERR,
635 "client_write(%d bytes) select failed: %s (%d)\n",
636 nbytes - bytes_written,
637 strerror(errno), errno);
644 retval = write(Ctx->client_socket, &buf[bytes_written],
645 nbytes - bytes_written);
647 CtdlLogPrintf(CTDL_ERR,
648 "client_write(%d bytes) failed: %s (%d)\n",
649 nbytes - bytes_written,
650 strerror(errno), errno);
652 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
656 bytes_written = bytes_written + retval;
663 * cprintf() Send formatted printable data to the client.
664 * Implemented in terms of client_write() so it's technically not sysdep...
666 void cprintf(const char *format, ...) {
670 va_start(arg_ptr, format);
671 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
672 buf[sizeof buf - 2] = '\n';
673 client_write(buf, strlen(buf));
679 * Read data from the client socket.
681 * 1 Requested number of bytes has been read.
682 * 0 Request timed out.
683 * -1 The socket is broken.
684 * If the socket breaks, the session will be terminated.
686 int client_read_to(char *buf, int bytes, int timeout)
695 if (CC->redirect_ssl) {
696 return (client_read_ssl(buf, bytes, timeout));
700 fd = CC->client_socket;
707 retval = select( (fd)+1,
708 &rfds, NULL, NULL, &tv);
713 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
719 if (FD_ISSET(fd, &rfds) == 0) {
723 rlen = read(fd, &buf[len], bytes-len);
725 /* The socket has been disconnected! */
735 * Read data from the client socket with default timeout.
736 * (This is implemented in terms of client_read_to() and could be
737 * justifiably moved out of sysdep.c)
739 INLINE int client_read(char *buf, int bytes)
741 return(client_read_to(buf, bytes, config.c_sleeping));
746 * client_getln() ... Get a LF-terminated line of text from the client.
747 * (This is implemented in terms of client_read() and could be
748 * justifiably moved out of sysdep.c)
750 int client_getln(char *buf, int bufsize)
754 /* Read one character at a time.
757 retval = client_read(&buf[i], 1);
758 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
762 /* If we got a long line, discard characters until the newline.
764 if (i == (bufsize-1))
765 while (buf[i] != '\n' && retval == 1)
766 retval = client_read(&buf[i], 1);
768 /* Strip the trailing LF, and the trailing CR if present.
772 && ( (buf[i - 1]==13)
773 || ( buf[i - 1]==10)) ) {
777 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
783 * Cleanup any contexts that are left lying around
785 void context_cleanup(void)
787 struct CitContext *ptr = NULL;
788 struct CitContext *rem = NULL;
791 * Clean up the contexts.
792 * There are no threads so no critical_section stuff is needed.
796 /* We need to update the ContextList because some modules may want to itterate it
797 * Question is should we NULL it before iterating here or should we just keep updating it
798 * as we remove items?
800 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
804 /* Remove the session from the active list */
808 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
817 void close_masters (void)
819 struct ServiceFunctionHook *serviceptr;
822 * close all protocol master sockets
824 for (serviceptr = ServiceHookTable; serviceptr != NULL;
825 serviceptr = serviceptr->next ) {
827 if (serviceptr->tcp_port > 0)
829 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
830 serviceptr->tcp_port);
831 serviceptr->tcp_port = 0;
834 if (serviceptr->sockpath != NULL)
835 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
836 serviceptr->sockpath);
838 close(serviceptr->msock);
839 /* If it's a Unix domain socket, remove the file. */
840 if (serviceptr->sockpath != NULL) {
841 unlink(serviceptr->sockpath);
842 serviceptr->sockpath = NULL;
849 * The system-dependent part of master_cleanup() - close the master socket.
851 void sysdep_master_cleanup(void) {
860 CtdlDestroyProtoHooks();
861 CtdlDestroyDeleteHooks();
862 CtdlDestroyXmsgHooks();
863 CtdlDestroyNetprocHooks();
864 CtdlDestroyUserHooks();
865 CtdlDestroyMessageHook();
866 CtdlDestroyCleanupHooks();
867 CtdlDestroyFixedOutputHooks();
868 CtdlDestroySessionHooks();
869 CtdlDestroyServiceHook();
870 CtdlDestroyRoomHooks();
871 CtdlDestroyDirectoryServiceFuncs();
872 #ifdef HAVE_BACKTRACE
880 * Terminate another session.
881 * (This could justifiably be moved out of sysdep.c because it
882 * no longer does anything that is system-dependent.)
884 void kill_session(int session_to_kill) {
885 struct CitContext *ptr;
887 begin_critical_section(S_SESSION_TABLE);
888 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
889 if (ptr->cs_pid == session_to_kill) {
893 end_critical_section(S_SESSION_TABLE);
897 void graceful_shutdown(int signum) {
898 kill(current_child, signum);
899 unlink(file_pid_file);
904 int nFireUpsNonRestart = 0;
908 * Start running as a daemon.
910 void start_daemon(int unused) {
918 /* Close stdin/stdout/stderr and replace them with /dev/null.
919 * We don't just call close() because we don't want these fd's
920 * to be reused for other files.
929 signal(SIGHUP, SIG_IGN);
930 signal(SIGINT, SIG_IGN);
931 signal(SIGQUIT, SIG_IGN);
935 freopen("/dev/null", "r", stdin);
936 freopen("/dev/null", "w", stdout);
937 freopen("/dev/null", "w", stderr);
940 current_child = fork();
942 signal(SIGTERM, graceful_shutdown);
944 if (current_child < 0) {
949 else if (current_child == 0) {
950 return; /* continue starting citadel. */
954 fp = fopen(file_pid_file, "w");
956 fprintf(fp, ""F_PID_T"\n", getpid());
959 waitpid(current_child, &status, 0);
962 nFireUpsNonRestart = nFireUps;
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. */
980 ForkedPid = current_child;
984 /* Any other type of termination (signals, etc.) should also restart. */
988 ForkedPid = current_child;
991 } while (do_restart);
993 unlink(file_pid_file);
994 exit(WEXITSTATUS(status));
999 void checkcrash(void)
1001 if (nFireUpsNonRestart != nFireUps)
1005 CrashMail = NewStrBuf();
1006 CtdlLogPrintf (CTDL_ALERT, "----------------sending crash mail\n");
1007 StrBufPrintf(CrashMail,
1008 "Your CitServer is just recovering from an unexpected termination.\n"
1009 " this maybe the result of an error in citserver or an external influence.\n"
1010 " You can get more information on this by enabling coredumping; for more information see\n"
1011 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files\n"
1012 " If you already did, the file you're looking for most probably is %score.%d\n"
1013 " Yours faithfully...",
1014 ctdl_run_dir, ForkedPid);
1015 aide_message(ChrPtr(CrashMail), "Citadel server crashed.");
1016 FreeStrBuf(&CrashMail);
1022 * Generic routine to convert a login name to a full name (gecos)
1023 * Returns nonzero if a conversion took place
1025 int convert_login(char NameToConvert[]) {
1029 pw = getpwnam(NameToConvert);
1034 strcpy(NameToConvert, pw->pw_gecos);
1035 for (a=0; a<strlen(NameToConvert); ++a) {
1036 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1043 * Purge all sessions which have the 'kill_me' flag set.
1044 * This function has code to prevent it from running more than once every
1045 * few seconds, because running it after every single unbind would waste a lot
1046 * of CPU time and keep the context list locked too much. To force it to run
1047 * anyway, set "force" to nonzero.
1049 void dead_session_purge(int force) {
1050 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1051 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1054 if ( (time(NULL) - last_purge) < 5 ) {
1055 return; /* Too soon, go away */
1060 if (try_critical_section(S_SESSION_TABLE))
1068 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1069 /* Remove the session from the active list */
1071 ptr2->prev->next = ptr2->next;
1074 ContextList = ptr2->next;
1077 ptr2->next->prev = ptr2->prev;
1081 /* And put it on our to-be-destroyed list */
1086 end_critical_section(S_SESSION_TABLE);
1088 /* Now that we no longer have the session list locked, we can take
1089 * our time and destroy any sessions on the to-be-killed list, which
1090 * is allocated privately on this thread's stack.
1092 while (rem != NULL) {
1093 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1106 * masterCC is the context we use when not attached to a session. This
1107 * function initializes it.
1109 void InitializeMasterCC(void) {
1110 memset(&masterCC, 0, sizeof(struct CitContext));
1111 masterCC.internal_pgm = 1;
1112 masterCC.cs_pid = 0;
1119 * Bind a thread to a context. (It's inline merely to speed things up.)
1121 INLINE void become_session(struct CitContext *which_con) {
1122 citthread_setspecific(MyConKey, (void *)which_con );
1128 * This loop just keeps going and going and going...
1132 * This current implimentation of worker_thread creates a bottle neck in several situations
1133 * The first thing to remember is that a single thread can handle more than one connection at a time.
1134 * More threads mean less memory for the system to run in.
1135 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1136 * something to happen anywhere.
1137 * This current implimentation requires worker threads to wait in other locations, after it has
1138 * been committed to a single connection which is very wasteful.
1139 * As an extreme case consider this:
1140 * A slow client connects and this slow client sends only one character each second.
1141 * With this current implimentation a single worker thread is dispatched to handle that connection
1142 * until such times as the client timeout expires, an error occurs on the socket or the client
1143 * completes its transmission.
1144 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1145 * second interval between chars.
1147 * It is my intention to re-write this code and the associated client_getln, client_read functions
1148 * to allow any thread to read data on behalf of any connection (context).
1149 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1150 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1152 * This worker thread loop also needs to be able to handle binary data.
1155 void *worker_thread(void *arg) {
1158 struct CitContext *ptr;
1159 struct CitContext *bind_me = NULL;
1162 struct CitContext *con= NULL; /* Temporary context pointer */
1163 struct ServiceFunctionHook *serviceptr;
1164 int ssock; /* Descriptor for client socket */
1166 int force_purge = 0;
1170 while (!CtdlThreadCheckStop()) {
1172 /* make doubly sure we're not holding any stale db handles
1173 * which might cause a deadlock.
1175 cdb_check_handles();
1176 do_select: force_purge = 0;
1177 bind_me = NULL; /* Which session shall we handle? */
1179 /* Initialize the fdset. */
1183 begin_critical_section(S_SESSION_TABLE);
1184 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1185 if (ptr->state == CON_IDLE) {
1186 FD_SET(ptr->client_socket, &readfds);
1187 if (ptr->client_socket > highest)
1188 highest = ptr->client_socket;
1190 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1192 ptr->state = CON_EXECUTING;
1195 end_critical_section(S_SESSION_TABLE);
1201 /* If we got this far, it means that there are no sessions
1202 * which a previous thread marked for attention, so we go
1203 * ahead and get ready to select().
1206 /* First, add the various master sockets to the fdset. */
1207 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1208 serviceptr = serviceptr->next ) {
1209 m = serviceptr->msock;
1210 FD_SET(m, &readfds);
1216 if (!CtdlThreadCheckStop()) {
1217 tv.tv_sec = 1; /* wake up every second if no input */
1219 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1224 /* Now figure out who made this select() unblock.
1225 * First, check for an error or exit condition.
1228 if (errno == EBADF) {
1229 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1233 if (errno != EINTR) {
1234 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1235 CtdlThreadStopAll();
1237 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1238 if (CtdlThreadCheckStop()) return(NULL);
1242 else if(retval == 0) {
1243 if (CtdlThreadCheckStop()) return(NULL);
1246 /* Next, check to see if it's a new client connecting
1247 * on a master socket.
1249 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1250 serviceptr = serviceptr->next ) {
1252 if (FD_ISSET(serviceptr->msock, &readfds)) {
1253 ssock = accept(serviceptr->msock, NULL, 0);
1255 CtdlLogPrintf(CTDL_DEBUG,
1256 "New client socket %d\n",
1259 /* The master socket is non-blocking but the client
1260 * sockets need to be blocking, otherwise certain
1261 * operations barf on FreeBSD. Not a fatal error.
1263 if (fcntl(ssock, F_SETFL, 0) < 0) {
1264 CtdlLogPrintf(CTDL_EMERG,
1265 "citserver: Can't set socket to blocking: %s\n",
1269 /* New context will be created already
1270 * set up in the CON_EXECUTING state.
1272 con = CreateNewContext();
1274 /* Assign our new socket number to it. */
1275 con->client_socket = ssock;
1276 con->h_command_function =
1277 serviceptr->h_command_function;
1278 con->h_async_function =
1279 serviceptr->h_async_function;
1281 serviceptr->ServiceName;
1283 /* Determine whether it's a local socket */
1284 if (serviceptr->sockpath != NULL)
1285 con->is_local_socket = 1;
1287 /* Set the SO_REUSEADDR socket option */
1289 setsockopt(ssock, SOL_SOCKET,
1293 become_session(con);
1295 serviceptr->h_greeting_function();
1296 become_session(NULL);
1297 con->state = CON_IDLE;
1303 /* It must be a client socket. Find a context that has data
1304 * waiting on its socket *and* is in the CON_IDLE state. Any
1305 * active sockets other than our chosen one are marked as
1306 * CON_READY so the next thread that comes around can just bind
1307 * to one without having to select() again.
1309 begin_critical_section(S_SESSION_TABLE);
1310 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1311 if ( (FD_ISSET(ptr->client_socket, &readfds))
1312 && (ptr->state != CON_EXECUTING) ) {
1313 ptr->input_waiting = 1;
1315 bind_me = ptr; /* I choose you! */
1316 bind_me->state = CON_EXECUTING;
1319 ptr->state = CON_READY;
1323 end_critical_section(S_SESSION_TABLE);
1326 /* We're bound to a session */
1327 if (bind_me != NULL) {
1328 become_session(bind_me);
1330 /* If the client has sent a command, execute it. */
1331 if (CC->input_waiting) {
1332 CC->h_command_function();
1333 CC->input_waiting = 0;
1336 /* If there are asynchronous messages waiting and the
1337 * client supports it, do those now */
1338 if ((CC->is_async) && (CC->async_waiting)
1339 && (CC->h_async_function != NULL)) {
1340 CC->h_async_function();
1341 CC->async_waiting = 0;
1344 force_purge = CC->kill_me;
1345 become_session(NULL);
1346 bind_me->state = CON_IDLE;
1349 dead_session_purge(force_purge);
1352 /* If control reaches this point, the server is shutting down */
1361 * Translate text facility name to syslog.h defined value.
1363 int SyslogFacility(char *name)
1372 { LOG_KERN, "kern" },
1373 { LOG_USER, "user" },
1374 { LOG_MAIL, "mail" },
1375 { LOG_DAEMON, "daemon" },
1376 { LOG_AUTH, "auth" },
1377 { LOG_SYSLOG, "syslog" },
1379 { LOG_NEWS, "news" },
1380 { LOG_UUCP, "uucp" },
1381 { LOG_LOCAL0, "local0" },
1382 { LOG_LOCAL1, "local1" },
1383 { LOG_LOCAL2, "local2" },
1384 { LOG_LOCAL3, "local3" },
1385 { LOG_LOCAL4, "local4" },
1386 { LOG_LOCAL5, "local5" },
1387 { LOG_LOCAL6, "local6" },
1388 { LOG_LOCAL7, "local7" },
1391 for(i = 0; facTbl[i].name != NULL; i++) {
1392 if(!strcasecmp(name, facTbl[i].name))
1393 return facTbl[i].facility;
1400 /********** MEM CHEQQER ***********/
1402 #ifdef DEBUG_MEMORY_LEAKS
1409 void *tracked_malloc(size_t size, char *file, int line) {
1410 struct igheap *thisheap;
1413 block = malloc(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);
1435 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1436 struct igheap *thisheap;
1439 block = realloc(ptr, size);
1440 if (block == NULL) return(block);
1442 thisheap = malloc(sizeof(struct igheap));
1443 if (thisheap == NULL) {
1448 thisheap->block = block;
1449 strcpy(thisheap->file, file);
1450 thisheap->line = line;
1452 begin_critical_section(S_DEBUGMEMLEAKS);
1453 thisheap->next = igheap;
1455 end_critical_section(S_DEBUGMEMLEAKS);
1462 void tracked_free(void *ptr) {
1463 struct igheap *thisheap;
1464 struct igheap *trash;
1468 if (igheap == NULL) return;
1469 begin_critical_section(S_DEBUGMEMLEAKS);
1470 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1471 if (thisheap->next != NULL) {
1472 if (thisheap->next->block == ptr) {
1473 trash = thisheap->next;
1474 thisheap->next = thisheap->next->next;
1479 if (igheap->block == ptr) {
1481 igheap = igheap->next;
1484 end_critical_section(S_DEBUGMEMLEAKS);
1487 char *tracked_strdup(const char *s, char *file, int line) {
1490 if (s == NULL) return(NULL);
1491 ptr = tracked_malloc(strlen(s) + 1, file, line);
1492 if (ptr == NULL) return(NULL);
1493 strncpy(ptr, s, strlen(s));
1497 void dump_heap(void) {
1498 struct igheap *thisheap;
1500 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1501 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1502 thisheap->file, thisheap->line);
1506 #endif /* DEBUG_MEMORY_LEAKS */