From 0886ad693a1d43fc24925a0ac638659a474e8010 Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Fri, 11 Sep 2026 09:34:59 +0200 Subject: [PATCH] Register `luazip` module This removes the runtime dependency on the external `lzip` C library. --- lua/libs/lzip/Makefile | 75 --- lua/libs/lzip/src/lzip.cpp | 735 ------------------------------ src/pob/modules.rs | 3 + src/pob/modules/luazip.rs | 158 +++++++ src/pob/modules/luazip/archive.rs | 716 +++++++++++++++++++++++++++++ 5 files changed, 877 insertions(+), 810 deletions(-) delete mode 100644 lua/libs/lzip/Makefile delete mode 100644 lua/libs/lzip/src/lzip.cpp create mode 100644 src/pob/modules/luazip.rs create mode 100644 src/pob/modules/luazip/archive.rs diff --git a/lua/libs/lzip/Makefile b/lua/libs/lzip/Makefile deleted file mode 100644 index 17c062c..0000000 --- a/lua/libs/lzip/Makefile +++ /dev/null @@ -1,75 +0,0 @@ -T=lzip - -UNAME ?= $(shell uname) -DESTDIR ?= / -PKG_CONFIG ?= pkg-config -INSTALL ?= install -RM ?= rm -LUA_IMPL ?= luajit -CC ?= $(MAC_ENV) g++ - -LUA_VERSION = $(shell $(PKG_CONFIG) --print-provides --silence-errors $(LUA_IMPL)) -ifeq ($(LUA_VERSION),) -LUA_CMOD ?= /usr/lib/lua/5.1 -LUA_LMOD ?= /usr/share/lua/5.1 -LIBDIR ?= /usr/lib -LUA_INC ?= /usr/include -ZLIB_LIBS = -L/usr/lib -lz -else -LUA_CMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_CMOD $(LUA_IMPL)) -LUA_LMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_LMOD $(LUA_IMPL)) -LIBDIR ?= $(shell $(PKG_CONFIG) --variable libdir $(LUA_IMPL)) -LUA_INC ?= $(shell $(PKG_CONFIG) --variable includedir $(LUA_IMPL)) -LUA_LIBS = $(shell $(PKG_CONFIG) --libs $(LUA_IMPL)) -ZLIB_LIBS = $(shell $(PKG_CONFIG) --libs zlib) -endif - -ifeq ($(UNAME), Linux) -OS_FLAGS ?= -shared -endif -ifeq ($(UNAME), Darwin) -OS_FLAGS ?= -bundle -undefined dynamic_lookup -MAC_ENV ?= env MACOSX_DEPLOYMENT_TARGET='10.3' -endif - -ifneq ($(DEBUG),) -DBG = -ggdb -endif - -ifeq ($(DEV),) -WARN = -Wall -Wno-unused-value -else -WARN = -Wall -W -Waggregate-return -Wcast-align -Wmissing-prototypes -Wnested-externs -Wshadow -Wwrite-strings -pedantic -endif - -INCLUDES = -I$(LUA_INC) -DEFINES = -LIBS = $(ZLIB_LIBS) -lstdc++ - -COMMONFLAGS = -O2 -g -pipe -fPIC $(OS_FLAGS) $(DBG) -LF = $(LIBS) $(LDFLAGS) -CF = $(INCLUDES) $(DEFINES) $(COMMONFLAGS) $(WARN) -DPTHREADS $(CFLAGS) - -SRCS = src/*.cpp -OBJS = $(subst src/,,$(subst .c,.o,$(SRCS))) - -BIN = $(T).so -STATIC_LIB = $(T).a - -all: $(BIN) - -$(BIN): $(SRCS) - $(CC) $(CF) -o $@ $^ $(LF) - -$(OBJS): $(SRCS) - $(CC) $(CF) -c $^ $(LF) - -$(STATIC_LIB): $(OBJS) - ar rcs $@ $^ - -install: all - $(INSTALL) -d $(DESTDIR)$(LUA_CMOD) - $(INSTALL) $(BIN) $(DESTDIR)$(LUA_CMOD) - -clean: - $(RM) -f $(BIN) $(OBJS) $(STATIC_LIB) diff --git a/lua/libs/lzip/src/lzip.cpp b/lua/libs/lzip/src/lzip.cpp deleted file mode 100644 index 9b84bf0..0000000 --- a/lua/libs/lzip/src/lzip.cpp +++ /dev/null @@ -1,735 +0,0 @@ -#include -#include -#include - -#include "zlib.h" - -#ifdef _WIN32 -#define LZIP_EXPORT __declspec(dllexport) -#else -#define LZIP_EXPORT -#endif - -extern "C" { -#include "lua.h" -#include "lauxlib.h" -#include "lualib.h" -#include "luajit.h" -} - -typedef unsigned char byte; -typedef unsigned int dword; -typedef unsigned long lword; - -char* AllocString(char* st) -{ - if (st == NULL) { - return NULL; - } - - int aslen = strlen(st) + 1; - char* al = new char[aslen]; - strcpy(al, st); - return al; -} - -char* AllocStringLen(int len) -{ - char* al = new char[len+1]; - al[len] = 0; - return al; -} - -void FreeString(char* st) -{ - if (st) delete st; -} - -// ============= -// Configuration -// ============= - -static const int FS_INFLATE_BUFFER = 65536; - -// ========================== -// Zip File format structures -// ========================== - -#pragma pack(push, 1) - -struct zf_cdHeader_s { - int sig; // 0x02014b50 (50,4B,01,02) - short ver_made; - short ver_ext; - short flag; - short method; - short ftime; - short fdate; - int crc32; - lword szComp; - lword szUcomp; - short szName; - short szExtra; - short szComm; - short nDisk; - short attInt; - int attExt; - int hOffset; -}; - -struct zf_localHeader_s { - int sig; // 0x04034b50 (50,4B,03,04) - short ver_ext; - short flag; - short method; - short ftime; - short fdate; - int crc32; - lword szComp; - lword szUcomp; - short szName; - short szExtra; -}; - -struct zf_dataDesc_s { - int crc32; - lword szComp; - lword szUcomp; -}; - -struct zf_cdEnd_s { - int sig; // 0x06054b50 (50,4B,05,06) - short nDisk; - short stDisk; - short noeDisk; - short noeTotal; - int szTotal; - int cdOffset; - short szComm; -}; - -#pragma pack(pop) - -// ========================= -// Zip File format constants -// ========================= - -static const int ZF_MAXVER = 20; - -static const int ZF_GPBF_ENC = 0x0001; -static const int ZF_GPBF_DD = 0x0008; - -static const int ZF_METHOD_STORE = 0; -static const int ZF_METHOD_DEFLATE = 8; - -static const int ZF_SIG_CDHEADER = 0x02014B50; -static const int ZF_SIG_LOCALHEADER = 0x04034B50; -static const int ZF_SIG_CDEND = 0x06054B50; - -// =============== -// ZLib Alloc/Free -// =============== - -static void* ZF_Alloc(void* unused, dword num, dword size) -{ - return new byte[num*size]; -} - -static void ZF_Free(void* unused, void* ptr) -{ - delete (byte*)ptr; -} - -// ======= -// Classes -// ======= - -struct fs_fileInfo_s { - FILE* f; // Zip file - char* name; // Filename - int fo; // File offset - int szU; // Uncompressed size - int szC; // Compressed size, 0 if not compressed -}; - -// ================ -// fsInflator class -// ================ - -class fs_inflator_c { -public: - fs_inflator_c(fs_fileInfo_s* i); - ~fs_inflator_c(); - int Inflate(byte* buf, int len);// Inflate - -private: - int pC; // Read pointer - byte* ibuf; // Input buffer - int ibuflen; // Input buffer length - fs_fileInfo_s* i; // Info structure - z_stream* zst; // ZLib stream - - void FillInput();// Fill decompression input -}; - -fs_inflator_c::fs_inflator_c(fs_fileInfo_s* info) -{ - i = info; - - // Initialise stream - zst = new z_stream; - memset(zst, 0, sizeof(z_stream)); - zst->zalloc = ZF_Alloc; - zst->zfree = ZF_Free; - - // Initialise decompression input - pC = 0; - if (i->szC < FS_INFLATE_BUFFER) { - ibuflen = i->szC; - } else { - ibuflen = FS_INFLATE_BUFFER; - } - ibuf = new byte[ibuflen]; - FillInput(); - - // Start decompressor - inflateInit2(zst, -MAX_WBITS); -} - -fs_inflator_c::~fs_inflator_c() -{ - // Stop decompressor - inflateEnd(zst); - - // Release stream and input buffer - delete ibuf; - delete zst; -} - -void fs_inflator_c::FillInput() -{ - // Relocate any remaining input - int remin = zst->avail_in; - if (remin) { - memcpy(ibuf, zst->next_in, remin); - } - - // Get reading amount - int rdmax = ibuflen - remin; - int rd = i->szC - pC; - if (rd > rdmax) { - rd = rdmax; - } - - // Read into buffer - if (rd) { - fseek(i->f, i->fo + pC, SEEK_SET); - fread(ibuf + remin, rd, 1, i->f); - } - - // Update stream - zst->next_in = ibuf; - zst->avail_in+= rd; - pC+= rd; -} - -int fs_inflator_c::Inflate(byte* out, int len) -{ - // Prepare stream - zst->next_out = out; - zst->avail_out = len; - - while (1) { - // Decompress some data - int r = inflate(zst, Z_SYNC_FLUSH); - - switch (r) { - case Z_OK: - // Progress made, check if we're done - if (zst->avail_out == 0) { - return len; - } - break; - case Z_BUF_ERROR: - // No progress made, so give it more input - FillInput(); - break; - default: - // We got an error - case Z_STREAM_END: - // Reached the end of the stream - return len - zst->avail_out; - } - } -} - -// ============= -// fsFile class -// ============= - -enum vf_state_e { - VF_OPEN =0x01, // Open - VF_SEEK =0x04 // Seek enabled -}; - -class fs_file_c { -public: - fs_file_c(fs_fileInfo_s* i); - ~fs_file_c(); - void Seek(int pos, int mode); // Seek - int Read(byte* buf, int len); // Read data - int Length(); // Return the file length - int Tell(); // Return the read pointer - -private: - fs_fileInfo_s* i; // Info structure - int pU; // Read pointer - fs_inflator_c* inf; // Inflator -}; - -fs_file_c::fs_file_c(fs_fileInfo_s* info) -{ - i = info; - - // Create inflator - if (i->szC) { - inf = new fs_inflator_c(i); - } else { - inf = NULL; - } - - // Set position - pU = 0; -} - -fs_file_c::~fs_file_c() -{ - delete inf; -} - -void fs_file_c::Seek(int pos, int mode) -{ - int seekto; - - switch (mode) { - case SEEK_SET: - seekto = pos; - break; - case SEEK_CUR: - seekto = pU + pos; - break; - case SEEK_END: - seekto = i->szU - pos; - break; - default: - return; - } - - if (i->szC) { - int diff = seekto - pU; - if (diff > 0) { - // Seek forward - byte* sk = new byte[diff]; - Read(sk, diff); - delete[] sk; - } else if (diff < 0) { - // Restart reading - pU = 0; - // Recreate inflator - delete inf; - inf = new fs_inflator_c(i); - if (seekto) { - // Seek forward - byte* sk = new byte[seekto]; - Read(sk, seekto); - delete[] sk; - } - } - } else { - pU = seekto; - if (pU < 0) { - pU = 0; - } else if (pU > i->szU) { - pU = i->szU; - } - } -} - -int fs_file_c::Read(byte* out, int len) -{ - // Determine read length - int rp = len + pU; - if (rp > i->szU) len = i->szU - pU; - if (len == 0) { - return 0; - } - - if (i->szC) { - // Decompress - len = inf->Inflate(out, len); - } else { - // Raw read - fseek(i->f, i->fo + pU, SEEK_SET); - len = fread(out, 1, len, i->f); - } - - pU+= len; - return len; -} - -int fs_file_c::Length() -{ - return i->szU; -} - -int fs_file_c::Tell() -{ - return pU; -} - -// ============= -// zipFile class -// ============= - -class fs_zipFile_c { -public: - fs_zipFile_c(const char* zname); - ~fs_zipFile_c(); - - int numFiles; - fs_fileInfo_s** files; -private: - FILE* zf; // File handle - int filesSz; - - int GetSignature(); // Get next signature -}; - -int fs_zipFile_c::GetSignature() -{ - int sig = 0; - if (fread(&sig, 4, 1, zf) == 0) { - return 0; - } - fseek(zf, -4, SEEK_CUR); - return sig; -} - -fs_zipFile_c::fs_zipFile_c(const char* zname) -{ - numFiles = 0; - filesSz = 32; - files = new fs_fileInfo_s*[filesSz]; - - int sig; - - // Open and lock file - zf = fopen(zname, "rb"); - if (zf == NULL) { - return; - } - - // Check signature - sig = GetSignature(); - if (strncmp((char*)&sig, "Rar", 3) == 0) { - fclose(zf); - return; - } - - // Read local headers - while (sig == ZF_SIG_LOCALHEADER) { - zf_localHeader_s lh; - if (fread(&lh, sizeof(lh), 1, zf) == 0) { - fclose(zf); - return; - } - - if (lh.szName) { - // Read filename - char* fname = AllocStringLen(lh.szName); - fread(fname, lh.szName, 1, zf); - - // Add it in if it is a file - if (fname[lh.szName-1] != '/') { - // Fill in info - fs_fileInfo_s* fi = new fs_fileInfo_s; - fi->f = zf; - fi->name = fname; - fi->fo = ftell(zf) + lh.szExtra; - fi->szU = lh.szUcomp; - fi->szC = (lh.method == ZF_METHOD_DEFLATE)? lh.szComp : 0; - - // Record file - if (numFiles == filesSz) { - filesSz<<= 1; - files = (fs_fileInfo_s**)realloc(files, sizeof(fs_fileInfo_s*)*filesSz); - } - files[numFiles++] = fi; - } else { - FreeString(fname); - } - - // Skip the extra information and file data - fseek(zf, lh.szExtra + lh.szComp, SEEK_CUR); - } - - sig = GetSignature(); - } -} - -fs_zipFile_c::~fs_zipFile_c() -{ - fclose(zf); - for (int f = 0; f < numFiles; f++) { - delete files[f]->name; - delete files[f]; - } - delete files; -} - -// ============= -// Lua Interface -// ============= - -static int IsUserData(lua_State* L, int index, const char* metaName) -{ - if (lua_type(L, index) != LUA_TUSERDATA || lua_getmetatable(L, index) == 0) { - return 0; - } - lua_getfield(L, lua_upvalueindex(1), metaName); - int ret = lua_rawequal(L, -2, -1); - lua_pop(L, 2); - return ret; -} - -struct lzip_s { - fs_zipFile_c* zipFile; -}; -static lzip_s* GetZip(lua_State* L, const char* method, bool valid) -{ - if ( !IsUserData(L, 1, "zipMeta") ) { - luaL_error(L, "zip:%s() must be used on a zip handle", method); - } - lzip_s* lz = (lzip_s*)lua_touserdata(L, 1); - lua_remove(L, 1); - if (valid && lz->zipFile == NULL) { - luaL_error(L, "zip:%s(): zip handle is closed"); - } - return lz; -} - -struct lzipFile_s { - fs_file_c* file; -}; -static lzipFile_s* GetZipFile(lua_State* L, const char* method, bool valid) -{ - if ( !IsUserData(L, 1, "zipFileMeta") ) { - luaL_error(L, "zipFile:%s() must be used on a zip file handle", method); - } - lzipFile_s* lzf = (lzipFile_s*)lua_touserdata(L, 1); - lua_remove(L, 1); - if (valid && lzf->file == NULL) { - luaL_error(L, "zipFile:%s(): zip file handle is closed"); - } - return lzf; -} - -static int l_open(lua_State* L) -{ - int n = lua_gettop(L); - if (n < 1 || !lua_isstring(L, 1)) { - luaL_error(L, "Usage: lzip.open(fileName)"); - } - fs_zipFile_c* zipFile = new fs_zipFile_c(lua_tostring(L, 1)); - if (zipFile->numFiles == 0) { - delete zipFile; - return 0; - } - lzip_s* lz = (lzip_s*)lua_newuserdata(L, sizeof(lzip_s)); - lz->zipFile = zipFile; - lua_pushvalue(L, lua_upvalueindex(2)); - lua_setmetatable(L, -2); - return 1; -} - -static int l_zip_Close(lua_State* L) -{ - lzip_s* lz = GetZip(L, "Closea", false); - delete lz->zipFile; - lz->zipFile = NULL; - return 0; -} - -static int l_zip_GetNumFiles(lua_State* L) -{ - lzip_s* lz = GetZip(L, "GetNumFiles", true); - lua_pushinteger(L, lz->zipFile->numFiles); - return 1; -} - -static int l_zip_GetFileName(lua_State* L) -{ - lzip_s* lz = GetZip(L, "GetFileName", true); - int n = lua_gettop(L); - if (n < 1 || !lua_isnumber(L, 1)) { - luaL_error(L, "Usage: zip:GetFileName(index)"); - } - int index = lua_tointeger(L, 1); - if (index < 1 || index > lz->zipFile->numFiles) { - return 0; - } - lua_pushstring(L, lz->zipFile->files[index - 1]->name); - return 1; -} - -static int l_zip_GetFileSize(lua_State* L) -{ - lzip_s* lz = GetZip(L, "GetFileSize", true); - int n = lua_gettop(L); - if (n < 1 || !lua_isnumber(L, 1)) { - luaL_error(L, "Usage: zip:GetFileSize(index)"); - } - int index = lua_tointeger(L, 1); - if (index < 1 || index > lz->zipFile->numFiles) { - return 0; - } - lua_pushinteger(L, lz->zipFile->files[index - 1]->szU); - return 1; -} - -static int l_zip_OpenFile(lua_State* L) -{ - lzip_s* lz = GetZip(L, "OpenFile", true); - int n = lua_gettop(L); - if (n < 1 || !(lua_isnumber(L, 1) || lua_isstring(L, 1))) { - luaL_error(L, "Usage: zip:OpenFile(index) or zip:OpenFile(fileName)"); - } - fs_fileInfo_s* i = NULL; - if (lua_isnumber(L, 1)) { - int index = lua_tointeger(L, 1); - if (index < 1 || index > lz->zipFile->numFiles) { - luaL_error(L, "zip:OpenFile(): invalid index"); - } - i = lz->zipFile->files[index - 1]; - } else { - const char* name = lua_tostring(L, 1); - for (int index = 0; index < lz->zipFile->numFiles; index++) { - if ( !strcmp(name, lz->zipFile->files[index]->name) ) { - i = lz->zipFile->files[index]; - break; - } - } - if ( !i ) { - return 0; - } - } - fs_file_c* file = new fs_file_c(i); - lzipFile_s* lzf = (lzipFile_s*)lua_newuserdata(L, sizeof(lzipFile_s)); - lzf->file = file; - lua_pushvalue(L, lua_upvalueindex(2)); - lua_setmetatable(L, -2); - return 1; -} - -static int l_zipFile_Close(lua_State* L) -{ - lzipFile_s* lzf = GetZipFile(L, "Close", false); - delete lzf->file; - lzf->file = NULL; - return 0; -} - -static int l_zipFile_Read(lua_State* L) -{ - lzipFile_s* lzf = GetZipFile(L, "Read", true); - int n = lua_gettop(L); - if (n < 1) { - luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")"); - } - int count = 0; - if (lua_isnumber(L, 1)) { - count = lua_tointeger(L, 1); - } else { - if ( !strcmp(lua_tostring(L, 1), "*a") ) { - count = lzf->file->Length() - lzf->file->Tell(); - } else { - luaL_error(L, "zipFile:Read(): unrecognised format: %s", lua_tostring(L, 1)); - } - } - if (count < 1) { - lua_pushstring(L, ""); - return 1; - } - byte* buf = new byte[count]; - lzf->file->Read(buf, count); - lua_pushlstring(L, (char*)buf, count); - return 1; -} - -static int l_zipFile_Length(lua_State* L) -{ - lzipFile_s* lzf = GetZipFile(L, "Read", true); - lua_pushinteger(L, lzf->file->Length()); - return 1; -} - -extern "C" LZIP_EXPORT int luaopen_lzip(lua_State* L) -{ - lua_settop(L, 0); - lua_newtable(L); // Library table - lua_newtable(L); // Zip metatable - lua_newtable(L); // Zip file metatable - - lua_pushvalue(L, 2); - lua_setfield(L, 1, "zipMeta"); - lua_pushvalue(L, 2); - lua_setfield(L, 2, "__index"); - - lua_pushvalue(L, 3); - lua_setfield(L, 1, "zipFileMeta"); - lua_pushvalue(L, 3); - lua_setfield(L, 3, "__index"); - - lua_pushvalue(L, 1); - lua_pushvalue(L, 2); - lua_pushcclosure(L, l_open, 2); - lua_setfield(L, 1, "open"); - - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zip_Close, 1); - lua_setfield(L, 2, "__gc"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zip_Close, 1); - lua_setfield(L, 2, "Close"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zip_GetNumFiles, 1); - lua_setfield(L, 2, "GetNumFiles"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zip_GetFileName, 1); - lua_setfield(L, 2, "GetFileName"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zip_GetFileSize, 1); - lua_setfield(L, 2, "GetFileSize"); - lua_pushvalue(L, 1); - lua_pushvalue(L, 3); - lua_pushcclosure(L, l_zip_OpenFile, 2); - lua_setfield(L, 2, "OpenFile"); - - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zipFile_Close, 1); - lua_setfield(L, 3, "__gc"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zipFile_Close, 1); - lua_setfield(L, 3, "Close"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zipFile_Read, 1); - lua_setfield(L, 3, "Read"); - lua_pushvalue(L, 1); - lua_pushcclosure(L, l_zipFile_Length, 1); - lua_setfield(L, 3, "Length"); - - // Pop metatables - lua_pop(L, 2); - - return 1; -} diff --git a/src/pob/modules.rs b/src/pob/modules.rs index 03a313f..6010c84 100644 --- a/src/pob/modules.rs +++ b/src/pob/modules.rs @@ -2,6 +2,8 @@ pub mod luacurl; #[cfg(feature = "bundled-lua-modules")] pub mod luasocket; +#[cfg(feature = "bundled-lua-modules")] +pub mod luazip; use mlua::{Lua, Result as LuaResult}; @@ -10,6 +12,7 @@ pub fn register(lua: &Lua) -> LuaResult<()> { lua.register_module("lua-utf8", luautf8::create_module(lua)?)?; lua.register_module("socket", luasocket::create_module(lua)?)?; lua.register_module("lcurl.safe", luacurl::create_module(lua)?)?; + lua.register_module("lzip", luazip::create_module(lua)?)?; Ok(()) } diff --git a/src/pob/modules/luazip.rs b/src/pob/modules/luazip.rs new file mode 100644 index 0000000..d36e7ab --- /dev/null +++ b/src/pob/modules/luazip.rs @@ -0,0 +1,158 @@ +//! Rust port of SimpleGraphic's `lzip`, a library for reading zip files. +//! + +use std::{fs::File, io::Read}; + +use mlua::{Integer as LuaInteger, Lua, Result as LuaResult, Table, UserData, UserDataMethods}; + +use crate::pob::modules::luazip::archive::{ZipArchive, ZipFile}; + +mod archive; + +pub fn create_module(lua: &Lua) -> LuaResult { + let exports = lua.create_table()?; + + exports.set( + "open", + lua.create_function(|_, path: String| { + let file = File::open(&path).map_err(mlua::Error::external)?; + let archive = ZipArchive::new(file).map_err(mlua::Error::external)?; + Ok(ZipArchiveHandle { + archive: Some(archive), + }) + })?, + )?; + + Ok(exports) +} + +fn to_index(i: LuaInteger, len: usize) -> Option { + usize::try_from(i.checked_sub(1)?).ok().filter(|&i| i < len) +} + +struct ZipArchiveHandle { + archive: Option>, +} + +impl ZipArchiveHandle { + fn get(&self) -> LuaResult<&ZipArchive> { + self.archive + .as_ref() + .ok_or_else(|| mlua::Error::runtime("zip handle is closed")) + } +} + +impl UserData for ZipArchiveHandle { + fn add_methods>(methods: &mut M) { + methods.add_method_mut("Close", |_, this, ()| { + this.archive = None; + Ok(()) + }); + + methods.add_method("GetNumFiles", |_, this, ()| Ok(this.get()?.entries().len())); + + methods.add_method("GetFileName", |lua, this, index: LuaInteger| { + let entries = this.get()?.entries(); + let len = entries.len(); + match to_index(index, len) { + Some(i) => Ok(Some(lua.create_string(entries[i].name())?)), + None => Ok(None), + } + }); + + methods.add_method("GetFileSize", |_, this, index: LuaInteger| { + let entries = this.get()?.entries(); + let len = entries.len(); + match to_index(index, len) { + Some(i) => Ok(Some(entries[i].uncompressed_size())), + None => Ok(None), + } + }); + + methods.add_method_mut("OpenFile", |_, this, index_or_name: mlua::Value| { + let archive = this.get()?; + let entries = archive.entries(); + + let index = match index_or_name { + mlua::Value::Integer(i) => { + let Some(index) = to_index(i, entries.len()) else { + return Err(mlua::Error::runtime("zip:OpenFile(): invalid index")); + }; + index + } + mlua::Value::String(s) => { + let name = s.as_bytes(); + let Some(index) = entries.iter().position(|e| e.name()[..] == *name) else { + return Ok(None); + }; + index + } + _ => { + return Err(mlua::Error::runtime( + "Usage: zip:OpenFile(index) or zip:OpenFile(fileName)", + )); + } + }; + + let file = archive.by_index(index).map_err(mlua::Error::external)?; + Ok(Some(ZipFileHandle { file: Some(file) })) + }); + } +} + +struct ZipFileHandle { + file: Option>, +} + +impl ZipFileHandle { + fn get(&mut self) -> LuaResult<&ZipFile> { + self.file + .as_ref() + .ok_or_else(|| mlua::Error::runtime("zip file handle is closed")) + } + + fn get_mut(&mut self) -> LuaResult<&mut ZipFile> { + self.file + .as_mut() + .ok_or_else(|| mlua::Error::runtime("zip file handle is closed")) + } +} + +impl UserData for ZipFileHandle { + fn add_methods>(methods: &mut M) { + methods.add_method_mut("Close", |_, this, ()| { + this.file = None; + Ok(()) + }); + + methods.add_method_mut("Length", |_, this, ()| Ok(this.get()?.size())); + + methods.add_method_mut("Read", |lua, this, arg: mlua::Value| { + let file = this.get_mut()?; + let mut buf = Vec::new(); + + match arg { + mlua::Value::String(s) if s.as_bytes() == b"*a" => { + file.read_to_end(&mut buf).map_err(mlua::Error::external)?; + } + mlua::Value::Integer(n) if n >= 0 => { + if n == 0 { + return lua.create_string(""); + } + + file.take(n as u64) + .read_to_end(&mut buf) + .map_err(mlua::Error::external)?; + } + other => { + return Err(mlua::Error::runtime(format!( + "zipFile:Read(): unrecognised format: {}", + other.to_string()? + ))); + } + } + + lua.create_string(buf) + }); + } +} diff --git a/src/pob/modules/luazip/archive.rs b/src/pob/modules/luazip/archive.rs new file mode 100644 index 0000000..266bef1 --- /dev/null +++ b/src/pob/modules/luazip/archive.rs @@ -0,0 +1,716 @@ +use std::{ + cell::RefCell, + io::{self, Read, Seek, SeekFrom, Take}, + rc::Rc, +}; + +use flate2::read::DeflateDecoder; + +const EOCD_LEN: usize = 22; +const EOCD_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x05, 0x06]; +const EOCD_MAX_SIZE: usize = EOCD_LEN + u16::MAX as usize; // fixed fields + variable-sized comment + +const EOCD64_LEN: usize = 56; +const EOCD64_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x06, 0x06]; + +const EOCD64_LOCATOR_LEN: usize = 20; +const EOCD64_LOCATOR_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x06, 0x07]; + +const CDFH_LEN: usize = 46; +const CDFH_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x01, 0x02]; + +const LFH_LEN: usize = 30; +const LFH_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x03, 0x04]; + +// 0 = encrypted | 6 = strong encryption | 13 = header masked +const ENCRYPTED_FLAGS: u16 = (1 << 0) | (1 << 6) | (1 << 13); + +#[inline] +fn parse_u16(b: &[u8], at: usize) -> u16 { + u16::from_le_bytes(b[at..at.saturating_add(2)].try_into().unwrap()) +} + +#[inline] +fn parse_u32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes(b[at..at.saturating_add(4)].try_into().unwrap()) +} + +#[inline] +fn parse_u64(b: &[u8], at: usize) -> u64 { + u64::from_le_bytes(b[at..at.saturating_add(8)].try_into().unwrap()) +} + +#[inline] +fn read_u8_slice(reader: &mut R, size: usize) -> io::Result> { + let mut buf = vec![0; size]; + reader.read_exact(&mut buf)?; + Ok(buf.into_boxed_slice()) +} + +#[inline] +fn take_u32(data: &[u8], at: &mut usize) -> io::Result { + let bytes = data + .get(*at..at.saturating_add(4)) + .ok_or_else(|| invalid("truncated extra field"))?; + + *at += 4; + Ok(u32::from_le_bytes(bytes.try_into().unwrap())) +} + +#[inline] +fn take_u64(data: &[u8], at: &mut usize) -> io::Result { + let bytes = data + .get(*at..at.saturating_add(8)) + .ok_or_else(|| invalid("truncated extra field"))?; + + *at += 8; + Ok(u64::from_le_bytes(bytes.try_into().unwrap())) +} + +#[inline] +fn invalid(msg: impl Into>) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, msg) +} + +#[inline] +fn unsupported(msg: impl Into>) -> io::Error { + io::Error::new(io::ErrorKind::Unsupported, msg) +} + +struct SharedReader { + inner: Rc>, + pos: u64, +} + +impl Read for SharedReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let mut r = self.inner.borrow_mut(); + r.seek(SeekFrom::Start(self.pos))?; + let n = r.read(buf)?; + self.pos += n as u64; + Ok(n) + } +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +enum CompressionMethod { + Stored, + Deflate, + Other(u16), +} + +impl From for CompressionMethod { + fn from(value: u16) -> Self { + match value { + 0 => Self::Stored, + 8 => Self::Deflate, + other => Self::Other(other), + } + } +} + +#[derive(Debug)] +pub struct ZipArchive { + reader: Rc>, + entries: Vec, +} + +impl ZipArchive { + pub fn new(mut reader: R) -> io::Result { + let cd_info = read_central_directory_info(&mut reader)?; + let entries = parse_central_directory( + &mut reader, + cd_info.cd_offset, + cd_info.cd_size, + cd_info.cd_records_on_disk as usize, + )?; + + Ok(Self { + reader: Rc::new(RefCell::new(reader)), + entries, + }) + } + + pub fn entries(&self) -> &[ZipEntry] { + &self.entries + } + + pub fn by_index(&self, index: usize) -> io::Result> { + let entry = self + .entries + .get(index) + .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "entry not found"))?; + + // reject unsupported entries + if entry.flags & ENCRYPTED_FLAGS != 0 { + return Err(unsupported("encrypted entries are not supported")); + } + let deflated = match entry.compression { + CompressionMethod::Stored => { + if entry.compressed_size != entry.uncompressed_size { + return Err(invalid("uncompressed entry has mismatched sizes")); + } + false + } + CompressionMethod::Deflate => true, + CompressionMethod::Other(method) => { + return Err(unsupported(format!( + "unsupported compression method {method}" + ))); + } + }; + + let start = data_start(&mut *self.reader.borrow_mut(), entry)?; + let limited = SharedReader { + inner: Rc::clone(&self.reader), + pos: start, + } + .take(entry.compressed_size); + + Ok(ZipFile { + inner: if deflated { + Inner::Deflate(DeflateDecoder::new(limited)) + } else { + Inner::Stored(limited) + }, + expected_size: entry.uncompressed_size, + produced: 0, + }) + } +} + +/// Entry metadata +#[derive(Debug)] +pub struct ZipEntry { + name: Box<[u8]>, + flags: u16, + compression: CompressionMethod, + _crc32: u32, + compressed_size: u64, + uncompressed_size: u64, + file_start_disk: u32, + local_header_offset: u64, + extra_fields: Box<[ExtraField]>, +} + +impl ZipEntry { + pub fn name(&self) -> &[u8] { + &self.name + } + + pub fn uncompressed_size(&self) -> u64 { + self.uncompressed_size + } +} + +impl From for ZipEntry { + fn from(cdfh: CDFH) -> Self { + Self { + name: cdfh.file_name, + flags: cdfh.general_purpose_bit_flag, + compression: CompressionMethod::from(cdfh.compression_method), + _crc32: cdfh.crc32, + compressed_size: u64::from(cdfh.compressed_size), + uncompressed_size: u64::from(cdfh.uncompressed_size), + local_header_offset: u64::from(cdfh.local_file_header_offset), + file_start_disk: u32::from(cdfh.file_start_disk), + extra_fields: cdfh.extra_fields, + } + } +} + +enum Inner { + Stored(Take>), + Deflate(DeflateDecoder>>), +} + +pub struct ZipFile { + inner: Inner, + expected_size: u64, + produced: u64, +} + +impl ZipFile { + pub fn size(&self) -> u64 { + self.expected_size + } +} + +impl Read for ZipFile { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + + // don't hand out more than one byte past the declared size to protect against malicious + // archives + let remaining = self.expected_size - self.produced.min(self.expected_size); + let max = remaining.saturating_add(1).min(buf.len() as u64) as usize; + let buf = &mut buf[..max]; + + let n = match &mut self.inner { + Inner::Stored(r) => r.read(buf)?, + Inner::Deflate(r) => r.read(buf)?, + }; + + if n > 0 { + self.produced += n as u64; + if self.produced > self.expected_size { + return Err(invalid("entry is larger than declared")); + } + } else { + if self.produced != self.expected_size { + return Err(invalid("entry is smaller than declared")); + } + } + + Ok(n) + } +} + +/// Returns the start position of an entrys payload. +fn data_start(r: &mut R, entry: &ZipEntry) -> io::Result { + r.seek(SeekFrom::Start(entry.local_header_offset))?; + + let mut buf = [0u8; LFH_LEN]; + r.read_exact(&mut buf)?; + + if [buf[0], buf[1], buf[2], buf[3]] != LFH_MAGIC_BYTES { + return Err(invalid("Invalid LFH magic number")); + } + + let name_len = parse_u16(&buf, 26) as u64; + let extra_len = parse_u16(&buf, 28) as u64; + Ok(entry.local_header_offset + LFH_LEN as u64 + name_len + extra_len) +} + +fn parse_central_directory( + reader: &mut R, + start: u64, + size: u64, + num_of_entries: usize, +) -> io::Result> { + reader.seek(SeekFrom::Start(start))?; + let end = start + .checked_add(size) + .ok_or_else(|| invalid("central directory too big"))?; + let mut entries = Vec::new(); + + for _ in 0..num_of_entries { + if reader.stream_position()? > end { + return Err(invalid("invalid number of entries")); + } + + let cdfh = parse_cdfh(reader)?; + + // check for ZIP64 sentinel values + let need_uncompressed = cdfh.uncompressed_size == u32::MAX; + let need_compressed = cdfh.compressed_size == u32::MAX; + let need_offset = cdfh.local_file_header_offset == u32::MAX; + let need_start_disk = cdfh.file_start_disk == u16::MAX; + + let mut entry = ZipEntry::from(cdfh); + + // update entry with info from ZIP64 extra field + if need_compressed || need_uncompressed || need_offset || need_start_disk { + let zip64_extra = entry + .extra_fields + .iter() + .find(|extra| extra.header == 0x0001) + .ok_or_else(|| invalid("ZIP64 extra field missing"))?; + + let data = &zip64_extra.data[..]; + let mut at = 0; + + if need_uncompressed { + entry.uncompressed_size = take_u64(data, &mut at)?; + } + if need_compressed { + entry.compressed_size = take_u64(data, &mut at)?; + } + if need_offset { + entry.local_header_offset = take_u64(data, &mut at)?; + } + if need_start_disk { + entry.file_start_disk = take_u32(data, &mut at)?; + } + } + + if entry.file_start_disk != 0 { + return Err(unsupported("split archives are not supported")); + } + + entries.push(entry); + } + + Ok(entries) +} + +/// Central Directory File Header (CDFH). +#[derive(Debug)] +#[allow(clippy::upper_case_acronyms)] +struct CDFH { + /// Version made by. + _version_made_by: u16, + /// Version needed to extract (minimum). + _version_needed_to_extract: u16, + /// General purpose bit flag. + general_purpose_bit_flag: u16, + /// Compression method. + compression_method: u16, + /// File last modification time. + _last_modification_time: u16, + /// File last modification date. + _last_modification_date: u16, + /// CRC-32 of uncompressed data. + crc32: u32, + /// Compressed size (or FF FF FF FF for ZIP64). + compressed_size: u32, + /// Uncompressed size (or FF FF FF FF for ZIP64). + uncompressed_size: u32, + /// Disk number where file starts (or FF FF for ZIP64). + file_start_disk: u16, + /// Internal file attributes. + _internal_file_attributes: u16, + /// External file attributes. + _external_file_attributes: u32, + /// Relative offset of local file header (or FF FF FF FF for ZIP64). This is the number of + /// bytes between the start of the first disk on which the file occurs, and the start of the + /// local file header. This allows software reading the central directory to locate the + /// position of the file inside the ZIP file. + local_file_header_offset: u32, + /// File name. + file_name: Box<[u8]>, + /// Extra field. + extra_fields: Box<[ExtraField]>, + /// File comment. + _file_comment: Box<[u8]>, +} + +/// Parses a CDFH. `reader` must be positioned at the start of a CDFH. +fn parse_cdfh(reader: &mut R) -> io::Result { + let mut buf = [0u8; CDFH_LEN]; + reader.read_exact(&mut buf)?; + + if [buf[0], buf[1], buf[2], buf[3]] != CDFH_MAGIC_BYTES { + return Err(invalid("Invalid CDFH magic number")); + } + + let file_name_length = parse_u16(&buf, 28) as usize; + let extra_fields_length = parse_u16(&buf, 30); + let file_comment_length = parse_u16(&buf, 32) as usize; + + Ok(CDFH { + _version_made_by: parse_u16(&buf, 4), + _version_needed_to_extract: parse_u16(&buf, 6), + general_purpose_bit_flag: parse_u16(&buf, 8), + compression_method: parse_u16(&buf, 10), + _last_modification_time: parse_u16(&buf, 12), + _last_modification_date: parse_u16(&buf, 14), + crc32: parse_u32(&buf, 16), + compressed_size: parse_u32(&buf, 20), + uncompressed_size: parse_u32(&buf, 24), + file_start_disk: parse_u16(&buf, 34), + _internal_file_attributes: parse_u16(&buf, 36), + _external_file_attributes: parse_u32(&buf, 38), + local_file_header_offset: parse_u32(&buf, 42), + file_name: read_u8_slice(reader, file_name_length)?, + extra_fields: read_extra_fields(reader, extra_fields_length)?, + _file_comment: read_u8_slice(reader, file_comment_length)?, + }) +} + +#[derive(Debug)] +struct ExtraField { + pub header: u16, + pub data: Box<[u8]>, +} + +fn read_extra_fields(reader: &mut R, size: u16) -> io::Result> { + let mut remaining = usize::from(size); + let mut fields = Vec::new(); + + while remaining > 0 { + if remaining < 4 { + return Err(invalid("truncated ZIP extra field")); + } + + let mut header = [0u8; 4]; + reader.read_exact(&mut header)?; + + let id = parse_u16(&header, 0); + let data_size = usize::from(parse_u16(&header, 2)); + + remaining -= 4; + + if data_size > remaining { + return Err(invalid("ZIP extra field data exceeds remaining length")); + } + + let mut data = vec![0u8; data_size]; + reader.read_exact(&mut data)?; + + fields.push(ExtraField { + header: id, + data: data.into_boxed_slice(), + }); + + remaining -= data_size; + } + + Ok(fields.into_boxed_slice()) +} + +/// Central directory metadata. +#[derive(Debug)] +struct CentralDirectoryInfo { + /// Number of this disk. + disk_number: u32, + /// Disk where central directory starts. + cd_start_disk: u32, + /// Number of central directory records on this disk. + cd_records_on_disk: u64, + /// Total number of central directory records. + cd_records_total: u64, + /// Size of central directory in bytes. + cd_size: u64, + /// Offset of start of central directory, relative to start of archive. + cd_offset: u64, + /// Comment + _comment: Box<[u8]>, +} + +impl CentralDirectoryInfo { + fn validate_single_disk(&self) -> io::Result<()> { + if self.disk_number != 0 + || self.cd_start_disk != 0 + || self.cd_records_on_disk != self.cd_records_total + { + return Err(unsupported("split archives are not supported")); + } + Ok(()) + } +} + +impl From for CentralDirectoryInfo { + fn from(eocd: EOCD) -> Self { + Self { + disk_number: u32::from(eocd.disk_number), + cd_start_disk: u32::from(eocd.cd_start_disk), + cd_records_on_disk: u64::from(eocd.cd_records_on_disk), + cd_records_total: u64::from(eocd.cd_records_total), + cd_size: u64::from(eocd.cd_size), + cd_offset: u64::from(eocd.cd_offset), + _comment: eocd.comment, + } + } +} + +impl From for CentralDirectoryInfo { + fn from(eocd: EOCD64) -> Self { + Self { + disk_number: eocd.disk_number, + cd_start_disk: eocd.cd_start_disk, + cd_records_on_disk: eocd.cd_records_on_disk, + cd_records_total: eocd.cd_records_total, + cd_size: eocd.cd_size, + cd_offset: eocd.cd_offset, + _comment: eocd.comment, + } + } +} + +fn read_central_directory_info(reader: &mut R) -> io::Result { + let eocd_start = find_eocd(reader)?; + reader.seek(SeekFrom::Start(eocd_start))?; + let eocd = parse_eocd(reader)?; + + let needs_zip64 = eocd.has_zip64_sentinels(); + + // check for presence of EOCD64 Locator which sits right before the EOCD + let locator_start = eocd_start.saturating_sub(EOCD64_LOCATOR_LEN as u64); + reader.seek(SeekFrom::Start(locator_start))?; + let eocd64_locator = parse_eocd64_locator(reader); + + let info = match eocd64_locator { + Ok(locator) => { + if locator.cd_start_disk != 0 || locator.disks_total != 1 { + return Err(unsupported("split archives are not supported")); + } + + // seek to and parse EOCD64 + reader.seek(SeekFrom::Start(locator.cd_offset))?; + let eocd64 = parse_eocd64(reader)?; + CentralDirectoryInfo::from(eocd64) + } + Err(_) if needs_zip64 => return Err(invalid("missing EOCD64")), + Err(_) => CentralDirectoryInfo::from(eocd), + }; + + info.validate_single_disk()?; + Ok(info) +} + +#[derive(Debug)] +struct EOCD64 { + /// Version made by. + _version_made_by: u16, + /// Version needed to extract (minimum). + _version_needed_to_extract: u16, + /// Number of this disk. + disk_number: u32, + /// Disk where central directory starts. + cd_start_disk: u32, + /// Number of central directory records on this disk. + cd_records_on_disk: u64, + /// Total number of central directory records. + cd_records_total: u64, + /// Size of central directory in bytes. + cd_size: u64, + /// Offset of start of central directory, relative to start of archive. + cd_offset: u64, + /// Comment. + comment: Box<[u8]>, +} + +/// Parses the EOCD64. `reader` must be positioned at the start of the EOCD64. +fn parse_eocd64(reader: &mut R) -> io::Result { + let mut buf = [0u8; EOCD64_LEN]; + reader.read_exact(&mut buf)?; + + if [buf[0], buf[1], buf[2], buf[3]] != EOCD64_MAGIC_BYTES { + return Err(invalid("Invalid EOCD64 magic number")); + } + + let size_minus_12 = parse_u64(&buf, 4) + 12; + let comment_length = size_minus_12 as usize - (EOCD64_LEN - 12); + + Ok(EOCD64 { + _version_made_by: parse_u16(&buf, 12), + _version_needed_to_extract: parse_u16(&buf, 14), + disk_number: parse_u32(&buf, 16), + cd_start_disk: parse_u32(&buf, 20), + cd_records_on_disk: parse_u64(&buf, 24), + cd_records_total: parse_u64(&buf, 32), + cd_size: parse_u64(&buf, 40), + cd_offset: parse_u64(&buf, 48), + comment: read_u8_slice(reader, comment_length)?, + }) +} + +#[derive(Debug)] +struct EOCD64Locator { + /// Disk where EOCD64 starts. + cd_start_disk: u32, + /// Offset to start of EOCD64, relative to start of archive. + cd_offset: u64, + /// Total number of disks. + disks_total: u32, +} + +/// Parses the EOCD64 Locator. `reader` must be positioned at the start of the EOCD64 Locator. +fn parse_eocd64_locator(reader: &mut R) -> io::Result { + let mut buf = [0u8; EOCD64_LOCATOR_LEN]; + reader.read_exact(&mut buf)?; + + if [buf[0], buf[1], buf[2], buf[3]] != EOCD64_LOCATOR_MAGIC_BYTES { + return Err(invalid("Invalid EOCD64 Locator magic number")); + } + + Ok(EOCD64Locator { + cd_start_disk: parse_u32(&buf, 4), + cd_offset: parse_u64(&buf, 8), + disks_total: parse_u32(&buf, 16), + }) +} + +/// End Of Central Directory record (EOCD). +#[derive(Debug)] +#[allow(clippy::upper_case_acronyms)] +struct EOCD { + /// Number of this disk (or FF FF for ZIP64). + disk_number: u16, + /// Disk where central directory starts (or FF FF for ZIP64). + cd_start_disk: u16, + /// Number of central directory records on this disk (or FF FF for ZIP64). + cd_records_on_disk: u16, + /// Total number of central directory records (or FF FF for ZIP64). + cd_records_total: u16, + /// Size of central directory in bytes (or FF FF FF FF for ZIP64). + cd_size: u32, + /// Offset of start of central directory, relative to start of archive (or FF FF FF FF for ZIP64). + cd_offset: u32, + /// Comment. + comment: Box<[u8]>, +} + +impl EOCD { + fn has_zip64_sentinels(&self) -> bool { + self.disk_number == u16::MAX + || self.cd_start_disk == u16::MAX + || self.cd_records_on_disk == u16::MAX + || self.cd_records_total == u16::MAX + || self.cd_size == u32::MAX + || self.cd_offset == u32::MAX + } +} + +/// Returns the start byte position of the EOCD. +fn find_eocd(reader: &mut R) -> io::Result { + // the EOCD is located at the end of the file and is at most `EOCD_MAX_SIZE` bytes long so the + // search is restricted to that region. + let file_len = reader.seek(SeekFrom::End(0))?; + let search_start = file_len.saturating_sub(EOCD_MAX_SIZE as u64); + reader.seek(SeekFrom::Start(search_start))?; + + let mut search_area = Vec::with_capacity((file_len - search_start) as usize); + reader.read_to_end(&mut search_area)?; + + let eocd_start_in_search_area = search_area + .windows(EOCD_MAGIC_BYTES.len()) + .enumerate() + .rev() + .find_map(|(pos, window)| { + if window != EOCD_MAGIC_BYTES { + return None; + } + + // we found the magic bytes! + // but they can theoretically appear in the comment so we need to verify that this + // candidate header ends exactly at the end of the search area. + let header_end = pos.checked_add(EOCD_LEN)?; + let header = search_area.get(pos..header_end)?; + let comment_length = u16::from_le_bytes([header[20], header[21]]) as usize; + if header_end.checked_add(comment_length)? == search_area.len() { + Some(pos) + } else { + None + } + }) + .ok_or_else(|| invalid("EOCD not found"))?; + + let eocd_start = search_start + eocd_start_in_search_area as u64; + Ok(eocd_start) +} + +/// Parses the EOCD. `reader` must be positioned at the start of the EOCD. +fn parse_eocd(reader: &mut R) -> io::Result { + let mut buf = [0u8; EOCD_LEN]; + reader.read_exact(&mut buf)?; + + if [buf[0], buf[1], buf[2], buf[3]] != EOCD_MAGIC_BYTES { + return Err(invalid("Invalid EOCD magic number")); + } + + let comment_length = parse_u16(&buf, 20) as usize; + + Ok(EOCD { + disk_number: parse_u16(&buf, 4), + cd_start_disk: parse_u16(&buf, 6), + cd_records_on_disk: parse_u16(&buf, 8), + cd_records_total: parse_u16(&buf, 10), + cd_size: parse_u32(&buf, 12), + cd_offset: parse_u32(&buf, 16), + comment: read_u8_slice(reader, comment_length)?, + }) +}