/*
 * c8-wallet-keeper DIR: started by pam_c8wallet as the user with the login
 * password on stdin. Gives it once to c8-wallet over DIR/c8-wallet.sock,
 * then forgets it; gives up after KEEP_S (a session without c8-wallet).
 *
 * Anything running as the user could ask too; asking that the caller be
 * c8-wallet only keeps stray clients from taking it by mistake.
 */
#define _GNU_SOURCE
#include <errno.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>

#define KEEP_S 120
#define MAX 4096

static char pass[MAX];
static size_t len;

static int from_c8_wallet(int fd) {
	struct ucred cred;
	socklen_t size = sizeof(cred);
	if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &size) < 0 ||
			cred.uid != getuid()) {
		return 0;
	}
	char link[64], exe[PATH_MAX];
	snprintf(link, sizeof(link), "/proc/%d/exe", cred.pid);
	ssize_t n = readlink(link, exe, sizeof(exe) - 1);
	if (n <= 0) {
		return 0;
	}
	exe[n] = '\0';
	/* The installed one, by its whole path: a name alone is anyone's
	 * to give a program of their own */
	return strcmp(exe, C8_WALLET) == 0;
}

int main(int argc, char *argv[]) {
	if (argc != 2) {
		return 2;
	}
	mlock(pass, sizeof(pass));
	ssize_t n;
	while (len < MAX - 1 &&
			(n = read(STDIN_FILENO, pass + len, MAX - 1 - len)) > 0) {
		len += n;
	}
	close(STDIN_FILENO);
	if (len == 0) {
		return 0;
	}
	signal(SIGPIPE, SIG_IGN);
	umask(077);

	struct sockaddr_un addr = {.sun_family = AF_UNIX};
	if (snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/c8-wallet.sock",
			argv[1]) >= (int)sizeof(addr.sun_path)) {
		goto out;
	}
	int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	unlink(addr.sun_path); // a keeper from an earlier login
	if (sock < 0 || bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0 ||
			listen(sock, 4) < 0) {
		goto out;
	}

	time_t end = time(NULL) + KEEP_S;
	for (time_t now; (now = time(NULL)) < end;) {
		struct pollfd p = {sock, POLLIN, 0};
		if (poll(&p, 1, (end - now) * 1000) <= 0) {
			continue;
		}
		int c = accept4(sock, NULL, NULL, SOCK_CLOEXEC);
		if (c < 0) {
			continue;
		}
		if (from_c8_wallet(c)) {
			ssize_t w = write(c, pass, len);
			close(c);
			if (w == (ssize_t)len) {
				break;
			}
		} else {
			close(c);
		}
	}
	unlink(addr.sun_path);
out:
	explicit_bzero(pass, sizeof(pass));
	return 0;
}
