subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

Client.swift (11486B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 
      4 // MARK: - pkt-line
      5 
      6 enum PktLine {
      7     static let flush: [UInt8] = Array("0000".utf8)
      8 
      9     static func encode(_ payload: [UInt8]) -> [UInt8] {
     10         Array(String(format: "%04x", payload.count + 4).utf8) + payload
     11     }
     12 
     13     static func encode(_ text: String) -> [UInt8] { encode(Array(text.utf8)) }
     14 
     15     /// Splits a stream into packets; `nil` = flush packet (0000).
     16     static func decode(_ data: [UInt8]) throws -> [[UInt8]?] {
     17         var out = [[UInt8]?]()
     18         var pos = 0
     19         while pos + 4 <= data.count {
     20             guard let length = Int(String(decoding: data[pos..<(pos + 4)], as: UTF8.self), radix: 16) else {
     21                 throw GitError.malformed("pkt-line: length")
     22             }
     23             if length < 4 {
     24                 out.append(nil)
     25                 pos += 4
     26                 continue
     27             }
     28             guard pos + length <= data.count else { throw GitError.malformed("truncated pkt-line") }
     29             out.append(Array(data[(pos + 4)..<(pos + length)]))
     30             pos += length
     31         }
     32         return out
     33     }
     34 }
     35 
     36 // MARK: - Transport
     37 
     38 public enum GitService: String, Sendable {
     39     case uploadPack = "git-upload-pack"
     40     case receivePack = "git-receive-pack"
     41 }
     42 
     43 /// Stateless transport, modelled on git's "smart HTTP" protocol.
     44 public protocol GitTransport: Sendable {
     45     func advertisement(_ service: GitService) async throws -> [UInt8]
     46     func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8]
     47 }
     48 
     49 public struct HTTPTransport: GitTransport {
     50     public let baseURL: URL
     51     public let username: String
     52     public let password: String
     53     public let userAgent: String
     54     public let session: URLSession
     55 
     56     public init(baseURL: URL, username: String, password: String, userAgent: String = "git/2.0 (divelog)", session: URLSession? = nil) {
     57         self.baseURL = baseURL
     58         self.username = username
     59         self.password = password
     60         self.userAgent = userAgent
     61         if let session {
     62             self.session = session
     63         } else {
     64             let config = URLSessionConfiguration.ephemeral
     65             config.timeoutIntervalForRequest = 60
     66             config.timeoutIntervalForResource = 600
     67             config.httpCookieStorage = nil
     68             config.urlCredentialStorage = nil
     69             self.session = URLSession(configuration: config)
     70         }
     71     }
     72 
     73     private func request(_ url: URL) -> URLRequest {
     74         var request = URLRequest(url: url)
     75         let token = Data("\(username):\(password)".utf8).base64EncodedString()
     76         request.setValue("Basic \(token)", forHTTPHeaderField: "Authorization")
     77         request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
     78         request.cachePolicy = .reloadIgnoringLocalCacheData
     79         return request
     80     }
     81 
     82     private func perform(_ request: URLRequest) async throws -> [UInt8] {
     83         let data: Data
     84         let response: URLResponse
     85         do {
     86             (data, response) = try await session.data(for: request)
     87         } catch {
     88             throw GitError.network(error.localizedDescription)
     89         }
     90         guard let http = response as? HTTPURLResponse else { throw GitError.network("unexpected response") }
     91         switch http.statusCode {
     92         case 200: return Array(data)
     93         case 401: throw GitError.unauthorized
     94         case 404: throw GitError.notFound
     95         default: throw GitError.http(http.statusCode)
     96         }
     97     }
     98 
     99     public func advertisement(_ service: GitService) async throws -> [UInt8] {
    100         var components = URLComponents(url: baseURL.appendingPathComponent("info/refs"), resolvingAgainstBaseURL: false)!
    101         components.queryItems = [URLQueryItem(name: "service", value: service.rawValue)]
    102         return try await perform(request(components.url!))
    103     }
    104 
    105     public func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8] {
    106         var request = request(baseURL.appendingPathComponent(service.rawValue))
    107         request.httpMethod = "POST"
    108         request.setValue("application/x-\(service.rawValue)-request", forHTTPHeaderField: "Content-Type")
    109         request.setValue("application/x-\(service.rawValue)-result", forHTTPHeaderField: "Accept")
    110         request.httpBody = Data(body)
    111         return try await perform(request)
    112     }
    113 }
    114 
    115 // MARK: - Client
    116 
    117 public struct RemoteRefs: Sendable {
    118     public var refs: [String: ObjectID] = [:]
    119     public var capabilities: Set<String> = []
    120 
    121     public func branch(_ name: String) -> ObjectID? { refs["refs/heads/\(name)"] }
    122 }
    123 
    124 public struct GitClient: Sendable {
    125     public let transport: GitTransport
    126     public let store: ObjectStore
    127     public var agent = "divelog/0.1"
    128 
    129     public init(transport: GitTransport, store: ObjectStore) {
    130         self.transport = transport
    131         self.store = store
    132     }
    133 
    134     public func refs(_ service: GitService = .uploadPack) async throws -> RemoteRefs {
    135         let packets = try PktLine.decode(try await transport.advertisement(service))
    136         var result = RemoteRefs()
    137         var first = true
    138         for packet in packets {
    139             guard var line = packet else { continue }
    140             if line.starts(with: Array("# service=".utf8)) { continue }
    141             if line.last == 0x0a { line.removeLast() }
    142             if first {
    143                 first = false
    144                 if let nul = line.firstIndex(of: 0) {
    145                     let caps = String(decoding: line[(nul + 1)...], as: UTF8.self)
    146                     result.capabilities = Set(caps.split(separator: " ").map(String.init))
    147                     line = Array(line[..<nul])
    148                 }
    149             }
    150             let text = String(decoding: line, as: UTF8.self)
    151             if text.hasPrefix("ERR ") { throw GitError.remote(String(text.dropFirst(4))) }
    152             guard text.count > 41, let id = ObjectID(hex: text.prefix(40)) else { continue }
    153             let name = String(text.dropFirst(41))
    154             if name == "capabilities^{}" || name.hasSuffix("^{}") || id.isZero { continue }
    155             result.refs[name] = id
    156         }
    157         return result
    158     }
    159 
    160     /// Fetches `want` and everything it depends on. `have` = commits already known, `shallow` = local commits without
    161     /// parents, `depth` = requested history depth. Returns the commits the server left without parents.
    162     @discardableResult
    163     public func fetch(want: ObjectID, have: [ObjectID] = [], shallow: [ObjectID] = [], depth: Int? = nil,
    164                       capabilities: Set<String>) async throws -> [ObjectID] {
    165         var caps = ["agent=\(agent)"]
    166         for wanted in ["side-band-64k", "ofs-delta", "no-progress"] where capabilities.contains(wanted) {
    167             caps.append(wanted)
    168         }
    169         let useDepth = depth != nil && capabilities.contains("shallow")
    170         var body = PktLine.encode("want \(want.hex) \(caps.joined(separator: " "))\n")
    171         if useDepth {
    172             for id in shallow { body += PktLine.encode("shallow \(id.hex)\n") }
    173             body += PktLine.encode("deepen \(depth!)\n")
    174         }
    175         body += PktLine.flush
    176         for id in have { body += PktLine.encode("have \(id.hex)\n") }
    177         body += PktLine.encode("done\n")
    178 
    179         let response = try await transport.rpc(.uploadPack, body: body)
    180         let sideband = caps.contains("side-band-64k")
    181         var newShallow = [ObjectID]()
    182         var pack = [UInt8]()
    183         var inPack = false
    184 
    185         if sideband {
    186             for packet in try PktLine.decode(response) {
    187                 guard let payload = packet, let first = payload.first else { continue }
    188                 if !inPack, first > 3 {
    189                     let text = String(decoding: payload, as: UTF8.self)
    190                     if text.hasPrefix("shallow "), let id = ObjectID(hex: text.dropFirst(8).prefix(40)) {
    191                         newShallow.append(id)
    192                     } else if text.hasPrefix("ERR ") {
    193                         throw GitError.remote(String(text.dropFirst(4)))
    194                     }
    195                     continue
    196                 }
    197                 inPack = true
    198                 switch first {
    199                 case 1: pack.append(contentsOf: payload.dropFirst())
    200                 case 3: throw GitError.remote(String(decoding: payload.dropFirst(), as: UTF8.self))
    201                 default: break
    202                 }
    203             }
    204         } else {
    205             // Without side-band: a few text packets, then the raw packfile.
    206             var pos = 0
    207             while pos + 4 <= response.count, !(response[pos] == 0x50 && response[pos + 1] == 0x41) {
    208                 guard let length = Int(String(decoding: response[pos..<(pos + 4)], as: UTF8.self), radix: 16) else { break }
    209                 if length >= 4, pos + length <= response.count {
    210                     let text = String(decoding: response[(pos + 4)..<(pos + length)], as: UTF8.self)
    211                     if text.hasPrefix("shallow "), let id = ObjectID(hex: text.dropFirst(8).prefix(40)) { newShallow.append(id) }
    212                     if text.hasPrefix("ERR ") { throw GitError.remote(String(text.dropFirst(4))) }
    213                 }
    214                 pos += max(length, 4)
    215             }
    216             pack = Array(response[min(pos, response.count)...])
    217         }
    218 
    219         guard !pack.isEmpty else { throw GitError.malformed("response without a packfile") }
    220         let store = self.store
    221         let objects = try Pack.parse(pack, external: { store.get($0) })
    222         for object in objects { _ = try store.put(object) }
    223         guard store.contains(want) else { throw GitError.missingObject(want.hex) }
    224         return newShallow
    225     }
    226 
    227     /// Sends objects and moves a reference from `old` (nil = creation) to `new`.
    228     public func push(ref: String, old: ObjectID?, new: ObjectID, objects: [GitObject]) async throws {
    229         var body = PktLine.encode(Array("\((old ?? .zero).hex) \(new.hex) \(ref)".utf8) + [0] + Array("report-status agent=\(agent)\n".utf8))
    230         body += PktLine.flush
    231         body += Pack.write(objects)
    232         let response = try await transport.rpc(.receivePack, body: body)
    233         var unpackOK = false
    234         var refOK = false
    235         for packet in try PktLine.decode(response) {
    236             guard var payload = packet else { continue }
    237             // Some servers wrap the report in side-band channel 1.
    238             if payload.first == 1 {
    239                 let inner = (try? PktLine.decode(Array(payload.dropFirst()))) ?? []
    240                 for case let line? in inner { try check(line, ref: ref, unpackOK: &unpackOK, refOK: &refOK) }
    241                 continue
    242             }
    243             if payload.first == 2 { continue }
    244             if payload.first == 3 { payload.removeFirst(); throw GitError.remote(String(decoding: payload, as: UTF8.self)) }
    245             try check(payload, ref: ref, unpackOK: &unpackOK, refOK: &refOK)
    246         }
    247         guard unpackOK, refOK else { throw GitError.pushRejected("incomplete response from the server") }
    248     }
    249 
    250     private func check(_ line: [UInt8], ref: String, unpackOK: inout Bool, refOK: inout Bool) throws {
    251         let text = String(decoding: line, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
    252         if text == "unpack ok" {
    253             unpackOK = true
    254         } else if text.hasPrefix("unpack ") {
    255             throw GitError.pushRejected(String(text.dropFirst(7)))
    256         } else if text == "ok \(ref)" {
    257             refOK = true
    258         } else if text.hasPrefix("ng ") {
    259             throw GitError.pushRejected(String(text.dropFirst(3)))
    260         }
    261     }
    262 }