@capgo/capacitor-updater 8.53.1 → 8.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,12 +23,9 @@ import UIKit
23
23
  private let PENDING_DELETE_IDS: String = "pendingDeleteIds"
24
24
  private var unzipPercent = 0
25
25
  private let TEMP_UNZIP_PREFIX: String = "capgo_unzip_"
26
- /// HTTP + decode share one pool. Cap by CPU: 8 on 4 cores, 16 on 8 cores, 64 max.
27
- static let manifestMaxConcurrentFiles = clampedManifestConcurrency(processorCount: ProcessInfo.processInfo.processorCount)
28
-
29
- static func clampedManifestConcurrency(processorCount: Int) -> Int {
30
- min(64, max(8, max(1, processorCount) * 2))
31
- }
26
+ /// 32 files in flight on every device. Fewer leaves 2-core phones waiting on per-request latency;
27
+ /// capping by CPU count (8 on 4 cores) was 2-4x slower on emulators limited to 2, 4 and 8 cores.
28
+ static let manifestMaxConcurrentFiles = 32
32
29
  private static let emptySha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
33
30
  private let deletePaceSeconds: TimeInterval = 0.075
34
31
  private let deleteLock = NSLock()
@@ -50,6 +47,38 @@ import UIKit
50
47
  public var deviceID = ""
51
48
  public var previewSession = false
52
49
  public var publicKey: String = ""
50
+ /// When true (default) every URL the updater talks to must be https, including redirect hops. Config `httpsOnly`.
51
+ public var httpsOnly: Bool = true {
52
+ didSet { redirectPolicy.httpsOnly = httpsOnly }
53
+ }
54
+ /// When true a bundle whose version is lower than the native app version is refused. Config `builtinMinimum`.
55
+ public var builtinMinimum: Bool = false
56
+ /// Error raised when `httpsOnly` is set and a URL is not https.
57
+ public static func httpsOnlyError(_ url: URL) -> NSError {
58
+ return NSError(
59
+ domain: "CapgoUpdater",
60
+ code: 7,
61
+ userInfo: [NSLocalizedDescriptionKey: "httpsOnly is enabled and \(url.absoluteString) is not https"]
62
+ )
63
+ }
64
+
65
+ /// Returns nil when the URL may be requested, or the `httpsOnly` error to fail with.
66
+ func checkAllowedScheme(_ url: URL?) -> Error? {
67
+ guard self.httpsOnly, let url else {
68
+ return nil
69
+ }
70
+ if url.scheme?.lowercased() == "https" {
71
+ return nil
72
+ }
73
+ logger.error("httpsOnly is enabled and \(url.absoluteString) is not https")
74
+ return Self.httpsOnlyError(url)
75
+ }
76
+
77
+ func assertAllowedScheme(_ url: URL) throws {
78
+ if let error = checkAllowedScheme(url) {
79
+ throw error
80
+ }
81
+ }
53
82
 
54
83
  // Cached key ID calculated once from publicKey
55
84
  private var cachedKeyId: String?
@@ -123,6 +152,13 @@ import UIKit
123
152
  let response: HTTPURLResponse?
124
153
  let error: Error?
125
154
  let timedOut: Bool
155
+ /// Bytes URLSession kept from an interrupted transfer, usable with downloadTask(withResumeData:).
156
+ var resumeData: Data?
157
+ }
158
+
159
+ /// Resume data carried between the retry attempts of one manifest file.
160
+ final class ManifestResumeState {
161
+ var data: Data?
126
162
  }
127
163
 
128
164
  enum SecurePathError: Error {
@@ -255,7 +291,7 @@ import UIKit
255
291
  configuration.urlCache = nil
256
292
  configuration.httpMaximumConnectionsPerHost = Self.manifestMaxConcurrentFiles
257
293
  redirectPolicy.onBlockedRedirect = { [weak self] source, target in
258
- self?.logger?.error("Blocked HTTPS to HTTP redirect; set allowHttpsToHttpRedirect to true to allow it")
294
+ self?.logger?.error("Blocked redirect to a non-https URL (httpsOnly, or allowHttpsToHttpRedirect is false)")
259
295
  self?.logger?.debug("Redirect from \(source?.absoluteString ?? "") to \(target?.absoluteString ?? "")")
260
296
  }
261
297
  let session = URLSession(configuration: configuration, delegate: redirectPolicy, delegateQueue: nil)
@@ -275,6 +311,12 @@ import UIKit
275
311
  /// Runs a raw data task on the updater session (no cookies, no cache, redirect policy applied).
276
312
  @discardableResult
277
313
  func startRawDataTask(_ request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
314
+ if let schemeError = checkAllowedScheme(request.url) {
315
+ // Never resumed: the session will not call back, so the completion runs exactly once.
316
+ let idle = self.urlSession.dataTask(with: request) { _, _, _ in }
317
+ completion(nil, nil, schemeError)
318
+ return idle
319
+ }
278
320
  let task = self.urlSession.dataTask(with: request, completionHandler: completion)
279
321
  task.resume()
280
322
  return task
@@ -289,6 +331,14 @@ import UIKit
289
331
  completionQueue: DispatchQueue,
290
332
  completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
291
333
  ) -> URLSessionDataTask {
334
+ if let schemeError = checkAllowedScheme(request.url) {
335
+ // Never resumed: the session will not call back, so the completion runs exactly once.
336
+ let idle = self.urlSession.dataTask(with: request) { _, _, _ in }
337
+ completionQueue.async {
338
+ completion(nil, nil, schemeError)
339
+ }
340
+ return idle
341
+ }
292
342
  let task = self.urlSession.dataTask(with: request) { data, response, error in
293
343
  let httpResponse = response as? HTTPURLResponse
294
344
  let body = (data?.isEmpty ?? true) ? nil : data
@@ -419,18 +469,28 @@ import UIKit
419
469
  }
420
470
 
421
471
  func performDownloadRequest(_ request: URLRequest, label: String) -> DownloadRequestResult {
472
+ performDownloadRequest(request, label: label, resumeData: nil)
473
+ }
474
+
475
+ func performDownloadRequest(_ request: URLRequest, label: String, resumeData: Data?) -> DownloadRequestResult {
476
+ if let schemeError = checkAllowedScheme(request.url) {
477
+ return DownloadRequestResult(fileURL: nil, response: nil, error: schemeError, timedOut: false)
478
+ }
422
479
  let waitTimeout = max(self.timeout + 5, 10)
423
480
  let semaphore = DispatchSemaphore(value: 0)
424
481
  var tempFileURL: URL?
425
482
  var httpResponse: HTTPURLResponse?
426
483
  var requestError: Error?
484
+ var interruptedResumeData: Data?
427
485
  let temporaryDownloadURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
428
- let downloadTask = self.urlSession.downloadTask(with: request) { location, response, error in
486
+ let completion: (URL?, URLResponse?, Error?) -> Void = { location, response, error in
429
487
  // URLSession deletes `location` once this handler returns, so move it synchronously here.
430
488
  var movedFileURL: URL?
431
489
  var resultError: Error?
490
+ var resultResumeData: Data?
432
491
  if let error {
433
492
  resultError = NetworkError.sessionTaskFailed(error)
493
+ resultResumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
434
494
  } else if let location {
435
495
  do {
436
496
  let fileManager = FileManager.default
@@ -453,9 +513,12 @@ import UIKit
453
513
  tempFileURL = movedFileURL
454
514
  httpResponse = taskResponse
455
515
  requestError = resultError
516
+ interruptedResumeData = resultResumeData
456
517
  semaphore.signal()
457
518
  }
458
519
  }
520
+ let downloadTask = resumeData.map { self.urlSession.downloadTask(withResumeData: $0, completionHandler: completion) }
521
+ ?? self.urlSession.downloadTask(with: request, completionHandler: completion)
459
522
  downloadTask.resume()
460
523
 
461
524
  if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
@@ -477,7 +540,8 @@ import UIKit
477
540
  fileURL: existingDownloadFileURL(tempFileURL, fallback: temporaryDownloadURL),
478
541
  response: httpResponse,
479
542
  error: requestError,
480
- timedOut: isTimedOutError(requestError)
543
+ timedOut: isTimedOutError(requestError),
544
+ resumeData: interruptedResumeData
481
545
  )
482
546
  }
483
547
 
@@ -497,13 +561,15 @@ import UIKit
497
561
  CryptoCipher.shortPathKey(fileName)
498
562
  }
499
563
 
500
- static func manifestPartialURL(cacheFolder: URL, hash: String, fileName: String) -> URL {
564
+ /// Scoped to one download so concurrent downloads of the same file never write one partial.
565
+ static func manifestPartialURL(cacheFolder: URL, downloadId: String, hash: String, fileName: String) -> URL {
566
+ let owner = CryptoCipher.shortPathKey(downloadId)
501
567
  let token = safePartialToken(fileName)
502
568
  if isSafeCacheHash(hash) && hash.count == 64 {
503
- return cacheFolder.appendingPathComponent("partial_\(hash)_\(token).tmp")
569
+ return cacheFolder.appendingPathComponent("partial_\(owner)_\(hash)_\(token).tmp")
504
570
  }
505
571
  let digest = CryptoCipher.shortPathKey("\(hash)|\(fileName)")
506
- return cacheFolder.appendingPathComponent("partial_\(digest)_\(token).tmp")
572
+ return cacheFolder.appendingPathComponent("partial_\(owner)_\(digest)_\(token).tmp")
507
573
  }
508
574
 
509
575
  private func removePartialManifestBundleDirectory(_ destFolder: URL) {
@@ -632,6 +698,34 @@ import UIKit
632
698
  }
633
699
  }
634
700
 
701
+ /// `builtinMinimum`: refuse any bundle version lower than the native app version (`versionBuild`).
702
+ /// Versions that do not parse as semver skip the check so odd native version strings never block updates.
703
+ func requireVersionNotBelowBuiltin(_ version: String) throws {
704
+ guard self.builtinMinimum else {
705
+ return
706
+ }
707
+ // Build metadata (+...) never takes part in ordering, and may contain dots the parser rejects.
708
+ let bundleCore = String(version.split(separator: "+", maxSplits: 1).first ?? "")
709
+ let nativeCore = String(self.versionBuild.split(separator: "+", maxSplits: 1).first ?? "")
710
+ guard let parsedBundle = try? CapgoSemanticVersion(bundleCore),
711
+ let parsedNative = try? CapgoSemanticVersion(nativeCore) else {
712
+ logger?.debug("builtinMinimum skipped: cannot parse bundle version \(version) or native version \(self.versionBuild)")
713
+ return
714
+ }
715
+ // Only major.minor.patch matter: a prerelease bundle at the native version is not a rollback.
716
+ let bundleVersion = CapgoSemanticVersion(major: parsedBundle.major, minor: parsedBundle.minor, patch: parsedBundle.patch)
717
+ let nativeVersion = CapgoSemanticVersion(major: parsedNative.major, minor: parsedNative.minor, patch: parsedNative.patch)
718
+ if bundleVersion < nativeVersion {
719
+ logger?.error("Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)")
720
+ self.sendStats(action: "version_below_native", versionName: version)
721
+ throw NSError(
722
+ domain: "CapgoUpdater",
723
+ code: 8,
724
+ userInfo: [NSLocalizedDescriptionKey: "Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)"]
725
+ )
726
+ }
727
+ }
728
+
635
729
  public func setPublicKey(_ publicKey: String) {
636
730
  // Empty string means no encryption - proceed normally
637
731
  if publicKey.isEmpty {
@@ -1270,8 +1364,7 @@ import UIKit
1270
1364
  let builtinLookupName = knownEntry?.originalFileName ?? relativePath
1271
1365
  let isBuiltinOrigin: Bool
1272
1366
  if let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: builtinLookupName) {
1273
- isBuiltinOrigin = fileManager.fileExists(atPath: builtinFilePath.path) &&
1274
- verifyChecksum(file: builtinFilePath, expectedHash: checksum)
1367
+ isBuiltinOrigin = builtinFileMatches(builtinFilePath, expectedHash: checksum)
1275
1368
  } else {
1276
1369
  isBuiltinOrigin = false
1277
1370
  }
@@ -1285,7 +1378,7 @@ import UIKit
1285
1378
  }
1286
1379
 
1287
1380
  do {
1288
- try copyItemAtomically(from: fileURL, to: cacheFile)
1381
+ try linkOrCopyImmutableFile(from: fileURL, to: cacheFile)
1289
1382
  } catch {
1290
1383
  logger.debug("Delta cache copy failed: \(fileURL.path)")
1291
1384
  }
@@ -1485,6 +1578,93 @@ import UIKit
1485
1578
  Bundle.main.bundleURL.appendingPathComponent("public")
1486
1579
  }
1487
1580
 
1581
+ // Precomputed builtin hashes: `ota-builtin-hashes.json` in the web assets dir (Capacitor sync hook).
1582
+ // Loaded lazily once per process; missing or invalid JSON is cached as an empty map.
1583
+ static let builtinHashesFileName = "ota-builtin-hashes.json"
1584
+ private static func isSha256Hex(_ value: String) -> Bool {
1585
+ guard value.count == 64 else { return false }
1586
+ let hex = CharacterSet(charactersIn: "0123456789abcdefABCDEF")
1587
+ return value.unicodeScalars.allSatisfy { hex.contains($0) }
1588
+ }
1589
+
1590
+ private struct BuiltinHashEntry {
1591
+ let hash: String
1592
+ /// `nil` for legacy string-only manifest entries (no size gate).
1593
+ let size: Int64?
1594
+ }
1595
+
1596
+ private var cachedBuiltinHashes: [String: BuiltinHashEntry]?
1597
+ private let builtinHashesLock = NSLock()
1598
+ /// Disk reads of `ota-builtin-hashes.json` (lazy once per updater instance / process).
1599
+ private(set) var builtinHashesTableLoadCount = 0
1600
+
1601
+ private func builtinHashes() -> [String: BuiltinHashEntry] {
1602
+ builtinHashesLock.lock()
1603
+ defer { builtinHashesLock.unlock() }
1604
+ if let hashes = cachedBuiltinHashes {
1605
+ return hashes
1606
+ }
1607
+ var hashes: [String: BuiltinHashEntry] = [:]
1608
+ let tableURL = builtinFolderURL().appendingPathComponent(Self.builtinHashesFileName)
1609
+ builtinHashesTableLoadCount += 1
1610
+ if let data = try? Data(contentsOf: tableURL),
1611
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1612
+ let files = json["files"] as? [String: Any] {
1613
+ for (key, value) in files {
1614
+ if let hash = value as? String, Self.isSha256Hex(hash) {
1615
+ hashes[key] = BuiltinHashEntry(hash: hash, size: nil)
1616
+ continue
1617
+ }
1618
+ guard let obj = value as? [String: Any],
1619
+ let hash = obj["sha256"] as? String,
1620
+ Self.isSha256Hex(hash) else { continue }
1621
+ let sizeValue: Int64?
1622
+ if obj["size"] == nil || obj["size"] is NSNull {
1623
+ sizeValue = nil
1624
+ } else if let size = obj["size"] as? NSNumber,
1625
+ CFGetTypeID(size) != CFBooleanGetTypeID(),
1626
+ let exact = Int64(exactly: size.doubleValue),
1627
+ exact >= 0 {
1628
+ sizeValue = exact
1629
+ } else {
1630
+ continue
1631
+ }
1632
+ hashes[key] = BuiltinHashEntry(hash: hash, size: sizeValue)
1633
+ }
1634
+ }
1635
+ cachedBuiltinHashes = hashes
1636
+ return hashes
1637
+ }
1638
+
1639
+ private func builtinTableVerdict(relativePath: String, fileURL: URL, expectedHash: String) -> Bool? {
1640
+ guard let entry = builtinHashes()[relativePath] else {
1641
+ return nil
1642
+ }
1643
+ guard FileManager.default.fileExists(atPath: fileURL.path) else {
1644
+ return false
1645
+ }
1646
+ if let expectedSize = entry.size {
1647
+ let actualSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Int64($0) }
1648
+ if actualSize != expectedSize {
1649
+ return nil
1650
+ }
1651
+ }
1652
+ return entry.hash.lowercased() == expectedHash.lowercased()
1653
+ }
1654
+
1655
+ private func builtinFileMatches(_ builtinFilePath: URL, expectedHash: String) -> Bool {
1656
+ let basePath = builtinFolderURL().standardizedFileURL.path
1657
+ let filePath = builtinFilePath.standardizedFileURL.path
1658
+ if filePath.hasPrefix(basePath + "/") {
1659
+ let relativePath = String(filePath.dropFirst(basePath.count + 1))
1660
+ if let verdict = builtinTableVerdict(relativePath: relativePath, fileURL: builtinFilePath, expectedHash: expectedHash) {
1661
+ return verdict
1662
+ }
1663
+ }
1664
+ return FileManager.default.fileExists(atPath: builtinFilePath.path) &&
1665
+ verifyChecksum(file: builtinFilePath, expectedHash: expectedHash)
1666
+ }
1667
+
1488
1668
  private func resolveManifestFileHash(entry: ManifestEntry, sessionKey: String) -> String? {
1489
1669
  guard var fileHash = entry.file_hash, !fileHash.isEmpty else {
1490
1670
  return nil
@@ -1515,7 +1695,7 @@ import UIKit
1515
1695
  guard let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName) else {
1516
1696
  return false
1517
1697
  }
1518
- if FileManager.default.fileExists(atPath: builtinFilePath.path) && verifyChecksum(file: builtinFilePath, expectedHash: fileHash) {
1698
+ if builtinFileMatches(builtinFilePath, expectedHash: fileHash) {
1519
1699
  return true
1520
1700
  }
1521
1701
 
@@ -1653,7 +1833,14 @@ import UIKit
1653
1833
  }
1654
1834
 
1655
1835
  public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
1836
+ let decryptionSession = CryptoCipher.DecryptionSession(publicKey: self.publicKey, sessionKey: sessionKey)
1656
1837
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
1838
+ try self.requireVersionNotBelowBuiltin(version)
1839
+ for entry in manifest {
1840
+ if let downloadUrl = entry.download_url, let url = URL(string: downloadUrl) {
1841
+ try self.assertAllowedScheme(url)
1842
+ }
1843
+ }
1657
1844
  try self.runBeforeDownload()
1658
1845
  let id = self.randomString(length: 10)
1659
1846
  logger.info("downloadManifest start \(id)")
@@ -1681,7 +1868,9 @@ import UIKit
1681
1868
  let totalFiles = manifest.count
1682
1869
 
1683
1870
  // Thread-safe counters for concurrent operations
1684
- let completedFiles = AtomicCounter()
1871
+ let progressLock = NSLock()
1872
+ var completedFiles = 0
1873
+ var lastProgressPercent = -1
1685
1874
  let hasError = AtomicBool(initialValue: false)
1686
1875
  var downloadError: Error?
1687
1876
  let errorLock = NSLock()
@@ -1855,8 +2044,7 @@ import UIKit
1855
2044
 
1856
2045
  do {
1857
2046
  // Try builtin first
1858
- if FileManager.default.fileExists(atPath: task.builtinFilePath.path) &&
1859
- self.verifyChecksum(file: task.builtinFilePath, expectedHash: task.finalFileHash) {
2047
+ if self.builtinFileMatches(task.builtinFilePath, expectedHash: task.finalFileHash) {
1860
2048
  try self.copyItemReplacing(from: task.builtinFilePath, to: task.destFilePath)
1861
2049
  self.logger.info("downloadManifest \(task.fileName) using builtin file \(id)")
1862
2050
  }
@@ -1870,23 +2058,19 @@ import UIKit
1870
2058
  }
1871
2059
  // Download
1872
2060
  else {
1873
- try self.downloadManifestFile(
1874
- downloadUrl: task.downloadUrl,
1875
- destFilePath: task.destFilePath,
1876
- cacheFilePath: task.cacheFilePath,
1877
- fileHash: task.finalFileHash,
1878
- fileName: task.fileName,
1879
- destFileName: task.destFileName,
1880
- isBrotli: task.isBrotli,
1881
- sessionKey: sessionKey,
1882
- version: version,
1883
- bundleId: id
1884
- )
2061
+ try self.downloadManifestFile(task, version: version, bundleId: id, decryptionSession: decryptionSession) {
2062
+ hasError.value
2063
+ }
1885
2064
  }
1886
2065
 
1887
- let completed = completedFiles.increment()
1888
- let percent = self.calcTotalPercent(percent: Int((Double(completed) / Double(totalFiles)) * 100), min: 10, max: 70)
1889
- self.notifyDownload(id: id, percent: percent)
2066
+ progressLock.lock()
2067
+ completedFiles += 1
2068
+ let percent = self.calcTotalPercent(percent: Int((Double(completedFiles) / Double(totalFiles)) * 100), min: 10, max: 70)
2069
+ if percent > lastProgressPercent {
2070
+ lastProgressPercent = percent
2071
+ self.notifyDownload(id: id, percent: percent, bundle: bundleInfo)
2072
+ }
2073
+ progressLock.unlock()
1890
2074
 
1891
2075
  } catch {
1892
2076
  errorLock.lock()
@@ -1934,17 +2118,73 @@ import UIKit
1934
2118
  /// Downloads a single manifest file synchronously
1935
2119
  /// Used by downloadManifest for concurrent file downloads
1936
2120
  private func downloadManifestFile(
1937
- downloadUrl: String,
1938
- destFilePath: URL,
1939
- cacheFilePath: URL?,
1940
- fileHash: String,
1941
- fileName: String,
1942
- destFileName: String,
1943
- isBrotli: Bool,
1944
- sessionKey: String,
1945
- version: String,
1946
- bundleId: String
2121
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2122
+ shouldStop: () -> Bool
2123
+ ) throws {
2124
+ let resume = ManifestResumeState()
2125
+ for attempt in 1...3 {
2126
+ do {
2127
+ try downloadManifestFileOnce(task, version: version, bundleId: bundleId, decryptionSession: decryptionSession, resume: resume)
2128
+ return
2129
+ } catch {
2130
+ guard attempt < 3 && Self.isRetryableManifestError(error) else {
2131
+ // One failure stat per file, after the last attempt.
2132
+ if Self.isManifestTransferError(error) {
2133
+ self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(task.fileName)")
2134
+ }
2135
+ throw error
2136
+ }
2137
+ // Back off in short steps so a failed or cancelled manifest stops retrying promptly.
2138
+ for _ in 0..<(5 * attempt) {
2139
+ if shouldStop() { throw error }
2140
+ Thread.sleep(forTimeInterval: 0.05)
2141
+ }
2142
+ }
2143
+ }
2144
+ }
2145
+
2146
+ /// Transport errors arrive wrapped in NetworkError.sessionTaskFailed; classify the underlying error.
2147
+ static func isRetryableManifestError(_ error: Error) -> Bool {
2148
+ if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
2149
+ return isRetryableManifestError(underlying)
2150
+ }
2151
+ let failure = error as NSError
2152
+ if failure.domain == manifestResumeErrorDomain {
2153
+ return true
2154
+ }
2155
+ if failure.domain == "StatusCodeError" {
2156
+ return failure.code == 408 || (500...599).contains(failure.code)
2157
+ }
2158
+ return failure.domain == NSURLErrorDomain && [
2159
+ NSURLErrorTimedOut, NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet,
2160
+ NSURLErrorCannotConnectToHost, NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed
2161
+ ].contains(failure.code)
2162
+ }
2163
+
2164
+ /// Failures that reach the server or network, as opposed to checksum, decryption or storage errors.
2165
+ private static func isManifestTransferError(_ error: Error) -> Bool {
2166
+ if error is NetworkError {
2167
+ return true
2168
+ }
2169
+ let failure = error as NSError
2170
+ return failure.domain == NSURLErrorDomain || failure.domain == "StatusCodeError" || failure.domain == manifestResumeErrorDomain ||
2171
+ (failure.domain == "ManifestDownloadError" && failure.code == 3)
2172
+ }
2173
+
2174
+ /// A resumed transfer that cannot be trusted: drop the partial and fetch the whole file on the next attempt.
2175
+ static let manifestResumeErrorDomain = "ManifestResumeError"
2176
+
2177
+ private func downloadManifestFileOnce(
2178
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2179
+ resume: ManifestResumeState
1947
2180
  ) throws {
2181
+ let downloadUrl = task.downloadUrl
2182
+ let destFilePath = task.destFilePath
2183
+ let cacheFilePath = task.cacheFilePath
2184
+ let fileHash = task.finalFileHash
2185
+ let fileName = task.fileName
2186
+ let destFileName = task.destFileName
2187
+ let isBrotli = task.isBrotli
1948
2188
  guard let url = URL(string: downloadUrl) else {
1949
2189
  throw NSError(
1950
2190
  domain: "ManifestDownloadError",
@@ -1962,7 +2202,13 @@ import UIKit
1962
2202
  }
1963
2203
 
1964
2204
  try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
1965
- let partialURL = Self.manifestPartialURL(cacheFolder: cacheFolder, hash: fileHash, fileName: fileName)
2205
+ let partialURL = Self.manifestPartialURL(cacheFolder: cacheFolder, downloadId: bundleId, hash: fileHash, fileName: fileName)
2206
+ let resumeData = resume.data
2207
+ resume.data = nil
2208
+ if resumeData != nil {
2209
+ // URLSession resumes its own interrupted transfer and returns the whole file.
2210
+ try? FileManager.default.removeItem(at: partialURL)
2211
+ }
1966
2212
  let existingBytes: Int64
1967
2213
  if FileManager.default.fileExists(atPath: partialURL.path) {
1968
2214
  existingBytes = Int64((try FileManager.default.attributesOfItem(atPath: partialURL.path)[.size] as? NSNumber)?.int64Value ?? 0)
@@ -1972,8 +2218,13 @@ import UIKit
1972
2218
  if existingBytes > 0 {
1973
2219
  request.setValue("bytes=\(existingBytes)-", forHTTPHeaderField: "Range")
1974
2220
  }
2221
+ // True while the bytes on disk come from more than one response; a bad result then earns a clean GET.
2222
+ var resumed = resumeData != nil
1975
2223
 
1976
- let result = performDownloadRequest(request, label: "downloadManifestFile \(fileName)")
2224
+ let label = "downloadManifestFile \(fileName)"
2225
+ let result = resumeData.map { performDownloadRequest(request, label: label, resumeData: $0) }
2226
+ ?? performDownloadRequest(request, label: label)
2227
+ resume.data = result.resumeData
1977
2228
  defer {
1978
2229
  if let fileURL = result.fileURL {
1979
2230
  try? FileManager.default.removeItem(at: fileURL)
@@ -1982,7 +2233,6 @@ import UIKit
1982
2233
 
1983
2234
  if result.timedOut {
1984
2235
  persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
1985
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
1986
2236
  throw NSError(
1987
2237
  domain: NSURLErrorDomain,
1988
2238
  code: NSURLErrorTimedOut,
@@ -1992,32 +2242,45 @@ import UIKit
1992
2242
 
1993
2243
  if let error = result.error {
1994
2244
  persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
1995
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
1996
2245
  self.logger.error("Manifest file download network error")
1997
2246
  self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
1998
2247
  throw error
1999
2248
  }
2000
2249
 
2001
2250
  let statusCode = result.response?.statusCode ?? 200
2251
+ var storeOffset = existingBytes
2252
+ if statusCode == 206 && existingBytes > 0 {
2253
+ switch Self.contentRangeStart(result.response?.value(forHTTPHeaderField: "Content-Range")) {
2254
+ case .some(existingBytes):
2255
+ resumed = true
2256
+ case .some(0):
2257
+ storeOffset = 0
2258
+ default:
2259
+ try? FileManager.default.removeItem(at: partialURL)
2260
+ throw NSError(
2261
+ domain: Self.manifestResumeErrorDomain,
2262
+ code: 1,
2263
+ userInfo: [NSLocalizedDescriptionKey: "Content-Range does not continue the partial for \(fileName)"]
2264
+ )
2265
+ }
2266
+ }
2002
2267
  if statusCode == 416 && existingBytes > 0 {
2003
2268
  logger.debug("Range not satisfiable, using existing partial \(partialURL.lastPathComponent)")
2269
+ resumed = true
2004
2270
  } else if statusCode < 200 || statusCode >= 300 {
2005
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2006
2271
  throw NSError(domain: "StatusCodeError", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "Failed to fetch. Status code (\(statusCode)) invalid for file \(fileName) at url \(downloadUrl)"])
2007
2272
  } else {
2008
2273
  guard let downloadedFileURL = result.fileURL, FileManager.default.fileExists(atPath: downloadedFileURL.path) else {
2009
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2010
2274
  throw NSError(
2011
2275
  domain: "ManifestDownloadError",
2012
2276
  code: 3,
2013
2277
  userInfo: [NSLocalizedDescriptionKey: "Manifest file response was empty for \(fileName) at url \(downloadUrl)"]
2014
2278
  )
2015
2279
  }
2016
- try storeDownloadedFile(downloadedFileURL, at: partialURL, existingBytes: existingBytes, response: result.response)
2280
+ try storeDownloadedFile(downloadedFileURL, at: partialURL, existingBytes: storeOffset, response: result.response)
2017
2281
  }
2018
2282
 
2019
2283
  guard FileManager.default.fileExists(atPath: partialURL.path) else {
2020
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2021
2284
  throw NSError(
2022
2285
  domain: "ManifestDownloadError",
2023
2286
  code: 3,
@@ -2034,14 +2297,15 @@ import UIKit
2034
2297
 
2035
2298
  do {
2036
2299
  var source = partialURL
2037
- if !self.publicKey.isEmpty && CryptoCipher.isValidSessionKey(sessionKey) {
2300
+ if decryptionSession.isEncrypted {
2038
2301
  let work = cacheFolder.appendingPathComponent("work_\(UUID().uuidString)_\((fileName as NSString).lastPathComponent)")
2039
2302
  try FileManager.default.copyItem(at: partialURL, to: work)
2040
2303
  workURL = work
2041
2304
  do {
2042
- try CryptoCipher.decryptFile(filePath: work, publicKey: self.publicKey, sessionKey: sessionKey, version: version)
2305
+ try decryptionSession.decryptFile(filePath: work)
2043
2306
  } catch {
2044
2307
  try? FileManager.default.removeItem(at: partialURL)
2308
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2045
2309
  self.sendStats(action: "decrypt_fail", versionName: version)
2046
2310
  throw error
2047
2311
  }
@@ -2054,14 +2318,13 @@ import UIKit
2054
2318
  calculatedChecksum = try decompressBrotli(from: source, to: destFilePath, fileName: fileName)
2055
2319
  } catch {
2056
2320
  try? FileManager.default.removeItem(at: partialURL)
2321
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2057
2322
  self.sendStats(action: "download_manifest_brotli_fail", versionName: "\(version):\(destFileName)")
2058
2323
  throw error
2059
2324
  }
2060
2325
  } else {
2061
2326
  let handle = try FileHandle(forReadingFrom: source)
2062
- defer {
2063
- try? handle.close()
2064
- }
2327
+ defer { try? handle.close() }
2065
2328
  let length = (try FileManager.default.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.uint64Value ?? 0
2066
2329
  calculatedChecksum = try streamCopy(from: handle, count: length, to: destFilePath)
2067
2330
  }
@@ -2071,17 +2334,23 @@ import UIKit
2071
2334
  if calculatedChecksum != fileHash {
2072
2335
  try? FileManager.default.removeItem(at: destFilePath)
2073
2336
  try? FileManager.default.removeItem(at: partialURL)
2337
+ let mismatch = NSError(domain: "ChecksumError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Computed checksum is not equal to required checksum (\(calculatedChecksum) != \(fileHash)) for file \(fileName) at url \(downloadUrl)"])
2338
+ if resumed { throw Self.resumeVerificationError(mismatch, fileName: fileName) }
2074
2339
  self.sendStats(action: "download_manifest_checksum_fail", versionName: "\(version):\(destFileName)")
2075
- throw NSError(domain: "ChecksumError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Computed checksum is not equal to required checksum (\(calculatedChecksum) != \(fileHash)) for file \(fileName) at url \(downloadUrl)"])
2340
+ throw mismatch
2076
2341
  }
2077
2342
 
2078
2343
  if let cacheFilePath {
2079
- try copyItemAtomically(from: destFilePath, to: cacheFilePath)
2344
+ do {
2345
+ try linkOrCopyImmutableFile(from: destFilePath, to: cacheFilePath)
2346
+ } catch {
2347
+ logger.debug("Delta cache write failed: \(error.localizedDescription)")
2348
+ }
2080
2349
  }
2081
2350
  try? FileManager.default.removeItem(at: partialURL)
2082
2351
 
2083
2352
  self.logger.info("Manifest file downloaded and cached")
2084
- self.logger.debug("Bundle: \(bundleId), File: \(fileName), Brotli: \(isBrotli), Encrypted: \(!self.publicKey.isEmpty && !sessionKey.isEmpty)")
2353
+ self.logger.debug("Bundle: \(bundleId), File: \(fileName), Brotli: \(isBrotli), Encrypted: \(decryptionSession.isEncrypted)")
2085
2354
  } catch {
2086
2355
  self.logger.error("Manifest file download failed")
2087
2356
  self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
@@ -2089,6 +2358,27 @@ import UIKit
2089
2358
  }
2090
2359
  }
2091
2360
 
2361
+ /// Bad bytes after a resume earn a clean GET; local storage errors are not wrapped and stay permanent.
2362
+ private static func resumeVerificationError(_ underlying: Error, fileName: String) -> NSError {
2363
+ NSError(
2364
+ domain: manifestResumeErrorDomain,
2365
+ code: 2,
2366
+ userInfo: [NSLocalizedDescriptionKey: "Resumed transfer failed verification for \(fileName)", NSUnderlyingErrorKey: underlying]
2367
+ )
2368
+ }
2369
+
2370
+ /// Start offset of a `bytes start-end/total` Content-Range header, or nil when absent or malformed.
2371
+ static func contentRangeStart(_ header: String?) -> Int64? {
2372
+ guard let header, header.hasPrefix("bytes ") else {
2373
+ return nil
2374
+ }
2375
+ let range = header.dropFirst("bytes ".count)
2376
+ guard let dash = range.firstIndex(of: "-") else {
2377
+ return nil
2378
+ }
2379
+ return Int64(range[range.startIndex..<dash].trimmingCharacters(in: .whitespaces))
2380
+ }
2381
+
2092
2382
  /// Copy a file to the destination, replacing any existing file.
2093
2383
  private func copyItemReplacing(from source: URL, to destination: URL) throws {
2094
2384
  let fileManager = FileManager.default
@@ -2144,6 +2434,21 @@ import UIKit
2144
2434
  try replaceItemAtomically(at: destination, withItemAt: tempURL)
2145
2435
  }
2146
2436
 
2437
+ /// Only updater-owned verified bundle/cache files, which are never rewritten in place.
2438
+ func linkOrCopyImmutableFile(from source: URL, to destination: URL) throws {
2439
+ let manager = FileManager.default
2440
+ try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
2441
+ let temp = destination.deletingLastPathComponent().appendingPathComponent("capgo-link-\(UUID().uuidString).tmp")
2442
+ defer { try? manager.removeItem(at: temp) }
2443
+ do {
2444
+ try manager.linkItem(at: source.resolvingSymlinksInPath(), to: temp)
2445
+ } catch {
2446
+ try copyItemAtomically(from: source.resolvingSymlinksInPath(), to: destination)
2447
+ return
2448
+ }
2449
+ try replaceItemAtomically(at: destination, withItemAt: temp)
2450
+ }
2451
+
2147
2452
  /// One-step replace when dest exists, move when it does not. Avoids the
2148
2453
  /// fileExists/removeItem race that can fail a verified install.
2149
2454
  private func replaceItemAtomically(at destination: URL, withItemAt tempURL: URL) throws {
@@ -2169,7 +2474,7 @@ import UIKit
2169
2474
  // Hash is in the cache file name and was verified when written.
2170
2475
  // Re-hashing here would re-read every reused file on low-RAM devices.
2171
2476
  do {
2172
- try copyItemAtomically(from: source, to: destination)
2477
+ try linkOrCopyImmutableFile(from: source, to: destination)
2173
2478
  return true
2174
2479
  } catch {
2175
2480
  // File was deleted between check and copy, or other IO error - caller should download instead
@@ -2375,6 +2680,8 @@ import UIKit
2375
2680
  expectedChecksum: String?
2376
2681
  ) throws -> BundleInfo {
2377
2682
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
2683
+ try self.requireVersionNotBelowBuiltin(version)
2684
+ try self.assertAllowedScheme(url)
2378
2685
  let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2379
2686
  try self.runBeforeDownload()
2380
2687
  let id: String = self.randomString(length: 10)