Compression.swift (9007B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import zlib 4 5 /// Decompression for imported files: gzip, and zip archives (stored or "deflate" entries). 6 public enum Inflate { 7 public enum Format: Int32 { 8 case gzip = 31 // 16 + 15: gzip header 9 case raw = -15 // raw "deflate" stream, as in a zip 10 case auto = 47 // 32 + 15: gzip or zlib, detected from the header 11 } 12 13 public static func decompress(_ input: [UInt8], format: Format, limit: Int = 256 << 20) throws -> [UInt8] { 14 guard !input.isEmpty else { return [] } 15 var stream = z_stream() 16 guard inflateInit2_(&stream, format.rawValue, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else { 17 throw GitError.malformed("zlib: initialization") 18 } 19 defer { inflateEnd(&stream) } 20 var output = [UInt8]() 21 var chunk = [UInt8](repeating: 0, count: 64 * 1024) 22 var status: Int32 = Z_OK 23 try input.withUnsafeBufferPointer { inPtr in 24 stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress!) 25 stream.avail_in = UInt32(input.count) 26 while status != Z_STREAM_END { 27 let produced: Int = chunk.withUnsafeMutableBufferPointer { outPtr in 28 stream.next_out = outPtr.baseAddress! 29 stream.avail_out = UInt32(outPtr.count) 30 status = inflate(&stream, Z_NO_FLUSH) 31 return outPtr.count - Int(stream.avail_out) 32 } 33 guard status == Z_OK || status == Z_STREAM_END else { throw GitError.malformed("invalid compressed data (\(status))") } 34 output.append(contentsOf: chunk[0..<produced]) 35 guard output.count <= limit else { throw GitError.malformed("file too large") } 36 if produced == 0, stream.avail_in == 0, status != Z_STREAM_END { throw GitError.malformed("truncated compressed data") } 37 } 38 } 39 return output 40 } 41 42 /// Compresses to the gzip format (used by the tests). 43 public static func gzip(_ input: [UInt8]) -> [UInt8] { 44 var stream = z_stream() 45 guard deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, 46 Int32(MemoryLayout<z_stream>.size)) == Z_OK else { return [] } 47 defer { deflateEnd(&stream) } 48 var output = [UInt8](repeating: 0, count: Int(deflateBound(&stream, UInt(input.count))) + 64) 49 var dummy: UInt8 = 0 50 let written: Int = input.withUnsafeBufferPointer { inPtr in 51 withUnsafeMutablePointer(to: &dummy) { dummyPtr in 52 output.withUnsafeMutableBufferPointer { outPtr in 53 stream.next_in = inPtr.baseAddress.map { UnsafeMutablePointer(mutating: $0) } ?? dummyPtr 54 stream.avail_in = UInt32(input.count) 55 stream.next_out = outPtr.baseAddress! 56 stream.avail_out = UInt32(outPtr.count) 57 _ = deflate(&stream, Z_FINISH) 58 return outPtr.count - Int(stream.avail_out) 59 } 60 } 61 } 62 return Array(output[0..<written]) 63 } 64 } 65 66 public extension Inflate { 67 /// Raw "deflate" stream, as stored in a zip entry. 68 static func deflateRaw(_ input: [UInt8]) -> [UInt8] { 69 guard !input.isEmpty else { return [] } 70 var stream = z_stream() 71 guard deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, 72 Int32(MemoryLayout<z_stream>.size)) == Z_OK else { return [] } 73 defer { deflateEnd(&stream) } 74 var output = [UInt8](repeating: 0, count: Int(deflateBound(&stream, UInt(input.count))) + 64) 75 let written: Int = input.withUnsafeBufferPointer { inPtr in 76 output.withUnsafeMutableBufferPointer { outPtr in 77 stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress!) 78 stream.avail_in = UInt32(input.count) 79 stream.next_out = outPtr.baseAddress! 80 stream.avail_out = UInt32(outPtr.count) 81 _ = deflate(&stream, Z_FINISH) 82 return outPtr.count - Int(stream.avail_out) 83 } 84 } 85 return Array(output[0..<written]) 86 } 87 } 88 89 public extension ZipArchive { 90 /// Writes a zip archive (deflate, no zip64): enough for a logbook, readable by any unzip tool. 91 static func archive(_ files: [(name: String, data: [UInt8])]) -> [UInt8] { 92 func le16(_ value: Int) -> [UInt8] { [UInt8(value & 0xFF), UInt8(value >> 8 & 0xFF)] } 93 func le32(_ value: Int) -> [UInt8] { le16(value & 0xFFFF) + le16(value >> 16 & 0xFFFF) } 94 var out = [UInt8]() 95 var directory = [UInt8]() 96 for file in files { 97 let name = Array(file.name.utf8) 98 let packed = Inflate.deflateRaw(file.data) 99 let stored = file.data.isEmpty || packed.isEmpty || packed.count >= file.data.count 100 let body = stored ? file.data : packed 101 let checksum = file.data.withUnsafeBufferPointer { Int(crc32(0, $0.baseAddress, UInt32($0.count))) } 102 // Version 2.0, UTF-8 names (bit 11), fixed date (1980-01-01): the archive only depends on its contents. 103 let common = le16(20) + le16(0x0800) + le16(stored ? 0 : 8) + le16(0) + le16(0x21) 104 + le32(checksum) + le32(body.count) + le32(file.data.count) + le16(name.count) + le16(0) 105 let offset = out.count 106 out += [0x50, 0x4b, 0x03, 0x04] + common + name + body 107 directory += [0x50, 0x4b, 0x01, 0x02] + le16(20) + common + le16(0) + le16(0) + le16(0) + le32(0) + le32(offset) + name 108 } 109 let start = out.count 110 out += directory 111 out += [0x50, 0x4b, 0x05, 0x06] + le16(0) + le16(0) + le16(files.count) + le16(files.count) 112 + le32(directory.count) + le32(start) + le16(0) 113 return out 114 } 115 } 116 117 /// Minimal reader for a zip archive (no zip64, no encryption). 118 public struct ZipArchive { 119 public struct Entry { 120 public let name: String 121 let method: Int 122 let compressedSize: Int 123 let localOffset: Int 124 } 125 126 public let entries: [Entry] 127 private let data: [UInt8] 128 129 public static func isZip(_ data: [UInt8]) -> Bool { 130 data.count > 4 && data[0] == 0x50 && data[1] == 0x4b && data[2] == 0x03 && data[3] == 0x04 131 } 132 133 public init(_ data: [UInt8]) throws { 134 self.data = data 135 func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 } 136 func u32(_ i: Int) -> Int { u16(i) | u16(i + 2) << 16 } 137 // End of central directory: searched from the end (a comment may follow it). 138 var end = data.count - 22 139 var found = -1 140 while end >= 0, end >= data.count - 22 - 65_535 { 141 if data[end] == 0x50, data[end + 1] == 0x4b, data[end + 2] == 0x05, data[end + 3] == 0x06 { found = end; break } 142 end -= 1 143 } 144 guard found >= 0 else { throw GitError.malformed("unreadable zip archive") } 145 let count = u16(found + 10) 146 var pos = u32(found + 16) 147 var list = [Entry]() 148 for _ in 0..<count { 149 guard pos + 46 <= data.count, u32(pos) == 0x0201_4b50 else { throw GitError.malformed("zip archive: central directory") } 150 let nameLength = u16(pos + 28), extraLength = u16(pos + 30), commentLength = u16(pos + 32) 151 guard pos + 46 + nameLength <= data.count else { throw GitError.malformed("zip archive: name") } 152 let name = String(decoding: data[(pos + 46)..<(pos + 46 + nameLength)], as: UTF8.self) 153 list.append(Entry(name: name, method: u16(pos + 10), compressedSize: u32(pos + 20), localOffset: u32(pos + 42))) 154 pos += 46 + nameLength + extraLength + commentLength 155 } 156 entries = list 157 } 158 159 public func contents(of entry: Entry) throws -> [UInt8] { 160 func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 } 161 let pos = entry.localOffset 162 guard pos + 30 <= data.count, data[pos] == 0x50, data[pos + 1] == 0x4b, data[pos + 2] == 0x03, data[pos + 3] == 0x04 else { 163 throw GitError.malformed("zip archive: entry") 164 } 165 let start = pos + 30 + u16(pos + 26) + u16(pos + 28) 166 guard start + entry.compressedSize <= data.count else { throw GitError.malformed("truncated zip archive") } 167 let raw = Array(data[start..<(start + entry.compressedSize)]) 168 switch entry.method { 169 case 0: return raw 170 case 8: return try Inflate.decompress(raw, format: .raw) 171 default: throw GitError.malformed("zip archive: unsupported compression") 172 } 173 } 174 175 public func contents(named name: String) throws -> [UInt8]? { 176 guard let entry = entries.first(where: { $0.name == name || $0.name.hasSuffix("/" + name) }) else { return nil } 177 return try contents(of: entry) 178 } 179 }