// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Tabmorph. Archives are read in memory, never extracted to a filesystem.
#include <archive.h>
#include <archive_entry.h>
#include <emscripten/emscripten.h>
#include <algorithm>
#include <cstdint>
#include <clocale>
#include <cstring>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>

struct Result {
  std::vector<unsigned char> bytes;
  std::string error, info, source;
  size_t limit = 0, expanded = 0, normalized = 0, copied_links = 0, kept_links = 0;
};
using EntryPtr = std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
struct Entry {
  EntryPtr header;
  std::vector<unsigned char> data;
  std::string name, hardlink;
  Entry(archive_entry* p): header(p, archive_entry_free) {}
};
using Entries = std::vector<Entry>;

static std::string message(archive* a, const char* fallback) {
  const char* p = archive_error_string(a);
  return p && *p ? p : fallback;
}
static void check(int code, archive* a, const char* fallback) {
  if (code < ARCHIVE_OK) throw std::runtime_error(message(a, fallback));
}
static std::string path(const char* value, bool directory = false) {
  if (!value) throw std::runtime_error("A filename could not be decoded as Unicode.");
  std::string text(value), output;
  std::replace(text.begin(), text.end(), '\\', '/');
  if (text.size() > 65535 || (!text.empty() && text[0] == '/') || (text.size() > 1 && text[1] == ':'))
    throw std::runtime_error("This archive has an unsafe or excessively long file path.");
  for (size_t i = 0; i < text.size();) {
    size_t end = text.find('/', i);
    if (end == std::string::npos) end = text.size();
    std::string part = text.substr(i, end - i);
    if (part == "..") throw std::runtime_error("This archive has an unsafe parent file path.");
    if (!part.empty() && part != ".") { if (!output.empty()) output += '/'; output += part; }
    i = end + 1;
  }
  if (directory && !output.empty()) output += '/';
  return output;
}
static void safe_symlink(const std::string& name, const char* value) {
  if (!value || !*value) throw std::runtime_error("An archive link has no target.");
  std::string target(value);
  std::replace(target.begin(), target.end(), '\\', '/');
  if (target[0] == '/' || (target.size() > 1 && target[1] == ':'))
    throw std::runtime_error("An archive link points outside its folder tree.");
  int depth = std::count(name.begin(), name.end(), '/');
  for (size_t i = 0; i < target.size();) {
    size_t end = target.find('/', i);
    if (end == std::string::npos) end = target.size();
    std::string part = target.substr(i, end - i);
    if (part == "..") { if (--depth < 0) throw std::runtime_error("An archive link escapes its folder tree."); }
    else if (!part.empty() && part != ".") ++depth;
    i = end + 1;
  }
}
static void zip_names(const unsigned char* b, size_t length) {
  if (length < 4 || b[0] != 'P' || b[1] != 'K' || !((b[2] == 3 && b[3] == 4) || (b[2] == 5 && b[3] == 6) || (b[2] == 7 && b[3] == 8))) return;
  auto need = [&](uint64_t pos, uint64_t count) {
    if (pos > length || count > length - pos) throw std::runtime_error("This ZIP has a truncated directory.");
  };
  auto u16 = [&](size_t p) -> uint16_t { need(p, 2); return uint16_t(b[p]) | uint16_t(b[p+1]) << 8; };
  auto u32 = [&](size_t p) -> uint32_t { need(p, 4); return uint32_t(b[p]) | uint32_t(b[p+1]) << 8 | uint32_t(b[p+2]) << 16 | uint32_t(b[p+3]) << 24; };
  auto u64 = [&](size_t p) -> uint64_t { return uint64_t(u32(p)) | uint64_t(u32(p+4)) << 32; };
  if (length < 22) throw std::runtime_error("This ZIP has no complete directory.");
  size_t end = length - 22, minimum = length > 65557 ? length - 65557 : 0;
  for (;;) {
    if (u32(end) == 0x06054b50 && end + 22 + u16(end+20) == length) break;
    if (end == minimum) throw std::runtime_error("This ZIP has no complete directory.");
    --end;
  }
  if (u16(end+4) || u16(end+6) || u16(end+8) != u16(end+10)) throw std::runtime_error("Split ZIP archives are not supported.");
  uint64_t count = u16(end+10), offset = u32(end+16), size = u32(end+12);
  if (count == 65535 || offset == 0xffffffff || size == 0xffffffff) {
    if (end < 20 || u32(end-20) != 0x07064b50 || u32(end-16) || u32(end-4) != 1) throw std::runtime_error("The ZIP64 locator is invalid or refers to split volumes.");
    uint64_t pos = u64(end-12); need(pos, 56);
    if (u32(pos) != 0x06064b50 || u32(pos+16) || u32(pos+20) || u64(pos+24) != u64(pos+32)) throw std::runtime_error("The ZIP64 directory is invalid.");
    count = u64(pos+32); size = u64(pos+40); offset = u64(pos+48);
  }
  if (count > 10000 || offset > end || size > end-offset) throw std::runtime_error("This ZIP has too many entries or a damaged directory.");
  auto filename = [&](size_t pos, size_t n) {
    need(pos, n);
    if (!n || std::memchr(b+pos, 0, n)) throw std::runtime_error("This ZIP has an empty filename or an embedded NUL character.");
  };
  size_t p = offset;
  for (uint64_t i = 0; i < count; ++i) {
    need(p, 46);
    if (u32(p) != 0x02014b50) throw std::runtime_error("This ZIP has a damaged directory entry.");
    size_t n = u16(p+28), extra = u16(p+30), comment = u16(p+32);
    filename(p+46, n); need(p+46+n, extra+comment);
    uint64_t local = u32(p+42); uint32_t disk = u16(p+34);
    for (size_t q = p+46+n, finish = q+extra; q+4 <= finish;) {
      size_t tag = u16(q), bytes = u16(q+2), value = q+4;
      if (bytes > finish-value) throw std::runtime_error("This ZIP has invalid extra fields.");
      if (tag == 0x7075 && bytes >= 5 && std::memchr(b+value+5, 0, bytes-5)) throw std::runtime_error("This ZIP has an embedded NUL filename.");
      if (tag == 1) {
        size_t v = value;
        if (u32(p+24) == 0xffffffff) v += 8;
        if (u32(p+20) == 0xffffffff) v += 8;
        if (local == 0xffffffff) { if (v+8 > value+bytes) throw std::runtime_error("This ZIP64 file offset is missing."); local = u64(v); v += 8; }
        if (disk == 65535) { if (v+4 > value+bytes) throw std::runtime_error("This ZIP64 volume is missing."); disk = u32(v); }
      }
      q = value+bytes;
    }
    if (disk) throw std::runtime_error("Split ZIP archives are not supported.");
    need(local, 30);
    if (u32(local) != 0x04034b50) throw std::runtime_error("This ZIP has a damaged local file header.");
    filename(local+30, u16(local+26));
    p += 46+n+extra+comment;
    if (p > offset+size) throw std::runtime_error("This ZIP directory is inconsistent.");
  }
}
static Entries read_entries(const unsigned char* input, size_t length, const char* password,
                            const char* fallback, bool raw, Result& r, bool require_tar = false) {
  zip_names(input, length);
  std::unique_ptr<archive, decltype(&archive_read_free)> a(archive_read_new(), archive_read_free);
  if (!a) throw std::bad_alloc();
  archive_read_support_filter_all(a.get());
  archive_read_support_format_7zip(a.get()); archive_read_support_format_ar(a.get());
  archive_read_support_format_cab(a.get()); archive_read_support_format_cpio(a.get());
  archive_read_support_format_empty(a.get()); archive_read_support_format_iso9660(a.get());
  archive_read_support_format_lha(a.get()); archive_read_support_format_rar(a.get());
  archive_read_support_format_rar5(a.get()); archive_read_support_format_tar(a.get());
  archive_read_support_format_xar(a.get()); archive_read_support_format_zip(a.get());
  if (raw) {
    check(archive_read_set_format(a.get(), ARCHIVE_FORMAT_RAW), a.get(), "Cannot read the compression stream.");
  }
  if (password && *password) check(archive_read_add_passphrase(a.get(), password), a.get(), "The password could not be used.");
  check(archive_read_open_memory(a.get(), input, length), a.get(), "This archive could not be opened.");
  Entries entries;
  size_t total = 0;
  archive_entry* header = nullptr;
  for (;;) {
    int status = archive_read_next_header(a.get(), &header);
    if (status == ARCHIVE_EOF) break;
    check(status, a.get(), "This archive has an invalid header.");
    int format = archive_format(a.get());
    if (require_tar && (format & ARCHIVE_FORMAT_BASE_MASK) != ARCHIVE_FORMAT_TAR)
      throw std::runtime_error("TAR.7Z must contain one TAR archive.");
    if (format == ARCHIVE_FORMAT_RAW && archive_filter_code(a.get(), 0) == ARCHIVE_FILTER_NONE)
      throw std::runtime_error("The compressed file has no recognized compression header.");
    if (entries.size() >= 10000) throw std::runtime_error("This archive has more than 10,000 entries.");
    const char* original = archive_entry_pathname_utf8(header);
    if (format == ARCHIVE_FORMAT_RAW && (!original || std::strcmp(original, "data") == 0)) original = fallback;
    const auto type = archive_entry_filetype(header);
    const char* hardlink = archive_entry_hardlink_utf8(header);
    if (type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK && !(type == 0 && hardlink))
      throw std::runtime_error("Devices, sockets and other special archive entries cannot be converted.");
    std::string name = path(original, type == AE_IFDIR);
    // A conventional TAR root directory is structural, not a file to discard.
    if (name.empty() && type == AE_IFDIR) { check(archive_read_data_skip(a.get()), a.get(), "Damaged root directory."); continue; }
    if (name.empty()) throw std::runtime_error("This archive contains an empty filename.");
    if (name != original) ++r.normalized;
    if (type == AE_IFLNK) safe_symlink(name, archive_entry_symlink_utf8(header));
    Entry entry(archive_entry_clone(header));
    if (!entry.header) throw std::bad_alloc();
    entry.name = name;
    archive_entry_set_pathname_utf8(entry.header.get(), name.c_str());
    if (hardlink) entry.hardlink = path(hardlink);
    const auto declared = archive_entry_size(header);
    if (archive_entry_size_is_set(header) && (declared < 0 || static_cast<uint64_t>(declared) > r.limit - total))
      throw std::runtime_error("This archive exceeds the expanded size limit.");
    unsigned char buffer[65536];
    for (;;) {
      la_ssize_t n = archive_read_data(a.get(), buffer, sizeof buffer);
      if (n < 0) throw std::runtime_error(message(a.get(), "Archive contents failed validation."));
      if (!n) break;
      if (static_cast<size_t>(n) > r.limit - total) throw std::runtime_error("This archive exceeds the expanded size limit.");
      total += n;
      entry.data.insert(entry.data.end(), buffer, buffer + n);
    }
    if (type == AE_IFREG && entry.hardlink.empty()) {
      if (archive_entry_size_is_set(header) && static_cast<uint64_t>(declared) != entry.data.size())
        throw std::runtime_error("An archive file has incomplete contents.");
      archive_entry_set_size(entry.header.get(), entry.data.size());
    } else if (type == AE_IFDIR || type == AE_IFLNK) {
      // Some ZIP readers return a symlink's stored target as data as well as metadata.
      // Writers already encode that target from the header; never append it twice.
      entry.data.clear();
      archive_entry_set_size(entry.header.get(), 0);
    }
    entries.push_back(std::move(entry));
  }
  if (require_tar && (archive_format(a.get()) & ARCHIVE_FORMAT_BASE_MASK) != ARCHIVE_FORMAT_TAR)
    throw std::runtime_error("The compressed TAR input does not contain a recognized TAR archive.");
  r.source = archive_format_name(a.get()) ? archive_format_name(a.get()) : "empty archive";
  r.expanded = total;
  check(archive_read_close(a.get()), a.get(), "The archive footer is damaged.");
  return entries;
}
static void validate_and_copy_links(Entries& entries, const std::string& output_format, Result& r) {
  std::unordered_map<std::string, size_t> names;
  for (size_t i = 0; i < entries.size(); ++i) {
    auto name = entries[i].name;
    if (name.back() == '/') name.pop_back();
    if (!names.emplace(name, i).second) throw std::runtime_error("This archive has duplicate or colliding filenames.");
  }
  for (const auto& e: entries) {
    auto name = e.name;
    if (name.back() == '/') name.pop_back();
    for (size_t p = name.find('/'); p != std::string::npos; p = name.find('/', p + 1)) {
      auto it = names.find(name.substr(0, p));
      if (it != names.end() && archive_entry_filetype(entries[it->second].header.get()) != AE_IFDIR)
        throw std::runtime_error("An archive path traverses a file or symbolic link.");
    }
  }
  const bool cpio = output_format == "cpio";
  const bool pax = output_format != "zip" && output_format != "7z" && !cpio;
  std::vector<size_t> terminals(entries.size());
  for (size_t i = 0; i < entries.size(); ++i) terminals[i] = i;
  // Resolve forward and backward hardlinks without recursive calls or filesystem access.
  for (size_t i = 0; i < entries.size(); ++i) {
    auto& entry = entries[i];
    if (entry.hardlink.empty()) continue;
    std::set<size_t> visited;
    size_t target = i;
    while (!entries[target].hardlink.empty()) {
      if (!visited.insert(target).second) throw std::runtime_error("This archive has a hardlink cycle.");
      auto it = names.find(entries[target].hardlink);
      if (it == names.end()) throw std::runtime_error("An archive hardlink has no matching file.");
      target = it->second;
    }
    if (archive_entry_filetype(entries[target].header.get()) != AE_IFREG)
      throw std::runtime_error("An archive hardlink does not reference a regular file.");
    terminals[i] = target;
    if (pax || cpio) continue;
    const auto& data = entries[target].data;
    if (data.size() > r.limit - r.expanded) throw std::runtime_error("Hardlink copies exceed the expanded size limit.");
    entry.data = data;
    r.expanded += data.size();
    archive_entry_set_hardlink(entry.header.get(), nullptr);
    archive_entry_set_filetype(entry.header.get(), AE_IFREG);
    archive_entry_set_size(entry.header.get(), data.size());
    archive_entry_set_nlink(entry.header.get(), 1);
    ++r.copied_links;
  }
  if (pax) {
    for (size_t i = 0; i < entries.size(); ++i) if (!entries[i].hardlink.empty()) {
      archive_entry_set_hardlink_utf8(entries[i].header.get(), entries[terminals[i]].name.c_str());
      archive_entry_set_filetype(entries[i].header.get(), AE_IFREG);
      archive_entry_set_size(entries[i].header.get(), 0); entries[i].data.clear(); ++r.kept_links;
    }
    // Put referents before links, including when the source used forward references.
    std::stable_partition(entries.begin(), entries.end(), [](const Entry& e) { return e.hardlink.empty(); });
  } else if (cpio) {
    std::unordered_map<size_t, std::vector<size_t>> groups;
    for (size_t i = 0; i < entries.size(); ++i) {
      archive_entry_set_nlink(entries[i].header.get(), 1);
      archive_entry_set_ino64(entries[i].header.get(), i + 1);
      archive_entry_set_dev(entries[i].header.get(), 0);
      if (archive_entry_filetype(entries[i].header.get()) == AE_IFREG || !entries[i].hardlink.empty()) groups[terminals[i]].push_back(i);
    }
    for (const auto& group: groups) if (group.second.size() > 1) {
      auto data = std::move(entries[group.first].data);
      for (size_t i: group.second) {
        auto& e = entries[i]; e.data.clear();
        archive_entry_set_hardlink(e.header.get(), nullptr); archive_entry_set_filetype(e.header.get(), AE_IFREG);
        archive_entry_set_ino64(e.header.get(), group.first + 1); archive_entry_set_nlink(e.header.get(), group.second.size()); archive_entry_set_size(e.header.get(), 0);
      }
      auto& last = entries[group.second.back()]; last.data = std::move(data); archive_entry_set_size(last.header.get(), last.data.size());
      r.kept_links += group.second.size() - 1;
    }
  }
}
static la_ssize_t output(archive* a, void* opaque, const void* data, size_t length) {
  auto& r = *static_cast<Result*>(opaque);
  if (length > r.limit - r.bytes.size()) {
    archive_set_error(a, 0, "The converted archive exceeds the output size limit."); return -1;
  }
  try { const auto* p = static_cast<const unsigned char*>(data); r.bytes.insert(r.bytes.end(), p, p + length); }
  catch (...) { archive_set_error(a, 0, "Not enough memory for the converted archive."); return -1; }
  return length;
}
static void write_entries(Entries& entries, const std::string& target, Result& r) {
  std::unique_ptr<archive, decltype(&archive_write_free)> a(archive_write_new(), archive_write_free);
  if (!a) throw std::bad_alloc();
  int status;
  if (target == "zip") status = archive_write_set_format_zip(a.get());
  else if (target == "7z") status = archive_write_set_format_7zip(a.get());
  else if (target == "cpio") status = archive_write_set_format_cpio_newc(a.get());
  else status = archive_write_set_format_pax(a.get());
  check(status, a.get(), "This output format is unavailable.");
  int filter = ARCHIVE_FILTER_NONE;
  if (target == "tgz") filter = ARCHIVE_FILTER_GZIP;
  else if (target == "tbz2") filter = ARCHIVE_FILTER_BZIP2;
  else if (target == "txz") filter = ARCHIVE_FILTER_XZ;
  else if (target == "tlz") filter = ARCHIVE_FILTER_LZIP;
  else if (target == "tlzma") filter = ARCHIVE_FILTER_LZMA;
  else if (target == "tz") filter = ARCHIVE_FILTER_COMPRESS;
  else if (target == "tzst") filter = ARCHIVE_FILTER_ZSTD;
  else if (target == "tlz4") filter = ARCHIVE_FILTER_LZ4;
  check(archive_write_add_filter(a.get(), filter), a.get(), "This compression is unavailable.");
  if (filter == ARCHIVE_FILTER_GZIP) check(archive_write_set_filter_option(a.get(), "gzip", "timestamp", nullptr), a.get(), "Cannot set the gzip header timestamp.");
  if (target == "7z") check(archive_write_set_options(a.get(), "compression=lzma2,compression-level=6"), a.get(), "7Z compression is unavailable.");
  if (target == "zip" || filter != ARCHIVE_FILTER_NONE && filter != ARCHIVE_FILTER_COMPRESS && filter != ARCHIVE_FILTER_LZ4)
    check(archive_write_set_options(a.get(), "compression-level=6"), a.get(), "The compression level is unavailable.");
  archive_write_set_bytes_per_block(a.get(), 0);
  check(archive_write_open(a.get(), &r, nullptr, output, nullptr), a.get(), "The output could not be started.");
  for (auto& e: entries) {
    // Every header has already been validated, and links have never been followed.
    check(archive_write_header(a.get(), e.header.get()), a.get(), "An entry cannot be represented in this output.");
    size_t at = 0;
    while (at < e.data.size()) {
      auto count = archive_write_data(a.get(), e.data.data() + at, e.data.size() - at);
      if (count <= 0) throw std::runtime_error(message(a.get(), "Archive output is incomplete."));
      at += count;
    }
    check(archive_write_finish_entry(a.get()), a.get(), "An archive entry could not be completed.");
  }
  check(archive_write_close(a.get()), a.get(), "The converted archive could not be completed.");
}

extern "C" {
EMSCRIPTEN_KEEPALIVE Result* tm_archive_convert(const unsigned char* input, size_t length,
    const char* target, const char* password, const char* fallback, int raw, int nested_tar, size_t limit) {
  auto r = std::make_unique<Result>();
  r->limit = limit;
  try {
    if (!std::setlocale(LC_ALL, "C.UTF-8")) throw std::runtime_error("The Unicode archive locale is unavailable.");
    if (length >= 12 && std::memcmp(input, "Rar!\x1a\x07\x00", 7) == 0 && input[9] == 0x73 && (input[10] & 1))
      throw std::runtime_error("Split RAR archives are not supported. Supply a single-volume archive.");
    if (length >= 36 && std::memcmp(input, "MSCF", 4) == 0 && (input[30] & 3))
      throw std::runtime_error("Split CAB archives are not supported. Supply a single cabinet.");
    if (length >= 16 && std::memcmp(input, "Rar!\x1a\x07\x01\x00", 8) == 0) {
      size_t at = 12;
      auto vint = [&]() -> uint64_t {
        uint64_t value = 0;
        for (unsigned shift = 0; shift < 63 && at < length; shift += 7) {
          unsigned byte = input[at++]; value |= uint64_t(byte & 127) << shift;
          if (!(byte & 128)) return value;
        }
        throw std::runtime_error("The RAR5 header is malformed.");
      };
      vint(); const auto type = vint(), flags = vint();
      if (flags & 1) vint();
      if (flags & 2) vint();
      if (type == 1 && (vint() & 1)) throw std::runtime_error("Split RAR5 archives are not supported.");
    }
    Entries entries;
    if (raw) {
      // Read the entire compressed stream before parsing a contained archive. TAR readers can
      // stop at their end marker before the outer compressor's checksum/footer is reached.
      // The temporary TAR container gets bounded space for its per-entry headers and padding.
      r->limit = limit + 10000 * 1024;
      auto stream = read_entries(input, length, password, fallback, true, *r);
      r->limit = limit;
      if (stream.size() != 1) throw std::runtime_error("This compression stream has no file contents.");
      if (raw == 1 && stream[0].data.empty()) entries = std::move(stream);
      else try {
        entries = read_entries(stream[0].data.data(), stream[0].data.size(), password, fallback, false, *r, raw == 2);
      } catch (const std::runtime_error& e) {
        if (raw == 2 || std::string(e.what()) != "Unrecognized archive format") throw;
        entries = std::move(stream);
        if (entries[0].data.size() > limit) throw std::runtime_error("This file exceeds the expanded size limit.");
        r->expanded = entries[0].data.size();
        r->source = "single compressed file";
      }
    } else entries = read_entries(input, length, password, fallback, false, *r);
    if (nested_tar) {
      if (entries.size() != 1 || archive_entry_filetype(entries[0].header.get()) != AE_IFREG)
        throw std::runtime_error("TAR.7Z must contain exactly one regular TAR file.");
      auto inner = read_entries(entries[0].data.data(), entries[0].data.size(), password, fallback, false, *r, true);
      entries = std::move(inner);
      r->source = "TAR inside 7Z";
    }
    validate_and_copy_links(entries, target, *r);
    write_entries(entries, target, *r);
    r->info = "{\"entries\":" + std::to_string(entries.size()) + ",\"expandedBytes\":" + std::to_string(r->expanded)
      + ",\"normalizedPaths\":" + std::to_string(r->normalized) + ",\"hardlinksCopied\":" + std::to_string(r->copied_links) + ",\"hardlinksKept\":" + std::to_string(r->kept_links) + "}";
  } catch (const std::exception& e) { r->error = e.what(); r->bytes.clear(); }
  catch (...) { r->error = "The archive could not be converted within this device's memory limit."; r->bytes.clear(); }
  return r.release();
}
EMSCRIPTEN_KEEPALIVE void tm_archive_destroy(Result* p) { delete p; }
EMSCRIPTEN_KEEPALIVE const char* tm_archive_error(Result* p) { return p->error.c_str(); }
EMSCRIPTEN_KEEPALIVE const char* tm_archive_info(Result* p) { return p->info.c_str(); }
EMSCRIPTEN_KEEPALIVE const char* tm_archive_source(Result* p) { return p->source.c_str(); }
EMSCRIPTEN_KEEPALIVE const unsigned char* tm_archive_bytes(Result* p) { return p->bytes.data(); }
EMSCRIPTEN_KEEPALIVE size_t tm_archive_length(Result* p) { return p->bytes.size(); }
}
