-
Notifications
You must be signed in to change notification settings - Fork 0
/
device_utils_proxy.go
67 lines (56 loc) · 1.7 KB
/
device_utils_proxy.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
package device
import (
"fmt"
"net"
"strings"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/shared"
)
// ProxyParseAddr validates a proxy address and parses it into its constituent parts.
func ProxyParseAddr(addr string) (*deviceConfig.ProxyAddress, error) {
// Split into <protocol> and <address>.
fields := strings.SplitN(addr, ":", 2)
if !shared.StringInSlice(fields[0], []string{"tcp", "udp", "unix"}) {
return nil, fmt.Errorf("Unknown connection type '%s'", fields[0])
}
newProxyAddr := &deviceConfig.ProxyAddress{
ConnType: fields[0],
Abstract: strings.HasPrefix(fields[1], "@"),
}
// unix addresses cannot have ports.
if newProxyAddr.ConnType == "unix" {
newProxyAddr.Addr = []string{fields[1]}
return newProxyAddr, nil
}
// Split <address> into <address> and <ports>.
address, port, err := net.SplitHostPort(fields[1])
if err != nil {
return nil, err
}
// Validate that it's a valid address.
if shared.StringInSlice(newProxyAddr.ConnType, []string{"udp", "tcp"}) {
err := NetworkValidAddress(address)
if err != nil {
return nil, err
}
}
// Split <ports> into individual ports and port ranges.
ports := strings.SplitN(port, ",", -1)
for _, p := range ports {
portFirst, portRange, err := networkParsePortRange(p)
if err != nil {
return nil, err
}
for i := int64(0); i < portRange; i++ {
var newAddr string
if strings.Contains(address, ":") {
// IPv6 addresses need to be enclosed in square brackets.
newAddr = fmt.Sprintf("[%s]:%d", address, portFirst+i)
} else {
newAddr = fmt.Sprintf("%s:%d", address, portFirst+i)
}
newProxyAddr.Addr = append(newProxyAddr.Addr, newAddr)
}
}
return newProxyAddr, nil
}