#ifdef __linux__
#include <sys/prctl.h>
#endif
#include <sys/stat.h>
#include <sys/wait.h>

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>

#include "util.h"
#include "../vendor/sha256.h"

/* Overridden only by the standalone regression build, never by request/env. */
#ifndef SIGNET_CMD_TIMEOUT_MS
#define SIGNET_CMD_TIMEOUT_MS 30000
#endif

static int64_t
monotonic_ms(void)
{
	struct timespec ts;

	if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
		return -1;
	return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

int
run_cmd(char *const argv[], char *out, size_t outsz)
{
	int pfd[2] = { -1, -1 }, status, devnull, saved, exited = 0;
	int64_t now, deadline;
	pid_t pid, parent = getpid();
	sigset_t blocked, oldmask;
	siginfo_t info;
	struct pollfd pollfd;
	size_t used = 0;
	ssize_t n;
	char sink[4096];

	if (argv == NULL || argv[0] == NULL || (out != NULL && outsz == 0)) {
		errno = EINVAL;
		return -1;
	}
	if (out != NULL)
		out[0] = '\0';
	if ((now = monotonic_ms()) == -1)
		return -1;
	deadline = now + SIGNET_CMD_TIMEOUT_MS;
	if (out != NULL) {
		if (pipe(pfd) == -1)
			return -1;
		if (fcntl(pfd[0], F_SETFL, O_NONBLOCK) == -1) {
			close(pfd[0]);
			close(pfd[1]);
			return -1;
		}
	}
	/* Keep ownership of the zombie/PGID until cleanup, even with CGI handlers. */
	sigemptyset(&blocked);
	sigaddset(&blocked, SIGCHLD);
	if (sigprocmask(SIG_BLOCK, &blocked, &oldmask) == -1) {
		if (out != NULL) {
			close(pfd[0]);
			close(pfd[1]);
		}
		return -1;
	}
	if ((pid = fork()) == 0) {
		if (setpgid(0, 0) == -1)
			_exit(127);
#ifdef __linux__
		/* Real qpdf/pdfinfo must not outlive a killed API/worker. */
		if (prctl(PR_SET_PDEATHSIG, SIGKILL) == -1 || getppid() != parent)
			_exit(127);
#else
		(void)parent;
#endif
		if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1 ||
		    (devnull = open("/dev/null", O_RDWR)) == -1 ||
		    dup2(devnull, STDIN_FILENO) == -1 ||
		    dup2(out != NULL ? pfd[1] : devnull, STDOUT_FILENO) == -1)
			_exit(127);
		if (devnull > STDERR_FILENO)
			close(devnull);
		if (out != NULL) {
			if (pfd[0] > STDERR_FILENO)
				close(pfd[0]);
			if (pfd[1] > STDERR_FILENO)
				close(pfd[1]);
		}
		execvp(argv[0], argv);
		_exit(127);
	}
	if (out != NULL)
		close(pfd[1]);
	if (pid == -1)
		goto fail;
	/* Close the fork/setup race before a very short deadline can expire. */
	if (setpgid(pid, pid) == -1 && errno != EACCES && errno != ESRCH)
		goto fail;
	for (;;) {
		if ((now = monotonic_ms()) == -1)
			goto fail;
		if (now >= deadline) {
			errno = ETIMEDOUT;
			goto fail;
		}
		memset(&info, 0, sizeof(info));
		if (!exited && waitid(P_PID, pid, &info,
		    WEXITED | WNOHANG | WNOWAIT) == -1) {
			if (errno == EINTR)
				continue;
			if (errno == ECHILD)
				pid = -1; /* Never signal a PID no longer owned by us. */
			goto fail;
		}
		if (!exited && info.si_pid == pid) {
			exited = 1;
			/* A background descendant must not keep stdout (or work) alive. */
			kill(-pid, SIGKILL);
		}
		if (pfd[0] != -1) {
			/* One bounded read per iteration: a flood cannot starve the clock. */
			if (used + 1 < outsz)
				n = read(pfd[0], out + used,
				    outsz - 1 - used < sizeof(sink) ?
				    outsz - 1 - used : sizeof(sink));
			else
				n = read(pfd[0], sink, sizeof(sink));
			if (n > 0 && used + 1 < outsz) {
				used += (size_t)n;
				out[used] = '\0';
			} else if (n == 0) {
				close(pfd[0]);
				pfd[0] = -1;
			} else if (n == -1 && errno != EAGAIN && errno != EINTR)
				goto fail;
		}
		if (exited && pfd[0] == -1)
			break;
		pollfd.fd = pfd[0];
		pollfd.events = POLLIN;
		if (poll(&pollfd, 1, deadline - now < 20 ?
		    (int)(deadline - now) : 20) == -1 && errno != EINTR)
			goto fail;
	}
	while (waitpid(pid, &status, 0) == -1) {
		if (errno == EINTR)
			continue;
		if (errno == ECHILD)
			pid = -1;
		goto fail;
	}
	sigprocmask(SIG_SETMASK, &oldmask, NULL);
	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		log_err("command %s failed (status 0x%x)", argv[0], status);
		errno = EIO;
		return -1;
	}
	return 0;
fail:
	saved = errno;
	if (pid > 0) {
		kill(-pid, SIGKILL);
		kill(pid, SIGKILL);
		while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
			;
	}
	if (pfd[0] != -1)
		close(pfd[0]);
	sigprocmask(SIG_SETMASK, &oldmask, NULL);
	log_err("command %s failed: %s", argv[0], strerror(saved));
	errno = saved;
	return -1;
}

/* --- SHA-256 (vendored) ------------------------------------------------ */

int
sha256_file(const char *path, char hex[65])
{
	SHA256_CTX ctx;
	unsigned char hash[32];
	unsigned char buf[4096];
	size_t n;
	FILE *f;
	int i;

	if ((f = fopen(path, "rb")) == NULL)
		return -1;
	sha256_init(&ctx);
	while ((n = fread(buf, 1, sizeof(buf), f)) > 0)
		sha256_update(&ctx, buf, n);
	if (ferror(f)) {
		fclose(f);
		return -1;
	}
	fclose(f);
	sha256_final(&ctx, hash);
	for (i = 0; i < 32; i++)
		snprintf(hex + i * 2, 3, "%02x", hash[i]);
	return 0;
}

/* --- files ----------------------------------------------------------------- */

int
mkdir_p(const char *path, int mode)
{
	char buf[1024], *p;

	if (strlen(path) >= sizeof(buf))
		return -1;
	strcpy(buf, path);
	for (p = buf + 1; *p; p++) {
		if (*p != '/')
			continue;
		*p = '\0';
		if (mkdir(buf, mode) == -1 && errno != EEXIST)
			return -1;
		*p = '/';
	}
	if (mkdir(buf, mode) == -1 && errno != EEXIST)
		return -1;
	return 0;
}

int
write_file(const char *path, const void *data, size_t len, int mode)
{
	int fd;
	const char *p = data;
	ssize_t n;

	if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode)) == -1)
		return -1;
	while (len > 0) {
		if ((n = write(fd, p, len)) == -1) {
			if (errno == EINTR)
				continue;
			close(fd);
			return -1;
		}
		p += n;
		len -= (size_t)n;
	}
	return close(fd);
}

int
copy_file(const char *src, const char *dst)
{
	char buf[16384];
	int in, out, rc = 0;
	ssize_t n;

	if ((in = open(src, O_RDONLY)) == -1)
		return -1;
	if ((out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0640)) == -1) {
		close(in);
		return -1;
	}
	while ((n = read(in, buf, sizeof(buf))) > 0)
		if (write(out, buf, (size_t)n) != n) {
			rc = -1;
			break;
		}
	if (n == -1)
		rc = -1;
	close(in);
	if (close(out) == -1)
		rc = -1;
	return rc;
}

int
file_exists(const char *path)
{
	struct stat st;

	return stat(path, &st) == 0 && S_ISREG(st.st_mode);
}

/* validators now inlined in util.h */

uint32_t
utf8_next(const char **sp)
{
	const unsigned char *s = (const unsigned char *)*sp;
	uint32_t cp;
	int n, i;

	if (s[0] < 0x80) {
		cp = s[0]; n = 0;
	} else if ((s[0] & 0xE0) == 0xC0) {
		cp = s[0] & 0x1F; n = 1;
	} else if ((s[0] & 0xF0) == 0xE0) {
		cp = s[0] & 0x0F; n = 2;
	} else if ((s[0] & 0xF8) == 0xF0) {
		cp = s[0] & 0x07; n = 3;
	} else {
		*sp += 1;
		return 0xFFFD;
	}
	for (i = 1; i <= n; i++) {
		if ((s[i] & 0xC0) != 0x80) {
			*sp += i;
			return 0xFFFD;
		}
		cp = cp << 6 | (s[i] & 0x3F);
	}
	*sp += n + 1;
	return cp;
}

/* --- logging -------------------------------------------------------------- */

static const char *log_ident = "signet";

void
log_open(const char *ident)
{
	log_ident = ident;
	openlog(ident, LOG_PID, LOG_LOCAL0);
}

void
log_err(const char *fmt, ...)
{
	va_list ap;
	char message[512];

	va_start(ap, fmt);
	vsnprintf(message, sizeof(message), fmt, ap);
	va_end(ap);
	syslog(LOG_ERR, "%s", message);
	fprintf(stderr, "%s[%ld]: %s\n", log_ident, (long)getpid(), message);
}

/* Never copy arbitrary path components, UUIDs or query values into logs. */
static void
log_route(const char *path, char route[256])
{
	static const char *const names[] = {
		"me", "facsimile", "default", "retry", "facsimiles", "pim", "dam",
		"templates", "retire", "delete", "series", "docs", "file", "source",
		"proof", "stamped", "final", "save", "upload", "submit", "rerender",
		"decide", "unlink", "attrs", "resync"
	};
	const char *part = path ? path : "", *label;
	char id[37];
	size_t len, i, o = 0;
	int depth;

	for (depth = 0; depth < 5; depth++) {
		while (*part == '/')
			part++;
		if (*part == '\0' || *part == '?')
			break;
		len = strcspn(part, "/?");
		label = ":other";
		for (i = 0; i < sizeof(names) / sizeof(names[0]); i++)
			if (strlen(names[i]) == len && strncmp(part, names[i], len) == 0) {
				label = names[i];
				break;
			}
		if (len == 36) {
			memcpy(id, part, 36);
			id[36] = '\0';
			if (is_uuid(id))
				label = ":id";
		}
		o += (size_t)snprintf(route + o, 256 - o, "/%s", label);
		part += len;
	}
	if (o == 0)
		snprintf(route, 256, "/");
	else if (*part && *part != '?')
		snprintf(route + o, 256 - o, "/...");
}

void
log_request(const char *method, const char *path, const char *user,
    int status, const char *site)
{
	char route[256];

	if (status < 400)
		return;
	log_route(path, route);
	if (!is_safe_name(user))
		user = "anonymous";
	syslog(status >= 500 ? LOG_ERR : LOG_WARNING,
	    "request method=%s route=%s actor=%s status=%d site=%s",
	    method, route, user, status, site);
	fprintf(stderr, "%s[%ld]: request method=%s route=%s actor=%s status=%d site=%s\n",
	    log_ident, (long)getpid(), method, route, user, status, site);
}
