/*
 * c8-files-unpack OUTDIR STEM: takes the archive on its standard input
 * apart into OUTDIR. Files runs it inside bubblewrap (archive.c), where
 * OUTDIR is all it can write to: an archive is somebody else's data, and
 * whatever a crafted one makes libarchive do, it does in there. Plain C
 * and libarchive only, so /usr is all it needs to see.
 *
 * It says how it goes on standard output, a line each, names and texts
 * with \n, \t and \\ escaped:
 *   D BYTES        that much of the archive is read
 *   C NAME         the file in hand
 *   F NAME<tab>WHY one that couldn't be done
 *   W 0|1          a password is wanted (1: the last one was wrong);
 *                  the answer comes on descriptor 3, "P PASSWORD" or "N"
 * Exit 0 when the archive was read to its end.
 */
#define _GNU_SOURCE
#include <archive.h>
#include <archive_entry.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define BLOCK (256 * 1024)
#define CONTROL_FD 3
#define SAY_EVERY (64 * 1024)

static const char *outdir, *stem;
static bool asked;
static char secret[1024];

static void put(const char *s) {
	for (; s && *s; s++) {
		switch (*s) {
		case '\n':
			fputs("\\n", stdout);
			break;
		case '\t':
			fputs("\\t", stdout);
			break;
		case '\r':
			fputs("\\r", stdout);
			break;
		case '\\':
			fputs("\\\\", stdout);
			break;
		default:
			putchar(*s);
		}
	}
}

static void say_current(const char *path) {
	const char *slash = strrchr(path, '/');
	fputs("C ", stdout);
	put(slash ? slash + 1 : path);
	putchar('\n');
	fflush(stdout);
}

static void say_failed(const char *name, const char *why) {
	fputs("F ", stdout);
	put(name);
	putchar('\t');
	put(why ? why : "It didn't work");
	putchar('\n');
	fflush(stdout);
}

static void say_done(struct archive *a) {
	static la_int64_t said = -1;
	la_int64_t done = archive_filter_bytes(a, -1);
	if (said < 0 || done - said >= SAY_EVERY) {
		said = done;
		printf("D %lld\n", (long long)done);
		fflush(stdout);
	}
}

/* libarchive asks again for as long as the last one didn't fit */
static const char *password(struct archive *a, void *data) {
	printf("W %d\n", asked);
	fflush(stdout);
	asked = true;
	char line[sizeof(secret) + 8];
	size_t len = 0;
	while (len < sizeof(line) - 1) {
		char c;
		if (read(CONTROL_FD, &c, 1) != 1 || c == '\n') {
			break;
		}
		line[len++] = c;
	}
	line[len] = '\0';
	if (line[0] != 'P' || line[1] != ' ') {
		return NULL;
	}
	/* Unescaped in place into secret */
	size_t n = 0;
	for (const char *s = line + 2; *s && n < sizeof(secret) - 1; s++) {
		if (*s == '\\' && s[1]) {
			s++;
			secret[n++] = *s == 'n' ? '\n' : *s == 't' ? '\t' :
				*s == 'r' ? '\r' : *s;
		} else {
			secret[n++] = *s;
		}
	}
	secret[n] = '\0';
	return secret;
}

/* A path from the archive as one under our folder: no "..", nothing
 * from the root. NULL when it is neither, or nothing at all; else to
 * free */
static char *clean_path(const char *path) {
	if (path == NULL) {
		return NULL;
	}
	char *out = malloc(strlen(path) + 1);
	size_t n = 0;
	while (*path) {
		while (*path == '/') {
			path++;
		}
		size_t len = strcspn(path, "/");
		if (len == 0) {
			break;
		}
		if (len == 2 && path[0] == '.' && path[1] == '.') {
			free(out);
			return NULL;
		}
		if (!(len == 1 && path[0] == '.')) {
			if (n) {
				out[n++] = '/';
			}
			memcpy(out + n, path, len);
			n += len;
		}
		path += len;
	}
	out[n] = '\0';
	if (n == 0) {
		free(out);
		return NULL;
	}
	return out;
}

static char *under(const char *rel) {
	char *path;
	if (asprintf(&path, "%s/%s", outdir, rel) < 0) {
		exit(1);
	}
	return path;
}

int main(int argc, char **argv) {
	if (argc != 3) {
		fprintf(stderr, "usage: c8-files-unpack OUTDIR STEM < ARCHIVE\n");
		return 2;
	}
	outdir = argv[1];
	stem = argv[2];
	setlocale(LC_CTYPE, ""); // names in the archive to UTF-8

	struct archive *a = archive_read_new();
	archive_read_support_filter_all(a);
	archive_read_support_format_all(a);
	archive_read_support_format_raw(a); // a lone .gz
	archive_read_set_passphrase_callback(a, NULL, password);
	if (archive_read_open_fd(a, STDIN_FILENO, BLOCK) != ARCHIVE_OK) {
		say_failed(stem, archive_error_string(a) ? archive_error_string(a) :
			"It can't be read as an archive");
		return 1;
	}
	/* No owners, no set-id bits (without ARCHIVE_EXTRACT_PERM the umask
	 * holds and those are dropped), and nothing written through a link
	 * the archive made */
	struct archive *disk = archive_write_disk_new();
	archive_write_disk_set_options(disk, ARCHIVE_EXTRACT_TIME |
		ARCHIVE_EXTRACT_SECURE_NODOTDOT | ARCHIVE_EXTRACT_SECURE_SYMLINKS);
	bool ok = true;
	struct archive_entry *e;
	while (ok) {
		int r = archive_read_next_header(a, &e);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r == ARCHIVE_RETRY) {
			continue;
		}
		if (r < ARCHIVE_WARN) {
			say_failed(stem, archive_error_string(a));
			ok = false;
			break;
		}
		const char *in = archive_entry_pathname_utf8(e);
		if (in == NULL) {
			in = archive_entry_pathname(e);
		}
		char *rel = archive_format(a) == ARCHIVE_FORMAT_RAW ? strdup(stem) :
			clean_path(in);
		mode_t type = archive_entry_filetype(e);
		const char *hard = archive_entry_hardlink(e);
		char *hard_rel = hard ? clean_path(hard) : NULL;
		if (rel == NULL || (hard && hard_rel == NULL)) {
			say_failed(in ? in : stem,
				"Its place in the archive isn't one to extract to");
			free(rel);
			free(hard_rel);
			continue;
		}
		/* Files, folders and links; no devices or pipes */
		if (!hard && type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK) {
			free(rel);
			continue;
		}
		say_current(rel);
		char *path = under(rel);
		archive_entry_copy_pathname(e, path);
		if (hard_rel) {
			char *hard_path = under(hard_rel);
			archive_entry_copy_hardlink(e, hard_path);
			free(hard_path);
		}
		/* The user's to open and to delete again, whatever it says */
		archive_entry_set_perm(e, (archive_entry_perm(e) & 0777) |
			(type == AE_IFDIR ? 0700 : 0600));
		if (archive_write_header(disk, e) < ARCHIVE_WARN) {
			say_failed(rel, archive_error_string(disk));
		} else if (archive_entry_size(e) != 0 || !archive_entry_size_is_set(e)) {
			const void *block;
			size_t size;
			la_int64_t offset;
			while ((r = archive_read_data_block(a, &block, &size, &offset)) !=
					ARCHIVE_EOF) {
				if (r == ARCHIVE_RETRY) {
					continue;
				}
				if (r < ARCHIVE_WARN) {
					say_failed(rel, archive_error_string(a));
					ok = false;
					break;
				}
				if (archive_write_data_block(disk, block, size, offset) <
						ARCHIVE_WARN) {
					say_failed(rel, archive_error_string(disk));
					ok = false; // a full disk, most likely
					break;
				}
				say_done(a);
			}
		}
		archive_write_finish_entry(disk);
		free(path);
		free(rel);
		free(hard_rel);
		say_done(a);
	}
	archive_write_close(disk);
	archive_write_free(disk);
	archive_read_free(a);
	return ok ? 0 : 1;
}
