aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuard/ConfigFile/WgQuickConfigFileWriter.swift
blob: 0a34fb7cf55ce2e3143b0fb2a34c843103b2596e (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
47
48
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.

import UIKit

class WgQuickConfigFileWriter {
    static func writeConfigFile(from tc: TunnelConfiguration) -> Data? {
        let interface = tc.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")
        }
        output.append("\n")

        for peer in tc.peers {
            output.append("[Peers]\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")
            }
            output.append("\n")
        }

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