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 */
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
76 #ifdef DEBUG_MEMORY_LEAKS
84 struct igheap *igheap = NULL;
88 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
89 pthread_key_t MyConKey; /* TSD key for MyContext() */
91 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
93 struct CitContext masterCC;
94 time_t last_purge = 0; /* Last dead session purge */
95 static int num_threads = 0; /* Current number of threads */
96 int num_sessions = 0; /* Current number of sessions */
98 int syslog_facility = LOG_DAEMON;
99 int enable_syslog = 0;
101 void DestroyWorkerList(void);
104 * lprintf() ... Write logging information
106 void lprintf(enum LogLevel loglevel, const char *format, ...) {
108 char buf[SIZ], buf2[SIZ];
111 va_start(arg_ptr, format);
112 vsyslog((syslog_facility | loglevel), format, arg_ptr);
116 /* stderr output code */
117 if (enable_syslog || running_as_daemon) return;
119 /* if we run in forground and syslog is disabled, log to terminal */
120 if (loglevel <= verbosity) {
125 gettimeofday(&tv, NULL);
126 /* Promote to time_t; types differ on some OSes (like darwin) */
127 unixtime = tv.tv_sec;
128 localtime_r(&unixtime, &tim);
129 if (CC->cs_pid != 0) {
131 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
132 tim.tm_year + 1900, tim.tm_mon + 1,
133 tim.tm_mday, tim.tm_hour, tim.tm_min,
134 tim.tm_sec, (long)tv.tv_usec,
138 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
139 tim.tm_year + 1900, tim.tm_mon + 1,
140 tim.tm_mday, tim.tm_hour, tim.tm_min,
141 tim.tm_sec, (long)tv.tv_usec);
143 va_start(arg_ptr, format);
144 vsprintf(buf2, format, arg_ptr);
147 fprintf(stderr, "%s%s", buf, buf2);
155 * Signal handler to shut down the server.
158 volatile int time_to_die = 0;
159 volatile int shutdown_and_halt = 0;
160 volatile int restart_server = 0;
161 volatile int running_as_daemon = 0;
163 static RETSIGTYPE signal_cleanup(int signum) {
164 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
166 master_cleanup(signum);
172 void InitialiseSemaphores(void)
176 /* Set up a bunch of semaphores to be used for critical sections */
177 for (i=0; i<MAX_SEMAPHORES; ++i) {
178 pthread_mutex_init(&Critters[i], NULL);
185 * Some initialization stuff...
187 void init_sysdep(void) {
190 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
194 getrlimit(RLIMIT_NOFILE, &rl);
195 rl.rlim_cur = FD_SETSIZE;
196 rl.rlim_max = FD_SETSIZE;
197 setrlimit(RLIMIT_NOFILE, &rl);
201 /* If we've got OpenSSL, we're going to use it. */
207 * Set up a place to put thread-specific data.
208 * We only need a single pointer per thread - it points to the
209 * CitContext structure (in the ContextList linked list) of the
210 * session to which the calling thread is currently bound.
212 if (pthread_key_create(&MyConKey, NULL) != 0) {
213 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
218 * The action for unexpected signals and exceptions should be to
219 * call signal_cleanup() to gracefully shut down the server.
222 sigaddset(&set, SIGINT);
223 sigaddset(&set, SIGQUIT);
224 sigaddset(&set, SIGHUP);
225 sigaddset(&set, SIGTERM);
226 // sigaddset(&set, SIGSEGV); commented out because
227 // sigaddset(&set, SIGILL); we want core dumps
228 // sigaddset(&set, SIGBUS);
229 sigprocmask(SIG_UNBLOCK, &set, NULL);
231 signal(SIGINT, signal_cleanup);
232 signal(SIGQUIT, signal_cleanup);
233 signal(SIGHUP, signal_cleanup);
234 signal(SIGTERM, signal_cleanup);
235 // signal(SIGSEGV, signal_cleanup); commented out because
236 // signal(SIGILL, signal_cleanup); we want core dumps
237 // signal(SIGBUS, signal_cleanup);
240 * Do not shut down the server on broken pipe signals, otherwise the
241 * whole Citadel service would come down whenever a single client
244 signal(SIGPIPE, SIG_IGN);
249 * Obtain a semaphore lock to begin a critical section.
251 void begin_critical_section(int which_one)
253 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
255 /* For all types of critical sections except those listed here,
256 * ensure nobody ever tries to do a critical section within a
257 * transaction; this could lead to deadlock.
259 if ( (which_one != S_FLOORCACHE)
260 #ifdef DEBUG_MEMORY_LEAKS
261 && (which_one != S_DEBUGMEMLEAKS)
263 && (which_one != S_RPLIST)
267 pthread_mutex_lock(&Critters[which_one]);
271 * Release a semaphore lock to end a critical section.
273 void end_critical_section(int which_one)
275 pthread_mutex_unlock(&Critters[which_one]);
281 * This is a generic function to set up a master socket for listening on
282 * a TCP port. The server shuts down if the bind fails.
285 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
287 struct sockaddr_in sin;
289 int actual_queue_len;
291 actual_queue_len = queue_len;
292 if (actual_queue_len < 5) actual_queue_len = 5;
294 memset(&sin, 0, sizeof(sin));
295 sin.sin_family = AF_INET;
296 sin.sin_port = htons((u_short)port_number);
297 if (ip_addr == NULL) {
298 sin.sin_addr.s_addr = INADDR_ANY;
301 sin.sin_addr.s_addr = inet_addr(ip_addr);
304 if (sin.sin_addr.s_addr == !INADDR_ANY) {
305 sin.sin_addr.s_addr = INADDR_ANY;
308 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
311 *errormessage = (char*) malloc(SIZ + 1);
312 snprintf(*errormessage, SIZ,
313 "citserver: Can't create a socket: %s",
315 lprintf(CTDL_EMERG, "%s\n", *errormessage);
320 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
322 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
323 *errormessage = (char*) malloc(SIZ + 1);
324 snprintf(*errormessage, SIZ,
325 "citserver: Can't bind: %s",
327 lprintf(CTDL_EMERG, "%s\n", *errormessage);
332 /* set to nonblock - we need this for some obscure situations */
333 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
334 *errormessage = (char*) malloc(SIZ + 1);
335 snprintf(*errormessage, SIZ,
336 "citserver: Can't set socket to non-blocking: %s",
338 lprintf(CTDL_EMERG, "%s\n", *errormessage);
343 if (listen(s, actual_queue_len) < 0) {
344 *errormessage = (char*) malloc(SIZ + 1);
345 snprintf(*errormessage, SIZ,
346 "citserver: Can't listen: %s",
348 lprintf(CTDL_EMERG, "%s\n", *errormessage);
359 * Create a Unix domain socket and listen on it
361 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
363 struct sockaddr_un addr;
366 int actual_queue_len;
368 actual_queue_len = queue_len;
369 if (actual_queue_len < 5) actual_queue_len = 5;
371 i = unlink(sockpath);
372 if (i != 0) if (errno != ENOENT) {
373 *errormessage = (char*) malloc(SIZ + 1);
374 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
375 sockpath, strerror(errno));
376 lprintf(CTDL_EMERG, "%s\n", *errormessage);
380 memset(&addr, 0, sizeof(addr));
381 addr.sun_family = AF_UNIX;
382 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
384 s = socket(AF_UNIX, SOCK_STREAM, 0);
386 *errormessage = (char*) malloc(SIZ + 1);
387 snprintf(*errormessage, SIZ,
388 "citserver: Can't create a socket: %s",
390 lprintf(CTDL_EMERG, "%s\n", *errormessage);
394 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
395 *errormessage = (char*) malloc(SIZ + 1);
396 snprintf(*errormessage, SIZ,
397 "citserver: Can't bind: %s",
399 lprintf(CTDL_EMERG, "%s\n", *errormessage);
403 /* set to nonblock - we need this for some obscure situations */
404 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
405 *errormessage = (char*) malloc(SIZ + 1);
406 snprintf(*errormessage, SIZ,
407 "citserver: Can't set socket to non-blocking: %s",
409 lprintf(CTDL_EMERG, "%s\n", *errormessage);
414 if (listen(s, actual_queue_len) < 0) {
415 *errormessage = (char*) malloc(SIZ + 1);
416 snprintf(*errormessage, SIZ,
417 "citserver: Can't listen: %s",
419 lprintf(CTDL_EMERG, "%s\n", *errormessage);
423 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
430 * Return a pointer to the CitContext structure bound to the thread which
431 * called this function. If there's no such binding (for example, if it's
432 * called by the housekeeper thread) then a generic 'master' CC is returned.
434 * This function is used *VERY* frequently and must be kept small.
436 struct CitContext *MyContext(void) {
438 register struct CitContext *c;
440 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
441 c == NULL) ? &masterCC : c
447 * Initialize a new context and place it in the list. The session number
448 * used to be the PID (which is why it's called cs_pid), but that was when we
449 * had one process per session. Now we just assign them sequentially, starting
450 * at 1 (don't change it to 0 because masterCC uses 0).
452 struct CitContext *CreateNewContext(void) {
453 struct CitContext *me;
454 static int next_pid = 0;
456 me = (struct CitContext *) malloc(sizeof(struct CitContext));
458 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
461 memset(me, 0, sizeof(struct CitContext));
463 /* The new context will be created already in the CON_EXECUTING state
464 * in order to prevent another thread from grabbing it while it's
467 me->state = CON_EXECUTING;
470 * Generate a unique session number and insert this context into
473 begin_critical_section(S_SESSION_TABLE);
474 me->cs_pid = ++next_pid;
476 me->next = ContextList;
478 if (me->next != NULL) {
482 end_critical_section(S_SESSION_TABLE);
488 * The following functions implement output buffering. If the kernel supplies
489 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
490 * user-space buffering.
494 # define HAVE_TCP_BUFFERING
497 # define HAVE_TCP_BUFFERING
498 # define TCP_CORK TCP_NOPUSH
500 #endif /* TCP_CORK */
501 #endif /* HAVE_DARWIN */
503 #ifdef HAVE_TCP_BUFFERING
504 static unsigned on = 1, off = 0;
505 void buffer_output(void) {
506 struct CitContext *ctx = MyContext();
507 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
511 void unbuffer_output(void) {
512 struct CitContext *ctx = MyContext();
513 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
517 void flush_output(void) {
518 struct CitContext *ctx = MyContext();
519 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
520 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
524 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
525 void buffer_output(void) {
528 void unbuffer_output(void) {
531 void flush_output(void) {
534 void buffer_output(void) {
535 if (CC->buffering == 0) {
538 CC->output_buffer = malloc(SIZ);
542 void flush_output(void) {
543 if (CC->buffering == 1) {
544 client_write(CC->output_buffer, CC->buffer_len);
549 void unbuffer_output(void) {
550 if (CC->buffering == 1) {
552 /* We don't call flush_output because we can't. */
553 client_write(CC->output_buffer, CC->buffer_len);
555 free(CC->output_buffer);
556 CC->output_buffer = NULL;
559 #endif /* HAVE_DARWIN */
560 #endif /* HAVE_TCP_BUFFERING */
565 * client_write() ... Send binary data to the client.
567 void client_write(char *buf, int nbytes)
569 int bytes_written = 0;
571 #ifndef HAVE_TCP_BUFFERING
572 int old_buffer_len = 0;
575 if (CC->redirect_buffer != NULL) {
576 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
577 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
578 CC->redirect_buffer = realloc(CC->redirect_buffer,
581 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
582 CC->redirect_len += nbytes;
583 CC->redirect_buffer[CC->redirect_len] = 0;
587 #ifndef HAVE_TCP_BUFFERING
588 /* If we're buffering for later, do that now. */
590 old_buffer_len = CC->buffer_len;
591 CC->buffer_len += nbytes;
592 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
593 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
598 /* Ok, at this point we're not buffering. Go ahead and write. */
601 if (CC->redirect_ssl) {
602 client_write_ssl(buf, nbytes);
607 while (bytes_written < nbytes) {
608 retval = write(CC->client_socket, &buf[bytes_written],
609 nbytes - bytes_written);
612 "client_write(%d bytes) failed: %s (%d)\n",
613 nbytes - bytes_written,
614 strerror(errno), errno);
616 lprintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
620 bytes_written = bytes_written + retval;
626 * cprintf() ... Send formatted printable data to the client. It is
627 * implemented in terms of client_write() but remains in
628 * sysdep.c in case we port to somewhere without va_args...
630 void cprintf(const char *format, ...) {
634 va_start(arg_ptr, format);
635 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
636 buf[sizeof buf - 2] = '\n';
637 client_write(buf, strlen(buf));
643 * Read data from the client socket.
645 * 1 Requested number of bytes has been read.
646 * 0 Request timed out.
647 * -1 The socket is broken.
648 * If the socket breaks, the session will be terminated.
650 int client_read_to(char *buf, int bytes, int timeout)
658 if (CC->redirect_ssl) {
659 return (client_read_ssl(buf, bytes, timeout));
665 FD_SET(CC->client_socket, &rfds);
669 retval = select( (CC->client_socket)+1,
670 &rfds, NULL, NULL, &tv);
672 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
676 rlen = read(CC->client_socket, &buf[len], bytes-len);
678 /* The socket has been disconnected! */
688 * Read data from the client socket with default timeout.
689 * (This is implemented in terms of client_read_to() and could be
690 * justifiably moved out of sysdep.c)
692 INLINE int client_read(char *buf, int bytes)
694 return(client_read_to(buf, bytes, config.c_sleeping));
699 * client_getln() ... Get a LF-terminated line of text from the client.
700 * (This is implemented in terms of client_read() and could be
701 * justifiably moved out of sysdep.c)
703 int client_getln(char *buf, int bufsize)
707 /* Read one character at a time.
710 retval = client_read(&buf[i], 1);
711 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
715 /* If we got a long line, discard characters until the newline.
717 if (i == (bufsize-1))
718 while (buf[i] != '\n' && retval == 1)
719 retval = client_read(&buf[i], 1);
721 /* Strip the trailing LF, and the trailing CR if present.
724 while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
725 buf[strlen(buf)-1] = 0;
727 if (retval < 0) safestrncpy(buf, "000", bufsize);
734 * The system-dependent part of master_cleanup() - close the master socket.
736 void sysdep_master_cleanup(void) {
737 struct ServiceFunctionHook *serviceptr;
739 ///// DestroyWorkerList();
741 * close all protocol master sockets
743 for (serviceptr = ServiceHookTable; serviceptr != NULL;
744 serviceptr = serviceptr->next ) {
746 if (serviceptr->tcp_port > 0)
747 lprintf(CTDL_INFO, "Closing listener on port %d\n",
748 serviceptr->tcp_port);
750 if (serviceptr->sockpath != NULL)
751 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
752 serviceptr->sockpath);
754 close(serviceptr->msock);
756 /* If it's a Unix domain socket, remove the file. */
757 if (serviceptr->sockpath != NULL) {
758 unlink(serviceptr->sockpath);
764 serv_calendar_destroy();
765 CtdlDestroyProtoHooks();
766 CtdlDestroyDeleteHooks();
767 CtdlDestroyXmsgHooks();
768 CtdlDestroyNetprocHooks();
769 CtdlDestroyUserHooks();
770 CtdlDestroyMessageHook();
771 CtdlDestroyCleanupHooks();
772 CtdlDestroyFixedOutputHooks();
773 CtdlDestroySessionHooks();
774 CtdlDestroyServiceHook();
775 #ifdef HAVE_BACKTRACE
784 * Terminate another session.
785 * (This could justifiably be moved out of sysdep.c because it
786 * no longer does anything that is system-dependent.)
788 void kill_session(int session_to_kill) {
789 struct CitContext *ptr;
791 begin_critical_section(S_SESSION_TABLE);
792 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
793 if (ptr->cs_pid == session_to_kill) {
797 end_critical_section(S_SESSION_TABLE);
801 void graceful_shutdown(int signum) {
802 kill(current_child, signum);
803 unlink(file_pid_file);
809 * Start running as a daemon.
811 void start_daemon(int unused) {
819 /* Close stdin/stdout/stderr and replace them with /dev/null.
820 * We don't just call close() because we don't want these fd's
821 * to be reused for other files.
830 signal(SIGHUP, SIG_IGN);
831 signal(SIGINT, SIG_IGN);
832 signal(SIGQUIT, SIG_IGN);
836 freopen("/dev/null", "r", stdin);
837 freopen("/dev/null", "w", stdout);
838 freopen("/dev/null", "w", stderr);
841 current_child = fork();
843 signal(SIGTERM, graceful_shutdown);
845 if (current_child < 0) {
850 else if (current_child == 0) {
851 return; /* continue starting citadel. */
855 fp = fopen(file_pid_file, "w");
858 * NB.. The pid file contains the pid of the actual server.
859 * This is not the pid of the watcher process
861 fprintf(fp, ""F_PID_T"\n", current_child);
864 waitpid(current_child, &status, 0);
869 /* Did the main process exit with an actual exit code? */
870 if (WIFEXITED(status)) {
872 /* Exit code 0 means the watcher should exit */
873 if (WEXITSTATUS(status) == 0) {
877 /* Exit code 101-109 means the watcher should exit */
878 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
882 /* Any other exit code means we should restart. */
888 /* Any other type of termination (signals, etc.) should also restart. */
893 } while (do_restart);
895 unlink(file_pid_file);
896 exit(WEXITSTATUS(status));
902 * Generic routine to convert a login name to a full name (gecos)
903 * Returns nonzero if a conversion took place
905 int convert_login(char NameToConvert[]) {
909 pw = getpwnam(NameToConvert);
914 strcpy(NameToConvert, pw->pw_gecos);
915 for (a=0; a<strlen(NameToConvert); ++a) {
916 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
922 struct worker_node *worker_list = NULL;
926 * create a worker thread. this function must always be called from within
927 * an S_WORKER_LIST critical section!
929 void create_worker(void) {
931 struct worker_node *n;
934 n = malloc(sizeof(struct worker_node));
936 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
941 if ((ret = pthread_attr_init(&attr))) {
942 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
947 /* Our per-thread stacks need to be bigger than the default size,
948 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
949 * crashes on 64-bit Linux.
951 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
952 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
955 pthread_attr_destroy(&attr);
959 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
962 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
966 n->next = worker_list;
968 pthread_attr_destroy(&attr);
971 void DestroyWorkerList(void)
973 struct CitContext *ptr; /* general-purpose utility pointer */
974 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
976 begin_critical_section(S_SESSION_TABLE);
979 /* Remove the session from the active list */
983 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
984 end_critical_section(S_SESSION_TABLE);
986 begin_critical_section(S_SESSION_TABLE);
990 end_critical_section(S_SESSION_TABLE);
992 struct worker_node *cur, *p;
1004 * Create the maintenance threads and begin their operation.
1006 void create_maintenance_threads(void) {
1008 pthread_attr_t attr;
1010 if ((ret = pthread_attr_init(&attr))) {
1011 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1016 /* Our per-thread stacks need to be bigger than the default size,
1017 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1018 * crashes on 64-bit Linux.
1020 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1021 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1024 pthread_attr_destroy(&attr);
1028 struct MaintenanceThreadHook *fcn;
1030 lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1032 for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1033 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1034 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1038 lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1039 fcn->MaintenanceThread_tid);
1044 pthread_attr_destroy(&attr);
1050 * Purge all sessions which have the 'kill_me' flag set.
1051 * This function has code to prevent it from running more than once every
1052 * few seconds, because running it after every single unbind would waste a lot
1053 * of CPU time and keep the context list locked too much. To force it to run
1054 * anyway, set "force" to nonzero.
1057 * After that's done, we raise the size of the worker thread pool
1058 * if such an action is appropriate.
1060 void dead_session_purge(int force) {
1061 struct CitContext *ptr; /* general-purpose utility pointer */
1062 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1065 if ( (time(NULL) - last_purge) < 5 ) {
1066 return; /* Too soon, go away */
1071 begin_critical_section(S_SESSION_TABLE);
1072 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1073 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1075 /* Remove the session from the active list */
1077 ptr->prev->next = ptr->next;
1080 ContextList = ptr->next;
1083 ptr->next->prev = ptr->prev;
1088 /* And put it on our to-be-destroyed list */
1094 end_critical_section(S_SESSION_TABLE);
1096 /* Now that we no longer have the session list locked, we can take
1097 * our time and destroy any sessions on the to-be-killed list, which
1098 * is allocated privately on this thread's stack.
1100 while (rem != NULL) {
1101 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1108 /* Raise the size of the worker thread pool if necessary. */
1109 if ( (num_sessions > num_threads)
1110 && (num_threads < config.c_max_workers) ) {
1111 begin_critical_section(S_WORKER_LIST);
1113 end_critical_section(S_WORKER_LIST);
1122 * masterCC is the context we use when not attached to a session. This
1123 * function initializes it.
1125 void InitializeMasterCC(void) {
1126 memset(&masterCC, 0, sizeof(struct CitContext));
1127 masterCC.internal_pgm = 1;
1128 masterCC.cs_pid = 0;
1137 * Bind a thread to a context. (It's inline merely to speed things up.)
1139 INLINE void become_session(struct CitContext *which_con) {
1140 pthread_setspecific(MyConKey, (void *)which_con );
1146 * This loop just keeps going and going and going...
1148 void *worker_thread(void *arg) {
1151 struct CitContext *ptr;
1152 struct CitContext *bind_me = NULL;
1155 struct CitContext *con= NULL; /* Temporary context pointer */
1156 struct ServiceFunctionHook *serviceptr;
1157 int ssock; /* Descriptor for client socket */
1159 int force_purge = 0;
1166 // Register for tracing
1167 #ifdef HAVE_BACKTRACE
1168 eCrash_RegisterThread("WorkerThread", 0);
1170 while (!time_to_die) {
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);
1217 tv.tv_sec = 1; /* wake up every second if no input */
1219 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1222 if (time_to_die) return(NULL);
1224 /* Now figure out who made this select() unblock.
1225 * First, check for an error or exit condition.
1228 if (errno == EBADF) {
1229 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1233 if (errno != EINTR) {
1234 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1236 } else if (!time_to_die)
1240 /* Next, check to see if it's a new client connecting
1241 * on a master socket.
1243 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1244 serviceptr = serviceptr->next ) {
1246 if (FD_ISSET(serviceptr->msock, &readfds)) {
1247 ssock = accept(serviceptr->msock, NULL, 0);
1250 "New client socket %d\n",
1253 /* The master socket is non-blocking but the client
1254 * sockets need to be blocking, otherwise certain
1255 * operations barf on FreeBSD. Not a fatal error.
1257 if (fcntl(ssock, F_SETFL, 0) < 0) {
1259 "citserver: Can't set socket to blocking: %s\n",
1263 /* New context will be created already
1264 * set up in the CON_EXECUTING state.
1266 con = CreateNewContext();
1268 /* Assign our new socket number to it. */
1269 con->client_socket = ssock;
1270 con->h_command_function =
1271 serviceptr->h_command_function;
1272 con->h_async_function =
1273 serviceptr->h_async_function;
1275 serviceptr->ServiceName;
1277 /* Determine whether it's a local socket */
1278 if (serviceptr->sockpath != NULL)
1279 con->is_local_socket = 1;
1281 /* Set the SO_REUSEADDR socket option */
1283 setsockopt(ssock, SOL_SOCKET,
1287 become_session(con);
1289 serviceptr->h_greeting_function();
1290 become_session(NULL);
1291 con->state = CON_IDLE;
1297 /* It must be a client socket. Find a context that has data
1298 * waiting on its socket *and* is in the CON_IDLE state. Any
1299 * active sockets other than our chosen one are marked as
1300 * CON_READY so the next thread that comes around can just bind
1301 * to one without having to select() again.
1303 begin_critical_section(S_SESSION_TABLE);
1304 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1305 if ( (FD_ISSET(ptr->client_socket, &readfds))
1306 && (ptr->state != CON_EXECUTING) ) {
1307 ptr->input_waiting = 1;
1309 bind_me = ptr; /* I choose you! */
1310 bind_me->state = CON_EXECUTING;
1313 ptr->state = CON_READY;
1317 end_critical_section(S_SESSION_TABLE);
1320 /* We're bound to a session */
1321 if (bind_me != NULL) {
1322 become_session(bind_me);
1324 /* If the client has sent a command, execute it. */
1325 if (CC->input_waiting) {
1326 CC->h_command_function();
1327 CC->input_waiting = 0;
1330 /* If there are asynchronous messages waiting and the
1331 * client supports it, do those now */
1332 if ((CC->is_async) && (CC->async_waiting)
1333 && (CC->h_async_function != NULL)) {
1334 CC->h_async_function();
1335 CC->async_waiting = 0;
1338 force_purge = CC->kill_me;
1339 become_session(NULL);
1340 bind_me->state = CON_IDLE;
1343 dead_session_purge(force_purge);
1345 check_sched_shutdown();
1347 if (con != NULL) free (con);//// TODO: could this harm other threads?
1348 /* If control reaches this point, the server is shutting down */
1349 #ifdef HAVE_BACKTRACE
1350 eCrash_UnregisterThread();
1360 * Translate text facility name to syslog.h defined value.
1362 int SyslogFacility(char *name)
1371 { LOG_KERN, "kern" },
1372 { LOG_USER, "user" },
1373 { LOG_MAIL, "mail" },
1374 { LOG_DAEMON, "daemon" },
1375 { LOG_AUTH, "auth" },
1376 { LOG_SYSLOG, "syslog" },
1378 { LOG_NEWS, "news" },
1379 { LOG_UUCP, "uucp" },
1380 { LOG_LOCAL0, "local0" },
1381 { LOG_LOCAL1, "local1" },
1382 { LOG_LOCAL2, "local2" },
1383 { LOG_LOCAL3, "local3" },
1384 { LOG_LOCAL4, "local4" },
1385 { LOG_LOCAL5, "local5" },
1386 { LOG_LOCAL6, "local6" },
1387 { LOG_LOCAL7, "local7" },
1390 for(i = 0; facTbl[i].name != NULL; i++) {
1391 if(!strcasecmp(name, facTbl[i].name))
1392 return facTbl[i].facility;
1399 /********** MEM CHEQQER ***********/
1401 #ifdef DEBUG_MEMORY_LEAKS
1408 void *tracked_malloc(size_t size, char *file, int line) {
1409 struct igheap *thisheap;
1412 block = malloc(size);
1413 if (block == NULL) return(block);
1415 thisheap = malloc(sizeof(struct igheap));
1416 if (thisheap == NULL) {
1421 thisheap->block = block;
1422 strcpy(thisheap->file, file);
1423 thisheap->line = line;
1425 begin_critical_section(S_DEBUGMEMLEAKS);
1426 thisheap->next = igheap;
1428 end_critical_section(S_DEBUGMEMLEAKS);
1434 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1435 struct igheap *thisheap;
1438 block = realloc(ptr, size);
1439 if (block == NULL) return(block);
1441 thisheap = malloc(sizeof(struct igheap));
1442 if (thisheap == NULL) {
1447 thisheap->block = block;
1448 strcpy(thisheap->file, file);
1449 thisheap->line = line;
1451 begin_critical_section(S_DEBUGMEMLEAKS);
1452 thisheap->next = igheap;
1454 end_critical_section(S_DEBUGMEMLEAKS);
1461 void tracked_free(void *ptr) {
1462 struct igheap *thisheap;
1463 struct igheap *trash;
1467 if (igheap == NULL) return;
1468 begin_critical_section(S_DEBUGMEMLEAKS);
1469 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1470 if (thisheap->next != NULL) {
1471 if (thisheap->next->block == ptr) {
1472 trash = thisheap->next;
1473 thisheap->next = thisheap->next->next;
1478 if (igheap->block == ptr) {
1480 igheap = igheap->next;
1483 end_critical_section(S_DEBUGMEMLEAKS);
1486 char *tracked_strdup(const char *s, char *file, int line) {
1489 if (s == NULL) return(NULL);
1490 ptr = tracked_malloc(strlen(s) + 1, file, line);
1491 if (ptr == NULL) return(NULL);
1492 strncpy(ptr, s, strlen(s));
1496 void dump_heap(void) {
1497 struct igheap *thisheap;
1499 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1500 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1501 thisheap->file, thisheap->line);
1505 #endif /* DEBUG_MEMORY_LEAKS */