Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocContainer/ZipArchive.swift3// Description: Minimal, defensive ZIP reader and writer (stored + deflate) used by the DOCX and .orixdoc containers.4// The reader treats every archive as hostile: size, ratio and entry-count limits, no path traversal, no ZIP64, no encryption.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Compression1011public enum ZipError: Error, Equatable, CustomStringConvertible {12 case notAZipArchive13 case corrupted(String)14 case unsupported(String)15 case unsafeEntryName(String)16 case tooManyEntries(Int)17 case entryTooLarge(name: String, size: Int)18 case archiveTooLarge(Int)19 case suspiciousCompressionRatio(name: String)20 case checksumMismatch(name: String)2122 public var description: String {23 switch self {24 case .notAZipArchive: return "The file is not a ZIP archive."25 case .corrupted(let why): return "The archive is damaged (\(why))."26 case .unsupported(let what): return "Unsupported archive feature: \(what)."27 case .unsafeEntryName(let n): return "The archive contains an unsafe entry name: \(n)."28 case .tooManyEntries(let n): return "The archive contains too many entries (\(n))."29 case .entryTooLarge(let n, let s): return "The entry \(n) is too large (\(s) bytes)."30 case .archiveTooLarge(let s): return "The uncompressed content is too large (\(s) bytes)."31 case .suspiciousCompressionRatio(let n): return "The entry \(n) has a compression ratio typical of a decompression bomb."32 case .checksumMismatch(let n): return "The entry \(n) fails its checksum."33 }34 }35}3637/// Safety limits applied while reading an archive.38public struct ZipLimits: Sendable {39 public var maxEntries = 20_00040 public var maxEntrySize = 256 * 1024 * 102441 public var maxTotalSize = 1024 * 1024 * 102442 /// Entries larger than 1 MB whose uncompressed/compressed ratio exceeds this are rejected.43 public var maxRatio = 100044 public init() {}45 public static let standard = ZipLimits()46}4748public struct ZipEntryInfo: Sendable, Equatable {49 public var name: String50 public var compressedSize: Int51 public var uncompressedSize: Int52 public var crc32: UInt3253 var method: UInt1654 var localHeaderOffset: Int55}5657/// A ZIP archive held in memory. Entries are decompressed on demand.58public struct ZipReader: Sendable {59 public let entries: [ZipEntryInfo]60 private let data: Data61 private let index: [String: Int]6263 public init(data: Data, limits: ZipLimits = .standard) throws {64 self.data = data65 let bytes = [UInt8](data.suffix(min(data.count, 65_557)))66 guard data.count >= 22 else { throw ZipError.notAZipArchive }67 // End of central directory record: scan backwards for its signature.68 var eocd = -169 var i = bytes.count - 2270 while i >= 0 {71 if bytes[i] == 0x50, bytes[i + 1] == 0x4B, bytes[i + 2] == 0x05, bytes[i + 3] == 0x06 { eocd = i; break }72 i -= 173 }74 guard eocd >= 0 else { throw ZipError.notAZipArchive }75 let base = data.count - bytes.count76 func u16(_ o: Int) -> Int { Int(bytes[o]) | Int(bytes[o + 1]) << 8 }77 func u32(_ o: Int) -> Int { Int(bytes[o]) | Int(bytes[o + 1]) << 8 | Int(bytes[o + 2]) << 16 | Int(bytes[o + 3]) << 24 }78 let count = u16(eocd + 10)79 let cdSize = u32(eocd + 12)80 let cdOffset = u32(eocd + 16)81 _ = base82 if count == 0xFFFF || cdOffset == 0xFFFF_FFFF { throw ZipError.unsupported("ZIP64") }83 guard count <= limits.maxEntries else { throw ZipError.tooManyEntries(count) }84 guard cdOffset >= 0, cdSize >= 0, cdOffset + cdSize <= data.count else { throw ZipError.corrupted("central directory out of bounds") }8586 let cd = [UInt8](data.subdata(in: (data.startIndex + cdOffset)..<(data.startIndex + cdOffset + cdSize)))87 func c16(_ o: Int) -> Int { Int(cd[o]) | Int(cd[o + 1]) << 8 }88 func c32(_ o: Int) -> Int { Int(cd[o]) | Int(cd[o + 1]) << 8 | Int(cd[o + 2]) << 16 | Int(cd[o + 3]) << 24 }89 var out: [ZipEntryInfo] = []90 var idx: [String: Int] = [:]91 var p = 092 var total = 093 for _ in 0..<count {94 guard p + 46 <= cd.count, c32(p) == 0x0201_4B50 else { throw ZipError.corrupted("bad central directory entry") }95 let flags = c16(p + 8), method = c16(p + 10)96 let crc = UInt32(truncatingIfNeeded: c32(p + 16))97 let csize = c32(p + 20), usize = c32(p + 24)98 let nameLen = c16(p + 28), extraLen = c16(p + 30), commentLen = c16(p + 32)99 let lho = c32(p + 42)100 guard p + 46 + nameLen <= cd.count else { throw ZipError.corrupted("truncated entry name") }101 let nameBytes = Array(cd[(p + 46)..<(p + 46 + nameLen)])102 let name = String(decoding: nameBytes, as: UTF8.self)103 p += 46 + nameLen + extraLen + commentLen104 if flags & 0x1 != 0 { throw ZipError.unsupported("encrypted entries") }105 guard method == 0 || method == 8 else { throw ZipError.unsupported("compression method \(method)") }106 if csize == 0xFFFF_FFFF || usize == 0xFFFF_FFFF { throw ZipError.unsupported("ZIP64") }107 try ZipReader.validate(name: name)108 guard usize <= limits.maxEntrySize else { throw ZipError.entryTooLarge(name: name, size: usize) }109 if usize > 1_048_576, usize / max(1, csize) > limits.maxRatio { throw ZipError.suspiciousCompressionRatio(name: name) }110 total += usize111 guard total <= limits.maxTotalSize else { throw ZipError.archiveTooLarge(total) }112 if name.hasSuffix("/") { continue } // directory entry113 // Two entries with one name let different readers see different content: refuse.114 guard idx[name] == nil else { throw ZipError.corrupted("duplicate entry \(name)") }115 idx[name] = out.count116 out.append(ZipEntryInfo(name: name, compressedSize: csize, uncompressedSize: usize, crc32: crc, method: UInt16(method), localHeaderOffset: lho))117 }118 entries = out119 index = idx120 }121122 static func validate(name: String) throws {123 if name.isEmpty || name.hasPrefix("/") || name.contains("\\") || name.contains("\0") || name.contains(":") { throw ZipError.unsafeEntryName(name) }124 for part in name.split(separator: "/", omittingEmptySubsequences: false) where part == ".." { throw ZipError.unsafeEntryName(name) }125 }126127 public func contains(_ name: String) -> Bool { index[name] != nil }128 public var names: [String] { entries.map(\.name) }129130 /// Decompresses and verifies (CRC-32) one entry. Returns nil when the entry does not exist.131 public func data(for name: String) throws -> Data? {132 guard let i = index[name] else { return nil }133 let e = entries[i]134 let start = data.startIndex + e.localHeaderOffset135 guard e.localHeaderOffset >= 0, e.localHeaderOffset + 30 <= data.count else { throw ZipError.corrupted("local header out of bounds") }136 let h = [UInt8](data.subdata(in: start..<(start + 30)))137 guard h[0] == 0x50, h[1] == 0x4B, h[2] == 0x03, h[3] == 0x04 else { throw ZipError.corrupted("bad local header") }138 let nameLen = Int(h[26]) | Int(h[27]) << 8, extraLen = Int(h[28]) | Int(h[29]) << 8139 let dataStart = e.localHeaderOffset + 30 + nameLen + extraLen140 // The local header must name the same entry as the central directory.141 guard start + 30 + nameLen <= data.endIndex,142 String(decoding: data.subdata(in: (start + 30)..<(start + 30 + nameLen)), as: UTF8.self) == e.name else { throw ZipError.corrupted("local header name mismatch") }143 guard dataStart + e.compressedSize <= data.count else { throw ZipError.corrupted("entry data out of bounds") }144 let raw = data.subdata(in: (data.startIndex + dataStart)..<(data.startIndex + dataStart + e.compressedSize))145 let out: Data146 if e.method == 0 {147 guard e.compressedSize == e.uncompressedSize else { throw ZipError.corrupted("stored entry size mismatch") }148 out = raw149 } else {150 out = try ZipReader.inflate(raw, expected: e.uncompressedSize, name: e.name)151 }152 guard CRC32.checksum(out) == e.crc32 else { throw ZipError.checksumMismatch(name: e.name) }153 return out154 }155156 static func inflate(_ raw: Data, expected: Int, name: String) throws -> Data {157 if expected == 0 { return Data() }158 var out = Data(count: expected + 1) // one spare byte detects entries that inflate beyond their declared size159 let written: Int = out.withUnsafeMutableBytes { dst in160 raw.withUnsafeBytes { src in161 guard let d = dst.bindMemory(to: UInt8.self).baseAddress, let s = src.bindMemory(to: UInt8.self).baseAddress else { return 0 }162 return compression_decode_buffer(d, expected + 1, s, raw.count, nil, COMPRESSION_ZLIB)163 }164 }165 guard written == expected else { throw ZipError.corrupted("entry \(name) does not inflate to its declared size") }166 out.count = expected167 return out168 }169}170171/// Builds a ZIP archive in memory.172public struct ZipWriter {173 private var body = Data()174 private var central = Data()175 private var count = 0176 private var names = Set<String>()177178 public init() {}179180 /// Adds an entry. `compress: false` stores the bytes verbatim (required for the `mimetype` entry and sensible for JPEG/PNG).181 public mutating func add(_ name: String, _ content: Data, compress: Bool = true) throws {182 try ZipReader.validate(name: name)183 guard !names.contains(name) else { throw ZipError.corrupted("duplicate entry \(name)") }184 guard content.count < 0xFFFF_FFFF, body.count < 0xFFFF_FFFF, count < 0xFFFF else { throw ZipError.unsupported("ZIP64") }185 names.insert(name)186 let crc = CRC32.checksum(content)187 var method: UInt16 = 0188 var payload = content189 if compress, content.count > 32, let deflated = ZipWriter.deflate(content), deflated.count < content.count {190 method = 8191 payload = deflated192 }193 let nameBytes = Array(name.utf8)194 let offset = body.count195 func header(central isCentral: Bool) -> Data {196 var h = Data()197 h.appendLE(UInt32(isCentral ? 0x0201_4B50 : 0x0403_4B50))198 if isCentral { h.appendLE(UInt16(20)) } // version made by199 h.appendLE(UInt16(20)) // version needed200 h.appendLE(UInt16(0x0800)) // flags: UTF-8 names201 h.appendLE(method)202 h.appendLE(UInt16(0)) // time 00:00:00203 h.appendLE(UInt16((2026 - 1980) << 9 | 1 << 5 | 1)) // fixed date keeps archives reproducible204 h.appendLE(crc)205 h.appendLE(UInt32(payload.count))206 h.appendLE(UInt32(content.count))207 h.appendLE(UInt16(nameBytes.count))208 h.appendLE(UInt16(0)) // extra length209 if isCentral {210 h.appendLE(UInt16(0)); h.appendLE(UInt16(0)); h.appendLE(UInt16(0)) // comment, disk, internal attrs211 h.appendLE(UInt32(0)) // external attrs212 h.appendLE(UInt32(offset))213 }214 h.append(contentsOf: nameBytes)215 return h216 }217 body.append(header(central: false))218 body.append(payload)219 central.append(header(central: true))220 count += 1221 }222223 public mutating func add(_ name: String, text: String, compress: Bool = true) throws {224 try add(name, Data(text.utf8), compress: compress)225 }226227 public func finalize() -> Data {228 var out = body229 out.append(central)230 out.appendLE(UInt32(0x0605_4B50))231 out.appendLE(UInt16(0)); out.appendLE(UInt16(0))232 out.appendLE(UInt16(count)); out.appendLE(UInt16(count))233 out.appendLE(UInt32(central.count))234 out.appendLE(UInt32(body.count))235 out.appendLE(UInt16(0))236 return out237 }238239 static func deflate(_ content: Data) -> Data? {240 let cap = content.count + content.count / 8 + 64241 var out = Data(count: cap)242 let written: Int = out.withUnsafeMutableBytes { dst in243 content.withUnsafeBytes { src in244 guard let d = dst.bindMemory(to: UInt8.self).baseAddress, let s = src.bindMemory(to: UInt8.self).baseAddress else { return 0 }245 return compression_encode_buffer(d, cap, s, content.count, nil, COMPRESSION_ZLIB)246 }247 }248 guard written > 0 else { return nil }249 out.count = written250 return out251 }252}253254public enum CRC32 {255 private static let table: [UInt32] = (0..<256).map { i -> UInt32 in256 var c = UInt32(i)257 for _ in 0..<8 { c = (c & 1) != 0 ? 0xEDB8_8320 ^ (c >> 1) : c >> 1 }258 return c259 }260 public static func checksum(_ data: Data) -> UInt32 {261 var c: UInt32 = 0xFFFF_FFFF262 data.withUnsafeBytes { buf in263 for b in buf.bindMemory(to: UInt8.self) { c = table[Int((c ^ UInt32(b)) & 0xFF)] ^ (c >> 8) }264 }265 return c ^ 0xFFFF_FFFF266 }267}268269extension Data {270 mutating func appendLE(_ v: UInt16) { append(UInt8(v & 0xFF)); append(UInt8(v >> 8)) }271 mutating func appendLE(_ v: UInt32) { append(UInt8(v & 0xFF)); append(UInt8((v >> 8) & 0xFF)); append(UInt8((v >> 16) & 0xFF)); append(UInt8(v >> 24)) }272}273