SPB Git

Repository Public

ZipArchive.swift 14.8 KB 252 lines swift

1// SP Lecture Studio — LectureStorage2// File: Packages/LectureStorage/Sources/ZipArchive.swift3// Description: Minimal streaming ZIP writer (stored, ZIP64) and reader (stored + deflate, ZIP64) used for portable project archives.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import zlib910public enum ZipError: Error, Equatable {11    case notAZip, unsupported(String), corrupt(String), unsafePath(String), cancelled12}1314public enum ZipArchive {15    private static let chunk = 1 << 201617    // MARK: Writer1819    /// Archives the content of `directory` under the top-level folder `rootName`. Files are stored uncompressed20    /// (lecture media is already compressed or PCM) and copied in constant memory.21    public static func create(at destination: URL, fromDirectory directory: URL, rootName: String,22                              exclude: (String) -> Bool = { _ in false },23                              progress: ((Double) -> Bool)? = nil) throws {24        let fm = FileManager.default25        var entries: [(relative: String, url: URL, isDir: Bool, size: UInt64)] = [(rootName + "/", directory, true, 0)]26        let base = directory.standardizedFileURL.path27        if let e = fm.enumerator(at: directory, includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey]) {28            for case let u as URL in e {29                var rel = String(u.standardizedFileURL.path.dropFirst(base.count))30                if rel.hasPrefix("/") { rel.removeFirst() }31                if exclude(rel) { if (try? u.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true { e.skipDescendants() }; continue }32                let v = try u.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey])33                let isDir = v.isDirectory ?? false34                entries.append((rootName + "/" + rel + (isDir ? "/" : ""), u, isDir, UInt64(v.fileSize ?? 0)))35            }36        }37        entries.sort { $0.relative < $1.relative }38        let total = max(1, entries.reduce(UInt64(0)) { $0 + $1.size })39        fm.createFile(atPath: destination.path, contents: nil)40        let out = try FileHandle(forWritingTo: destination)41        defer { try? out.close() }4243        struct Central { var name: Data; var crc: UInt32; var size: UInt64; var offset: UInt64; var isDir: Bool }44        var central: [Central] = []45        var offset: UInt64 = 046        var done: UInt64 = 047        let (dosTime, dosDate) = dosDateTime(Date())4849        for entry in entries {50            let name = Data(entry.relative.precomposedStringWithCanonicalMapping.utf8)51            var crc: UInt32 = 052            if !entry.isDir {53                let h = try FileHandle(forReadingFrom: entry.url); defer { try? h.close() }54                var c = crc32(0, nil, 0)55                while let d = try h.read(upToCount: chunk), !d.isEmpty { c = d.withUnsafeBytes { crc32(c, $0.bindMemory(to: Bytef.self).baseAddress, uInt(d.count)) } }56                crc = UInt32(truncatingIfNeeded: c)57            }58            let big = entry.size >= 0xFFFF_FFFF59            var header = Data()60            header.le(UInt32(0x04034b50)); header.le(UInt16(big ? 45 : 20)); header.le(UInt16(0x0800)); header.le(UInt16(0))61            header.le(dosTime); header.le(dosDate); header.le(crc)62            header.le(big ? UInt32(0xFFFF_FFFF) : UInt32(entry.size)); header.le(big ? UInt32(0xFFFF_FFFF) : UInt32(entry.size))63            header.le(UInt16(name.count)); header.le(UInt16(big ? 20 : 0)); header.append(name)64            if big { header.le(UInt16(1)); header.le(UInt16(16)); header.le(entry.size); header.le(entry.size) }65            try out.write(contentsOf: header)66            central.append(Central(name: name, crc: crc, size: entry.size, offset: offset, isDir: entry.isDir))67            offset += UInt64(header.count)68            if !entry.isDir {69                let h = try FileHandle(forReadingFrom: entry.url); defer { try? h.close() }70                while let d = try h.read(upToCount: chunk), !d.isEmpty {71                    try out.write(contentsOf: d); offset += UInt64(d.count); done += UInt64(d.count)72                    if let progress, !progress(Double(done) / Double(total)) { try? out.close(); try? fm.removeItem(at: destination); throw ZipError.cancelled }73                }74            }75        }7677        let cdStart = offset78        for c in central {79            var extra = Data()80            let bigSize = c.size >= 0xFFFF_FFFF, bigOffset = c.offset >= 0xFFFF_FFFF81            if bigSize { extra.le(c.size); extra.le(c.size) }82            if bigOffset { extra.le(c.offset) }83            var h = Data()84            h.le(UInt32(0x02014b50)); h.le(UInt16(45 | (3 << 8))); h.le(UInt16(bigSize || bigOffset ? 45 : 20)); h.le(UInt16(0x0800)); h.le(UInt16(0))85            h.le(dosTime); h.le(dosDate); h.le(c.crc)86            h.le(bigSize ? UInt32(0xFFFF_FFFF) : UInt32(c.size)); h.le(bigSize ? UInt32(0xFFFF_FFFF) : UInt32(c.size))87            h.le(UInt16(c.name.count)); h.le(UInt16(extra.isEmpty ? 0 : extra.count + 4)); h.le(UInt16(0)); h.le(UInt16(0)); h.le(UInt16(0))88            h.le(UInt32((c.isDir ? 0o040755 : 0o100644) << 16 | (c.isDir ? 0x10 : 0)))89            h.le(bigOffset ? UInt32(0xFFFF_FFFF) : UInt32(c.offset)); h.append(c.name)90            if !extra.isEmpty { h.le(UInt16(1)); h.le(UInt16(extra.count)); h.append(extra) }91            try out.write(contentsOf: h); offset += UInt64(h.count)92        }93        let cdSize = offset - cdStart94        var tail = Data()95        if central.count >= 0xFFFF || cdStart >= 0xFFFF_FFFF || cdSize >= 0xFFFF_FFFF {96            tail.le(UInt32(0x06064b50)); tail.le(UInt64(44)); tail.le(UInt16(45)); tail.le(UInt16(45)); tail.le(UInt32(0)); tail.le(UInt32(0))97            tail.le(UInt64(central.count)); tail.le(UInt64(central.count)); tail.le(cdSize); tail.le(cdStart)98            tail.le(UInt32(0x07064b50)); tail.le(UInt32(0)); tail.le(offset); tail.le(UInt32(1))99        }100        tail.le(UInt32(0x06054b50)); tail.le(UInt16(0)); tail.le(UInt16(0))101        tail.le(UInt16(min(central.count, 0xFFFF))); tail.le(UInt16(min(central.count, 0xFFFF)))102        tail.le(UInt32(min(cdSize, 0xFFFF_FFFF))); tail.le(UInt32(min(cdStart, 0xFFFF_FFFF))); tail.le(UInt16(0))103        try out.write(contentsOf: tail)104        try out.synchronize()105    }106107    // MARK: Reader108109    public struct Entry: Sendable, Hashable {110        public var path: String111        public var isDirectory: Bool112        public var method: UInt16113        public var crc: UInt32114        public var compressedSize: UInt64115        public var size: UInt64116        var localOffset: UInt64117    }118119    public static func entries(of archive: URL) throws -> [Entry] {120        let h = try FileHandle(forReadingFrom: archive); defer { try? h.close() }121        let fileSize = try h.seekToEnd()122        guard fileSize >= 22 else { throw ZipError.notAZip }123        let tailLen = min(fileSize, 65_557 + 20)124        try h.seek(toOffset: fileSize - tailLen)125        let tail = try h.read(upToCount: Int(tailLen)) ?? Data()126        guard let eocd = lastIndex(of: [0x50, 0x4b, 0x05, 0x06], in: tail) else { throw ZipError.notAZip }127        var count = UInt64(tail.u16(eocd + 10)), cdSize = UInt64(tail.u32(eocd + 12)), cdOffset = UInt64(tail.u32(eocd + 16))128        if eocd >= 20, tail.u32(eocd - 20) == 0x07064b50 {129            let z64 = tail.u64(eocd - 20 + 8)130            try h.seek(toOffset: z64)131            let rec = try h.read(upToCount: 56) ?? Data()132            guard rec.count == 56, rec.u32(0) == 0x06064b50 else { throw ZipError.corrupt("zip64 end record") }133            count = rec.u64(32); cdSize = rec.u64(40); cdOffset = rec.u64(48)134        }135        guard cdOffset + cdSize <= fileSize else { throw ZipError.corrupt("central directory out of bounds") }136        try h.seek(toOffset: cdOffset)137        let cd = try h.read(upToCount: Int(cdSize)) ?? Data()138        var out: [Entry] = []; var p = 0139        for _ in 0..<count {140            guard p + 46 <= cd.count, cd.u32(p) == 0x02014b50 else { throw ZipError.corrupt("central header") }141            let flags = cd.u16(p + 8), method = cd.u16(p + 10)142            var comp = UInt64(cd.u32(p + 20)), size = UInt64(cd.u32(p + 24)), local = UInt64(cd.u32(p + 42))143            let n = Int(cd.u16(p + 28)), m = Int(cd.u16(p + 30)), k = Int(cd.u16(p + 32))144            guard p + 46 + n + m + k <= cd.count else { throw ZipError.corrupt("central entry") }145            if flags & 1 != 0 { throw ZipError.unsupported("encrypted zip") }146            let name = String(decoding: cd.subdata(in: (cd.startIndex + p + 46)..<(cd.startIndex + p + 46 + n)), as: UTF8.self)147            var e = p + 46 + n148            let extraEnd = e + m149            while e + 4 <= extraEnd {150                let id = cd.u16(e), len = Int(cd.u16(e + 2)); var q = e + 4151                if id == 1 {152                    if size == 0xFFFF_FFFF, q + 8 <= extraEnd { size = cd.u64(q); q += 8 }153                    if comp == 0xFFFF_FFFF, q + 8 <= extraEnd { comp = cd.u64(q); q += 8 }154                    if local == 0xFFFF_FFFF, q + 8 <= extraEnd { local = cd.u64(q) }155                }156                e += 4 + len157            }158            out.append(Entry(path: name, isDirectory: name.hasSuffix("/"), method: method, crc: cd.u32(p + 16), compressedSize: comp, size: size, localOffset: local))159            p += 46 + n + m + k160        }161        return out162    }163164    /// Extracts the archive into `directory`. Paths escaping the destination are refused; CRCs are verified.165    public static func extract(_ archive: URL, to directory: URL, progress: ((Double) -> Bool)? = nil) throws {166        let fm = FileManager.default167        let list = try entries(of: archive)168        let total = max(1, list.reduce(UInt64(0)) { $0 + $1.size })169        var done: UInt64 = 0170        let h = try FileHandle(forReadingFrom: archive); defer { try? h.close() }171        try fm.createDirectory(at: directory, withIntermediateDirectories: true)172        let root = directory.standardizedFileURL.path173        for entry in list {174            let parts = entry.path.split(separator: "/", omittingEmptySubsequences: true)175            if entry.path.hasPrefix("/") || parts.contains("..") || entry.path.contains("\\") { throw ZipError.unsafePath(entry.path) }176            if parts.first == "__MACOSX" || parts.last == ".DS_Store" { continue }177            let target = directory.appendingPathComponent(entry.path).standardizedFileURL178            guard target.path.hasPrefix(root) else { throw ZipError.unsafePath(entry.path) }179            if entry.isDirectory { try fm.createDirectory(at: target, withIntermediateDirectories: true); continue }180            try fm.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)181            try h.seek(toOffset: entry.localOffset)182            let lh = try h.read(upToCount: 30) ?? Data()183            guard lh.count == 30, lh.u32(0) == 0x04034b50 else { throw ZipError.corrupt("local header of \(entry.path)") }184            try h.seek(toOffset: entry.localOffset + 30 + UInt64(lh.u16(26)) + UInt64(lh.u16(28)))185            fm.createFile(atPath: target.path, contents: nil)186            let out = try FileHandle(forWritingTo: target); defer { try? out.close() }187            var crc = crc32(0, nil, 0)188            var remaining = entry.compressedSize189            func emit(_ d: Data) throws {190                crc = d.withUnsafeBytes { crc32(crc, $0.bindMemory(to: Bytef.self).baseAddress, uInt(d.count)) }191                try out.write(contentsOf: d); done += UInt64(d.count)192                if let progress, !progress(Double(done) / Double(total)) { throw ZipError.cancelled }193            }194            switch entry.method {195            case 0:196                while remaining > 0 {197                    guard let d = try h.read(upToCount: Int(min(UInt64(chunk), remaining))), !d.isEmpty else { throw ZipError.corrupt("truncated \(entry.path)") }198                    remaining -= UInt64(d.count); try emit(d)199                }200            case 8:201                var stream = z_stream()202                guard inflateInit2_(&stream, -MAX_WBITS, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else { throw ZipError.corrupt("inflate init") }203                defer { inflateEnd(&stream) }204                var outBuf = [UInt8](repeating: 0, count: chunk)205                var finished = false206                while !finished {207                    guard remaining > 0, var input = try h.read(upToCount: Int(min(UInt64(chunk), remaining))), !input.isEmpty else { throw ZipError.corrupt("truncated \(entry.path)") }208                    remaining -= UInt64(input.count)209                    let inputCount = input.count210                    try input.withUnsafeMutableBytes { (raw: UnsafeMutableRawBufferPointer) in211                        stream.next_in = raw.bindMemory(to: Bytef.self).baseAddress; stream.avail_in = uInt(inputCount)212                        repeat {213                            let status: Int32 = outBuf.withUnsafeMutableBufferPointer { ob in214                                stream.next_out = ob.baseAddress; stream.avail_out = uInt(chunk)215                                return inflate(&stream, Z_NO_FLUSH)216                            }217                            guard status == Z_OK || status == Z_STREAM_END else { throw ZipError.corrupt("inflate \(entry.path)") }218                            let produced = chunk - Int(stream.avail_out)219                            if produced > 0 { try emit(Data(outBuf[0..<produced])) }220                            if status == Z_STREAM_END { finished = true; break }221                        } while stream.avail_in > 0 || stream.avail_out == 0222                    }223                }224            default: throw ZipError.unsupported("compression method \(entry.method)")225            }226            guard UInt32(truncatingIfNeeded: crc) == entry.crc else { throw ZipError.corrupt("checksum of \(entry.path)") }227        }228    }229230    private static func lastIndex(of pattern: [UInt8], in data: Data) -> Int? {231        guard data.count >= pattern.count else { return nil }232        let bytes = [UInt8](data)233        var i = bytes.count - 22234        while i >= 0 { if bytes[i] == pattern[0], Array(bytes[i..<(i + 4)]) == pattern { return i }; i -= 1 }235        return nil236    }237238    private static func dosDateTime(_ date: Date) -> (UInt16, UInt16) {239        let c = Calendar(identifier: .gregorian).dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)240        let time = UInt16((c.hour ?? 0) << 11 | (c.minute ?? 0) << 5 | (c.second ?? 0) / 2)241        let day = UInt16((max(1980, c.year ?? 1980) - 1980) << 9 | (c.month ?? 1) << 5 | (c.day ?? 1))242        return (time, day)243    }244}245246extension Data {247    mutating func le<T: FixedWidthInteger>(_ v: T) { var x = v.littleEndian; Swift.withUnsafeBytes(of: &x) { append(contentsOf: $0) } }248    func u16(_ o: Int) -> UInt16 { UInt16(self[startIndex + o]) | UInt16(self[startIndex + o + 1]) << 8 }249    func u32(_ o: Int) -> UInt32 { UInt32(u16(o)) | UInt32(u16(o + 2)) << 16 }250    func u64(_ o: Int) -> UInt64 { UInt64(u32(o)) | UInt64(u32(o + 4)) << 32 }251}252
Files main
Menu

Theme