@capgo/capacitor-updater 9.0.1 → 9.0.4
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.
- package/README.md +106 -81
- package/android/build.gradle +1 -3
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +521 -21
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +675 -34
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +10 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
- package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +5 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
- package/dist/docs.json +13 -13
- package/dist/esm/definitions.d.ts +57 -23
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2718 -77
- package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
- package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
- package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +259 -119
- package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
- package/package.json +2 -2
|
@@ -29,6 +29,12 @@ import UIKit
|
|
|
29
29
|
private static let emptySha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
|
30
30
|
private let deletePaceSeconds: TimeInterval = 0.075
|
|
31
31
|
private let deleteLock = NSLock()
|
|
32
|
+
/// Guards every write of the stored next bundle so a compare-and-clear cannot drop a concurrent `next(B)`.
|
|
33
|
+
private let nextBundleLock = NSRecursiveLock()
|
|
34
|
+
private static let retryAccountingLock = NSLock()
|
|
35
|
+
private let decryptFailureLock = NSLock()
|
|
36
|
+
/// Bundle IDs whose current manifest attempt hit a file decryption failure (attempt-local classification).
|
|
37
|
+
private var decryptFailedBundleIds = Set<String>()
|
|
32
38
|
|
|
33
39
|
// Add this line to declare cacheFolder
|
|
34
40
|
private let cacheFolder: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("capgo_downloads")
|
|
@@ -345,16 +351,21 @@ import UIKit
|
|
|
345
351
|
/// Runs a data task and reports `(data, response, error)` like Alamofire's `responseData` did:
|
|
346
352
|
/// `data` is nil when no bytes were received, transport errors are wrapped, and an empty body is an error
|
|
347
353
|
/// unless the status code is 204/205 (or the request is HEAD).
|
|
354
|
+
/// `completionQueue` nil runs `completion` inline on the session delegate queue (or the caller, for a scheme error).
|
|
348
355
|
@discardableResult
|
|
349
356
|
private func startDataTask(
|
|
350
357
|
_ request: URLRequest,
|
|
351
|
-
completionQueue: DispatchQueue
|
|
358
|
+
completionQueue: DispatchQueue?,
|
|
352
359
|
completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
|
|
353
360
|
) -> URLSessionDataTask {
|
|
354
361
|
if let schemeError = checkAllowedScheme(request.url) {
|
|
355
362
|
// Never resumed: the session will not call back, so the completion runs exactly once.
|
|
356
363
|
let idle = self.urlSession.dataTask(with: request) { _, _, _ in }
|
|
357
|
-
completionQueue
|
|
364
|
+
if let completionQueue {
|
|
365
|
+
completionQueue.async {
|
|
366
|
+
completion(nil, nil, schemeError)
|
|
367
|
+
}
|
|
368
|
+
} else {
|
|
358
369
|
completion(nil, nil, schemeError)
|
|
359
370
|
}
|
|
360
371
|
return idle
|
|
@@ -374,7 +385,11 @@ import UIKit
|
|
|
374
385
|
} else {
|
|
375
386
|
resultError = Self.emptyResponseError(data: body, response: httpResponse, method: request.httpMethod)
|
|
376
387
|
}
|
|
377
|
-
completionQueue
|
|
388
|
+
if let completionQueue {
|
|
389
|
+
completionQueue.async {
|
|
390
|
+
completion(body, httpResponse, resultError)
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
378
393
|
completion(body, httpResponse, resultError)
|
|
379
394
|
}
|
|
380
395
|
}
|
|
@@ -416,7 +431,43 @@ import UIKit
|
|
|
416
431
|
}
|
|
417
432
|
}
|
|
418
433
|
}
|
|
419
|
-
|
|
434
|
+
/// Result slot shared by a blocking request and its URLSession completion handler.
|
|
435
|
+
///
|
|
436
|
+
/// The completion stores the result and signals the waiter directly on the session delegate queue. Hopping
|
|
437
|
+
/// through a low-QoS queue first is a priority inversion: a semaphore does not donate the blocked caller's
|
|
438
|
+
/// priority, so under CPU pressure the hop could be starved for seconds after the bytes arrived and trip
|
|
439
|
+
/// the request timeout even though the server already answered.
|
|
440
|
+
private final class BlockingResult<Value> {
|
|
441
|
+
private let lock = NSLock()
|
|
442
|
+
private let semaphore = DispatchSemaphore(value: 0)
|
|
443
|
+
private var stored: Value?
|
|
444
|
+
|
|
445
|
+
func complete(_ value: Value) {
|
|
446
|
+
lock.lock()
|
|
447
|
+
let first = stored == nil
|
|
448
|
+
if first {
|
|
449
|
+
stored = value
|
|
450
|
+
}
|
|
451
|
+
lock.unlock()
|
|
452
|
+
if first {
|
|
453
|
+
semaphore.signal()
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/// Returns the stored value, or nil when `timeout` elapsed first.
|
|
458
|
+
func wait(timeout: TimeInterval) -> Value? {
|
|
459
|
+
guard semaphore.wait(timeout: .now() + timeout) == .success else {
|
|
460
|
+
return nil
|
|
461
|
+
}
|
|
462
|
+
lock.lock()
|
|
463
|
+
defer { lock.unlock() }
|
|
464
|
+
return stored
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
deinit {
|
|
468
|
+
// SwiftLint required_deinit; no owned resources to release.
|
|
469
|
+
}
|
|
470
|
+
}
|
|
420
471
|
|
|
421
472
|
public var notifyDownloadRaw: (String, Int, Bool, BundleInfo?) -> Void = { _, _, _, _ in }
|
|
422
473
|
public func notifyDownload(id: String, percent: Int, ignoreMultipleOfTen: Bool = false, bundle: BundleInfo? = nil) {
|
|
@@ -469,21 +520,15 @@ import UIKit
|
|
|
469
520
|
|
|
470
521
|
func performRequest(_ request: URLRequest, label: String) -> RequestResult {
|
|
471
522
|
let waitTimeout = max(self.timeout + 5, 10)
|
|
472
|
-
let
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
var requestError: Error?
|
|
476
|
-
let dataTask = self.startDataTask(request, completionQueue: self.networkResponseQueue) { data, response, error in
|
|
477
|
-
responseData = data
|
|
478
|
-
httpResponse = response
|
|
479
|
-
requestError = error
|
|
480
|
-
semaphore.signal()
|
|
523
|
+
let outcome = BlockingResult<(data: Data?, response: HTTPURLResponse?, error: Error?)>()
|
|
524
|
+
let dataTask = self.startDataTask(request, completionQueue: nil) { data, response, error in
|
|
525
|
+
outcome.complete((data, response, error))
|
|
481
526
|
}
|
|
482
527
|
|
|
483
|
-
|
|
528
|
+
guard let (responseData, httpResponse, requestError) = outcome.wait(timeout: waitTimeout) else {
|
|
484
529
|
dataTask.cancel()
|
|
485
530
|
logger.error("\(label) timed out after \(Int(waitTimeout))s")
|
|
486
|
-
return RequestResult(data:
|
|
531
|
+
return RequestResult(data: nil, response: nil, error: nil, timedOut: true)
|
|
487
532
|
}
|
|
488
533
|
|
|
489
534
|
// URLSession can report its own timeout (NSURLErrorTimedOut) before the semaphore deadline.
|
|
@@ -524,11 +569,7 @@ import UIKit
|
|
|
524
569
|
return DownloadRequestResult(fileURL: nil, response: nil, error: schemeError, timedOut: false)
|
|
525
570
|
}
|
|
526
571
|
let waitTimeout = max(self.timeout + 5, 10)
|
|
527
|
-
let
|
|
528
|
-
var tempFileURL: URL?
|
|
529
|
-
var httpResponse: HTTPURLResponse?
|
|
530
|
-
var requestError: Error?
|
|
531
|
-
var interruptedResumeData: Data?
|
|
572
|
+
let outcome = BlockingResult<DownloadRequestResult>()
|
|
532
573
|
let temporaryDownloadURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
533
574
|
let completion: (URL?, URLResponse?, Error?) -> Void = { location, response, error in
|
|
534
575
|
// URLSession deletes `location` once this handler returns, so move it synchronously here.
|
|
@@ -553,14 +594,10 @@ import UIKit
|
|
|
553
594
|
resultError = NetworkError.downloadedFileMoveFailed(error, source: location, destination: temporaryDownloadURL)
|
|
554
595
|
}
|
|
555
596
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
requestError = resultError
|
|
561
|
-
interruptedResumeData = resultResumeData
|
|
562
|
-
semaphore.signal()
|
|
563
|
-
}
|
|
597
|
+
outcome.complete(DownloadRequestResult(
|
|
598
|
+
fileURL: movedFileURL, response: response as? HTTPURLResponse, error: resultError,
|
|
599
|
+
timedOut: false, resumeData: resultResumeData
|
|
600
|
+
))
|
|
564
601
|
}
|
|
565
602
|
// Plain http keeps exactly the previous path: no HTTP/3 hint and no metrics delegate.
|
|
566
603
|
let secureDownload = Self.isHTTPS(request.url)
|
|
@@ -615,27 +652,28 @@ import UIKit
|
|
|
615
652
|
}
|
|
616
653
|
downloadTask.resume()
|
|
617
654
|
|
|
618
|
-
|
|
655
|
+
guard let completed = outcome.wait(timeout: waitTimeout) else {
|
|
619
656
|
downloadTask.cancel()
|
|
620
657
|
logger.error("\(label) timed out after \(Int(waitTimeout))s")
|
|
621
658
|
return DownloadRequestResult(
|
|
622
|
-
fileURL: existingDownloadFileURL(
|
|
623
|
-
response:
|
|
624
|
-
error:
|
|
659
|
+
fileURL: existingDownloadFileURL(nil, fallback: temporaryDownloadURL),
|
|
660
|
+
response: nil,
|
|
661
|
+
error: nil,
|
|
625
662
|
timedOut: true
|
|
626
663
|
)
|
|
627
664
|
}
|
|
628
665
|
|
|
629
|
-
|
|
666
|
+
let timedOut = isTimedOutError(completed.error)
|
|
667
|
+
if timedOut {
|
|
630
668
|
logger.error("\(label) timed out after \(Int(waitTimeout))s")
|
|
631
669
|
}
|
|
632
670
|
|
|
633
671
|
return DownloadRequestResult(
|
|
634
|
-
fileURL: existingDownloadFileURL(
|
|
635
|
-
response:
|
|
636
|
-
error:
|
|
637
|
-
timedOut:
|
|
638
|
-
resumeData:
|
|
672
|
+
fileURL: existingDownloadFileURL(completed.fileURL, fallback: temporaryDownloadURL),
|
|
673
|
+
response: completed.response,
|
|
674
|
+
error: completed.error,
|
|
675
|
+
timedOut: timedOut,
|
|
676
|
+
resumeData: completed.resumeData
|
|
639
677
|
)
|
|
640
678
|
}
|
|
641
679
|
|
|
@@ -799,22 +837,19 @@ import UIKit
|
|
|
799
837
|
_ = self.recordVersionFloorRejection(nil)
|
|
800
838
|
return
|
|
801
839
|
}
|
|
802
|
-
//
|
|
803
|
-
|
|
804
|
-
let
|
|
805
|
-
guard let parsedBundle = try? CapgoSemanticVersion(bundleCore),
|
|
806
|
-
let parsedNative = try? CapgoSemanticVersion(nativeCore) else {
|
|
840
|
+
// Only major.minor.patch matter: a prerelease bundle at the native version is not a rollback.
|
|
841
|
+
// Components are compared without an Int limit, like Android.
|
|
842
|
+
guard let order = CapgoSemanticVersion.compareNumericCore(version, self.versionBuild) else {
|
|
807
843
|
_ = self.recordVersionFloorRejection(nil)
|
|
808
844
|
logger?.debug("builtinMinimum skipped: cannot parse bundle version \(version) or native version \(self.versionBuild)")
|
|
809
845
|
return
|
|
810
846
|
}
|
|
811
|
-
|
|
812
|
-
let bundleVersion = CapgoSemanticVersion(major: parsedBundle.major, minor: parsedBundle.minor, patch: parsedBundle.patch)
|
|
813
|
-
let nativeVersion = CapgoSemanticVersion(major: parsedNative.major, minor: parsedNative.minor, patch: parsedNative.patch)
|
|
814
|
-
if bundleVersion < nativeVersion {
|
|
847
|
+
if order == .orderedAscending {
|
|
815
848
|
let message = "Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)"
|
|
816
849
|
logger?.error(message)
|
|
817
|
-
|
|
850
|
+
// Latch only a stat that will be queued, so a rejection dropped by preview or a missing stats URL
|
|
851
|
+
// is still reported once stats become available.
|
|
852
|
+
if self.canQueueStats() && self.recordVersionFloorRejection(message) {
|
|
818
853
|
self.sendStats(action: "version_below_native", versionName: version)
|
|
819
854
|
}
|
|
820
855
|
throw NSError(
|
|
@@ -826,6 +861,11 @@ import UIKit
|
|
|
826
861
|
_ = self.recordVersionFloorRejection(nil)
|
|
827
862
|
}
|
|
828
863
|
|
|
864
|
+
/// Whether `sendStats` would queue an event right now (not stopped, not previewing, stats URL set).
|
|
865
|
+
func canQueueStats() -> Bool {
|
|
866
|
+
return !statsStopped && !previewSession && !statsUrl.isEmpty
|
|
867
|
+
}
|
|
868
|
+
|
|
829
869
|
/// Records the latest rejection atomically and returns whether it needs a stat. Nil clears the last rejection.
|
|
830
870
|
private func recordVersionFloorRejection(_ message: String?) -> Bool {
|
|
831
871
|
versionFloorRejectionLock.lock()
|
|
@@ -889,6 +929,11 @@ import UIKit
|
|
|
889
929
|
* Matches Android behavior: 2x safety margin, throws "insufficient_disk_space"
|
|
890
930
|
* - Parameter estimatedSize: The estimated size of the download in bytes. Defaults to 50MB.
|
|
891
931
|
*/
|
|
932
|
+
/// 100KB per file, minimum 50MB.
|
|
933
|
+
static func manifestDiskEstimate(fileCount: Int) -> Int64 {
|
|
934
|
+
Int64(max(fileCount * 100 * 1024, 50 * 1024 * 1024))
|
|
935
|
+
}
|
|
936
|
+
|
|
892
937
|
private func checkDiskSpace(estimatedSize: Int64 = 50 * 1024 * 1024) throws {
|
|
893
938
|
let fileManager = FileManager.default
|
|
894
939
|
guard let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
|
|
@@ -1942,6 +1987,27 @@ import UIKit
|
|
|
1942
1987
|
}
|
|
1943
1988
|
|
|
1944
1989
|
public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
|
|
1990
|
+
return try self.downloadManifestWithTransferHook(
|
|
1991
|
+
manifest: manifest,
|
|
1992
|
+
version: version,
|
|
1993
|
+
sessionKey: sessionKey,
|
|
1994
|
+
link: link,
|
|
1995
|
+
comment: comment,
|
|
1996
|
+
beforeTransfer: nil
|
|
1997
|
+
)
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
/// `beforeTransfer` runs once every admission check and entry validation has passed, right before the first
|
|
2001
|
+
/// file operation is submitted; throwing from it aborts the attempt without starting a transfer.
|
|
2002
|
+
/// A distinct name (not an overload) keeps bare references to `downloadManifest` unambiguous.
|
|
2003
|
+
public func downloadManifestWithTransferHook(
|
|
2004
|
+
manifest: [ManifestEntry],
|
|
2005
|
+
version: String,
|
|
2006
|
+
sessionKey: String,
|
|
2007
|
+
link: String?,
|
|
2008
|
+
comment: String?,
|
|
2009
|
+
beforeTransfer: (() throws -> Void)?
|
|
2010
|
+
) throws -> BundleInfo {
|
|
1945
2011
|
let id = self.randomString(length: 10)
|
|
1946
2012
|
let totalFiles = manifest.count
|
|
1947
2013
|
|
|
@@ -1950,6 +2016,10 @@ import UIKit
|
|
|
1950
2016
|
var completedFiles = 0
|
|
1951
2017
|
var lastProgressPercent = -1
|
|
1952
2018
|
let hasError = AtomicBool(initialValue: false)
|
|
2019
|
+
let hasChecksumError = AtomicBool(initialValue: false)
|
|
2020
|
+
// Classify this attempt on its own: a block left by an earlier (or concurrent) attempt must not turn a
|
|
2021
|
+
// connection loss into an integrity failure. File decryption failures are recorded per bundle ID.
|
|
2022
|
+
self.takeDecryptFailure(bundleId: id)
|
|
1953
2023
|
var downloadError: Error?
|
|
1954
2024
|
var firstFile: String?
|
|
1955
2025
|
var failedFiles = 0
|
|
@@ -2003,8 +2073,7 @@ import UIKit
|
|
|
2003
2073
|
destFolder = try self.getBundleDirectory(id: id)
|
|
2004
2074
|
|
|
2005
2075
|
// Check disk space before starting manifest download (estimate 100KB per file, minimum 50MB)
|
|
2006
|
-
|
|
2007
|
-
try checkDiskSpace(estimatedSize: estimatedSize)
|
|
2076
|
+
try checkDiskSpace(estimatedSize: Self.manifestDiskEstimate(fileCount: manifest.count))
|
|
2008
2077
|
|
|
2009
2078
|
try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
|
|
2010
2079
|
cleanupOldManifestPartials()
|
|
@@ -2013,7 +2082,6 @@ import UIKit
|
|
|
2013
2082
|
reportFailure(error)
|
|
2014
2083
|
throw error
|
|
2015
2084
|
}
|
|
2016
|
-
|
|
2017
2085
|
// Create and save BundleInfo before starting the download process
|
|
2018
2086
|
let bundleInfo = BundleInfo(id: id, version: version, status: BundleStatus.DOWNLOADING, downloaded: Date(), checksum: "", link: link, comment: comment)
|
|
2019
2087
|
self.saveBundleInfo(id: id, bundle: bundleInfo)
|
|
@@ -2144,14 +2212,19 @@ import UIKit
|
|
|
2144
2212
|
userInfo: [NSLocalizedDescriptionKey: "Manifest download failed due to invalid or missing entries"]
|
|
2145
2213
|
)
|
|
2146
2214
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
2215
|
+
// Invalid entries (bad path, undecryptable checksum) fail before any transfer: an artifact
|
|
2216
|
+
// problem, not an interruption, so it uses the integrity retry budget.
|
|
2217
|
+
self.markIntegrityBlockedVersion(version: version)
|
|
2218
|
+
// An automatic replacement of an invalid manifest still spends a retry slot (a refusal at the cap ends
|
|
2219
|
+
// the same way), so repeated invalid offers of this version stay bounded by the retry budget.
|
|
2220
|
+
try? beforeTransfer?()
|
|
2147
2221
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
2148
2222
|
removePartialManifestBundleDirectory(destFolder)
|
|
2149
2223
|
reportFailure(resolvedError)
|
|
2150
2224
|
throw resolvedError
|
|
2151
2225
|
}
|
|
2152
2226
|
|
|
2153
|
-
|
|
2154
|
-
|
|
2227
|
+
// Prepare every parent directory first: a failure here submits no file operation and charges no retry.
|
|
2155
2228
|
for task in tasks {
|
|
2156
2229
|
do {
|
|
2157
2230
|
try FileManager.default.createDirectory(
|
|
@@ -2161,6 +2234,7 @@ import UIKit
|
|
|
2161
2234
|
)
|
|
2162
2235
|
} catch {
|
|
2163
2236
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
2237
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2164
2238
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
2165
2239
|
removePartialManifestBundleDirectory(destFolder)
|
|
2166
2240
|
self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
|
|
@@ -2168,7 +2242,21 @@ import UIKit
|
|
|
2168
2242
|
reportFailure(error)
|
|
2169
2243
|
throw error
|
|
2170
2244
|
}
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
// Every entry is valid and the destination is prepared: admit the transfer (an automatic retry is charged
|
|
2248
|
+
// here), right before the first file operation. A refusal leaves no record behind and starts no operation.
|
|
2249
|
+
do {
|
|
2250
|
+
try beforeTransfer?()
|
|
2251
|
+
} catch {
|
|
2252
|
+
self.saveBundleInfo(id: id, bundle: nil)
|
|
2253
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
2254
|
+
throw error
|
|
2255
|
+
}
|
|
2171
2256
|
|
|
2257
|
+
var operations: [Operation] = []
|
|
2258
|
+
|
|
2259
|
+
for task in tasks {
|
|
2172
2260
|
let operation = BlockOperation { [weak self] in
|
|
2173
2261
|
guard let self = self else { return }
|
|
2174
2262
|
guard !hasError.value else { return } // Skip if error already occurred
|
|
@@ -2207,6 +2295,13 @@ import UIKit
|
|
|
2207
2295
|
errorLock.lock()
|
|
2208
2296
|
failureStage = "process_file"
|
|
2209
2297
|
failedFiles += 1
|
|
2298
|
+
let nsError = error as NSError
|
|
2299
|
+
// A rejected resume wraps its checksum error: it discarded resumed bytes, which is not a fresh
|
|
2300
|
+
// response failing verification, so it must not set the version integrity block.
|
|
2301
|
+
if nsError.domain != Self.manifestResumeErrorDomain && (nsError.domain == "ChecksumError" ||
|
|
2302
|
+
(nsError.userInfo[NSUnderlyingErrorKey] as? NSError)?.domain == "ChecksumError") {
|
|
2303
|
+
hasChecksumError.value = true
|
|
2304
|
+
}
|
|
2210
2305
|
if downloadError == nil {
|
|
2211
2306
|
downloadError = error
|
|
2212
2307
|
firstFile = task.fileName
|
|
@@ -2232,6 +2327,15 @@ import UIKit
|
|
|
2232
2327
|
)
|
|
2233
2328
|
// Update bundle status to ERROR if download failed
|
|
2234
2329
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
2330
|
+
let decryptFailed = self.takeDecryptFailure(bundleId: id)
|
|
2331
|
+
let checksumFailure = hasChecksumError.value
|
|
2332
|
+
|| (resolvedError as NSError).domain == "ChecksumError"
|
|
2333
|
+
|| decryptFailed
|
|
2334
|
+
if checksumFailure {
|
|
2335
|
+
self.markIntegrityBlockedVersion(version: version)
|
|
2336
|
+
} else {
|
|
2337
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2338
|
+
}
|
|
2235
2339
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
2236
2340
|
removePartialManifestBundleDirectory(destFolder)
|
|
2237
2341
|
reportFailure(resolvedError)
|
|
@@ -2248,6 +2352,7 @@ import UIKit
|
|
|
2248
2352
|
oldVersionName: "", metadata: ["attempt_id": id]
|
|
2249
2353
|
)
|
|
2250
2354
|
|
|
2355
|
+
self.takeDecryptFailure(bundleId: id)
|
|
2251
2356
|
self.notifyDownload(id: id, percent: 100, bundle: updatedBundle)
|
|
2252
2357
|
logger.info("downloadManifest done \(id)")
|
|
2253
2358
|
return updatedBundle
|
|
@@ -2439,6 +2544,9 @@ import UIKit
|
|
|
2439
2544
|
} else {
|
|
2440
2545
|
self.sendStats(action: "decrypt_fail", versionName: version)
|
|
2441
2546
|
}
|
|
2547
|
+
// A fresh file that cannot be decrypted is an integrity failure, not an interruption.
|
|
2548
|
+
self.markIntegrityBlockedVersion(version: version)
|
|
2549
|
+
self.recordDecryptFailure(bundleId: bundleId)
|
|
2442
2550
|
throw error
|
|
2443
2551
|
}
|
|
2444
2552
|
source = work
|
|
@@ -2810,7 +2918,38 @@ import UIKit
|
|
|
2810
2918
|
link: String? = nil,
|
|
2811
2919
|
comment: String? = nil
|
|
2812
2920
|
) throws -> BundleInfo {
|
|
2813
|
-
return try self.
|
|
2921
|
+
return try self.downloadVerifiedWithTransferHook(
|
|
2922
|
+
url: url,
|
|
2923
|
+
version: version,
|
|
2924
|
+
sessionKey: sessionKey,
|
|
2925
|
+
expectedChecksum: expectedChecksum,
|
|
2926
|
+
link: link,
|
|
2927
|
+
comment: comment,
|
|
2928
|
+
beforeTransfer: nil
|
|
2929
|
+
)
|
|
2930
|
+
}
|
|
2931
|
+
|
|
2932
|
+
/// `beforeTransfer` runs once every admission check has passed, right before the ZIP is requested;
|
|
2933
|
+
/// throwing from it aborts the attempt without starting a transfer.
|
|
2934
|
+
/// A distinct name (not an overload) keeps bare references to `downloadVerified` unambiguous.
|
|
2935
|
+
public func downloadVerifiedWithTransferHook(
|
|
2936
|
+
url: URL,
|
|
2937
|
+
version: String,
|
|
2938
|
+
sessionKey: String,
|
|
2939
|
+
expectedChecksum: String,
|
|
2940
|
+
link: String?,
|
|
2941
|
+
comment: String?,
|
|
2942
|
+
beforeTransfer: (() throws -> Void)?
|
|
2943
|
+
) throws -> BundleInfo {
|
|
2944
|
+
return try self.downloadZip(
|
|
2945
|
+
url: url,
|
|
2946
|
+
version: version,
|
|
2947
|
+
sessionKey: sessionKey,
|
|
2948
|
+
link: link,
|
|
2949
|
+
comment: comment,
|
|
2950
|
+
expectedChecksum: expectedChecksum,
|
|
2951
|
+
beforeTransfer: beforeTransfer
|
|
2952
|
+
)
|
|
2814
2953
|
}
|
|
2815
2954
|
|
|
2816
2955
|
/// Downloads, verifies, and extracts a zip bundle while emitting progress from 0% to 100%.
|
|
@@ -2820,11 +2959,21 @@ import UIKit
|
|
|
2820
2959
|
sessionKey: String,
|
|
2821
2960
|
link: String?,
|
|
2822
2961
|
comment: String?,
|
|
2823
|
-
expectedChecksum: String
|
|
2962
|
+
expectedChecksum: String?,
|
|
2963
|
+
beforeTransfer: (() throws -> Void)? = nil
|
|
2824
2964
|
) throws -> BundleInfo {
|
|
2825
2965
|
try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
|
|
2826
2966
|
try self.requireVersionNotBelowBuiltin(version)
|
|
2827
2967
|
try self.assertAllowedScheme(url)
|
|
2968
|
+
if expectedChecksum == nil && !self.publicKey.isEmpty && CryptoCipher.isValidSessionKey(sessionKey) {
|
|
2969
|
+
// Decrypting needs the signed ciphertext checksum: fail before any download state or network I/O.
|
|
2970
|
+
logger.error("Encrypted bundle download needs its signed checksum, use downloadVerified")
|
|
2971
|
+
throw NSError(
|
|
2972
|
+
domain: "ChecksumError",
|
|
2973
|
+
code: 2,
|
|
2974
|
+
userInfo: [NSLocalizedDescriptionKey: "Checksum required: download encrypted bundles with downloadVerified"]
|
|
2975
|
+
)
|
|
2976
|
+
}
|
|
2828
2977
|
let expectedChecksums = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
|
|
2829
2978
|
let expectedHash = expectedChecksums?.plain
|
|
2830
2979
|
try self.runBeforeDownload()
|
|
@@ -2838,6 +2987,12 @@ import UIKit
|
|
|
2838
2987
|
|
|
2839
2988
|
// Check disk space before starting download (matches Android behavior)
|
|
2840
2989
|
try checkDiskSpace()
|
|
2990
|
+
do {
|
|
2991
|
+
try beforeTransfer?()
|
|
2992
|
+
} catch {
|
|
2993
|
+
cleanDownloadData(for: id)
|
|
2994
|
+
throw error
|
|
2995
|
+
}
|
|
2841
2996
|
|
|
2842
2997
|
var checksum = ""
|
|
2843
2998
|
var lastSentProgress = 0
|
|
@@ -2859,6 +3014,7 @@ import UIKit
|
|
|
2859
3014
|
var mainError: NSError?
|
|
2860
3015
|
|
|
2861
3016
|
guard var request = createRequest(url: url, method: "GET") else {
|
|
3017
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2862
3018
|
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2863
3019
|
throw NSError(
|
|
2864
3020
|
domain: "DownloadError",
|
|
@@ -2935,6 +3091,7 @@ import UIKit
|
|
|
2935
3091
|
if mainError != nil {
|
|
2936
3092
|
logger.error("Failed to download bundle")
|
|
2937
3093
|
logger.debug("Error: \(String(describing: mainError))")
|
|
3094
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2938
3095
|
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2939
3096
|
throw mainError!
|
|
2940
3097
|
}
|
|
@@ -2949,13 +3106,33 @@ import UIKit
|
|
|
2949
3106
|
version: version,
|
|
2950
3107
|
expectedCiphertextSha256: expectedChecksums?.ciphertext
|
|
2951
3108
|
)
|
|
2952
|
-
try FileManager.default.moveItem(at: tempPath, to: finalPath)
|
|
2953
3109
|
} catch {
|
|
3110
|
+
let ciphertextMismatch: Bool
|
|
2954
3111
|
if case CryptoCipher.CiphertextChecksumError.mismatch = error {
|
|
3112
|
+
ciphertextMismatch = true
|
|
2955
3113
|
self.sendStats(action: "checksum_fail", versionName: version)
|
|
3114
|
+
} else {
|
|
3115
|
+
ciphertextMismatch = false
|
|
2956
3116
|
}
|
|
2957
3117
|
logger.error("Failed to decrypt file")
|
|
2958
3118
|
logger.debug("Error: \(error)")
|
|
3119
|
+
self.markIntegrityBlockedVersion(version: version)
|
|
3120
|
+
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
3121
|
+
cleanDownloadData(for: id)
|
|
3122
|
+
// Callers see the same checksum error whether the encrypted or the decrypted bytes mismatch.
|
|
3123
|
+
if ciphertextMismatch {
|
|
3124
|
+
// Drop the ERROR record like the plaintext mismatch does, so the next update check downloads it again.
|
|
3125
|
+
_ = self.delete(id: id)
|
|
3126
|
+
throw ObjectSavableError.checksum
|
|
3127
|
+
}
|
|
3128
|
+
throw error
|
|
3129
|
+
}
|
|
3130
|
+
do {
|
|
3131
|
+
try FileManager.default.moveItem(at: tempPath, to: finalPath)
|
|
3132
|
+
} catch {
|
|
3133
|
+
logger.error("Failed to move downloaded file")
|
|
3134
|
+
logger.debug("Error: \(error)")
|
|
3135
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2959
3136
|
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2960
3137
|
cleanDownloadData(for: id)
|
|
2961
3138
|
throw error
|
|
@@ -2968,6 +3145,7 @@ import UIKit
|
|
|
2968
3145
|
logger.error("Checksum mismatch, bundle rejected before extraction")
|
|
2969
3146
|
CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedHash)
|
|
2970
3147
|
self.sendStats(action: "checksum_fail", versionName: version)
|
|
3148
|
+
self.markIntegrityBlockedVersion(version: version)
|
|
2971
3149
|
try? FileManager.default.removeItem(at: finalPath)
|
|
2972
3150
|
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2973
3151
|
cleanDownloadData(for: id)
|
|
@@ -2984,6 +3162,7 @@ import UIKit
|
|
|
2984
3162
|
} catch {
|
|
2985
3163
|
logger.error("Failed to unzip file")
|
|
2986
3164
|
logger.debug("Error: \(error)")
|
|
3165
|
+
self.markInterruptedDownloadBundle(bundleId: id)
|
|
2987
3166
|
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2988
3167
|
// Best-effort cleanup of the decrypted zip file when unzip fails
|
|
2989
3168
|
do {
|
|
@@ -3521,12 +3700,14 @@ import UIKit
|
|
|
3521
3700
|
|
|
3522
3701
|
self.setCurrentBundle(bundle: currentBundlePath)
|
|
3523
3702
|
UserDefaults.standard.set(fallbackBundleId, forKey: self.FALLBACK_VERSION)
|
|
3703
|
+
nextBundleLock.lock()
|
|
3524
3704
|
if let nextBundleId = state.nextBundleId, !nextBundleId.isEmpty {
|
|
3525
3705
|
UserDefaults.standard.set(nextBundleId, forKey: self.NEXT_VERSION)
|
|
3526
3706
|
} else {
|
|
3527
3707
|
UserDefaults.standard.removeObject(forKey: self.NEXT_VERSION)
|
|
3528
3708
|
}
|
|
3529
3709
|
UserDefaults.standard.synchronize()
|
|
3710
|
+
nextBundleLock.unlock()
|
|
3530
3711
|
}
|
|
3531
3712
|
|
|
3532
3713
|
func prepareResetStateForTransition() {
|
|
@@ -3535,12 +3716,279 @@ import UIKit
|
|
|
3535
3716
|
_ = self.setNextBundle(next: Optional<String>.none)
|
|
3536
3717
|
}
|
|
3537
3718
|
|
|
3719
|
+
/// Startup floor fallback: an internal reset to builtin that keeps a distinct queued update pending,
|
|
3720
|
+
/// because activating that update runs its own floor check.
|
|
3721
|
+
func resetRejectedStartupBundle() {
|
|
3722
|
+
self.clearNextBundleIfCurrent()
|
|
3723
|
+
self.setCurrentBundle(bundle: "")
|
|
3724
|
+
self.setFallbackBundle(fallback: Optional<BundleInfo>.none)
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3538
3727
|
func finalizeResetTransition(previousBundleName: String, isInternal: Bool) {
|
|
3539
3728
|
if !isInternal {
|
|
3540
3729
|
self.sendStats(action: "reset", versionName: self.getCurrentBundle().getVersionName(), oldVersionName: previousBundleName)
|
|
3541
3730
|
}
|
|
3542
3731
|
}
|
|
3543
3732
|
|
|
3733
|
+
/// Retries for interrupted downloads only. Checksum/signature blocks use `markIntegrityBlockedVersion(version:)`.
|
|
3734
|
+
public static let maxIncompleteDownloadRetries = 3
|
|
3735
|
+
private let incompleteRetryCountPrefix = "capgo_incomplete_retry_count_"
|
|
3736
|
+
private let incompleteFailReportedPrefix = "capgo_incomplete_fail_reported_"
|
|
3737
|
+
private let integrityBlockedVersionPrefix = "capgo_integrity_blocked_version_"
|
|
3738
|
+
private let interruptedDownloadBundlePrefix = "capgo_interrupted_download_bundle_"
|
|
3739
|
+
private let incompleteRetryReservationPrefix = "capgo_incomplete_retry_reserved_"
|
|
3740
|
+
|
|
3741
|
+
func incompleteDownloadRetryCount(version: String) -> Int {
|
|
3742
|
+
guard !version.isEmpty else {
|
|
3743
|
+
return 0
|
|
3744
|
+
}
|
|
3745
|
+
return max(0, UserDefaults.standard.integer(forKey: incompleteRetryCountPrefix + self.retryScopedVersion(version)))
|
|
3746
|
+
}
|
|
3747
|
+
|
|
3748
|
+
func incrementIncompleteDownloadRetryCount(version: String) {
|
|
3749
|
+
guard !version.isEmpty else {
|
|
3750
|
+
return
|
|
3751
|
+
}
|
|
3752
|
+
let next = self.incompleteDownloadRetryCount(version: version) + 1
|
|
3753
|
+
UserDefaults.standard.set(next, forKey: incompleteRetryCountPrefix + self.retryScopedVersion(version))
|
|
3754
|
+
UserDefaults.standard.synchronize()
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
func resetIncompleteDownloadRetryCount(version: String) {
|
|
3758
|
+
guard !version.isEmpty else {
|
|
3759
|
+
return
|
|
3760
|
+
}
|
|
3761
|
+
UserDefaults.standard.removeObject(forKey: incompleteRetryCountPrefix + self.retryScopedVersion(version))
|
|
3762
|
+
UserDefaults.standard.removeObject(forKey: incompleteRetryReservationPrefix + self.retryScopedVersion(version))
|
|
3763
|
+
UserDefaults.standard.removeObject(forKey: self.integrityBlockedVersionKey(version: version))
|
|
3764
|
+
UserDefaults.standard.synchronize()
|
|
3765
|
+
}
|
|
3766
|
+
|
|
3767
|
+
/// Persist that the next download of `version` replaces a failed or interrupted attempt, before the old
|
|
3768
|
+
/// record is deleted, so process death between the delete and the download start cannot skip the charge.
|
|
3769
|
+
func reserveIncompleteDownloadRetry(version: String) {
|
|
3770
|
+
guard !version.isEmpty else {
|
|
3771
|
+
return
|
|
3772
|
+
}
|
|
3773
|
+
UserDefaults.standard.set(true, forKey: incompleteRetryReservationPrefix + self.retryScopedVersion(version))
|
|
3774
|
+
UserDefaults.standard.synchronize()
|
|
3775
|
+
}
|
|
3776
|
+
|
|
3777
|
+
func hasIncompleteDownloadRetryReservation(version: String) -> Bool {
|
|
3778
|
+
!version.isEmpty && UserDefaults.standard.bool(forKey: incompleteRetryReservationPrefix + self.retryScopedVersion(version))
|
|
3779
|
+
}
|
|
3780
|
+
|
|
3781
|
+
/// Charge one retry slot right before a replacement download starts and consume the reservation.
|
|
3782
|
+
/// Downloads on iOS run synchronously, so a started attempt keeps its charge even if it throws.
|
|
3783
|
+
/// The cap check and the charge are atomic: returns false (refused, nothing charged) once the cap is reached.
|
|
3784
|
+
@discardableResult
|
|
3785
|
+
func chargeIncompleteDownloadRetry(version: String, admittedRetry: Bool) -> Bool {
|
|
3786
|
+
CapgoUpdater.retryAccountingLock.lock()
|
|
3787
|
+
defer { CapgoUpdater.retryAccountingLock.unlock() }
|
|
3788
|
+
guard !version.isEmpty else {
|
|
3789
|
+
return true
|
|
3790
|
+
}
|
|
3791
|
+
// Derive the preview/production scope once so the read, the write and the reservation use one key.
|
|
3792
|
+
let scoped = self.retryScopedVersion(version)
|
|
3793
|
+
let countKey = incompleteRetryCountPrefix + scoped
|
|
3794
|
+
let reservationKey = incompleteRetryReservationPrefix + scoped
|
|
3795
|
+
guard admittedRetry || UserDefaults.standard.bool(forKey: reservationKey) else {
|
|
3796
|
+
return true
|
|
3797
|
+
}
|
|
3798
|
+
let count = UserDefaults.standard.integer(forKey: countKey)
|
|
3799
|
+
if count >= CapgoUpdater.maxIncompleteDownloadRetries {
|
|
3800
|
+
return false
|
|
3801
|
+
}
|
|
3802
|
+
UserDefaults.standard.set(count + 1, forKey: countKey)
|
|
3803
|
+
UserDefaults.standard.removeObject(forKey: reservationKey)
|
|
3804
|
+
UserDefaults.standard.synchronize()
|
|
3805
|
+
return true
|
|
3806
|
+
}
|
|
3807
|
+
|
|
3808
|
+
/// A transfer-start hook that refuses the download because the retry cap is already reached.
|
|
3809
|
+
struct IncompleteRetryRefusedError: Error {}
|
|
3810
|
+
|
|
3811
|
+
/// The slot owner could not delete an incomplete stored record before replacing it.
|
|
3812
|
+
struct IncompleteBundleDeletionPendingError: Error {}
|
|
3813
|
+
|
|
3814
|
+
/// Preview sessions keep their own retry budget and reservation (same scope as the integrity block).
|
|
3815
|
+
private func retryScopedVersion(_ version: String) -> String {
|
|
3816
|
+
(self.previewSession ? "preview:" : "") + version
|
|
3817
|
+
}
|
|
3818
|
+
|
|
3819
|
+
private func integrityBlockedVersionKey(version: String) -> String {
|
|
3820
|
+
let scope = self.previewSession ? "preview:" : ""
|
|
3821
|
+
return integrityBlockedVersionPrefix + scope + version
|
|
3822
|
+
}
|
|
3823
|
+
|
|
3824
|
+
func markIntegrityBlockedVersion(version: String) {
|
|
3825
|
+
guard !version.isEmpty else {
|
|
3826
|
+
return
|
|
3827
|
+
}
|
|
3828
|
+
UserDefaults.standard.set(true, forKey: self.integrityBlockedVersionKey(version: version))
|
|
3829
|
+
UserDefaults.standard.synchronize()
|
|
3830
|
+
}
|
|
3831
|
+
|
|
3832
|
+
func isIntegrityBlockedVersion(version: String) -> Bool {
|
|
3833
|
+
!version.isEmpty && UserDefaults.standard.bool(forKey: self.integrityBlockedVersionKey(version: version))
|
|
3834
|
+
}
|
|
3835
|
+
|
|
3836
|
+
func markInterruptedDownloadBundle(bundleId: String) {
|
|
3837
|
+
guard !bundleId.isEmpty else {
|
|
3838
|
+
return
|
|
3839
|
+
}
|
|
3840
|
+
UserDefaults.standard.set(true, forKey: interruptedDownloadBundlePrefix + bundleId)
|
|
3841
|
+
UserDefaults.standard.synchronize()
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3844
|
+
func isInterruptedDownloadBundle(bundleId: String) -> Bool {
|
|
3845
|
+
!bundleId.isEmpty && UserDefaults.standard.bool(forKey: interruptedDownloadBundlePrefix + bundleId)
|
|
3846
|
+
}
|
|
3847
|
+
|
|
3848
|
+
func clearInterruptedDownloadBundle(bundleId: String) {
|
|
3849
|
+
guard !bundleId.isEmpty else {
|
|
3850
|
+
return
|
|
3851
|
+
}
|
|
3852
|
+
UserDefaults.standard.removeObject(forKey: interruptedDownloadBundlePrefix + bundleId)
|
|
3853
|
+
UserDefaults.standard.synchronize()
|
|
3854
|
+
}
|
|
3855
|
+
|
|
3856
|
+
static func shouldRetryDownloadForExistingBundle(
|
|
3857
|
+
_ bundle: BundleInfo,
|
|
3858
|
+
bundleOnDisk: Bool,
|
|
3859
|
+
incompleteRetryCount: Int,
|
|
3860
|
+
integrityBlocked: Bool,
|
|
3861
|
+
interruptedDownloadFailure: Bool,
|
|
3862
|
+
isCurrentBundle: Bool,
|
|
3863
|
+
isQueuedNext: Bool
|
|
3864
|
+
) -> Bool {
|
|
3865
|
+
if incompleteRetryCount >= CapgoUpdater.maxIncompleteDownloadRetries {
|
|
3866
|
+
return false
|
|
3867
|
+
}
|
|
3868
|
+
// An integrity block (left by an earlier attempt) stops on-disk rows from being reused, but a later attempt
|
|
3869
|
+
// that was interrupted is still a retry candidate: its files are deleted and the replacement is verified again.
|
|
3870
|
+
if integrityBlocked, !(bundle.isErrorStatus() && (!bundleOnDisk || interruptedDownloadFailure)) {
|
|
3871
|
+
return false
|
|
3872
|
+
}
|
|
3873
|
+
if bundle.isDeleted() || bundle.isDeleting() || bundle.isDownloading() {
|
|
3874
|
+
return incompleteRetryCount < CapgoUpdater.maxIncompleteDownloadRetries
|
|
3875
|
+
}
|
|
3876
|
+
if bundle.isErrorStatus() {
|
|
3877
|
+
if !bundleOnDisk {
|
|
3878
|
+
return incompleteRetryCount < CapgoUpdater.maxIncompleteDownloadRetries
|
|
3879
|
+
}
|
|
3880
|
+
return interruptedDownloadFailure
|
|
3881
|
+
}
|
|
3882
|
+
if bundle.getStatus() == BundleStatus.SUCCESS.storedValue {
|
|
3883
|
+
if isCurrentBundle || bundleOnDisk {
|
|
3884
|
+
return false
|
|
3885
|
+
}
|
|
3886
|
+
return incompleteRetryCount < CapgoUpdater.maxIncompleteDownloadRetries
|
|
3887
|
+
}
|
|
3888
|
+
if bundle.getStatus() == BundleStatus.PENDING.storedValue {
|
|
3889
|
+
if bundleOnDisk {
|
|
3890
|
+
return false
|
|
3891
|
+
}
|
|
3892
|
+
return true
|
|
3893
|
+
}
|
|
3894
|
+
return false
|
|
3895
|
+
}
|
|
3896
|
+
|
|
3897
|
+
private func recordDecryptFailure(bundleId: String) {
|
|
3898
|
+
decryptFailureLock.lock()
|
|
3899
|
+
decryptFailedBundleIds.insert(bundleId)
|
|
3900
|
+
decryptFailureLock.unlock()
|
|
3901
|
+
}
|
|
3902
|
+
|
|
3903
|
+
@discardableResult
|
|
3904
|
+
private func takeDecryptFailure(bundleId: String) -> Bool {
|
|
3905
|
+
decryptFailureLock.lock()
|
|
3906
|
+
defer { decryptFailureLock.unlock() }
|
|
3907
|
+
return decryptFailedBundleIds.remove(bundleId) != nil
|
|
3908
|
+
}
|
|
3909
|
+
|
|
3910
|
+
func isBundleOnDisk(id: String) -> Bool {
|
|
3911
|
+
self.bundleExists(id: id)
|
|
3912
|
+
}
|
|
3913
|
+
|
|
3914
|
+
/// Interrupted `downloading` records (e.g. process kill) emit `download_fail` once on the next launch, then move to `error`.
|
|
3915
|
+
func reconcileInterruptedDownloadsOnLaunch() {
|
|
3916
|
+
for info in self.list(raw: true) {
|
|
3917
|
+
if info.isBuiltin() || info.getId().isEmpty {
|
|
3918
|
+
continue
|
|
3919
|
+
}
|
|
3920
|
+
if info.getId() == self.getCurrentBundleId() {
|
|
3921
|
+
continue
|
|
3922
|
+
}
|
|
3923
|
+
let version = info.getVersionName()
|
|
3924
|
+
if info.isErrorStatus() {
|
|
3925
|
+
// Recoverable capped cleanup: a previous launch may have died after the ERROR write, or failed to
|
|
3926
|
+
// remove the files. Retry on every launch until they are gone.
|
|
3927
|
+
self.deleteLock.lock()
|
|
3928
|
+
if self.getBundleInfo(id: info.getId()).isErrorStatus() {
|
|
3929
|
+
self.removeCappedInterruptedBundleFilesLocked(id: info.getId(), version: version)
|
|
3930
|
+
}
|
|
3931
|
+
self.deleteLock.unlock()
|
|
3932
|
+
continue
|
|
3933
|
+
}
|
|
3934
|
+
if !info.isDownloading() {
|
|
3935
|
+
continue
|
|
3936
|
+
}
|
|
3937
|
+
let reportedKey = incompleteFailReportedPrefix + info.getId()
|
|
3938
|
+
// Claim the row under deleteLock so a concurrent delete/replacement cannot interleave between the
|
|
3939
|
+
// reread and the ERROR write. The stat is sent outside the lock.
|
|
3940
|
+
var shouldReport = false
|
|
3941
|
+
self.deleteLock.lock()
|
|
3942
|
+
let currentInfo = self.getBundleInfo(id: info.getId())
|
|
3943
|
+
if !currentInfo.isDeleted() && !currentInfo.isDeleting() && currentInfo.isDownloading() {
|
|
3944
|
+
self.markInterruptedDownloadBundle(bundleId: info.getId())
|
|
3945
|
+
_ = self.saveBundleInfo(id: info.getId(), bundle: currentInfo.setStatus(status: BundleStatus.ERROR.storedValue))
|
|
3946
|
+
// The decrypted ZIP renamed to Documents/<id> before extraction is not covered by cleanDownloadData,
|
|
3947
|
+
// and no later attempt reuses this id: drop it for every stale attempt.
|
|
3948
|
+
let renamedZip = tempDataPath(for: info.getId()).deletingLastPathComponent().appendingPathComponent(info.getId())
|
|
3949
|
+
let partialDir = try? self.getBundleDirectory(id: info.getId())
|
|
3950
|
+
if FileManager.default.fileExists(atPath: renamedZip.path), renamedZip.path != partialDir?.path {
|
|
3951
|
+
try? FileManager.default.removeItem(at: renamedZip)
|
|
3952
|
+
}
|
|
3953
|
+
self.removeCappedInterruptedBundleFilesLocked(id: info.getId(), version: version)
|
|
3954
|
+
if !UserDefaults.standard.bool(forKey: reportedKey) {
|
|
3955
|
+
UserDefaults.standard.set(true, forKey: reportedKey)
|
|
3956
|
+
UserDefaults.standard.synchronize()
|
|
3957
|
+
shouldReport = true
|
|
3958
|
+
}
|
|
3959
|
+
}
|
|
3960
|
+
self.deleteLock.unlock()
|
|
3961
|
+
if shouldReport {
|
|
3962
|
+
self.sendStats(action: "download_fail", versionName: version)
|
|
3963
|
+
}
|
|
3964
|
+
}
|
|
3965
|
+
}
|
|
3966
|
+
|
|
3967
|
+
/// No retry will replace a capped interrupted bundle, and cleanup protects every non-deleted record: drop its
|
|
3968
|
+
/// partial files. The record and interruption marker stay for retry accounting. Caller holds `deleteLock`.
|
|
3969
|
+
private func removeCappedInterruptedBundleFilesLocked(id: String, version: String) {
|
|
3970
|
+
guard self.isInterruptedDownloadBundle(bundleId: id),
|
|
3971
|
+
self.incompleteDownloadRetryCount(version: version) >= CapgoUpdater.maxIncompleteDownloadRetries,
|
|
3972
|
+
let partialDir = try? self.getBundleDirectory(id: id) else {
|
|
3973
|
+
return
|
|
3974
|
+
}
|
|
3975
|
+
removePartialManifestBundleDirectory(partialDir)
|
|
3976
|
+
cleanDownloadData(for: id)
|
|
3977
|
+
self.removeManifestPartials(ownedBy: id)
|
|
3978
|
+
}
|
|
3979
|
+
|
|
3980
|
+
/// Removes manifest partial files owned by one download ID (see `manifestPartialURL`). Verified cache files
|
|
3981
|
+
/// and partials owned by other downloads are kept.
|
|
3982
|
+
private func removeManifestPartials(ownedBy id: String) {
|
|
3983
|
+
let prefix = "partial_\(CryptoCipher.shortPathKey(id))_"
|
|
3984
|
+
guard let files = try? FileManager.default.contentsOfDirectory(at: cacheFolder, includingPropertiesForKeys: nil) else {
|
|
3985
|
+
return
|
|
3986
|
+
}
|
|
3987
|
+
for url in files where url.lastPathComponent.hasPrefix(prefix) && url.lastPathComponent.hasSuffix(".tmp") {
|
|
3988
|
+
try? FileManager.default.removeItem(at: url)
|
|
3989
|
+
}
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3544
3992
|
func canSet(bundle: BundleInfo) -> Bool {
|
|
3545
3993
|
bundle.isBuiltin() || self.bundleExists(id: bundle.getId())
|
|
3546
3994
|
}
|
|
@@ -3549,6 +3997,11 @@ import UIKit
|
|
|
3549
3997
|
return self.set(id: bundle.getId())
|
|
3550
3998
|
}
|
|
3551
3999
|
|
|
4000
|
+
/// True when `id` still has a stored record and an installed folder (not deleted or being deleted).
|
|
4001
|
+
func hasStoredDownloadedBundle(id: String) -> Bool {
|
|
4002
|
+
self.hasStoredBundleInfo(id: id) && self.bundleExists(id: id)
|
|
4003
|
+
}
|
|
4004
|
+
|
|
3552
4005
|
func bundleExists(id: String) -> Bool {
|
|
3553
4006
|
let destPersist: URL
|
|
3554
4007
|
do {
|
|
@@ -3681,6 +4134,11 @@ import UIKit
|
|
|
3681
4134
|
|
|
3682
4135
|
public func setSuccess(bundle: BundleInfo, autoDeletePrevious: Bool) {
|
|
3683
4136
|
self.setBundleStatus(id: bundle.getId(), status: BundleStatus.SUCCESS)
|
|
4137
|
+
let versionName = bundle.getVersionName()
|
|
4138
|
+
if !versionName.isEmpty {
|
|
4139
|
+
self.resetIncompleteDownloadRetryCount(version: versionName)
|
|
4140
|
+
}
|
|
4141
|
+
self.clearInterruptedDownloadBundle(bundleId: bundle.getId())
|
|
3684
4142
|
let fallback: BundleInfo = self.getFallbackBundle()
|
|
3685
4143
|
let previewFallback = self.getPreviewFallbackBundle()
|
|
3686
4144
|
let fallbackIsPreviewFallback = previewFallback?.getId() == fallback.getId()
|
|
@@ -4437,6 +4895,38 @@ import UIKit
|
|
|
4437
4895
|
return result
|
|
4438
4896
|
}
|
|
4439
4897
|
|
|
4898
|
+
/// Fills a missing link/comment on the stored record of `id` and returns it, or returns nil without writing
|
|
4899
|
+
/// when the record or its folder no longer exists. Runs under `deleteLock` so it cannot race `delete`.
|
|
4900
|
+
func fillStoredBundleMetadataIfPresent(id: String, link: String?, comment: String?) -> BundleInfo? {
|
|
4901
|
+
self.deleteLock.lock()
|
|
4902
|
+
defer { self.deleteLock.unlock() }
|
|
4903
|
+
guard self.hasStoredBundleInfo(id: id), self.bundleExists(id: id) else {
|
|
4904
|
+
return nil
|
|
4905
|
+
}
|
|
4906
|
+
var stored = self.getBundleInfo(id: id)
|
|
4907
|
+
guard stored.getId() == id else {
|
|
4908
|
+
return nil
|
|
4909
|
+
}
|
|
4910
|
+
var changed = false
|
|
4911
|
+
if let link, stored.getLink() == nil {
|
|
4912
|
+
stored = stored.setLink(link: link)
|
|
4913
|
+
changed = true
|
|
4914
|
+
}
|
|
4915
|
+
if let comment, stored.getComment() == nil {
|
|
4916
|
+
stored = stored.setComment(comment: comment)
|
|
4917
|
+
changed = true
|
|
4918
|
+
}
|
|
4919
|
+
if changed {
|
|
4920
|
+
self.saveBundleInfo(id: id, bundle: stored)
|
|
4921
|
+
}
|
|
4922
|
+
return stored
|
|
4923
|
+
}
|
|
4924
|
+
|
|
4925
|
+
/// Every stored bundle whose version name matches `version`, in `list()` order.
|
|
4926
|
+
public func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
|
|
4927
|
+
self.list().filter { $0.getVersionName() == version }
|
|
4928
|
+
}
|
|
4929
|
+
|
|
4440
4930
|
public func getBundleInfoByVersionName(version: String) -> BundleInfo? {
|
|
4441
4931
|
let installed: [BundleInfo] = self.list()
|
|
4442
4932
|
for i in installed {
|
|
@@ -4447,6 +4937,26 @@ import UIKit
|
|
|
4447
4937
|
return nil
|
|
4448
4938
|
}
|
|
4449
4939
|
|
|
4940
|
+
/// Includes deleted or incomplete registry entries omitted from the default non-raw list.
|
|
4941
|
+
func findRegistryBundleByVersionName(version: String) -> BundleInfo? {
|
|
4942
|
+
guard !version.isEmpty else {
|
|
4943
|
+
return nil
|
|
4944
|
+
}
|
|
4945
|
+
var tombstoneMatch: BundleInfo?
|
|
4946
|
+
for i in self.list(raw: true) {
|
|
4947
|
+
if i.isBuiltin() || i.isUnknown() || i.getVersionName() != version {
|
|
4948
|
+
continue
|
|
4949
|
+
}
|
|
4950
|
+
if !i.isDeleted() && !i.isDeleting() {
|
|
4951
|
+
return i
|
|
4952
|
+
}
|
|
4953
|
+
if tombstoneMatch == nil {
|
|
4954
|
+
tombstoneMatch = i
|
|
4955
|
+
}
|
|
4956
|
+
}
|
|
4957
|
+
return tombstoneMatch
|
|
4958
|
+
}
|
|
4959
|
+
|
|
4450
4960
|
private func removeBundleInfo(id: String) {
|
|
4451
4961
|
self.saveBundleInfo(id: id, bundle: nil)
|
|
4452
4962
|
}
|
|
@@ -4552,18 +5062,35 @@ import UIKit
|
|
|
4552
5062
|
return true
|
|
4553
5063
|
}
|
|
4554
5064
|
|
|
5065
|
+
/// Clears the stored next bundle only while it still refers to `bundleId` (atomic with `setNextBundle`).
|
|
5066
|
+
@discardableResult
|
|
5067
|
+
func clearNextBundleIfMatches(bundleId: String) -> Bool {
|
|
5068
|
+
nextBundleLock.lock()
|
|
5069
|
+
defer { nextBundleLock.unlock() }
|
|
5070
|
+
guard !bundleId.isEmpty, UserDefaults.standard.string(forKey: self.NEXT_VERSION) == bundleId else {
|
|
5071
|
+
return false
|
|
5072
|
+
}
|
|
5073
|
+
UserDefaults.standard.removeObject(forKey: self.NEXT_VERSION)
|
|
5074
|
+
UserDefaults.standard.synchronize()
|
|
5075
|
+
return true
|
|
5076
|
+
}
|
|
5077
|
+
|
|
4555
5078
|
public func setNextBundle(next: String?) -> Bool {
|
|
4556
5079
|
guard let nextId: String = next else {
|
|
5080
|
+
nextBundleLock.lock()
|
|
4557
5081
|
UserDefaults.standard.removeObject(forKey: self.NEXT_VERSION)
|
|
4558
5082
|
UserDefaults.standard.synchronize()
|
|
5083
|
+
nextBundleLock.unlock()
|
|
4559
5084
|
return false
|
|
4560
5085
|
}
|
|
4561
5086
|
let newBundle: BundleInfo = self.getBundleInfo(id: nextId)
|
|
4562
5087
|
if !newBundle.isBuiltin() && !self.bundleExists(id: nextId) {
|
|
4563
5088
|
return false
|
|
4564
5089
|
}
|
|
5090
|
+
nextBundleLock.lock()
|
|
4565
5091
|
UserDefaults.standard.set(nextId, forKey: self.NEXT_VERSION)
|
|
4566
5092
|
UserDefaults.standard.synchronize()
|
|
5093
|
+
nextBundleLock.unlock()
|
|
4567
5094
|
self.setBundleStatus(id: nextId, status: BundleStatus.PENDING)
|
|
4568
5095
|
self.sendStats(action: "set_next", versionName: newBundle.getVersionName(), oldVersionName: self.getCurrentBundle().getVersionName())
|
|
4569
5096
|
self.notifyListeners("setNext", ["bundle": newBundle.toJSON()])
|