-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
endpoints.go
217 lines (201 loc) · 5.5 KB
/
endpoints.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
Copyright 2023 Avi Zimmerman <avi.zimmerman@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoints
import (
"context"
"fmt"
"net"
"net/netip"
"slices"
"time"
"github.com/webmeshproj/webmesh/pkg/net/system/link"
)
// DetectOpts contains options for endpoint detection.
type DetectOpts struct {
// DetectIPv6 enables IPv6 detection.
DetectIPv6 bool
// DetectPrivate enables private address detection.
DetectPrivate bool
// AllowRemoteDetection enables remote address detection.
AllowRemoteDetection bool
// SkipInterfaces contains a list of interfaces to skip.
SkipInterfaces []string
}
type PrefixList []netip.Prefix
func (a PrefixList) Contains(addr netip.Addr) bool {
for _, prefix := range a {
if prefix.Addr().Compare(addr) == 0 || prefix.Contains(addr) {
return true
}
}
return false
}
func (a PrefixList) Strings() []string {
var out []string
for _, addr := range a {
out = append(out, addr.String())
}
return out
}
func (a PrefixList) AddrStrings() []string {
var out []string
for _, addr := range a {
out = append(out, addr.Addr().String())
}
return out
}
func (a PrefixList) Len() int { return len(a) }
func (a PrefixList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// Sort by IPv4 addresses first, then IPv6 addresses.
func (a PrefixList) Less(i, j int) bool {
iis4 := a[i].Addr().Is4()
jis4 := a[j].Addr().Is4()
if iis4 && !jis4 {
return true
}
if !iis4 && jis4 {
return false
}
return a[i].Addr().Less(a[j].Addr())
}
// Detect detects endpoints for this machine.
func Detect(ctx context.Context, opts DetectOpts) (PrefixList, error) {
addrs, err := detectFromInterfaces(&opts)
if err != nil {
return nil, err
}
if opts.AllowRemoteDetection {
detected, err := DetectPublicAddresses(ctx)
if err != nil {
return nil, fmt.Errorf("detect public address: %w", err)
}
for _, addr := range detected {
if !addrs.Contains(addr) {
if addr.Is6() && !opts.DetectIPv6 {
continue
}
addrs = append(addrs, netip.PrefixFrom(addr, func() int {
if addr.Is4() {
return 32
}
return 128
}()))
}
}
}
return addrs, nil
}
// DetectPublicAddresses detects the public addresses of the machine
// using the opendns resolver service.
func DetectPublicAddresses(ctx context.Context) ([]netip.Addr, error) {
const myip = "myip.opendns.com"
const dnsaddr = "resolver1.opendns.com"
const timeout = 5 * time.Second
addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip", dnsaddr)
if err != nil {
return nil, fmt.Errorf("lookup %s: %w", dnsaddr, err)
}
if len(addrs) == 0 {
return nil, fmt.Errorf("no resolvers found for detection")
}
var ipv4, ipv6 netip.Addr
for _, addr := range addrs {
if addr.Is4() {
ipv4 = addr
} else if addr.Is6() {
ipv6 = addr
}
}
ip4Resolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
return net.DialTimeout(network, net.JoinHostPort(ipv4.String(), "53"), timeout)
},
}
ip6Resolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
return net.DialTimeout(network, net.JoinHostPort(ipv6.String(), "53"), timeout)
},
}
var out []netip.Addr
if ipv4.IsValid() {
ips, err := ip4Resolver.LookupNetIP(ctx, "ip4", myip)
if err == nil {
out = append(out, ips...)
}
}
if ipv6.IsValid() {
ips, err := ip6Resolver.LookupNetIP(ctx, "ip6", myip)
if err == nil {
out = append(out, ips...)
}
}
if len(out) == 0 {
return nil, fmt.Errorf("no addresses found")
}
return out, nil
}
func detectFromInterfaces(opts *DetectOpts) (PrefixList, error) {
interfaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("list interfaces: %w", err)
}
var ips PrefixList
for _, iface := range interfaces {
if iface.Flags&net.FlagUp == 0 {
continue
}
if iface.Flags&net.FlagLoopback != 0 {
continue
}
if iface.Flags&net.FlagPointToPoint != 0 {
continue
}
if slices.Contains(opts.SkipInterfaces, iface.Name) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return nil, fmt.Errorf("failed to list addresses for interface %s: %w", iface.Name, err)
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return nil, fmt.Errorf("failed to parse address %s: %w", addr.String(), err)
}
addr, err := netip.ParseAddr(ip.String())
if err != nil {
return nil, fmt.Errorf("failed to parse address %s: %w", ip.String(), err)
}
if addr.IsPrivate() && !opts.DetectPrivate {
continue
}
if addr.Is6() && opts.DetectIPv6 {
prefix, err := link.InterfaceNetwork(iface.Name, addr, true)
if err != nil {
return nil, fmt.Errorf("failed to get network for interface %s: %w", iface.Name, err)
}
ips = append(ips, prefix)
}
if addr.Is4() {
prefix, err := link.InterfaceNetwork(iface.Name, addr, false)
if err != nil {
return nil, fmt.Errorf("failed to get network for interface %s: %w", iface.Name, err)
}
ips = append(ips, prefix)
}
}
}
return ips, nil
}