aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/Models/Attribute.swift
blob: 61e7246c56e6f2313eab289599ad31f65378d421 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//
//  Copyright © 2018 WireGuard LLC. All rights reserved.
//

import Foundation

struct Attribute {

    enum Key: String, CaseIterable {
        case address = "Address"
        case allowedIPs = "AllowedIPs"
        case dns = "DNS"
        case endpoint = "Endpoint"
        case listenPort = "ListenPort"
        case mtu = "MTU"
        case persistentKeepalive = "PersistentKeepalive"
        case presharedKey = "PresharedKey"
        case privateKey = "PrivateKey"
        case publicKey = "PublicKey"
    }

    private static let separatorPattern = (try? NSRegularExpression(pattern: "\\s|=", options: []))!

    let line: String
    let key: Key
    let stringValue: String
    var arrayValue: [String] {
        return stringValue.commaSeparatedToArray()
    }

    static func match(line: String) -> Attribute? {
        guard let equalsIndex = line.firstIndex(of: "=") else { return nil }
        let keyString = line[..<equalsIndex].trimmingCharacters(in: .whitespaces)
        let value = line[line.index(equalsIndex, offsetBy: 1)...].trimmingCharacters(in: .whitespaces)
        guard let key = Key.allCases.first(where: { $0.rawValue.lowercased() == keyString.lowercased() }) else { return nil }

        return Attribute(line: line, key: key, stringValue: value)
    }

}