#include "Unzip.h" #define NOMINMAX #include #include "Utils.h" #include "Miniz.h" #include #include #include #include namespace updater { struct Unzip::Archive { mz_zip_archive zip; }; namespace { // Zip Slip 防护:拒绝绝对路径、盘符、.. 片段 bool IsSafeRelativePath(const std::wstring& rel) { if (rel.empty()) return false; if (rel.front() == L'/' || rel.front() == L'\\') return false; if (rel.size() >= 2 && rel[1] == L':') return false; size_t start = 0; for (;;) { size_t pos = rel.find_first_of(L"/\\", start); std::wstring seg = (pos == std::wstring::npos) ? rel.substr(start) : rel.substr(start, pos - start); if (seg == L"..") return false; if (pos == std::wstring::npos) break; start = pos + 1; if (start >= rel.size()) break; } return true; } // 解压回调上下文:把数据写入目标文件 struct WriteContext { HANDLE file = INVALID_HANDLE_VALUE; bool ok = true; }; size_t WriteCallback(void* opaque, mz_uint64 /*file_ofs*/, const void* buf, size_t n) { WriteContext* ctx = static_cast(opaque); if (!ctx->ok) return 0; if (n == 0) return n; const char* data = static_cast(buf); size_t done = 0; while (done < n) { DWORD step = 0; DWORD want = static_cast(n - done); if (!WriteFile(ctx->file, data + done, want, &step, nullptr) || step == 0) { ctx->ok = false; return done; } done += step; } return done; } class FileHandle { public: FileHandle() = default; ~FileHandle() { Close(); } bool Open(const std::wstring& path) { path_ = path; handle_ = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); return handle_ != INVALID_HANDLE_VALUE; } void Close() { if (handle_ != INVALID_HANDLE_VALUE) { FlushFileBuffers(handle_); CloseHandle(handle_); handle_ = INVALID_HANDLE_VALUE; } } bool valid() const { return handle_ != INVALID_HANDLE_VALUE; } HANDLE get() const { return handle_; } const std::wstring& path() const { return path_; } private: HANDLE handle_ = INVALID_HANDLE_VALUE; std::wstring path_; }; } Unzip::Unzip() : archive_(new Archive()) { memset(&archive_->zip, 0, sizeof(archive_->zip)); } Unzip::~Unzip() { Close(); delete archive_; archive_ = nullptr; } bool Unzip::Open(const std::wstring& zipPath, std::wstring& err) { Close(); if (!Utils::FileExists(zipPath)) { err = L"压缩包不存在:" + zipPath; return false; } std::string utf8 = Utils::WideToUtf8(zipPath); // miniz 内部用 CP_UTF8 转换后 fopen,传入 UTF-8 路径即可支持中文 if (!mz_zip_reader_init_file(&archive_->zip, utf8.c_str(), 0)) { err = L"无法打开压缩包(文件损坏或不是 zip)"; memset(&archive_->zip, 0, sizeof(archive_->zip)); return false; } opened_ = true; return true; } void Unzip::Close() { if (opened_) { mz_zip_reader_end(&archive_->zip); opened_ = false; } memset(&archive_->zip, 0, sizeof(archive_->zip)); } unsigned int Unzip::EntryCount() const { if (!opened_) return 0; return mz_zip_reader_get_num_files(&archive_->zip); } bool Unzip::EntryAt(unsigned int index, Entry& out) const { if (!opened_) return false; mz_zip_archive_file_stat stat; if (!mz_zip_reader_file_stat(&archive_->zip, index, &stat)) return false; out.name = Utils::NormalizeSlashes(Utils::DecodeEntryName(std::string(stat.m_filename))); out.size = static_cast(stat.m_uncomp_size); out.directory = stat.m_is_directory != 0; return true; } bool Unzip::DetectCommonRoot(std::wstring& root) const { root.clear(); unsigned int count = EntryCount(); if (count == 0) return false; std::wstring candidate; for (unsigned int i = 0; i < count; ++i) { Entry entry; if (!EntryAt(i, entry)) return false; if (entry.name.empty()) return false; size_t pos = entry.name.find_first_of(L"/\\"); if (pos == std::wstring::npos || pos == 0) return false; std::wstring seg = entry.name.substr(0, pos); std::wstring rest = entry.name.substr(pos + 1); if (rest.empty()) return false; // 存在仅根目录自身的条目,说明不是纯包装目录 if (candidate.empty()) candidate = seg; else if (candidate != seg) return false; } if (candidate.empty()) return false; root = candidate; return true; } bool Unzip::ExtractAll(const std::wstring& targetDir, bool stripRoot, ProgressFunc progress, std::vector& writtenFiles, std::wstring& err) { writtenFiles.clear(); if (!opened_) { err = L"压缩包未打开"; return false; } std::wstring root; bool hasRoot = stripRoot && DetectCommonRoot(root); if (hasRoot && !IsSafeRelativePath(root)) hasRoot = false; unsigned int count = EntryCount(); unsigned long long totalBytes = 0; std::vector entries; std::vector indices; // 条目在压缩包中的原始下标 entries.reserve(count); indices.reserve(count); for (unsigned int i = 0; i < count; ++i) { Entry entry; if (!EntryAt(i, entry)) { err = L"读取压缩包条目失败"; return false; } if (hasRoot) { if (entry.name.size() > root.size()) entry.name = entry.name.substr(root.size() + 1); else entry.name.clear(); } if (entry.name.empty()) continue; if (!IsSafeRelativePath(entry.name)) { err = L"压缩包包含非法路径,已中止:" + entry.name; return false; } totalBytes += entry.size; entries.push_back(entry); indices.push_back(i); } if (!Utils::CreateDirRecursive(targetDir)) { err = L"无法创建目录:" + targetDir; return false; } unsigned long long doneBytes = 0; for (size_t i = 0; i < entries.size(); ++i) { const Entry& entry = entries[i]; std::wstring dest = Utils::JoinPath(targetDir, entry.name); if (entry.directory) { if (!Utils::CreateDirRecursive(dest)) { err = L"无法创建目录:" + dest; return false; } continue; } std::wstring parent = Utils::GetParentDir(dest); if (!parent.empty() && !Utils::CreateDirRecursive(parent)) { err = L"无法创建目录:" + parent; return false; } Utils::DeleteFileForce(dest); FileHandle file; if (!file.Open(dest)) { err = L"无法写入文件:" + dest; return false; } WriteContext ctx; ctx.file = file.get(); if (!mz_zip_reader_extract_to_callback(&archive_->zip, static_cast(indices[i]), &WriteCallback, &ctx, 0)) { file.Close(); DeleteFileW(dest.c_str()); err = L"解压失败:" + entry.name; return false; } if (!ctx.ok) { file.Close(); DeleteFileW(dest.c_str()); err = L"写入失败(磁盘空间不足?):" + dest; return false; } file.Close(); writtenFiles.push_back(dest); doneBytes += entry.size; if (progress && !progress(doneBytes, totalBytes, entry.name)) { err = L"已取消"; return false; } } return true; } }