-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer.go
62 lines (51 loc) · 1.59 KB
/
peer.go
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
package wgconf
import (
"fmt"
"strings"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// Key is a public or private key used by WireGuard.
type Key = wgtypes.Key
// PeerFilter is a filter that can be applied to peers.
type PeerFilter func(Peer) bool
// Peer is a WireGuard peer.
type Peer struct {
Name string
Description string
PublicKey Key
AllowedIPs AllowedIPs
}
// NetDev returns the systemd netdev configuration for the peer.
func (p Peer) NetDev() string {
// Collect sanitized string representations of each field
name := sanitizeComment(p.Name)
description := sanitizeComment(p.Description)
pubkey := sanitizeKey(p.PublicKey)
addrs := p.AllowedIPs.String()
// Reject keyless peers without a comment
if name == "" && description == "" && pubkey == "" {
return ""
}
// Aggregate the peer configuration with a string builder
var sb strings.Builder
// Include a leading comment with the peer name and/or description
switch {
case name != "" && description != "":
sb.WriteString(fmt.Sprintf("# %s (%s)\n", name, description))
case name != "":
sb.WriteString(fmt.Sprintf("# %s\n", name))
case description != "":
sb.WriteString(fmt.Sprintf("# %s\n", description))
}
// Include the WireGuardPeer entry
if pubkey == "" || addrs == "" {
sb.WriteString("#[WireGuardPeer]\n")
sb.WriteString(fmt.Sprintf("#PublicKey=%s\n", pubkey))
sb.WriteString(fmt.Sprintf("#AllowedIPs=%s", addrs))
} else {
sb.WriteString("[WireGuardPeer]\n")
sb.WriteString(fmt.Sprintf("PublicKey=%s\n", pubkey))
sb.WriteString(fmt.Sprintf("AllowedIPs=%s", addrs))
}
return sb.String()
}