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, ...) {
109 va_start(arg_ptr, format);
110 vsyslog((syslog_facility | loglevel), format, arg_ptr);
114 /* stderr output code */
115 if (enable_syslog || running_as_daemon) return;
117 /* if we run in forground and syslog is disabled, log to terminal */
118 if (loglevel <= verbosity) {
123 gettimeofday(&tv, NULL);
124 /* Promote to time_t; types differ on some OSes (like darwin) */
125 unixtime = tv.tv_sec;
126 localtime_r(&unixtime, &tim);
127 if (CC->cs_pid != 0) {
129 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
130 tim.tm_year + 1900, tim.tm_mon + 1,
131 tim.tm_mday, tim.tm_hour, tim.tm_min,
132 tim.tm_sec, (long)tv.tv_usec,
136 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
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);
141 va_start(arg_ptr, format);
142 vfprintf(stderr, format, arg_ptr);
151 * Signal handler to shut down the server.
154 volatile int time_to_die = 0;
155 volatile int shutdown_and_halt = 0;
156 volatile int restart_server = 0;
157 volatile int running_as_daemon = 0;
159 static RETSIGTYPE signal_cleanup(int signum) {
160 lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
162 master_cleanup(signum);
166 * Some initialization stuff...
168 void init_sysdep(void) {
172 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
176 getrlimit(RLIMIT_NOFILE, &rl);
177 rl.rlim_cur = FD_SETSIZE;
178 rl.rlim_max = FD_SETSIZE;
179 setrlimit(RLIMIT_NOFILE, &rl);
183 /* If we've got OpenSSL, we're going to use it. */
188 /* Set up a bunch of semaphores to be used for critical sections */
189 for (i=0; i<MAX_SEMAPHORES; ++i) {
190 pthread_mutex_init(&Critters[i], NULL);
194 * Set up a place to put thread-specific data.
195 * We only need a single pointer per thread - it points to the
196 * CitContext structure (in the ContextList linked list) of the
197 * session to which the calling thread is currently bound.
199 if (pthread_key_create(&MyConKey, NULL) != 0) {
200 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
205 * The action for unexpected signals and exceptions should be to
206 * call signal_cleanup() to gracefully shut down the server.
209 sigaddset(&set, SIGINT);
210 sigaddset(&set, SIGQUIT);
211 sigaddset(&set, SIGHUP);
212 sigaddset(&set, SIGTERM);
213 // sigaddset(&set, SIGSEGV); commented out because
214 // sigaddset(&set, SIGILL); we want core dumps
215 // sigaddset(&set, SIGBUS);
216 sigprocmask(SIG_UNBLOCK, &set, NULL);
218 signal(SIGINT, signal_cleanup);
219 signal(SIGQUIT, signal_cleanup);
220 signal(SIGHUP, signal_cleanup);
221 signal(SIGTERM, signal_cleanup);
222 // signal(SIGSEGV, signal_cleanup); commented out because
223 // signal(SIGILL, signal_cleanup); we want core dumps
224 // signal(SIGBUS, signal_cleanup);
227 * Do not shut down the server on broken pipe signals, otherwise the
228 * whole Citadel service would come down whenever a single client
231 signal(SIGPIPE, SIG_IGN);
236 * Obtain a semaphore lock to begin a critical section.
238 void begin_critical_section(int which_one)
240 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
242 /* For all types of critical sections except those listed here,
243 * ensure nobody ever tries to do a critical section within a
244 * transaction; this could lead to deadlock.
246 if ( (which_one != S_FLOORCACHE)
247 #ifdef DEBUG_MEMORY_LEAKS
248 && (which_one != S_DEBUGMEMLEAKS)
250 && (which_one != S_RPLIST)
254 pthread_mutex_lock(&Critters[which_one]);
258 * Release a semaphore lock to end a critical section.
260 void end_critical_section(int which_one)
262 pthread_mutex_unlock(&Critters[which_one]);
268 * This is a generic function to set up a master socket for listening on
269 * a TCP port. The server shuts down if the bind fails.
272 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
274 struct sockaddr_in sin;
276 int actual_queue_len;
278 actual_queue_len = queue_len;
279 if (actual_queue_len < 5) actual_queue_len = 5;
281 memset(&sin, 0, sizeof(sin));
282 sin.sin_family = AF_INET;
283 sin.sin_port = htons((u_short)port_number);
284 if (ip_addr == NULL) {
285 sin.sin_addr.s_addr = INADDR_ANY;
288 sin.sin_addr.s_addr = inet_addr(ip_addr);
291 if (sin.sin_addr.s_addr == !INADDR_ANY) {
292 sin.sin_addr.s_addr = INADDR_ANY;
295 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
298 *errormessage = (char*) malloc(SIZ + 1);
299 snprintf(*errormessage, SIZ,
300 "citserver: Can't create a socket: %s",
302 lprintf(CTDL_EMERG, "%s\n", *errormessage);
307 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
309 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
310 *errormessage = (char*) malloc(SIZ + 1);
311 snprintf(*errormessage, SIZ,
312 "citserver: Can't bind: %s",
314 lprintf(CTDL_EMERG, "%s\n", *errormessage);
319 /* set to nonblock - we need this for some obscure situations */
320 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
321 *errormessage = (char*) malloc(SIZ + 1);
322 snprintf(*errormessage, SIZ,
323 "citserver: Can't set socket to non-blocking: %s",
325 lprintf(CTDL_EMERG, "%s\n", *errormessage);
330 if (listen(s, actual_queue_len) < 0) {
331 *errormessage = (char*) malloc(SIZ + 1);
332 snprintf(*errormessage, SIZ,
333 "citserver: Can't listen: %s",
335 lprintf(CTDL_EMERG, "%s\n", *errormessage);
346 * Create a Unix domain socket and listen on it
348 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
350 struct sockaddr_un addr;
353 int actual_queue_len;
355 actual_queue_len = queue_len;
356 if (actual_queue_len < 5) actual_queue_len = 5;
358 i = unlink(sockpath);
359 if (i != 0) if (errno != ENOENT) {
360 *errormessage = (char*) malloc(SIZ + 1);
361 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
362 sockpath, strerror(errno));
363 lprintf(CTDL_EMERG, "%s\n", *errormessage);
367 memset(&addr, 0, sizeof(addr));
368 addr.sun_family = AF_UNIX;
369 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
371 s = socket(AF_UNIX, SOCK_STREAM, 0);
373 *errormessage = (char*) malloc(SIZ + 1);
374 snprintf(*errormessage, SIZ,
375 "citserver: Can't create a socket: %s",
377 lprintf(CTDL_EMERG, "%s\n", *errormessage);
381 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
382 *errormessage = (char*) malloc(SIZ + 1);
383 snprintf(*errormessage, SIZ,
384 "citserver: Can't bind: %s",
386 lprintf(CTDL_EMERG, "%s\n", *errormessage);
390 /* set to nonblock - we need this for some obscure situations */
391 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
392 *errormessage = (char*) malloc(SIZ + 1);
393 snprintf(*errormessage, SIZ,
394 "citserver: Can't set socket to non-blocking: %s",
396 lprintf(CTDL_EMERG, "%s\n", *errormessage);
401 if (listen(s, actual_queue_len) < 0) {
402 *errormessage = (char*) malloc(SIZ + 1);
403 snprintf(*errormessage, SIZ,
404 "citserver: Can't listen: %s",
406 lprintf(CTDL_EMERG, "%s\n", *errormessage);
410 chmod(sockpath, 0777);
417 * Return a pointer to the CitContext structure bound to the thread which
418 * called this function. If there's no such binding (for example, if it's
419 * called by the housekeeper thread) then a generic 'master' CC is returned.
421 * This function is used *VERY* frequently and must be kept small.
423 struct CitContext *MyContext(void) {
425 register struct CitContext *c;
427 return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
428 c == NULL) ? &masterCC : c
434 * Initialize a new context and place it in the list. The session number
435 * used to be the PID (which is why it's called cs_pid), but that was when we
436 * had one process per session. Now we just assign them sequentially, starting
437 * at 1 (don't change it to 0 because masterCC uses 0).
439 struct CitContext *CreateNewContext(void) {
440 struct CitContext *me;
441 static int next_pid = 0;
443 me = (struct CitContext *) malloc(sizeof(struct CitContext));
445 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
448 memset(me, 0, sizeof(struct CitContext));
450 /* The new context will be created already in the CON_EXECUTING state
451 * in order to prevent another thread from grabbing it while it's
454 me->state = CON_EXECUTING;
457 * Generate a unique session number and insert this context into
460 begin_critical_section(S_SESSION_TABLE);
461 me->cs_pid = ++next_pid;
463 me->next = ContextList;
465 if (me->next != NULL) {
469 end_critical_section(S_SESSION_TABLE);
475 * The following functions implement output buffering. If the kernel supplies
476 * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
477 * user-space buffering.
481 # define HAVE_TCP_BUFFERING
484 # define HAVE_TCP_BUFFERING
485 # define TCP_CORK TCP_NOPUSH
487 #endif /* TCP_CORK */
488 #endif /* HAVE_DARWIN */
490 #ifdef HAVE_TCP_BUFFERING
491 static unsigned on = 1, off = 0;
492 void buffer_output(void) {
493 struct CitContext *ctx = MyContext();
494 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
498 void unbuffer_output(void) {
499 struct CitContext *ctx = MyContext();
500 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
504 void flush_output(void) {
505 struct CitContext *ctx = MyContext();
506 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
507 setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
510 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
511 void buffer_output(void) {
514 void unbuffer_output(void) {
517 void flush_output(void) {
520 void buffer_output(void) {
521 if (CC->buffering == 0) {
524 CC->output_buffer = malloc(SIZ);
528 void flush_output(void) {
529 if (CC->buffering == 1) {
530 client_write(CC->output_buffer, CC->buffer_len);
535 void unbuffer_output(void) {
536 if (CC->buffering == 1) {
538 /* We don't call flush_output because we can't. */
539 client_write(CC->output_buffer, CC->buffer_len);
541 free(CC->output_buffer);
542 CC->output_buffer = NULL;
550 * client_write() ... Send binary data to the client.
552 void client_write(char *buf, int nbytes)
554 int bytes_written = 0;
556 #ifndef HAVE_TCP_BUFFERING
557 int old_buffer_len = 0;
560 if (CC->redirect_buffer != NULL) {
561 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
562 CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
563 CC->redirect_buffer = realloc(CC->redirect_buffer,
566 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
567 CC->redirect_len += nbytes;
568 CC->redirect_buffer[CC->redirect_len] = 0;
572 #ifndef HAVE_TCP_BUFFERING
573 /* If we're buffering for later, do that now. */
575 old_buffer_len = CC->buffer_len;
576 CC->buffer_len += nbytes;
577 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
578 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
583 /* Ok, at this point we're not buffering. Go ahead and write. */
586 if (CC->redirect_ssl) {
587 client_write_ssl(buf, nbytes);
592 while (bytes_written < nbytes) {
593 retval = write(CC->client_socket, &buf[bytes_written],
594 nbytes - bytes_written);
597 "client_write(%d bytes) failed: %s (%d)\n",
598 nbytes - bytes_written,
599 strerror(errno), errno);
603 bytes_written = bytes_written + retval;
609 * cprintf() ... Send formatted printable data to the client. It is
610 * implemented in terms of client_write() but remains in
611 * sysdep.c in case we port to somewhere without va_args...
613 void cprintf(const char *format, ...) {
617 va_start(arg_ptr, format);
618 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
619 buf[sizeof buf - 2] = '\n';
620 client_write(buf, strlen(buf));
626 * Read data from the client socket.
628 * 1 Requested number of bytes has been read.
629 * 0 Request timed out.
630 * -1 The socket is broken.
631 * If the socket breaks, the session will be terminated.
633 int client_read_to(char *buf, int bytes, int timeout)
641 if (CC->redirect_ssl) {
642 return (client_read_ssl(buf, bytes, timeout));
648 FD_SET(CC->client_socket, &rfds);
652 retval = select( (CC->client_socket)+1,
653 &rfds, NULL, NULL, &tv);
655 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
659 rlen = read(CC->client_socket, &buf[len], bytes-len);
661 /* The socket has been disconnected! */
671 * Read data from the client socket with default timeout.
672 * (This is implemented in terms of client_read_to() and could be
673 * justifiably moved out of sysdep.c)
675 INLINE int client_read(char *buf, int bytes)
677 return(client_read_to(buf, bytes, config.c_sleeping));
682 * client_getln() ... Get a LF-terminated line of text from the client.
683 * (This is implemented in terms of client_read() and could be
684 * justifiably moved out of sysdep.c)
686 int client_getln(char *buf, int bufsize)
690 /* Read one character at a time.
693 retval = client_read(&buf[i], 1);
694 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
698 /* If we got a long line, discard characters until the newline.
700 if (i == (bufsize-1))
701 while (buf[i] != '\n' && retval == 1)
702 retval = client_read(&buf[i], 1);
704 /* Strip the trailing LF, and the trailing CR if present.
707 while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
708 buf[strlen(buf)-1] = 0;
710 if (retval < 0) safestrncpy(buf, "000", bufsize);
717 * The system-dependent part of master_cleanup() - close the master socket.
719 void sysdep_master_cleanup(void) {
720 struct ServiceFunctionHook *serviceptr;
722 ///// DestroyWorkerList();
724 * close all protocol master sockets
726 for (serviceptr = ServiceHookTable; serviceptr != NULL;
727 serviceptr = serviceptr->next ) {
729 if (serviceptr->tcp_port > 0)
730 lprintf(CTDL_INFO, "Closing listener on port %d\n",
731 serviceptr->tcp_port);
733 if (serviceptr->sockpath != NULL)
734 lprintf(CTDL_INFO, "Closing listener on '%s'\n",
735 serviceptr->sockpath);
737 close(serviceptr->msock);
739 /* If it's a Unix domain socket, remove the file. */
740 if (serviceptr->sockpath != NULL) {
741 unlink(serviceptr->sockpath);
747 serv_calendar_destroy();
748 CtdlDestroyProtoHooks();
749 CtdlDestroyDeleteHooks();
750 CtdlDestroyXmsgHooks();
751 CtdlDestroyNetprocHooks();
752 CtdlDestroyUserHooks();
753 CtdlDestroyMessageHook();
754 CtdlDestroyCleanupHooks();
755 CtdlDestroyFixedOutputHooks();
756 CtdlDestroySessionHooks();
757 CtdlDestroyServiceHook();
764 * Terminate another session.
765 * (This could justifiably be moved out of sysdep.c because it
766 * no longer does anything that is system-dependent.)
768 void kill_session(int session_to_kill) {
769 struct CitContext *ptr;
771 begin_critical_section(S_SESSION_TABLE);
772 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
773 if (ptr->cs_pid == session_to_kill) {
777 end_critical_section(S_SESSION_TABLE);
781 void graceful_shutdown(int signum) {
782 kill(current_child, signum);
783 unlink(file_pid_file);
789 * Start running as a daemon.
791 void start_daemon(int unused) {
799 /* Close stdin/stdout/stderr and replace them with /dev/null.
800 * We don't just call close() because we don't want these fd's
801 * to be reused for other files.
810 signal(SIGHUP, SIG_IGN);
811 signal(SIGINT, SIG_IGN);
812 signal(SIGQUIT, SIG_IGN);
816 freopen("/dev/null", "r", stdin);
817 freopen("/dev/null", "w", stdout);
818 freopen("/dev/null", "w", stderr);
821 current_child = fork();
823 signal(SIGTERM, graceful_shutdown);
825 if (current_child < 0) {
830 else if (current_child == 0) {
831 return; /* continue starting citadel. */
835 fp = fopen(file_pid_file, "w");
837 fprintf(fp, ""F_PID_T"\n", child);
840 waitpid(current_child, &status, 0);
845 /* Did the main process exit with an actual exit code? */
846 if (WIFEXITED(status)) {
848 /* Exit code 0 means the watcher should exit */
849 if (WEXITSTATUS(status) == 0) {
853 /* Exit code 101-109 means the watcher should exit */
854 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
858 /* Any other exit code means we should restart. */
864 /* Any other type of termination (signals, etc.) should also restart. */
869 } while (do_restart);
871 unlink(file_pid_file);
872 exit(WEXITSTATUS(status));
878 * Generic routine to convert a login name to a full name (gecos)
879 * Returns nonzero if a conversion took place
881 int convert_login(char NameToConvert[]) {
885 pw = getpwnam(NameToConvert);
890 strcpy(NameToConvert, pw->pw_gecos);
891 for (a=0; a<strlen(NameToConvert); ++a) {
892 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
898 struct worker_node *worker_list = NULL;
902 * create a worker thread. this function must always be called from within
903 * an S_WORKER_LIST critical section!
905 void create_worker(void) {
907 struct worker_node *n;
910 n = malloc(sizeof(struct worker_node));
912 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
917 if ((ret = pthread_attr_init(&attr))) {
918 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
923 /* Our per-thread stacks need to be bigger than the default size,
924 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
925 * crashes on 64-bit Linux.
927 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
928 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
931 pthread_attr_destroy(&attr);
935 if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
938 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
942 n->next = worker_list;
944 pthread_attr_destroy(&attr);
947 void DestroyWorkerList(void)
949 struct CitContext *ptr; /* general-purpose utility pointer */
950 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
952 begin_critical_section(S_SESSION_TABLE);
955 /* Remove the session from the active list */
959 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
960 end_critical_section(S_SESSION_TABLE);
962 begin_critical_section(S_SESSION_TABLE);
966 end_critical_section(S_SESSION_TABLE);
968 struct worker_node *cur, *p;
980 * Create the maintenance threads and begin their operation.
982 void create_maintenance_threads(void) {
986 if ((ret = pthread_attr_init(&attr))) {
987 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
992 /* Our per-thread stacks need to be bigger than the default size,
993 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
994 * crashes on 64-bit Linux.
996 if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
997 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1000 pthread_attr_destroy(&attr);
1004 struct MaintenanceThreadHook *fcn;
1006 lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1008 for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1009 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1010 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1014 lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1015 fcn->MaintenanceThread_tid);
1020 pthread_attr_destroy(&attr);
1026 * Purge all sessions which have the 'kill_me' flag set.
1027 * This function has code to prevent it from running more than once every
1028 * few seconds, because running it after every single unbind would waste a lot
1029 * of CPU time and keep the context list locked too much. To force it to run
1030 * anyway, set "force" to nonzero.
1033 * After that's done, we raise the size of the worker thread pool
1034 * if such an action is appropriate.
1036 void dead_session_purge(int force) {
1037 struct CitContext *ptr; /* general-purpose utility pointer */
1038 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1041 if ( (time(NULL) - last_purge) < 5 ) {
1042 return; /* Too soon, go away */
1047 begin_critical_section(S_SESSION_TABLE);
1048 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1049 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1051 /* Remove the session from the active list */
1053 ptr->prev->next = ptr->next;
1056 ContextList = ptr->next;
1059 ptr->next->prev = ptr->prev;
1064 /* And put it on our to-be-destroyed list */
1070 end_critical_section(S_SESSION_TABLE);
1072 /* Now that we no longer have the session list locked, we can take
1073 * our time and destroy any sessions on the to-be-killed list, which
1074 * is allocated privately on this thread's stack.
1076 while (rem != NULL) {
1077 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1084 /* Raise the size of the worker thread pool if necessary. */
1085 if ( (num_sessions > num_threads)
1086 && (num_threads < config.c_max_workers) ) {
1087 begin_critical_section(S_WORKER_LIST);
1089 end_critical_section(S_WORKER_LIST);
1098 * masterCC is the context we use when not attached to a session. This
1099 * function initializes it.
1101 void InitializeMasterCC(void) {
1102 memset(&masterCC, 0, sizeof(struct CitContext));
1103 masterCC.internal_pgm = 1;
1104 masterCC.cs_pid = 0;
1113 * Bind a thread to a context. (It's inline merely to speed things up.)
1115 INLINE void become_session(struct CitContext *which_con) {
1116 pthread_setspecific(MyConKey, (void *)which_con );
1122 * This loop just keeps going and going and going...
1124 void *worker_thread(void *arg) {
1127 struct CitContext *ptr;
1128 struct CitContext *bind_me = NULL;
1131 struct CitContext *con= NULL; /* Temporary context pointer */
1132 struct ServiceFunctionHook *serviceptr;
1133 int ssock; /* Descriptor for client socket */
1135 int force_purge = 0;
1142 while (!time_to_die) {
1144 /* make doubly sure we're not holding any stale db handles
1145 * which might cause a deadlock.
1147 cdb_check_handles();
1148 do_select: force_purge = 0;
1149 bind_me = NULL; /* Which session shall we handle? */
1151 /* Initialize the fdset. */
1155 begin_critical_section(S_SESSION_TABLE);
1156 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1157 if (ptr->state == CON_IDLE) {
1158 FD_SET(ptr->client_socket, &readfds);
1159 if (ptr->client_socket > highest)
1160 highest = ptr->client_socket;
1162 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1164 ptr->state = CON_EXECUTING;
1167 end_critical_section(S_SESSION_TABLE);
1173 /* If we got this far, it means that there are no sessions
1174 * which a previous thread marked for attention, so we go
1175 * ahead and get ready to select().
1178 /* First, add the various master sockets to the fdset. */
1179 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1180 serviceptr = serviceptr->next ) {
1181 m = serviceptr->msock;
1182 FD_SET(m, &readfds);
1189 tv.tv_sec = 1; /* wake up every second if no input */
1191 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1194 if (time_to_die) return(NULL);
1196 /* Now figure out who made this select() unblock.
1197 * First, check for an error or exit condition.
1200 if (errno == EBADF) {
1201 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1205 if (errno != EINTR) {
1206 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1208 } else if (!time_to_die)
1212 /* Next, check to see if it's a new client connecting
1213 * on a master socket.
1215 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1216 serviceptr = serviceptr->next ) {
1218 if (FD_ISSET(serviceptr->msock, &readfds)) {
1219 ssock = accept(serviceptr->msock, NULL, 0);
1222 "New client socket %d\n",
1225 /* The master socket is non-blocking but the client
1226 * sockets need to be blocking, otherwise certain
1227 * operations barf on FreeBSD. Not a fatal error.
1229 if (fcntl(ssock, F_SETFL, 0) < 0) {
1231 "citserver: Can't set socket to blocking: %s\n",
1235 /* New context will be created already
1236 * set up in the CON_EXECUTING state.
1238 con = CreateNewContext();
1240 /* Assign our new socket number to it. */
1241 con->client_socket = ssock;
1242 con->h_command_function =
1243 serviceptr->h_command_function;
1244 con->h_async_function =
1245 serviceptr->h_async_function;
1247 /* Determine whether it's a local socket */
1248 if (serviceptr->sockpath != NULL)
1249 con->is_local_socket = 1;
1251 /* Set the SO_REUSEADDR socket option */
1253 setsockopt(ssock, SOL_SOCKET,
1257 become_session(con);
1259 serviceptr->h_greeting_function();
1260 become_session(NULL);
1261 con->state = CON_IDLE;
1267 /* It must be a client socket. Find a context that has data
1268 * waiting on its socket *and* is in the CON_IDLE state. Any
1269 * active sockets other than our chosen one are marked as
1270 * CON_READY so the next thread that comes around can just bind
1271 * to one without having to select() again.
1273 begin_critical_section(S_SESSION_TABLE);
1274 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1275 if ( (FD_ISSET(ptr->client_socket, &readfds))
1276 && (ptr->state != CON_EXECUTING) ) {
1277 ptr->input_waiting = 1;
1279 bind_me = ptr; /* I choose you! */
1280 bind_me->state = CON_EXECUTING;
1283 ptr->state = CON_READY;
1287 end_critical_section(S_SESSION_TABLE);
1290 /* We're bound to a session */
1291 if (bind_me != NULL) {
1292 become_session(bind_me);
1294 /* If the client has sent a command, execute it. */
1295 if (CC->input_waiting) {
1296 CC->h_command_function();
1297 CC->input_waiting = 0;
1300 /* If there are asynchronous messages waiting and the
1301 * client supports it, do those now */
1302 if ((CC->is_async) && (CC->async_waiting)
1303 && (CC->h_async_function != NULL)) {
1304 CC->h_async_function();
1305 CC->async_waiting = 0;
1308 force_purge = CC->kill_me;
1309 become_session(NULL);
1310 bind_me->state = CON_IDLE;
1313 dead_session_purge(force_purge);
1315 check_sched_shutdown();
1317 if (con != NULL) free (con);//// TODO: could this harm other threads?
1318 /* If control reaches this point, the server is shutting down */
1327 * Translate text facility name to syslog.h defined value.
1329 int SyslogFacility(char *name)
1338 { LOG_KERN, "kern" },
1339 { LOG_USER, "user" },
1340 { LOG_MAIL, "mail" },
1341 { LOG_DAEMON, "daemon" },
1342 { LOG_AUTH, "auth" },
1343 { LOG_SYSLOG, "syslog" },
1345 { LOG_NEWS, "news" },
1346 { LOG_UUCP, "uucp" },
1347 { LOG_LOCAL0, "local0" },
1348 { LOG_LOCAL1, "local1" },
1349 { LOG_LOCAL2, "local2" },
1350 { LOG_LOCAL3, "local3" },
1351 { LOG_LOCAL4, "local4" },
1352 { LOG_LOCAL5, "local5" },
1353 { LOG_LOCAL6, "local6" },
1354 { LOG_LOCAL7, "local7" },
1357 for(i = 0; facTbl[i].name != NULL; i++) {
1358 if(!strcasecmp(name, facTbl[i].name))
1359 return facTbl[i].facility;
1366 /********** MEM CHEQQER ***********/
1368 #ifdef DEBUG_MEMORY_LEAKS
1375 void *tracked_malloc(size_t size, char *file, int line) {
1376 struct igheap *thisheap;
1379 block = malloc(size);
1380 if (block == NULL) return(block);
1382 thisheap = malloc(sizeof(struct igheap));
1383 if (thisheap == NULL) {
1388 thisheap->block = block;
1389 strcpy(thisheap->file, file);
1390 thisheap->line = line;
1392 begin_critical_section(S_DEBUGMEMLEAKS);
1393 thisheap->next = igheap;
1395 end_critical_section(S_DEBUGMEMLEAKS);
1401 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1402 struct igheap *thisheap;
1405 block = realloc(ptr, size);
1406 if (block == NULL) return(block);
1408 thisheap = malloc(sizeof(struct igheap));
1409 if (thisheap == NULL) {
1414 thisheap->block = block;
1415 strcpy(thisheap->file, file);
1416 thisheap->line = line;
1418 begin_critical_section(S_DEBUGMEMLEAKS);
1419 thisheap->next = igheap;
1421 end_critical_section(S_DEBUGMEMLEAKS);
1428 void tracked_free(void *ptr) {
1429 struct igheap *thisheap;
1430 struct igheap *trash;
1434 if (igheap == NULL) return;
1435 begin_critical_section(S_DEBUGMEMLEAKS);
1436 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1437 if (thisheap->next != NULL) {
1438 if (thisheap->next->block == ptr) {
1439 trash = thisheap->next;
1440 thisheap->next = thisheap->next->next;
1445 if (igheap->block == ptr) {
1447 igheap = igheap->next;
1450 end_critical_section(S_DEBUGMEMLEAKS);
1453 char *tracked_strdup(const char *s, char *file, int line) {
1456 if (s == NULL) return(NULL);
1457 ptr = tracked_malloc(strlen(s) + 1, file, line);
1458 if (ptr == NULL) return(NULL);
1459 strncpy(ptr, s, strlen(s));
1463 void dump_heap(void) {
1464 struct igheap *thisheap;
1466 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1467 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1468 thisheap->file, thisheap->line);
1472 #endif /* DEBUG_MEMORY_LEAKS */