: asapien/signet

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378 
379 
380 
381 
382 
383 
384 
385 
386 
387 
388 
389 
390 
391 
392 
393 
394 
395 
396 
397 
398 
399 
400 
401 
402 
403 
404 
405 
406 
407 
408 
409 
#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);
}