aboutsummaryrefslogtreecommitdiff
path: root/wgcfg/config.go
blob: ffb7556a9c78753bc859a3032cf2f4e236b6c9c7 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
 */

// Package wgcfg has types and a parser for representing WireGuard config.
package wgcfg

import (
	"fmt"
	"strings"
)

// Config is a wireguard configuration.
type Config struct {
	Name       string
	PrivateKey PrivateKey
	Addresses  []CIDR
	ListenPort uint16
	MTU        uint16
	DNS        []IP
	Peers      []Peer
}

type Peer struct {
	PublicKey           PublicKey
	PresharedKey        SymmetricKey
	AllowedIPs          []CIDR
	Endpoints           []Endpoint
	PersistentKeepalive uint16
}

type Endpoint struct {
	Host string
	Port uint16
}

func (e *Endpoint) String() string {
	if strings.IndexByte(e.Host, ':') > 0 {
		return fmt.Sprintf("[%s]:%d", e.Host, e.Port)
	}
	return fmt.Sprintf("%s:%d", e.Host, e.Port)
}

func (e *Endpoint) IsEmpty() bool {
	return len(e.Host) == 0
}

// Copy makes a deep copy of Config.
// The result aliases no memory with the original.
func (cfg Config) Copy() Config {
	res := cfg
	if res.Addresses != nil {
		res.Addresses = append([]CIDR{}, res.Addresses...)
	}
	if res.DNS != nil {
		res.DNS = append([]IP{}, res.DNS...)
	}
	peers := make([]Peer, 0, len(res.Peers))
	for _, peer := range res.Peers {
		peers = append(peers, peer.Copy())
	}
	res.Peers = peers
	return res
}

// Copy makes a deep copy of Peer.
// The result aliases no memory with the original.
func (peer Peer) Copy() Peer {
	res := peer
	if res.AllowedIPs != nil {
		res.AllowedIPs = append([]CIDR{}, res.AllowedIPs...)
	}
	if res.Endpoints != nil {
		res.Endpoints = append([]Endpoint{}, res.Endpoints...)
	}
	return res
}