SPB Git

Repository Public License

DownloadFilename.swift 17.6 KB 324 lines swift

1import Foundation2import UniformTypeIdentifiers34// MARK: - Content-Disposition56/// The file name parameters of a `Content-Disposition` header (RFC 6266), with `filename*` decoded per RFC 5987.7public struct ContentDisposition: Sendable, Equatable {8    public enum Kind: String, Sendable { case inline, attachment, other }910    public var kind: Kind11    /// `filename` parameter, unquoted and unescaped. Untrusted.12    public var filename: String?13    /// `filename*` parameter, charset-decoded. `nil` when absent or not decodable. Untrusted.14    public var extendedFilename: String?1516    /// The name a client should use: RFC 6266 §4.3 says `filename*` wins when both are present.17    public var preferredFilename: String? {18        if let extendedFilename, !extendedFilename.isEmpty { return extendedFilename }19        if let filename, !filename.isEmpty { return filename }20        return nil21    }2223    /// Parses a header value. Tolerant of what servers really send: missing quotes, stray whitespace, a24    /// trailing `;`, parameters in any order and case. Returns `nil` for an empty value.25    public static func parse(_ header: String) -> ContentDisposition? {26        let scalars = Array(header.unicodeScalars)27        var index = 028        func skipSpaces() { while index < scalars.count, scalars[index] == " " || scalars[index] == "\t" { index += 1 } }29        func readToken(stoppingAt stops: Set<Unicode.Scalar>) -> String {30            var result = String.UnicodeScalarView()31            while index < scalars.count, !stops.contains(scalars[index]) { result.append(scalars[index]); index += 1 }32            return String(result).trimmingCharacters(in: .whitespaces)33        }34        func readQuoted() -> String {35            var result = String.UnicodeScalarView()36            index += 1   // opening quote37            while index < scalars.count, scalars[index] != "\"" {38                // quoted-pair: a backslash escapes the next character. Many servers send Windows paths39                // unescaped; treating `\x` as `x` loses the separator, which the sanitiser would drop anyway.40                if scalars[index] == "\\", index + 1 < scalars.count { index += 1 }41                result.append(scalars[index])42                index += 143            }44            if index < scalars.count { index += 1 }   // closing quote45            return String(result)46        }4748        skipSpaces()49        let type = readToken(stoppingAt: [";"]).lowercased()50        guard !type.isEmpty || index < scalars.count else { return nil }51        var result = ContentDisposition(kind: Kind(rawValue: type) ?? .other, filename: nil, extendedFilename: nil)52        while index < scalars.count {53            if scalars[index] == ";" { index += 1 }54            skipSpaces()55            let name = readToken(stoppingAt: ["=", ";"]).lowercased()56            guard index < scalars.count, scalars[index] == "=" else { continue }57            index += 158            skipSpaces()59            let value = index < scalars.count && scalars[index] == "\"" ? readQuoted() : readToken(stoppingAt: [";"])60            switch name {61            case "filename" where result.filename == nil: result.filename = value62            case "filename*" where result.extendedFilename == nil: result.extendedFilename = decodeExtendedValue(value)63            default: break64            }65            // Skip anything left before the next parameter.66            while index < scalars.count, scalars[index] != ";" { index += 1 }67        }68        return result69    }7071    /// RFC 5987 `ext-value`: `charset'[language]'percent-encoded`. UTF-8 and ISO-8859-1 are the two charsets the72    /// RFC requires; anything else, a bad escape or bytes invalid for the charset give `nil`.73    static func decodeExtendedValue(_ value: String) -> String? {74        let parts = value.split(separator: "'", maxSplits: 2, omittingEmptySubsequences: false)75        guard parts.count == 3 else { return nil }76        let charset = parts[0].lowercased()77        var bytes: [UInt8] = []78        var iterator = parts[2].utf8.makeIterator()79        while let byte = iterator.next() {80            if byte == UInt8(ascii: "%") {81                guard let high = iterator.next().flatMap(hexValue), let low = iterator.next().flatMap(hexValue) else { return nil }82                bytes.append(high << 4 | low)83            } else {84                guard byte < 0x80 else { return nil }85                bytes.append(byte)86            }87        }88        switch charset {89        case "utf-8", "utf8": return String(validatingUTF8Bytes: bytes)90        case "iso-8859-1", "latin1": return String(bytes: bytes, encoding: .isoLatin1)91        default: return nil92        }93    }9495    private static func hexValue(_ byte: UInt8) -> UInt8? {96        switch byte {97        case UInt8(ascii: "0")...UInt8(ascii: "9"): byte - UInt8(ascii: "0")98        case UInt8(ascii: "a")...UInt8(ascii: "f"): byte - UInt8(ascii: "a") + 1099        case UInt8(ascii: "A")...UInt8(ascii: "F"): byte - UInt8(ascii: "A") + 10100        default: nil101        }102    }103}104105private extension String {106    /// Strict UTF-8 decoding: `nil` instead of replacement characters.107    init?(validatingUTF8Bytes bytes: [UInt8]) {108        guard let text = String(validating: bytes, as: UTF8.self) else { return nil }109        self = text110    }111}112113// MARK: - File names114115/// Where a proposed name came from. Names stated by the server are kept as stated (after sanitising); a name116/// that is only the last path component of the URL may have its extension corrected from the MIME type.117public enum FilenameSource: Sendable, Equatable { case contentDisposition, suggested, url, fallback }118119public struct DerivedFilename: Sendable, Equatable {120    public var name: String121    public var source: FilenameSource122}123124/// Safe file names for downloads. Every input — header, URL, MIME type, WebKit's suggestion — is untrusted.125public enum DownloadFilename {126    /// Longest name produced, in UTF-8 bytes. APFS and HFS+ allow 255; the margin leaves room for the127    /// ` (2)` uniqueness suffix and for a temporary suffix a download layer may append while writing.128    public static let maximumBytes = 200129    public static let maximumExtensionBytes = 20130    public static let defaultName = "download"131132    /// Device names Windows reserves, with or without an extension. Harmless on Apple systems, but a file the133    /// user later copies to a Windows volume or shares must not be unopenable or dangerous there.134    static let reservedNames: Set<String> = {135        var names: Set<String> = ["con", "prn", "aux", "nul"]136        for index in 1...9 { names.insert("com\(index)"); names.insert("lpt\(index)") }137        return names138    }()139140    /// Extensions that only make sense together with the one before them.141    static let compoundSuffixes: Set<String> = ["gz", "bz2", "xz", "zst", "lz", "z", "br"]142    /// Extensions a server-side script leaves in a URL: they say how the page was produced, not what the file is.143    static let serverSideExtensions: Set<String> = ["php", "php3", "php4", "php5", "phtml", "asp", "aspx", "ashx", "jsp", "jspx",144                                                    "cgi", "do", "action", "cfm", "html", "htm"]145    static let genericMIMETypes: Set<String> = ["", "application/octet-stream", "binary/octet-stream", "application/force-download",146                                                "application/x-download", "application/download", "application/unknown",147                                                "application/x-unknown", "unknown/unknown"]148149    // MARK: Sanitising150151    /// Makes one path component out of arbitrary text. Returns `nil` when nothing usable is left.152    ///153    /// 1. Unicode NFC.154    /// 2. Control characters (NUL included), format characters (bidirectional overrides such as U+202E,155    ///    zero-width characters, the BOM, soft hyphens) and line / paragraph separators are removed.156    /// 3. Only the last path component is kept, `/` and `\` both being separators: `../../etc/passwd` → `passwd`.157    /// 4. `: * ? " < > |` become `_`; every kind of white space becomes a plain space; runs collapse.158    /// 5. Leading dots and spaces are removed (no hidden file, no `..`), trailing dots and spaces too.159    /// 6. A Windows reserved device name gets a leading `_`.160    /// 7. The result is capped at `maximumBytes` UTF-8 bytes, keeping the extension.161    public static func sanitize(_ raw: String) -> String? {162        var scalars = String.UnicodeScalarView()163        for scalar in raw.precomposedStringWithCanonicalMapping.unicodeScalars {164            switch scalar.properties.generalCategory {165            case .control, .format, .lineSeparator, .paragraphSeparator, .surrogate, .unassigned: continue166            case .spaceSeparator: scalars.append(" ")167            default:168                // Variation selectors and tag characters are "marks"/"format" in practice: invisible.169                if (0xE0000...0xE0FFF).contains(scalar.value) { continue }170                scalars.append(scalar == "\\" ? "/" : scalar)171            }172        }173        let component = String(scalars).split(separator: "/", omittingEmptySubsequences: true).last.map(String.init) ?? ""174        var name = ""175        var previousWasSpace = false176        for character in component {177            let mapped: Character = ":*?\"<>|".contains(character) ? "_" : character178            if mapped == " " {179                if previousWasSpace { continue }180                previousWasSpace = true181            } else {182                previousWasSpace = false183            }184            name.append(mapped)185        }186        while let first = name.first, first == "." || first == " " { name.removeFirst() }187        while let last = name.last, last == "." || last == " " { name.removeLast() }188        guard !name.isEmpty else { return nil }189        // "a .pdf" → "a.pdf": no space may sit between the stem and its extension.190        var (stem, ext) = split(name)191        while stem.last == " " || stem.last == "." { stem.removeLast() }192        guard !stem.isEmpty else { return ext.isEmpty ? nil : truncate(stem: ext, ext: "") }193        if reservedNames.contains(stem.lowercased()) || reservedNames.contains(String(stem.prefix { $0 != "." }).lowercased()) {194            stem = "_" + stem195        }196        return truncate(stem: stem, ext: ext)197    }198199    /// Splits a name into stem and extension (without the dot). `archive.tar.gz` → (`archive`, `tar.gz`).200    /// An "extension" longer than `maximumExtensionBytes` or containing anything but letters, digits, `_`, `-`201    /// and `+` is not one: the whole name is the stem.202    public static func split(_ name: String) -> (stem: String, ext: String) {203        func isExtension(_ text: Substring) -> Bool {204            !text.isEmpty && text.utf8.count <= maximumExtensionBytes205                && text.unicodeScalars.allSatisfy { ($0.isASCII && ($0.properties.isAlphabetic || ("0"..."9").contains($0))) || "_-+".unicodeScalars.contains($0) }206        }207        guard let dot = name.lastIndex(of: "."), dot != name.startIndex else { return (name, "") }208        let last = name[name.index(after: dot)...]209        guard isExtension(last) else { return (name, "") }210        var stem = name[..<dot]211        var ext = String(last)212        if compoundSuffixes.contains(ext.lowercased()), let inner = stem.lastIndex(of: "."), inner != stem.startIndex {213            let middle = stem[stem.index(after: inner)...]214            if middle.lowercased() == "tar" {215                ext = middle + "." + ext216                stem = stem[..<inner]217            }218        }219        return (String(stem), ext)220    }221222    private static func truncate(stem: String, ext: String) -> String {223        let suffix = ext.isEmpty ? "" : "." + ext224        var stem = stem225        let budget = max(maximumBytes - suffix.utf8.count, 1)226        // Whole characters only: never cut a grapheme (an emoji, a letter with its accents) in two.227        while stem.utf8.count > budget { stem.removeLast() }228        while stem.last == " " || stem.last == "." { stem.removeLast() }229        return (stem.isEmpty ? "_" : stem) + suffix230    }231232    // MARK: Deriving233234    static func normalizedMIMEType(_ mimeType: String?) -> String {235        (mimeType ?? "").split(separator: ";").first.map { $0.trimmingCharacters(in: .whitespaces).lowercased() } ?? ""236    }237238    /// The file name for a download.239    ///240    /// Candidates, first usable one wins: `Content-Disposition` (`filename*` before `filename`), the name241    /// suggested by the web layer, the last path component of the URL (percent-decoded), `fallback`.242    /// Then the extension is reconciled with the MIME type through `UTType`:243    /// - no extension and a specific MIME type → the type's preferred extension is appended;244    /// - an extension the system does not know and a specific MIME type → the type's extension is appended245    ///   (`report.final` + `application/pdf` → `report.final.pdf`);246    /// - a name taken from the URL whose extension is a server-side one (`download.php`, `view.aspx`,247    ///   `page.html`) and a MIME type that says otherwise → the extension is replaced (`download.pdf`);248    /// - in every other case the name stays as stated: the extension is what the system will use to open the249    ///   file, so it is never silently changed. A conflict between extension and MIME type is a matter for250    ///   `DownloadRisk`, not for renaming.251    public static func derive(contentDisposition: String? = nil, suggested: String? = nil, url: URL?,252                              mimeType: String? = nil, fallback: String = defaultName) -> DerivedFilename {253        var chosen: DerivedFilename?254        if let header = contentDisposition, let name = ContentDisposition.parse(header)?.preferredFilename.flatMap(sanitize) {255            chosen = DerivedFilename(name: name, source: .contentDisposition)256        }257        if chosen == nil, let name = suggested.flatMap(sanitize) { chosen = DerivedFilename(name: name, source: .suggested) }258        if chosen == nil, let url {259            let component = url.path(percentEncoded: true).split(separator: "/", omittingEmptySubsequences: true).last.map(String.init) ?? ""260            let decoded = component.removingPercentEncoding ?? component261            if let name = sanitize(decoded) { chosen = DerivedFilename(name: name, source: .url) }262        }263        var result = chosen ?? DerivedFilename(name: sanitize(fallback) ?? defaultName, source: .fallback)264265        let mime = normalizedMIMEType(mimeType)266        guard !genericMIMETypes.contains(mime), let type = UTType(mimeType: mime), !type.isDynamic,267              let preferred = type.preferredFilenameExtension else { return result }268        let (stem, ext) = split(result.name)269        if ext.isEmpty {270            result.name = sanitize(result.name + "." + preferred) ?? result.name271            return result272        }273        let lastExtension = ext.split(separator: ".").last.map(String.init) ?? ext274        let extensionType = UTType(filenameExtension: lastExtension)275        let isKnown = extensionType.map { !$0.isDynamic } ?? false276        let agrees = extensionType.map { $0.conforms(to: type) || type.conforms(to: $0) } ?? false277        if result.source == .url || result.source == .fallback, serverSideExtensions.contains(lastExtension.lowercased()), !(isKnown && agrees) {278            result.name = sanitize(stem + "." + preferred) ?? result.name279        } else if !isKnown {280            result.name = sanitize(result.name + "." + preferred) ?? result.name281        }282        return result283    }284285    // MARK: Destination286287    /// `name (2).ext`, `name (3).ext`… for the n-th attempt (n ≥ 2). Compound extensions stay whole.288    public static func numbered(_ name: String, attempt: Int) -> String {289        guard attempt >= 2 else { return name }290        let (stem, ext) = split(name)291        let suffix = " (\(attempt))"292        var shortened = stem293        let budget = maximumBytes - suffix.utf8.count - (ext.isEmpty ? 0 : ext.utf8.count + 1)294        while shortened.utf8.count > max(budget, 1) { shortened.removeLast() }295        return shortened + suffix + (ext.isEmpty ? "" : "." + ext)296    }297298    /// Whether `file` is a direct child of `directory` (after resolving `.` and `..`, without following299    /// symbolic links: the name was just built, the link target does not exist yet).300    public static func isDirectChild(_ file: URL, of directory: URL) -> Bool {301        let parent = directory.standardizedFileURL.path(percentEncoded: false)302        let child = file.standardizedFileURL.path(percentEncoded: false)303        let prefix = parent.hasSuffix("/") ? parent : parent + "/"304        guard child.hasPrefix(prefix) else { return false }305        let rest = child.dropFirst(prefix.count)306        return !rest.isEmpty && !rest.contains("/") && rest != "." && rest != ".."307    }308309    /// A URL inside `directory` for `filename` that is not taken. `filename` is sanitised again, so the310    /// result can never leave the directory whatever the caller passes. `isTaken` reports existing files and311    /// names reserved by transfers in progress (compare case-insensitively: the default file system is).312    public static func uniqueURL(in directory: URL, filename: String, isTaken: (URL) -> Bool) -> URL {313        let safe = sanitize(filename) ?? defaultName314        for attempt in 1...9_999 {315            let candidate = directory.appending(path: numbered(safe, attempt: attempt), directoryHint: .notDirectory)316            guard isDirectChild(candidate, of: directory) else { break }317            if !isTaken(candidate) { return candidate }318        }319        // Ten thousand files with the same name, or a name that escaped: fall back to a unique neutral name.320        let (_, ext) = split(safe)321        return directory.appending(path: "\(defaultName)-\(UUID().uuidString)" + (ext.isEmpty ? "" : "." + ext), directoryHint: .notDirectory)322    }323}324
Files main
Menu

Theme