SPB Git

Repository Public

SSHConfigParser.swift 12.6 KB 307 lines swift

1import Foundation23/// Effective options of one concrete host alias found in an OpenSSH client config.4public struct SSHConfigHost: Sendable, Hashable, Codable {5    /// The alias as written on a `Host` line (or the name passed to ``SSHConfig/resolve(_:)``).6    public var alias: String7    /// `HostName`, if any.8    public var hostName: String?9    /// `User`, if any.10    public var user: String?11    /// `Port`, if any and valid (1–65535).12    public var port: Int?13    /// `ProxyJump`, if any.14    public var proxyJump: String?15    /// `IdentityFile` paths exactly as written (never opened or expanded).16    public var identityFiles: [String]17    /// `ForwardAgent`: `yes`/`no`; any other value (socket path, `$VAR`) is reported as `true`.18    public var forwardAgent: Bool?1920    public init(21        alias: String,22        hostName: String? = nil,23        user: String? = nil,24        port: Int? = nil,25        proxyJump: String? = nil,26        identityFiles: [String] = [],27        forwardAgent: Bool? = nil28    ) {29        self.alias = alias30        self.hostName = hostName31        self.user = user32        self.port = port33        self.proxyJump = proxyJump34        self.identityFiles = identityFiles35        self.forwardAgent = forwardAgent36    }37}3839/// File access used by ``SSHConfigParser`` for `Include`; injectable so tests need no disk.40public struct SSHConfigFileSystem: Sendable {41    /// Returns the text of the file at an absolute path, or `nil` when it cannot be read.42    public var read: @Sendable (String) -> String?43    /// Expands an absolute glob pattern into the matching paths, sorted.44    public var glob: @Sendable (String) -> [String]4546    public init(read: @escaping @Sendable (String) -> String?, glob: @escaping @Sendable (String) -> [String]) {47        self.read = read48        self.glob = glob49    }5051    /// Reads real files (UTF-8) and expands globs with `glob(3)`.52    public static let live = SSHConfigFileSystem(53        read: { path in try? String(contentsOfFile: path, encoding: .utf8) },54        glob: { pattern in55            var result = glob_t()56            defer { globfree(&result) }57            guard Darwin.glob(pattern, 0, nil, &result) == 0, let paths = result.gl_pathv else { return [] }58            return (0..<Int(result.gl_pathc)).compactMap { paths[$0].map { String(cString: $0) } }59        }60    )6162    /// A file system backed by a dictionary of absolute path → contents (`*`/`?` never cross `/`).63    public static func inMemory(_ files: [String: String]) -> SSHConfigFileSystem {64        SSHConfigFileSystem(65            read: { files[$0] },66            glob: { pattern in67                let wanted = pattern.split(separator: "/", omittingEmptySubsequences: false).map(String.init)68                return files.keys.filter { path in69                    let parts = path.split(separator: "/", omittingEmptySubsequences: false).map(String.init)70                    return parts.count == wanted.count71                        && zip(wanted, parts).allSatisfy { SSHWildcard.matches(pattern: $0, text: $1) }72                }.sorted()73            }74        )75    }76}7778/// A parsed OpenSSH client configuration.79public struct SSHConfig: Sendable, Hashable {80    enum Condition: Sendable, Hashable {81        case always82        case never83        case hosts([HostPattern])8485        func matches(_ host: String) -> Bool {86            switch self {87            case .always: return true88            case .never: return false89            case .hosts(let patterns):90                var positive = false91                for pattern in patterns where SSHWildcard.matches(pattern: pattern.text, text: host) {92                    if pattern.negated { return false }93                    positive = true94                }95                return positive96            }97        }98    }99100    struct HostPattern: Sendable, Hashable {101        var negated: Bool102        var text: String103    }104105    struct Directive: Sendable, Hashable {106        var condition: Condition107        var keyword: String108        var arguments: [String]109    }110111    var directives: [Directive]112113    /// Concrete aliases (patterns without wildcards or negation), in order of first appearance.114    public internal(set) var aliases: [String]115116    /// Every concrete alias with its effective options.117    public var hosts: [SSHConfigHost] { aliases.map(resolve) }118119    /// Effective options for any host name, using OpenSSH's first-obtained-value-wins rule.120    public func resolve(_ host: String) -> SSHConfigHost {121        var result = SSHConfigHost(alias: host)122        for directive in directives where directive.condition.matches(host) {123            guard let value = directive.arguments.first else { continue }124            switch directive.keyword {125            case "hostname": if result.hostName == nil { result.hostName = value }126            case "user": if result.user == nil { result.user = value }127            case "port":128                if result.port == nil, let port = Int(value), (1...65535).contains(port) { result.port = port }129            case "proxyjump": if result.proxyJump == nil { result.proxyJump = value }130            case "identityfile":131                if !result.identityFiles.contains(value) { result.identityFiles.append(value) }132            case "forwardagent":133                if result.forwardAgent == nil {134                    switch value.lowercased() {135                    case "no", "false": result.forwardAgent = false136                    default: result.forwardAgent = true137                    }138                }139            default: break140            }141        }142        return result143    }144}145146/// Parses OpenSSH client configuration text (`~/.ssh/config`). Never reads key material.147public struct SSHConfigParser: Sendable {148    /// File access used for `Include`.149    public var fileSystem: SSHConfigFileSystem150    /// Directory substituted for a leading `~`.151    public var homeDirectory: String152    /// Maximum `Include` nesting (OpenSSH uses 16).153    public var maxIncludeDepth: Int154155    public init(156        fileSystem: SSHConfigFileSystem = .live,157        homeDirectory: String = NSHomeDirectory(),158        maxIncludeDepth: Int = 16159    ) {160        self.fileSystem = fileSystem161        self.homeDirectory = homeDirectory162        self.maxIncludeDepth = maxIncludeDepth163    }164165    /// Parses config text. Relative `Include` paths resolve against `configDirectory`.166    public func parse(_ text: String, configDirectory: String = "~/.ssh") -> SSHConfig {167        var config = SSHConfig(directives: [], aliases: [])168        var condition = SSHConfig.Condition.always169        parse(text, baseDirectory: expandTilde(configDirectory), depth: 0, condition: &condition, into: &config)170        return config171    }172173    /// Parses the config file at `path`; a missing or unreadable file yields an empty config.174    public func parseFile(at path: String = "~/.ssh/config") -> SSHConfig {175        let absolute = expandTilde(path)176        let directory = (absolute as NSString).deletingLastPathComponent177        return parse(fileSystem.read(absolute) ?? "", configDirectory: directory)178    }179180    static let keptKeywords: Set<String> = ["hostname", "user", "port", "proxyjump", "identityfile", "forwardagent"]181182    private func parse(183        _ text: String,184        baseDirectory: String,185        depth: Int,186        condition: inout SSHConfig.Condition,187        into config: inout SSHConfig188    ) {189        for line in text.split(omittingEmptySubsequences: true, whereSeparator: \.isNewline) {190            guard let (keyword, rest) = Self.splitKeyword(line) else { continue }191            let arguments = Self.tokenize(rest)192            switch keyword {193            case "host":194                let patterns = arguments.map { argument -> SSHConfig.HostPattern in195                    argument.hasPrefix("!")196                        ? .init(negated: true, text: String(argument.dropFirst()))197                        : .init(negated: false, text: argument)198                }199                condition = .hosts(patterns)200                for pattern in patterns where !pattern.negated && !pattern.text.isEmpty {201                    if pattern.text.contains("*") || pattern.text.contains("?") { continue }202                    if !config.aliases.contains(pattern.text) { config.aliases.append(pattern.text) }203                }204            case "match":205                // Only the unconditional `Match all` is evaluated; every other Match block is skipped.206                let isAll = arguments.count == 1 && arguments[0].lowercased() == "all"207                condition = isAll ? .always : .never208            case "include":209                guard depth < maxIncludeDepth else { continue }210                for argument in arguments where !argument.isEmpty {211                    var path = expandTilde(argument)212                    if !path.hasPrefix("/") { path = baseDirectory + "/" + path }213                    let isGlob = path.contains("*") || path.contains("?") || path.contains("[")214                    for file in isGlob ? fileSystem.glob(path) : [path] {215                        guard let included = fileSystem.read(file) else { continue }216                        // Host/Match blocks of an included file never leak into the including file.217                        let saved = condition218                        parse(included, baseDirectory: baseDirectory, depth: depth + 1, condition: &condition, into: &config)219                        condition = saved220                    }221                }222            default:223                guard Self.keptKeywords.contains(keyword), !arguments.isEmpty else { continue }224                config.directives.append(.init(condition: condition, keyword: keyword, arguments: arguments))225            }226        }227    }228229    private func expandTilde(_ path: String) -> String {230        if path == "~" { return homeDirectory }231        if path.hasPrefix("~/") { return homeDirectory + path.dropFirst(1) }232        return path233    }234235    /// Splits `Keyword value`, `Keyword=value` or `Keyword = value`; `nil` for blank and comment lines.236    static func splitKeyword(_ line: Substring) -> (keyword: String, rest: Substring)? {237        let trimmed = line.drop(while: \.isWhitespace)238        guard let first = trimmed.first, first != "#" else { return nil }239        let keyword = trimmed.prefix { !$0.isWhitespace && $0 != "=" }240        guard !keyword.isEmpty else { return nil }241        var rest = trimmed.dropFirst(keyword.count).drop(while: \.isWhitespace)242        if rest.first == "=" { rest = rest.dropFirst().drop(while: \.isWhitespace) }243        return (keyword.lowercased(), rest)244    }245246    /// Splits arguments like OpenSSH: whitespace separated, single/double quotes, `\` escapes, `#` comments.247    static func tokenize(_ text: Substring) -> [String] {248        let characters = Array(text)249        var tokens: [String] = []250        var index = 0251        while true {252            while index < characters.count, characters[index].isWhitespace { index += 1 }253            guard index < characters.count, characters[index] != "#" else { break }254            var token = ""255            var quote: Character?256            while index < characters.count {257                let character = characters[index]258                let next: Character? = index + 1 < characters.count ? characters[index + 1] : nil259                if character == "\\", let next,260                   next == "\\" || next == "\"" || next == "'" || (quote == nil && next == " ") {261                    token.append(next)262                    index += 1263                } else if let open = quote {264                    if character == open { quote = nil } else { token.append(character) }265                } else if character == "\"" || character == "'" {266                    quote = character267                } else if character.isWhitespace {268                    break269                } else {270                    token.append(character)271                }272                index += 1273            }274            tokens.append(token)275        }276        return tokens277    }278}279280/// `*` / `?` wildcard matching as used by OpenSSH host patterns (case-sensitive).281enum SSHWildcard {282    static func matches(pattern: String, text: String) -> Bool {283        let p = Array(pattern), t = Array(text)284        var pi = 0, ti = 0285        var star: Int?286        var mark = 0287        while ti < t.count {288            if pi < p.count, p[pi] == "?" || p[pi] == t[ti] {289                pi += 1290                ti += 1291            } else if pi < p.count, p[pi] == "*" {292                star = pi293                mark = ti294                pi += 1295            } else if let star {296                pi = star + 1297                mark += 1298                ti = mark299            } else {300                return false301            }302        }303        while pi < p.count, p[pi] == "*" { pi += 1 }304        return pi == p.count305    }306}307
Files main
Menu

Theme