text:
#define _BSD_SOURCE
#define _GNU_SOURCE

#include <asm/unistd.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <inttypes.h>
#include <limits.h>
#include <linux/capability.h>
#include <pwd.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syscall.h>
#include <sys/capability.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "libminijail.h"
#include "libminijail-private.h"

#include "signal.h"
#include "syscall_filter.h"
#include "util.h"

#ifdef HAVE_SECUREBITS_H
#include <linux/securebits.h>
#else
#define SECURE_ALL_BITS         0x15
#define SECURE_ALL_LOCKS        (SECURE_ALL_BITS << 1)
#endif

/* Until these are reliably available in linux/prctl.h */
#ifndef PR_SET_SECCOMP
# define PR_SET_SECCOMP 22
#endif

/* For seccomp_filter using BPF. */
#ifndef PR_SET_NO_NEW_PRIVS
# define PR_SET_NO_NEW_PRIVS 38
#endif
#ifndef SECCOMP_MODE_FILTER
# define SECCOMP_MODE_FILTER 2 /* uses user-supplied filter. */
#endif

#ifdef USE_SECCOMP_SOFTFAIL
# define SECCOMP_SOFTFAIL 1
#else
# define SECCOMP_SOFTFAIL 0
#endif

struct binding {
	char *src;
	char *dest;
	int writeable;
	struct binding *next;
};

struct minijail {
	/*
	 * WARNING: if you add a flag here you need to make sure it's
	 * accounted for in minijail_pre{enter|exec}() below.
	 */
	struct {
		int uid:1;
		int gid:1;
		int caps:1;
		int vfs:1;
		int enter_vfs:1;
		int pids:1;
		int net:1;
		int seccomp:1;
		int readonly:1;
		int usergroups:1;
		int ptrace:1;
		int no_new_privs:1;
		int seccomp_filter:1;
		int log_seccomp_filter:1;
		int chroot:1;
		int mount_tmp:1;
		int do_init:1;
		int chdir:1;
		/* The following are only used for omegaUp */
		int stack_limit:1;
		int time_limit:1;
		int output_limit:1;
		int memory_limit:1;
		int meta_file:1;
		int close_all_files:1;
		int redirect_stdin:1;
		int redirect_stdout:1;
		int redirect_stderr:1;
	} flags;
	uid_t uid;
	gid_t gid;
	gid_t usergid;
	char *user;
	uint64_t caps;
	pid_t initpid;
	int mountns_fd;
	int filter_len;
	int binding_count;
	char *chrootdir;
	char *chdir;
	int log_level;
	struct sock_fprog *filter_prog;
	struct binding *bindings_head;
	struct binding *bindings_tail;

	/* The following fields are only used for omegaUp */
	int stack_limit;
	int time_limit;
	int extra_wall_time;
	int memory_limit;
	int output_limit;
	int syscall_pipe_fds[2];
	FILE *meta_file;
};

/*
 * Strip out flags meant for the parent.
 * We keep things that are not inherited across execve(2) (e.g. capabilities),
 * or are easier to set after execve(2) (e.g. seccomp filters).
 */
void minijail_preenter(struct minijail *j)
{
	j->flags.vfs = 0;
	j->flags.enter_vfs = 0;
	j->flags.readonly = 0;
	j->flags.pids = 0;
	j->flags.do_init = 0;
	j->flags.chdir = 0;
	j->flags.chroot = 0;
}

/*
 * Strip out flags meant for the child.
 * We keep things that are inherited across execve(2).
 */
void minijail_preexec(struct minijail *j)
{
	int vfs = j->flags.vfs;
	int enter_vfs = j->flags.enter_vfs;
	int readonly = j->flags.readonly;
	int stack_limit = j->flags.stack_limit;
	int time_limit = j->flags.time_limit;
	int memory_limit = j->flags.memory_limit;
	int output_limit = j->flags.output_limit;
	int meta_file = j->flags.meta_file;
	int chdir = j->flags.chdir;
	int chroot = j->flags.chroot;
	if (j->user)
		free(j->user);
	j->user = NULL;
	memset(&j->flags, 0, sizeof(j->flags));
	/* Now restore anything we meant to keep. */
	j->flags.vfs = vfs;
	j->flags.enter_vfs = enter_vfs;
	j->flags.readonly = readonly;
	/* Note, |pids| will already have been used before this call. */
	j->flags.stack_limit = stack_limit;
	j->flags.time_limit = time_limit;
	j->flags.memory_limit = memory_limit;
	j->flags.output_limit = output_limit;
	j->flags.meta_file = meta_file;
	j->flags.chdir = chdir;
	j->flags.chroot = chroot;
}

/* Minijail API. */

struct minijail API *minijail_new(void)
{
	struct minijail *j = calloc(1, sizeof(struct minijail));
	if (j) {
		j->log_level = LOG_INFO;
	}
	return j;
}

void API minijail_change_uid(struct minijail *j, uid_t uid)
{
	if (uid == 0)
		die("useless change to uid 0");
	j->uid = uid;
	j->flags.uid = 1;
}

void API minijail_change_gid(struct minijail *j, gid_t gid)
{
	if (gid == 0)
		die("useless change to gid 0");
	j->gid = gid;
	j->flags.gid = 1;
}

int API minijail_change_user(struct minijail *j, const char *user)
{
	char *buf = NULL;
	struct passwd pw;
	struct passwd *ppw = NULL;
	ssize_t sz = sysconf(_SC_GETPW_R_SIZE_MAX);
	if (sz == -1)
		sz = 65536;	/* your guess is as good as mine... */

	/*
	 * sysconf(_SC_GETPW_R_SIZE_MAX), under glibc, is documented to return
	 * the maximum needed size of the buffer, so we don't have to search.
	 */
	buf = malloc(sz);
	if (!buf)
		return -ENOMEM;
	getpwnam_r(user, &pw, buf, sz, &ppw);
	/*
	 * We're safe to free the buffer here. The strings inside pw point
	 * inside buf, but we don't use any of them; this leaves the pointers
	 * dangling but it's safe. ppw points at pw if getpwnam_r succeeded.
	 */
	free(buf);
	/* getpwnam_r(3) does *not* set errno when |ppw| is NULL. */
	if (!ppw)
		return -1;
	minijail_change_uid(j, ppw->pw_uid);
	j->user = strdup(user);
	if (!j->user)
		return -ENOMEM;
	j->usergid = ppw->pw_gid;
	return 0;
}

int API minijail_change_group(struct minijail *j, const char *group)
{
	char *buf = NULL;
	struct group gr;
	struct group *pgr = NULL;
	ssize_t sz = sysconf(_SC_GETGR_R_SIZE_MAX);
	if (sz == -1)
		sz = 65536;	/* and mine is as good as yours, really */

	/*
	 * sysconf(_SC_GETGR_R_SIZE_MAX), under glibc, is documented to return
	 * the maximum needed size of the buffer, so we don't have to search.
	 */
	buf = malloc(sz);
	if (!buf)
		return -ENOMEM;
	getgrnam_r(group, &gr, buf, sz, &pgr);
	/*
	 * We're safe to free the buffer here. The strings inside gr point
	 * inside buf, but we don't use any of them; this leaves the pointers
	 * dangling but it's safe. pgr points at gr if getgrnam_r succeeded.
	 */
	free(buf);
	/* getgrnam_r(3) does *not* set errno when |pgr| is NULL. */
	if (!pgr)
		return -1;
	minijail_change_gid(j, pgr->gr_gid);
	return 0;
}

void API minijail_use_seccomp(struct minijail *j)
{
	j->flags.seccomp = 1;
}

void API minijail_no_new_privs(struct minijail *j)
{
	j->flags.no_new_privs = 1;
}

void API minijail_use_seccomp_filter(struct minijail *j)
{
	j->flags.seccomp_filter = 1;
}

void API minijail_log_seccomp_filter_failures(struct minijail *j)
{
	j->flags.log_seccomp_filter = 1;
}

void API minijail_use_caps(struct minijail *j, uint64_t capmask)
{
	j->caps = capmask;
	j->flags.caps = 1;
}

void API minijail_namespace_vfs(struct minijail *j)
{
	j->flags.vfs = 1;
}

void API minijail_namespace_enter_vfs(struct minijail *j, const char *ns_path)
{
	int ns_fd = open(ns_path, O_RDONLY);
	if (ns_fd < 0) {
		pdie("failed to open namespace '%s'", ns_path);
	}
	j->mountns_fd = ns_fd;
	j->flags.enter_vfs = 1;
}

void API minijail_namespace_pids(struct minijail *j)
{
	j->flags.vfs = 1;
	j->flags.readonly = 1;
	j->flags.pids = 1;
	j->flags.do_init = 1;
}

void API minijail_namespace_net(struct minijail *j)
{
	j->flags.net = 1;
}

void API minijail_remount_readonly(struct minijail *j)
{
	j->flags.vfs = 1;
	j->flags.readonly = 1;
}

void API minijail_inherit_usergroups(struct minijail *j)
{
	j->flags.usergroups = 1;
}

void API minijail_disable_ptrace(struct minijail *j)
{
	j->flags.ptrace = 1;
}

void API minijail_log_level(struct minijail *j, int syslog_priority)
{
	j->log_level = syslog_priority;
}

int API minijail_get_log_level(struct minijail *j)
{
	return j->log_level;
}

void API minijail_run_as_init(struct minijail *j)
{
	/*
	 * Since the jailed program will become 'init' in the new PID namespace,
	 * Minijail does not need to fork an 'init' process.
	 */
	j->flags.do_init = 0;
}

int API minijail_enter_chroot(struct minijail *j, const char *dir)
{
	if (j->chrootdir)
		return -EINVAL;
	j->chrootdir = strdup(dir);
	if (!j->chrootdir)
		return -ENOMEM;
	j->flags.chroot = 1;
	return 0;
}

void API minijail_mount_tmp(struct minijail *j)
{
	j->flags.mount_tmp = 1;
}

int API minijail_chroot_chdir(struct minijail *j, const char *dir) {
	if (!j->chrootdir)
		return -EINVAL;
	if (j->chdir)
		return -EINVAL;
	if (!dir || dir[0] != '/')
		return -EINVAL;
	j->chdir = strdup(dir);
	if (!j->chdir)
		return -ENOMEM;
	j->flags.chdir = 1;
	return 0;
}

int API minijail_bind(struct minijail *j, const char *src, const char *dest,
		      int writeable)
{
	struct binding *b;

	if (*dest != '/')
		return -EINVAL;
	b = calloc(1, sizeof(*b));
	if (!b)
		return -ENOMEM;
	b->dest = strdup(dest);
	if (!b->dest)
		goto error;
	b->src = strdup(src);
	if (!b->src)
		goto error;
	b->writeable = writeable;

	info(j->log_level, "bind %s -> %s", src, dest);

	/*
	 * Force vfs namespacing so the bind mounts don't leak out into the
	 * containing vfs namespace.
	 */
	minijail_namespace_vfs(j);

	if (j->bindings_tail)
		j->bindings_tail->next = b;
	else
		j->bindings_head = b;
	j->bindings_tail = b;
	j->binding_count++;

	return 0;

error:
	free(b->src);
	free(b->dest);
	free(b);
	return -ENOMEM;
}

void API minijail_parse_seccomp_filters(struct minijail *j, const char *path)
{
	if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, NULL)) {
		if ((errno == ENOSYS) && SECCOMP_SOFTFAIL) {
			warn(j->log_level,
			     "not loading seccomp filter, seccomp not supported");
			return;
		}
	}
	FILE *file = fopen(path, "r");
	if (!file) {
		pdie("failed to open seccomp filter file '%s'", path);
	}

	struct sock_fprog *fprog = malloc(sizeof(struct sock_fprog));
	if (compile_filter(file, fprog, j->flags.log_seccomp_filter, j->log_level)) {
		die("failed to compile seccomp filter BPF program in '%s'",
		    path);
	}

	j->filter_len = fprog->len;
	j->filter_prog = fprog;

	fclose(file);
}

struct marshal_state {
	size_t available;
	size_t total;
	char *buf;
};

void marshal_state_init(struct marshal_state *state,
			char *buf, size_t available)
{
	state->available = available;
	state->buf = buf;
	state->total = 0;
}

void marshal_append(struct marshal_state *state,
		    char *src, size_t length)
{
	size_t copy_len = MIN(state->available, length);

	/* Up to |available| will be written. */
	if (copy_len) {
		memcpy(state->buf, src, copy_len);
		state->buf += copy_len;
		state->available -= copy_len;
	}
	/* |total| will contain the expected length. */
	state->total += length;
}

void minijail_marshal_helper(struct marshal_state *state,
			     const struct minijail *j)
{
	struct binding *b = NULL;
	marshal_append(state, (char *)j, sizeof(*j));
	if (j->user)
		marshal_append(state, j->user, strlen(j->user) + 1);
	if (j->chrootdir)
		marshal_append(state, j->chrootdir, strlen(j->chrootdir) + 1);
	if (j->chdir)
		marshal_append(state, j->chdir, strlen(j->chdir) + 1);
	if (j->flags.seccomp_filter && j->filter_prog) {
		struct sock_fprog *fp = j->filter_prog;
		marshal_append(state, (char *)fp->filter,
				fp->len * sizeof(struct sock_filter));
	}
	for (b = j->bindings_head; b; b = b->next) {
		marshal_append(state, b->src, strlen(b->src) + 1);
		marshal_append(state, b->dest, strlen(b->dest) + 1);
		marshal_append(state, (char *)&b->writeable,
				sizeof(b->writeable));
	}
}

size_t API minijail_size(const struct minijail *j)
{
	struct marshal_state state;
	marshal_state_init(&state, NULL, 0);
	minijail_marshal_helper(&state, j);
	return state.total;
}

int minijail_marshal(const struct minijail *j, char *buf, size_t available)
{
	struct marshal_state state;
	marshal_state_init(&state, buf, available);
	minijail_marshal_helper(&state, j);
	return (state.total > available);
}

/* consumebytes: consumes @length bytes from a buffer @buf of length @buflength
 * @length    Number of bytes to consume
 * @buf       Buffer to consume from
 * @buflength Size of @buf
 *
 * Returns a pointer to the base of the bytes, or NULL for errors.
 */
void *consumebytes(size_t length, char **buf, size_t *buflength)
{
	char *p = *buf;
	if (length > *buflength)
		return NULL;
	*buf += length;
	*buflength -= length;
	return p;
}

/* consumestr: consumes a C string from a buffer @buf of length @length
 * @buf    Buffer to consume
 * @length Length of buffer
 *
 * Returns a pointer to the base of the string, or NULL for errors.
 */
char *consumestr(char **buf, size_t *buflength)
{
	size_t len = strnlen(*buf, *buflength);
	if (len == *buflength)
		/* There's no null-terminator */
		return NULL;
	return consumebytes(len + 1, buf, buflength);
}

int minijail_unmarshal(struct minijail *j, char *serialized, size_t length)
{
	int i;
	int count;
	int ret = -EINVAL;

	if (length < sizeof(*j))
		goto out;
	memcpy((void *)j, serialized, sizeof(*j));
	serialized += sizeof(*j);
	length -= sizeof(*j);

	/* Potentially stale pointers not used as signals. */
	j->bindings_head = NULL;
	j->bindings_tail = NULL;
	j->filter_prog = NULL;

	if (j->user) {		/* stale pointer */
		char *user = consumestr(&serialized, &length);
		if (!user)
			goto clear_pointers;
		j->user = strdup(user);
		if (!j->user)
			goto clear_pointers;
	}

	if (j->chrootdir) {	/* stale pointer */
		char *chrootdir = consumestr(&serialized, &length);
		if (!chrootdir)
			goto bad_chrootdir;
		j->chrootdir = strdup(chrootdir);
		if (!j->chrootdir)
			goto bad_chrootdir;
	}

	if (j->chdir) {	/* stale pointer */
		char *chdirstr = consumestr(&serialized, &length);
		if (!chdirstr)
			goto bad_chdir;
		j->chdir = strdup(chdirstr);
		if (!j->chdir)
			goto bad_chdir;
	}

	if (j->flags.seccomp_filter && j->filter_len > 0) {
		size_t ninstrs = j->filter_len;
		if (ninstrs > (SIZE_MAX / sizeof(struct sock_filter)) ||
		    ninstrs > USHRT_MAX)
			goto bad_filters;

		size_t program_len = ninstrs * sizeof(struct sock_filter);
		void *program = consumebytes(program_len, &serialized, &length);
		if (!program)
			goto bad_filters;

		j->filter_prog = malloc(sizeof(struct sock_fprog));
		j->filter_prog->len = ninstrs;
		j->filter_prog->filter = malloc(program_len);
		memcpy(j->filter_prog->filter, program, program_len);
	}

	if (j->meta_file) {
		j->meta_file = NULL;
	}

	count = j->binding_count;
	j->binding_count = 0;
	for (i = 0; i < count; ++i) {
		int *writeable;
		const char *dest;
		const char *src = consumestr(&serialized, &length);
		if (!src)
			goto bad_bindings;
		dest = consumestr(&serialized, &length);
		if (!dest)
			goto bad_bindings;
		writeable = consumebytes(sizeof(*writeable), &serialized, &length);
		if (!writeable)
			goto bad_bindings;
		if (minijail_bind(j, src, dest, *writeable))
			goto bad_bindings;
	}

	close(j->syscall_pipe_fds[0]); /* read endpoint */
	j->syscall_pipe_fds[0] = -1;
	signum_fd = j->syscall_pipe_fds[1];

	return 0;

bad_bindings:
	if (j->flags.seccomp_filter && j->filter_len > 0) {
		free(j->filter_prog->filter);
		free(j->filter_prog);
	}
bad_filters:
	if (j->chrootdir)
		free(j->chrootdir);
bad_chdir:
	if (j->chdir)
		free(j->chdir);
bad_chrootdir:
	if (j->user)
		free(j->user);
clear_pointers:
	j->user = NULL;
	j->chrootdir = NULL;
	j->chdir = NULL;
out:
	return ret;
}

/* bind_one: Applies bindings from @b for @j, recursing as needed.
 * @j Minijail these bindings are for
 * @b Head of list of bindings
 *
 * Returns 0 for success.
 */
int bind_one(const struct minijail *j, struct binding *b)
{
	int ret = 0;
	char *dest = NULL;
	if (ret)
		return ret;
	/* dest has a leading "/" */
	if (asprintf(&dest, "%s%s", j->chrootdir, b->dest) < 0)
		return -ENOMEM;
	ret = mount(b->src, dest, NULL, MS_BIND, NULL);
	if (ret)
		pdie("bind: %s -> %s", b->src, dest);
	if (!b->writeable) {
		ret = mount(b->src, dest, NULL,
			    MS_BIND | MS_REMOUNT | MS_RDONLY, NULL);
		if (ret)
			pdie("bind ro: %s -> %s", b->src, dest);
	}
	free(dest);
	if (b->next)
		return bind_one(j, b->next);
	return ret;
}

int enter_chroot(const struct minijail *j)
{
	int ret;
	if (j->bindings_head && (ret = bind_one(j, j->bindings_head)))
		return ret;

	if (chroot(j->chrootdir))
		return -errno;

	if (chdir(j->flags.chdir ? j->chdir : "/"))
		return -errno;

	return 0;
}

int mount_tmp(void)
{
	return mount("none", "/tmp", "tmpfs", 0, "size=64M,mode=777");
}

int unshare_vfs(void)
{
	if (unshare(CLONE_NEWNS))
		return -errno;
#if defined(MS_PRIVATE)
	/*
	 * Systems with systemd will have / be a shared mount instead
	 * of a private mount, which makes the CLONE_NEWNS flag useless
	 * unless we make / a private mount again.
	 */
	if (mount(NULL, "/", "none", MS_PRIVATE | MS_REC, NULL))
		return -errno;
#endif
	return 0;
}

int unmount_proc(void)
{
	const char *kProcPath = "/proc";
	/*
	 * Right now, we're holding a reference to our parent's old mount of
	 * /proc in our namespace, which means using MS_REMOUNT here would
	 * mutate our parent's mount as well, even though we're in a VFS
	 * namespace (!). Instead, remove their mount from our namespace
	 * and make our own.
	 */
	/* Some distros have JDK mount this. Unmount it without erroring out */
	if (umount2(kProcPath, MNT_DETACH))
		return -errno;
	return 0;
}

int remount_readonly(void)
{
	const char *kProcPath = "/proc";
	const unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
	if (mount("", kProcPath, "proc", kSafeFlags | MS_RDONLY, ""))
		return -errno;
	return 0;
}

void drop_ugid(const struct minijail *j)
{
	if (j->flags.usergroups) {
		if (initgroups(j->user, j->usergid))
			pdie("initgroups");
	} else {
		/* Only attempt to clear supplemental groups if we are changing
		 * users. */
		if ((j->uid || j->gid) && setgroups(0, NULL))
			pdie("setgroups");
	}

	if (j->flags.gid && setresgid(j->gid, j->gid, j->gid))
		pdie("setresgid");

	if (j->flags.uid && setresuid(j->uid, j->uid, j->uid))
		pdie("setresuid");
}

void redirect_stdio(const struct minijail *j)
{
	if (j->flags.redirect_stdin) {
		int fd = open("/dev/stdin", O_RDONLY | O_NOFOLLOW);
		if (fd == -1) {
			pdie("open(stdin)");
		}
		if (fd != 0) {
			if (dup2(fd, 0) != 0) {
				pdie("dup2(stdin)");
			}
			close(fd);
		}
	}
	if (j->flags.redirect_stdout) {
		int fd = open("/dev/stdout", O_WRONLY | O_TRUNC | O_NOFOLLOW);
		if (fd == -1) {
			pdie("open(stdout)");
		}
		if (fd != 1) {
			if (dup2(fd, 1) != 1) {
				pdie("dup2(stdout)");
			}
			close(fd);
		}
	}
	if (j->flags.redirect_stderr) {
		int fd = open("/dev/stderr", O_WRONLY | O_TRUNC | O_NOFOLLOW);
		if (fd == -1) {
			pdie("open(stderr)");
		}
		if (fd != 2) {
			if (dup2(fd, 2) != 2) {
				pdie("dup2(stderr)");
			}
			close(fd);
		}
	}
}

/*
 * We specifically do not use cap_valid() as that only tells us the last
 * valid cap we were *compiled* against (i.e. what the version of kernel
 * headers says).  If we run on a different kernel version, then it's not
 * uncommon for that to be less (if an older kernel) or more (if a newer
 * kernel).  So suck up the answer via /proc.
 */
static int run_cap_valid(unsigned int cap)
{
	static unsigned int last_cap;

	if (!last_cap) {
		const char cap_file[] = "/proc/sys/kernel/cap_last_cap";
		FILE *fp = fopen(cap_file, "re");
		if (fp == NULL)
			pdie("fopen(%s)", cap_file);
		if (fscanf(fp, "%u", &last_cap) != 1)
			pdie("fscanf(%s)", cap_file);
		fclose(fp);
	}

	return cap <= last_cap;
}

void drop_caps(const struct minijail *j)
{
	cap_t caps = cap_get_proc();
	cap_value_t flag[1];
	const uint64_t one = 1;
	unsigned int i;
	if (!caps)
		die("can't get process caps");
	if (cap_clear_flag(caps, CAP_INHERITABLE))
		die("can't clear inheritable caps");
	if (cap_clear_flag(caps, CAP_EFFECTIVE))
		die("can't clear effective caps");
	if (cap_clear_flag(caps, CAP_PERMITTED))
		die("can't clear permitted caps");
	for (i = 0; i < sizeof(j->caps) * 8 && run_cap_valid(i); ++i) {
		/* Keep CAP_SETPCAP for dropping bounding set bits. */
		if (i != CAP_SETPCAP && !(j->caps & (one << i)))
			continue;
		flag[0] = i;
		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_SET))
			die("can't add effective cap");
		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_SET))
			die("can't add permitted cap");
		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_SET))
			die("can't add inheritable cap");
	}
	if (cap_set_proc(caps))
		die("can't apply initial cleaned capset");

	/*
	 * Instead of dropping bounding set first, do it here in case
	 * the caller had a more permissive bounding set which could
	 * have been used above to raise a capability that wasn't already
	 * present. This requires CAP_SETPCAP, so we raised/kept it above.
	 */
	for (i = 0; i < sizeof(j->caps) * 8 && run_cap_valid(i); ++i) {
		if (j->caps & (one << i))
			continue;
		if (prctl(PR_CAPBSET_DROP, i))
			pdie("prctl(PR_CAPBSET_DROP)");
	}

	/* If CAP_SETPCAP wasn't specifically requested, now we remove it. */
	if ((j->caps & (one << CAP_SETPCAP)) == 0) {
		flag[0] = CAP_SETPCAP;
		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_CLEAR))
			die("can't clear effective cap");
		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_CLEAR))
			die("can't clear permitted cap");
		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_CLEAR))
			die("can't clear inheritable cap");
	}

	if (cap_set_proc(caps))
		die("can't apply final cleaned capset");

	cap_free(caps);
}

void set_seccomp_filter(const struct minijail *j)
{
	/*
	 * Set no_new_privs. See </kernel/seccomp.c> and </kernel/sys.c>
	 * in the kernel source tree for an explanation of the parameters.
	 */
	if (j->flags.no_new_privs) {
		if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
			pdie("prctl(PR_SET_NO_NEW_PRIVS)");
	}

	/*
	 * If we're logging seccomp filter failures,
	 * install the SIGSYS handler first.
	 */
	if (j->flags.seccomp_filter && j->flags.log_seccomp_filter) {
		if (install_sigsys_handler())
			pdie("install SIGSYS handler");
	}

	/*
	 * Install the syscall filter.
	 */
	if (j->flags.seccomp_filter) {
		if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, j->filter_prog)) {
			if ((errno == ENOSYS) && SECCOMP_SOFTFAIL) {
				warn(j->log_level, "seccomp not supported");
				return;
			}
			pdie("prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER)");
		}
	}
}

void API minijail_enter(const struct minijail *j)
{
	/*
	 * In case the cap_last_cap file is not available once we switch to the
	 * read-only /proc filesystem, we get it preemptively here.
	 */
	if (j->flags.caps)
		run_cap_valid(0);

	if (j->flags.pids)
		die("tried to enter a pid-namespaced jail;"
		    " try minijail_run()?");

	if (j->flags.usergroups && !j->user)
		die("usergroup inheritance without username");

	/*
	 * We can't recover from failures if we've dropped privileges partially,
	 * so we don't even try. If any of our operations fail, we abort() the
	 * entire process.
	 */
	if (j->flags.enter_vfs && setns(j->mountns_fd, CLONE_NEWNS))
		pdie("setns(CLONE_NEWNS)");

	if (j->flags.vfs && unshare_vfs())
		pdie("unshare(vfs)");

	if (j->flags.net && unshare(CLONE_NEWNET))
		pdie("unshare(net)");

	if (j->flags.readonly && unmount_proc())
		pdie("unmount_proc()");

	if (j->flags.chroot && enter_chroot(j))
		pdie("chroot");

	if (j->flags.mount_tmp && mount_tmp())
		pdie("mount_tmp");

	if (j->flags.readonly && remount_readonly())
		pdie("remount_redonly()");

	if (j->flags.caps) {
		/*
		 * POSIX capabilities are a bit tricky. If we drop our
		 * capability to change uids, our attempt to use setuid()
		 * below will fail. Hang on to root caps across setuid(), then
		 * lock securebits.
		 */
		if (prctl(PR_SET_KEEPCAPS, 1))
			pdie("prctl(PR_SET_KEEPCAPS)");
		if (prctl
		    (PR_SET_SECUREBITS, SECURE_ALL_BITS | SECURE_ALL_LOCKS))
			pdie("prctl(PR_SET_SECUREBITS)");
	}

	/*
	 * File descriptor management.
	 */
	if (j->flags.close_all_files) {
		long max_filedescriptor = sysconf(_SC_OPEN_MAX);
		if (max_filedescriptor == -1) {
			max_filedescriptor = 1024;
		}
		long fd;
		for (fd = 0; fd < max_filedescriptor; ++fd) {
			// We set up some pipes that need to be up.
			if (fd == j->syscall_pipe_fds[1]) {
				continue;
			}
			// Ignore errors.
			close(fd);
		}
	}

	/*
	 * If we're setting no_new_privs, we can drop privileges
	 * before setting seccomp filter. This way filter policies
	 * don't need to allow privilege-dropping syscalls.
	 */
	if (j->flags.no_new_privs) {
		drop_ugid(j);
		if (j->flags.caps)
			drop_caps(j);
		redirect_stdio(j);

		set_seccomp_filter(j);
	} else {
		/*
		 * If we're not setting no_new_privs,
		 * we need to set seccomp filter *before* dropping privileges.
		 * WARNING: this means that filter policies *must* allow
		 * setgroups()/setresgid()/setresuid() for dropping root and
		 * capget()/capset()/prctl() for dropping caps.
		 */
		set_seccomp_filter(j);

		drop_ugid(j);
		if (j->flags.caps)
			drop_caps(j);
		redirect_stdio(j);
	}

	/*
	 * seccomp has to come last since it cuts off all the other
	 * privilege-dropping syscalls :)
	 */
	if (j->flags.seccomp && prctl(PR_SET_SECCOMP, 1)) {
		if ((errno == ENOSYS) && SECCOMP_SOFTFAIL) {
			warn(j->log_level, "seccomp not supported");
			return;
		}
		pdie("prctl(PR_SET_SECCOMP)");
	}
}

/* TODO(wad) will visibility affect this variable? */
static int init_exitstatus = 0;
static pid_t child_pid = 0;
static int signal_override = 0;

void init_term(int __attribute__ ((unused)) sig)
{
	_exit(init_exitstatus);
}

void timeout(int __attribute__ ((unused)) sig)
{
	/* Something went wrong or the child ignored SIGALRM. */
	signal_override = SIGXCPU;
	kill(-child_pid, SIGKILL);
}

int init(struct minijail *j, pid_t rootpid)
{
	pid_t pid;
	int exit_signal = 0;
	int exit_syscall = -1;
	int status;
	const char *exit_syscall_name;
	const char *exit_signal_name;
	struct rusage usage;
	struct timespec t0, t1;
	/* Measure wall-time when outputting metadata information */
	if (j->flags.meta_file) {
		clock_gettime(CLOCK_REALTIME, &t0);
	}
	/* Backup for timeouts */
	if (j->flags.time_limit) {
		child_pid = rootpid;
		signal(SIGALRM, timeout);
		alarm((j->time_limit + j->extra_wall_time + 1999) / 1000);
	}
	/* so that we exit with the right status */
	signal(SIGTERM, init_term);
	/* TODO(wad) self jail with seccomp_filters here. */
	while ((pid = wait3(&status, 0, &usage)) > 0) {
		/*
		 * This loop will only end when either there are no processes
		 * left inside our pid namespace or we get a signal.
		 */
		if (pid == rootpid)
			init_exitstatus = status;
	}
	if (j->flags.meta_file) {
		clock_gettime(CLOCK_REALTIME, &t1);
		t1.tv_sec -= t0.tv_sec;
		if (t1.tv_nsec < t0.tv_nsec) {
			t1.tv_sec--;
			t1.tv_nsec = 1000000000L + t1.tv_nsec - t0.tv_nsec;
		} else {
			t1.tv_nsec -= t0.tv_nsec;
		}
		fprintf(j->meta_file,
				"time:%ld\ntime-sys:%ld\ntime-wall:%ld\nmem:%ld\n",
				1000000 * usage.ru_utime.tv_sec + usage.ru_utime.tv_usec,
				1000000 * usage.ru_stime.tv_sec + usage.ru_stime.tv_usec,
				(1000000000L * t1.tv_sec + t1.tv_nsec) / 1000L,
				usage.ru_maxrss * 1024);
	}
	if (signal_override) {
		int exit_signal = signal_override;
		exit_signal_name = lookup_signal_name(exit_signal);
		if (exit_signal_name) {
			fprintf(j->meta_file, "signal:%s\n", exit_signal_name);
		} else {
			fprintf(j->meta_file, "signal_number:%d\n", exit_signal);
		}
		fclose(j->meta_file);
		_exit(MINIJAIL_ERR_INIT);
	} else if (!WIFEXITED(init_exitstatus)) {
		if (j->flags.meta_file) {
			int exit_signal = -1;
			if (WIFSIGNALED(init_exitstatus))
				exit_signal = WTERMSIG(init_exitstatus);
			exit_signal_name = lookup_signal_name(exit_signal);
			if (exit_signal_name) {
				fprintf(j->meta_file, "signal:%s\n", exit_signal_name);
			} else {
				fprintf(j->meta_file, "signal_number:%d\n", exit_signal);
			}
			fclose(j->meta_file);
		}
		_exit(MINIJAIL_ERR_INIT);
	}
	if (j->flags.meta_file) {
		if (read(j->syscall_pipe_fds[0], &exit_syscall, sizeof(exit_syscall)) ==
				sizeof(exit_syscall)) {
			exit_signal = SIGSYS;
			exit_syscall_name = lookup_syscall_name(exit_syscall);
			if (exit_syscall_name) {
				fprintf(j->meta_file, "syscall:%s\n", exit_syscall_name);
			} else {
				fprintf(j->meta_file, "syscall_number:%d\n", exit_syscall);
			}
		}
		if (exit_signal != 0) {
			exit_signal_name = lookup_signal_name(exit_signal);
			if (exit_signal_name) {
				fprintf(j->meta_file, "signal:%s\n", exit_signal_name);
			} else {
				fprintf(j->meta_file, "signal_number:%d\n", exit_signal);
			}
		} else {
			fprintf(j->meta_file, "status:%d\n", WEXITSTATUS(init_exitstatus));
		}
		fclose(j->meta_file);
	}
	_exit(WEXITSTATUS(init_exitstatus));
}

int API minijail_from_fd(int fd, struct minijail *j)
{
	size_t sz = 0;
	size_t bytes = read(fd, &sz, sizeof(sz));
	char *buf;
	int r;
	if (sizeof(sz) != bytes)
		return -EINVAL;
	if (sz > USHRT_MAX)	/* Arbitrary sanity check */
		return -E2BIG;
	buf = malloc(sz);
	if (!buf)
		return -ENOMEM;
	bytes = read(fd, buf, sz);
	if (bytes != sz) {
		free(buf);
		return -EINVAL;
	}
	r = minijail_unmarshal(j, buf, sz);
	free(buf);
	return r;
}

int API minijail_to_fd(struct minijail *j, int fd)
{
	char *buf;
	size_t sz = minijail_size(j);
	ssize_t written;
	int r;

	if (!sz)
		return -EINVAL;
	buf = malloc(sz);
	r = minijail_marshal(j, buf, sz);
	if (r) {
		free(buf);
		return r;
	}
	/* Sends [size][minijail]. */
	written = write(fd, &sz, sizeof(sz));
	if (written != sizeof(sz)) {
		free(buf);
		return -EFAULT;
	}
	written = write(fd, buf, sz);
	if (written < 0 || (size_t) written != sz) {
		free(buf);
		return -EFAULT;
	}
	free(buf);
	return 0;
}

int setup_preload(void)
{
	char *oldenv = getenv(kLdPreloadEnvVar) ? : "";
	char *newenv = malloc(strlen(oldenv) + 2 + strlen(PRELOADPATH));
	if (!newenv)
		return -ENOMEM;

	/* Only insert a separating space if we have something to separate... */
	sprintf(newenv, "%s%s%s", oldenv, strlen(oldenv) ? " " : "",
		PRELOADPATH);

	/* setenv() makes a copy of the string we give it */
	setenv(kLdPreloadEnvVar, newenv, 1);
	free(newenv);
	return 0;
}

int setup_pipe(int fds[2])
{
	int r = pipe(fds);
	char fd_buf[11];
	if (r)
		return r;
	r = snprintf(fd_buf, sizeof(fd_buf), "%d", fds[0]);
	if (r <= 0)
		return -EINVAL;
	setenv(kFdEnvVar, fd_buf, 1);
	return 0;
}

int setup_pipe_end(int fds[2], size_t index)
{
	if (index > 1)
		return -1;

	close(fds[1 - index]);
	return fds[index];
}

int setup_and_dupe_pipe_end(int fds[2], size_t index, int fd)
{
	if (index > 1)
		return -1;

	close(fds[1 - index]);
	/* dup2(2) the corresponding end of the pipe into |fd|. */
	return dup2(fds[index], fd);
}

int setup_limits(struct minijail *j) {
	struct rlimit limit;

	if (j->flags.memory_limit) {
		limit.rlim_cur = limit.rlim_max = j->memory_limit;
		if (setrlimit(RLIMIT_AS, &limit)) {
			return -1;
		}
	}

	if (j->flags.output_limit) {
		limit.rlim_cur = limit.rlim_max = j->output_limit;
		if (setrlimit(RLIMIT_FSIZE, &limit)) {
			return -1;
		}

		/* Diable core dumping if there is an output limit. */
		limit.rlim_cur = limit.rlim_max = 0;
		if (setrlimit(RLIMIT_CORE, &limit)) {
			return -1;
		}
	}

	if (j->flags.stack_limit) {
		limit.rlim_cur = limit.rlim_max = j->stack_limit;
		if (setrlimit(RLIMIT_STACK, &limit)) {
			return -1;
		}
	}

	if (j->flags.time_limit) {
		limit.rlim_cur = (999 + j->time_limit) / 1000;
		limit.rlim_max = limit.rlim_cur + 1;
		if (setrlimit(RLIMIT_CPU, &limit)) {
			return -1;
		}

		ualarm((j->time_limit + j->extra_wall_time) * 1000, 0);
	}

	return 0;
}

int API minijail_run(struct minijail *j, const char *filename,
		     char *const argv[])
{
	return minijail_run_pid_pipes(j, filename, argv,
				      NULL, NULL, NULL, NULL);
}

int API minijail_run_pid(struct minijail *j, const char *filename,
			 char *const argv[], pid_t *pchild_pid)
{
	return minijail_run_pid_pipes(j, filename, argv, pchild_pid,
				      NULL, NULL, NULL);
}

int API minijail_run_pipe(struct minijail *j, const char *filename,
			  char *const argv[], int *pstdin_fd)
{
	return minijail_run_pid_pipes(j, filename, argv, NULL, pstdin_fd,
				      NULL, NULL);
}

int API minijail_run_pid_pipe(struct minijail *j, const char *filename,
			      char *const argv[], pid_t *pchild_pid,
			      int *pstdin_fd)
{
	return minijail_run_pid_pipes(j, filename, argv, pchild_pid, pstdin_fd,
				      NULL, NULL);
}

int API minijail_run_pid_pipes(struct minijail *j, const char *filename,
			       char *const argv[], pid_t *pchild_pid,
			       int *pstdin_fd, int *pstdout_fd, int *pstderr_fd)
{
	char *oldenv, *oldenv_copy = NULL;
	pid_t child_pid;
	int pipe_fds[2];
	int stdin_fds[2];
	int stdout_fds[2];
	int stderr_fds[2];
	int ret;
	/* We need to remember this across the minijail_preexec() call. */
	int pid_namespace = j->flags.pids;
	int do_init = j->flags.do_init;

	oldenv = getenv(kLdPreloadEnvVar);
	if (oldenv) {
		oldenv_copy = strdup(oldenv);
		if (!oldenv_copy)
			return -ENOMEM;
	}

	if (setup_preload())
		return -EFAULT;

	/*
	 * Make the process group ID of this process equal to its PID, so that
	 * both the Minijail process and the jailed process can be killed
	 * together.
	 * Don't fail on EPERM, since setpgid(0, 0) can only EPERM when
	 * the process is already a process group leader.
	 */
	if (setpgid(0 /* use calling PID */, 0 /* make PGID = PID */)) {
		if (errno != EPERM) {
			pdie("setpgid(0, 0)");
		}
	}

	/*
	 * Before we fork(2) and execve(2) the child process, we need to open
	 * a pipe(2) to send the minijail configuration over.
	 */
	if (setup_pipe(pipe_fds))
		return -EFAULT;

	/*
	 * Setup another pipe pair to receive the syscall number that caused the
	 * process to be killed, if any
	 */
	if (pipe(j->syscall_pipe_fds))
		return -EFAULT;

	/*
	 * If we want to write to the child process' standard input,
	 * create the pipe(2) now.
	 */
	if (pstdin_fd) {
		if (pipe(stdin_fds))
			return -EFAULT;
	}

	/*
	 * If we want to read from the child process' standard output,
	 * create the pipe(2) now.
	 */
	if (pstdout_fd) {
		if (pipe(stdout_fds))
			return -EFAULT;
	}

	/*
	 * If we want to read from the child process' standard error,
	 * create the pipe(2) now.
	 */
	if (pstderr_fd) {
		if (pipe(stderr_fds))
			return -EFAULT;
	}

	/* Use sys_clone() if and only if we're creating a pid namespace.
	 *
	 * tl;dr: WARNING: do not mix pid namespaces and multithreading.
	 *
	 * In multithreaded programs, there are a bunch of locks inside libc,
	 * some of which may be held by other threads at the time that we call
	 * minijail_run_pid(). If we call fork(), glibc does its level best to
	 * ensure that we hold all of these locks before it calls clone()
	 * internally and drop them after clone() returns, but when we call
	 * sys_clone(2) directly, all that gets bypassed and we end up with a
	 * child address space where some of libc's important locks are held by
	 * other threads (which did not get cloned, and hence will never release
	 * those locks). This is okay so long as we call exec() immediately
	 * after, but a bunch of seemingly-innocent libc functions like setenv()
	 * take locks.
	 *
	 * Hence, only call sys_clone() if we need to, in order to get at pid
	 * namespacing. If we follow this path, the child's address space might
	 * have broken locks; you may only call functions that do not acquire
	 * any locks.
	 *
	 * Unfortunately, fork() acquires every lock it can get its hands on, as
	 * previously detailed, so this function is highly likely to deadlock
	 * later on (see "deadlock here") if we're multithreaded.
	 *
	 * We might hack around this by having the clone()d child (init of the
	 * pid namespace) return directly, rather than leaving the clone()d
	 * process hanging around to be init for the new namespace (and having
	 * its fork()ed child return in turn), but that process would be crippled
	 * with its libc locks potentially broken. We might try fork()ing in the
	 * parent before we clone() to ensure that we own all the locks, but
	 * then we have to have the forked child hanging around consuming
	 * resources (and possibly having file descriptors / shared memory
	 * regions / etc attached). We'd need to keep the child around to avoid
	 * having its children get reparented to init.
	 *
	 * TODO(ellyjones): figure out if the "forked child hanging around"
	 * problem is fixable or not. It would be nice if we worked in this
	 * case.
	 */
	if (pid_namespace)
		child_pid = syscall(SYS_clone, CLONE_NEWPID | SIGCHLD, NULL);
	else
		child_pid = fork();

	if (child_pid < 0) {
		free(oldenv_copy);
		die("failed to fork child");
	}

	if (child_pid) {
		/* Restore parent's LD_PRELOAD. */
		if (oldenv_copy) {
			setenv(kLdPreloadEnvVar, oldenv_copy, 1);
			free(oldenv_copy);
		} else {
			unsetenv(kLdPreloadEnvVar);
		}
		unsetenv(kFdEnvVar);

		j->initpid = child_pid;

		/* Send marshalled minijail. */
		close(pipe_fds[0]);	/* read endpoint */
		ret = minijail_to_fd(j, pipe_fds[1]);
		close(pipe_fds[1]);	/* write endpoint */
		close(j->syscall_pipe_fds[0]); /* read endpoint */
		j->syscall_pipe_fds[0] = -1;
		close(j->syscall_pipe_fds[1]); /* write endpoint */
		j->syscall_pipe_fds[1] = -1;
		if (ret) {
			kill(j->initpid, SIGKILL);
			die("failed to send marshalled minijail");
		}

		if (pchild_pid)
			*pchild_pid = child_pid;

		/*
		 * If we want to write to the child process' standard input,
		 * set up the write end of the pipe.
		 */
		if (pstdin_fd)
			*pstdin_fd = setup_pipe_end(stdin_fds,
						    1	/* write end */);

		/*
		 * If we want to read from the child process' standard output,
		 * set up the read end of the pipe.
		 */
		if (pstdout_fd)
			*pstdout_fd = setup_pipe_end(stdout_fds,
						     0	/* read end */);

		/*
		 * If we want to read from the child process' standard error,
		 * set up the read end of the pipe.
		 */
		if (pstderr_fd)
			*pstderr_fd = setup_pipe_end(stderr_fds,
						     0	/* read end */);

		return 0;
	} else {
		close(pipe_fds[1]);	/* write endpoint */
	}
	free(oldenv_copy);

	/*
	 * If we want to write to the jailed process' standard input,
	 * set up the read end of the pipe.
	 */
	if (pstdin_fd) {
		if (setup_and_dupe_pipe_end(stdin_fds, 0 /* read end */,
					    STDIN_FILENO) < 0)
			die("failed to set up stdin pipe");
	}

	/*
	 * If we want to read from the jailed process' standard output,
	 * set up the write end of the pipe.
	 */
	if (pstdout_fd) {
		if (setup_and_dupe_pipe_end(stdout_fds, 1 /* write end */,
					    STDOUT_FILENO) < 0)
			die("failed to set up stdout pipe");
	}

	/*
	 * If we want to read from the jailed process' standard error,
	 * set up the write end of the pipe.
	 */
	if (pstderr_fd) {
		if (setup_and_dupe_pipe_end(stderr_fds, 1 /* write end */,
					    STDERR_FILENO) < 0)
			die("failed to set up stderr pipe");
	}

	/* Strip out flags that cannot be inherited across execve. */
	minijail_preexec(j);
	/* Jail this process and its descendants... */
	minijail_enter(j);

	if (pid_namespace && do_init) {
		/*
		 * pid namespace: this process will become init inside the new
		 * namespace. We don't want all programs we might exec to have
		 * to know how to be init. Normally |do_init == 1| we fork off
		 * a child to actually run the program. If |do_init == 0|, we
		 * let the program keep pid 1 and be init.
		 *
		 * If we're multithreaded, we'll probably deadlock here. See
		 * WARNING above.
		 */
		child_pid = fork();
		if (child_pid < 0)
			_exit(child_pid);
		else if (child_pid > 0) {
			close(j->syscall_pipe_fds[1]); /* write endpoint */
			j->syscall_pipe_fds[1] = -1;
			init(j, child_pid);	/* never returns */
		}
	}

	/* Move the child into its own process group to kill it easily */
	if (setsid() == -1) {
		die("setsid");
	}

	if (setup_limits(j)) {
		die("failed to set execution limits");
	}

	/*
	 * If we aren't pid-namespaced, or jailed program asked to be init:
	 *   calling process
	 *   -> execve()-ing process
	 * If we are:
	 *   calling process
	 *   -> init()-ing process
	 *      -> execve()-ing process
	 */
	_exit(execve(filename, argv, environ));
}

int API minijail_run_static(struct minijail *j, const char *filename,
			    char *const argv[])
{
	pid_t child_pid;
	int pid_namespace = j->flags.pids;
	int do_init = j->flags.do_init;

	if (j->flags.caps)
		die("caps not supported with static targets");

	if (pid_namespace)
		child_pid = syscall(SYS_clone, CLONE_NEWPID | SIGCHLD, NULL);
	else
		child_pid = fork();

	if (child_pid < 0) {
		die("failed to fork child");
	}
	if (child_pid > 0 ) {
		j->initpid = child_pid;
		return 0;
	}

	/*
	 * We can now drop this child into the sandbox
	 * then execve the target.
	 */

	j->flags.pids = 0;
	minijail_enter(j);

	if (pid_namespace && do_init) {
		/*
		 * pid namespace: this process will become init inside the new
		 * namespace. We don't want all programs we might exec to have
		 * to know how to be init. Normally |do_init == 1| we fork off
		 * a child to actually run the program. If |do_init == 0|, we
		 * let the program keep pid 1 and be init.
		 *
		 * If we're multithreaded, we'll probably deadlock here. See
		 * WARNING above.
		 */
		child_pid = fork();
		if (child_pid < 0)
			_exit(child_pid);
		else if (child_pid > 0)
			init(j, child_pid);	/* never returns */
	}

	if (setup_limits(j)) {
		die("failed to set execution limits");
	}

	if (j->flags.meta_file) {
		fclose(j->meta_file);
	}

	_exit(execve(filename, argv, environ));
}

int API minijail_kill(struct minijail *j)
{
	int st;
	if (kill(j->initpid, SIGTERM))
		return -errno;
	if (waitpid(j->initpid, &st, 0) < 0)
		return -errno;
	return st;
}

int API minijail_wait(struct minijail *j)
{
	int st;
	if (waitpid(j->initpid, &st, 0) < 0)
		return -errno;

	if (!WIFEXITED(st)) {
		int error_status = st;
		if (WIFSIGNALED(st)) {
			int signum = WTERMSIG(st);
			warn(j->log_level, "child process %d received signal %d",
			     j->initpid, signum);
			/*
			 * We return MINIJAIL_ERR_JAIL if the process received
			 * SIGSYS, which happens when a syscall is blocked by
			 * seccomp filters.
			 * If not, we do what bash(1) does:
			 * $? = 128 + signum
			 */
			if (signum == SIGSYS) {
				error_status = MINIJAIL_ERR_JAIL;
			} else {
				error_status = 128 + signum;
			}
		}
		return error_status;
	}

	int exit_status = WEXITSTATUS(st);
	if (exit_status != 0)
		info(j->log_level, "child process %d exited with status %d",
		     j->initpid, exit_status);

	return exit_status;
}

void API minijail_destroy(struct minijail *j)
{
	if (j->flags.seccomp_filter && j->filter_prog) {
		free(j->filter_prog->filter);
		free(j->filter_prog);
	}
	while (j->bindings_head) {
		struct binding *b = j->bindings_head;
		j->bindings_head = j->bindings_head->next;
		free(b->dest);
		free(b->src);
		free(b);
	}
	j->bindings_tail = NULL;
	if (j->user)
		free(j->user);
	if (j->chrootdir)
		free(j->chrootdir);
	if (j->chdir)
		free(j->chdir);
	free(j);
}

int concat_path(char *buffer, size_t buffer_len, const char *path)
{
	if (buffer == NULL || path == NULL)
		return 1;
	size_t len = strlen(buffer);
	size_t pathlen = strlen(path);
	if (len && buffer[len - 1] != '/' && path[0] != '/') {
		if (len + pathlen + 1 >= buffer_len)
			return -1;
		snprintf(buffer + len, buffer_len - len, "/%s", path);
	} else if (len && buffer[len - 1] == '/' && path[0] == '/') {
		if (len + pathlen >= buffer_len)
			return -1;
		strncpy(buffer + len, path + 1, buffer_len - len);
	} else {
		if (len + pathlen >= buffer_len)
			return -1;
		strncpy(buffer + len, path, buffer_len - len);
	}
	return 0;
}

int API minijail_get_path(const struct minijail *j, char *buffer,
		size_t buffer_len, const char *path)
{
	struct stat st;
	buffer[0] = '\0';

 	// Get the absolute path of the file, including the chdir if this is a
 	// relative path.
 	if (path[0] != '/') {
 		if (j->flags.chdir) {
 			if (0 != concat_path(buffer, buffer_len, j->chdir))
 				return 1;
 		} else if (j->flags.chroot) {
 			if (0 != concat_path(buffer, buffer_len, "/"))
 				return 1;
 		} else {
 			if (getcwd(buffer, buffer_len) == NULL)
 				return 1;
 		}
 	}
 	size_t len = strlen(buffer);
 	if (0 != concat_path(buffer, buffer_len - len, path))
 		return 1;
 	len = strlen(buffer);

 	// Get the binding with the longest match.
 	struct binding *cur = j->bindings_head, *best = NULL;
 	size_t best_len = 0, mount_len = 0;
 	while (j->bindings_tail) {
 		mount_len = strlen(cur->dest);
 		if (strncmp(cur->dest, buffer, mount_len) == 0 && mount_len > best_len) {
 			best_len = mount_len;
 			best = cur;
 		}
 		if (cur == j->bindings_tail)
 			break;
 		cur = cur->next;
 	}

 	const char* src_path = NULL;
 	if (best != NULL) {
 		src_path = best->src;
 	} else if (j->flags.chroot) {
 		src_path = j->chrootdir;
 		best_len = 1;
 	} else {
 		src_path = "/";
 		best_len = 1;
 	}
 	size_t src_len = strlen(src_path);
 	// Trim the trailing /, if any
 	if (src_path[src_len - 1] == '/') {
 		src_len--;
 	}
 	if (len - best_len + src_len + 2 >= buffer_len) {
 		fprintf(stderr, "Not enough space\n");
 		return 1;
 	}

	memmove(buffer + src_len + 1, buffer + best_len, len - best_len);
	strncpy(buffer, src_path, src_len);
	buffer[src_len] = '/';

	if (lstat(buffer, &st) == -1) {
		return 1;
	}

	// Regular file. All is good.
	if (S_ISREG(st.st_mode)) {
		return 0;
	}

	// Not a symbolic link. Disallowing.
	if (!S_ISLNK(st.st_mode)) {
		return 1;
	}

	char linkpath[PATH_MAX+1];
	ssize_t linklen;
	linklen = readlink(buffer, linkpath, sizeof(linkpath) - 1);
	if (linklen == -1) {
		fprintf(stderr, "Invalid symlink\n");
		return 1;
	}
	linkpath[linklen] = '\0';

	// Relativize the symbolic link.
	if (linkpath[0] != '/') {
		strncpy(buffer, path, buffer_len);
		char* basename = strrchr(buffer, '/');
		if (basename != NULL) {
			*basename = '\0';
			if (0 != concat_path(buffer, buffer_len - (basename - buffer), linkpath))
				return 1;
			if (strlen(buffer) > PATH_MAX)
				return 1;
			strncpy(linkpath, buffer, sizeof(linkpath));
		}
	}

	// Recursively try to figure out the real path.
	return minijail_get_path(j, buffer, buffer_len, linkpath);
}

/* The following are only used for omegaUp */
void API minijail_stack_limit(struct minijail *j, int stack_limit)
{
	j->flags.stack_limit = 1;
	j->stack_limit = stack_limit;
}

void API minijail_time_limit(struct minijail *j, int msec_limit)
{
	j->flags.time_limit = 1;
	j->time_limit = msec_limit;
}

void API minijail_extra_wall_time(struct minijail *j, int extra_msec)
{
	j->extra_wall_time = extra_msec;
}

void API minijail_output_limit(struct minijail *j, int byte_limit)
{
	j->flags.output_limit = 1;
	j->output_limit = byte_limit;
}

void API minijail_memory_limit(struct minijail *j, int byte_limit)
{
	j->flags.memory_limit = 1;
	j->memory_limit = byte_limit;
}

int API minijail_meta_file(struct minijail *j, const char *meta_path)
{
	j->flags.meta_file = 1;
	j->meta_file = fopen(meta_path, "w");
	if (j->meta_file == NULL) {
		return -1;
	}
	return 0;
}

void API minijail_close_all_files(struct minijail *j)
{
	j->flags.close_all_files = 1;
}

int API minijail_redirect_stdin(struct minijail *j, const char *stdin_path)
{
	int fd = open(stdin_path, O_RDONLY | O_NOFOLLOW);
	if (fd == -1) {
		perror("open(stdin)");
		return -1;
	}
	close(fd);
	int rc = minijail_bind(j, stdin_path, "/dev/stdin", 0);
	if (rc == 0) {
		j->flags.redirect_stdin = 1;
	}
	return rc;
}

int API minijail_redirect_stdout(struct minijail *j, const char *stdout_path)
{
	int fd = open(stdout_path, O_WRONLY | O_CREAT | O_NOFOLLOW, 0644);
	if (fd == -1) {
		perror("open(stdout)");
		return -1;
	}
	close(fd);
	int rc = minijail_bind(j, stdout_path, "/dev/stdout", 1);
	if (rc == 0) {
		j->flags.redirect_stdout = 1;
	}
	return rc;
}

int API minijail_redirect_stderr(struct minijail *j, const char *stderr_path)
{
	int fd = open(stderr_path, O_WRONLY | O_CREAT | O_NOFOLLOW, 0644);
	if (fd == -1) {
		perror("open(stderr)");
		return -1;
	}
	close(fd);
	int rc = minijail_bind(j, stderr_path, "/dev/stderr", 1);
	if (rc == 0) {
		j->flags.redirect_stderr = 1;
	}
	return rc;
}


text:
<?php

namespace Benski\ReservationBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class BenskiReservationBundle extends Bundle
{
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Cam class
 *
 * Stores information about the screen and the
 * camera position
 */

#ifndef CAM_H
#define CAM_H

#include <iostream>

#include <GL/glfw.h>

#include "Vector.h"

class Cam {
	Cam();

	Cam(const Cam&);
	void operator=(const Cam&);

	int screen_size_[2];
	float zoom_;
	Vector pos_;

	void SetupProjection();
	void SetupView();
public:
	static Cam& I();

	static void GLFWCALL ResizeCallback(int width, int height);

	int Width();
	int Height();
	int HalfWidth();
	int HalfHeight();

	void SetZoom(float zoom);
	void SetPos(Vector pos);

	Vector GetMaxCoord(float z);

	float  GetZoom();
	Vector GetPos();
};

#endif


text:
package com.rodrigodev.xgen4j.test.code.codeNumberCanBeEqualToRootCodeNumberForErrorsThatAreNotChildrenOfRootError;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public class ErrorCode {

    private final String id;
    private final String name;
    private final String numericId;
    private final int number;

    public ErrorCode(String name, int number){
        this.id = name;
        this.name = name;
        this.numericId = String.valueOf(number);
        this.number = number;
    }

    public ErrorCode(String name, int number, ErrorCode parent){
        this.id = parent.id + "." + name;
        this.name = name;
        this.numericId = parent.numericId + ":" + number;
        this.number = number;
    }

    public String id(){
        return id;
    }

    public String name(){
        return name;
    }

    public String numericId(){
        return numericId;
    }

    public int number(){
        return number;
    }

    @Override
    final public boolean equals(Object o){
        return o instanceof ErrorCode && ((ErrorCode)o).id.equals(id);
    }

    @Override
    public String toString(){
        return String.format("{id: '%s'}", id);
    }
}


text:
package com.github.krooken.edxvideoviewer;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CourseViewer extends Activity {

	private static final String TAG = "CourseViewer";

	private ArrayAdapter<String> adapter;
	private LinkedList<String> courseAddresses = new LinkedList<String>();
	private String cookieData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_viewer_screen);

		adapter = new ArrayAdapter<String>(this, R.layout.course_viewer_item);

		Intent intent = getIntent();
		cookieData = intent.getCharSequenceExtra("cookie_data").toString();
		HttpGetRequest getRequest = null;
		try {
			getRequest = new HttpGetRequest(new URI("https://courses.edx.org/dashboard"));
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		getRequest.addCookieHeader(cookieData);

		final HttpGetRequest request = getRequest;

		final Handler responseHandler = new Handler();

		Thread getRequestThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpGetRequest req = request;

				final String response = req.executeGetRequest();
				responseHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// Log.d(TAG, response);
						Pattern pattern = Pattern.compile("
\\s*<a href=\"([^<\"]+)\">([^<]+)\\s*
");
						Matcher matcher = pattern.matcher(response);
						while(matcher.find()) {
							Log.d(TAG, matcher.group(1));
							Log.d(TAG,  matcher.group(2));
							adapter.add(matcher.group(2));
							courseAddresses.add(matcher.group(1));
						}
						ListView listView = (ListView)findViewById(R.id.courses_list_view);
						listView.setAdapter(adapter);
						listView.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View v, int position, long id) {
								// TODO Auto-generated method stub
								Log.d(TAG, "Adapter: position: " + position + " id: " + id);
								Log.d(TAG, "Selected address: " + courseAddresses.get(position));
								Intent intent = new Intent(CourseViewer.this, CoursewareContentViewer.class);
								intent.putExtra("cookie_data", cookieData);
								intent.putExtra("course_info_address", courseAddresses.get(position));
								startActivity(intent);
							}
						});
					}
				});
			}
		});

		getRequestThread.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		super.onCreateOptionsMenu(menu);
		menu.add("Log off");

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		if(item.getTitle().equals("Log off")) {
			SharedPreferences.Editor prefsEditor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
			prefsEditor.putString("session_cookie", null);
			prefsEditor.putString("edxloggedin_cookie", null);
			prefsEditor.commit();
			Intent i = new Intent(this, LoginScreen.class);
			startActivity(i);
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}

}


text:
function [MARP,DP] = CRP_stats(CRP)

%This determines CRP stats: Mean Absolute Relative Phase (MARP) and
%Deviation Phase (DP)

MARP=nanmean(CRP);
DP=nanstd(CRP);

end


text:
function createStore(reducer) {
  const state = {};
  const dispatch = (action) => {
    reducer(state, action);
  };
  const getState = () => state;
  dispatch({});
  return { getState, dispatch };
}

function combineReducers(reducers) {
  return (state, action) => (
    Object.keys(reducers).reduce((nextState, key) => {
      nextState[key] = reducers[key](state, action);
      return nextState;
    }, {})
  );
}

export { createStore, combineReducers };


text:
/* @flow */
import {
  createStyleTagMarkup,
  objectReduce,
  clusterCache,
  RULE_TYPE,
  KEYFRAME_TYPE,
  FONT_TYPE,
  STATIC_TYPE
} from 'fela-utils'

const sheetMap = {
  fontFaces: FONT_TYPE,
  statics: STATIC_TYPE,
  keyframes: KEYFRAME_TYPE,
  rules: RULE_TYPE
}

export default function renderToMarkup(renderer: Object): string {
  const cacheCluster = clusterCache(renderer.cache, renderer.mediaQueryOrder)

  const basicMarkup = objectReduce(
    sheetMap,
    (markup, type, key) => {
      if (cacheCluster[key].length > 0) {
        markup += createStyleTagMarkup(cacheCluster[key], type)
      }

      return markup
    },
    ''
  )

  return objectReduce(
    cacheCluster.mediaRules,
    (markup, css, media) => {
      if (css.length > 0) {
        markup += createStyleTagMarkup(css, RULE_TYPE, media)
      }

      return markup
    },
    basicMarkup
  )
}


text:
#ifndef __JS_COCOSBUILDER_SPECIFICS_H__
#define __JS_COCOSBUILDER_SPECIFICS_H__

#include "scripting/js-bindings/manual/cocos2d_specifics.hpp"

class JSCCBAnimationWrapper: public JSCallbackWrapper
{
public:
    JSCCBAnimationWrapper(JS::HandleValue owner) : JSCallbackWrapper(owner) {}

    void animationCompleteCallback()
    {
        JSContext *cx = ScriptingCore::getInstance()->getGlobalContext();
        JS::RootedValue callback(cx, getJSCallbackFunc());
        JS::RootedValue thisObj(cx, getJSCallbackThis());
        if(!callback.isNullOrUndefined()  && !thisObj.isNullOrUndefined())
        {
            JS::RootedValue retval(cx);

            JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET

            JS::RootedObject jsThis(cx, thisObj.toObjectOrNull());
            JS::RootedValue jsCallback(cx, callback);
            JS_CallFunctionValue(cx, jsThis, jsCallback, JS::HandleValueArray::empty(), &retval);
        }
    }

};

#endif


text:
#include <aws/common/byte_buf.h>
#include <proof_helpers/make_common_data_structures.h>

void aws_byte_buf_from_c_str_harness() {
    /* parameter */
    const char *c_str = nondet_bool() ? NULL : ensure_c_str_is_allocated(MAX_BUFFER_SIZE);

    /* operation under verification */
    struct aws_byte_buf buf = aws_byte_buf_from_c_str(c_str);

    /* assertions */
    assert(aws_byte_buf_is_valid(&buf));
    assert(buf.allocator == NULL);
    if (buf.buffer) {
        assert(buf.len == strlen(c_str));
        assert(buf.capacity == buf.len);
        assert_bytes_match(buf.buffer, (uint8_t *)c_str, buf.len);
    } else {
        if (c_str) {
            assert(strlen(c_str) == 0);
        }
        assert(buf.len == 0);
        assert(buf.capacity == 0);
    }
}


text:
module.exports = function (grunt) {

	grunt.initConfig({
		jshint: {
			files: ['gruntfile.js', 'src/**/*.js']
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');

	grunt.registerTask('grunt-hint', ['jshint']);

};


text:
<?php

class DefaultController extends LandratesModuleController {

        public function actionIndex()
        {
                $this->render('index');
        }

}


text:
<?php

namespace Illuminate\View\Compilers\Concerns;

trait CompilesHelpers
{
    /**
     * Compile the CSRF statements into valid PHP.
     *
     * @return string
     */
    protected function compileCsrf()
    {
        return '<?php echo csrf_field(); ?>';
    }

    /*
     * Compile the "dd" statements into valid PHP.
     *
     * @param  string  $arguments
     * @return string
     */
    protected function compileDd($arguments)
    {
        return "<?php dd{$arguments}; ?>";
    }

    /*
     * Compile the method statements into valid PHP.
     *
     * @param  string  $method
     * @return string
     */
    protected function compileMethod($method)
    {
        return "<?php echo method_field{$method}; ?>";
    }
}


text:
<?php

namespace DVelopment\FastBillBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DVelopmentFastBillExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->getDefinition('d_velopment_fast_bill.api')
            ->addArgument($config['username'])
            ->addArgument($config['apiKey'])
        ;

    }
}


text:
package ee.ria.xroad.proxy.testsuite.testcases;

import ee.ria.xroad.proxy.testsuite.Message;
import ee.ria.xroad.proxy.testsuite.MessageTestCase;

import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static ee.ria.xroad.common.ErrorCodes.SERVER_CLIENTPROXY_X;
import static ee.ria.xroad.common.ErrorCodes.X_IO_ERROR;
import static ee.ria.xroad.common.ErrorCodes.X_SERVICE_FAILED_X;

/**
 * Client sends normal message, SP aborts connection (content type: text/xml).
 * Result: CP responds with RequestFailed
 */
public class ServerProxyConnectionAborted2 extends MessageTestCase {

    /**
     * Constructs the test case.
     */
    public ServerProxyConnectionAborted2() {
        requestFileName = "getstate.query";
    }

    @Override
    public String getProviderAddress(String providerName) {
        return "127.0.0.2";
    }

    @Override
    public AbstractHandler getServerProxyHandler() {
        return new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest,
                    HttpServletRequest request, HttpServletResponse response)
                    throws IOException {
                // Read all of the request.
                IOUtils.readLines(request.getInputStream());

                response.setContentType("text/xml");
                response.setContentLength(1000);
                response.getOutputStream().close();
                response.flushBuffer();
                baseRequest.setHandled(true);
            }
        };
    }

    @Override
    protected void validateFaultResponse(Message receivedResponse) {
        assertErrorCode(SERVER_CLIENTPROXY_X, X_SERVICE_FAILED_X, X_IO_ERROR);
    }
}


text:
<Record>
<Term>Caroverine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Calcium Channel Blocker</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Cardiovascular Agent/Antihypertensive Agent/Calcium Channel Blocker/Caroverine,/NCIThesaurus/Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Antispasmotic Agent/Caroverine</ClassificationPath>
<BroaderTerm>Calcium Channel Blocker</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Cardiovascular Agent</BroaderTerm>
<BroaderTerm>Caroverine</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Antihypertensive Agent</BroaderTerm>
<BroaderTerm>Antispasmotic Agent</BroaderTerm>
<BroaderTerm>Caroverine,</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>CAROVERINE</Synonym>
<Synonym>Caroverine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
define(["helper/Basic", "Tone/source/Noise", "helper/SourceTests", "helper/OutputAudio"],
	function (BasicTests, Noise, SourceTests, OutputAudio) {

	describe("Noise", function(){

		//run the common tests
		BasicTests(Noise);
		SourceTests(Noise);

		context("Get/Set", function(){

			it("can be constructed with an options object", function(){
				var noise = new Noise({
					"type" : "brown"
				});
				expect(noise.type).to.equal("brown");
				noise.dispose();
			});

			it("can set the playbackRate in the constructor", function(){
				var noise = new Noise({
					"playbackRate" : 2
				});
				expect(noise.playbackRate).to.equal(2);
				noise.dispose();
			});

			it("can set the playbackRate", function(){
				var noise = new Noise();
				noise.playbackRate = 3;
				expect(noise.playbackRate).to.equal(3);
				noise.dispose();
			});

		});

		context("Type", function(){

			it ("can be set to 3 noise types", function(){
				var noise = new Noise();
				var types = ["white", "brown", "pink"];
				for (var i = 0; i < types.length; i++){
					noise.type = types[i];
					expect(noise.type).to.equal(types[i]);

				}
				noise.dispose();
			});

			it ("cant set invalid type", function(){
				var noise = new Noise();
				expect(function(){
					noise.type = "else";
				}).to.throw(Error);
				noise.dispose();
			});

			it("outputs white noise", function(done){
				var noise;
				OutputAudio(function(dest){
					noise = new Noise("white");
					noise.connect(dest);
					noise.start();
				}, function(){
					noise.dispose();
					done();
				});
			});

			it("outputs pink noise", function(done){
				var noise;
				OutputAudio(function(dest){
					noise = new Noise("pink");
					noise.connect(dest);
					noise.start();
				}, function(){
					noise.dispose();
					done();
				});
			});

			it("outputs brown noise", function(done){
				var noise;
				OutputAudio(function(dest){
					noise = new Noise("brown");
					noise.connect(dest);
					noise.start();
				}, function(){
					noise.dispose();
					done();
				});
			});
		});

		/*it("be scheduled to start in the future", function(done){
			var noise;
			var offline = new Offline();
			Test.offlineTest(1, function(dest){
				noise = new Noise();
				noise.connect(dest);
				noise.start("+0.1");
			}, function(sample, time){
				if (sample !== 0){
					expect(time).to.be.at.least(0.1);
				}
			}, function(){
				noise.dispose();
				done();
			});
		});

		it("can set the noise types", function(){
			var noise = new Noise();
			noise.type = "brown";
			noise.type = "white";
			noise.type = "pink";
			//even after started
			noise.start();
			noise.type = "brown";
			noise.type = "white";
			noise.type = "pink";
			noise.stop();
			noise.dispose();
		});

		it("can be created with an options object", function(){
			var noise = new Noise({
				"type" : "brown"
			});
			expect(noise.type).to.equal("brown");
			noise.dispose();
		});

		it("can be set with an options object", function(){
			var noise = new Noise();
			noise.set({
				"type" : "pink"
			});
			expect(noise.type).to.equal("pink");
			noise.dispose();
		});*/
	});
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>FreeType-2.6.3 API Reference</title>

[Index]	[TOC]

FreeType-2.6.3 API Reference

Quick retrieval of advance values

Synopsis

FT_Get_Advance

FT_Get_Advances	FT_ADVANCE_FLAG_FAST_ONLY

This section contains functions to quickly extract advance values without handling glyph outlines, if possible.

FT_Get_Advance

Defined in FT_ADVANCES_H (freetype/ftadvanc.h).

  FT_EXPORT( FT_Error )
  FT_Get_Advance( FT_Face    face,
                  FT_UInt    gindex,
                  FT_Int32   load_flags,
                  FT_Fixed  *padvance );

Retrieve the advance value of a given glyph outline in an FT_Face.

input

face

The source FT_Face handle.

gindex

The glyph index.

load_flags

A set of bit flags similar to those used when calling FT_Load_Glyph, used to determine what kind of advances you need.

output

padvance

The advance value. If scaling is performed (based on the value of ‘load_flags’), the advance value is in 16.16 format. Otherwise, it is in font units.

If FT_LOAD_VERTICAL_LAYOUT is set, this is the vertical advance corresponding to a vertical layout. Otherwise, it is the horizontal advance in a horizontal layout.

return

FreeType error code. 0 means success.

note

This function may fail if you use FT_ADVANCE_FLAG_FAST_ONLY and if the corresponding font backend doesn't have a quick way to retrieve the advances.

A scaled advance is returned in 16.16 format but isn't transformed by the affine transformation specified by FT_Set_Transform.

[Index]	[Top]	[TOC]

FT_Get_Advances

Defined in FT_ADVANCES_H (freetype/ftadvanc.h).

  FT_EXPORT( FT_Error )
  FT_Get_Advances( FT_Face    face,
                   FT_UInt    start,
                   FT_UInt    count,
                   FT_Int32   load_flags,
                   FT_Fixed  *padvances );

Retrieve the advance values of several glyph outlines in an FT_Face.

input

face

The source FT_Face handle.

start

The first glyph index.

count

The number of advance values you want to retrieve.

load_flags

A set of bit flags similar to those used when calling FT_Load_Glyph.

output

padvance

The advance values. This array, to be provided by the caller, must contain at least ‘count’ elements.

If scaling is performed (based on the value of ‘load_flags’), the advance values are in 16.16 format. Otherwise, they are in font units.

If FT_LOAD_VERTICAL_LAYOUT is set, these are the vertical advances corresponding to a vertical layout. Otherwise, they are the horizontal advances in a horizontal layout.

return

FreeType error code. 0 means success.

note

This function may fail if you use FT_ADVANCE_FLAG_FAST_ONLY and if the corresponding font backend doesn't have a quick way to retrieve the advances.

Scaled advances are returned in 16.16 format but aren't transformed by the affine transformation specified by FT_Set_Transform.

[Index]	[Top]	[TOC]

FT_ADVANCE_FLAG_FAST_ONLY

Defined in FT_ADVANCES_H (freetype/ftadvanc.h).

#define FT_ADVANCE_FLAG_FAST_ONLY  0x20000000L

A bit-flag to be OR-ed with the ‘flags’ parameter of the FT_Get_Advance and FT_Get_Advances functions.

If set, it indicates that you want these functions to fail if the corresponding hinting mode or font driver doesn't allow for very quick advance computation.

Typically, glyphs that are either unscaled, unhinted, bitmapped, or light-hinted can have their advance width computed very quickly.

Normal and bytecode hinted modes that require loading, scaling, and hinting of the glyph outline, are extremely slow by comparison.

[Index]	[Top]	[TOC]


text:
<?php
$detail = isset($detail) ? $detail : FALSE;
?>
<script>
    $(document).ready(function () {
        $('#tr_aktifitas_mulai').timepicker({minuteStep: 1, showMeridian: false});
//        $('#tr_aktifitas_selesai').timepicker({showMeridian: false});
    });
    function hitungSelesai() {
        $('input[type=submit]').attr('disabled', true);
        var idAktifitas = $('#aktifitas_id').val();
        $.ajax({
            url: "<?php echo base_url(); ?>back_end/aktifitasharian/get_waktu/" + idAktifitas,
            success: function (resp) {
                var mulai = $('#tr_aktifitas_mulai').val().split(':');
                var selesai = new Date(0, 0, 0, mulai[0], parseInt(mulai[1]) + resp, 0);
                $('#tr_aktifitas_selesai').val(selesai.getHours() + ':' + selesai.getMinutes());
            }
        });
        $('input[type=submit]').attr('disabled', false);
    }
</script>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII" />
    <title>BfsIterator - SeqAn API Documentation</title>

      <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="lib/bootstrap-multiselect/css/bootstrap-multiselect.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />
      <link rel="stylesheet" href="css/common.less.css" type="text/css" media="screen" charset="utf-8" />

Spec
BfsIterator

Iterate vertices of a graph in breadth-first fashion.

    Extends

      Iter

    All Extended

    Iter

    All Impl'd

    IteratorAssociatedTypesConcept

    Defined in

      <seqan/graph_types.h>

    Signature

      Iterator<TGraph, BfsIterator>::Type;
template <typename TGraph, typename TSpec>
class Iter<TGraph, GraphIterator<InternalBfsIterator<TSpec> >;

Template Parameters

        TGraph
        The graph to iterate the vertices of.

Member Function Overview

    Iter::Iter();, Iter::Iter(iter);, Iter::Iter(graph, v);

Constructor.

Member Functions Inherited From Iter

Iter

Interface Function Overview

Interface Functions Inherited From IteratorAssociatedTypesConcept

operator*

value

getValue

Interface  Metafunction Overview

Interface Metafunctions Inherited From Iter

Container

IterComplementConst

IterMakeConst

Spec

Interface Metafunctions Inherited From IteratorAssociatedTypesConcept

Difference

GetValue

Pointer

Reference

Value

Detailed Description

The first signature is the signature of the corresponding graph's Iterator
metafunction call. The second call is the internal definition of the type. You should always get this type using
the metafunction call from the first signature.

Member Functions Detail

      Iter::Iter();
Iter::Iter(iter);
Iter::Iter(graph, v);

Constructor.

Parameters

                iter

      Other BfsIterator to copy from.

                graph

      The Graph to iterate vertices in BFS fashion.

                v

      The descriptor of the vertex to start BFS iteration.

Data Races

    Thread safety unknown!

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Dox Sources

/*!
 * @class BfsIterator
 *
 * @extends Iter
 *
 * @headerfile <seqan/graph_types.h>
 *
 * @brief Iterate vertices of a graph in breadth-first fashion.
 *
 * @signature Iterator<TGraph, BfsIterator>::Type;
 * @signature template <typename TGraph, typename TSpec> class Iter<TGraph,
 *            GraphIterator<InternalBfsIterator<TSpec> >;
 *
 * @tparam TGraph The graph to iterate the vertices of.
 *
 * The first signature is the signature of the corresponding @link
 * ContainerConcept#Iterator graph's Iterator @endlink metafunction call. The
 * second call is the internal definition of the type. You should always get
 * this type using the metafunction call from the first signature.
 *
 * @fn BfsIterator::BfsIterator
 *
 * @brief Constructor.
 *
 * @signature Iter::Iter();
 * @signature Iter::Iter(iter);
 * @signature Iter::Iter(graph, v);
 *
 * @param[in] iter Other BfsIterator to copy from.
 * @param[in] graph The @link Graph @endlink to iterate vertices in BFS fashion.
 * @param[in] v The descriptor of the vertex to start BFS iteration.
 */

        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>


text:
package org.cagrid.gaards.dorian.ca;

import gov.nih.nci.cagrid.common.FaultHelper;

import java.io.ByteArrayInputStream;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.cagrid.gaards.dorian.common.LoggingObject;
import org.cagrid.gaards.dorian.stubs.types.DorianInternalFault;
import org.cagrid.gaards.pki.CertUtil;
import org.cagrid.gaards.pki.KeyUtil;
import org.cagrid.tools.database.Database;

/**
 * @author Stephen Langella
 * @author Scott Oster
 * @author Shannon Hastings
 * @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
 *          Exp $
 */
public class CredentialsManager extends LoggingObject {

    public static String CREDENTIALS_TABLE = "certificate_authority";

    private Database db;

    private boolean dbBuilt = false;

    public CredentialsManager(Database db) {
        this.db = db;
    }

    public boolean hasCredentials(String alias) throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        boolean exists = false;
        try {
            c = db.getConnection();
            PreparedStatement s = c.prepareStatement("select count(*) from " + CREDENTIALS_TABLE + " where ALIAS= ?");
            s.setString(1, alias);
            ResultSet rs = s.executeQuery();
            if (rs.next()) {
                int count = rs.getInt(1);
                if (count > 0) {
                    exists = true;
                }
            }
            rs.close();
            s.close();
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Database Error, Error determining if the user " + alias
                + " has credentials.");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
        return exists;
    }

    public void deleteCredentials(String alias) throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        try {
            c = db.getConnection();
            PreparedStatement s = c.prepareStatement("delete from " + CREDENTIALS_TABLE + " where ALIAS= ? ");
            s.setString(1, alias);
            s.execute();
            s.close();
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Database Error, Error removing the credentials for the user " + alias
                + "!!!");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
    }

    public void addCredentials(String alias, String password, X509Certificate cert, PrivateKey key)
        throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        try {
            if (!hasCredentials(alias)) {
                c = db.getConnection();
                long serial = cert.getSerialNumber().longValue();
                String keyStr = KeyUtil.writePrivateKey(key, password);
                String certStr = CertUtil.writeCertificate(cert);
                PreparedStatement s = c.prepareStatement("INSERT INTO " + CREDENTIALS_TABLE
                    + " SET ALIAS= ?, SERIAL_NUMBER= ?, CERTIFICATE= ?, PRIVATE_KEY= ?");
                s.setString(1, alias);
                s.setLong(2, serial);
                s.setString(3, certStr);
                s.setString(4, keyStr);
                s.execute();
                s.close();
            }
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Error, could not add credentials to the credentials database.");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
    }

    public void addCertificate(String alias, X509Certificate cert) throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        try {
            if (!hasCredentials(alias)) {
                c = db.getConnection();
                long serial = cert.getSerialNumber().longValue();
                String keyStr = "";
                String certStr = CertUtil.writeCertificate(cert);
                PreparedStatement s = c.prepareStatement("INSERT INTO " + CREDENTIALS_TABLE
                    + " SET ALIAS= ?, SERIAL_NUMBER= ?, CERTIFICATE= ?, PRIVATE_KEY= ?");
                s.setString(1, alias);
                s.setLong(2, serial);
                s.setString(3, certStr);
                s.setString(4, keyStr);
                s.execute();
                s.close();
            }
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Error, could not add certificate to the credentials database.");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
    }

    public PrivateKey getPrivateKey(String alias, String password) throws DorianInternalFault, InvalidPasswordFault {
        this.buildDatabase();
        Connection c = null;
        PrivateKey key = null;
        String keyStr = null;
        try {
            c = db.getConnection();
            PreparedStatement s = c
                .prepareStatement("select PRIVATE_KEY from " + CREDENTIALS_TABLE + " where ALIAS= ?");
            s.setString(1, alias);
            ResultSet rs = s.executeQuery();
            if (rs.next()) {
                keyStr = rs.getString("PRIVATE_KEY");
            }
            rs.close();
            s.close();
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Database Error, Error obtaining the private key for the user " + alias
                + ".");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
        if (keyStr == null || keyStr.trim().equals("")) {
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("No PrivateKey exists for the user " + alias + ".");
            throw fault;
        }
        try {
            key = KeyUtil.loadPrivateKey(new ByteArrayInputStream(keyStr.getBytes()), password);
        } catch (Exception e) {
            InvalidPasswordFault fault = new InvalidPasswordFault();
            fault.setFaultString("Invalid Password Specified.");
            throw fault;
        }
        return key;
    }

    public X509Certificate getCertificate(String alias) throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        X509Certificate cert = null;
        try {
            c = db.getConnection();
            PreparedStatement s = c
                .prepareStatement("select CERTIFICATE from " + CREDENTIALS_TABLE + " where ALIAS= ?");
            s.setString(1, alias);
            ResultSet rs = s.executeQuery();
            if (rs.next()) {
                String certStr = rs.getString("CERTIFICATE");
                cert = CertUtil.loadCertificate(certStr);
            }
            rs.close();
            s.close();
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("Unexpected Database Error, Error obtaining the certificate for the user " + alias
                + ".");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
        if (cert == null) {
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("No Certificate exists for the user " + alias + ".");
            throw fault;
        }
        return cert;
    }

    public long getCertificateSerialNumber(String alias) throws DorianInternalFault {
        this.buildDatabase();
        Connection c = null;
        long sn = -1;
        try {
            c = db.getConnection();
            PreparedStatement s = c.prepareStatement("select SERIAL_NUMBER from " + CREDENTIALS_TABLE
                + " where ALIAS= ?");
            s.setString(1, alias);
            ResultSet rs = s.executeQuery();
            if (rs.next()) {
                sn = rs.getLong("SERIAL_NUMBER");
            }
            rs.close();
            s.close();
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault
                .setFaultString("Unexpected Database Error, Error obtaining the certificate serial number for the user "
                    + alias + ".");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        } finally {
            db.releaseConnection(c);
        }
        if (sn == -1) {
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("No Certificate exists for the user " + alias + ".");
            throw fault;
        }
        return sn;
    }

    private synchronized void buildDatabase() throws DorianInternalFault {
        try {
            if (!dbBuilt) {
                if (!this.db.tableExists(CREDENTIALS_TABLE)) {
                    String users = "CREATE TABLE " + CREDENTIALS_TABLE + " ("
                        + "ALIAS VARCHAR(255) NOT NULL PRIMARY KEY," + " SERIAL_NUMBER BIGINT NOT NULL,"
                        + "CERTIFICATE TEXT NOT NULL," + "PRIVATE_KEY TEXT NOT NULL,"
                        + "INDEX document_index (ALIAS));";
                    db.update(users);
                }
                this.dbBuilt = true;
            }
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("An unexpected database error occurred.");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        }
    }

    public void clearDatabase() throws DorianInternalFault {
        buildDatabase();
        try {
            db.update("delete from " + CREDENTIALS_TABLE);
        } catch (Exception e) {
            logError(e.getMessage(), e);
            DorianInternalFault fault = new DorianInternalFault();
            fault.setFaultString("An unexpected database error occurred.");
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            fault = (DorianInternalFault) helper.getFault();
            throw fault;
        }
    }

}


text:
<?php

namespace CronDog;

class ApiResponse
{
    function __construct($response)
    {
        $this->response = $response;
    }

    function __call($method, $params)
    {
        return $this->response->{$method}(...$params);
    }

    function __get($key)
    {
        return $this->response->json()[$key];
    }
}


text:
require 'spec_helper'
require 'deployable/patch/not_nil'

describe 'Object not_nil ' do

  it "string" do
    expect( "test".not_nil? ).to  be true
  end

  it "nil" do
    expect( nil.not_nil? ).to  be false
  end

end


text:
/* INIT */
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}

.dashboard.game-connected .no-connection {
z-index: 0;
display: block;
}
.dashboard.game-connected .has-connection {
display: none;
}
.dashboard.game-connected.yes .no-connection {
display: none;
}
.dashboard.game-connected.yes .has-connection {
z-index: 0;
display: block;
}

.gameOffline {
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 70px;
text-align: left;
color: #BB0000;
}

.truck-engineOn > .EngineFalse {
z-index: 1;
display: block;
width: 1920px;
height: 1080px;
background-image: url("images/bg-off.png");
}
.truck-engineOn > .EngineTrue {
display: none;
}
.truck-engineOn.yes > .EngineFalse {
display: none;
}
.truck-engineOn.yes > .EngineTrue {
z-index: 1;
display: block;
width: 1920px;
height: 1080px;
background-image: url("images/bg-on.png");
}

/*	hasJob from trailer-attached	*/
.hasJob > .JobFalse {
display: block;
}
.hasJob > .JobTrue {
display: none;
}
.hasJob.yes > .JobFalse {
display: none;
}
.hasJob.yes > .JobTrue {
display: block;
}

/* METERS*/
.truck-speed[data-type="meter"] {
	z-index: 2;
	visibility: visible;
	position: absolute;
	left: 535px;
	top: 125px;
	width: 10px;
	height: 85px;
	background-color: #cd0000;
	-webkit-transform: rotate(-114deg);
	-moz-transform: rotate(-114deg);
	-ms-transform: rotate(-114deg);
	-o-transform: rotate(-114deg);
	transform: rotate(-114deg);
	-webkit-transform-origin: 50% 400px;
	-moz-transform-origin: 50% 400px;
	-ms-transform-origin: 50% 400px;
	-o-transform-origin: 50% 400px;
	transform-origin: 50% 400px;
}
.truck-engineRpm {
	position: absolute;
	left: 1480px;
	top: 105px;
	width: 10px;
	height: 90px;
	background-color: #cd0000;
	-webkit-transform: rotate(-97deg);
	-moz-transform: rotate(-97deg);
	-ms-transform: rotate(-97deg);
	-o-transform: rotate(-97deg);
	transform: rotate(-97deg);
	-webkit-transform-origin: 50% 300px;
	-moz-transform-origin: 50% 300px;
	-ms-transform-origin: 50% 300px;
	-o-transform-origin: 50% 300px;
	transform-origin: 50% 300px;
}
.truck-fuel {
	position: absolute;
	left: 1452px;
	top: 546px;
	width: 10px;
	height: 60px;
	background-color: #cd0000;
	-webkit-transform: rotate(-96deg);
	-moz-transform: rotate(-96deg);
	-ms-transform: rotate(-96deg);
	-o-transform: rotate(-96deg);
	transform: rotate(-96deg);
	-webkit-transform-origin: 50% 198px;
	-moz-transform-origin: 50% 198px;
	-ms-transform-origin: 50% 198px;
	-o-transform-origin: 50% 198px;
	transform-origin: 50% 198px;
}

/* DATA [text] */
.truck-speedRounded,
.truck-cruiseControlSpeedRounded {
color: #2491b9;
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 70px;
position: absolute;
left: 431px;
top: 256px;
width: 178px;
height: 62px;
text-align: right;
}
.truck-cruiseControlSpeedRounded {
color: #24b999;
top: 404px;
}
.truck-displayedGear {
color: #35B32E;
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 70px;
position: absolute;
left: 484px;
top: 649px;
width: 125px;
height: 94px;
text-align: center;
}

.truck-odometer {
color: #1a6783;
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 70px;
position: absolute;
left: 375px;
top: 528px;
width: 345px;
height: 70px;
text-align: right;
}

.truck-retarderBrake,
.TextRPM {
font-size: 50px;
color: #1A6783;
font-family: Courier New, Courier, monospace;
font-weight: bold;
position: absolute;
left: 1420px;
top: 290px;
width: 140px;
height: 50px;
text-align: right;
}
.TextRPM > .TrueRPM {
color: #8AB800;
}
.truck-retarderBrake {
font-size: 60px;
top: 368px;
}
.RetarderIMG{
background-image: url("images/retarder-off.png");
position: absolute;
left: 1450px;
top: 375px;
width: 64px;
height: 50px;
}
.RetarderIMG.yes{
background-image: url("images/retarder.png");
}
.TextFuel {
color: #1a6783;
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 40px;
position: absolute;
left: 1230px;
top: 700px;
width: 150px;
height: 50px;
text-align: right;
}

/* Lights*/
.truck-cruiseControlOn {
background-image: url("images/cruise-off.png");
position: absolute;
left: 645px;
top: 400px;
width: 82px;
height: 72px;
}
.truck-cruiseControlOn.yes {
background-image: url("images/cruise-on.png");
}
.truck-blinkerLeftOn {
background-image: url("images/blinker-left-off.png");
position: absolute;
left: 130px;
top: 80px;
width: 102px;
height: 92px;
}
.truck-blinkerLeftOn.yes {
background-image: url("images/blinker-left-on.png");
}
.truck-blinkerRightOn {
background-image: url("images/blinker-right-off.png");
position: absolute;
left: 840px;
top: 80px;
width: 102px;
height: 92px;
}
.truck-blinkerRightOn.yes {
background-image: url("images/blinker-right-on.png");
}
.truck-lightsParkingOn {
background-image: url("images/Park_off.png");
position: absolute;
left: 30px;
top: 800px;
width: 80px;
height: 50px;
}
.truck-lightsParkingOn.yes {
background-image: url("images/Park.png");
}
.truck-lightsBeamLowOn {
background-image: url("images/Low-beam_off.png");
position: absolute;
left: 120px;
top: 800px;
width: 70px;
height: 50px;
}
.truck-lightsBeamLowOn.yes {
background-image: url("images/Low-beam.png");
}
.truck-lightsBeamHighOn {
background-image: url("images/High-beam_off.png");
position: absolute;
left: 200px;
top: 800px;
width: 79px;
height: 50px;
}
.truck-lightsBeamHighOn.yes {
background-image: url("images/High-beam.png");
}
.truck-parkBrakeOn {
background-image: url("images/HandBrake_off.png");
position: absolute;
left: 290px;
top: 800px;
width: 64px;
height: 50px;
}
.truck-parkBrakeOn.yes {
background-image: url("images/HandBrake.png");
}

.truck-airPressureWarningOn {
background-image: url("images/airPressWarn_false.png");
position: absolute;
left: 360px;
top: 800px;
width: 64px;
height: 50px;
}
.truck-airPressureWarningOn.yes {
background-image: url("images/airPressWarn.png");
}
.truck-lightsBeaconOn{
background-image: url("images/Beacon2_off.png");
position: absolute;
left: 1020px;
top: 920px;
width: 46px;
height: 38px;
}
.truck-lightsBeaconOn.yes{
background-image: url("images/Beacon2.png");
}
.truck-lightsAuxRoofOn{
background-image: url("images/Aux-off.png");
position: absolute;
left: 940px;
top: 920px;
width: 70px;
height: 50px;
}
.truck-lightsAuxRoofOn.yes{
background-image: url("images/AuxRoof.png");
}
.truck-lightsAuxFrontOn{
background-image: url("images/Aux-off.png");
position: absolute;
left: 870px;
top: 1000px;
width: 70px;
height: 50px;
}
.truck-lightsAuxFrontOn.yes{
background-image: url("images/AuxFront.png");
}
.truck-fuelWarningOn{
background-image: url("images/gasoline.png");
position: absolute;
left: 1300px;
top: 650px;
width: 40px;
height: 50px;
}
.truck-fuelWarningOn.yes{
background-image: url("images/gasoline_Warn.png");
}
.SLimit{
z-index: 1;
position: absolute;
display: block;
left: 20px;
top: 920px;
width: 140px;
height: 140px;
border-radius: 50% 50% 50% 50%;
background-color: #CC2900;
}
.SLimit > .Circle {
margin: 10px;
width: 120px;
height: 120px;
border-radius: 50% 50% 50% 50%;
background-color: #FFF;
}
.navigation-speedLimit {
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 55px;
position: absolute;
left: 40px;
top: 40px;
font-align: right;
}
/* Additional */
.truck-lightsBrakeOn{
background-image: url("images/Truck.png");
position: absolute;
left: 935px;
top: 940px;
width: 262px;
height: 136px;
}
.truck-lightsBrakeOn.yes{
background-image: url("images/Brakes2.png");
}
.trailer-attached {
background-image: url("images/trailer-off.png");
position: absolute;
left: 1080px;
top: 920px;
width: 278px;
height: 152px;
}
.trailer-attached.yes {
background-image: url("images/trailer-on.png");
}
.trailer-wear {
color: #D00;
font-family: Courier New, Courier, monospace;
font-weight: bold;
font-size: 50px;
position: absolute;
left: 1120px;
top: 950px;
width: 200px;
height: 80px;
text-align: right;
}

/* PROPERTIES OF VISUALIZATIONS */
.truck-speed,
.truck-speedRounded,
.truck-displayedGear,
.truck-odometer,
.TextFuel,
.TextRPM,
.TrueRPM,
.truck-retarderBrake,
.truck-lightsBeaconOn,
.trailer-attached,
.Display,
.trailer-wear,
.truck-wearEngine,
.truck-wearTransmission,
.truck-wearCabin,
.truck-wearChassis,
.truck-wearWheels {
z-index: 2;
visibility: visible;
}

/*	Display INIT	*/
.Display{
background-color: #29293D;
display: block;
z-index: 1;
position: absolute;
left: 1400px;
top: 485px;
width: 500px;
height: 570px;
}
.Menu{
margin-left: 50px;
z-index: 1;
display: inline;
background-color: #669900;
height: 50px;
font-weight: bold;
color: #FFF;
}
._link{
font-size: 22px;

}
.Menu > .Select{
border-bottom: solid 6px #CF9;
background-color: #077;
}
.Context{
z-index: 2;
height: 520px;
font-size: 20px;
color: yellow;
margin-top: 10px;
margin-left: 10px;
}
.alterBG .row:nth-child(odd) {
background-color: rgba(0,255,130,0.1);
}
/*	properties of table	*/
.tabela{
display: flex;
}
.rows{
flex-direction: column;
width: 100px;
margin-left: 15px;
margin-right: 15px;
}

.column{
margin-left: 5px;
margin-right: 5px;
font-family: Courier New, Courier, monospace;
font-size: 15px;
color: white;
text-align: right;
}
.text{
color: yellow;
}
.RSide{
text-align: right;
}
/*	end of table	*/

._TGreen {
font-size: 20px;
color: #00B000;
}
._TRedAbout{
padding-left: 50px;
color: red;
font-size: 30px;
font-weight: bold;
text-decoration: underline;
}
.game-time,
._TWhite {
color:#DDD;
}

/*	TABS	*/
/*	Cargo	*/
.job-deadlineTime,
.job-remainingTime {
  color: #54D9A8;
}

table._Tabela {
font-family: Courier New, Courier, monospace;
font-size: 20px;
width: 500px;
height: 200px;
}
table._Tabela th {
color: #aaa;
width: 150px;
text-align: right;
}
table._Tabela td {
text-align: left;
}

/*	Damage	*/
.truck-wearEngine,
.truck-wearTransmission,
.truck-wearCabin,
.truck-wearChassis,
.truck-wearWheels {
text-align: right;
font-size: 20px;
color: red;
}