2021-01-29 20:16:36 +00:00
|
|
|
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package wgcfg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
"github.com/tailscale/wireguard-go/device"
|
|
|
|
"tailscale.com/types/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
func DeviceConfig(d *device.Device) (*Config, error) {
|
|
|
|
r, w := io.Pipe()
|
|
|
|
errc := make(chan error, 1)
|
|
|
|
go func() {
|
|
|
|
errc <- d.IpcGetOperation(w)
|
|
|
|
w.Close()
|
|
|
|
}()
|
|
|
|
cfg, err := FromUAPI(r)
|
2021-04-30 21:15:03 +00:00
|
|
|
// Prefer errors from IpcGetOperation.
|
|
|
|
if setErr := <-errc; setErr != nil {
|
|
|
|
return nil, setErr
|
2021-01-29 20:16:36 +00:00
|
|
|
}
|
2021-04-30 21:15:03 +00:00
|
|
|
// Check FromUAPI error.
|
|
|
|
if err != nil {
|
2021-01-29 20:16:36 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
sort.Slice(cfg.Peers, func(i, j int) bool {
|
|
|
|
return cfg.Peers[i].PublicKey.LessThan(&cfg.Peers[j].PublicKey)
|
|
|
|
})
|
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReconfigDevice replaces the existing device configuration with cfg.
|
|
|
|
func ReconfigDevice(d *device.Device, cfg *Config, logf logger.Logf) (err error) {
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
logf("wgcfg.Reconfig failed: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
prev, err := DeviceConfig(d)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
r, w := io.Pipe()
|
2021-04-29 22:48:00 +00:00
|
|
|
errc := make(chan error, 1)
|
2021-01-29 20:16:36 +00:00
|
|
|
go func() {
|
|
|
|
errc <- d.IpcSetOperation(r)
|
2021-04-29 22:48:00 +00:00
|
|
|
w.Close()
|
2021-01-29 20:16:36 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
err = cfg.ToUAPI(w, prev)
|
|
|
|
w.Close()
|
2021-04-30 21:15:03 +00:00
|
|
|
// Prefer errors from IpcSetOperation.
|
|
|
|
if setErr := <-errc; setErr != nil {
|
|
|
|
return setErr
|
|
|
|
}
|
|
|
|
return err // err (if any) from cfg.ToUAPI
|
2021-01-29 20:16:36 +00:00
|
|
|
}
|