/*
 * c8-askpass: asks for a password the way Windows 8's User Account
 * Control did, for sudo -A (SUDO_ASKPASS), ssh and git (SSH_ASKPASS) and
 * anything else that follows the askpass convention:
 *
 *	c8-askpass PROMPT
 *
 * prints what was typed and a newline, and exits 0; exits 1 when the
 * user says No. SSH_ASKPASS_PROMPT=confirm asks Yes or No and answers
 * only by the exit status; =none just shows the message.
 *
 * The screen dims behind a card (a layer-shell overlay that keeps the
 * keyboard); without layer shell it is an ordinary window.
 */
#define _GNU_SOURCE
#include <math.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <glib.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-wayland.h>
#include "pixels.h"
#include "uac.h"

enum mode {
	ASK_PASSWORD,
	ASK_YESNO, // prints yes or no (ssh's new host question)
	ASK_CONFIRM, // the exit status says it
	ASK_INFO, // only a message
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct zwlr_layer_shell_v1 *shell;
	struct zwlr_layer_surface_v1 *layer;
	enum mode mode;
	char *prompt;
	/* Who asked: sudo, ssh, ... and what is being run */
	char *asker, *command, *run_as;
	int asker_pid;
	bool known;
	char *user, *real_name;
	cairo_surface_t *face;
	struct c8ui_widget *entry, *details;
	bool done;
	bool retry; // the same caller asked before: the last answer was wrong
} A;

/* Who is asking */

/* argv of a process, from its first'th word on, joined by spaces */
static char *proc_cmdline(int pid, int first, char ***argv_out) {
	gsize len = 0;
	char *data = uac_proc_read(pid, "cmdline", &len);
	if (data == NULL || len == 0) {
		g_free(data);
		return NULL;
	}
	GPtrArray *args = g_ptr_array_new_with_free_func(g_free);
	for (gsize at = 0; at < len; at += strlen(data + at) + 1) {
		g_ptr_array_add(args, g_strdup(data + at));
	}
	g_ptr_array_add(args, NULL);
	g_free(data);
	char **argv = (char **)g_ptr_array_free(args, FALSE);
	char *joined = (int)g_strv_length(argv) > first ?
		g_strjoinv(" ", argv + first) : g_strdup("");
	if (argv_out) {
		*argv_out = argv;
	} else {
		g_strfreev(argv);
	}
	return joined;
}

/* sudo's own options are left out of the command; -u says who it runs as */
static void read_sudo(int pid) {
	char **argv = NULL;
	g_free(proc_cmdline(pid, 0, &argv));
	if (argv == NULL) {
		return;
	}
	int i = 1;
	for (; argv[i] && argv[i][0] == '-'; i++) {
		if (strcmp(argv[i], "--") == 0) {
			i++;
			break;
		}
		/* Options that take a value, given separately */
		if (strchr("ugCDhprtT", argv[i][1]) && argv[i][2] == '\0' &&
				argv[i + 1]) {
			if (argv[i][1] == 'u') {
				A.run_as = g_strdup(argv[i + 1]);
			}
			i++;
		} else if (strncmp(argv[i], "--user=", 7) == 0) {
			A.run_as = g_strdup(argv[i] + 7);
		}
	}
	A.command = argv[i] ? g_strjoinv(" ", argv + i) : NULL;
	g_strfreev(argv);
}

/* A name is whatever a program calls itself (prctl, or its file's
 * name), so the blue band wants more. sudo is setuid root: its /proc
 * entry is root's, which nothing of ours can fake. The others must be
 * the system's own programs: root's files under /usr. */
static bool asker_is_root(int pid) {
	char path[64];
	struct stat st;
	snprintf(path, sizeof(path), "/proc/%d", pid);
	return stat(path, &st) == 0 && st.st_uid == 0;
}

static bool asker_is_system(int pid) {
	char link[64], exe[PATH_MAX];
	struct stat st;
	snprintf(link, sizeof(link), "/proc/%d/exe", pid);
	ssize_t n = readlink(link, exe, sizeof(exe) - 1);
	if (n <= 0) {
		return false;
	}
	exe[n] = '\0';
	return g_str_has_prefix(exe, "/usr/") && stat(exe, &st) == 0 &&
		st.st_uid == 0 && !(st.st_mode & (S_IWGRP | S_IWOTH));
}

static void find_asker(void) {
	A.asker_pid = getppid();
	A.asker = uac_proc_comm(A.asker_pid);
	if (A.asker == NULL) {
		A.asker = g_strdup("an app");
		return;
	}
	if (strcmp(A.asker, "sudo") == 0 && asker_is_root(A.asker_pid)) {
		A.known = true;
		read_sudo(A.asker_pid);
		if (A.run_as == NULL) {
			A.run_as = g_strdup("root");
		}
	} else {
		A.known = (strcmp(A.asker, "ssh") == 0 ||
			strcmp(A.asker, "ssh-add") == 0 || strcmp(A.asker, "git") == 0 ||
			strcmp(A.asker, "scp") == 0 || strcmp(A.asker, "sftp") == 0 ||
			strcmp(A.asker, "c8-wallet") == 0) &&
			asker_is_system(A.asker_pid);
		A.command = proc_cmdline(A.asker_pid, 0, NULL);
	}
}

/* When the process started, so a reused pid isn't taken for the same
 * caller: field 22 of /proc/PID/stat, counted after the name's ")" */
static unsigned long long start_time(int pid) {
	char *stat = uac_proc_read(pid, "stat", NULL);
	char *at = stat ? strrchr(stat, ')') : NULL;
	unsigned long long t = 0;
	for (int field = 2; at && *at; at++) {
		if (*at == ' ' && ++field == 22) {
			t = strtoull(at + 1, NULL, 10);
			break;
		}
	}
	g_free(stat);
	return t;
}

/* sudo asks again after a wrong password, by running us again: a note
 * in the runtime dir per caller tells us it's a second try. Notes of
 * callers that have gone are cleared out on the way. C8_ASKPASS_RETRY=0|1
 * overrides the guess. */
static void check_retry(void) {
	/* A caller that knows (c8-wallet confirming a new password) says so */
	const char *told = getenv("C8_ASKPASS_RETRY");
	if (told) {
		A.retry = strcmp(told, "1") == 0;
		return;
	}
	const char *dir = g_get_user_runtime_dir();
	DIR *d = opendir(dir);
	struct dirent *e;
	while (d && (e = readdir(d))) {
		int pid;
		if (sscanf(e->d_name, "c8-askpass-%d-", &pid) == 1 &&
				kill(pid, 0) < 0 && errno == ESRCH) {
			char *old = g_build_filename(dir, e->d_name, NULL);
			unlink(old);
			g_free(old);
		}
	}
	if (d) {
		closedir(d);
	}
	char name[96];
	snprintf(name, sizeof(name), "c8-askpass-%d-%llu", A.asker_pid,
		start_time(A.asker_pid));
	char *note = g_build_filename(dir, name, NULL);
	A.retry = g_file_test(note, G_FILE_TEST_EXISTS);
	g_file_set_contents(note, "", 0, NULL);
	g_free(note);
}

/* The account, and its picture as SDDM finds it */
static void read_account(void) {
	account_read(&A.user, &A.real_name, &A.face, UAC_FACE * 2);
}

/* Answering */

static void finish(int status, const char *answer) {
	if (A.done) {
		return;
	}
	A.done = true;
	if (status == 0 && answer) {
		fputs(answer, stdout);
		fputc('\n', stdout);
		fflush(stdout);
	}
	if (A.entry) {
		c8ui_entry_set(A.entry, ""); // not left lying in memory
	}
	c8ui_app_quit(A.app, status);
}

static void yes(void) {
	switch (A.mode) {
	case ASK_PASSWORD:
		/* sudo counts an empty one as a wrong try */
		if (c8ui_entry_get(A.entry)[0] != '\0') {
			finish(0, c8ui_entry_get(A.entry));
		}
		break;
	case ASK_YESNO:
		finish(0, "yes");
		break;
	default:
		finish(0, NULL);
		break;
	}
}

static void no(void) {
	if (A.mode == ASK_YESNO) {
		finish(0, "no"); // ssh wants the word
	} else {
		finish(1, NULL);
	}
}

static void yes_clicked(struct c8ui_widget *w, void *data) {
	yes();
}

static void no_clicked(struct c8ui_widget *w, void *data) {
	no();
}

static bool key(const struct c8ui_event *ev, void *data) {
	switch (ev->sym) {
	case XKB_KEY_Escape:
		no();
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		yes();
		return true;
	}
	return false;
}

static void details_clicked(struct c8ui_widget *w, void *data) {
	c8ui_widget_set_hidden(A.details, !A.details->hidden);
}

/* Building it */

static const char *question(void) {
	switch (A.mode) {
	case ASK_PASSWORD:
		if (A.run_as) {
			return "Do you want to allow this app to make changes to your "
				"PC?";
		}
		return A.known ? "This app needs your password or passphrase to "
			"continue." : "An app is asking for a password. Do you want to "
			"give it one?";
	case ASK_YESNO:
	case ASK_CONFIRM:
		return "Do you want to allow this?";
	case ASK_INFO:
	default:
		return "An app has a message for you.";
	}
}

static struct c8ui_widget *build_card(void) {
	struct c8ui_widget *body;
	struct c8ui_widget *card = uac_card_new(&A.known, question(), &body);
	if (A.run_as) {
		uac_row(body, "Program", A.command ? A.command : "a shell");
		uac_row(body, "Runs as", A.run_as);
	} else {
		/* ssh and the like say what they want in the prompt itself */
		struct c8ui_widget *p = c8ui_label_new(c8_stealth_show(A.prompt),
			C8UI_TEXT_BODY);
		c8ui_label_set_max_lines(p, 8);
		c8ui_widget_add(body, p);
		uac_row(body, "Asked by", A.asker);
	}

	A.details = c8ui_box_new(C8UI_VERTICAL, 4);
	c8ui_widget_set_hidden(A.details, true);
	c8ui_widget_add(body, A.details);
	char *who = g_strdup_printf("Asked by: %s (process %d)", A.asker,
		A.asker_pid);
	uac_caption(A.details, who);
	g_free(who);
	if (A.command) {
		char *cmd = g_strdup_printf("Command: %s", A.command);
		uac_caption(A.details, cmd);
		g_free(cmd);
	}
	if (A.run_as) {
		/* Otherwise the prompt is shown already */
		char *pr = g_strdup_printf("It asked: %s", A.prompt);
		uac_caption(A.details, pr);
		g_free(pr);
	}

	if (A.mode == ASK_PASSWORD) {
		c8ui_widget_add(body, c8ui_spacer_new(0, 8));
		if (A.retry) {
			c8ui_widget_add(body, c8ui_label_new("The password is incorrect. "
				"Try again.", C8UI_TEXT_BODY_STRONG));
		}
		c8ui_widget_add(body, c8ui_label_new(A.run_as ?
			"To continue, type your password, and then click Yes." :
			"To continue, type it, and then click Yes.", C8UI_TEXT_BODY));
		struct c8ui_widget *who_row = c8ui_box_new(C8UI_HORIZONTAL, 16);
		who_row->fill = true;
		c8ui_widget_add(body, who_row);
		c8ui_widget_add(who_row, c8ui_canvas_new(UAC_FACE, UAC_FACE,
			uac_draw_face, NULL, &A.face));
		struct c8ui_widget *col = c8ui_box_new(C8UI_VERTICAL, 6);
		col->expand = true;
		c8ui_widget_add(who_row, col);
		c8ui_widget_add(col, c8ui_label_new(A.real_name,
			C8UI_TEXT_BODY_STRONG));
		A.entry = c8ui_entry_new(NULL, "", yes_clicked, NULL);
		c8ui_entry_set_enter_only(A.entry, true); // not focus leaving
		c8ui_entry_set_password(A.entry, true);
		c8ui_entry_set_placeholder(A.entry, A.run_as ? "Password" :
			"Password or passphrase");
		A.entry->fill = true;
		c8ui_widget_add(col, A.entry);
	}

	uac_footer(card, A.mode == ASK_INFO ? "OK" : "Yes", details_clicked,
		yes_clicked, A.mode == ASK_INFO ? NULL : no_clicked, NULL, NULL);
	return card;
}

/* Layer shell */

static void layer_closed(void *data, struct zwlr_layer_surface_v1 *layer) {
	finish(1, NULL);
}

static const struct zwlr_layer_surface_v1_listener layer_listener = {
	.configure = uac_layer_configure,
	.closed = layer_closed,
};

/* No Wayland (an X11 session, a console): being the askpass for the whole
 * system, hand over to the one the distribution sets up */
static void fall_back(char **argv) {
	static const char *const others[] = {
		"/usr/libexec/ssh/ssh-askpass", // openSUSE
		"/usr/libexec/openssh/ssh-askpass", // Fedora
		"/usr/lib/ssh/ssh-askpass", // Arch, Debian
		"/usr/bin/ssh-askpass",
	};
	/* Once: whatever it runs may come back here through SSH_ASKPASS */
	if (getenv("C8_ASKPASS_FALLBACK")) {
		return;
	}
	setenv("C8_ASKPASS_FALLBACK", "1", 1);
	for (size_t i = 0; i < sizeof(others) / sizeof(others[0]); i++) {
		if (access(others[i], X_OK) == 0) {
			argv[0] = (char *)others[i];
			execv(others[i], argv);
		}
	}
}

int main(int argc, char *argv[]) {
	A.prompt = g_strdup(argc > 1 && argv[1][0] ? argv[1] : "Password:");
	g_strstrip(A.prompt);
	const char *kind = getenv("SSH_ASKPASS_PROMPT");
	if (kind && strcmp(kind, "confirm") == 0) {
		A.mode = ASK_CONFIRM;
	} else if (kind && strcmp(kind, "none") == 0) {
		A.mode = ASK_INFO;
	} else if (strstr(A.prompt, "(yes/no")) {
		A.mode = ASK_YESNO;
	}
	find_asker();
	if (A.mode == ASK_PASSWORD) {
		check_retry();
	}
	read_account();

	A.app = c8ui_app_new("org.cont8nuum.Askpass");
	if (A.app == NULL) {
		fprintf(stderr, "c8-askpass: can't reach the compositor\n");
		fall_back(argv);
		return 1;
	}
	struct c8ui_widget *card = build_card();
	A.shell = c8ui_app_bind(A.app, &zwlr_layer_shell_v1_interface, 4);
	struct c8ui_root *root;
	if (A.shell) {
		A.win = c8ui_window_new_bare(A.app);
		A.layer = uac_overlay_new(A.shell, A.win, "c8-askpass",
			&layer_listener);
		root = c8ui_window_root(A.win);
		c8ui_root_set_child(root, uac_cover(card));
	} else {
		/* Another compositor: a plain window will do */
		A.win = c8ui_window_new(A.app, "User Account Control", UAC_CARD_W,
			400);
		root = c8ui_window_root(A.win);
		c8ui_root_set_child(root, card);
	}
	c8ui_root_set_key_handler(root, key, NULL);
	if (A.entry) {
		c8ui_widget_grab_focus(A.entry);
	}
	c8ui_widget_enter(card);
	int status = c8ui_app_run(A.app);
	/* Closed without an answer: that's a No */
	return A.done ? status : 1;
}
