Pack.swift (10821B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import zlib 4 5 enum Zlib { 6 /// Inflates a zlib stream that starts at `offset`; returns the data and the number of bytes consumed. 7 static func inflate(_ input: [UInt8], from offset: Int, expectedSize: Int) throws -> (data: [UInt8], consumed: Int) { 8 var stream = z_stream() 9 guard inflateInit_(&stream, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else { 10 throw GitError.malformed("zlib: initialization") 11 } 12 defer { inflateEnd(&stream) } 13 var output = [UInt8](repeating: 0, count: max(expectedSize, 1)) 14 let available = input.count - offset 15 guard available > 0 else { throw GitError.malformed("zlib: empty stream") } 16 var status: Int32 = Z_OK 17 var produced = 0 18 try input.withUnsafeBufferPointer { inPtr in 19 try output.withUnsafeMutableBufferPointer { outPtr in 20 stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress! + offset) 21 stream.avail_in = UInt32(min(available, Int(UInt32.max))) 22 stream.next_out = outPtr.baseAddress! 23 stream.avail_out = UInt32(outPtr.count) 24 status = zlib.inflate(&stream, Z_FINISH) 25 produced = outPtr.count - Int(stream.avail_out) 26 if status != Z_STREAM_END { 27 throw GitError.malformed("zlib: invalid stream (\(status))") 28 } 29 } 30 } 31 guard produced == expectedSize else { throw GitError.malformed("zlib: unexpected size") } 32 let consumed = min(available, Int(UInt32.max)) - Int(stream.avail_in) 33 if output.count != expectedSize { output.removeLast(output.count - expectedSize) } 34 return (output, consumed) 35 } 36 37 static func deflate(_ input: [UInt8]) -> [UInt8] { 38 var bound = compressBound(UInt(input.count)) 39 var output = [UInt8](repeating: 0, count: Int(bound)) 40 let status = input.withUnsafeBufferPointer { inPtr -> Int32 in 41 // compress2 requires a non-null pointer even for an empty input. 42 var dummy: UInt8 = 0 43 return withUnsafePointer(to: &dummy) { dummyPtr in 44 compress2(&output, &bound, inPtr.baseAddress ?? dummyPtr, UInt(input.count), Z_DEFAULT_COMPRESSION) 45 } 46 } 47 precondition(status == Z_OK, "zlib: compression failed") 48 output.removeLast(output.count - Int(bound)) 49 return output 50 } 51 } 52 53 /// Reading and writing packfiles (version 2). 54 public enum Pack { 55 private struct Entry { 56 var type: UInt8 // 1…4 object, 6 ofs-delta, 7 ref-delta 57 var data: [UInt8] // content, or delta instructions 58 var baseOffset: Int = 0 59 var baseID: ObjectID? 60 } 61 62 /// Decodes a pack; `external` provides the bases missing from the pack ("thin" packs). 63 public static func parse(_ pack: [UInt8], external: (ObjectID) -> GitObject? = { _ in nil }) throws -> [GitObject] { 64 guard pack.count >= 32, pack[0] == 0x50, pack[1] == 0x41, pack[2] == 0x43, pack[3] == 0x4b else { 65 throw GitError.malformed("pack: header") 66 } 67 let version = be32(pack, 4) 68 guard version == 2 || version == 3 else { throw GitError.malformed("pack: version \(version)") } 69 let count = Int(be32(pack, 8)) 70 guard sha1(Array(pack[0..<(pack.count - 20)])) == Array(pack[(pack.count - 20)...]) else { 71 throw GitError.malformed("pack: checksum") 72 } 73 74 var entries = [Int: Entry]() 75 var order = [Int]() 76 order.reserveCapacity(count) 77 var pos = 12 78 let end = pack.count - 20 79 for _ in 0..<count { 80 guard pos < end else { throw GitError.malformed("truncated pack") } 81 let start = pos 82 var byte = pack[pos]; pos += 1 83 let type = (byte >> 4) & 7 84 var size = Int(byte & 15) 85 var shift = 4 86 while byte & 0x80 != 0 { 87 guard pos < end else { throw GitError.malformed("truncated pack") } 88 byte = pack[pos]; pos += 1 89 size |= Int(byte & 0x7f) << shift 90 shift += 7 91 } 92 var entry = Entry(type: type, data: []) 93 switch type { 94 case 1, 2, 3, 4: 95 break 96 case 6: 97 guard pos < end else { throw GitError.malformed("truncated pack") } 98 byte = pack[pos]; pos += 1 99 var offset = Int(byte & 0x7f) 100 while byte & 0x80 != 0 { 101 guard pos < end else { throw GitError.malformed("truncated pack") } 102 byte = pack[pos]; pos += 1 103 offset = ((offset + 1) << 7) | Int(byte & 0x7f) 104 } 105 entry.baseOffset = start - offset 106 case 7: 107 guard pos + 20 <= end else { throw GitError.malformed("truncated pack") } 108 entry.baseID = ObjectID(bytes: Array(pack[pos..<(pos + 20)])) 109 pos += 20 110 default: 111 throw GitError.malformed("pack: type \(type)") 112 } 113 let (data, consumed) = try Zlib.inflate(pack, from: pos, expectedSize: size) 114 entry.data = data 115 pos += consumed 116 entries[start] = entry 117 order.append(start) 118 } 119 120 var resolved = [Int: GitObject]() 121 var byID = [ObjectID: GitObject]() 122 123 // Whole objects first: they are the bases of the deltas that refer to them by identifier. 124 for offset in order { 125 let e = entries[offset]! 126 if let type = ObjectType(rawValue: e.type) { 127 let object = GitObject(type: type, data: e.data) 128 resolved[offset] = object 129 byID[object.id] = object 130 } 131 } 132 133 func resolve(_ offset: Int, depth: Int) throws -> GitObject { 134 if let done = resolved[offset] { return done } 135 guard depth < 4096, let e = entries[offset] else { throw GitError.malformed("pack: delta chain") } 136 let base: GitObject 137 if e.type == 6 { 138 base = try resolve(e.baseOffset, depth: depth + 1) 139 } else { 140 guard let id = e.baseID else { throw GitError.malformed("pack: delta without a base") } 141 if let found = byID[id] { 142 base = found 143 } else if let found = external(id) { 144 base = found 145 } else { 146 throw GitError.missingObject(id.hex) 147 } 148 } 149 let object = GitObject(type: base.type, data: try applyDelta(base: base.data, delta: e.data)) 150 resolved[offset] = object 151 byID[object.id] = object 152 return object 153 } 154 155 // Ref-deltas may point to a delta that is not resolved yet: several passes. 156 var pending = order.filter { resolved[$0] == nil } 157 while !pending.isEmpty { 158 var next = [Int]() 159 var firstError: Error? 160 for offset in pending { 161 do { 162 _ = try resolve(offset, depth: 0) 163 } catch let error as GitError { 164 if case .missingObject = error { 165 next.append(offset) 166 firstError = firstError ?? error 167 } else { 168 throw error 169 } 170 } 171 } 172 if next.count == pending.count { throw firstError ?? GitError.malformed("pack: deltas") } 173 pending = next 174 } 175 return order.compactMap { resolved[$0] } 176 } 177 178 static func applyDelta(base: [UInt8], delta: [UInt8]) throws -> [UInt8] { 179 var pos = 0 180 func varint() throws -> Int { 181 var value = 0, shift = 0 182 while true { 183 guard pos < delta.count else { throw GitError.malformed("truncated delta") } 184 let b = delta[pos]; pos += 1 185 value |= Int(b & 0x7f) << shift 186 shift += 7 187 if b & 0x80 == 0 { return value } 188 } 189 } 190 let baseSize = try varint() 191 guard baseSize == base.count else { throw GitError.malformed("delta: base size") } 192 let resultSize = try varint() 193 var out = [UInt8]() 194 out.reserveCapacity(resultSize) 195 while pos < delta.count { 196 let op = delta[pos]; pos += 1 197 if op & 0x80 != 0 { 198 var offset = 0, size = 0 199 for i in 0..<4 where op & (1 << UInt8(i)) != 0 { 200 guard pos < delta.count else { throw GitError.malformed("truncated delta") } 201 offset |= Int(delta[pos]) << (8 * i); pos += 1 202 } 203 for i in 0..<3 where op & (0x10 << UInt8(i)) != 0 { 204 guard pos < delta.count else { throw GitError.malformed("truncated delta") } 205 size |= Int(delta[pos]) << (8 * i); pos += 1 206 } 207 if size == 0 { size = 0x10000 } 208 guard offset + size <= base.count else { throw GitError.malformed("delta: copy out of bounds") } 209 out.append(contentsOf: base[offset..<(offset + size)]) 210 } else if op != 0 { 211 let size = Int(op) 212 guard pos + size <= delta.count else { throw GitError.malformed("truncated delta") } 213 out.append(contentsOf: delta[pos..<(pos + size)]) 214 pos += size 215 } else { 216 throw GitError.malformed("delta: zero instruction") 217 } 218 } 219 guard out.count == resultSize else { throw GitError.malformed("delta: result size") } 220 return out 221 } 222 223 /// Writes a pack of whole objects (no deltas). 224 public static func write(_ objects: [GitObject]) -> [UInt8] { 225 var out: [UInt8] = [0x50, 0x41, 0x43, 0x4b, 0, 0, 0, 2] 226 let n = UInt32(objects.count) 227 out.append(contentsOf: [UInt8(n >> 24), UInt8((n >> 16) & 255), UInt8((n >> 8) & 255), UInt8(n & 255)]) 228 for object in objects { 229 var size = object.data.count 230 var byte = (object.type.rawValue << 4) | UInt8(size & 15) 231 size >>= 4 232 while size > 0 { 233 out.append(byte | 0x80) 234 byte = UInt8(size & 0x7f) 235 size >>= 7 236 } 237 out.append(byte) 238 out.append(contentsOf: Zlib.deflate(object.data)) 239 } 240 out.append(contentsOf: sha1(out)) 241 return out 242 } 243 244 private static func be32(_ b: [UInt8], _ i: Int) -> UInt32 { 245 UInt32(b[i]) << 24 | UInt32(b[i + 1]) << 16 | UInt32(b[i + 2]) << 8 | UInt32(b[i + 3]) 246 } 247 }