SPB Git

Repository Public License

ResourceDownloader.swift 17.8 KB 350 lines swift

1import CryptoKit2import Diagnostics3import Foundation4#if os(macOS)5import CoreServices6#endif78public struct ResourceDownloadRequest: Sendable, Equatable {9    public var url: URL10    /// Directory the finished file is moved into. Created when missing.11    public var destinationDirectory: URL12    /// File name to use instead of the one the server proposes. Sanitised either way.13    public var filename: String?14    /// The transfer is refused or stopped beyond this size.15    public var maximumBytes: Int6416    /// Page or feature that asked for the file; recorded in the quarantine attribute on macOS.17    public var originURL: URL?1819    public init(url: URL, destinationDirectory: URL, filename: String? = nil, maximumBytes: Int64 = 2_147_483_648, originURL: URL? = nil) {20        self.url = url; self.destinationDirectory = destinationDirectory; self.filename = filename21        self.maximumBytes = max(maximumBytes, 1); self.originURL = originURL22    }23}2425public struct ResourceDownloadResult: Sendable, Equatable {26    public var fileURL: URL27    public var bytes: Int6428    /// The transfer continued a partial file with a `Range` request instead of starting over.29    public var resumed: Bool30    public var mimeType: String?31}3233public enum ResourceDownloadError: Error, Sendable, Equatable {34    case unsupportedScheme35    /// A redirect left http(s) or went from https to http.36    case insecureRedirect37    case httpStatus(Int)38    case tooLarge(limit: Int64)39    /// The server answered a range request with a range other than the one asked for.40    case rangeMismatch41    case fileSystem(String)42    case transport(String)43    case cancelled44}4546/// Downloads a file the *browser itself* needs — resources of a page archive, a capsule the user imports —47/// with `URLSession`. Page downloads never come here: they belong to WebKit and `DownloadManager`.48///49/// Only for actions the user started: there is no queue, no background session and no retry loop.50///51/// - `http` and `https` only; a redirect may not leave them nor downgrade https to http.52/// - Ephemeral session: no cookies sent or stored, no credential storage, no cache.53/// - Bytes go to a partial file in `partialsDirectory`. If the transfer stops, the next attempt for the same54///   URL sends `Range: bytes=N-` with `If-Range: <ETag or Last-Modified>` and appends on `206`; a `200` means55///   the resource changed or ranges are unsupported and the transfer starts over. Without a validator from56///   the first response the partial file is never trusted.57/// - The finished file is moved into the destination directory under a sanitised, unique name58///   (`DownloadFilename`), and on macOS marked with the quarantine attribute, like a browser download.59public final class ResourceDownloader: Sendable {60    public typealias Progress = @Sendable (_ bytesReceived: Int64, _ totalBytes: Int64?) -> Void6162    private let configuration: URLSessionConfiguration63    private let partialsDirectory: URL6465    /// - Parameter protocolClasses: test hook (a stub `URLProtocol`); production code passes nothing.66    public init(partialsDirectory: URL? = nil, timeout: TimeInterval = 60, protocolClasses: [AnyClass]? = nil) {67        let configuration = URLSessionConfiguration.ephemeral68        configuration.httpCookieStorage = nil69        configuration.httpShouldSetCookies = false70        configuration.urlCredentialStorage = nil71        configuration.urlCache = nil72        configuration.requestCachePolicy = .reloadIgnoringLocalCacheData73        configuration.timeoutIntervalForRequest = timeout74        configuration.waitsForConnectivity = false75        if let protocolClasses { configuration.protocolClasses = protocolClasses }76        self.configuration = configuration77        self.partialsDirectory = partialsDirectory78            ?? FileManager.default.temporaryDirectory.appending(path: "orix-navigator-partials", directoryHint: .isDirectory)79    }8081    struct PartialMetadata: Codable, Equatable {82        var url: String83        var validator: String84        var totalBytes: Int64?85    }8687    func partialURLs(for url: URL) -> (data: URL, metadata: URL) {88        let digest = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined()89        return (partialsDirectory.appending(path: digest + ".part"), partialsDirectory.appending(path: digest + ".json"))90    }9192    /// Removes the partial file kept for a URL (the user gave up on it).93    public func discardPartial(for url: URL) {94        let files = partialURLs(for: url)95        try? FileManager.default.removeItem(at: files.data)96        try? FileManager.default.removeItem(at: files.metadata)97    }9899    public func download(_ request: ResourceDownloadRequest, progress: Progress? = nil) async throws -> ResourceDownloadResult {100        guard let scheme = request.url.scheme?.lowercased(), scheme == "http" || scheme == "https" else {101            throw ResourceDownloadError.unsupportedScheme102        }103        let files = partialURLs(for: request.url)104        do {105            try FileManager.default.createDirectory(at: partialsDirectory, withIntermediateDirectories: true)106        } catch { throw ResourceDownloadError.fileSystem("cannot create the partial files directory") }107108        // Resume only with a validator and a non-empty partial file that match this URL.109        var offset: Int64 = 0110        var validator: String?111        if let data = try? Data(contentsOf: files.metadata), let metadata = try? JSONDecoder().decode(PartialMetadata.self, from: data),112           metadata.url == request.url.absoluteString, !metadata.validator.isEmpty,113           let size = (try? FileManager.default.attributesOfItem(atPath: files.data.path(percentEncoded: false))[.size] as? NSNumber)?.int64Value,114           size > 0 {115            offset = size116            validator = metadata.validator117        } else {118            discardPartial(for: request.url)119        }120121        var attempt = try await run(request, files: files, offset: offset, validator: validator, progress: progress)122        if attempt.restartFromZero {123            // 416: the partial file does not match what the server has now.124            discardPartial(for: request.url)125            attempt = try await run(request, files: files, offset: 0, validator: nil, progress: progress)126            if attempt.restartFromZero { throw ResourceDownloadError.httpStatus(416) }127        }128129        let derived = DownloadFilename.derive(contentDisposition: attempt.contentDisposition, suggested: request.filename,130                                              url: attempt.finalURL ?? request.url, mimeType: attempt.mimeType)131        // An explicit name from the caller wins over the server's header.132        let name = request.filename.flatMap(DownloadFilename.sanitize) ?? derived.name133        do {134            try FileManager.default.createDirectory(at: request.destinationDirectory, withIntermediateDirectories: true)135            let destination = DownloadFilename.uniqueURL(in: request.destinationDirectory, filename: name) {136                FileManager.default.fileExists(atPath: $0.path(percentEncoded: false))137            }138            try FileManager.default.moveItem(at: files.data, to: destination)139            try? FileManager.default.removeItem(at: files.metadata)140            Self.markQuarantined(destination, source: request.url, origin: request.originURL)141            return ResourceDownloadResult(fileURL: destination, bytes: attempt.bytes, resumed: attempt.resumed, mimeType: attempt.mimeType)142        } catch {143            throw ResourceDownloadError.fileSystem("cannot move the downloaded file into place")144        }145    }146147    private struct Attempt {148        var bytes: Int64 = 0149        var resumed = false150        var restartFromZero = false151        var mimeType: String?152        var contentDisposition: String?153        var finalURL: URL?154    }155156    private func run(_ request: ResourceDownloadRequest, files: (data: URL, metadata: URL), offset: Int64, validator: String?,157                     progress: Progress?) async throws -> Attempt {158        var urlRequest = URLRequest(url: request.url)159        urlRequest.httpShouldHandleCookies = false160        if offset > 0, let validator {161            urlRequest.setValue("bytes=\(offset)-", forHTTPHeaderField: "Range")162            urlRequest.setValue(validator, forHTTPHeaderField: "If-Range")163        }164        // The compressed length is what Range counts: ask for the raw bytes so offsets mean the same thing.165        urlRequest.setValue("identity", forHTTPHeaderField: "Accept-Encoding")166167        let transfer = Transfer(request: request, files: files, offset: offset, progress: progress)168        let session = URLSession(configuration: configuration, delegate: transfer, delegateQueue: nil)169        defer { session.finishTasksAndInvalidate() }170        let task = session.dataTask(with: urlRequest)171        return try await withTaskCancellationHandler {172            try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Attempt, any Error>) in173                transfer.start(continuation)174                task.resume()175            }176        } onCancel: {177            task.cancel()178        }179    }180181    /// Marks a file as downloaded from the internet (macOS quarantine), so Gatekeeper treats it like a file182    /// saved by a browser. On iOS there is no such attribute. Failures are logged, not fatal.183    static func markQuarantined(_ file: URL, source: URL, origin: URL?) {184        #if os(macOS)185        var properties: [String: Any] = [186            kLSQuarantineTypeKey as String: kLSQuarantineTypeWebDownload as String,187            kLSQuarantineDataURLKey as String: source,188            kLSQuarantineAgentNameKey as String: "ORIX Navigator",189        ]190        if let origin { properties[kLSQuarantineOriginURLKey as String] = origin }191        var values = URLResourceValues()192        values.quarantineProperties = properties193        var url = file194        do { try url.setResourceValues(values) } catch {195            Log.downloads.error("Could not set the quarantine attribute: \(String(describing: error), privacy: .public)")196        }197        #endif198    }199200    /// Whether a file carries the macOS quarantine attribute. Always `false` on other systems.201    public static func isQuarantined(_ file: URL) -> Bool {202        #if os(macOS)203        return (try? file.resourceValues(forKeys: [.quarantinePropertiesKey]).quarantineProperties) != nil204        #else205        return false206        #endif207    }208209    // MARK: Transfer210211    /// Delegate of one transfer. URLSession calls it on its own serial queue; the lock only protects the212    /// hand-over of the continuation with the cancellation path.213    private final class Transfer: NSObject, URLSessionDataDelegate, @unchecked Sendable {214        private let request: ResourceDownloadRequest215        private let files: (data: URL, metadata: URL)216        private let offset: Int64217        private let progress: Progress?218        private let lock = NSLock()219        private var continuation: CheckedContinuation<Attempt, any Error>?220        private var attempt = Attempt()221        private var handle: FileHandle?222        private var total: Int64?223        private var failure: ResourceDownloadError?224225        init(request: ResourceDownloadRequest, files: (data: URL, metadata: URL), offset: Int64, progress: Progress?) {226            self.request = request; self.files = files; self.offset = offset; self.progress = progress227        }228229        func start(_ continuation: CheckedContinuation<Attempt, any Error>) { lock.withLock { self.continuation = continuation } }230231        private func finish(_ result: Result<Attempt, any Error>) {232            try? handle?.close()233            handle = nil234            let continuation = lock.withLock { () -> CheckedContinuation<Attempt, any Error>? in235                defer { self.continuation = nil }236                return self.continuation237            }238            continuation?.resume(with: result)239        }240241        func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,242                        newRequest: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {243            let from = response.url?.scheme?.lowercased(), to = newRequest.url?.scheme?.lowercased()244            guard to == "https" || (to == "http" && from == "http") else {245                failure = .insecureRedirect246                completionHandler(nil)247                task.cancel()248                return249            }250            completionHandler(newRequest)251        }252253        func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,254                        completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {255            guard let http = response as? HTTPURLResponse else {256                failure = .transport("not an HTTP response")257                return completionHandler(.cancel)258            }259            attempt.mimeType = http.mimeType260            attempt.contentDisposition = http.value(forHTTPHeaderField: "Content-Disposition")261            attempt.finalURL = http.url262            let manager = FileManager.default263            let path = files.data.path(percentEncoded: false)264            do {265                switch http.statusCode {266                case 206 where offset > 0:267                    // "bytes 100-199/200": the range must start exactly where the partial file ends.268                    let range = http.value(forHTTPHeaderField: "Content-Range") ?? ""269                    let pieces = range.replacingOccurrences(of: "bytes", with: "").trimmingCharacters(in: .whitespaces).split(separator: "/")270                    guard let first = pieces.first?.split(separator: "-").first, Int64(first) == offset else {271                        failure = .rangeMismatch272                        return completionHandler(.cancel)273                    }274                    total = pieces.count == 2 ? Int64(pieces[1]) : nil275                    attempt.resumed = true276                    attempt.bytes = offset277                    let handle = try FileHandle(forWritingTo: files.data)278                    try handle.seekToEnd()279                    self.handle = handle280                case 200:281                    total = http.expectedContentLength > 0 ? http.expectedContentLength : nil282                    attempt.resumed = false283                    attempt.bytes = 0284                    if manager.fileExists(atPath: path) { try manager.removeItem(atPath: path) }285                    guard manager.createFile(atPath: path, contents: nil) else { throw ResourceDownloadError.fileSystem("cannot create the partial file") }286                    handle = try FileHandle(forWritingTo: files.data)287                    // Remember how to resume: only a strong ETag or a Last-Modified date can validate a range.288                    try? manager.removeItem(at: files.metadata)289                    let etag = http.value(forHTTPHeaderField: "ETag").flatMap { $0.hasPrefix("W/") ? nil : $0 }290                    if let validator = etag ?? http.value(forHTTPHeaderField: "Last-Modified"),291                       (http.value(forHTTPHeaderField: "Accept-Ranges") ?? "").lowercased() != "none" {292                        let metadata = PartialMetadata(url: request.url.absoluteString, validator: validator, totalBytes: total)293                        try? JSONEncoder().encode(metadata).write(to: files.metadata, options: .atomic)294                    }295                case 416 where offset > 0:296                    attempt.restartFromZero = true297                    return completionHandler(.cancel)298                default:299                    failure = .httpStatus(http.statusCode)300                    return completionHandler(.cancel)301                }302            } catch {303                failure = (error as? ResourceDownloadError) ?? .fileSystem("cannot open the partial file")304                return completionHandler(.cancel)305            }306            if let total, total > request.maximumBytes {307                failure = .tooLarge(limit: request.maximumBytes)308                return completionHandler(.cancel)309            }310            progress?(attempt.bytes, total)311            completionHandler(.allow)312        }313314        func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {315            guard failure == nil, let handle else { return }316            attempt.bytes += Int64(data.count)317            guard attempt.bytes <= request.maximumBytes else {318                failure = .tooLarge(limit: request.maximumBytes)319                dataTask.cancel()320                return321            }322            do { try handle.write(contentsOf: data) } catch {323                failure = .fileSystem("cannot write the partial file")324                dataTask.cancel()325                return326            }327            progress?(attempt.bytes, total)328        }329330        func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {331            if attempt.restartFromZero { return finish(.success(attempt)) }332            if let failure {333                // A file that grew past the limit or failed a check is not worth resuming.334                if case .tooLarge = failure { try? FileManager.default.removeItem(at: files.data); try? FileManager.default.removeItem(at: files.metadata) }335                return finish(.failure(failure))336            }337            if let error {338                let nsError = error as NSError339                if nsError.domain == NSURLErrorDomain, nsError.code == NSURLErrorCancelled { return finish(.failure(ResourceDownloadError.cancelled)) }340                // The partial file and its metadata stay: the next attempt resumes.341                return finish(.failure(ResourceDownloadError.transport(nsError.localizedDescription)))342            }343            if let total, attempt.bytes != total {344                return finish(.failure(ResourceDownloadError.transport("connection closed after \(attempt.bytes) of \(total) bytes")))345            }346            finish(.success(attempt))347        }348    }349}350
Files main
Menu

Theme