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);
153 // end_critical_section(S_LOG);
160 * Signal handler to shut down the server.
163 volatile int time_to_die = 0;
164 volatile int shutdown_and_halt = 0;
165 volatile int restart_server = 0;
166 volatile int running_as_daemon = 0;
168 static RETSIGTYPE signal_cleanup(int signum) {
169 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
171 master_cleanup(signum);
177 void InitialiseSemaphores(void)
181 /* Set up a bunch of semaphores to be used for critical sections */
182 for (i=0; i<MAX_SEMAPHORES; ++i) {
183 pthread_mutex_init(&Critters[i], NULL);
190 * Some initialization stuff...
192 void init_sysdep(void) {
195 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
199 getrlimit(RLIMIT_NOFILE, &rl);
200 rl.rlim_cur = FD_SETSIZE;
201 rl.rlim_max = FD_SETSIZE;
202 setrlimit(RLIMIT_NOFILE, &rl);
206 /* If we've got OpenSSL, we're going to use it. */
212 * Set up a place to put thread-specific data.
213 * We only need a single pointer per thread - it points to the
214 * CitContext structure (in the ContextList linked list) of the
215 * session to which the calling thread is currently bound.
217 if (pthread_key_create(&MyConKey, NULL) != 0) {
218 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
223 * The action for unexpected signals and exceptions should be to
224 * call signal_cleanup() to gracefully shut down the server.
227 sigaddset(&set, SIGINT);
228 sigaddset(&set, SIGQUIT);
229 sigaddset(&set, SIGHUP);
230 sigaddset(&set, SIGTERM);
231 // sigaddset(&set, SIGSEGV); commented out because
232 // sigaddset(&set, SIGILL); we want core dumps
233 // sigaddset(&set, SIGBUS);
234 sigprocmask(SIG_UNBLOCK, &set, NULL);
236 signal(SIGINT, signal_cleanup);
237 signal(SIGQUIT, signal_cleanup);
238 signal(SIGHUP, signal_cleanup);
239 signal(SIGTERM, signal_cleanup);
240 // signal(SIGSEGV, signal_cleanup); commented out because
241 // signal(SIGILL, signal_cleanup); we want core dumps
242 // signal(SIGBUS, signal_cleanup);
245 * Do not shut down the server on broken pipe signals, otherwise the
246 * whole Citadel service would come down whenever a single client
249 signal(SIGPIPE, SIG_IGN);
254 * Obtain a semaphore lock to begin a critical section.
256 void begin_critical_section(int which_one)
258 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
260 /* For all types of critical sections except those listed here,
261 * ensure nobody ever tries to do a critical section within a
262 * transaction; this could lead to deadlock.
264 if ( (which_one != S_FLOORCACHE)
265 #ifdef DEBUG_MEMORY_LEAKS
266 && (which_one != S_DEBUGMEMLEAKS)
268 && (which_one != S_RPLIST)
272 pthread_mutex_lock(&Critters[which_one]);
276 * Release a semaphore lock to end a critical section.
278 void end_critical_section(int which_one)
280 pthread_mutex_unlock(&Critters[which_one]);
286 * This is a generic function to set up a master socket for listening on
287 * a TCP port. The server shuts down if the bind fails.
290 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
292 struct sockaddr_in sin;
294 int actual_queue_len;
296 actual_queue_len = queue_len;
297 if (actual_queue_len < 5) actual_queue_len = 5;
299 memset(&sin, 0, sizeof(sin));
300 sin.sin_family = AF_INET;
301 sin.sin_port = htons((u_short)port_number);
302 if (ip_addr == NULL) {
303 sin.sin_addr.s_addr = INADDR_ANY;
306 sin.sin_addr.s_addr = inet_addr(ip_addr);
309 if (sin.sin_addr.s_addr == !INADDR_ANY) {
310 sin.sin_addr.s_addr = INADDR_ANY;
313 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
316 *errormessage = (char*) malloc(SIZ + 1);
317 snprintf(*errormessage, SIZ,
318 "citserver: Can't create a socket: %s",
320 lprintf(CTDL_EMERG, "%s\n", *errormessage);
325 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
327 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
328 *errormessage = (char*) malloc(SIZ + 1);
329 snprintf(*errormessage, SIZ,
330 "citserver: Can't bind: %s",
332 lprintf(CTDL_EMERG, "%s\n", *errormessage);
337 /* set to nonblock - we need this for some obscure situations */
338 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
339 *errormessage = (char*) malloc(SIZ + 1);
340 snprintf(*errormessage, SIZ,
341 "citserver: Can't set socket to non-blocking: %s",
343 lprintf(CTDL_EMERG, "%s\n", *errormessage);
348 if (listen(s, actual_queue_len) < 0) {
349 *errormessage = (char*) malloc(SIZ + 1);
350 snprintf(*errormessage, SIZ,
351 "citserver: Can't listen: %s",
353 lprintf(CTDL_EMERG, "%s\n", *errormessage);
364 * Create a Unix domain socket and listen on it
366 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
368 struct sockaddr_un addr;
371 int actual_queue_len;
373 actual_queue_len = queue_len;
374 if (actual_queue_len < 5) actual_queue_len = 5;
376 i = unlink(sockpath);
377 if (i != 0) if (errno != ENOENT) {
378 *errormessage = (char*) malloc(SIZ + 1);
379 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
380 sockpath, strerror(errno));
381 lprintf(CTDL_EMERG, "%s\n", *errormessage);
385 memset(&addr, 0, sizeof(addr));
386 addr.sun_family = AF_UNIX;
387 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
389 s = socket(AF_UNIX, SOCK_STREAM, 0);
391 *errormessage = (char*) malloc(SIZ + 1);
392 snprintf(*errormessage, SIZ,
393 "citserver: Can't create a socket: %s",
395 lprintf(CTDL_EMERG, "%s\n", *errormessage);
399 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
400 *errormessage = (char*) malloc(SIZ + 1);
401 snprintf(*errormessage, SIZ,
402 "citserver: Can't bind: %s",
404 lprintf(CTDL_EMERG, "%s\n", *errormessage);
408 /* set to nonblock - we need this for some obscure situations */
409 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
410 *errormessage = (char*) malloc(SIZ + 1);
411 snprintf(*errormessage, SIZ,
412 "citserver: Can't set socket to non-blocking: %s",
414 lprintf(CTDL_EMERG, "%s\n", *errormessage);
419 if (listen(s, actual_queue_len) < 0) {
420 *errormessage = (char*) malloc(SIZ + 1);
421 snprintf(*errormessage, SIZ,
422 "citserver: Can't listen: %s",
424 lprintf(CTDL_EMERG, "%s\n", *errormessage);
428 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
435 * Return a pointer to the CitContext structure bound to the thread which
436 * called this function. If there's no such binding (for example, if it's
437 * called by the housekeeper thread) then a generic 'master' CC is returned.
439 * This function is used *VERY* frequently and must be kept small.
441 struct CitContext *MyContext(void) {
443 register struct CitContext *c;
445 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
446 c == NULL) ? &masterCC : c
452 * Initialize a new context and place it in the list. The session number
453 * used to be the PID (which is why it's called cs_pid), but that was when we
454 * had one process per session. Now we just assign them sequentially, starting
455 * at 1 (don't change it to 0 because masterCC uses 0).
457 struct CitContext *CreateNewContext(void) {
458 struct CitContext *me;
459 static int next_pid = 0;
461 me = (struct CitContext *) malloc(sizeof(struct CitContext));
463 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
466 memset(me, 0, sizeof(struct CitContext));
468 /* The new context will be created already in the CON_EXECUTING state
469 * in order to prevent another thread from grabbing it while it's
472 me->state = CON_EXECUTING;
475 * Generate a unique session number and insert this context into
478 begin_critical_section(S_SESSION_TABLE);
479 me->cs_pid = ++next_pid;
481 me->next = ContextList;
483 if (me->next != NULL) {
487 end_critical_section(S_SESSION_TABLE);
493 * The following functions implement output buffering. If the kernel supplies
494 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
495 * user-space buffering.
499 # define HAVE_TCP_BUFFERING
502 # define HAVE_TCP_BUFFERING
503 # define TCP_CORK TCP_NOPUSH
505 #endif /* TCP_CORK */
506 #endif /* HAVE_DARWIN */
508 #ifdef HAVE_TCP_BUFFERING
509 static unsigned on = 1, off = 0;
510 void buffer_output(void) {
511 struct CitContext *ctx = MyContext();
512 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
516 void unbuffer_output(void) {
517 struct CitContext *ctx = MyContext();
518 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
522 void flush_output(void) {
523 struct CitContext *ctx = MyContext();
524 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
525 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
529 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
530 void buffer_output(void) {
533 void unbuffer_output(void) {
536 void flush_output(void) {
539 void buffer_output(void) {
540 if (CC->buffering == 0) {
543 CC->output_buffer = malloc(SIZ);
547 void flush_output(void) {
548 if (CC->buffering == 1) {
549 client_write(CC->output_buffer, CC->buffer_len);
554 void unbuffer_output(void) {
555 if (CC->buffering == 1) {
557 /* We don't call flush_output because we can't. */
558 client_write(CC->output_buffer, CC->buffer_len);
560 free(CC->output_buffer);
561 CC->output_buffer = NULL;
564 #endif /* HAVE_DARWIN */
565 #endif /* HAVE_TCP_BUFFERING */
570 * client_write() ... Send binary data to the client.
572 void client_write(char *buf, int nbytes)
574 int bytes_written = 0;
576 #ifndef HAVE_TCP_BUFFERING
577 int old_buffer_len = 0;
580 if (CC->redirect_buffer != NULL) {
581 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
582 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
583 CC->redirect_buffer = realloc(CC->redirect_buffer,
586 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
587 CC->redirect_len += nbytes;
588 CC->redirect_buffer[CC->redirect_len] = 0;
592 #ifndef HAVE_TCP_BUFFERING
593 /* If we're buffering for later, do that now. */
595 old_buffer_len = CC->buffer_len;
596 CC->buffer_len += nbytes;
597 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
598 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
603 /* Ok, at this point we're not buffering. Go ahead and write. */
606 if (CC->redirect_ssl) {
607 client_write_ssl(buf, nbytes);
612 while (bytes_written < nbytes) {
613 retval = write(CC->client_socket, &buf[bytes_written],
614 nbytes - bytes_written);
617 "client_write(%d bytes) failed: %s (%d)\n",
618 nbytes - bytes_written,
619 strerror(errno), errno);
624 bytes_written = bytes_written + retval;
630 * cprintf() ... Send formatted printable data to the client. It is
631 * implemented in terms of client_write() but remains in
632 * sysdep.c in case we port to somewhere without va_args...
634 void cprintf(const char *format, ...) {
638 va_start(arg_ptr, format);
639 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
640 buf[sizeof buf - 2] = '\n';
641 client_write(buf, strlen(buf));
647 * Read data from the client socket.
649 * 1 Requested number of bytes has been read.
650 * 0 Request timed out.
651 * -1 The socket is broken.
652 * If the socket breaks, the session will be terminated.
654 int client_read_to(char *buf, int bytes, int timeout)
662 if (CC->redirect_ssl) {
663 return (client_read_ssl(buf, bytes, timeout));
669 FD_SET(CC->client_socket, &rfds);
673 retval = select( (CC->client_socket)+1,
674 &rfds, NULL, NULL, &tv);
676 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
680 rlen = read(CC->client_socket, &buf[len], bytes-len);
682 /* The socket has been disconnected! */
692 * Read data from the client socket with default timeout.
693 * (This is implemented in terms of client_read_to() and could be
694 * justifiably moved out of sysdep.c)
696 INLINE int client_read(char *buf, int bytes)
698 return(client_read_to(buf, bytes, config.c_sleeping));
703 * client_getln() ... Get a LF-terminated line of text from the client.
704 * (This is implemented in terms of client_read() and could be
705 * justifiably moved out of sysdep.c)
707 int client_getln(char *buf, int bufsize)
711 /* Read one character at a time.
714 retval = client_read(&buf[i], 1);
715 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
719 /* If we got a long line, discard characters until the newline.
721 if (i == (bufsize-1))
722 while (buf[i] != '\n' && retval == 1)
723 retval = client_read(&buf[i], 1);
725 /* Strip the trailing LF, and the trailing CR if present.
728 while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
729 buf[strlen(buf)-1] = 0;
731 if (retval < 0) safestrncpy(buf, "000", bufsize);
738 * The system-dependent part of master_cleanup() - close the master socket.
740 void sysdep_master_cleanup(void) {
741 struct ServiceFunctionHook *serviceptr;
743 ///// DestroyWorkerList();
745 * close all protocol master sockets
747 for (serviceptr = ServiceHookTable; serviceptr != NULL;
748 serviceptr = serviceptr->next ) {
750 if (serviceptr->tcp_port > 0)
751 lprintf(CTDL_INFO, "Closing listener on port %d\n",
752 serviceptr->tcp_port);
754 if (serviceptr->sockpath != NULL)
755 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
756 serviceptr->sockpath);
758 close(serviceptr->msock);
760 /* If it's a Unix domain socket, remove the file. */
761 if (serviceptr->sockpath != NULL) {
762 unlink(serviceptr->sockpath);
768 serv_calendar_destroy();
769 CtdlDestroyProtoHooks();
770 CtdlDestroyDeleteHooks();
771 CtdlDestroyXmsgHooks();
772 CtdlDestroyNetprocHooks();
773 CtdlDestroyUserHooks();
774 CtdlDestroyMessageHook();
775 CtdlDestroyCleanupHooks();
776 CtdlDestroyFixedOutputHooks();
777 CtdlDestroySessionHooks();
778 CtdlDestroyServiceHook();
785 * Terminate another session.
786 * (This could justifiably be moved out of sysdep.c because it
787 * no longer does anything that is system-dependent.)
789 void kill_session(int session_to_kill) {
790 struct CitContext *ptr;
792 begin_critical_section(S_SESSION_TABLE);
793 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
794 if (ptr->cs_pid == session_to_kill) {
798 end_critical_section(S_SESSION_TABLE);
802 void graceful_shutdown(int signum) {
803 kill(current_child, signum);
804 unlink(file_pid_file);
810 * Start running as a daemon.
812 void start_daemon(int unused) {
820 /* Close stdin/stdout/stderr and replace them with /dev/null.
821 * We don't just call close() because we don't want these fd's
822 * to be reused for other files.
831 signal(SIGHUP, SIG_IGN);
832 signal(SIGINT, SIG_IGN);
833 signal(SIGQUIT, SIG_IGN);
837 freopen("/dev/null", "r", stdin);
838 freopen("/dev/null", "w", stdout);
839 freopen("/dev/null", "w", stderr);
842 current_child = fork();
844 signal(SIGTERM, graceful_shutdown);
846 if (current_child < 0) {
851 else if (current_child == 0) {
852 return; /* continue starting citadel. */
856 fp = fopen(file_pid_file, "w");
858 fprintf(fp, ""F_PID_T"\n", child);
861 waitpid(current_child, &status, 0);
866 /* Did the main process exit with an actual exit code? */
867 if (WIFEXITED(status)) {
869 /* Exit code 0 means the watcher should exit */
870 if (WEXITSTATUS(status) == 0) {
874 /* Exit code 101-109 means the watcher should exit */
875 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
879 /* Any other exit code means we should restart. */
885 /* Any other type of termination (signals, etc.) should also restart. */
890 } while (do_restart);
892 unlink(file_pid_file);
893 exit(WEXITSTATUS(status));
899 * Generic routine to convert a login name to a full name (gecos)
900 * Returns nonzero if a conversion took place
902 int convert_login(char NameToConvert[]) {
906 pw = getpwnam(NameToConvert);
911 strcpy(NameToConvert, pw->pw_gecos);
912 for (a=0; a<strlen(NameToConvert); ++a) {
913 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
919 struct worker_node *worker_list = NULL;
923 * create a worker thread. this function must always be called from within
924 * an S_WORKER_LIST critical section!
926 void create_worker(void) {
928 struct worker_node *n;
931 n = malloc(sizeof(struct worker_node));
933 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
938 if ((ret = pthread_attr_init(&attr))) {
939 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
944 /* Our per-thread stacks need to be bigger than the default size,
945 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
946 * crashes on 64-bit Linux.
948 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
949 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
952 pthread_attr_destroy(&attr);
956 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
959 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
963 n->next = worker_list;
965 pthread_attr_destroy(&attr);
968 void DestroyWorkerList(void)
970 struct CitContext *ptr; /* general-purpose utility pointer */
971 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
973 begin_critical_section(S_SESSION_TABLE);
976 /* Remove the session from the active list */
980 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
981 end_critical_section(S_SESSION_TABLE);
983 begin_critical_section(S_SESSION_TABLE);
987 end_critical_section(S_SESSION_TABLE);
989 struct worker_node *cur, *p;
1001 * Create the maintenance threads and begin their operation.
1003 void create_maintenance_threads(void) {
1005 pthread_attr_t attr;
1007 if ((ret = pthread_attr_init(&attr))) {
1008 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
1013 /* Our per-thread stacks need to be bigger than the default size,
1014 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1015 * crashes on 64-bit Linux.
1017 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1018 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1021 pthread_attr_destroy(&attr);
1025 struct MaintenanceThreadHook *fcn;
1027 lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1029 for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1030 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1031 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1035 lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1036 fcn->MaintenanceThread_tid);
1041 pthread_attr_destroy(&attr);
1047 * Purge all sessions which have the 'kill_me' flag set.
1048 * This function has code to prevent it from running more than once every
1049 * few seconds, because running it after every single unbind would waste a lot
1050 * of CPU time and keep the context list locked too much. To force it to run
1051 * anyway, set "force" to nonzero.
1054 * After that's done, we raise the size of the worker thread pool
1055 * if such an action is appropriate.
1057 void dead_session_purge(int force) {
1058 struct CitContext *ptr; /* general-purpose utility pointer */
1059 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1062 if ( (time(NULL) - last_purge) < 5 ) {
1063 return; /* Too soon, go away */
1068 begin_critical_section(S_SESSION_TABLE);
1069 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1070 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1072 /* Remove the session from the active list */
1074 ptr->prev->next = ptr->next;
1077 ContextList = ptr->next;
1080 ptr->next->prev = ptr->prev;
1085 /* And put it on our to-be-destroyed list */
1091 end_critical_section(S_SESSION_TABLE);
1093 /* Now that we no longer have the session list locked, we can take
1094 * our time and destroy any sessions on the to-be-killed list, which
1095 * is allocated privately on this thread's stack.
1097 while (rem != NULL) {
1098 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1105 /* Raise the size of the worker thread pool if necessary. */
1106 if ( (num_sessions > num_threads)
1107 && (num_threads < config.c_max_workers) ) {
1108 begin_critical_section(S_WORKER_LIST);
1110 end_critical_section(S_WORKER_LIST);
1119 * masterCC is the context we use when not attached to a session. This
1120 * function initializes it.
1122 void InitializeMasterCC(void) {
1123 memset(&masterCC, 0, sizeof(struct CitContext));
1124 masterCC.internal_pgm = 1;
1125 masterCC.cs_pid = 0;
1134 * Bind a thread to a context. (It's inline merely to speed things up.)
1136 INLINE void become_session(struct CitContext *which_con) {
1137 pthread_setspecific(MyConKey, (void *)which_con );
1143 * This loop just keeps going and going and going...
1145 void *worker_thread(void *arg) {
1148 struct CitContext *ptr;
1149 struct CitContext *bind_me = NULL;
1152 struct CitContext *con= NULL; /* Temporary context pointer */
1153 struct ServiceFunctionHook *serviceptr;
1154 int ssock; /* Descriptor for client socket */
1156 int force_purge = 0;
1163 while (!time_to_die) {
1165 /* make doubly sure we're not holding any stale db handles
1166 * which might cause a deadlock.
1168 cdb_check_handles();
1169 do_select: force_purge = 0;
1170 bind_me = NULL; /* Which session shall we handle? */
1172 /* Initialize the fdset. */
1176 begin_critical_section(S_SESSION_TABLE);
1177 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1178 if (ptr->state == CON_IDLE) {
1179 FD_SET(ptr->client_socket, &readfds);
1180 if (ptr->client_socket > highest)
1181 highest = ptr->client_socket;
1183 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1185 ptr->state = CON_EXECUTING;
1188 end_critical_section(S_SESSION_TABLE);
1194 /* If we got this far, it means that there are no sessions
1195 * which a previous thread marked for attention, so we go
1196 * ahead and get ready to select().
1199 /* First, add the various master sockets to the fdset. */
1200 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1201 serviceptr = serviceptr->next ) {
1202 m = serviceptr->msock;
1203 FD_SET(m, &readfds);
1210 tv.tv_sec = 1; /* wake up every second if no input */
1212 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1215 if (time_to_die) return(NULL);
1217 /* Now figure out who made this select() unblock.
1218 * First, check for an error or exit condition.
1221 if (errno == EBADF) {
1222 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1226 if (errno != EINTR) {
1227 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1229 } else if (!time_to_die)
1233 /* Next, check to see if it's a new client connecting
1234 * on a master socket.
1236 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1237 serviceptr = serviceptr->next ) {
1239 if (FD_ISSET(serviceptr->msock, &readfds)) {
1240 ssock = accept(serviceptr->msock, NULL, 0);
1243 "New client socket %d\n",
1246 /* The master socket is non-blocking but the client
1247 * sockets need to be blocking, otherwise certain
1248 * operations barf on FreeBSD. Not a fatal error.
1250 if (fcntl(ssock, F_SETFL, 0) < 0) {
1252 "citserver: Can't set socket to blocking: %s\n",
1256 /* New context will be created already
1257 * set up in the CON_EXECUTING state.
1259 con = CreateNewContext();
1261 /* Assign our new socket number to it. */
1262 con->client_socket = ssock;
1263 con->h_command_function =
1264 serviceptr->h_command_function;
1265 con->h_async_function =
1266 serviceptr->h_async_function;
1268 /* Determine whether it's a local socket */
1269 if (serviceptr->sockpath != NULL)
1270 con->is_local_socket = 1;
1272 /* Set the SO_REUSEADDR socket option */
1274 setsockopt(ssock, SOL_SOCKET,
1278 become_session(con);
1280 serviceptr->h_greeting_function();
1281 become_session(NULL);
1282 con->state = CON_IDLE;
1288 /* It must be a client socket. Find a context that has data
1289 * waiting on its socket *and* is in the CON_IDLE state. Any
1290 * active sockets other than our chosen one are marked as
1291 * CON_READY so the next thread that comes around can just bind
1292 * to one without having to select() again.
1294 begin_critical_section(S_SESSION_TABLE);
1295 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1296 if ( (FD_ISSET(ptr->client_socket, &readfds))
1297 && (ptr->state != CON_EXECUTING) ) {
1298 ptr->input_waiting = 1;
1300 bind_me = ptr; /* I choose you! */
1301 bind_me->state = CON_EXECUTING;
1304 ptr->state = CON_READY;
1308 end_critical_section(S_SESSION_TABLE);
1311 /* We're bound to a session */
1312 if (bind_me != NULL) {
1313 become_session(bind_me);
1315 /* If the client has sent a command, execute it. */
1316 if (CC->input_waiting) {
1317 CC->h_command_function();
1318 CC->input_waiting = 0;
1321 /* If there are asynchronous messages waiting and the
1322 * client supports it, do those now */
1323 if ((CC->is_async) && (CC->async_waiting)
1324 && (CC->h_async_function != NULL)) {
1325 CC->h_async_function();
1326 CC->async_waiting = 0;
1329 force_purge = CC->kill_me;
1330 become_session(NULL);
1331 bind_me->state = CON_IDLE;
1334 dead_session_purge(force_purge);
1336 check_sched_shutdown();
1338 if (con != NULL) free (con);//// TODO: could this harm other threads?
1339 /* If control reaches this point, the server is shutting down */
1348 * Translate text facility name to syslog.h defined value.
1350 int SyslogFacility(char *name)
1359 { LOG_KERN, "kern" },
1360 { LOG_USER, "user" },
1361 { LOG_MAIL, "mail" },
1362 { LOG_DAEMON, "daemon" },
1363 { LOG_AUTH, "auth" },
1364 { LOG_SYSLOG, "syslog" },
1366 { LOG_NEWS, "news" },
1367 { LOG_UUCP, "uucp" },
1368 { LOG_LOCAL0, "local0" },
1369 { LOG_LOCAL1, "local1" },
1370 { LOG_LOCAL2, "local2" },
1371 { LOG_LOCAL3, "local3" },
1372 { LOG_LOCAL4, "local4" },
1373 { LOG_LOCAL5, "local5" },
1374 { LOG_LOCAL6, "local6" },
1375 { LOG_LOCAL7, "local7" },
1378 for(i = 0; facTbl[i].name != NULL; i++) {
1379 if(!strcasecmp(name, facTbl[i].name))
1380 return facTbl[i].facility;
1387 /********** MEM CHEQQER ***********/
1389 #ifdef DEBUG_MEMORY_LEAKS
1396 void *tracked_malloc(size_t size, char *file, int line) {
1397 struct igheap *thisheap;
1400 block = malloc(size);
1401 if (block == NULL) return(block);
1403 thisheap = malloc(sizeof(struct igheap));
1404 if (thisheap == NULL) {
1409 thisheap->block = block;
1410 strcpy(thisheap->file, file);
1411 thisheap->line = line;
1413 begin_critical_section(S_DEBUGMEMLEAKS);
1414 thisheap->next = igheap;
1416 end_critical_section(S_DEBUGMEMLEAKS);
1422 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1423 struct igheap *thisheap;
1426 block = realloc(ptr, size);
1427 if (block == NULL) return(block);
1429 thisheap = malloc(sizeof(struct igheap));
1430 if (thisheap == NULL) {
1435 thisheap->block = block;
1436 strcpy(thisheap->file, file);
1437 thisheap->line = line;
1439 begin_critical_section(S_DEBUGMEMLEAKS);
1440 thisheap->next = igheap;
1442 end_critical_section(S_DEBUGMEMLEAKS);
1449 void tracked_free(void *ptr) {
1450 struct igheap *thisheap;
1451 struct igheap *trash;
1455 if (igheap == NULL) return;
1456 begin_critical_section(S_DEBUGMEMLEAKS);
1457 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1458 if (thisheap->next != NULL) {
1459 if (thisheap->next->block == ptr) {
1460 trash = thisheap->next;
1461 thisheap->next = thisheap->next->next;
1466 if (igheap->block == ptr) {
1468 igheap = igheap->next;
1471 end_critical_section(S_DEBUGMEMLEAKS);
1474 char *tracked_strdup(const char *s, char *file, int line) {
1477 if (s == NULL) return(NULL);
1478 ptr = tracked_malloc(strlen(s) + 1, file, line);
1479 if (ptr == NULL) return(NULL);
1480 strncpy(ptr, s, strlen(s));
1484 void dump_heap(void) {
1485 struct igheap *thisheap;
1487 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1488 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1489 thisheap->file, thisheap->line);
1493 #endif /* DEBUG_MEMORY_LEAKS */