@capgo/capacitor-updater 7.51.21 → 7.53.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.
- package/CapgoCapacitorUpdater.podspec +0 -3
- package/Package.swift +3 -11
- package/README.md +202 -67
- package/android/build.gradle +2 -3
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +610 -177
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +909 -196
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +53 -19
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +210 -58
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
- package/dist/docs.json +394 -27
- package/dist/esm/definitions.d.ts +220 -7
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +562 -187
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +564 -109
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +11 -2
- package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
- package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
- package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +9 -3
- package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
- package/package.json +7 -3
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import Foundation
|
|
8
|
-
import ZIPFoundation
|
|
9
|
-
import Alamofire
|
|
10
8
|
import Compression
|
|
11
9
|
import UIKit
|
|
12
10
|
|
|
@@ -120,7 +118,7 @@ import UIKit
|
|
|
120
118
|
let timedOut: Bool
|
|
121
119
|
}
|
|
122
120
|
|
|
123
|
-
|
|
121
|
+
struct DownloadRequestResult {
|
|
124
122
|
let fileURL: URL?
|
|
125
123
|
let response: HTTPURLResponse?
|
|
126
124
|
let error: Error?
|
|
@@ -134,6 +132,10 @@ import UIKit
|
|
|
134
132
|
case pathTraversal
|
|
135
133
|
}
|
|
136
134
|
|
|
135
|
+
static func containsPathTraversalSegment(_ relativePath: String) -> Bool {
|
|
136
|
+
return relativePath.split(separator: "/").contains(where: { $0 == ".." })
|
|
137
|
+
}
|
|
138
|
+
|
|
137
139
|
static func resolvePathInsideDirectory(baseDirectory: URL, relativePath: String) throws -> URL {
|
|
138
140
|
if relativePath.isEmpty {
|
|
139
141
|
throw SecurePathError.emptyPath
|
|
@@ -141,6 +143,9 @@ import UIKit
|
|
|
141
143
|
if relativePath.contains("\\") || relativePath.contains("\0") {
|
|
142
144
|
throw SecurePathError.windowsPath
|
|
143
145
|
}
|
|
146
|
+
if containsPathTraversalSegment(relativePath) {
|
|
147
|
+
throw SecurePathError.pathTraversal
|
|
148
|
+
}
|
|
144
149
|
if (relativePath as NSString).isAbsolutePath {
|
|
145
150
|
throw SecurePathError.absolutePath
|
|
146
151
|
}
|
|
@@ -151,20 +156,45 @@ import UIKit
|
|
|
151
156
|
let canonicalTarget = canonicalBase.appendingPathComponent(relativePath).standardizedFileURL
|
|
152
157
|
let canonicalTargetPath = canonicalTarget.path
|
|
153
158
|
|
|
154
|
-
|
|
159
|
+
// Require a strict child of the base. Equality would accept "." and wipe/write the root.
|
|
160
|
+
if !canonicalTargetPath.hasPrefix(normalizedBasePath) {
|
|
155
161
|
throw SecurePathError.pathTraversal
|
|
156
162
|
}
|
|
157
163
|
|
|
158
164
|
return canonicalTarget
|
|
159
165
|
}
|
|
160
166
|
|
|
167
|
+
static func resolveBundleDirectory(libraryDir: URL, bundleId: String) throws -> URL {
|
|
168
|
+
let bundleRoot = libraryDir.appendingPathComponent("NoCloud/ionic_built_snapshots")
|
|
169
|
+
return try resolvePathInsideDirectory(baseDirectory: bundleRoot, relativePath: bundleId)
|
|
170
|
+
}
|
|
171
|
+
|
|
161
172
|
static func resolveManifestTargetPath(baseDirectory: URL, fileName: String) throws -> URL {
|
|
162
173
|
let isBrotli = fileName.hasSuffix(".br")
|
|
163
174
|
let targetFileName = isBrotli ? String(fileName.dropLast(3)) : fileName
|
|
164
175
|
return try resolvePathInsideDirectory(baseDirectory: baseDirectory, relativePath: targetFileName)
|
|
165
176
|
}
|
|
166
177
|
|
|
178
|
+
static func rememberManifestTarget(_ seenTargets: inout Set<String>, targetFile: URL) -> Bool {
|
|
179
|
+
return seenTargets.insert(targetFile.standardizedFileURL.path).inserted
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private struct ManifestDownloadTask {
|
|
183
|
+
let fileName: String
|
|
184
|
+
let downloadUrl: String
|
|
185
|
+
let finalFileHash: String
|
|
186
|
+
let isBrotli: Bool
|
|
187
|
+
let destFileName: String
|
|
188
|
+
let destFilePath: URL
|
|
189
|
+
let builtinFilePath: URL
|
|
190
|
+
let cacheFilePath: URL?
|
|
191
|
+
let legacyCacheFilePath: URL?
|
|
192
|
+
}
|
|
193
|
+
|
|
167
194
|
private func isTimedOutError(_ error: Error?) -> Bool {
|
|
195
|
+
if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
|
|
196
|
+
return isTimedOutError(underlying)
|
|
197
|
+
}
|
|
168
198
|
guard let nsError = error as NSError? else {
|
|
169
199
|
return false
|
|
170
200
|
}
|
|
@@ -172,13 +202,49 @@ import UIKit
|
|
|
172
202
|
return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut
|
|
173
203
|
}
|
|
174
204
|
|
|
205
|
+
/// Errors produced by the URLSession transport. Descriptions intentionally match the messages the
|
|
206
|
+
/// previous Alamofire transport surfaced so logs and JS-facing error strings stay the same.
|
|
207
|
+
enum NetworkError: LocalizedError {
|
|
208
|
+
case sessionTaskFailed(Error)
|
|
209
|
+
case emptyResponse
|
|
210
|
+
case invalidURL(String)
|
|
211
|
+
case bodyEncodingFailed(Error?)
|
|
212
|
+
case downloadedFileMoveFailed(Error, source: URL, destination: URL)
|
|
213
|
+
|
|
214
|
+
var errorDescription: String? {
|
|
215
|
+
switch self {
|
|
216
|
+
case let .sessionTaskFailed(error):
|
|
217
|
+
return "URLSessionTask failed with error: \(error.localizedDescription)"
|
|
218
|
+
case .emptyResponse:
|
|
219
|
+
return "Response could not be serialized, input data was nil or zero length."
|
|
220
|
+
case let .invalidURL(url):
|
|
221
|
+
return "URL is not valid: \(url)"
|
|
222
|
+
case let .bodyEncodingFailed(error):
|
|
223
|
+
return "JSON could not be encoded because of error:\n\(error?.localizedDescription ?? "Invalid JSON object provided for parameter or object encoding.")"
|
|
224
|
+
case let .downloadedFileMoveFailed(error, source, destination):
|
|
225
|
+
return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/// Mirrors Alamofire's `responseData` serializer: an empty body is an error unless the status allows it.
|
|
231
|
+
static func emptyResponseError(data: Data?, response: HTTPURLResponse?, method: String?) -> Error? {
|
|
232
|
+
if let data, !data.isEmpty {
|
|
233
|
+
return nil
|
|
234
|
+
}
|
|
235
|
+
if method?.uppercased() == "HEAD" || [204, 205].contains(response?.statusCode ?? 0) {
|
|
236
|
+
return nil
|
|
237
|
+
}
|
|
238
|
+
return NetworkError.emptyResponse
|
|
239
|
+
}
|
|
240
|
+
|
|
175
241
|
// lazy var is not thread-safe; concurrent manifest downloads can race first access when statsUrl is empty.
|
|
176
|
-
private var
|
|
177
|
-
private let
|
|
178
|
-
private var
|
|
179
|
-
|
|
180
|
-
defer {
|
|
181
|
-
if let session =
|
|
242
|
+
private var cachedUrlSession: URLSession?
|
|
243
|
+
private let urlSessionLock = NSLock()
|
|
244
|
+
private var urlSession: URLSession {
|
|
245
|
+
urlSessionLock.lock()
|
|
246
|
+
defer { urlSessionLock.unlock() }
|
|
247
|
+
if let session = cachedUrlSession {
|
|
182
248
|
return session
|
|
183
249
|
}
|
|
184
250
|
let configuration = URLSessionConfiguration.ephemeral
|
|
@@ -188,10 +254,92 @@ import UIKit
|
|
|
188
254
|
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
189
255
|
configuration.urlCache = nil
|
|
190
256
|
configuration.httpMaximumConnectionsPerHost = Self.manifestMaxConcurrentFiles
|
|
191
|
-
|
|
192
|
-
|
|
257
|
+
redirectPolicy.onBlockedRedirect = { [weak self] source, target in
|
|
258
|
+
self?.logger?.error("Blocked HTTPS to HTTP redirect; set allowHttpsToHttpRedirect to true to allow it")
|
|
259
|
+
self?.logger?.debug("Redirect from \(source?.absoluteString ?? "") to \(target?.absoluteString ?? "")")
|
|
260
|
+
}
|
|
261
|
+
let session = URLSession(configuration: configuration, delegate: redirectPolicy, delegateQueue: nil)
|
|
262
|
+
cachedUrlSession = session
|
|
193
263
|
return session
|
|
194
264
|
}
|
|
265
|
+
|
|
266
|
+
/// Owned separately from `CapgoUpdater` because URLSession retains its delegate strongly.
|
|
267
|
+
private let redirectPolicy = RedirectPolicyDelegate()
|
|
268
|
+
|
|
269
|
+
/// Follow redirects from HTTPS to plain HTTP. Off by default so a redirect can never downgrade updater traffic.
|
|
270
|
+
public var allowHttpsToHttpRedirect: Bool {
|
|
271
|
+
get { redirectPolicy.allowHttpsToHttpRedirect }
|
|
272
|
+
set { redirectPolicy.allowHttpsToHttpRedirect = newValue }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// Runs a raw data task on the updater session (no cookies, no cache, redirect policy applied).
|
|
276
|
+
@discardableResult
|
|
277
|
+
func startRawDataTask(_ request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
|
|
278
|
+
let task = self.urlSession.dataTask(with: request, completionHandler: completion)
|
|
279
|
+
task.resume()
|
|
280
|
+
return task
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/// Runs a data task and reports `(data, response, error)` like Alamofire's `responseData` did:
|
|
284
|
+
/// `data` is nil when no bytes were received, transport errors are wrapped, and an empty body is an error
|
|
285
|
+
/// unless the status code is 204/205 (or the request is HEAD).
|
|
286
|
+
@discardableResult
|
|
287
|
+
private func startDataTask(
|
|
288
|
+
_ request: URLRequest,
|
|
289
|
+
completionQueue: DispatchQueue,
|
|
290
|
+
completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
|
|
291
|
+
) -> URLSessionDataTask {
|
|
292
|
+
let task = self.urlSession.dataTask(with: request) { data, response, error in
|
|
293
|
+
let httpResponse = response as? HTTPURLResponse
|
|
294
|
+
let body = (data?.isEmpty ?? true) ? nil : data
|
|
295
|
+
let resultError: Error?
|
|
296
|
+
if let error {
|
|
297
|
+
resultError = NetworkError.sessionTaskFailed(error)
|
|
298
|
+
} else {
|
|
299
|
+
resultError = Self.emptyResponseError(data: body, response: httpResponse, method: request.httpMethod)
|
|
300
|
+
}
|
|
301
|
+
completionQueue.async {
|
|
302
|
+
completion(body, httpResponse, resultError)
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
task.resume()
|
|
306
|
+
return task
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/// Builds a POST request with a JSON body (same headers as Alamofire's JSON encoders).
|
|
310
|
+
func makeJSONPostRequest(urlString: String, body: () throws -> Data) -> Result<URLRequest, Error> {
|
|
311
|
+
guard let url = URL(string: urlString) else {
|
|
312
|
+
return .failure(NetworkError.invalidURL(urlString))
|
|
313
|
+
}
|
|
314
|
+
var request = URLRequest(url: url)
|
|
315
|
+
request.httpMethod = "POST"
|
|
316
|
+
request.timeoutInterval = self.timeout
|
|
317
|
+
do {
|
|
318
|
+
request.httpBody = try body()
|
|
319
|
+
} catch let error as NetworkError {
|
|
320
|
+
return .failure(error)
|
|
321
|
+
} catch {
|
|
322
|
+
return .failure(NetworkError.bodyEncodingFailed(error))
|
|
323
|
+
}
|
|
324
|
+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
325
|
+
return .success(request)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/// Fire-and-forget JSON POST whose completion runs on the main queue, like Alamofire's default `responseData`.
|
|
329
|
+
private func sendJSONPost(
|
|
330
|
+
urlString: String,
|
|
331
|
+
body: () throws -> Data,
|
|
332
|
+
completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
|
|
333
|
+
) {
|
|
334
|
+
switch makeJSONPostRequest(urlString: urlString, body: body) {
|
|
335
|
+
case let .success(request):
|
|
336
|
+
self.startDataTask(request, completionQueue: .main, completion: completion)
|
|
337
|
+
case let .failure(error):
|
|
338
|
+
DispatchQueue.main.async {
|
|
339
|
+
completion(nil, nil, error)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
195
343
|
private let networkResponseQueue = DispatchQueue(label: "ee.forgr.capacitor-updater.network-response", qos: .utility)
|
|
196
344
|
|
|
197
345
|
public var notifyDownloadRaw: (String, Int, Bool, BundleInfo?) -> Void = { _, _, _, _ in }
|
|
@@ -249,43 +397,69 @@ import UIKit
|
|
|
249
397
|
var responseData: Data?
|
|
250
398
|
var httpResponse: HTTPURLResponse?
|
|
251
399
|
var requestError: Error?
|
|
252
|
-
let
|
|
253
|
-
responseData =
|
|
254
|
-
httpResponse = response
|
|
255
|
-
requestError =
|
|
400
|
+
let dataTask = self.startDataTask(request, completionQueue: self.networkResponseQueue) { data, response, error in
|
|
401
|
+
responseData = data
|
|
402
|
+
httpResponse = response
|
|
403
|
+
requestError = error
|
|
256
404
|
semaphore.signal()
|
|
257
405
|
}
|
|
258
|
-
dataRequest.resume()
|
|
259
406
|
|
|
260
407
|
if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
|
|
261
|
-
|
|
408
|
+
dataTask.cancel()
|
|
262
409
|
logger.error("\(label) timed out after \(Int(waitTimeout))s")
|
|
263
410
|
return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: true)
|
|
264
411
|
}
|
|
265
412
|
|
|
266
|
-
|
|
413
|
+
// URLSession can report its own timeout (NSURLErrorTimedOut) before the semaphore deadline.
|
|
414
|
+
let timedOut = isTimedOutError(requestError)
|
|
415
|
+
if timedOut {
|
|
416
|
+
logger.error("\(label) timed out after \(Int(request.timeoutInterval))s")
|
|
417
|
+
}
|
|
418
|
+
return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: timedOut)
|
|
267
419
|
}
|
|
268
420
|
|
|
269
|
-
|
|
421
|
+
func performDownloadRequest(_ request: URLRequest, label: String) -> DownloadRequestResult {
|
|
270
422
|
let waitTimeout = max(self.timeout + 5, 10)
|
|
271
423
|
let semaphore = DispatchSemaphore(value: 0)
|
|
272
424
|
var tempFileURL: URL?
|
|
273
425
|
var httpResponse: HTTPURLResponse?
|
|
274
426
|
var requestError: Error?
|
|
275
427
|
let temporaryDownloadURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
276
|
-
let
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
428
|
+
let downloadTask = self.urlSession.downloadTask(with: request) { location, response, error in
|
|
429
|
+
// URLSession deletes `location` once this handler returns, so move it synchronously here.
|
|
430
|
+
var movedFileURL: URL?
|
|
431
|
+
var resultError: Error?
|
|
432
|
+
if let error {
|
|
433
|
+
resultError = NetworkError.sessionTaskFailed(error)
|
|
434
|
+
} else if let location {
|
|
435
|
+
do {
|
|
436
|
+
let fileManager = FileManager.default
|
|
437
|
+
try fileManager.createDirectory(
|
|
438
|
+
at: temporaryDownloadURL.deletingLastPathComponent(),
|
|
439
|
+
withIntermediateDirectories: true,
|
|
440
|
+
attributes: nil
|
|
441
|
+
)
|
|
442
|
+
if fileManager.fileExists(atPath: temporaryDownloadURL.path) {
|
|
443
|
+
try fileManager.removeItem(at: temporaryDownloadURL)
|
|
444
|
+
}
|
|
445
|
+
try fileManager.moveItem(at: location, to: temporaryDownloadURL)
|
|
446
|
+
movedFileURL = temporaryDownloadURL
|
|
447
|
+
} catch {
|
|
448
|
+
resultError = NetworkError.downloadedFileMoveFailed(error, source: location, destination: temporaryDownloadURL)
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
let taskResponse = response as? HTTPURLResponse
|
|
452
|
+
self.networkResponseQueue.async {
|
|
453
|
+
tempFileURL = movedFileURL
|
|
454
|
+
httpResponse = taskResponse
|
|
455
|
+
requestError = resultError
|
|
456
|
+
semaphore.signal()
|
|
457
|
+
}
|
|
284
458
|
}
|
|
285
|
-
|
|
459
|
+
downloadTask.resume()
|
|
286
460
|
|
|
287
461
|
if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
|
|
288
|
-
|
|
462
|
+
downloadTask.cancel()
|
|
289
463
|
logger.error("\(label) timed out after \(Int(waitTimeout))s")
|
|
290
464
|
return DownloadRequestResult(
|
|
291
465
|
fileURL: existingDownloadFileURL(tempFileURL, fallback: temporaryDownloadURL),
|
|
@@ -332,6 +506,18 @@ import UIKit
|
|
|
332
506
|
return cacheFolder.appendingPathComponent("partial_\(digest)_\(token).tmp")
|
|
333
507
|
}
|
|
334
508
|
|
|
509
|
+
private func removePartialManifestBundleDirectory(_ destFolder: URL) {
|
|
510
|
+
guard FileManager.default.fileExists(atPath: destFolder.path) else {
|
|
511
|
+
return
|
|
512
|
+
}
|
|
513
|
+
do {
|
|
514
|
+
try FileManager.default.removeItem(at: destFolder)
|
|
515
|
+
} catch {
|
|
516
|
+
logger.error("Failed to remove partial manifest bundle directory")
|
|
517
|
+
logger.debug("Path: \(destFolder.path), Error: \(error.localizedDescription)")
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
335
521
|
private func cleanupOldManifestPartials() {
|
|
336
522
|
let cutoff = Date().addingTimeInterval(-3600)
|
|
337
523
|
guard let files = try? FileManager.default.contentsOfDirectory(
|
|
@@ -412,6 +598,8 @@ import UIKit
|
|
|
412
598
|
|
|
413
599
|
deinit {
|
|
414
600
|
shutdown()
|
|
601
|
+
// Alamofire's Session invalidated its URLSession on deinit; keep releasing the session the same way.
|
|
602
|
+
cachedUrlSession?.invalidateAndCancel()
|
|
415
603
|
}
|
|
416
604
|
|
|
417
605
|
public func shutdown() {
|
|
@@ -432,6 +620,18 @@ import UIKit
|
|
|
432
620
|
return String((0..<length).map { _ in letters.randomElement()! })
|
|
433
621
|
}
|
|
434
622
|
|
|
623
|
+
private func requireSessionKeyForEncryptedUpdate(sessionKey: String, versionName: String? = nil) throws {
|
|
624
|
+
if !self.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
|
|
625
|
+
logger.error("Public key present but no valid session key provided")
|
|
626
|
+
self.sendStats(action: "session_key_required", versionName: versionName)
|
|
627
|
+
throw NSError(
|
|
628
|
+
domain: "CapgoUpdater",
|
|
629
|
+
code: 1,
|
|
630
|
+
userInfo: [NSLocalizedDescriptionKey: "Session key required when public key is present"]
|
|
631
|
+
)
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
435
635
|
public func setPublicKey(_ publicKey: String) {
|
|
436
636
|
// Empty string means no encryption - proceed normally
|
|
437
637
|
if publicKey.isEmpty {
|
|
@@ -678,28 +878,27 @@ import UIKit
|
|
|
678
878
|
|
|
679
879
|
// Send synchronously using semaphore (safe because we're on a background queue)
|
|
680
880
|
let semaphore = DispatchSemaphore(value: 0)
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
let statusCode = response
|
|
689
|
-
|
|
690
|
-
case .success where (200...299).contains(statusCode ?? 0):
|
|
691
|
-
self.logger.info("Rate limit statistic sent")
|
|
692
|
-
case .success:
|
|
881
|
+
let parameterValues = parameters.toParameters()
|
|
882
|
+
self.sendJSONPost(urlString: self.statsUrl, body: {
|
|
883
|
+
guard JSONSerialization.isValidJSONObject(parameterValues) else {
|
|
884
|
+
throw NetworkError.bodyEncodingFailed(nil)
|
|
885
|
+
}
|
|
886
|
+
return try JSONSerialization.data(withJSONObject: parameterValues)
|
|
887
|
+
}, completion: { _, response, error in
|
|
888
|
+
let statusCode = response?.statusCode
|
|
889
|
+
if let error {
|
|
693
890
|
CapgoUpdater.releaseRateLimitStatisticClaim()
|
|
694
891
|
self.logger.error("Error sending rate limit statistic")
|
|
695
|
-
self.logger.debug("
|
|
696
|
-
|
|
892
|
+
self.logger.debug("Error: \(error.localizedDescription)")
|
|
893
|
+
} else if (200...299).contains(statusCode ?? 0) {
|
|
894
|
+
self.logger.info("Rate limit statistic sent")
|
|
895
|
+
} else {
|
|
697
896
|
CapgoUpdater.releaseRateLimitStatisticClaim()
|
|
698
897
|
self.logger.error("Error sending rate limit statistic")
|
|
699
|
-
self.logger.debug("
|
|
898
|
+
self.logger.debug("Response code: \(statusCode.map(String.init) ?? "nil")")
|
|
700
899
|
}
|
|
701
900
|
semaphore.signal()
|
|
702
|
-
}
|
|
901
|
+
})
|
|
703
902
|
semaphore.wait()
|
|
704
903
|
}
|
|
705
904
|
|
|
@@ -791,7 +990,59 @@ import UIKit
|
|
|
791
990
|
}
|
|
792
991
|
}
|
|
793
992
|
|
|
794
|
-
|
|
993
|
+
// Symlink targets are paths; anything bigger than this is not a legitimate link.
|
|
994
|
+
private static let maxZipSymlinkTargetBytes = 64 * 1024
|
|
995
|
+
|
|
996
|
+
/// A zip symlink target must be a relative path without `..`, so a link can only point further down.
|
|
997
|
+
/// A lexical check alone is not enough: with `m -> .`, the target `m/..` normalizes to the link folder but
|
|
998
|
+
/// physically resolves to its parent.
|
|
999
|
+
static func isSafeZipSymlinkTarget(_ target: String) -> Bool {
|
|
1000
|
+
if target.isEmpty || target.contains("\0") || target.contains("\\") {
|
|
1001
|
+
return false
|
|
1002
|
+
}
|
|
1003
|
+
if (target as NSString).isAbsolutePath {
|
|
1004
|
+
return false
|
|
1005
|
+
}
|
|
1006
|
+
return !containsPathTraversalSegment(target)
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
private static func realPath(_ path: String) -> String? {
|
|
1010
|
+
guard let resolved = Darwin.realpath(path, nil) else {
|
|
1011
|
+
return nil
|
|
1012
|
+
}
|
|
1013
|
+
defer { free(resolved) }
|
|
1014
|
+
return String(cString: resolved)
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/// Resolves symlinks on the deepest existing ancestor of `url` and throws when it is outside `root`.
|
|
1018
|
+
/// Run before creating anything, so a symlinked folder can never redirect a write out of the bundle.
|
|
1019
|
+
static func assertPhysicallyInsideDirectory(_ url: URL, root: URL) throws {
|
|
1020
|
+
guard let rootPath = realPath(root.path) else {
|
|
1021
|
+
throw SecurePathError.pathTraversal
|
|
1022
|
+
}
|
|
1023
|
+
let normalizedRoot = rootPath.hasSuffix("/") ? rootPath : "\(rootPath)/"
|
|
1024
|
+
var candidate = url.standardizedFileURL.path
|
|
1025
|
+
while true {
|
|
1026
|
+
if let resolved = realPath(candidate) {
|
|
1027
|
+
if resolved != rootPath && !resolved.hasPrefix(normalizedRoot) {
|
|
1028
|
+
throw SecurePathError.pathTraversal
|
|
1029
|
+
}
|
|
1030
|
+
return
|
|
1031
|
+
}
|
|
1032
|
+
let parent = (candidate as NSString).deletingLastPathComponent
|
|
1033
|
+
if parent == candidate || parent.isEmpty {
|
|
1034
|
+
throw SecurePathError.pathTraversal
|
|
1035
|
+
}
|
|
1036
|
+
candidate = parent
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/// `fileExists` follows symlinks, so a dangling link would be missed; this does not follow the last component.
|
|
1041
|
+
private static func itemExistsWithoutFollowingLink(at url: URL) -> Bool {
|
|
1042
|
+
return (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
private func extractZipEntry(_ archive: ZipArchiveReader, entry: ZipEntry, to destPath: URL, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
|
|
795
1046
|
let fileManager = FileManager.default
|
|
796
1047
|
|
|
797
1048
|
switch entry.type {
|
|
@@ -801,7 +1052,7 @@ import UIKit
|
|
|
801
1052
|
let parentDir = destPath.deletingLastPathComponent()
|
|
802
1053
|
try fileManager.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
|
|
803
1054
|
|
|
804
|
-
if
|
|
1055
|
+
if Self.itemExistsWithoutFollowingLink(at: destPath) {
|
|
805
1056
|
try fileManager.removeItem(at: destPath)
|
|
806
1057
|
}
|
|
807
1058
|
|
|
@@ -814,18 +1065,18 @@ import UIKit
|
|
|
814
1065
|
fileHandle.closeFile()
|
|
815
1066
|
}
|
|
816
1067
|
|
|
817
|
-
|
|
1068
|
+
try archive.extract(entry, bufferSize: bufferSize) { data in
|
|
818
1069
|
if !data.isEmpty {
|
|
819
1070
|
fileHandle.write(data)
|
|
820
1071
|
}
|
|
821
1072
|
}
|
|
822
1073
|
case .symlink:
|
|
823
|
-
|
|
824
|
-
_ = try archive.extract(entry, bufferSize: bufferSize, skipCRC32: true) { data in
|
|
825
|
-
linkData.append(data)
|
|
826
|
-
}
|
|
1074
|
+
let linkData = try archive.readSmallEntry(entry, maxBytes: Self.maxZipSymlinkTargetBytes, bufferSize: bufferSize)
|
|
827
1075
|
|
|
828
|
-
guard let linkPath = String(data: linkData, encoding: .utf8) else {
|
|
1076
|
+
guard let linkPath = String(data: linkData, encoding: .utf8), Self.isSafeZipSymlinkTarget(linkPath) else {
|
|
1077
|
+
logger.error("Unzip failed: unsafe symlink target")
|
|
1078
|
+
logger.debug("Entry: \(entry.path)")
|
|
1079
|
+
self.sendStats(action: "canonical_path_fail")
|
|
829
1080
|
throw CustomError.cannotUnzip
|
|
830
1081
|
}
|
|
831
1082
|
|
|
@@ -842,7 +1093,7 @@ import UIKit
|
|
|
842
1093
|
throw CustomError.cannotUnzip
|
|
843
1094
|
}
|
|
844
1095
|
|
|
845
|
-
if
|
|
1096
|
+
if Self.itemExistsWithoutFollowingLink(at: destPath) {
|
|
846
1097
|
try fileManager.removeItem(at: destPath)
|
|
847
1098
|
}
|
|
848
1099
|
|
|
@@ -859,9 +1110,9 @@ import UIKit
|
|
|
859
1110
|
self.notifyDownload(id: id, percent: 75)
|
|
860
1111
|
|
|
861
1112
|
// Open the archive
|
|
862
|
-
let archive:
|
|
1113
|
+
let archive: ZipArchiveReader
|
|
863
1114
|
do {
|
|
864
|
-
archive = try
|
|
1115
|
+
archive = try ZipArchiveReader(url: sourceZip)
|
|
865
1116
|
} catch {
|
|
866
1117
|
self.sendStats(action: "unzip_fail")
|
|
867
1118
|
throw CustomError.cannotUnzip
|
|
@@ -871,12 +1122,21 @@ import UIKit
|
|
|
871
1122
|
try FileManager.default.createDirectory(at: destUnZip, withIntermediateDirectories: true, attributes: nil)
|
|
872
1123
|
|
|
873
1124
|
// Count total entries for progress
|
|
874
|
-
let totalEntries = archive.
|
|
1125
|
+
let totalEntries = archive.entries.count
|
|
875
1126
|
var processedEntries = 0
|
|
876
1127
|
|
|
877
1128
|
do {
|
|
878
|
-
for entry in archive {
|
|
1129
|
+
for entry in archive.entries {
|
|
879
1130
|
let destPath = try resolveZipEntry(path: entry.path, destUnZip: destUnZip)
|
|
1131
|
+
do {
|
|
1132
|
+
// Symlinks extracted earlier must not move this entry out of the bundle folder.
|
|
1133
|
+
try Self.assertPhysicallyInsideDirectory(destPath.deletingLastPathComponent(), root: destUnZip)
|
|
1134
|
+
} catch {
|
|
1135
|
+
logger.error("Unzip failed: entry resolves outside the bundle folder")
|
|
1136
|
+
logger.debug("Entry: \(entry.path)")
|
|
1137
|
+
self.sendStats(action: "canonical_path_fail")
|
|
1138
|
+
throw CustomError.cannotUnzip
|
|
1139
|
+
}
|
|
880
1140
|
|
|
881
1141
|
if entry.type == .directory {
|
|
882
1142
|
try FileManager.default.createDirectory(at: destPath, withIntermediateDirectories: true, attributes: nil)
|
|
@@ -963,7 +1223,13 @@ import UIKit
|
|
|
963
1223
|
/// `manifest` must only contain entries the caller already checksum-verified
|
|
964
1224
|
/// (as `downloadManifest` does) — the hashes are trusted as-is, not re-checked.
|
|
965
1225
|
func populateDeltaCache(for id: String, manifest: [ManifestEntry]? = nil, sessionKey: String = "") {
|
|
966
|
-
let bundleDir
|
|
1226
|
+
let bundleDir: URL
|
|
1227
|
+
do {
|
|
1228
|
+
bundleDir = try self.getBundleDirectory(id: id)
|
|
1229
|
+
} catch {
|
|
1230
|
+
logger.debug("Skip delta cache population: invalid bundle id")
|
|
1231
|
+
return
|
|
1232
|
+
}
|
|
967
1233
|
let fileManager = FileManager.default
|
|
968
1234
|
|
|
969
1235
|
guard fileManager.fileExists(atPath: bundleDir.path) else {
|
|
@@ -1223,7 +1489,10 @@ import UIKit
|
|
|
1223
1489
|
guard var fileHash = entry.file_hash, !fileHash.isEmpty else {
|
|
1224
1490
|
return nil
|
|
1225
1491
|
}
|
|
1226
|
-
if !self.publicKey.isEmpty
|
|
1492
|
+
if !self.publicKey.isEmpty {
|
|
1493
|
+
if !CryptoCipher.isValidSessionKey(sessionKey) {
|
|
1494
|
+
return nil
|
|
1495
|
+
}
|
|
1227
1496
|
do {
|
|
1228
1497
|
fileHash = try CryptoCipher.decryptChecksum(checksum: fileHash, publicKey: self.publicKey)
|
|
1229
1498
|
} catch {
|
|
@@ -1384,10 +1653,11 @@ import UIKit
|
|
|
1384
1653
|
}
|
|
1385
1654
|
|
|
1386
1655
|
public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
|
|
1656
|
+
try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
|
|
1387
1657
|
try self.runBeforeDownload()
|
|
1388
1658
|
let id = self.randomString(length: 10)
|
|
1389
1659
|
logger.info("downloadManifest start \(id)")
|
|
1390
|
-
let destFolder = self.getBundleDirectory(id: id)
|
|
1660
|
+
let destFolder = try self.getBundleDirectory(id: id)
|
|
1391
1661
|
let builtinFolder = self.builtinFolderURL()
|
|
1392
1662
|
|
|
1393
1663
|
// Check disk space before starting manifest download (estimate 100KB per file, minimum 50MB)
|
|
@@ -1416,8 +1686,8 @@ import UIKit
|
|
|
1416
1686
|
var downloadError: Error?
|
|
1417
1687
|
let errorLock = NSLock()
|
|
1418
1688
|
|
|
1419
|
-
|
|
1420
|
-
var
|
|
1689
|
+
var tasks: [ManifestDownloadTask] = []
|
|
1690
|
+
var seenTargets = Set<String>()
|
|
1421
1691
|
|
|
1422
1692
|
for entry in manifest {
|
|
1423
1693
|
guard let fileName = entry.file_name,
|
|
@@ -1458,7 +1728,23 @@ import UIKit
|
|
|
1458
1728
|
var fileHash = entryFileHash
|
|
1459
1729
|
|
|
1460
1730
|
// Decrypt checksum if needed (done before creating operation)
|
|
1461
|
-
if !self.publicKey.isEmpty
|
|
1731
|
+
if !self.publicKey.isEmpty {
|
|
1732
|
+
if !CryptoCipher.isValidSessionKey(sessionKey) {
|
|
1733
|
+
let error = NSError(
|
|
1734
|
+
domain: "CapgoUpdater",
|
|
1735
|
+
code: 1,
|
|
1736
|
+
userInfo: [NSLocalizedDescriptionKey: "Session key required when public key is present"]
|
|
1737
|
+
)
|
|
1738
|
+
self.sendStats(action: "session_key_required", versionName: version)
|
|
1739
|
+
errorLock.lock()
|
|
1740
|
+
if downloadError == nil {
|
|
1741
|
+
downloadError = error
|
|
1742
|
+
}
|
|
1743
|
+
errorLock.unlock()
|
|
1744
|
+
hasError.value = true
|
|
1745
|
+
logger.error("Public key present but no valid session key provided")
|
|
1746
|
+
continue
|
|
1747
|
+
}
|
|
1462
1748
|
do {
|
|
1463
1749
|
fileHash = try CryptoCipher.decryptChecksum(checksum: fileHash, publicKey: self.publicKey)
|
|
1464
1750
|
} catch {
|
|
@@ -1489,6 +1775,24 @@ import UIKit
|
|
|
1489
1775
|
do {
|
|
1490
1776
|
destFilePath = try Self.resolveManifestTargetPath(baseDirectory: destFolder, fileName: fileName)
|
|
1491
1777
|
builtinFilePath = try Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName)
|
|
1778
|
+
if !Self.rememberManifestTarget(&seenTargets, targetFile: destFilePath) {
|
|
1779
|
+
logger.error("Duplicate manifest target path: \(fileName)")
|
|
1780
|
+
self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
|
|
1781
|
+
let error = NSError(
|
|
1782
|
+
domain: "ManifestEntryError",
|
|
1783
|
+
code: 3,
|
|
1784
|
+
userInfo: [
|
|
1785
|
+
NSLocalizedDescriptionKey: "Duplicate manifest target path for \(fileName)"
|
|
1786
|
+
]
|
|
1787
|
+
)
|
|
1788
|
+
errorLock.lock()
|
|
1789
|
+
if downloadError == nil {
|
|
1790
|
+
downloadError = error
|
|
1791
|
+
}
|
|
1792
|
+
errorLock.unlock()
|
|
1793
|
+
hasError.value = true
|
|
1794
|
+
continue
|
|
1795
|
+
}
|
|
1492
1796
|
} catch {
|
|
1493
1797
|
logger.error("Invalid manifest file path: \(fileName)")
|
|
1494
1798
|
self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
|
|
@@ -1501,8 +1805,49 @@ import UIKit
|
|
|
1501
1805
|
continue
|
|
1502
1806
|
}
|
|
1503
1807
|
|
|
1504
|
-
|
|
1505
|
-
|
|
1808
|
+
tasks.append(
|
|
1809
|
+
ManifestDownloadTask(
|
|
1810
|
+
fileName: fileName,
|
|
1811
|
+
downloadUrl: downloadUrl,
|
|
1812
|
+
finalFileHash: finalFileHash,
|
|
1813
|
+
isBrotli: isBrotli,
|
|
1814
|
+
destFileName: destFileName,
|
|
1815
|
+
destFilePath: destFilePath,
|
|
1816
|
+
builtinFilePath: builtinFilePath,
|
|
1817
|
+
cacheFilePath: cacheFilePath,
|
|
1818
|
+
legacyCacheFilePath: legacyCacheFilePath
|
|
1819
|
+
)
|
|
1820
|
+
)
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
if hasError.value {
|
|
1824
|
+
let resolvedError = downloadError ?? NSError(
|
|
1825
|
+
domain: "ManifestDownloadError",
|
|
1826
|
+
code: 1,
|
|
1827
|
+
userInfo: [NSLocalizedDescriptionKey: "Manifest download failed due to invalid or missing entries"]
|
|
1828
|
+
)
|
|
1829
|
+
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1830
|
+
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1831
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1832
|
+
throw resolvedError
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
var operations: [Operation] = []
|
|
1836
|
+
|
|
1837
|
+
for task in tasks {
|
|
1838
|
+
do {
|
|
1839
|
+
try FileManager.default.createDirectory(
|
|
1840
|
+
at: task.destFilePath.deletingLastPathComponent(),
|
|
1841
|
+
withIntermediateDirectories: true,
|
|
1842
|
+
attributes: nil
|
|
1843
|
+
)
|
|
1844
|
+
} catch {
|
|
1845
|
+
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1846
|
+
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1847
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1848
|
+
self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
|
|
1849
|
+
throw error
|
|
1850
|
+
}
|
|
1506
1851
|
|
|
1507
1852
|
let operation = BlockOperation { [weak self] in
|
|
1508
1853
|
guard let self = self else { return }
|
|
@@ -1510,26 +1855,29 @@ import UIKit
|
|
|
1510
1855
|
|
|
1511
1856
|
do {
|
|
1512
1857
|
// Try builtin first
|
|
1513
|
-
if FileManager.default.fileExists(atPath: builtinFilePath.path) &&
|
|
1514
|
-
|
|
1515
|
-
self.
|
|
1858
|
+
if FileManager.default.fileExists(atPath: task.builtinFilePath.path) &&
|
|
1859
|
+
self.verifyChecksum(file: task.builtinFilePath, expectedHash: task.finalFileHash) {
|
|
1860
|
+
try self.copyItemReplacing(from: task.builtinFilePath, to: task.destFilePath)
|
|
1861
|
+
self.logger.info("downloadManifest \(task.fileName) using builtin file \(id)")
|
|
1516
1862
|
}
|
|
1517
1863
|
// Try cache
|
|
1518
1864
|
else if
|
|
1519
|
-
(cacheFilePath != nil &&
|
|
1520
|
-
|
|
1521
|
-
|
|
1865
|
+
(task.cacheFilePath != nil &&
|
|
1866
|
+
self.tryCopyFromCache(from: task.cacheFilePath!, to: task.destFilePath, expectedHash: task.finalFileHash)) ||
|
|
1867
|
+
(task.legacyCacheFilePath != nil &&
|
|
1868
|
+
self.tryCopyFromCache(from: task.legacyCacheFilePath!, to: task.destFilePath, expectedHash: task.finalFileHash)) {
|
|
1869
|
+
self.logger.info("downloadManifest \(task.fileName) copy from cache \(id)")
|
|
1522
1870
|
}
|
|
1523
1871
|
// Download
|
|
1524
1872
|
else {
|
|
1525
1873
|
try self.downloadManifestFile(
|
|
1526
|
-
downloadUrl: downloadUrl,
|
|
1527
|
-
destFilePath: destFilePath,
|
|
1528
|
-
cacheFilePath: cacheFilePath,
|
|
1529
|
-
fileHash: finalFileHash,
|
|
1530
|
-
fileName: fileName,
|
|
1531
|
-
destFileName: destFileName,
|
|
1532
|
-
isBrotli: isBrotli,
|
|
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,
|
|
1533
1881
|
sessionKey: sessionKey,
|
|
1534
1882
|
version: version,
|
|
1535
1883
|
bundleId: id
|
|
@@ -1547,8 +1895,8 @@ import UIKit
|
|
|
1547
1895
|
}
|
|
1548
1896
|
errorLock.unlock()
|
|
1549
1897
|
hasError.value = true
|
|
1550
|
-
self.logger.error("Manifest file download failed: \(fileName)")
|
|
1551
|
-
self.logger.debug("Bundle: \(id), File: \(fileName), Error: \(error.localizedDescription)")
|
|
1898
|
+
self.logger.error("Manifest file download failed: \(task.fileName)")
|
|
1899
|
+
self.logger.debug("Bundle: \(id), File: \(task.fileName), Error: \(error.localizedDescription)")
|
|
1552
1900
|
}
|
|
1553
1901
|
}
|
|
1554
1902
|
|
|
@@ -1567,6 +1915,7 @@ import UIKit
|
|
|
1567
1915
|
// Update bundle status to ERROR if download failed
|
|
1568
1916
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1569
1917
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1918
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1570
1919
|
throw resolvedError
|
|
1571
1920
|
}
|
|
1572
1921
|
|
|
@@ -1685,7 +2034,7 @@ import UIKit
|
|
|
1685
2034
|
|
|
1686
2035
|
do {
|
|
1687
2036
|
var source = partialURL
|
|
1688
|
-
if !self.publicKey.isEmpty &&
|
|
2037
|
+
if !self.publicKey.isEmpty && CryptoCipher.isValidSessionKey(sessionKey) {
|
|
1689
2038
|
let work = cacheFolder.appendingPathComponent("work_\(UUID().uuidString)_\((fileName as NSString).lastPathComponent)")
|
|
1690
2039
|
try FileManager.default.copyItem(at: partialURL, to: work)
|
|
1691
2040
|
workURL = work
|
|
@@ -1986,7 +2335,47 @@ import UIKit
|
|
|
1986
2335
|
return hasher.hex()
|
|
1987
2336
|
}
|
|
1988
2337
|
|
|
2338
|
+
/// Resolves the checksum a zip bundle must match: required, and RSA-decrypted when a public key is set.
|
|
2339
|
+
func resolveExpectedBundleChecksum(_ checksum: String, versionName: String) throws -> String {
|
|
2340
|
+
if checksum.isEmpty {
|
|
2341
|
+
logger.error("No checksum provided")
|
|
2342
|
+
self.sendStats(action: "checksum_required", versionName: versionName)
|
|
2343
|
+
throw NSError(domain: "ChecksumError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Checksum required"])
|
|
2344
|
+
}
|
|
2345
|
+
return try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.publicKey)
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
/// Downloads and extracts a zip bundle without checking its checksum; the caller must verify it.
|
|
2349
|
+
/// Prefer `downloadVerified`, which rejects a bad archive before extracting it.
|
|
1989
2350
|
public func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
|
|
2351
|
+
return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: nil)
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
/// Downloads a zip bundle and extracts it only when it matches `expectedChecksum`, the checksum from the
|
|
2355
|
+
/// update response (required, RSA-decrypted when a public key is set). The SHA-256 of the downloaded and
|
|
2356
|
+
/// decrypted archive is compared before anything is extracted: a mismatch deletes the archive, reports
|
|
2357
|
+
/// `checksum_fail` and throws `ObjectSavableError.checksum`.
|
|
2358
|
+
public func downloadVerified(
|
|
2359
|
+
url: URL,
|
|
2360
|
+
version: String,
|
|
2361
|
+
sessionKey: String,
|
|
2362
|
+
expectedChecksum: String,
|
|
2363
|
+
link: String? = nil,
|
|
2364
|
+
comment: String? = nil
|
|
2365
|
+
) throws -> BundleInfo {
|
|
2366
|
+
return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: expectedChecksum)
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
private func downloadZip(
|
|
2370
|
+
url: URL,
|
|
2371
|
+
version: String,
|
|
2372
|
+
sessionKey: String,
|
|
2373
|
+
link: String?,
|
|
2374
|
+
comment: String?,
|
|
2375
|
+
expectedChecksum: String?
|
|
2376
|
+
) throws -> BundleInfo {
|
|
2377
|
+
try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
|
|
2378
|
+
let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
|
|
1990
2379
|
try self.runBeforeDownload()
|
|
1991
2380
|
let id: String = self.randomString(length: 10)
|
|
1992
2381
|
// Each download uses its own temp files keyed by bundle ID to prevent collisions
|
|
@@ -2029,6 +2418,12 @@ import UIKit
|
|
|
2029
2418
|
}
|
|
2030
2419
|
|
|
2031
2420
|
let downloadResult = performDownloadRequest(request, label: "download \(version)")
|
|
2421
|
+
// Error responses (e.g. an HTTP 404 body) are also saved to a temp file; never leave them behind.
|
|
2422
|
+
defer {
|
|
2423
|
+
if let fileURL = downloadResult.fileURL {
|
|
2424
|
+
try? FileManager.default.removeItem(at: fileURL)
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2032
2427
|
|
|
2033
2428
|
if downloadResult.timedOut {
|
|
2034
2429
|
persistPartialDownload(downloadResult, id: id, tempPath: tempPath, existingBytes: totalReceivedBytes)
|
|
@@ -2089,9 +2484,22 @@ import UIKit
|
|
|
2089
2484
|
throw error
|
|
2090
2485
|
}
|
|
2091
2486
|
|
|
2487
|
+
checksum = CryptoCipher.calcChecksum(filePath: finalPath)
|
|
2488
|
+
CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
|
|
2489
|
+
if let expectedHash, checksum.isEmpty || checksum != expectedHash {
|
|
2490
|
+
// Never extract an archive that failed verification.
|
|
2491
|
+
logger.error("Checksum mismatch, bundle rejected before extraction")
|
|
2492
|
+
CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedHash)
|
|
2493
|
+
self.sendStats(action: "checksum_fail", versionName: version)
|
|
2494
|
+
try? FileManager.default.removeItem(at: finalPath)
|
|
2495
|
+
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2496
|
+
cleanDownloadData(for: id)
|
|
2497
|
+
// Drop it like the previous post-extraction check did, so the next update check downloads it again.
|
|
2498
|
+
_ = self.delete(id: id)
|
|
2499
|
+
throw ObjectSavableError.checksum
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2092
2502
|
do {
|
|
2093
|
-
checksum = CryptoCipher.calcChecksum(filePath: finalPath)
|
|
2094
|
-
CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
|
|
2095
2503
|
logger.info("Downloading: 80% (unzipping)")
|
|
2096
2504
|
try self.saveDownloaded(sourceZip: finalPath, id: id, base: self.libraryDir.appendingPathComponent(self.bundleDirectory), notify: true)
|
|
2097
2505
|
self.populateDeltaCacheAsync(for: id)
|
|
@@ -2267,6 +2675,15 @@ import UIKit
|
|
|
2267
2675
|
self.deleteLock.lock()
|
|
2268
2676
|
defer { self.deleteLock.unlock() }
|
|
2269
2677
|
|
|
2678
|
+
let destPersist: URL
|
|
2679
|
+
do {
|
|
2680
|
+
destPersist = try self.getBundleDirectory(id: id)
|
|
2681
|
+
} catch {
|
|
2682
|
+
logger.error("Cannot delete bundle with invalid id")
|
|
2683
|
+
logger.debug("Bundle ID: \(id), Error: \(error.localizedDescription)")
|
|
2684
|
+
return false
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2270
2687
|
let deleted: BundleInfo = self.getBundleInfo(id: id)
|
|
2271
2688
|
if deleted.isBuiltin() || self.getCurrentBundleId() == id {
|
|
2272
2689
|
logger.info("Cannot delete current or builtin bundle")
|
|
@@ -2295,7 +2712,6 @@ import UIKit
|
|
|
2295
2712
|
return false
|
|
2296
2713
|
}
|
|
2297
2714
|
|
|
2298
|
-
let destPersist: URL = libraryDir.appendingPathComponent(bundleDirectory).appendingPathComponent(id)
|
|
2299
2715
|
let hadRegistry = self.hasStoredBundleInfo(id: id)
|
|
2300
2716
|
let hadFolder = FileManager.default.fileExists(atPath: destPersist.path)
|
|
2301
2717
|
if !hadRegistry && !hadFolder {
|
|
@@ -2599,8 +3015,8 @@ import UIKit
|
|
|
2599
3015
|
}
|
|
2600
3016
|
}
|
|
2601
3017
|
|
|
2602
|
-
public func getBundleDirectory(id: String) -> URL {
|
|
2603
|
-
return
|
|
3018
|
+
public func getBundleDirectory(id: String) throws -> URL {
|
|
3019
|
+
return try Self.resolveBundleDirectory(libraryDir: libraryDir, bundleId: id)
|
|
2604
3020
|
}
|
|
2605
3021
|
|
|
2606
3022
|
struct ResetState {
|
|
@@ -2654,7 +3070,12 @@ import UIKit
|
|
|
2654
3070
|
}
|
|
2655
3071
|
|
|
2656
3072
|
private func bundleExists(id: String) -> Bool {
|
|
2657
|
-
let destPersist: URL
|
|
3073
|
+
let destPersist: URL
|
|
3074
|
+
do {
|
|
3075
|
+
destPersist = try self.getBundleDirectory(id: id)
|
|
3076
|
+
} catch {
|
|
3077
|
+
return false
|
|
3078
|
+
}
|
|
2658
3079
|
let indexPersist: URL = destPersist.appendingPathComponent("index.html")
|
|
2659
3080
|
let bundleIndo: BundleInfo = self.getBundleInfo(id: id)
|
|
2660
3081
|
if
|
|
@@ -2677,7 +3098,12 @@ import UIKit
|
|
|
2677
3098
|
}
|
|
2678
3099
|
if bundleExists(id: id) {
|
|
2679
3100
|
let currentBundleName = self.getCurrentBundle().getVersionName()
|
|
2680
|
-
|
|
3101
|
+
guard let bundleDir = try? self.getBundleDirectory(id: id) else {
|
|
3102
|
+
self.setBundleStatus(id: id, status: BundleStatus.ERROR)
|
|
3103
|
+
self.sendStats(action: "set_fail", versionName: newBundle.getVersionName())
|
|
3104
|
+
return false
|
|
3105
|
+
}
|
|
3106
|
+
self.setCurrentBundle(bundle: bundleDir.path)
|
|
2681
3107
|
self.setBundleStatus(id: id, status: BundleStatus.PENDING)
|
|
2682
3108
|
self.sendStats(action: "set", versionName: newBundle.getVersionName(), oldVersionName: currentBundleName)
|
|
2683
3109
|
return true
|
|
@@ -2691,10 +3117,23 @@ import UIKit
|
|
|
2691
3117
|
guard !bundle.isBuiltin(), bundleExists(id: bundle.getId()) else {
|
|
2692
3118
|
return false
|
|
2693
3119
|
}
|
|
2694
|
-
|
|
3120
|
+
guard let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) else {
|
|
3121
|
+
return false
|
|
3122
|
+
}
|
|
3123
|
+
self.setCurrentBundle(bundle: bundleDir.path)
|
|
2695
3124
|
return true
|
|
2696
3125
|
}
|
|
2697
3126
|
|
|
3127
|
+
/// Points the current bundle back at `bundle` without sending stats, after an
|
|
3128
|
+
/// install whose reload failed left the WebView on it.
|
|
3129
|
+
func restoreCurrentBundle(_ bundle: BundleInfo) {
|
|
3130
|
+
if bundle.isBuiltin() {
|
|
3131
|
+
self.setCurrentBundle(bundle: "")
|
|
3132
|
+
} else {
|
|
3133
|
+
_ = self.stagePendingReload(bundle: bundle)
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
|
|
2698
3137
|
func stagePreviewFallbackReload(bundle: BundleInfo) -> Bool {
|
|
2699
3138
|
guard !bundle.isErrorStatus() else {
|
|
2700
3139
|
return false
|
|
@@ -2706,7 +3145,10 @@ import UIKit
|
|
|
2706
3145
|
guard bundleExists(id: bundle.getId()) else {
|
|
2707
3146
|
return false
|
|
2708
3147
|
}
|
|
2709
|
-
|
|
3148
|
+
guard let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) else {
|
|
3149
|
+
return false
|
|
3150
|
+
}
|
|
3151
|
+
self.setCurrentBundle(bundle: bundleDir.path)
|
|
2710
3152
|
return true
|
|
2711
3153
|
}
|
|
2712
3154
|
|
|
@@ -2792,9 +3234,16 @@ import UIKit
|
|
|
2792
3234
|
self.setBundleStatus(id: bundle.getId(), status: BundleStatus.ERROR)
|
|
2793
3235
|
}
|
|
2794
3236
|
|
|
2795
|
-
func unsetChannel(defaultChannelKey: String, configDefaultChannel: String) -> SetChannel {
|
|
3237
|
+
func unsetChannel(defaultChannelKey: String, configDefaultChannel: String, allowSetDefaultChannel: Bool) -> SetChannel {
|
|
2796
3238
|
let setChannel: SetChannel = SetChannel()
|
|
2797
3239
|
|
|
3240
|
+
if !allowSetDefaultChannel {
|
|
3241
|
+
logger.error("unsetChannel is disabled by allowSetDefaultChannel config")
|
|
3242
|
+
setChannel.message = "unsetChannel is disabled by configuration"
|
|
3243
|
+
setChannel.error = "disabled_by_config"
|
|
3244
|
+
return setChannel
|
|
3245
|
+
}
|
|
3246
|
+
|
|
2798
3247
|
// Clear persisted defaultChannel and revert to config value
|
|
2799
3248
|
UserDefaults.standard.removeObject(forKey: defaultChannelKey)
|
|
2800
3249
|
UserDefaults.standard.synchronize()
|
|
@@ -3315,24 +3764,20 @@ import UIKit
|
|
|
3315
3764
|
|
|
3316
3765
|
let operation = BlockOperation {
|
|
3317
3766
|
let semaphore = DispatchSemaphore(value: 0)
|
|
3318
|
-
self.
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
parameters: eventsToSend,
|
|
3322
|
-
encoder: JSONParameterEncoder.default,
|
|
3323
|
-
requestModifier: { $0.timeoutInterval = self.timeout }
|
|
3324
|
-
).responseData { response in
|
|
3767
|
+
self.sendJSONPost(urlString: self.statsUrl, body: {
|
|
3768
|
+
try JSONEncoder().encode(eventsToSend)
|
|
3769
|
+
}, completion: { responseData, httpResponse, responseError in
|
|
3325
3770
|
if self.abandonStoppedStatsFlush() {
|
|
3326
3771
|
semaphore.signal()
|
|
3327
3772
|
return
|
|
3328
3773
|
}
|
|
3329
|
-
if self.checkAndHandleRateLimitResponse(statusCode:
|
|
3774
|
+
if self.checkAndHandleRateLimitResponse(statusCode: httpResponse?.statusCode, data: responseData, response: httpResponse).blocked {
|
|
3330
3775
|
self.requeueStatsEvents(queuedEvents)
|
|
3331
3776
|
semaphore.signal()
|
|
3332
3777
|
return
|
|
3333
3778
|
}
|
|
3334
3779
|
|
|
3335
|
-
if let statusCode =
|
|
3780
|
+
if let statusCode = httpResponse?.statusCode, !(200...299).contains(statusCode) {
|
|
3336
3781
|
if CapgoUpdater.isTransientStatsFailure(statusCode) {
|
|
3337
3782
|
self.requeueStatsEvents(queuedEvents)
|
|
3338
3783
|
self.logger.error("Error sending stats batch")
|
|
@@ -3346,19 +3791,18 @@ import UIKit
|
|
|
3346
3791
|
return
|
|
3347
3792
|
}
|
|
3348
3793
|
|
|
3349
|
-
|
|
3350
|
-
|
|
3794
|
+
if let error = responseError {
|
|
3795
|
+
self.requeueStatsEvents(queuedEvents)
|
|
3796
|
+
self.logger.error("Error sending stats batch")
|
|
3797
|
+
self.logger.debug("Response: nil, Error: \(error.localizedDescription)")
|
|
3798
|
+
} else {
|
|
3351
3799
|
self.clearStatsInFlight()
|
|
3352
3800
|
self.logger.info("Stats batch sent successfully")
|
|
3353
3801
|
self.logger.debug("Sent \(eventsToSend.count) events")
|
|
3354
3802
|
self.runStatsCallbacks(queuedEvents)
|
|
3355
|
-
case let .failure(error):
|
|
3356
|
-
self.requeueStatsEvents(queuedEvents)
|
|
3357
|
-
self.logger.error("Error sending stats batch")
|
|
3358
|
-
self.logger.debug("Response: \(response.value?.debugDescription ?? "nil"), Error: \(error.localizedDescription)")
|
|
3359
3803
|
}
|
|
3360
3804
|
semaphore.signal()
|
|
3361
|
-
}
|
|
3805
|
+
})
|
|
3362
3806
|
semaphore.wait()
|
|
3363
3807
|
if !self.statsStopped {
|
|
3364
3808
|
self.persistStatsQueue()
|
|
@@ -3500,6 +3944,17 @@ import UIKit
|
|
|
3500
3944
|
return self.getBundleInfo(id: id)
|
|
3501
3945
|
}
|
|
3502
3946
|
|
|
3947
|
+
/// Clears the stored next bundle when it is already the running bundle, so nothing stays pending.
|
|
3948
|
+
@discardableResult
|
|
3949
|
+
public func clearNextBundleIfCurrent() -> Bool {
|
|
3950
|
+
guard let next = self.getNextBundle(), !next.isUnknown(), next.getId() == self.getCurrentBundle().getId() else {
|
|
3951
|
+
return false
|
|
3952
|
+
}
|
|
3953
|
+
logger?.info("Next bundle \(next.getId()) is already the current bundle. Clearing next.")
|
|
3954
|
+
_ = self.setNextBundle(next: Optional<String>.none)
|
|
3955
|
+
return true
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3503
3958
|
public func getPreviewFallbackBundle() -> BundleInfo? {
|
|
3504
3959
|
guard let id = UserDefaults.standard.string(forKey: self.PREVIEW_FALLBACK_VERSION) else {
|
|
3505
3960
|
return nil
|