aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/Shared/NETunnelProviderProtocol+Extension.swift
blob: 2f6ea1f6c68a244f336d5ae7efe83fe8183b0370 (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
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.

import NetworkExtension

private var tunnelNameKey: Void?

extension NETunnelProviderProtocol {

    enum Keys: String {
        case wgQuickConfig = "WgQuickConfig"
    }

    convenience init?(tunnelConfiguration: TunnelConfiguration) {
        self.init()

        let appId = Bundle.main.bundleIdentifier!
        providerBundleIdentifier = "\(appId).network-extension"
        providerConfiguration = [Keys.wgQuickConfig.rawValue: tunnelConfiguration.asWgQuickConfig()]

        let endpoints = tunnelConfiguration.peers.compactMap { $0.endpoint }
        if endpoints.count == 1 {
            serverAddress = endpoints[0].stringRepresentation
        } else if endpoints.isEmpty {
            serverAddress = "Unspecified"
        } else {
            serverAddress = "Multiple endpoints"
        }

        username = tunnelConfiguration.interface.name
    }

    func tunnelConfiguration(name: String?) -> TunnelConfiguration? {
        migrateConfigurationIfNeeded()
        guard let serializedConfig = providerConfiguration?[Keys.wgQuickConfig.rawValue] as? String else { return nil }
        return try? TunnelConfiguration(serializedConfig, name: name)
    }

}