Repository navigation
Expand file tree
/
Copy pathtunnel.go
More file actions
823 lines (748 loc) · 22 KB
/
Copy pathtunnel.go
File metadata and controls
823 lines (748 loc) · 22 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
package vpn
import (
"context"
"database/sql/driver"
"encoding/json"
"fmt"
"io"
"net/http"
"net/netip"
"net/url"
"reflect"
"sort"
"strconv"
"sync"
"time"
"unicode"
"github.com/google/uuid"
"github.com/tailscale/wireguard-go/tun"
"golang.org/x/xerrors"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"tailscale.com/net/dns"
"tailscale.com/net/netmon"
"tailscale.com/util/dnsname"
"tailscale.com/wgengine/router"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/tailnet"
"github.com/coder/quartz"
)
// netStatusInterval is the interval at which the tunnel records latencies,
// and sends network status updates to the manager.
const netStatusInterval = 5 * time.Second
type Tunnel struct {
speaker[*TunnelMessage, *ManagerMessage, ManagerMessage]
updater
ctx context.Context
requestLoopDone chan struct{}
logger slog.Logger
client Client
// clientLogger is a separate logger than `logger` when the `UseAsLogger`
// option is used, to avoid the tunnel using itself as a sink for it's own
// logs, which could lead to deadlocks.
clientLogger slog.Logger
// the following may be nil
networkingStackFn func(*Tunnel, *StartRequest, slog.Logger) (NetworkStack, error)
}
type TunnelOption func(t *Tunnel)
func NewTunnel(
ctx context.Context,
logger slog.Logger,
mgrConn io.ReadWriteCloser,
client Client,
opts ...TunnelOption,
) (*Tunnel, error) {
logger = logger.Named("vpn")
s, err := newSpeaker[*TunnelMessage, *ManagerMessage](
ctx, logger, mgrConn, SpeakerRoleTunnel, SpeakerRoleManager)
if err != nil {
return nil, err
}
uCtx, uCancel := context.WithCancel(ctx)
t := &Tunnel{
//nolint:govet // safe to copy the locks here because we haven't started the speaker
speaker: *(s),
ctx: ctx,
logger: logger,
clientLogger: logger,
requestLoopDone: make(chan struct{}),
client: client,
updater: updater{
ctx: uCtx,
cancel: uCancel,
netLoopDone: make(chan struct{}),
logger: logger,
uSendCh: s.sendCh,
agents: map[uuid.UUID]agentWithPing{},
workspaces: map[uuid.UUID]tailnet.Workspace{},
clock: quartz.NewReal(),
},
}
for _, opt := range opts {
opt(t)
}
t.speaker.start()
go t.requestLoop()
go t.netStatusLoop()
return t, nil
}
func (t *Tunnel) requestLoop() {
defer close(t.requestLoopDone)
for req := range t.requests {
if req.msg.Rpc != nil && req.msg.Rpc.MsgId != 0 {
t.handleRPC(req)
if _, ok := req.msg.GetMsg().(*ManagerMessage_Stop); ok {
close(t.sendCh)
return
}
continue
}
// Not a unary RPC. We don't know of any message types that are neither a response nor a
// unary RPC from the Manager. This shouldn't ever happen because we checked the protocol
// version during the handshake.
t.logger.Critical(t.ctx, "unknown request", slog.F("msg", req.msg))
}
}
// handleRPC handles unary RPCs from the manager, sending a reply back to the manager.
func (t *Tunnel) handleRPC(req *request[*TunnelMessage, *ManagerMessage]) {
resp := &TunnelMessage{}
resp.Rpc = &RPC{ResponseTo: req.msg.Rpc.MsgId}
switch msg := req.msg.GetMsg().(type) {
case *ManagerMessage_GetPeerUpdate:
err := t.sendUpdateResponse(req)
if err != nil {
t.logger.Error(t.ctx, "failed to send peer update", slog.Error(err))
}
// Reply has already been sent.
return
case *ManagerMessage_Start:
startReq := msg.Start
t.logger.Info(t.ctx, "starting CoderVPN tunnel",
slog.F("url", startReq.CoderUrl),
slog.F("tunnel_fd", startReq.TunnelFileDescriptor),
)
err := t.start(startReq)
var errStr string
if err != nil {
t.logger.Error(t.ctx, "failed to start tunnel", slog.Error(err))
errStr = err.Error()
}
resp.Msg = &TunnelMessage_Start{
Start: &StartResponse{
Success: err == nil,
ErrorMessage: errStr,
},
}
case *ManagerMessage_Stop:
t.logger.Info(t.ctx, "stopping CoderVPN tunnel")
err := t.stop(msg.Stop)
var errStr string
if err != nil {
t.logger.Error(t.ctx, "failed to stop tunnel", slog.Error(err))
errStr = err.Error()
} else {
t.logger.Info(t.ctx, "coderVPN tunnel stopped")
}
resp.Msg = &TunnelMessage_Stop{
Stop: &StopResponse{
Success: err == nil,
ErrorMessage: errStr,
},
}
case *ManagerMessage_Wake:
if t.rebind() {
t.logger.Info(t.ctx, "handling system wake; rebinding")
} else {
t.logger.Debug(t.ctx, "ignoring system wake; tunnel is not running or a rebind happened recently")
}
resp.Msg = &TunnelMessage_Wake{
Wake: &WakeResponse{},
}
default:
t.logger.Warn(t.ctx, "unhandled manager request", slog.F("request", msg))
}
if err := req.sendReply(resp); err != nil {
t.logger.Debug(t.ctx, "failed to send RPC reply", slog.Error(err))
}
}
type NetworkStack struct {
WireguardMonitor *netmon.Monitor
TUNDevice tun.Device
Router router.Router
DNSConfigurator dns.OSConfigurator
}
func UseOSNetworkingStack() TunnelOption {
return func(t *Tunnel) {
t.networkingStackFn = GetNetworkingStack
}
}
func UseAsLogger() TunnelOption {
return func(t *Tunnel) {
t.clientLogger = t.clientLogger.AppendSinks(t)
}
}
func WithClock(clock quartz.Clock) TunnelOption {
return func(t *Tunnel) {
t.clock = clock
}
}
// ApplyNetworkSettings sends a request to the manager to apply the given network settings
func (t *Tunnel) ApplyNetworkSettings(ctx context.Context, ns *NetworkSettingsRequest) error {
msg, err := t.unaryRPC(ctx, &TunnelMessage{
Msg: &TunnelMessage_NetworkSettings{
NetworkSettings: ns,
},
})
if err != nil {
return xerrors.Errorf("rpc failure: %w", err)
}
resp := msg.GetNetworkSettings()
if !resp.Success {
return xerrors.Errorf("network settings failed: %s", resp.ErrorMessage)
}
return nil
}
func (t *Tunnel) start(req *StartRequest) error {
rawURL := req.GetCoderUrl()
if rawURL == "" {
return xerrors.New("missing coder url")
}
svrURL, err := url.Parse(rawURL)
if err != nil {
return xerrors.Errorf("parse url %q: %w", rawURL, err)
}
apiToken := req.GetApiToken()
if apiToken == "" {
return xerrors.New("missing api token")
}
header := make(http.Header)
for _, h := range req.GetHeaders() {
header.Add(h.GetName(), h.GetValue())
}
// Add desktop telemetry if any fields are provided
telemetryData := codersdk.CoderDesktopTelemetry{
DeviceID: req.GetDeviceId(),
DeviceOS: req.GetDeviceOs(),
CoderDesktopVersion: req.GetCoderDesktopVersion(),
}
if !telemetryData.IsEmpty() {
headerValue, err := json.Marshal(telemetryData)
if err == nil {
header.Set(codersdk.CoderDesktopTelemetryHeader, string(headerValue))
t.logger.Debug(t.ctx, "added desktop telemetry header",
slog.F("data", telemetryData))
} else {
t.logger.Warn(t.ctx, "failed to marshal telemetry data")
}
}
var networkingStack NetworkStack
if t.networkingStackFn != nil {
networkingStack, err = t.networkingStackFn(t, req, t.clientLogger)
if err != nil {
return xerrors.Errorf("failed to create networking stack dependencies: %w", err)
}
} else {
t.logger.Debug(t.ctx, "using default networking stack as no custom stack was provided")
}
conn, err := t.client.NewConn(
t.ctx,
svrURL,
apiToken,
&Options{
Headers: header,
Logger: t.clientLogger,
DNSConfigurator: networkingStack.DNSConfigurator,
Router: networkingStack.Router,
TUNDevice: networkingStack.TUNDevice,
WireguardMonitor: networkingStack.WireguardMonitor,
UpdateHandler: t,
},
)
if err != nil {
return xerrors.Errorf("failed to start connection: %w", err)
}
if ok := t.setConn(conn); !ok {
t.logger.Warn(t.ctx, "asked to start tunnel, but tunnel is already running")
}
return err
}
func (t *Tunnel) stop(*StopRequest) error {
return t.updater.stop()
}
var _ slog.Sink = &Tunnel{}
func (t *Tunnel) LogEntry(_ context.Context, e slog.SinkEntry) {
msg := &TunnelMessage{
Msg: &TunnelMessage_Log{
Log: sinkEntryToPb(e),
},
}
select {
case <-t.updater.ctx.Done():
return
case <-t.ctx.Done():
return
case t.sendCh <- msg:
}
}
func (*Tunnel) Sync() {}
func sinkEntryToPb(e slog.SinkEntry) *Log {
l := &Log{
// #nosec G115 - Safe conversion for log levels which are small positive integers
Level: Log_Level(e.Level),
Message: e.Message,
LoggerNames: e.LoggerNames,
}
for _, field := range e.Fields {
l.Fields = append(l.Fields, &Log_Field{
Name: field.Name,
Value: formatValue(field.Value),
})
}
return l
}
// updater is the component of the tunnel responsible for sending workspace
// updates to the manager.
type updater struct {
ctx context.Context
cancel context.CancelFunc
netLoopDone chan struct{}
logger slog.Logger
mu sync.Mutex
uSendCh chan<- *TunnelMessage
// agents contains the agents that are currently connected to the tunnel.
agents map[uuid.UUID]agentWithPing
// workspaces contains the workspaces to which agents are currently connected via the tunnel.
workspaces map[uuid.UUID]tailnet.Workspace
conn Conn
// lastRebind debounces wake-triggered rebinds.
lastRebind time.Time
clock quartz.Clock
}
type agentWithPing struct {
tailnet.Agent
// non-nil if a successful ping has been made
lastPing *lastPing
}
func (a *agentWithPing) Clone() *agentWithPing {
return &agentWithPing{
Agent: a.Agent.Clone(),
lastPing: a.lastPing,
}
}
type lastPing struct {
pingDur time.Duration
didP2p bool
preferredDerp string
preferredDerpLatency *time.Duration
}
// Update pushes a workspace update to the manager
func (u *updater) Update(update tailnet.WorkspaceUpdate) error {
u.mu.Lock()
defer u.mu.Unlock()
peerUpdate := u.createPeerUpdateLocked(update)
msg := &TunnelMessage{
Msg: &TunnelMessage_PeerUpdate{
PeerUpdate: peerUpdate,
},
}
select {
case <-u.ctx.Done():
return u.ctx.Err()
case u.uSendCh <- msg:
}
return nil
}
// sendUpdateResponse responds to the provided `ManagerMessage_GetPeerUpdate` request
// with the current state of the workspaces.
func (u *updater) sendUpdateResponse(req *request[*TunnelMessage, *ManagerMessage]) error {
u.mu.Lock()
defer u.mu.Unlock()
state, err := u.conn.CurrentWorkspaceState()
if err != nil {
return xerrors.Errorf("failed to get current workspace state: %w", err)
}
update := u.createPeerUpdateLocked(state)
resp := &TunnelMessage{
Msg: &TunnelMessage_PeerUpdate{
PeerUpdate: update,
},
}
err = req.sendReply(resp)
if err != nil {
return xerrors.Errorf("failed to send RPC reply: %w", err)
}
return nil
}
// createPeerUpdateLocked creates a PeerUpdate message from a workspace update, populating
// the network status of the agents.
func (u *updater) createPeerUpdateLocked(update tailnet.WorkspaceUpdate) *PeerUpdate {
// if the update is a snapshot, we need to process the full state
if update.Kind == tailnet.Snapshot {
processSnapshotUpdate(&update, u.agents, u.workspaces)
}
out := &PeerUpdate{
UpsertedWorkspaces: make([]*Workspace, len(update.UpsertedWorkspaces)),
UpsertedAgents: make([]*Agent, len(update.UpsertedAgents)),
DeletedWorkspaces: make([]*Workspace, len(update.DeletedWorkspaces)),
DeletedAgents: make([]*Agent, len(update.DeletedAgents)),
}
var upsertedAgentsWithPing []*agentWithPing
// save the workspace update to the tunnel's state, such that it can
// be used to populate automated peer updates.
for _, agent := range update.UpsertedAgents {
var lastPing *lastPing
if existing, ok := u.agents[agent.ID]; ok {
lastPing = existing.lastPing
}
upsertedAgent := agentWithPing{
Agent: agent.Clone(),
lastPing: lastPing,
}
u.agents[agent.ID] = upsertedAgent
upsertedAgentsWithPing = append(upsertedAgentsWithPing, &upsertedAgent)
}
for _, agent := range update.DeletedAgents {
delete(u.agents, agent.ID)
}
for _, workspace := range update.UpsertedWorkspaces {
u.workspaces[workspace.ID] = workspace.Clone()
}
for _, workspace := range update.DeletedWorkspaces {
delete(u.workspaces, workspace.ID)
}
for i, ws := range update.UpsertedWorkspaces {
out.UpsertedWorkspaces[i] = &Workspace{
Id: tailnet.UUIDToByteSlice(ws.ID),
Name: ws.Name,
Status: Workspace_Status(ws.Status),
}
}
upsertedAgents := u.convertAgentsLocked(upsertedAgentsWithPing)
out.UpsertedAgents = upsertedAgents
for i, ws := range update.DeletedWorkspaces {
out.DeletedWorkspaces[i] = &Workspace{
Id: tailnet.UUIDToByteSlice(ws.ID),
Name: ws.Name,
Status: Workspace_Status(ws.Status),
}
}
for i, agent := range update.DeletedAgents {
fqdn := make([]string, 0, len(agent.Hosts))
for name := range agent.Hosts {
fqdn = append(fqdn, name.WithTrailingDot())
}
sort.Slice(fqdn, func(i, j int) bool {
return len(fqdn[i]) < len(fqdn[j])
})
out.DeletedAgents[i] = &Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(agent.WorkspaceID),
Fqdn: fqdn,
IpAddrs: hostsToIPStrings(agent.Hosts),
LastHandshake: nil,
}
}
return out
}
// convertAgentsLocked takes a list of `tailnet.Agent` and converts them to proto agents.
// If there is an active connection, the last handshake time is populated.
func (u *updater) convertAgentsLocked(agents []*agentWithPing) []*Agent {
out := make([]*Agent, 0, len(agents))
for _, agent := range agents {
fqdn := make([]string, 0, len(agent.Hosts))
for name := range agent.Hosts {
fqdn = append(fqdn, name.WithTrailingDot())
}
sort.Slice(fqdn, func(i, j int) bool {
return len(fqdn[i]) < len(fqdn[j])
})
var lastPing *LastPing
if agent.lastPing != nil {
var preferredDerpLatency *durationpb.Duration
if agent.lastPing.preferredDerpLatency != nil {
preferredDerpLatency = durationpb.New(*agent.lastPing.preferredDerpLatency)
}
lastPing = &LastPing{
Latency: durationpb.New(agent.lastPing.pingDur),
DidP2P: agent.lastPing.didP2p,
PreferredDerp: agent.lastPing.preferredDerp,
PreferredDerpLatency: preferredDerpLatency,
}
}
protoAgent := &Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(agent.WorkspaceID),
Fqdn: fqdn,
IpAddrs: hostsToIPStrings(agent.Hosts),
LastPing: lastPing,
}
if u.conn != nil {
diags := u.conn.GetPeerDiagnostics(agent.ID)
// Clients read an unset timestamp as no handshake yet. The zero
// time would encode as year 1, which the Windows client shows as
// connecting.
if !diags.LastWireguardHandshake.IsZero() {
protoAgent.LastHandshake = timestamppb.New(diags.LastWireguardHandshake)
}
}
out = append(out, protoAgent)
}
return out
}
// setConn sets the `conn` and returns false if there's already a connection set.
func (u *updater) setConn(conn Conn) bool {
u.mu.Lock()
defer u.mu.Unlock()
if u.conn != nil {
return false
}
u.conn = conn
return true
}
func (u *updater) stop() error {
u.mu.Lock()
defer u.mu.Unlock()
if u.conn == nil {
return nil
}
err := u.conn.Close()
u.cancel()
u.conn = nil
return err
}
// wakeRebindDebounce is the minimum interval between wake-triggered rebinds.
// Rebinding resets peer path trust, so duplicate wake events must not each
// trigger one.
const wakeRebindDebounce = 5 * time.Second
// rebind resets network bindings and rediscovers peer paths. It reports
// whether it ran; calls within wakeRebindDebounce of the previous rebind, or
// while the tunnel is not running, are dropped.
func (u *updater) rebind() bool {
u.mu.Lock()
conn := u.conn
if conn == nil {
u.mu.Unlock()
return false
}
now := u.clock.Now()
if now.Sub(u.lastRebind) < wakeRebindDebounce {
u.mu.Unlock()
return false
}
u.lastRebind = now
u.mu.Unlock()
conn.Rebind()
return true
}
// sendAgentUpdate sends a peer update message to the manager with the current
// state of the agents, including the latest network status.
func (u *updater) sendAgentUpdate() {
u.mu.Lock()
defer u.mu.Unlock()
agents := make([]*agentWithPing, 0, len(u.agents))
for _, agent := range u.agents {
agents = append(agents, &agent)
}
upsertedAgents := u.convertAgentsLocked(agents)
if len(upsertedAgents) == 0 {
return
}
u.logger.Debug(u.ctx, "sending agent update")
msg := &TunnelMessage{
Msg: &TunnelMessage_PeerUpdate{
PeerUpdate: &PeerUpdate{
UpsertedAgents: upsertedAgents,
},
},
}
select {
case <-u.ctx.Done():
return
case u.uSendCh <- msg:
}
}
func (u *updater) netStatusLoop() {
ticker := u.clock.NewTicker(netStatusInterval)
defer ticker.Stop()
defer close(u.netLoopDone)
for {
select {
case <-u.ctx.Done():
return
case <-ticker.C:
u.recordLatencies()
u.sendAgentUpdate()
}
}
}
func (u *updater) recordLatencies() {
var agentsIDsToPing []uuid.UUID
u.mu.Lock()
for _, agent := range u.agents {
agentsIDsToPing = append(agentsIDsToPing, agent.ID)
}
conn := u.conn
u.mu.Unlock()
if conn == nil {
u.logger.Debug(u.ctx, "skipping pings as tunnel is not connected")
return
}
go func() {
// We need a waitgroup to cancel the context after all pings are done.
var wg sync.WaitGroup
pingCtx, cancelFunc := context.WithTimeout(u.ctx, netStatusInterval)
defer cancelFunc()
for _, agentID := range agentsIDsToPing {
wg.Add(1)
go func() {
defer wg.Done()
pingDur, didP2p, pingResult, err := conn.Ping(pingCtx, agentID)
if err != nil {
u.logger.Warn(u.ctx, "failed to ping agent", slog.F("agent_id", agentID), slog.Error(err))
return
}
// We fetch the Node and DERPMap after each ping, as it may have
// changed.
node := conn.Node()
derpMap := conn.DERPMap()
if node == nil || derpMap == nil {
u.logger.Warn(u.ctx, "failed to get DERP map or node after ping")
return
}
derpLatencies := tailnet.ExtractDERPLatency(node, derpMap)
preferredDerp := tailnet.ExtractPreferredDERPName(pingResult, node, derpMap)
var preferredDerpLatency *time.Duration
if derpLatency, ok := derpLatencies[preferredDerp]; ok {
preferredDerpLatency = &derpLatency
} else {
u.logger.Debug(u.ctx, "preferred DERP not found in DERP latency map", slog.F("preferred_derp", preferredDerp))
}
// Write back results
u.mu.Lock()
defer u.mu.Unlock()
if agent, ok := u.agents[agentID]; ok {
agent.lastPing = &lastPing{
pingDur: pingDur,
didP2p: didP2p,
preferredDerp: preferredDerp,
preferredDerpLatency: preferredDerpLatency,
}
u.agents[agentID] = agent
} else {
u.logger.Debug(u.ctx, "ignoring ping result for unknown agent", slog.F("agent_id", agentID))
}
}()
}
wg.Wait()
}()
}
// processSnapshotUpdate handles the logic when a full state update is received.
// When the tunnel is live, we only receive diffs, but the first packet on any given
// reconnect to the tailnet API is a full state.
// Without this logic we weren't processing deletes for any workspaces or agents deleted
// while the client was disconnected while the computer was asleep.
func processSnapshotUpdate(update *tailnet.WorkspaceUpdate, agents map[uuid.UUID]agentWithPing, workspaces map[uuid.UUID]tailnet.Workspace) {
// ignoredWorkspaces is initially populated with the workspaces that are
// in the current update. Later on we populate it with the deleted workspaces too
// so that we don't send duplicate updates. Same applies to ignoredAgents.
ignoredWorkspaces := make(map[uuid.UUID]struct{}, len(update.UpsertedWorkspaces))
ignoredAgents := make(map[uuid.UUID]struct{}, len(update.UpsertedAgents))
for _, workspace := range update.UpsertedWorkspaces {
ignoredWorkspaces[workspace.ID] = struct{}{}
}
for _, agent := range update.UpsertedAgents {
ignoredAgents[agent.ID] = struct{}{}
}
for _, agent := range agents {
if _, present := ignoredAgents[agent.ID]; !present {
// delete any current agents that are not in the new update
update.DeletedAgents = append(update.DeletedAgents, &tailnet.Agent{
ID: agent.ID,
Name: agent.Name,
WorkspaceID: agent.WorkspaceID,
})
}
}
for _, workspace := range workspaces {
if _, present := ignoredWorkspaces[workspace.ID]; !present {
update.DeletedWorkspaces = append(update.DeletedWorkspaces, &tailnet.Workspace{
ID: workspace.ID,
Name: workspace.Name,
Status: workspace.Status,
})
ignoredWorkspaces[workspace.ID] = struct{}{}
}
}
}
// hostsToIPStrings returns a slice of all unique IP addresses in the values
// of the given map.
func hostsToIPStrings(hosts map[dnsname.FQDN][]netip.Addr) []string {
seen := make(map[netip.Addr]struct{})
var result []string
for _, inner := range hosts {
for _, elem := range inner {
if _, exists := seen[elem]; !exists {
seen[elem] = struct{}{}
result = append(result, elem.String())
}
}
}
return result
}
// the following are taken from sloghuman:
func formatValue(v interface{}) string {
if vr, ok := v.(driver.Valuer); ok {
var err error
v, err = vr.Value()
if err != nil {
return fmt.Sprintf("error calling Value: %v", err)
}
}
if v == nil {
return "<nil>"
}
typ := reflect.TypeOf(v)
switch typ.Kind() {
case reflect.Struct, reflect.Map:
byt, err := json.Marshal(v)
if err != nil {
panic(err)
}
return string(byt)
case reflect.Slice:
// Byte slices are optimistically readable.
if typ.Elem().Kind() == reflect.Uint8 {
return fmt.Sprintf("%q", v)
}
fallthrough
default:
return quote(fmt.Sprintf("%+v", v))
}
}
// quotes quotes a string so that it is suitable
// as a key for a map or in general some output that
// cannot span multiple lines or have weird characters.
func quote(key string) string {
// strconv.Quote does not quote an empty string so we need this.
if key == "" {
return `""`
}
var hasSpace bool
for _, r := range key {
if unicode.IsSpace(r) {
hasSpace = true
break
}
}
quoted := strconv.Quote(key)
// If the key doesn't need to be quoted, don't quote it.
// We do not use strconv.CanBackquote because it doesn't
// account tabs.
if !hasSpace && quoted[1:len(quoted)-1] == key {
return key
}
return quoted
}