/*
 * Archives. Looking inside one is gvfs's doing (an archive:// place, read
 * only, which the panes show like any folder); taking one apart and
 * making one are ours, with libarchive, as operations in the band like a
 * copy. An archive is somebody else's data: it is read by a helper in a
 * sandbox (c8-files-unpack, unpack.c), and nothing in it may land outside
 * the folder made for it. Making one reads the user's own files, here.
 */
#define _GNU_SOURCE
#include <archive.h>
#include <archive_entry.h>
#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "ops.h"

#define BLOCK (256 * 1024)

/* What we take apart and look into. By exact type: a .docx or .jar is a
 * zip underneath, but opens in its app */
static const char *const archive_types[] = {
	"application/zip",
	"application/x-tar",
	"application/x-compressed-tar",
	"application/x-bzip-compressed-tar",
	"application/x-bzip2-compressed-tar",
	"application/x-xz-compressed-tar",
	"application/x-zstd-compressed-tar",
	"application/x-lzma-compressed-tar",
	"application/x-lz4-compressed-tar",
	"application/x-lzip-compressed-tar",
	"application/x-tarz",
	"application/x-7z-compressed",
	"application/vnd.rar",
	"application/x-rar",
	"application/x-cpio",
	"application/x-cpio-compressed",
	"application/x-cd-image",
	"application/x-iso9660-image",
	"application/x-archive",
	"application/vnd.debian.binary-package",
	"application/x-rpm",
	"application/x-source-rpm",
	"application/vnd.ms-cab-compressed",
	"application/x-lha",
	"application/x-xar",
};

/* One file squeezed, no folder inside: taken apart, not looked into */
static const char *const squeezed_types[] = {
	"application/gzip",
	"application/x-bzip",
	"application/x-bzip2",
	"application/x-xz",
	"application/zstd",
	"application/x-lzma",
	"application/x-lz4",
	"application/x-lzip",
	"application/x-compress",
};

static bool one_of(const char *mime, const char *const *types, size_t n) {
	for (size_t i = 0; mime && i < n; i++) {
		if (strcmp(mime, types[i]) == 0) {
			return true;
		}
	}
	return false;
}

bool arc_is(const char *mime) {
	return one_of(mime, archive_types, G_N_ELEMENTS(archive_types)) ||
		one_of(mime, squeezed_types, G_N_ELEMENTS(squeezed_types));
}

bool arc_can_browse(const char *mime) {
	static int have = -1;
	if (have < 0) {
		/* gvfs-backends' archive mounter */
		have = g_strv_contains(g_vfs_get_supported_uri_schemes(
			g_vfs_get_default()), "archive");
	}
	return have && one_of(mime, archive_types, G_N_ELEMENTS(archive_types));
}

/* archive://HOST/, HOST being the file's URI escaped twice */
GFile *arc_root(GFile *file) {
	char *uri = g_file_get_uri(file);
	char *once = g_uri_escape_string(uri, NULL, FALSE);
	char *twice = g_uri_escape_string(once, NULL, FALSE);
	char *all = g_strdup_printf("archive://%s/", twice);
	GFile *root = g_file_new_for_uri(all);
	g_free(all);
	g_free(twice);
	g_free(once);
	g_free(uri);
	return root;
}

GFile *arc_file(GFile *inside) {
	if (!g_file_has_uri_scheme(inside, "archive")) {
		return NULL;
	}
	char *uri = g_file_get_uri(inside);
	const char *host = uri + strlen("archive://");
	const char *end = strchr(host, '/');
	char *twice = end ? g_strndup(host, end - host) : g_strdup(host);
	char *once = g_uri_unescape_string(twice, NULL);
	char *plain = once ? g_uri_unescape_string(once, NULL) : NULL;
	GFile *file = plain && plain[0] ? g_file_new_for_uri(plain) : NULL;
	g_free(plain);
	g_free(once);
	g_free(twice);
	g_free(uri);
	return file;
}

/* "photos.tar.gz" → "photos": what the folder it becomes is called */
char *arc_stem(const char *name) {
	char *stem = g_strdup(name);
	char *dot = strrchr(stem, '.');
	if (dot && dot != stem) {
		*dot = '\0';
		if (g_str_has_suffix(stem, ".tar") && strlen(stem) > 4) {
			stem[strlen(stem) - 4] = '\0';
		}
	}
	return stem;
}

const char *arc_format_name(enum arc_format format) {
	switch (format) {
	case ARC_ZIP:
		return "Zip (.zip)";
	case ARC_7Z:
		return "7-Zip (.7z)";
	case ARC_TAR_GZ:
		return "Tar, gzip (.tar.gz)";
	case ARC_TAR_XZ:
		return "Tar, xz (.tar.xz)";
	case ARC_TAR_ZST:
		return "Tar, Zstandard (.tar.zst)";
	case ARC_FORMATS:
		break;
	}
	return "";
}

const char *arc_format_ext(enum arc_format format) {
	switch (format) {
	case ARC_ZIP:
		return ".zip";
	case ARC_7Z:
		return ".7z";
	case ARC_TAR_GZ:
		return ".tar.gz";
	case ARC_TAR_XZ:
		return ".tar.xz";
	case ARC_TAR_ZST:
		return ".tar.zst";
	case ARC_FORMATS:
		break;
	}
	return "";
}

/* Little things */

static int remove_one(const char *path, const struct stat *st, int type,
		struct FTW *ftw) {
	remove(path);
	return 0;
}

/* Ours, made a moment ago: links in it are never followed */
static void remove_all(const char *path) {
	nftw(path, remove_one, 16, FTW_DEPTH | FTW_PHYS);
}

/* Gives path the name wanted in dir, or one like it that's free, never
 * taking the place of what is there. The file it is now, or NULL */
static GFile *move_in(const char *path, GFile *dir, const char *wanted,
		GError **error) {
	for (int tries = 0; tries < 100; tries++) {
		GFile *to = files_unique_child(dir, wanted);
		char *to_path = g_file_get_path(to);
		if (to_path && renameat2(AT_FDCWD, path, AT_FDCWD, to_path,
				RENAME_NOREPLACE) == 0) {
			g_free(to_path);
			return to;
		}
		int err = errno;
		g_free(to_path);
		g_object_unref(to);
		/* Taken since we looked: the next free name, then */
		if (err != EEXIST && err != ENOTEMPTY) {
			g_set_error_literal(error, G_IO_ERROR, g_io_error_from_errno(err),
				g_strerror(err));
			return NULL;
		}
	}
	g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_EXISTS,
		"No free name for it");
	return NULL;
}

/* Extracting. The reading is c8-files-unpack's, inside bubblewrap: /usr
 * read-only, the archive on its standard input, and one folder to write
 * to, a hidden one of ours beside where the files will be. A crafted
 * archive that gets the better of libarchive is still in there, with
 * nothing of the user's in reach and no network. No bwrap, no extracting.
 * One thing in the archive comes out as itself; several come out in a
 * folder with the archive's name. */

#define SANDBOX_OUT "/tmp/out"
#define SANDBOX_HELPER "/tmp/unpack"

static void add(GPtrArray *argv, const char *arg) {
	g_ptr_array_add(argv, g_strdup(arg));
}

/* As c8ui's thumbnails box theirs in (thumbnail.c) */
static GPtrArray *sandbox(const char *bwrap, const char *out,
		const char *stem) {
	GPtrArray *argv = g_ptr_array_new_with_free_func(g_free);
	add(argv, bwrap);
	add(argv, "--ro-bind");
	add(argv, "/usr");
	add(argv, "/usr");
	const char *dirs[] = { "/bin", "/sbin", "/lib", "/lib32", "/lib64" };
	for (size_t i = 0; i < G_N_ELEMENTS(dirs); i++) {
		char *target = g_file_read_link(dirs[i], NULL);
		if (target) {
			add(argv, "--symlink");
			add(argv, target);
			add(argv, dirs[i]);
			g_free(target);
		} else if (g_file_test(dirs[i], G_FILE_TEST_IS_DIR)) {
			add(argv, "--ro-bind");
			add(argv, dirs[i]);
			add(argv, dirs[i]);
		}
	}
	add(argv, "--ro-bind-try");
	add(argv, "/etc/ld.so.cache");
	add(argv, "/etc/ld.so.cache");
	add(argv, "--proc");
	add(argv, "/proc");
	add(argv, "--dev");
	add(argv, "/dev");
	add(argv, "--tmpfs");
	add(argv, "/tmp");
	add(argv, "--bind");
	add(argv, out);
	add(argv, SANDBOX_OUT);
	/* Ours may be installed outside /usr */
	add(argv, "--ro-bind");
	add(argv, UNPACK_PATH);
	add(argv, SANDBOX_HELPER);
	/* Nothing shared: no network, no other processes, no IPC */
	add(argv, "--unshare-all");
	add(argv, "--die-with-parent");
	add(argv, "--new-session");
	add(argv, "--clearenv");
	add(argv, "--setenv");
	add(argv, "LANG"); // names in the archive are turned to UTF-8 by it
	const char *lang = g_getenv("LANG");
	add(argv, lang && strstr(lang, "UTF-8") ? lang : "C.UTF-8");
	add(argv, "--chdir");
	add(argv, SANDBOX_OUT);
	add(argv, "--");
	add(argv, SANDBOX_HELPER);
	add(argv, SANDBOX_OUT);
	add(argv, stem);
	g_ptr_array_add(argv, NULL);
	return argv;
}

/* An archive that isn't a file on this PC (in another archive, on a
 * share without a path): fed to the helper through a pipe */
struct pump {
	GInputStream *in;
	int fd;
	GCancellable *cancel;
};

static gpointer pump_run(gpointer data) {
	struct pump *p = data;
	guchar *buf = g_malloc(BLOCK);
	gssize n;
	while ((n = g_input_stream_read(p->in, buf, BLOCK, p->cancel, NULL)) > 0) {
		gssize at = 0;
		while (at < n) {
			ssize_t w = write(p->fd, buf + at, n - at);
			if (w < 0 && errno == EINTR) {
				continue;
			}
			if (w <= 0) {
				goto out; // the helper went
			}
			at += w;
		}
	}
out:
	g_free(buf);
	close(p->fd);
	g_object_unref(p->in);
	g_object_unref(p->cancel);
	g_free(p);
	return NULL;
}

/* The archive as a descriptor the helper reads: the file itself (it can
 * then seek, which zip likes and 7z needs), or a pipe we fill */
static int archive_fd(struct op *op, GFile *file, GThread **pump,
		GError **error) {
	char *path = g_file_get_path(file);
	int fd = path ? open(path, O_RDONLY | O_CLOEXEC) : -1;
	g_free(path);
	if (fd >= 0) {
		return fd;
	}
	GInputStream *in = G_INPUT_STREAM(g_file_read(file, op_cancellable(op),
		error));
	if (in == NULL) {
		return -1;
	}
	int ends[2];
	if (pipe2(ends, O_CLOEXEC) != 0) {
		g_set_error_literal(error, G_IO_ERROR, g_io_error_from_errno(errno),
			g_strerror(errno));
		g_object_unref(in);
		return -1;
	}
	struct pump *p = g_new0(struct pump, 1);
	p->in = in;
	p->fd = ends[1];
	p->cancel = g_object_ref(op_cancellable(op));
	*pump = g_thread_new("archive-pump", pump_run, p);
	return ends[0];
}

static void helper_cancelled(GCancellable *cancel, gpointer data) {
	g_subprocess_force_exit(data);
}

/* Runs the helper on file into dir (ours, empty), hearing how it goes */
static void unpack(struct op *op, GFile *file, const char *name,
		const char *dir, const char *stem, gint64 base) {
	static char *bwrap;
	static gsize looked;
	if (g_once_init_enter(&looked)) {
		bwrap = g_find_program_in_path("bwrap");
		g_once_init_leave(&looked, 1);
	}
	if (bwrap == NULL) {
		op_fail(op, name, "Archives are only opened inside bubblewrap "
			"(bwrap), which isn't installed");
		return;
	}
	GError *error = NULL;
	GThread *pump = NULL;
	int control[2] = { -1, -1 };
	int in = archive_fd(op, file, &pump, &error);
	if (in < 0 || pipe2(control, O_CLOEXEC) != 0) {
		op_fail(op, name, error ? error->message : g_strerror(errno));
		g_clear_error(&error);
		if (in >= 0) {
			close(in);
		}
		goto out;
	}
	GPtrArray *argv = sandbox(bwrap, dir, stem);
	GSubprocessLauncher *launcher = g_subprocess_launcher_new(
		G_SUBPROCESS_FLAGS_STDOUT_PIPE);
	g_subprocess_launcher_take_stdin_fd(launcher, in);
	g_subprocess_launcher_take_fd(launcher, control[0], 3);
	GSubprocess *helper = g_subprocess_launcher_spawnv(launcher,
		(const char *const *)argv->pdata, &error);
	g_object_unref(launcher); // closes the helper's ends here
	g_ptr_array_unref(argv);
	if (helper == NULL) {
		op_fail(op, name, error->message);
		g_clear_error(&error);
		close(control[1]);
		goto out;
	}
	gulong handler = g_cancellable_connect(op_cancellable(op),
		G_CALLBACK(helper_cancelled), helper, NULL);
	GDataInputStream *lines = g_data_input_stream_new(
		g_subprocess_get_stdout_pipe(helper));
	bool failed = false;
	char *line;
	while ((line = g_data_input_stream_read_line(lines, NULL, NULL, NULL))) {
		/* What it says is the archive's as much as its own: taken as
		 * text to show, nothing more */
		char *text = line[0] && line[1] == ' ' ?
			g_utf8_make_valid(line + 2, -1) : NULL;
		if (text == NULL) {
		} else if (line[0] == 'D') {
			op_set_done(op, base + g_ascii_strtoll(text, NULL, 10));
		} else if (line[0] == 'C') {
			char *current = g_strcompress(text);
			op_set_current(op, current);
			g_free(current);
		} else if (line[0] == 'F') {
			char *tab = strchr(text, '\t');
			if (tab) {
				*tab = '\0';
			}
			char *what = g_strcompress(text);
			char *why = tab ? g_strcompress(tab + 1) : NULL;
			op_fail(op, what, why);
			failed = true;
			g_free(what);
			g_free(why);
		} else if (line[0] == 'W') {
			char *typed = op_ask_password(op, name, text[0] == '1');
			char *escaped = typed ? g_strescape(typed, "") : NULL;
			char *answer = escaped ? g_strdup_printf("P %s\n", escaped) :
				g_strdup("N\n");
			if (write(control[1], answer, strlen(answer)) < 0) {
				/* It went meanwhile: the loop ends by itself */
			}
			g_free(answer);
			g_free(escaped);
			g_free(typed);
		}
		g_free(text);
		g_free(line);
	}
	g_cancellable_disconnect(op_cancellable(op), handler);
	g_subprocess_wait(helper, NULL, NULL);
	if (!op_cancelled(op) && !failed && !(g_subprocess_get_if_exited(helper) &&
			g_subprocess_get_exit_status(helper) == 0)) {
		op_fail(op, name, "It couldn't be read as an archive");
	}
	g_object_unref(lines);
	g_object_unref(helper);
	close(control[1]);
out:
	if (pump) {
		g_thread_join(pump);
	}
}

void arc_extract(struct op *op, GFile *file, GFile *into, gint64 base) {
	char *name = g_file_get_basename(file);
	char *stem = arc_stem(name);
	if (stem[0] == '\0' || stem[0] == '.' || stem[0] == '-') {
		g_free(stem);
		stem = g_strdup("Extracted");
	}
	char *into_path = g_file_get_path(into);
	char *dir = NULL;
	GError *error = NULL;
	if (into_path == NULL) {
		op_fail(op, name, "Files can't be extracted to here");
		goto out;
	}
	/* Not mkdtemp: its folder is ours alone, and this one may become the
	 * folder the files stay in */
	for (int tries = 0; dir == NULL && tries < 100; tries++) {
		dir = g_strdup_printf("%s/.%s.%08x", into_path, stem,
			g_random_int());
		if (mkdir(dir, 0777) != 0) {
			g_clear_pointer(&dir, g_free);
			if (errno != EEXIST) {
				break;
			}
		}
	}
	if (dir == NULL) {
		op_fail(op, name, g_strerror(errno));
		goto out;
	}
	unpack(op, file, name, dir, stem, base);
	if (op_cancelled(op)) {
		remove_all(dir);
		goto out;
	}
	/* What came out, even if not all of it did */
	char *only = NULL;
	int count = 0;
	GDir *d = g_dir_open(dir, 0, NULL);
	const char *child;
	while (d && (child = g_dir_read_name(d))) {
		if (count++ == 0) {
			only = g_strdup(child);
		}
	}
	if (d) {
		g_dir_close(d);
	}
	GFile *result = NULL;
	if (count == 1) {
		char *path = g_build_filename(dir, only, NULL);
		result = move_in(path, into, only, &error);
		g_free(path);
		if (result) {
			rmdir(dir);
		}
	} else if (count > 1) {
		result = move_in(dir, into, stem, &error);
	} else {
		rmdir(dir);
	}
	if (error) {
		op_fail(op, name, error->message);
		g_clear_error(&error);
		remove_all(dir);
	}
	if (result) {
		op_made(op, result);
		g_object_unref(result);
	}
	g_free(only);
out:
	g_free(dir);
	g_free(into_path);
	g_free(stem);
	g_free(name);
}

/* Compressing */

struct pack {
	struct op *op;
	struct archive *a;
	bool broken; // the archive itself can't go on
	guchar buf[BLOCK];
};

/* path on the disk goes in as name; a folder with all under it */
static void pack_add(struct pack *p, const char *path, const char *name) {
	struct op *op = p->op;
	if (p->broken || op_cancelled(op)) {
		return;
	}
	struct stat st;
	if (lstat(path, &st) != 0) {
		op_fail(op, name, g_strerror(errno));
		return;
	}
	if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode)) {
		return;
	}
	char *base = g_path_get_basename(path);
	op_set_current(op, base);
	g_free(base);
	int fd = -1;
	if (S_ISREG(st.st_mode)) {
		fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
		if (fd < 0 || fstat(fd, &st) != 0) {
			op_fail(op, name, g_strerror(errno));
			if (fd >= 0) {
				close(fd);
			}
			op_set_done(op, op_get_done(op) + MAX(st.st_size, 1));
			op_item_done(op);
			return;
		}
	}
	struct archive_entry *e = archive_entry_new();
	archive_entry_copy_stat(e, &st);
	archive_entry_set_pathname_utf8(e, name);
	/* Whose it was here means nothing where it's opened */
	archive_entry_set_uid(e, 0);
	archive_entry_set_gid(e, 0);
	if (S_ISLNK(st.st_mode)) {
		char *target = g_file_read_link(path, NULL);
		if (target) {
			archive_entry_set_symlink(e, target);
			g_free(target);
		}
	}
	int r = archive_write_header(p->a, e);
	if (r < ARCHIVE_WARN) {
		op_fail(op, name, archive_error_string(p->a));
		p->broken = r == ARCHIVE_FATAL;
	} else if (fd >= 0) {
		/* As much as the header said, though the file may change under
		 * us: short is padded by libarchive, more is left */
		gint64 left = st.st_size, start = op_get_done(op);
		while (left > 0 && !op_cancelled(op)) {
			ssize_t n = read(fd, p->buf, MIN((gint64)sizeof(p->buf), left));
			if (n < 0 && errno == EINTR) {
				continue;
			}
			if (n <= 0) {
				if (n < 0) {
					op_fail(op, name, g_strerror(errno));
				}
				break;
			}
			if (archive_write_data(p->a, p->buf, n) < 0) {
				op_fail(op, name, archive_error_string(p->a));
				p->broken = true;
				break;
			}
			left -= n;
			op_set_done(op, start + st.st_size - left);
		}
		op_set_done(op, start + MAX(st.st_size, 1));
		op_item_done(op);
	} else {
		op_set_done(op, op_get_done(op) + 1);
		if (!S_ISDIR(st.st_mode)) {
			op_item_done(op);
		}
	}
	archive_entry_free(e);
	if (fd >= 0) {
		close(fd);
	}
	if (S_ISDIR(st.st_mode) && !p->broken) {
		GDir *d = g_dir_open(path, 0, NULL);
		const char *child;
		while (d && (child = g_dir_read_name(d))) {
			char *child_path = g_build_filename(path, child, NULL);
			char *child_name = g_strdup_printf("%s/%s", name, child);
			pack_add(p, child_path, child_name);
			g_free(child_name);
			g_free(child_path);
		}
		if (d) {
			g_dir_close(d);
		} else {
			op_fail(op, name, "It couldn't be read");
		}
	}
}

void arc_compress(struct op *op, GList *files, GFile *dest,
		enum arc_format format) {
	char *name = g_file_get_basename(dest);
	GFile *dir = g_file_get_parent(dest);
	char *dir_path = dir ? g_file_get_path(dir) : NULL;
	if (dir_path == NULL) {
		op_fail(op, name, "An archive can't be made here");
		g_clear_object(&dir);
		g_free(name);
		return;
	}
	gint64 total = 0;
	for (GList *l = files; l; l = l->next) {
		total += op_measure(op, l->data);
	}
	op_set_total(op, total);

	/* Under another name until it's whole */
	char *part = g_strdup_printf("%s/.%s.%08x.part", dir_path, name,
		g_random_int());
	int fd = open(part, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666);
	if (fd < 0) {
		op_fail(op, name, g_strerror(errno));
		goto out;
	}
	struct pack *p = g_new0(struct pack, 1);
	p->op = op;
	p->a = archive_write_new();
	switch (format) {
	case ARC_ZIP:
	case ARC_FORMATS:
		archive_write_set_format_zip(p->a);
		break;
	case ARC_7Z:
		archive_write_set_format_7zip(p->a);
		break;
	case ARC_TAR_GZ:
		archive_write_set_format_pax_restricted(p->a);
		archive_write_add_filter_gzip(p->a);
		break;
	case ARC_TAR_XZ:
		archive_write_set_format_pax_restricted(p->a);
		archive_write_add_filter_xz(p->a);
		/* Every core: xz on one is slow. Fine if it won't */
		archive_write_set_filter_option(p->a, "xz", "threads", "0");
		break;
	case ARC_TAR_ZST:
		archive_write_set_format_pax_restricted(p->a);
		archive_write_add_filter_zstd(p->a);
		archive_write_set_filter_option(p->a, "zstd", "threads", "0");
		break;
	}
	archive_clear_error(p->a);
	if (archive_write_open_fd(p->a, fd) != ARCHIVE_OK) {
		op_fail(op, name, archive_error_string(p->a));
		p->broken = true;
	}
	for (GList *l = files; l && !p->broken; l = l->next) {
		char *path = g_file_get_path(l->data);
		char *base = g_file_get_basename(l->data);
		if (path == NULL || !g_utf8_validate(base, -1, NULL)) {
			op_fail(op, base, "It can't be read from where it is");
		} else {
			pack_add(p, path, base);
		}
		g_free(base);
		g_free(path);
	}
	if (archive_write_close(p->a) != ARCHIVE_OK && !p->broken) {
		op_fail(op, name, archive_error_string(p->a));
		p->broken = true;
	}
	archive_write_free(p->a);
	close(fd);
	if (p->broken || op_cancelled(op)) {
		unlink(part);
	} else {
		GError *error = NULL;
		GFile *made = move_in(part, dir, name, &error);
		if (made) {
			op_made(op, made);
			g_object_unref(made);
		} else {
			op_fail(op, name, error->message);
			g_error_free(error);
			unlink(part);
		}
	}
	g_free(p);
out:
	g_free(part);
	g_free(dir_path);
	g_object_unref(dir);
	g_free(name);
}
