From 609f48a2d13c4284fc2c975224619e12669b6390 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Fri, 25 Aug 2023 17:59:59 +0000 Subject: [PATCH] wireguard: Config.WriteTo() Signed-off-by: Alejandro Mery --- pkg/wireguard/config.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pkg/wireguard/config.go b/pkg/wireguard/config.go index 931e37b..f27d5b0 100644 --- a/pkg/wireguard/config.go +++ b/pkg/wireguard/config.go @@ -1,17 +1,40 @@ package wireguard import ( + "bytes" "errors" "fmt" "io" "net/netip" "strconv" "strings" + "text/template" "darvaza.org/core" "gopkg.in/gcfg.v1" ) +var configTemplate = template.Must(template.New("config").Funcs(template.FuncMap{ + "PrefixJoin": func(a []netip.Prefix, sep string) string { + s := make([]string, len(a)) + for i, p := range a { + s[i] = p.String() + } + return strings.Join(s, sep) + }, +}).Parse(`[Interface] +Address = {{.Interface.Address}} +PrivateKey = {{.Interface.PrivateKey}} +ListenPort = {{.Interface.ListenPort}} +{{- range .Peer }} + +[Peer] +PublicKey = {{.PublicKey}} +Endpoint = {{.Endpoint}} +AllowedIPs = {{ PrefixJoin .AllowedIPs ", "}} +{{- end }} +`)) + // Config represents a wgN.conf file type Config struct { Interface InterfaceConfig @@ -28,6 +51,17 @@ func (f *Config) Peers() int { return len(f.Peer) } +// WriteTo writes a Wireguard [Config] onto the provided [io.Writer] +func (f *Config) WriteTo(w io.Writer) (int64, error) { + var buf bytes.Buffer + + if err := configTemplate.Execute(&buf, f); err != nil { + return 0, err + } + + return buf.WriteTo(w) +} + // InterfaceConfig represents the [Interface] section type InterfaceConfig struct { Address netip.Addr