/*
 * c8-login-picture: puts the user's lock screen picture where the SDDM
 * theme can show it, /var/lib/cont8nuum/login/USER.jpg. The login
 * screen runs as sddm, which can't read our homes, hence a copy, made
 * as root.
 *
 *   pkexec c8-login-picture set < picture.jpg
 *   pkexec c8-login-picture remove
 *
 * Run by the shell when the lock picture changes. Only through pkexec
 * (polkit action org.cont8nuum.login-picture: the active local user may,
 * without asking, as they may change their own AccountsService icon),
 * and only ever for the user who ran pkexec (PKEXEC_UID). The picture
 * comes in on stdin, so no path of the user's is opened as root. Nothing
 * here decodes it: like an AccountsService icon, the bytes are kept as
 * they are (a JPEG by its first bytes, 8 MiB at most) and the greeter
 * decodes them.
 */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define DIR_PARENT "/var/lib/cont8nuum"
#define DIR_LOGIN DIR_PARENT "/login"
#define MAX_BYTES (8 * 1024 * 1024)

static int fail(const char *what) {
	fprintf(stderr, "c8-login-picture: %s\n", what);
	return 1;
}

/* A name SDDM's theme can put in a file: URL as it is */
static int plain_name(const char *name) {
	if (name[0] == '\0' || name[0] == '.' || strlen(name) > 64) {
		return 0;
	}
	for (const char *p = name; *p; p++) {
		if (!((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
				(*p >= '0' && *p <= '9') || *p == '_' || *p == '-' ||
				*p == '.')) {
			return 0;
		}
	}
	return 1;
}

static int read_all(int fd, unsigned char **out, size_t *len) {
	size_t cap = 1 << 16, n = 0;
	unsigned char *buf = malloc(cap);
	if (buf == NULL) {
		return -1;
	}
	for (;;) {
		if (n == cap) {
			if (cap >= MAX_BYTES + 1) {
				break; // one more than allowed was read: too big
			}
			cap *= 2;
			if (cap > MAX_BYTES + 1) {
				cap = MAX_BYTES + 1;
			}
			unsigned char *more = realloc(buf, cap);
			if (more == NULL) {
				free(buf);
				return -1;
			}
			buf = more;
		}
		ssize_t r = read(fd, buf + n, cap - n);
		if (r < 0 && errno == EINTR) {
			continue;
		}
		if (r < 0) {
			free(buf);
			return -1;
		}
		if (r == 0) {
			break;
		}
		n += r;
	}
	*out = buf;
	*len = n;
	return 0;
}

static int write_all(int fd, const unsigned char *buf, size_t len) {
	while (len > 0) {
		ssize_t w = write(fd, buf, len);
		if (w < 0 && errno == EINTR) {
			continue;
		}
		if (w <= 0) {
			return -1;
		}
		buf += w;
		len -= w;
	}
	return 0;
}

int main(int argc, char *argv[]) {
	if (argc != 2 || (strcmp(argv[1], "set") != 0 &&
			strcmp(argv[1], "remove") != 0)) {
		return fail("usage: pkexec c8-login-picture set|remove");
	}
	const char *uid_s = getenv("PKEXEC_UID");
	if (geteuid() != 0 || uid_s == NULL || uid_s[0] == '\0') {
		return fail("run through pkexec");
	}
	char *end;
	errno = 0;
	unsigned long uid = strtoul(uid_s, &end, 10);
	if (errno || *end || uid == 0) {
		return fail("not for root");
	}
	struct passwd *pw = getpwuid((uid_t)uid);
	if (pw == NULL || !plain_name(pw->pw_name)) {
		return fail("no such user, or a name the login screen can't use");
	}
	char name[80];
	snprintf(name, sizeof(name), "%s.jpg", pw->pw_name);

	umask(022);
	/* Only root writes in /var/lib, so these are ours */
	if (mkdir(DIR_PARENT, 0755) != 0 && errno != EEXIST) {
		return fail("can't make " DIR_PARENT);
	}
	if (mkdir(DIR_LOGIN, 0755) != 0 && errno != EEXIST) {
		return fail("can't make " DIR_LOGIN);
	}
	int dir = open(DIR_LOGIN, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
	if (dir < 0) {
		return fail("can't open " DIR_LOGIN);
	}

	if (strcmp(argv[1], "remove") == 0) {
		if (unlinkat(dir, name, 0) != 0 && errno != ENOENT) {
			return fail("can't remove the picture");
		}
		return 0;
	}

	unsigned char *buf;
	size_t len;
	if (read_all(STDIN_FILENO, &buf, &len) != 0) {
		return fail("can't read the picture");
	}
	if (len > MAX_BYTES) {
		return fail("the picture is too big");
	}
	if (len < 3 || buf[0] != 0xff || buf[1] != 0xd8 || buf[2] != 0xff) {
		return fail("not a JPEG");
	}
	/* By rename, so the greeter never reads half of one */
	char tmp[96];
	snprintf(tmp, sizeof(tmp), ".%s.new", pw->pw_name);
	unlinkat(dir, tmp, 0);
	int fd = openat(dir, tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
		O_CLOEXEC, 0644);
	if (fd < 0) {
		return fail("can't write the picture");
	}
	if (write_all(fd, buf, len) != 0 || fsync(fd) != 0 || close(fd) != 0 ||
			renameat(dir, tmp, dir, name) != 0) {
		unlinkat(dir, tmp, 0);
		return fail("can't write the picture");
	}
	free(buf);
	return 0;
}
