-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
99 lines (79 loc) · 1.96 KB
/
client.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package wguser
import (
"fmt"
"net"
"os"
"path/filepath"
"strings"
"github.com/bi-zone/ruwireguard-go/wgctrl/internal/wginternal"
"github.com/bi-zone/ruwireguard-go/wgctrl/wgtypes"
)
var _ wginternal.Client = &Client{}
// A Client provides access to userspace WireGuard device information.
type Client struct {
dial func(device string) (net.Conn, error)
find func() ([]string, error)
}
// New creates a new Client.
func New() (*Client, error) {
return &Client{
// Operating system-specific functions which can identify and connect
// to userspace WireGuard devices. These functions can also be
// overridden for tests.
dial: dial,
find: find,
}, nil
}
// Close implements wginternal.Client.
func (c *Client) Close() error { return nil }
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
devices, err := c.find()
if err != nil {
return nil, err
}
var wgds []*wgtypes.Device
for _, d := range devices {
wgd, err := c.getDevice(d)
if err != nil {
return nil, err
}
wgds = append(wgds, wgd)
}
return wgds, nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
devices, err := c.find()
if err != nil {
return nil, err
}
for _, d := range devices {
if name != deviceName(d) {
continue
}
return c.getDevice(d)
}
return nil, os.ErrNotExist
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
devices, err := c.find()
if err != nil {
return err
}
for _, d := range devices {
if name != deviceName(d) {
continue
}
return c.configureDevice(d, cfg)
}
return os.ErrNotExist
}
// deviceName infers a device name from an absolute file path with extension.
func deviceName(sock string) string {
return strings.TrimSuffix(filepath.Base(sock), filepath.Ext(sock))
}
func panicf(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}