/* Disposable LD_PRELOAD scheduling probe; never linked into product binaries. */
#define _POSIX_C_SOURCE 200809L
#include <sys/select.h>

#include <dlfcn.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "http.h"

/* Observe the admission retry without stopping it or consuming kcgi's socket. */
int
pselect(int nfds, fd_set *reads, fd_set *writes, fd_set *excepts,
    const struct timespec *timeout, const sigset_t *mask)
{
	static int (*wait_ready)(int, fd_set *, fd_set *, fd_set *,
	    const struct timespec *, const sigset_t *);
	static int observed;
	const char *dir = getenv("SIGNET_PARSE_GATE");
	char path[512];
	int fd;

	if (wait_ready == NULL) {
		wait_ready = (int (*)(int, fd_set *, fd_set *, fd_set *,
		    const struct timespec *, const sigset_t *))dlsym(RTLD_NEXT, "pselect");
		if (wait_ready == NULL)
			_exit(126);
	}
	if (nfds == 0 && timeout != NULL && dir != NULL && !observed) {
		if (snprintf(path, sizeof(path), "%s/admission-wait", dir) >= (int)sizeof(path))
			_exit(127);
		fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
		if (fd == -1 || close(fd) == -1)
			_exit(128);
		observed = 1;
	}
	return wait_ready(nfds, reads, writes, excepts, timeout, mask);
}

/* Hold the real library's completed, unpruned request, without copying it. */
enum kcgi_err
khttp_fcgi_parse(struct kfcgi *fcgi, struct kreq *req)
{
	static enum kcgi_err (*parse)(struct kfcgi *, struct kreq *);
	static int gated;
	const char *dir;
	char path[512], pending[512], record[64];
	enum kcgi_err result;
	int fd, n;

	if (parse == NULL) {
		parse = (enum kcgi_err (*)(struct kfcgi *, struct kreq *))
		    dlsym(RTLD_NEXT, "khttp_fcgi_parse");
		if (parse == NULL)
			_exit(120);
	}
	result = parse(fcgi, req);
	dir = getenv("SIGNET_PARSE_GATE");
	if (result != KCGI_OK || gated || dir == NULL || req->fieldsz < 35000)
		return result;
	gated = 1;
	n = snprintf(path, sizeof(path), "%s/paused", dir);
	if (n < 0 || (size_t)n >= sizeof(path))
		_exit(121);
	n = snprintf(pending, sizeof(pending), "%s/preparing", dir);
	if (n < 0 || (size_t)n >= sizeof(pending))
		_exit(121);
	fd = open(pending, O_CREAT | O_EXCL | O_WRONLY, 0600);
	if (fd == -1)
		_exit(122);
	n = snprintf(record, sizeof(record), "%ld %zu\n", (long)getpid(), req->fieldsz);
	if (n < 0 || (size_t)n >= sizeof(record) ||
	    write(fd, record, (size_t)n) != n || close(fd) == -1)
		_exit(123);
	/* Publish readiness only after the complete PID/count record is visible. */
	if (rename(pending, path) == -1)
		_exit(125);
	if (raise(SIGSTOP) != 0)
		_exit(124);
	return result;
}
