@capgo/capacitor-updater 8.53.1 → 8.54.0

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 {
@@ -1285,7 +1379,7 @@ import UIKit
1285
1379
  }
1286
1380
 
1287
1381
  do {
1288
- try copyItemAtomically(from: fileURL, to: cacheFile)
1382
+ try linkOrCopyImmutableFile(from: fileURL, to: cacheFile)
1289
1383
  } catch {
1290
1384
  logger.debug("Delta cache copy failed: \(fileURL.path)")
1291
1385
  }
@@ -1653,7 +1747,14 @@ import UIKit
1653
1747
  }
1654
1748
 
1655
1749
  public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
1750
+ let decryptionSession = CryptoCipher.DecryptionSession(publicKey: self.publicKey, sessionKey: sessionKey)
1656
1751
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
1752
+ try self.requireVersionNotBelowBuiltin(version)
1753
+ for entry in manifest {
1754
+ if let downloadUrl = entry.download_url, let url = URL(string: downloadUrl) {
1755
+ try self.assertAllowedScheme(url)
1756
+ }
1757
+ }
1657
1758
  try self.runBeforeDownload()
1658
1759
  let id = self.randomString(length: 10)
1659
1760
  logger.info("downloadManifest start \(id)")
@@ -1681,7 +1782,9 @@ import UIKit
1681
1782
  let totalFiles = manifest.count
1682
1783
 
1683
1784
  // Thread-safe counters for concurrent operations
1684
- let completedFiles = AtomicCounter()
1785
+ let progressLock = NSLock()
1786
+ var completedFiles = 0
1787
+ var lastProgressPercent = -1
1685
1788
  let hasError = AtomicBool(initialValue: false)
1686
1789
  var downloadError: Error?
1687
1790
  let errorLock = NSLock()
@@ -1870,23 +1973,19 @@ import UIKit
1870
1973
  }
1871
1974
  // Download
1872
1975
  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
- )
1976
+ try self.downloadManifestFile(task, version: version, bundleId: id, decryptionSession: decryptionSession) {
1977
+ hasError.value
1978
+ }
1885
1979
  }
1886
1980
 
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)
1981
+ progressLock.lock()
1982
+ completedFiles += 1
1983
+ let percent = self.calcTotalPercent(percent: Int((Double(completedFiles) / Double(totalFiles)) * 100), min: 10, max: 70)
1984
+ if percent > lastProgressPercent {
1985
+ lastProgressPercent = percent
1986
+ self.notifyDownload(id: id, percent: percent, bundle: bundleInfo)
1987
+ }
1988
+ progressLock.unlock()
1890
1989
 
1891
1990
  } catch {
1892
1991
  errorLock.lock()
@@ -1934,17 +2033,73 @@ import UIKit
1934
2033
  /// Downloads a single manifest file synchronously
1935
2034
  /// Used by downloadManifest for concurrent file downloads
1936
2035
  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
2036
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2037
+ shouldStop: () -> Bool
2038
+ ) throws {
2039
+ let resume = ManifestResumeState()
2040
+ for attempt in 1...3 {
2041
+ do {
2042
+ try downloadManifestFileOnce(task, version: version, bundleId: bundleId, decryptionSession: decryptionSession, resume: resume)
2043
+ return
2044
+ } catch {
2045
+ guard attempt < 3 && Self.isRetryableManifestError(error) else {
2046
+ // One failure stat per file, after the last attempt.
2047
+ if Self.isManifestTransferError(error) {
2048
+ self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(task.fileName)")
2049
+ }
2050
+ throw error
2051
+ }
2052
+ // Back off in short steps so a failed or cancelled manifest stops retrying promptly.
2053
+ for _ in 0..<(5 * attempt) {
2054
+ if shouldStop() { throw error }
2055
+ Thread.sleep(forTimeInterval: 0.05)
2056
+ }
2057
+ }
2058
+ }
2059
+ }
2060
+
2061
+ /// Transport errors arrive wrapped in NetworkError.sessionTaskFailed; classify the underlying error.
2062
+ static func isRetryableManifestError(_ error: Error) -> Bool {
2063
+ if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
2064
+ return isRetryableManifestError(underlying)
2065
+ }
2066
+ let failure = error as NSError
2067
+ if failure.domain == manifestResumeErrorDomain {
2068
+ return true
2069
+ }
2070
+ if failure.domain == "StatusCodeError" {
2071
+ return failure.code == 408 || (500...599).contains(failure.code)
2072
+ }
2073
+ return failure.domain == NSURLErrorDomain && [
2074
+ NSURLErrorTimedOut, NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet,
2075
+ NSURLErrorCannotConnectToHost, NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed
2076
+ ].contains(failure.code)
2077
+ }
2078
+
2079
+ /// Failures that reach the server or network, as opposed to checksum, decryption or storage errors.
2080
+ private static func isManifestTransferError(_ error: Error) -> Bool {
2081
+ if error is NetworkError {
2082
+ return true
2083
+ }
2084
+ let failure = error as NSError
2085
+ return failure.domain == NSURLErrorDomain || failure.domain == "StatusCodeError" || failure.domain == manifestResumeErrorDomain ||
2086
+ (failure.domain == "ManifestDownloadError" && failure.code == 3)
2087
+ }
2088
+
2089
+ /// A resumed transfer that cannot be trusted: drop the partial and fetch the whole file on the next attempt.
2090
+ static let manifestResumeErrorDomain = "ManifestResumeError"
2091
+
2092
+ private func downloadManifestFileOnce(
2093
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2094
+ resume: ManifestResumeState
1947
2095
  ) throws {
2096
+ let downloadUrl = task.downloadUrl
2097
+ let destFilePath = task.destFilePath
2098
+ let cacheFilePath = task.cacheFilePath
2099
+ let fileHash = task.finalFileHash
2100
+ let fileName = task.fileName
2101
+ let destFileName = task.destFileName
2102
+ let isBrotli = task.isBrotli
1948
2103
  guard let url = URL(string: downloadUrl) else {
1949
2104
  throw NSError(
1950
2105
  domain: "ManifestDownloadError",
@@ -1962,7 +2117,13 @@ import UIKit
1962
2117
  }
1963
2118
 
1964
2119
  try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
1965
- let partialURL = Self.manifestPartialURL(cacheFolder: cacheFolder, hash: fileHash, fileName: fileName)
2120
+ let partialURL = Self.manifestPartialURL(cacheFolder: cacheFolder, downloadId: bundleId, hash: fileHash, fileName: fileName)
2121
+ let resumeData = resume.data
2122
+ resume.data = nil
2123
+ if resumeData != nil {
2124
+ // URLSession resumes its own interrupted transfer and returns the whole file.
2125
+ try? FileManager.default.removeItem(at: partialURL)
2126
+ }
1966
2127
  let existingBytes: Int64
1967
2128
  if FileManager.default.fileExists(atPath: partialURL.path) {
1968
2129
  existingBytes = Int64((try FileManager.default.attributesOfItem(atPath: partialURL.path)[.size] as? NSNumber)?.int64Value ?? 0)
@@ -1972,8 +2133,13 @@ import UIKit
1972
2133
  if existingBytes > 0 {
1973
2134
  request.setValue("bytes=\(existingBytes)-", forHTTPHeaderField: "Range")
1974
2135
  }
2136
+ // True while the bytes on disk come from more than one response; a bad result then earns a clean GET.
2137
+ var resumed = resumeData != nil
1975
2138
 
1976
- let result = performDownloadRequest(request, label: "downloadManifestFile \(fileName)")
2139
+ let label = "downloadManifestFile \(fileName)"
2140
+ let result = resumeData.map { performDownloadRequest(request, label: label, resumeData: $0) }
2141
+ ?? performDownloadRequest(request, label: label)
2142
+ resume.data = result.resumeData
1977
2143
  defer {
1978
2144
  if let fileURL = result.fileURL {
1979
2145
  try? FileManager.default.removeItem(at: fileURL)
@@ -1982,7 +2148,6 @@ import UIKit
1982
2148
 
1983
2149
  if result.timedOut {
1984
2150
  persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
1985
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
1986
2151
  throw NSError(
1987
2152
  domain: NSURLErrorDomain,
1988
2153
  code: NSURLErrorTimedOut,
@@ -1992,32 +2157,45 @@ import UIKit
1992
2157
 
1993
2158
  if let error = result.error {
1994
2159
  persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
1995
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
1996
2160
  self.logger.error("Manifest file download network error")
1997
2161
  self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
1998
2162
  throw error
1999
2163
  }
2000
2164
 
2001
2165
  let statusCode = result.response?.statusCode ?? 200
2166
+ var storeOffset = existingBytes
2167
+ if statusCode == 206 && existingBytes > 0 {
2168
+ switch Self.contentRangeStart(result.response?.value(forHTTPHeaderField: "Content-Range")) {
2169
+ case .some(existingBytes):
2170
+ resumed = true
2171
+ case .some(0):
2172
+ storeOffset = 0
2173
+ default:
2174
+ try? FileManager.default.removeItem(at: partialURL)
2175
+ throw NSError(
2176
+ domain: Self.manifestResumeErrorDomain,
2177
+ code: 1,
2178
+ userInfo: [NSLocalizedDescriptionKey: "Content-Range does not continue the partial for \(fileName)"]
2179
+ )
2180
+ }
2181
+ }
2002
2182
  if statusCode == 416 && existingBytes > 0 {
2003
2183
  logger.debug("Range not satisfiable, using existing partial \(partialURL.lastPathComponent)")
2184
+ resumed = true
2004
2185
  } else if statusCode < 200 || statusCode >= 300 {
2005
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2006
2186
  throw NSError(domain: "StatusCodeError", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "Failed to fetch. Status code (\(statusCode)) invalid for file \(fileName) at url \(downloadUrl)"])
2007
2187
  } else {
2008
2188
  guard let downloadedFileURL = result.fileURL, FileManager.default.fileExists(atPath: downloadedFileURL.path) else {
2009
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2010
2189
  throw NSError(
2011
2190
  domain: "ManifestDownloadError",
2012
2191
  code: 3,
2013
2192
  userInfo: [NSLocalizedDescriptionKey: "Manifest file response was empty for \(fileName) at url \(downloadUrl)"]
2014
2193
  )
2015
2194
  }
2016
- try storeDownloadedFile(downloadedFileURL, at: partialURL, existingBytes: existingBytes, response: result.response)
2195
+ try storeDownloadedFile(downloadedFileURL, at: partialURL, existingBytes: storeOffset, response: result.response)
2017
2196
  }
2018
2197
 
2019
2198
  guard FileManager.default.fileExists(atPath: partialURL.path) else {
2020
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(fileName)")
2021
2199
  throw NSError(
2022
2200
  domain: "ManifestDownloadError",
2023
2201
  code: 3,
@@ -2034,14 +2212,15 @@ import UIKit
2034
2212
 
2035
2213
  do {
2036
2214
  var source = partialURL
2037
- if !self.publicKey.isEmpty && CryptoCipher.isValidSessionKey(sessionKey) {
2215
+ if decryptionSession.isEncrypted {
2038
2216
  let work = cacheFolder.appendingPathComponent("work_\(UUID().uuidString)_\((fileName as NSString).lastPathComponent)")
2039
2217
  try FileManager.default.copyItem(at: partialURL, to: work)
2040
2218
  workURL = work
2041
2219
  do {
2042
- try CryptoCipher.decryptFile(filePath: work, publicKey: self.publicKey, sessionKey: sessionKey, version: version)
2220
+ try decryptionSession.decryptFile(filePath: work)
2043
2221
  } catch {
2044
2222
  try? FileManager.default.removeItem(at: partialURL)
2223
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2045
2224
  self.sendStats(action: "decrypt_fail", versionName: version)
2046
2225
  throw error
2047
2226
  }
@@ -2054,14 +2233,13 @@ import UIKit
2054
2233
  calculatedChecksum = try decompressBrotli(from: source, to: destFilePath, fileName: fileName)
2055
2234
  } catch {
2056
2235
  try? FileManager.default.removeItem(at: partialURL)
2236
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2057
2237
  self.sendStats(action: "download_manifest_brotli_fail", versionName: "\(version):\(destFileName)")
2058
2238
  throw error
2059
2239
  }
2060
2240
  } else {
2061
2241
  let handle = try FileHandle(forReadingFrom: source)
2062
- defer {
2063
- try? handle.close()
2064
- }
2242
+ defer { try? handle.close() }
2065
2243
  let length = (try FileManager.default.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.uint64Value ?? 0
2066
2244
  calculatedChecksum = try streamCopy(from: handle, count: length, to: destFilePath)
2067
2245
  }
@@ -2071,17 +2249,23 @@ import UIKit
2071
2249
  if calculatedChecksum != fileHash {
2072
2250
  try? FileManager.default.removeItem(at: destFilePath)
2073
2251
  try? FileManager.default.removeItem(at: partialURL)
2252
+ 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)"])
2253
+ if resumed { throw Self.resumeVerificationError(mismatch, fileName: fileName) }
2074
2254
  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)"])
2255
+ throw mismatch
2076
2256
  }
2077
2257
 
2078
2258
  if let cacheFilePath {
2079
- try copyItemAtomically(from: destFilePath, to: cacheFilePath)
2259
+ do {
2260
+ try linkOrCopyImmutableFile(from: destFilePath, to: cacheFilePath)
2261
+ } catch {
2262
+ logger.debug("Delta cache write failed: \(error.localizedDescription)")
2263
+ }
2080
2264
  }
2081
2265
  try? FileManager.default.removeItem(at: partialURL)
2082
2266
 
2083
2267
  self.logger.info("Manifest file downloaded and cached")
2084
- self.logger.debug("Bundle: \(bundleId), File: \(fileName), Brotli: \(isBrotli), Encrypted: \(!self.publicKey.isEmpty && !sessionKey.isEmpty)")
2268
+ self.logger.debug("Bundle: \(bundleId), File: \(fileName), Brotli: \(isBrotli), Encrypted: \(decryptionSession.isEncrypted)")
2085
2269
  } catch {
2086
2270
  self.logger.error("Manifest file download failed")
2087
2271
  self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
@@ -2089,6 +2273,27 @@ import UIKit
2089
2273
  }
2090
2274
  }
2091
2275
 
2276
+ /// Bad bytes after a resume earn a clean GET; local storage errors are not wrapped and stay permanent.
2277
+ private static func resumeVerificationError(_ underlying: Error, fileName: String) -> NSError {
2278
+ NSError(
2279
+ domain: manifestResumeErrorDomain,
2280
+ code: 2,
2281
+ userInfo: [NSLocalizedDescriptionKey: "Resumed transfer failed verification for \(fileName)", NSUnderlyingErrorKey: underlying]
2282
+ )
2283
+ }
2284
+
2285
+ /// Start offset of a `bytes start-end/total` Content-Range header, or nil when absent or malformed.
2286
+ static func contentRangeStart(_ header: String?) -> Int64? {
2287
+ guard let header, header.hasPrefix("bytes ") else {
2288
+ return nil
2289
+ }
2290
+ let range = header.dropFirst("bytes ".count)
2291
+ guard let dash = range.firstIndex(of: "-") else {
2292
+ return nil
2293
+ }
2294
+ return Int64(range[range.startIndex..<dash].trimmingCharacters(in: .whitespaces))
2295
+ }
2296
+
2092
2297
  /// Copy a file to the destination, replacing any existing file.
2093
2298
  private func copyItemReplacing(from source: URL, to destination: URL) throws {
2094
2299
  let fileManager = FileManager.default
@@ -2144,6 +2349,21 @@ import UIKit
2144
2349
  try replaceItemAtomically(at: destination, withItemAt: tempURL)
2145
2350
  }
2146
2351
 
2352
+ /// Only updater-owned verified bundle/cache files, which are never rewritten in place.
2353
+ func linkOrCopyImmutableFile(from source: URL, to destination: URL) throws {
2354
+ let manager = FileManager.default
2355
+ try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
2356
+ let temp = destination.deletingLastPathComponent().appendingPathComponent("capgo-link-\(UUID().uuidString).tmp")
2357
+ defer { try? manager.removeItem(at: temp) }
2358
+ do {
2359
+ try manager.linkItem(at: source.resolvingSymlinksInPath(), to: temp)
2360
+ } catch {
2361
+ try copyItemAtomically(from: source.resolvingSymlinksInPath(), to: destination)
2362
+ return
2363
+ }
2364
+ try replaceItemAtomically(at: destination, withItemAt: temp)
2365
+ }
2366
+
2147
2367
  /// One-step replace when dest exists, move when it does not. Avoids the
2148
2368
  /// fileExists/removeItem race that can fail a verified install.
2149
2369
  private func replaceItemAtomically(at destination: URL, withItemAt tempURL: URL) throws {
@@ -2169,7 +2389,7 @@ import UIKit
2169
2389
  // Hash is in the cache file name and was verified when written.
2170
2390
  // Re-hashing here would re-read every reused file on low-RAM devices.
2171
2391
  do {
2172
- try copyItemAtomically(from: source, to: destination)
2392
+ try linkOrCopyImmutableFile(from: source, to: destination)
2173
2393
  return true
2174
2394
  } catch {
2175
2395
  // File was deleted between check and copy, or other IO error - caller should download instead
@@ -2375,6 +2595,8 @@ import UIKit
2375
2595
  expectedChecksum: String?
2376
2596
  ) throws -> BundleInfo {
2377
2597
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
2598
+ try self.requireVersionNotBelowBuiltin(version)
2599
+ try self.assertAllowedScheme(url)
2378
2600
  let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2379
2601
  try self.runBeforeDownload()
2380
2602
  let id: String = self.randomString(length: 10)