/*
 * Thumbnails from the freedesktop thumbnail cache, made when missing.
 *
 * The cache: ~/.cache/thumbnails/SIZE/MD5(uri).png, valid while its
 * Thumb::MTime text matches the file's modification time. A file no
 * thumbnailer could do gets an empty one under fail/c8ui/, so it isn't
 * tried again until it changes.
 *
 * Thumbnailers (.thumbnailer files in share/thumbnailers)
 * read files that may come from anyone, and some have had bugs a crafted
 * file could use to run code. So they only run inside bubblewrap, as
 * GNOME runs them: /usr read-only, the one file read-only under a fixed
 * name, a scratch folder to write to, no network, no other namespaces
 * shared, a clean environment. No bwrap, no new thumbnails.
 *
 * All of it runs on a few worker threads; the answer comes back on the
 * main loop.
 */
#define _GNU_SOURCE
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <gio/gio.h>
#include <glib/gstdio.h>
#include "c8ui-files.h"

#define WORKERS 3
#define TIMEOUT_MS 30000 // a thumbnailer taking longer is killed
#define SANDBOX_IN "/tmp/in/file" // where the sandbox sees the file
#define SANDBOX_OUT "/tmp/out"

struct c8ui_thumbnail {
	char *uri;
	int size;
	c8ui_thumbnail_fn fn;
	void *data;
	gint cancelled; // atomic: the worker may skip the work
	cairo_surface_t *result;
};

struct thumbnailer {
	char *exec;
	char *program; // argv[0], resolved
};

static GThreadPool *pool;
static GMutex lock; // guards the thumbnailers table
static GHashTable *thumbnailers; // MIME type → struct thumbnailer
static char *bwrap;

/* PNG chunks: the cache keeps its facts in tEXt chunks */

static guint32 crc_table[256];

static void crc_init(void) {
	for (guint32 n = 0; n < 256; n++) {
		guint32 c = n;
		for (int k = 0; k < 8; k++) {
			c = c & 1 ? 0xedb88320u ^ (c >> 1) : c >> 1;
		}
		crc_table[n] = c;
	}
}

static guint32 crc(const guint8 *buf, size_t len) {
	guint32 c = 0xffffffffu;
	for (size_t i = 0; i < len; i++) {
		c = crc_table[(c ^ buf[i]) & 0xff] ^ (c >> 8);
	}
	return c ^ 0xffffffffu;
}

static guint32 be32(const guint8 *p) {
	return (guint32)p[0] << 24 | (guint32)p[1] << 16 | (guint32)p[2] << 8 | p[3];
}

static void put_be32(GByteArray *out, guint32 v) {
	guint8 b[4] = { v >> 24, v >> 16, v >> 8, v };
	g_byte_array_append(out, b, 4);
}

static const guint8 png_signature[8] = { 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n' };

/* The text under key in a PNG's tEXt chunks, or NULL */
static char *png_text(const guint8 *png, size_t len, const char *key) {
	if (len < 8 || memcmp(png, png_signature, 8) != 0) {
		return NULL;
	}
	size_t keylen = strlen(key);
	for (size_t at = 8; at + 12 <= len;) {
		guint32 n = be32(png + at);
		if (n > len - at - 12) {
			return NULL; // cut short
		}
		const guint8 *type = png + at + 4, *data = png + at + 8;
		if (memcmp(type, "tEXt", 4) == 0 && n > keylen &&
				memcmp(data, key, keylen) == 0 && data[keylen] == '\0') {
			return g_strndup((const char *)data + keylen + 1, n - keylen - 1);
		}
		if (memcmp(type, "IEND", 4) == 0) {
			break;
		}
		at += 12 + n;
	}
	return NULL;
}

static void add_text(GByteArray *out, const char *key, const char *value) {
	GByteArray *chunk = g_byte_array_new();
	g_byte_array_append(chunk, (const guint8 *)"tEXt", 4);
	g_byte_array_append(chunk, (const guint8 *)key, strlen(key) + 1);
	g_byte_array_append(chunk, (const guint8 *)value, strlen(value));
	put_be32(out, chunk->len - 4);
	g_byte_array_append(out, chunk->data, chunk->len);
	put_be32(out, crc(chunk->data, chunk->len));
	g_byte_array_free(chunk, TRUE);
}

static cairo_status_t write_bytes(void *closure, const unsigned char *data,
		unsigned int length) {
	g_byte_array_append(closure, data, length);
	return CAIRO_STATUS_SUCCESS;
}

/* Writes image to path with the cache's facts, by a temporary file so a
 * reader never sees half of it */
static bool save(cairo_surface_t *image, const char *path, const char *uri,
		guint64 mtime, guint64 size) {
	GByteArray *png = g_byte_array_new();
	if (cairo_surface_write_to_png_stream(image, write_bytes, png) !=
			CAIRO_STATUS_SUCCESS || png->len < 33) {
		g_byte_array_free(png, TRUE);
		return false;
	}
	/* Signature and IHDR, then our text, then the rest */
	GByteArray *out = g_byte_array_new();
	g_byte_array_append(out, png->data, 33);
	char num[32];
	add_text(out, "Thumb::URI", uri);
	snprintf(num, sizeof(num), "%" G_GUINT64_FORMAT, mtime);
	add_text(out, "Thumb::MTime", num);
	snprintf(num, sizeof(num), "%" G_GUINT64_FORMAT, size);
	add_text(out, "Thumb::Size", num);
	add_text(out, "Software", "c8ui");
	g_byte_array_append(out, png->data + 33, png->len - 33);
	g_byte_array_free(png, TRUE);

	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);
	char *tmp = g_strdup_printf("%s.%u.tmp", path, (unsigned)getpid());
	bool ok = false;
	int fd = g_open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
	if (fd >= 0) {
		ok = write(fd, out->data, out->len) == (ssize_t)out->len;
		ok = close(fd) == 0 && ok;
		ok = ok && g_rename(tmp, path) == 0;
		if (!ok) {
			g_unlink(tmp);
		}
	}
	g_free(tmp);
	g_byte_array_free(out, TRUE);
	return ok;
}

/* The cached PNG at path if it is for this version of the file */
static bool cached(const char *path, guint64 mtime, cairo_surface_t **image) {
	gchar *png;
	gsize len;
	if (!g_file_get_contents(path, &png, &len, NULL)) {
		return false;
	}
	char *text = png_text((guint8 *)png, len, "Thumb::MTime");
	g_free(png);
	bool fresh = text && g_ascii_strtoull(text, NULL, 10) == mtime;
	g_free(text);
	if (fresh && image) {
		*image = cairo_image_surface_create_from_png(path);
		if (cairo_surface_status(*image) != CAIRO_STATUS_SUCCESS) {
			cairo_surface_destroy(*image);
			*image = NULL;
			return false;
		}
	}
	return fresh;
}

/* Thumbnailers */

static void thumbnailer_free(gpointer data) {
	struct thumbnailer *t = data;
	g_free(t->exec);
	g_free(t->program);
	g_free(t);
}

static void read_thumbnailer(const char *path) {
	GKeyFile *kf = g_key_file_new();
	if (!g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL)) {
		g_key_file_free(kf);
		return;
	}
	const char *group = "Thumbnailer Entry";
	char *exec = g_key_file_get_string(kf, group, "Exec", NULL);
	char *try = g_key_file_get_string(kf, group, "TryExec", NULL);
	char **types = g_key_file_get_string_list(kf, group, "MimeType", NULL,
		NULL);
	char **argv = NULL;
	char *program = NULL;
	if (exec && types && g_shell_parse_argv(exec, NULL, &argv, NULL)) {
		program = g_find_program_in_path(try ? try : argv[0]);
	}
	/* The sandbox has /usr only: a thumbnailer elsewhere can't run */
	if (program && g_str_has_prefix(program, "/usr/")) {
		for (char **t = types; *t; t++) {
			if (**t && !g_hash_table_contains(thumbnailers, *t)) {
				struct thumbnailer *th = g_new0(struct thumbnailer, 1);
				th->exec = g_strdup(exec);
				th->program = g_strdup(program);
				g_hash_table_insert(thumbnailers, g_strdup(*t), th);
			}
		}
	}
	g_free(program);
	g_strfreev(argv);
	g_strfreev(types);
	g_free(try);
	g_free(exec);
	g_key_file_free(kf);
}

static void read_dir(const char *base) {
	char *path = g_build_filename(base, "thumbnailers", NULL);
	GDir *dir = g_dir_open(path, 0, NULL);
	if (dir) {
		/* Sorted, so which one wins a type doesn't depend on the disk */
		GPtrArray *names = g_ptr_array_new_with_free_func(g_free);
		const char *name;
		while ((name = g_dir_read_name(dir))) {
			if (g_str_has_suffix(name, ".thumbnailer")) {
				g_ptr_array_add(names, g_strdup(name));
			}
		}
		g_dir_close(dir);
		g_ptr_array_sort_values(names, (GCompareFunc)strcmp);
		for (guint i = 0; i < names->len; i++) {
			char *file = g_build_filename(path, names->pdata[i], NULL);
			read_thumbnailer(file);
			g_free(file);
		}
		g_ptr_array_unref(names);
	}
	g_free(path);
}

static void load_thumbnailers(void) {
	thumbnailers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		thumbnailer_free);
	/* The user's first: they win a type */
	read_dir(g_get_user_data_dir());
	for (const char *const *d = g_get_system_data_dirs(); *d; d++) {
		read_dir(*d);
	}
}

/* A copy of the Exec line of the thumbnailer for type, or NULL */
static char *thumbnailer_for(const char *type) {
	g_mutex_lock(&lock);
	struct thumbnailer *t = g_hash_table_lookup(thumbnailers, type);
	if (t == NULL) {
		/* Subtypes and aliases: image/x-ms-bmp is image/bmp */
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, thumbnailers);
		while (t == NULL && g_hash_table_iter_next(&iter, &key, &value)) {
			if (g_content_type_is_a(type, key)) {
				t = value;
			}
		}
	}
	char *exec = t ? g_strdup(t->exec) : NULL;
	g_mutex_unlock(&lock);
	return exec;
}

/* Running one */

/* A file extension safe to put in the sandbox's name for the file; some
 * thumbnailers go by it */
static char *safe_extension(const char *path) {
	char *base = g_path_get_basename(path);
	const char *dot = strrchr(base, '.');
	GString *ext = g_string_new("");
	if (dot && dot != base) {
		for (const char *p = dot + 1; *p && ext->len < 10; p++) {
			if (g_ascii_isalnum(*p)) {
				g_string_append_c(ext, *p);
			}
		}
	}
	g_free(base);
	if (ext->len > 0) {
		g_string_prepend_c(ext, '.');
	}
	return g_string_free(ext, FALSE);
}

/* %u %i %o %s in one argument of the Exec line */
static char *expand(const char *arg, const char *in, const char *out,
		int size) {
	GString *s = g_string_new("");
	for (const char *p = arg; *p; p++) {
		if (p[0] != '%' || p[1] == '\0') {
			g_string_append_c(s, *p);
			continue;
		}
		switch (*++p) {
		case 'u': {
			char *uri = g_filename_to_uri(in, NULL, NULL);
			g_string_append(s, uri);
			g_free(uri);
			break;
		}
		case 'i':
			g_string_append(s, in);
			break;
		case 'o':
			g_string_append(s, out);
			break;
		case 's':
			g_string_append_printf(s, "%d", size);
			break;
		case '%':
			g_string_append_c(s, '%');
			break;
		}
	}
	return g_string_free(s, FALSE);
}

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

/* The usual top-level links into /usr (bin → usr/bin), or the folders
 * themselves where /usr isn't merged */
static void add_system(GPtrArray *argv) {
	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]);
		}
	}
	/* What libraries and fonts read from /etc and /var */
	const char *try[] = {
		"/etc/ld.so.cache", "/etc/alternatives", "/etc/fonts",
		"/var/cache/fontconfig",
	};
	for (size_t i = 0; i < G_N_ELEMENTS(try); i++) {
		add(argv, "--ro-bind-try");
		add(argv, try[i]);
		add(argv, try[i]);
	}
}

/* Runs the thumbnailer on path in the sandbox; the PNG it wrote, or
 * NULL */
static cairo_surface_t *run(const char *exec, const char *path, int size) {
	char **exec_argv;
	if (!g_shell_parse_argv(exec, NULL, &exec_argv, NULL)) {
		return NULL;
	}
	char *scratch = g_dir_make_tmp("c8ui-thumbnail-XXXXXX", NULL);
	if (scratch == NULL) {
		g_strfreev(exec_argv);
		return NULL;
	}
	char *ext = safe_extension(path);
	char *in = g_strconcat(SANDBOX_IN, ext, NULL);
	const char *out = SANDBOX_OUT "/thumbnail.png";

	GPtrArray *argv = g_ptr_array_new_with_free_func(g_free);
	add(argv, bwrap);
	add_system(argv);
	add(argv, "--proc");
	add(argv, "/proc");
	add(argv, "--dev");
	add(argv, "/dev");
	add(argv, "--tmpfs");
	add(argv, "/tmp");
	add(argv, "--bind");
	add(argv, scratch);
	add(argv, SANDBOX_OUT);
	add(argv, "--ro-bind");
	add(argv, path);
	add(argv, in);
	/* Nothing shared: no network, no other processes, no IPC */
	add(argv, "--unshare-all");
	add(argv, "--die-with-parent");
	add(argv, "--new-session"); // can't type into our terminal
	add(argv, "--clearenv");
	add(argv, "--setenv");
	add(argv, "PATH");
	add(argv, "/usr/bin:/bin");
	add(argv, "--setenv");
	add(argv, "HOME");
	add(argv, "/tmp");
	add(argv, "--setenv");
	add(argv, "GIO_USE_VFS");
	add(argv, "local");
	const char *lang = g_getenv("LANG");
	if (lang) {
		add(argv, "--setenv");
		add(argv, "LANG");
		add(argv, lang);
	}
	add(argv, "--chdir");
	add(argv, "/tmp");
	add(argv, "--");
	for (char **a = exec_argv; *a; a++) {
		g_ptr_array_add(argv, expand(*a, in, out, size));
	}
	g_ptr_array_add(argv, NULL);

	cairo_surface_t *image = NULL;
	GPid pid;
	if (g_spawn_async(NULL, (char **)argv->pdata, NULL,
			G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_STDOUT_TO_DEV_NULL |
			G_SPAWN_STDERR_TO_DEV_NULL | G_SPAWN_CLOEXEC_PIPES,
			NULL, NULL, &pid, NULL)) {
		int status = 0;
		int waited = 0;
		pid_t r;
		while ((r = waitpid(pid, &status, WNOHANG)) == 0 &&
				waited < TIMEOUT_MS) {
			g_usleep(20 * 1000);
			waited += 20;
		}
		if (r == 0) {
			kill(pid, SIGKILL); // and with it the thumbnailer
			waitpid(pid, &status, 0);
		} else if (r > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0) {
			char *file = g_build_filename(scratch, "thumbnail.png", NULL);
			image = cairo_image_surface_create_from_png(file);
			if (cairo_surface_status(image) != CAIRO_STATUS_SUCCESS) {
				cairo_surface_destroy(image);
				image = NULL;
			}
			g_unlink(file);
			g_free(file);
		}
	}
	g_rmdir(scratch); // the sandbox only wrote thumbnail.png there
	g_ptr_array_unref(argv);
	g_strfreev(exec_argv);
	g_free(in);
	g_free(ext);
	g_free(scratch);
	return image;
}

/* Thumbnailers may ignore %s: never keep more than the size */
static cairo_surface_t *fit(cairo_surface_t *image, int size) {
	int w = cairo_image_surface_get_width(image);
	int h = cairo_image_surface_get_height(image);
	if (w <= size && h <= size) {
		return image;
	}
	double s = (double)size / MAX(w, h);
	int nw = MAX(1, (int)(w * s + 0.5)), nh = MAX(1, (int)(h * s + 0.5));
	cairo_surface_t *small = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		nw, nh);
	cairo_t *cr = cairo_create(small);
	cairo_scale(cr, s, s);
	cairo_set_source_surface(cr, image, 0, 0);
	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);
	cairo_paint(cr);
	cairo_destroy(cr);
	cairo_surface_destroy(image);
	return small;
}

static const char *size_dir(int size) {
	return size <= 128 ? "normal" : size <= 256 ? "large" :
		size <= 512 ? "x-large" : "xx-large";
}

static void work(struct c8ui_thumbnail *job) {
	GFile *file = g_file_new_for_uri(job->uri);
	GFileInfo *info = g_file_query_info(file,
		G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
		G_FILE_ATTRIBUTE_STANDARD_TYPE ","
		G_FILE_ATTRIBUTE_STANDARD_SIZE ","
		G_FILE_ATTRIBUTE_TIME_MODIFIED,
		G_FILE_QUERY_INFO_NONE, NULL, NULL);
	char *path = g_file_get_path(file);
	g_object_unref(file);
	if (info == NULL) {
		g_free(path);
		return;
	}
	guint64 mtime = g_file_info_get_attribute_uint64(info,
		G_FILE_ATTRIBUTE_TIME_MODIFIED);
	guint64 bytes = g_file_info_get_size(info);
	bool regular = g_file_info_get_file_type(info) == G_FILE_TYPE_REGULAR;
	const char *type = g_file_info_get_content_type(info);
	char *mime = type ? g_content_type_get_mime_type(type) : NULL;
	g_object_unref(info);

	char *md5 = g_compute_checksum_for_string(G_CHECKSUM_MD5, job->uri, -1);
	char *name = g_strconcat(md5, ".png", NULL);
	char *base = g_build_filename(g_get_user_cache_dir(), "thumbnails", NULL);
	char *thumb = g_build_filename(base, size_dir(job->size), name, NULL);
	char *failed = g_build_filename(base, "fail", "c8ui", name, NULL);

	if (cached(thumb, mtime, &job->result) || cached(failed, mtime, NULL)) {
		goto out;
	}
	/* Made only for local files (not the cache's own), with a sandbox */
	char *exec = NULL;
	if (path && regular && mime && bwrap && !g_str_has_prefix(path, base) &&
			!g_atomic_int_get(&job->cancelled)) {
		exec = thumbnailer_for(mime);
	}
	if (exec) {
		int px = job->size <= 128 ? 128 : job->size <= 256 ? 256 :
			job->size <= 512 ? 512 : 1024;
		cairo_surface_t *image = run(exec, path, px);
		if (image) {
			image = fit(image, px);
			save(image, thumb, job->uri, mtime, bytes);
			job->result = image;
		} else {
			cairo_surface_t *none =
				cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
			save(none, failed, job->uri, mtime, bytes);
			cairo_surface_destroy(none);
		}
		g_free(exec);
	}
out:
	g_free(failed);
	g_free(thumb);
	g_free(base);
	g_free(name);
	g_free(md5);
	g_free(mime);
	g_free(path);
}

static gboolean deliver(gpointer data) {
	struct c8ui_thumbnail *job = data;
	if (!g_atomic_int_get(&job->cancelled)) {
		job->fn(job->result, job->data);
	} else if (job->result) {
		cairo_surface_destroy(job->result);
	}
	g_free(job->uri);
	free(job);
	return G_SOURCE_REMOVE;
}

static void worker(gpointer data, gpointer unused) {
	struct c8ui_thumbnail *job = data;
	if (!g_atomic_int_get(&job->cancelled)) {
		work(job);
	}
	g_idle_add(deliver, job);
}

static gpointer start(gpointer unused) {
	crc_init();
	load_thumbnailers();
	bwrap = g_find_program_in_path("bwrap");
	if (bwrap == NULL) {
		fprintf(stderr, "c8ui: no bwrap (bubblewrap): only thumbnails "
			"already made are shown\n");
	}
	pool = g_thread_pool_new(worker, NULL, WORKERS, FALSE, NULL);
	return NULL;
}

static GOnce once = G_ONCE_INIT;

bool c8ui_thumbnail_supported(const char *mime) {
	g_once(&once, start, NULL);
	if (bwrap == NULL || mime == NULL) {
		return false;
	}
	char *exec = thumbnailer_for(mime);
	g_free(exec);
	return exec != NULL;
}

struct c8ui_thumbnail *c8ui_thumbnail_load(const char *uri, int size,
		c8ui_thumbnail_fn fn, void *data) {
	g_once(&once, start, NULL);
	struct c8ui_thumbnail *job = calloc(1, sizeof(*job));
	job->uri = g_strdup(uri);
	job->size = size;
	job->fn = fn;
	job->data = data;
	g_thread_pool_push(pool, job, NULL);
	return job;
}

void c8ui_thumbnail_cancel(struct c8ui_thumbnail *job) {
	g_atomic_int_set(&job->cancelled, 1);
}
