-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathderpmap.go
More file actions
311 lines (286 loc) · 8.13 KB
/
derpmap.go
File metadata and controls
311 lines (286 loc) · 8.13 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package tailnet
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"golang.org/x/xerrors"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
)
const DisableSTUN = "disable"
func STUNRegions(baseRegionID int, stunAddrs []string) ([]*tailcfg.DERPRegion, error) {
regions := make([]*tailcfg.DERPRegion, 0, len(stunAddrs))
for index, stunAddr := range stunAddrs {
if stunAddr == DisableSTUN {
return []*tailcfg.DERPRegion{}, nil
}
host, rawPort, err := net.SplitHostPort(stunAddr)
if err != nil {
return nil, xerrors.Errorf("split host port for %q: %w", stunAddr, err)
}
port, err := strconv.Atoi(rawPort)
if err != nil {
return nil, xerrors.Errorf("parse port for %q: %w", stunAddr, err)
}
regionID := baseRegionID + index + 1
regions = append(regions, &tailcfg.DERPRegion{
EmbeddedRelay: false,
RegionID: regionID,
RegionCode: fmt.Sprintf("coder_stun_%d", regionID),
RegionName: fmt.Sprintf("Coder STUN %d", regionID),
Nodes: []*tailcfg.DERPNode{{
Name: fmt.Sprintf("%dstun0", regionID),
RegionID: regionID,
HostName: host,
STUNOnly: true,
STUNPort: port,
}},
})
}
return regions, nil
}
// NewDERPMap constructs a DERPMap from a set of STUN addresses and optionally a remote
// URL to fetch a mapping from e.g. https://controlplane.tailscale.com/derpmap/default.
//
//nolint:revive
func NewDERPMap(ctx context.Context, region *tailcfg.DERPRegion, stunAddrs []string, remoteURL, localPath string, disableSTUN bool) (*tailcfg.DERPMap, error) {
if remoteURL != "" && localPath != "" {
return nil, xerrors.New("a remote URL or local path must be specified, not both")
}
if disableSTUN {
stunAddrs = nil
}
// stunAddrs only applies when a default region is set. Each STUN node gets
// it's own region ID because netcheck will only try a single STUN server in
// each region before canceling the region's STUN check.
addRegions := []*tailcfg.DERPRegion{}
if region != nil {
addRegions = append(addRegions, region)
stunRegions, err := STUNRegions(region.RegionID, stunAddrs)
if err != nil {
return nil, xerrors.Errorf("create stun regions: %w", err)
}
addRegions = append(addRegions, stunRegions...)
}
derpMap := &tailcfg.DERPMap{
Regions: map[int]*tailcfg.DERPRegion{},
}
if remoteURL != "" {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, remoteURL, nil)
if err != nil {
return nil, xerrors.Errorf("create request: %w", err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, xerrors.Errorf("get derpmap: %w", err)
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&derpMap)
if err != nil {
return nil, xerrors.Errorf("fetch derpmap: %w", err)
}
}
if localPath != "" {
content, err := os.ReadFile(localPath)
if err != nil {
return nil, xerrors.Errorf("read derpmap from %q: %w", localPath, err)
}
err = json.Unmarshal(content, &derpMap)
if err != nil {
return nil, xerrors.Errorf("unmarshal derpmap: %w", err)
}
}
// Add our custom regions to the DERP map.
if len(addRegions) > 0 {
for _, region := range addRegions {
_, conflicts := derpMap.Regions[region.RegionID]
if conflicts {
return nil, xerrors.Errorf("a default region ID %d (%s - %q) conflicts with a remote region from %q", region.RegionID, region.RegionCode, region.RegionName, remoteURL)
}
derpMap.Regions[region.RegionID] = region
}
}
// Remove all STUNPorts from DERPy nodes, and fully remove all STUNOnly
// nodes.
if disableSTUN {
for _, region := range derpMap.Regions {
newNodes := make([]*tailcfg.DERPNode, 0, len(region.Nodes))
for _, node := range region.Nodes {
node.STUNPort = -1
if !node.STUNOnly {
newNodes = append(newNodes, node)
}
}
region.Nodes = newNodes
}
}
// Fail if the DERP map has no regions or no DERP nodes.
badDerpMapMsg := "A valid DERP map is required for networking to work. You must either supply your own DERP map or use the built-in DERP server"
if len(derpMap.Regions) == 0 {
return nil, xerrors.New("DERP map has no regions. " + badDerpMapMsg)
}
foundValidNode := false
regionLoop:
for _, region := range derpMap.Regions {
for _, node := range region.Nodes {
if !node.STUNOnly {
foundValidNode = true
break regionLoop
}
}
}
if !foundValidNode {
return nil, xerrors.New("DERP map has no DERP nodes. " + badDerpMapMsg)
}
return derpMap, nil
}
func ExtractPreferredDERPName(pingResult *ipnstate.PingResult, node *Node, derpMap *tailcfg.DERPMap) string {
// Sometimes the preferred DERP doesn't match the one we're actually
// connected with. Perhaps because the agent prefers a different DERP and
// we're using that server instead.
preferredDerpID := node.PreferredDERP
if pingResult.DERPRegionID != 0 {
preferredDerpID = pingResult.DERPRegionID
}
preferredDerp, ok := derpMap.Regions[preferredDerpID]
preferredDerpName := fmt.Sprintf("Unnamed %d", preferredDerpID)
if ok {
preferredDerpName = preferredDerp.RegionName
}
return preferredDerpName
}
// ExtractDERPLatency extracts a map of derp region names to their latencies
func ExtractDERPLatency(node *Node, derpMap *tailcfg.DERPMap) map[string]time.Duration {
latencyMs := make(map[string]time.Duration)
// Convert DERP region IDs to friendly names for display in the UI.
for rawRegion, latency := range node.DERPLatency {
regionParts := strings.SplitN(rawRegion, "-", 2)
regionID, err := strconv.Atoi(regionParts[0])
if err != nil {
continue
}
region, found := derpMap.Regions[regionID]
if !found {
// It's possible that a workspace agent is using an old DERPMap
// and reports regions that do not exist. If that's the case,
// report the region as unknown!
region = &tailcfg.DERPRegion{
RegionID: regionID,
RegionName: fmt.Sprintf("Unnamed %d", regionID),
}
}
latencyMs[region.RegionName] = time.Duration(latency * float64(time.Second))
}
return latencyMs
}
// CompareDERPMaps returns true if the given DERPMaps are equivalent. Ordering
// of slices is ignored.
//
// If the first map is nil, the second map must also be nil for them to be
// considered equivalent. If the second map is nil, the first map can be any
// value and the function will return true.
func CompareDERPMaps(a *tailcfg.DERPMap, b *tailcfg.DERPMap) bool {
if a == nil {
return b == nil
}
if b == nil {
return true
}
if len(a.Regions) != len(b.Regions) {
return false
}
if a.OmitDefaultRegions != b.OmitDefaultRegions {
return false
}
for id, region := range a.Regions {
other, ok := b.Regions[id]
if !ok {
return false
}
if !compareDERPRegions(region, other) {
return false
}
}
return true
}
func compareDERPRegions(a *tailcfg.DERPRegion, b *tailcfg.DERPRegion) bool {
if a == nil || b == nil {
return false
}
if a.EmbeddedRelay != b.EmbeddedRelay {
return false
}
if a.RegionID != b.RegionID {
return false
}
if a.RegionCode != b.RegionCode {
return false
}
if a.RegionName != b.RegionName {
return false
}
if a.Avoid != b.Avoid {
return false
}
if len(a.Nodes) != len(b.Nodes) {
return false
}
// Convert both slices to maps so ordering can be ignored easier.
aNodes := map[string]*tailcfg.DERPNode{}
for _, node := range a.Nodes {
aNodes[node.Name] = node
}
bNodes := map[string]*tailcfg.DERPNode{}
for _, node := range b.Nodes {
bNodes[node.Name] = node
}
for name, aNode := range aNodes {
bNode, ok := bNodes[name]
if !ok {
return false
}
if aNode.Name != bNode.Name {
return false
}
if aNode.RegionID != bNode.RegionID {
return false
}
if aNode.HostName != bNode.HostName {
return false
}
if aNode.CertName != bNode.CertName {
return false
}
if aNode.IPv4 != bNode.IPv4 {
return false
}
if aNode.IPv6 != bNode.IPv6 {
return false
}
if aNode.STUNPort != bNode.STUNPort {
return false
}
if aNode.STUNOnly != bNode.STUNOnly {
return false
}
if aNode.DERPPort != bNode.DERPPort {
return false
}
if aNode.InsecureForTests != bNode.InsecureForTests {
return false
}
if aNode.ForceHTTP != bNode.ForceHTTP {
return false
}
if aNode.STUNTestIP != bNode.STUNTestIP {
return false
}
}
return true
}