/*
 * c8-wallet: runs oo7-daemon (the Secret Service apps keep saved
 * passwords in, oo7 >= 0.6) for a cont8nuum session and opens the wallet.
 *
 * The daemon starts with the wallet locked; we open it by sending a
 * password to its PAM socket: first the one you logged in with (from
 * c8-wallet-keeper, which pam_c8wallet gave it), else one typed into
 * c8-askpass. When the typed one isn't the login password, the wallet is
 * changed to the login password, so it opens by itself next time however
 * that password was changed. While starting we hold the secrets name
 * ourselves (replaceable), so nothing else grabs it in the meantime;
 * after that we stay as the daemon's keeper, and stopping us stops it.
 */
#define _DEFAULT_SOURCE
#include <errno.h>
#include <gio/gio.h>
#include <glib-unix.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>

#include "oo7-pam.h"

#define SECRETS "org.freedesktop.secrets"
#define TRIES 3
#define START_MS 20000
#define UNLOCK_MS 3000

#ifndef C8_OO7_DAEMON
#define C8_OO7_DAEMON "/usr/local/libexec/oo7-daemon"
#endif

static struct {
	GDBusConnection *bus;
	GMainLoop *loop;
	pid_t daemon;
	char *socket; // the daemon's PAM socket
	int status;
} W = {.daemon = -1};

static void wipe(char *s) {
	if (s) {
		explicit_bzero(s, strlen(s));
		g_free(s);
	}
}

/* Runs c8-askpass; NULL when cancelled */
static char *ask(const char *prompt, bool retry) {
	char *askpass = g_find_program_in_path("c8-askpass");
	if (askpass == NULL) {
		fprintf(stderr, "c8-wallet: no c8-askpass in PATH\n");
		return NULL;
	}
	char *argv[] = {askpass, (char *)prompt, NULL};
	char **env = g_environ_setenv(g_get_environ(), "C8_ASKPASS_RETRY",
		retry ? "1" : "0", TRUE);
	/* Set by c8 for real sessions; a plain sudo prompt is no use here */
	env = g_environ_unsetenv(env, "C8_ASKPASS_FALLBACK");
	char *out = NULL;
	int wait = 0;
	GError *error = NULL;
	bool ok = g_spawn_sync(NULL, argv, env, G_SPAWN_DEFAULT, NULL, NULL,
		&out, NULL, &wait, &error);
	g_strfreev(env);
	g_free(askpass);
	if (!ok) {
		fprintf(stderr, "c8-wallet: %s\n", error->message);
		g_error_free(error);
		return NULL;
	}
	if (!g_spawn_check_wait_status(wait, NULL)) {
		wipe(out);
		return NULL;
	}
	out[strcspn(out, "\n")] = '\0';
	return out;
}

/* The password, asked twice for a new wallet (an empty one takes any) */
static char *password(bool exists, bool retry) {
	if (exists) {
		return ask("Type your wallet password. Your wallet is where apps "
			"keep the passwords you save.", retry);
	}
	for (bool again = false;; again = true) {
		char *first = ask(again ? "The passwords didn't match. Choose a "
			"password for your wallet again." : "Choose a password for your "
			"wallet. Apps keep the passwords you save in it.", false);
		if (first == NULL || first[0] == '\0') {
			if (first == NULL) {
				return NULL;
			}
			wipe(first);
			continue;
		}
		char *second = ask("Type the wallet password again.", false);
		if (second == NULL) {
			wipe(first);
			return NULL;
		}
		bool same = strcmp(first, second) == 0;
		wipe(second);
		if (same) {
			return first;
		}
		wipe(first);
	}
}

static bool request_name(void) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_sync(W.bus, "org.freedesktop.DBus",
		"/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName",
		g_variant_new("(su)", SECRETS, 0x1 /* allow replacement */),
		G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
	if (r == NULL) {
		fprintf(stderr, "c8-wallet: %s\n", error->message);
		g_error_free(error);
		return false;
	}
	guint32 reply;
	g_variant_get(r, "(u)", &reply);
	g_variant_unref(r);
	if (reply != 1 && reply != 4) {
		fprintf(stderr, "c8-wallet: " SECRETS " is taken already\n");
		return false;
	}
	return true;
}

static pid_t name_owner_pid(void) {
	GVariant *r = g_dbus_connection_call_sync(W.bus, "org.freedesktop.DBus",
		"/org/freedesktop/DBus", "org.freedesktop.DBus",
		"GetConnectionUnixProcessID", g_variant_new("(s)", SECRETS),
		G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL);
	guint32 pid = 0;
	if (r) {
		g_variant_get(r, "(u)", &pid);
		g_variant_unref(r);
	}
	return pid;
}

/* The wallet: the default collection, there and unlocked */
static bool opened(void) {
	GVariant *r = g_dbus_connection_call_sync(W.bus, SECRETS,
		"/org/freedesktop/secrets", "org.freedesktop.Secret.Service",
		"ReadAlias", g_variant_new("(s)", "default"), G_VARIANT_TYPE("(o)"),
		G_DBUS_CALL_FLAGS_NO_AUTO_START, 1000, NULL, NULL);
	if (r == NULL) {
		return false;
	}
	const char *path;
	g_variant_get(r, "(&o)", &path);
	GVariant *locked = NULL;
	if (strcmp(path, "/") != 0) {
		locked = g_dbus_connection_call_sync(W.bus, SECRETS, path,
			"org.freedesktop.DBus.Properties", "Get",
			g_variant_new("(ss)", "org.freedesktop.Secret.Collection",
				"Locked"), G_VARIANT_TYPE("(v)"),
			G_DBUS_CALL_FLAGS_NO_AUTO_START, 1000, NULL, NULL);
	}
	g_variant_unref(r);
	if (locked == NULL) {
		return false;
	}
	GVariant *v;
	g_variant_get(locked, "(v)", &v);
	bool open = g_variant_is_of_type(v, G_VARIANT_TYPE_BOOLEAN) &&
		!g_variant_get_boolean(v);
	g_variant_unref(v);
	g_variant_unref(locked);
	return open;
}

/* The login password, if pam_c8wallet kept it for us (c8-wallet-keeper);
 * NULL after autologin, a fingerprint, or a login it isn't set up for */
static char *login_password(void) {
	struct sockaddr_un addr = {.sun_family = AF_UNIX};
	snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/c8-wallet.sock",
		g_get_user_runtime_dir());
	int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (fd < 0) {
		return NULL;
	}
	if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		close(fd);
		return NULL;
	}
	char *pw = g_malloc0(4096);
	size_t len = 0;
	struct pollfd p = {fd, POLLIN, 0};
	ssize_t n;
	while (len < 4095 && poll(&p, 1, 2000) > 0 &&
			(n = read(fd, pw + len, 4095 - len)) > 0) {
		len += n;
	}
	close(fd);
	if (len == 0) {
		g_free(pw);
		return NULL;
	}
	return pw;
}

/* Starts the daemon; true once it owns the name, serves the wallet and
 * listens on its PAM socket */
static bool start_daemon(void) {
	char *argv[] = {C8_OO7_DAEMON, "--replace", NULL};
	GError *error = NULL;
	GPid pid;
	if (!g_spawn_async(NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD |
			G_SPAWN_STDIN_FROM_DEV_NULL, NULL, NULL, &pid, &error)) {
		fprintf(stderr, "c8-wallet: %s\n", error->message);
		g_error_free(error);
		return false;
	}
	W.daemon = pid;
	gint64 end = g_get_monotonic_time() + START_MS * 1000;
	while (g_get_monotonic_time() < end) {
		if (waitpid(pid, NULL, WNOHANG) == pid) {
			W.daemon = -1;
			fprintf(stderr, "c8-wallet: oo7-daemon quit while starting\n");
			return false;
		}
		if (name_owner_pid() == pid && access(W.socket, F_OK) == 0) {
			GVariant *r = g_dbus_connection_call_sync(W.bus, SECRETS,
				"/org/freedesktop/secrets", "org.freedesktop.Secret.Service",
				"ReadAlias", g_variant_new("(s)", "default"),
				G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NO_AUTO_START, 1000,
				NULL, NULL);
			if (r) {
				const char *path;
				g_variant_get(r, "(&o)", &path);
				bool there = strcmp(path, "/") != 0;
				g_variant_unref(r);
				if (there) {
					return true;
				}
			}
		}
		g_usleep(100 * 1000);
	}
	fprintf(stderr, "c8-wallet: oo7-daemon didn't start\n");
	kill(pid, SIGTERM);
	waitpid(pid, NULL, 0);
	W.daemon = -1;
	return false;
}

/* Gives the daemon a password; true once the wallet is open with it */
static bool unlock(const char *pw) {
	if (oo7_pam_send(W.socket, OO7_PAM_UNLOCK, g_get_user_name(), "", pw) < 0) {
		fprintf(stderr, "c8-wallet: can't reach %s\n", W.socket);
		return false;
	}
	gint64 end = g_get_monotonic_time() + UNLOCK_MS * 1000;
	while (g_get_monotonic_time() < end) {
		if (opened()) {
			return true;
		}
		g_usleep(100 * 1000);
	}
	return false;
}

/* Asks until the wallet opens: TRIES times, or until cancelled. A wallet
 * that opens with another password than the login one is changed to it. */
static void open_by_asking(bool exists, const char *login) {
	for (int i = 0; i < TRIES; i++) {
		char *pw;
		if (login && exists) {
			pw = ask("Your wallet's password isn't the one you sign in with. "
				"Type the wallet's password once, and it will open by itself "
				"from now on.", i > 0);
		} else {
			pw = password(exists, i > 0);
		}
		if (pw == NULL) {
			fprintf(stderr, "c8-wallet: not opened\n");
			return;
		}
		bool open = unlock(pw);
		if (open && login && strcmp(pw, login) != 0) {
			oo7_pam_send(W.socket, OO7_PAM_CHANGE_PASSWORD,
				g_get_user_name(), pw, login);
			fprintf(stderr, "c8-wallet: the wallet now has the login "
				"password\n");
		}
		wipe(pw);
		if (open) {
			return;
		}
	}
	fprintf(stderr, "c8-wallet: not opened\n");
}

static void daemon_exited(GPid pid, int status, void *data) {
	W.daemon = -1;
	g_spawn_check_wait_status(status, NULL);
	/* Gone by itself (or replaced): let systemd decide about a restart */
	W.status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
	g_main_loop_quit(W.loop);
}

static gboolean stop(void *data) {
	if (W.daemon > 0) {
		kill(W.daemon, SIGTERM);
	}
	W.status = 0;
	g_main_loop_quit(W.loop);
	return G_SOURCE_REMOVE;
}

int main(int argc, char *argv[]) {
	if (access(C8_OO7_DAEMON, X_OK) < 0) {
		fprintf(stderr, "c8-wallet: no " C8_OO7_DAEMON
			" (oo7 0.6 or newer; build-oo7.sh)\n");
		return 2;
	}
	GError *error = NULL;
	W.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (W.bus == NULL) {
		fprintf(stderr, "c8-wallet: %s\n", error->message);
		return 1;
	}
	/* Where the daemon listens (OO7_PAM_SOCKET moves it, for tests) */
	const char *sock = getenv("OO7_PAM_SOCKET");
	W.socket = sock ? g_strdup(sock) :
		g_strdup_printf("/run/user/%u/oo7-pam.sock", (unsigned)getuid());
	if (!request_name()) {
		return 1;
	}

	char *keyring = g_build_filename(g_get_user_data_dir(), "keyrings", "v1",
		"login.keyring", NULL);
	bool exists = g_file_test(keyring, G_FILE_TEST_EXISTS);
	g_free(keyring);

	if (!start_daemon()) {
		return 1;
	}
	/* The password you logged in with first; ask only if that won't do.
	 * A new wallet simply gets it. */
	char *login = login_password();
	if (!opened() && !(login && unlock(login))) {
		if (login) {
			fprintf(stderr, "c8-wallet: the login password isn't the "
				"wallet's; asking\n");
		}
		/* Not opened stays running: locked, it can still be opened later */
		open_by_asking(exists, login);
	}
	wipe(login);

	W.loop = g_main_loop_new(NULL, FALSE);
	g_child_watch_add(W.daemon, daemon_exited, NULL);
	g_unix_signal_add(SIGTERM, stop, NULL);
	g_unix_signal_add(SIGINT, stop, NULL);
	g_main_loop_run(W.loop);
	if (W.daemon > 0) {
		waitpid(W.daemon, NULL, 0);
	}
	return W.status;
}
