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>
57 #include "sysdep_decls.h"
58 #include "citserver.h"
62 #include "housekeeping.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
75 #ifdef DEBUG_MEMORY_LEAKS
83 struct igheap *igheap = NULL;
87 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
88 pthread_key_t MyConKey; /* TSD key for MyContext() */
90 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
92 struct CitContext masterCC;
93 time_t last_purge = 0; /* Last dead session purge */
94 static int num_threads = 0; /* Current number of threads */
95 int num_sessions = 0; /* Current number of sessions */
97 int syslog_facility = LOG_DAEMON;
98 int enable_syslog = 0;
100 void DestroyWorkerList(void);
103 * lprintf() ... Write logging information
105 void lprintf(enum LogLevel loglevel, const char *format, ...) {
110 va_start(arg_ptr, format);
111 vsyslog((syslog_facility | loglevel), format, arg_ptr);
115 /* stderr output code */
116 if (enable_syslog || running_as_daemon) {
120 /* if we run in forground and syslog is disabled, log to terminal */
121 if (loglevel <= verbosity) {
126 gettimeofday(&tv, NULL);
127 /* Promote to time_t; types differ on some OSes (like darwin) */
128 unixtime = tv.tv_sec;
129 localtime_r(&unixtime, &tim);
130 // begin_critical_section(S_LOG);
132 buf = malloc(SIZ+strlen(format));
134 if (CC->cs_pid != 0) {
136 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
137 tim.tm_year + 1900, tim.tm_mon + 1,
138 tim.tm_mday, tim.tm_hour, tim.tm_min,
139 tim.tm_sec, (long)tv.tv_usec,
143 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
144 tim.tm_year + 1900, tim.tm_mon + 1,
145 tim.tm_mday, tim.tm_hour, tim.tm_min,
146 tim.tm_sec, (long)tv.tv_usec);
149 va_start(arg_ptr, buf);
150 vfprintf(stderr, buf, arg_ptr);
154 // end_critical_section(S_LOG);
161 * Signal handler to shut down the server.
164 volatile int time_to_die = 0;
165 volatile int shutdown_and_halt = 0;
166 volatile int restart_server = 0;
167 volatile int running_as_daemon = 0;
169 static RETSIGTYPE signal_cleanup(int signum) {
170 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
172 master_cleanup(signum);
178 void InitialiseSemaphores(void)
182 /* Set up a bunch of semaphores to be used for critical sections */
183 for (i=0; i<MAX_SEMAPHORES; ++i) {
184 pthread_mutex_init(&Critters[i], NULL);
191 * Some initialization stuff...
193 void init_sysdep(void) {
196 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
200 getrlimit(RLIMIT_NOFILE, &rl);
201 rl.rlim_cur = FD_SETSIZE;
202 rl.rlim_max = FD_SETSIZE;
203 setrlimit(RLIMIT_NOFILE, &rl);
207 /* If we've got OpenSSL, we're going to use it. */
213 * Set up a place to put thread-specific data.
214 * We only need a single pointer per thread - it points to the
215 * CitContext structure (in the ContextList linked list) of the
216 * session to which the calling thread is currently bound.
218 if (pthread_key_create(&MyConKey, NULL) != 0) {
219 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
224 * The action for unexpected signals and exceptions should be to
225 * call signal_cleanup() to gracefully shut down the server.
228 sigaddset(&set, SIGINT);
229 sigaddset(&set, SIGQUIT);
230 sigaddset(&set, SIGHUP);
231 sigaddset(&set, SIGTERM);
232 // sigaddset(&set, SIGSEGV); commented out because
233 // sigaddset(&set, SIGILL); we want core dumps
234 // sigaddset(&set, SIGBUS);
235 sigprocmask(SIG_UNBLOCK, &set, NULL);
237 signal(SIGINT, signal_cleanup);
238 signal(SIGQUIT, signal_cleanup);
239 signal(SIGHUP, signal_cleanup);
240 signal(SIGTERM, signal_cleanup);
241 // signal(SIGSEGV, signal_cleanup); commented out because
242 // signal(SIGILL, signal_cleanup); we want core dumps
243 // signal(SIGBUS, signal_cleanup);
246 * Do not shut down the server on broken pipe signals, otherwise the
247 * whole Citadel service would come down whenever a single client
250 signal(SIGPIPE, SIG_IGN);
255 * Obtain a semaphore lock to begin a critical section.
257 void begin_critical_section(int which_one)
259 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
261 /* For all types of critical sections except those listed here,
262 * ensure nobody ever tries to do a critical section within a
263 * transaction; this could lead to deadlock.
265 if ( (which_one != S_FLOORCACHE)
266 #ifdef DEBUG_MEMORY_LEAKS
267 && (which_one != S_DEBUGMEMLEAKS)
269 && (which_one != S_RPLIST)
273 pthread_mutex_lock(&Critters[which_one]);
277 * Release a semaphore lock to end a critical section.
279 void end_critical_section(int which_one)
281 pthread_mutex_unlock(&Critters[which_one]);
287 * This is a generic function to set up a master socket for listening on
288 * a TCP port. The server shuts down if the bind fails.
291 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
293 struct sockaddr_in sin;
295 int actual_queue_len;
297 actual_queue_len = queue_len;
298 if (actual_queue_len < 5) actual_queue_len = 5;
300 memset(&sin, 0, sizeof(sin));
301 sin.sin_family = AF_INET;
302 sin.sin_port = htons((u_short)port_number);
303 if (ip_addr == NULL) {
304 sin.sin_addr.s_addr = INADDR_ANY;
307 sin.sin_addr.s_addr = inet_addr(ip_addr);
310 if (sin.sin_addr.s_addr == !INADDR_ANY) {
311 sin.sin_addr.s_addr = INADDR_ANY;
314 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
317 *errormessage = (char*) malloc(SIZ + 1);
318 snprintf(*errormessage, SIZ,
319 "citserver: Can't create a socket: %s",
321 lprintf(CTDL_EMERG, "%s\n", *errormessage);
326 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
328 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
329 *errormessage = (char*) malloc(SIZ + 1);
330 snprintf(*errormessage, SIZ,
331 "citserver: Can't bind: %s",
333 lprintf(CTDL_EMERG, "%s\n", *errormessage);
338 /* set to nonblock - we need this for some obscure situations */
339 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
340 *errormessage = (char*) malloc(SIZ + 1);
341 snprintf(*errormessage, SIZ,
342 "citserver: Can't set socket to non-blocking: %s",
344 lprintf(CTDL_EMERG, "%s\n", *errormessage);
349 if (listen(s, actual_queue_len) < 0) {
350 *errormessage = (char*) malloc(SIZ + 1);
351 snprintf(*errormessage, SIZ,
352 "citserver: Can't listen: %s",
354 lprintf(CTDL_EMERG, "%s\n", *errormessage);
365 * Create a Unix domain socket and listen on it
367 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
369 struct sockaddr_un addr;
372 int actual_queue_len;
374 actual_queue_len = queue_len;
375 if (actual_queue_len < 5) actual_queue_len = 5;
377 i = unlink(sockpath);
378 if (i != 0) if (errno != ENOENT) {
379 *errormessage = (char*) malloc(SIZ + 1);
380 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
381 sockpath, strerror(errno));
382 lprintf(CTDL_EMERG, "%s\n", *errormessage);
386 memset(&addr, 0, sizeof(addr));
387 addr.sun_family = AF_UNIX;
388 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
390 s = socket(AF_UNIX, SOCK_STREAM, 0);
392 *errormessage = (char*) malloc(SIZ + 1);
393 snprintf(*errormessage, SIZ,
394 "citserver: Can't create a socket: %s",
396 lprintf(CTDL_EMERG, "%s\n", *errormessage);
400 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
401 *errormessage = (char*) malloc(SIZ + 1);
402 snprintf(*errormessage, SIZ,
403 "citserver: Can't bind: %s",
405 lprintf(CTDL_EMERG, "%s\n", *errormessage);
409 /* set to nonblock - we need this for some obscure situations */
410 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
411 *errormessage = (char*) malloc(SIZ + 1);
412 snprintf(*errormessage, SIZ,
413 "citserver: Can't set socket to non-blocking: %s",
415 lprintf(CTDL_EMERG, "%s\n", *errormessage);
420 if (listen(s, actual_queue_len) < 0) {
421 *errormessage = (char*) malloc(SIZ + 1);
422 snprintf(*errormessage, SIZ,
423 "citserver: Can't listen: %s",
425 lprintf(CTDL_EMERG, "%s\n", *errormessage);
429 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
436 * Return a pointer to the CitContext structure bound to the thread which
437 * called this function. If there's no such binding (for example, if it's
438 * called by the housekeeper thread) then a generic 'master' CC is returned.
440 * This function is used *VERY* frequently and must be kept small.
442 struct CitContext *MyContext(void) {
444 register struct CitContext *c;
446 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
447 c == NULL) ? &masterCC : c
453 * Initialize a new context and place it in the list. The session number
454 * used to be the PID (which is why it's called cs_pid), but that was when we
455 * had one process per session. Now we just assign them sequentially, starting
456 * at 1 (don't change it to 0 because masterCC uses 0).
458 struct CitContext *CreateNewContext(void) {
459 struct CitContext *me;
460 static int next_pid = 0;
462 me = (struct CitContext *) malloc(sizeof(struct CitContext));
464 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
467 memset(me, 0, sizeof(struct CitContext));
469 /* The new context will be created already in the CON_EXECUTING state
470 * in order to prevent another thread from grabbing it while it's
473 me->state = CON_EXECUTING;
476 * Generate a unique session number and insert this context into
479 begin_critical_section(S_SESSION_TABLE);
480 me->cs_pid = ++next_pid;
482 me->next = ContextList;
484 if (me->next != NULL) {
488 end_critical_section(S_SESSION_TABLE);
494 * The following functions implement output buffering. If the kernel supplies
495 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
496 * user-space buffering.
500 # define HAVE_TCP_BUFFERING
503 # define HAVE_TCP_BUFFERING
504 # define TCP_CORK TCP_NOPUSH
506 #endif /* TCP_CORK */
507 #endif /* HAVE_DARWIN */
509 #ifdef HAVE_TCP_BUFFERING
510 static unsigned on = 1, off = 0;
511 void buffer_output(void) {
512 struct CitContext *ctx = MyContext();
513 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
517 void unbuffer_output(void) {
518 struct CitContext *ctx = MyContext();
519 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
523 void flush_output(void) {
524 struct CitContext *ctx = MyContext();
525 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
526 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
530 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
531 void buffer_output(void) {
534 void unbuffer_output(void) {
537 void flush_output(void) {
540 void buffer_output(void) {
541 if (CC->buffering == 0) {
544 CC->output_buffer = malloc(SIZ);
548 void flush_output(void) {
549 if (CC->buffering == 1) {
550 client_write(CC->output_buffer, CC->buffer_len);
555 void unbuffer_output(void) {
556 if (CC->buffering == 1) {
558 /* We don't call flush_output because we can't. */
559 client_write(CC->output_buffer, CC->buffer_len);
561 free(CC->output_buffer);
562 CC->output_buffer = NULL;
565 #endif /* HAVE_DARWIN */
566 #endif /* HAVE_TCP_BUFFERING */
571 * client_write() ... Send binary data to the client.
573 void client_write(char *buf, int nbytes)
575 int bytes_written = 0;
577 #ifndef HAVE_TCP_BUFFERING
578 int old_buffer_len = 0;
581 if (CC->redirect_buffer != NULL) {
582 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
583 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
584 CC->redirect_buffer = realloc(CC->redirect_buffer,
587 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
588 CC->redirect_len += nbytes;
589 CC->redirect_buffer[CC->redirect_len] = 0;
593 #ifndef HAVE_TCP_BUFFERING
594 /* If we're buffering for later, do that now. */
596 old_buffer_len = CC->buffer_len;
597 CC->buffer_len += nbytes;
598 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
599 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
604 /* Ok, at this point we're not buffering. Go ahead and write. */
607 if (CC->redirect_ssl) {
608 client_write_ssl(buf, nbytes);
613 while (bytes_written < nbytes) {
614 retval = write(CC->client_socket, &buf[bytes_written],
615 nbytes - bytes_written);
618 "client_write(%d bytes) failed: %s (%d)\n",
619 nbytes - bytes_written,
620 strerror(errno), errno);
625 bytes_written = bytes_written + retval;
631 * cprintf() ... Send formatted printable data to the client. It is
632 * implemented in terms of client_write() but remains in
633 * sysdep.c in case we port to somewhere without va_args...
635 void cprintf(const char *format, ...) {
639 va_start(arg_ptr, format);
640 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
641 buf[sizeof buf - 2] = '\n';
642 client_write(buf, strlen(buf));
648 * Read data from the client socket.
650 * 1 Requested number of bytes has been read.
651 * 0 Request timed out.
652 * -1 The socket is broken.
653 * If the socket breaks, the session will be terminated.
655 int client_read_to(char *buf, int bytes, int timeout)
663 if (CC->redirect_ssl) {
664 return (client_read_ssl(buf, bytes, timeout));
670 FD_SET(CC->client_socket, &rfds);
674 retval = select( (CC->client_socket)+1,
675 &rfds, NULL, NULL, &tv);
677 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
681 rlen = read(CC->client_socket, &buf[len], bytes-len);
683 /* The socket has been disconnected! */
693 * Read data from the client socket with default timeout.
694 * (This is implemented in terms of client_read_to() and could be
695 * justifiably moved out of sysdep.c)
697 INLINE int client_read(char *buf, int bytes)
699 return(client_read_to(buf, bytes, config.c_sleeping));
704 * client_getln() ... Get a LF-terminated line of text from the client.
705 * (This is implemented in terms of client_read() and could be
706 * justifiably moved out of sysdep.c)
708 int client_getln(char *buf, int bufsize)
712 /* Read one character at a time.
715 retval = client_read(&buf[i], 1);
716 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
720 /* If we got a long line, discard characters until the newline.
722 if (i == (bufsize-1))
723 while (buf[i] != '\n' && retval == 1)
724 retval = client_read(&buf[i], 1);
726 /* Strip the trailing LF, and the trailing CR if present.
729 while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
730 buf[strlen(buf)-1] = 0;
732 if (retval < 0) safestrncpy(buf, "000", bufsize);
739 * The system-dependent part of master_cleanup() - close the master socket.
741 void sysdep_master_cleanup(void) {
742 struct ServiceFunctionHook *serviceptr;
744 ///// DestroyWorkerList();
746 * close all protocol master sockets
748 for (serviceptr = ServiceHookTable; serviceptr != NULL;
749 serviceptr = serviceptr->next ) {
751 if (serviceptr->tcp_port > 0)
752 lprintf(CTDL_INFO, "Closing listener on port %d\n",
753 serviceptr->tcp_port);
755 if (serviceptr->sockpath != NULL)
756 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
757 serviceptr->sockpath);
759 close(serviceptr->msock);
761 /* If it's a Unix domain socket, remove the file. */
762 if (serviceptr->sockpath != NULL) {
763 unlink(serviceptr->sockpath);
769 serv_calendar_destroy();
770 CtdlDestroyProtoHooks();
771 CtdlDestroyDeleteHooks();
772 CtdlDestroyXmsgHooks();
773 CtdlDestroyNetprocHooks();
774 CtdlDestroyUserHooks();
775 CtdlDestroyMessageHook();
776 CtdlDestroyCleanupHooks();
777 CtdlDestroyFixedOutputHooks();
778 CtdlDestroySessionHooks();
779 CtdlDestroyServiceHook();
786 * Terminate another session.
787 * (This could justifiably be moved out of sysdep.c because it
788 * no longer does anything that is system-dependent.)
790 void kill_session(int session_to_kill) {
791 struct CitContext *ptr;
793 begin_critical_section(S_SESSION_TABLE);
794 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
795 if (ptr->cs_pid == session_to_kill) {
799 end_critical_section(S_SESSION_TABLE);
803 void graceful_shutdown(int signum) {
804 kill(current_child, signum);
805 unlink(file_pid_file);
811 * Start running as a daemon.
813 void start_daemon(int unused) {
821 /* Close stdin/stdout/stderr and replace them with /dev/null.
822 * We don't just call close() because we don't want these fd's
823 * to be reused for other files.
832 signal(SIGHUP, SIG_IGN);
833 signal(SIGINT, SIG_IGN);
834 signal(SIGQUIT, SIG_IGN);
838 freopen("/dev/null", "r", stdin);
839 freopen("/dev/null", "w", stdout);
840 freopen("/dev/null", "w", stderr);
843 current_child = fork();
845 signal(SIGTERM, graceful_shutdown);
847 if (current_child < 0) {
852 else if (current_child == 0) {
853 return; /* continue starting citadel. */
857 fp = fopen(file_pid_file, "w");
859 fprintf(fp, ""F_PID_T"\n", child);
862 waitpid(current_child, &status, 0);
867 /* Did the main process exit with an actual exit code? */
868 if (WIFEXITED(status)) {
870 /* Exit code 0 means the watcher should exit */
871 if (WEXITSTATUS(status) == 0) {
875 /* Exit code 101-109 means the watcher should exit */
876 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
880 /* Any other exit code means we should restart. */
886 /* Any other type of termination (signals, etc.) should also restart. */
891 } while (do_restart);
893 unlink(file_pid_file);
894 exit(WEXITSTATUS(status));
900 * Generic routine to convert a login name to a full name (gecos)
901 * Returns nonzero if a conversion took place
903 int convert_login(char NameToConvert[]) {
907 pw = getpwnam(NameToConvert);
912 strcpy(NameToConvert, pw->pw_gecos);
913 for (a=0; a<strlen(NameToConvert); ++a) {
914 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
920 struct worker_node *worker_list = NULL;
924 * create a worker thread. this function must always be called from within
925 * an S_WORKER_LIST critical section!
927 void create_worker(void) {
929 struct worker_node *n;
932 n = malloc(sizeof(struct worker_node));
934 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
939 if ((ret = pthread_attr_init(&attr))) {
940 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
945 /* Our per-thread stacks need to be bigger than the default size,
946 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
947 * crashes on 64-bit Linux.
949 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
950 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
953 pthread_attr_destroy(&attr);
957 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
960 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
964 n->next = worker_list;
966 pthread_attr_destroy(&attr);
969 void DestroyWorkerList(void)
971 struct CitContext *ptr; /* general-purpose utility pointer */
972 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
974 begin_critical_section(S_SESSION_TABLE);
977 /* Remove the session from the active list */
981 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
982 end_critical_section(S_SESSION_TABLE);
984 begin_critical_section(S_SESSION_TABLE);
988 end_critical_section(S_SESSION_TABLE);
990 struct worker_node *cur, *p;
1002 * Create the maintenance threads and begin their operation.
1004 void create_maintenance_threads(void) {
1006 pthread_attr_t attr;
1008 if ((ret = pthread_attr_init(&attr))) {
1009 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1014 /* Our per-thread stacks need to be bigger than the default size,
1015 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1016 * crashes on 64-bit Linux.
1018 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1019 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1022 pthread_attr_destroy(&attr);
1026 struct MaintenanceThreadHook *fcn;
1028 lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1030 for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1031 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1032 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1036 lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1037 fcn->MaintenanceThread_tid);
1042 pthread_attr_destroy(&attr);
1048 * Purge all sessions which have the 'kill_me' flag set.
1049 * This function has code to prevent it from running more than once every
1050 * few seconds, because running it after every single unbind would waste a lot
1051 * of CPU time and keep the context list locked too much. To force it to run
1052 * anyway, set "force" to nonzero.
1055 * After that's done, we raise the size of the worker thread pool
1056 * if such an action is appropriate.
1058 void dead_session_purge(int force) {
1059 struct CitContext *ptr; /* general-purpose utility pointer */
1060 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1063 if ( (time(NULL) - last_purge) < 5 ) {
1064 return; /* Too soon, go away */
1069 begin_critical_section(S_SESSION_TABLE);
1070 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1071 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1073 /* Remove the session from the active list */
1075 ptr->prev->next = ptr->next;
1078 ContextList = ptr->next;
1081 ptr->next->prev = ptr->prev;
1086 /* And put it on our to-be-destroyed list */
1092 end_critical_section(S_SESSION_TABLE);
1094 /* Now that we no longer have the session list locked, we can take
1095 * our time and destroy any sessions on the to-be-killed list, which
1096 * is allocated privately on this thread's stack.
1098 while (rem != NULL) {
1099 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1106 /* Raise the size of the worker thread pool if necessary. */
1107 if ( (num_sessions > num_threads)
1108 && (num_threads < config.c_max_workers) ) {
1109 begin_critical_section(S_WORKER_LIST);
1111 end_critical_section(S_WORKER_LIST);
1120 * masterCC is the context we use when not attached to a session. This
1121 * function initializes it.
1123 void InitializeMasterCC(void) {
1124 memset(&masterCC, 0, sizeof(struct CitContext));
1125 masterCC.internal_pgm = 1;
1126 masterCC.cs_pid = 0;
1135 * Bind a thread to a context. (It's inline merely to speed things up.)
1137 INLINE void become_session(struct CitContext *which_con) {
1138 pthread_setspecific(MyConKey, (void *)which_con );
1144 * This loop just keeps going and going and going...
1146 void *worker_thread(void *arg) {
1149 struct CitContext *ptr;
1150 struct CitContext *bind_me = NULL;
1153 struct CitContext *con= NULL; /* Temporary context pointer */
1154 struct ServiceFunctionHook *serviceptr;
1155 int ssock; /* Descriptor for client socket */
1157 int force_purge = 0;
1164 while (!time_to_die) {
1166 /* make doubly sure we're not holding any stale db handles
1167 * which might cause a deadlock.
1169 cdb_check_handles();
1170 do_select: force_purge = 0;
1171 bind_me = NULL; /* Which session shall we handle? */
1173 /* Initialize the fdset. */
1177 begin_critical_section(S_SESSION_TABLE);
1178 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1179 if (ptr->state == CON_IDLE) {
1180 FD_SET(ptr->client_socket, &readfds);
1181 if (ptr->client_socket > highest)
1182 highest = ptr->client_socket;
1184 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1186 ptr->state = CON_EXECUTING;
1189 end_critical_section(S_SESSION_TABLE);
1195 /* If we got this far, it means that there are no sessions
1196 * which a previous thread marked for attention, so we go
1197 * ahead and get ready to select().
1200 /* First, add the various master sockets to the fdset. */
1201 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1202 serviceptr = serviceptr->next ) {
1203 m = serviceptr->msock;
1204 FD_SET(m, &readfds);
1211 tv.tv_sec = 1; /* wake up every second if no input */
1213 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1216 if (time_to_die) return(NULL);
1218 /* Now figure out who made this select() unblock.
1219 * First, check for an error or exit condition.
1222 if (errno == EBADF) {
1223 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1227 if (errno != EINTR) {
1228 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1230 } else if (!time_to_die)
1234 /* Next, check to see if it's a new client connecting
1235 * on a master socket.
1237 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1238 serviceptr = serviceptr->next ) {
1240 if (FD_ISSET(serviceptr->msock, &readfds)) {
1241 ssock = accept(serviceptr->msock, NULL, 0);
1244 "New client socket %d\n",
1247 /* The master socket is non-blocking but the client
1248 * sockets need to be blocking, otherwise certain
1249 * operations barf on FreeBSD. Not a fatal error.
1251 if (fcntl(ssock, F_SETFL, 0) < 0) {
1253 "citserver: Can't set socket to blocking: %s\n",
1257 /* New context will be created already
1258 * set up in the CON_EXECUTING state.
1260 con = CreateNewContext();
1262 /* Assign our new socket number to it. */
1263 con->client_socket = ssock;
1264 con->h_command_function =
1265 serviceptr->h_command_function;
1266 con->h_async_function =
1267 serviceptr->h_async_function;
1269 /* Determine whether it's a local socket */
1270 if (serviceptr->sockpath != NULL)
1271 con->is_local_socket = 1;
1273 /* Set the SO_REUSEADDR socket option */
1275 setsockopt(ssock, SOL_SOCKET,
1279 become_session(con);
1281 serviceptr->h_greeting_function();
1282 become_session(NULL);
1283 con->state = CON_IDLE;
1289 /* It must be a client socket. Find a context that has data
1290 * waiting on its socket *and* is in the CON_IDLE state. Any
1291 * active sockets other than our chosen one are marked as
1292 * CON_READY so the next thread that comes around can just bind
1293 * to one without having to select() again.
1295 begin_critical_section(S_SESSION_TABLE);
1296 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1297 if ( (FD_ISSET(ptr->client_socket, &readfds))
1298 && (ptr->state != CON_EXECUTING) ) {
1299 ptr->input_waiting = 1;
1301 bind_me = ptr; /* I choose you! */
1302 bind_me->state = CON_EXECUTING;
1305 ptr->state = CON_READY;
1309 end_critical_section(S_SESSION_TABLE);
1312 /* We're bound to a session */
1313 if (bind_me != NULL) {
1314 become_session(bind_me);
1316 /* If the client has sent a command, execute it. */
1317 if (CC->input_waiting) {
1318 CC->h_command_function();
1319 CC->input_waiting = 0;
1322 /* If there are asynchronous messages waiting and the
1323 * client supports it, do those now */
1324 if ((CC->is_async) && (CC->async_waiting)
1325 && (CC->h_async_function != NULL)) {
1326 CC->h_async_function();
1327 CC->async_waiting = 0;
1330 force_purge = CC->kill_me;
1331 become_session(NULL);
1332 bind_me->state = CON_IDLE;
1335 dead_session_purge(force_purge);
1337 check_sched_shutdown();
1339 if (con != NULL) free (con);//// TODO: could this harm other threads?
1340 /* If control reaches this point, the server is shutting down */
1349 * Translate text facility name to syslog.h defined value.
1351 int SyslogFacility(char *name)
1360 { LOG_KERN, "kern" },
1361 { LOG_USER, "user" },
1362 { LOG_MAIL, "mail" },
1363 { LOG_DAEMON, "daemon" },
1364 { LOG_AUTH, "auth" },
1365 { LOG_SYSLOG, "syslog" },
1367 { LOG_NEWS, "news" },
1368 { LOG_UUCP, "uucp" },
1369 { LOG_LOCAL0, "local0" },
1370 { LOG_LOCAL1, "local1" },
1371 { LOG_LOCAL2, "local2" },
1372 { LOG_LOCAL3, "local3" },
1373 { LOG_LOCAL4, "local4" },
1374 { LOG_LOCAL5, "local5" },
1375 { LOG_LOCAL6, "local6" },
1376 { LOG_LOCAL7, "local7" },
1379 for(i = 0; facTbl[i].name != NULL; i++) {
1380 if(!strcasecmp(name, facTbl[i].name))
1381 return facTbl[i].facility;
1388 /********** MEM CHEQQER ***********/
1390 #ifdef DEBUG_MEMORY_LEAKS
1397 void *tracked_malloc(size_t size, char *file, int line) {
1398 struct igheap *thisheap;
1401 block = malloc(size);
1402 if (block == NULL) return(block);
1404 thisheap = malloc(sizeof(struct igheap));
1405 if (thisheap == NULL) {
1410 thisheap->block = block;
1411 strcpy(thisheap->file, file);
1412 thisheap->line = line;
1414 begin_critical_section(S_DEBUGMEMLEAKS);
1415 thisheap->next = igheap;
1417 end_critical_section(S_DEBUGMEMLEAKS);
1423 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1424 struct igheap *thisheap;
1427 block = realloc(ptr, size);
1428 if (block == NULL) return(block);
1430 thisheap = malloc(sizeof(struct igheap));
1431 if (thisheap == NULL) {
1436 thisheap->block = block;
1437 strcpy(thisheap->file, file);
1438 thisheap->line = line;
1440 begin_critical_section(S_DEBUGMEMLEAKS);
1441 thisheap->next = igheap;
1443 end_critical_section(S_DEBUGMEMLEAKS);
1450 void tracked_free(void *ptr) {
1451 struct igheap *thisheap;
1452 struct igheap *trash;
1456 if (igheap == NULL) return;
1457 begin_critical_section(S_DEBUGMEMLEAKS);
1458 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1459 if (thisheap->next != NULL) {
1460 if (thisheap->next->block == ptr) {
1461 trash = thisheap->next;
1462 thisheap->next = thisheap->next->next;
1467 if (igheap->block == ptr) {
1469 igheap = igheap->next;
1472 end_critical_section(S_DEBUGMEMLEAKS);
1475 char *tracked_strdup(const char *s, char *file, int line) {
1478 if (s == NULL) return(NULL);
1479 ptr = tracked_malloc(strlen(s) + 1, file, line);
1480 if (ptr == NULL) return(NULL);
1481 strncpy(ptr, s, strlen(s));
1485 void dump_heap(void) {
1486 struct igheap *thisheap;
1488 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1489 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1490 thisheap->file, thisheap->line);
1494 #endif /* DEBUG_MEMORY_LEAKS */