aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuard/ConfigFile/WgQuickConfigFileWriter.swift
blob: 78c4f8ba59b15318e8e6727a2de6be783d0b85ac (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
41
42
43
44
45
46
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.

import UIKit

class WgQuickConfigFileWriter {
    static func writeConfigFile(from configuration: TunnelConfiguration) -> Data? {
        let interface = configuration.interface
        var output = "[Interface]\n"
        output.append("PrivateKey = \(interface.privateKey.base64EncodedString())\n")
        if let listenPort = interface.listenPort {
            output.append("ListenPort = \(listenPort)\n")
        }
        if !interface.addresses.isEmpty {
            let addressString = interface.addresses.map { $0.stringRepresentation() }.joined(separator: ", ")
            output.append("Address = \(addressString)\n")
        }
        if !interface.dns.isEmpty {
            let dnsString = interface.dns.map { $0.stringRepresentation() }.joined(separator: ", ")
            output.append("DNS = \(dnsString)\n")
        }
        if let mtu = interface.mtu {
            output.append("MTU = \(mtu)\n")
        }

        for peer in configuration.peers {
            output.append("\n[Peer]\n")
            output.append("PublicKey = \(peer.publicKey.base64EncodedString())\n")
            if let preSharedKey = peer.preSharedKey {
                output.append("PresharedKey = \(preSharedKey.base64EncodedString())\n")
            }
            if !peer.allowedIPs.isEmpty {
                let allowedIPsString = peer.allowedIPs.map { $0.stringRepresentation() }.joined(separator: ", ")
                output.append("AllowedIPs = \(allowedIPsString)\n")
            }
            if let endpoint = peer.endpoint {
                output.append("Endpoint = \(endpoint.stringRepresentation())\n")
            }
            if let persistentKeepAlive = peer.persistentKeepAlive {
                output.append("PersistentKeepalive = \(persistentKeepAlive)\n")
            }
        }

        return output.data(using: .utf8)
    }
}