Debian Codegraph @

punchy.go

raw
1 package nebula
2
3 import (
4 "context"
5 "log/slog"
6 "net/netip"
7 "sync/atomic"
8 "time"
9
10 "github.com/rcrowley/go-metrics"
11 "github.com/slackhq/nebula/config"
12 "github.com/slackhq/nebula/header"
13 "github.com/slackhq/nebula/udp"
14 )
15
16 // holepunchQueueSize buffers the channel that pending holepunchJobs land on after their delay timer fires.
17 const holepunchQueueSize = 64
18
19 // holepunchJob is one scheduled item delivered to the worker goroutine.
20 // - target valid -> send a UDP punch to target. vpnAddr, if set, is the peer's vpn addr carried for log context.
21 // - target invalid, vpnAddr valid -> send an encrypted test packet to vpnAddr (a "punchback").
22 type holepunchJob struct {
23 target netip.AddrPort
24 vpnAddr netip.Addr
25 }
26
27 // lighthouseChecker is the slice of LightHouse that Punchy actually needs.
28 // Defined here so Punchy doesn't take a *LightHouse dependency (LightHouse
29 // already holds a *Punchy, and the bidirectional pointer reference is awkward
30 // even within the same package). Tests can also substitute a fake.
31 type lighthouseChecker interface {
32 IsAnyLighthouseAddr(vpnAddrs []netip.Addr) bool
33 }
34
35 type Punchy struct {
36 punch atomic.Bool
37 respond atomic.Bool
38 delay atomic.Int64
39 respondDelay atomic.Int64
40 punchEverything atomic.Bool
41
42 sched *Scheduler[holepunchJob]
43 punchConn udp.Conn
44 metricHolepunchTx metrics.Counter
45 metricPunchyTx metrics.Counter
46
47 ctx context.Context
48 ifce EncWriter
49 hm *HostMap
50 lh lighthouseChecker
51
52 l *slog.Logger
53 }
54
55 func NewPunchyFromConfig(l *slog.Logger, c *config.C, punchConn udp.Conn) *Punchy {
56 p := &Punchy{
57 l: l,
58 punchConn: punchConn,
59 sched: NewScheduler[holepunchJob](holepunchQueueSize),
60 metricPunchyTx: metrics.GetOrRegisterCounter("messages.tx.punchy", nil),
61 }
62
63 if c.GetBool("stats.lighthouse_metrics", false) {
64 p.metricHolepunchTx = metrics.GetOrRegisterCounter("messages.tx.holepunch", nil)
65 } else {
66 p.metricHolepunchTx = metrics.NilCounter{}
67 }
68
69 p.reload(c, true)
70 c.RegisterReloadCallback(func(c *config.C) {
71 p.reload(c, false)
72 })
73
74 return p
75 }
76
77 func (p *Punchy) reload(c *config.C, initial bool) {
78 if initial || c.HasChanged("punchy.punch") || c.HasChanged("punchy") {
79 var yes bool
80 if c.IsSet("punchy.punch") {
81 yes = c.GetBool("punchy.punch", false)
82 } else {
83 // Deprecated fallback
84 yes = c.GetBool("punchy", false)
85 }
86
87 old := p.punch.Swap(yes)
88 switch {
89 case initial && yes:
90 p.l.Info("punchy enabled")
91 case initial:
92 p.l.Info("punchy disabled")
93 case old != yes:
94 p.l.Info("punchy.punch changed", "punch", yes)
95 }
96 }
97
98 if initial || c.HasChanged("punchy.respond") || c.HasChanged("punch_back") {
99 var yes bool
100 if c.IsSet("punchy.respond") {
101 yes = c.GetBool("punchy.respond", false)
102 } else {
103 // Deprecated fallback
104 yes = c.GetBool("punch_back", false)
105 }
106
107 old := p.respond.Swap(yes)
108 if !initial && old != yes {
109 p.l.Info("punchy.respond changed", "respond", yes)
110 }
111 }
112
113 //NOTE: this will not apply to any in progress operations, only the next one
114 if initial || c.HasChanged("punchy.delay") {
115 newDelay := int64(c.GetDuration("punchy.delay", time.Second))
116 old := p.delay.Swap(newDelay)
117 if !initial && old != newDelay {
118 p.l.Info("punchy.delay changed", "delay", time.Duration(newDelay))
119 }
120 }
121
122 if initial || c.HasChanged("punchy.target_all_remotes") {
123 yes := c.GetBool("punchy.target_all_remotes", false)
124 old := p.punchEverything.Swap(yes)
125 if !initial && old != yes {
126 p.l.Info("punchy.target_all_remotes changed", "target_all_remotes", yes)
127 }
128 }
129
130 if initial || c.HasChanged("punchy.respond_delay") {
131 newDelay := int64(c.GetDuration("punchy.respond_delay", 5*time.Second))
132 old := p.respondDelay.Swap(newDelay)
133 if !initial && old != newDelay {
134 p.l.Info("punchy.respond_delay changed", "respond_delay", time.Duration(newDelay))
135 }
136 }
137 }
138
139 // Schedule queues a punch packet to target, to be sent after the configured delay.
140 // vpnAddr is the peer's vpn addr, used for log context when the packet actually fires.
141 // No-op if target is not a valid AddrPort or if Start has not yet been called. Safe to call from any goroutine.
142 func (p *Punchy) Schedule(target netip.AddrPort, vpnAddr netip.Addr) {
143 if !target.IsValid() || p.ctx == nil {
144 return
145 }
146 p.scheduleJob(holepunchJob{target: target, vpnAddr: vpnAddr}, time.Duration(p.delay.Load()))
147 }
148
149 // ScheduleRespond queues a punchback test packet to vpnAddr after the configured respond delay,
150 // gated on punchy.respond. No-op when respond is disabled or before Start has been called.
151 func (p *Punchy) ScheduleRespond(vpnAddr netip.Addr) {
152 if !p.respond.Load() || p.ctx == nil {
153 return
154 }
155 p.scheduleJob(holepunchJob{vpnAddr: vpnAddr}, time.Duration(p.respondDelay.Load()))
156 }
157
158 // scheduleJob delegates to the pooled Scheduler.
159 // The callback observes p.ctx so a job that becomes due after Stop is dropped instead of queued.
160 func (p *Punchy) scheduleJob(job holepunchJob, delay time.Duration) {
161 p.sched.Schedule(p.ctx, job, delay)
162 }
163
164 // SendPunch sends an immediate keepalive punch for an idle hostinfo.
165 // The configured punchy.target_all_remotes mode picks the targets. Gated on punchy.punch and the lighthouse-skip rule
166 // (lighthouses don't get keepalive punches because the regular update interval keeps their NAT state warm).
167 func (p *Punchy) SendPunch(hostinfo *HostInfo) {
168 if !p.punch.Load() {
169 return
170 }
171 if p.lh.IsAnyLighthouseAddr(hostinfo.vpnAddrs) {
172 return
173 }
174
175 if p.punchEverything.Load() {
176 p.sendPunchToAllRemotes(hostinfo)
177 } else if hr := hostinfo.GetRemote(); hr.IsValid() {
178 p.metricPunchyTx.Inc(1)
179 p.punchConn.WriteTo([]byte{1}, hr)
180 }
181 }
182
183 // SendPunchToAll punches every known remote for hostinfo, but only when punchy.target_all_remotes is enabled.
184 // The connection manager calls this during outbound-only traffic: the outbound traffic itself keeps the primary's
185 // NAT state warm, but non-primary remotes need separate refresh, so we fan out to all of them (the redundant
186 // primary punch is harmless). Gated on punchy.punch and the lighthouse-skip rule.
187 func (p *Punchy) SendPunchToAll(hostinfo *HostInfo) {
188 if !p.punchEverything.Load() {
189 return
190 }
191 if !p.punch.Load() {
192 return
193 }
194 if p.lh.IsAnyLighthouseAddr(hostinfo.vpnAddrs) {
195 return
196 }
197 p.sendPunchToAllRemotes(hostinfo)
198 }
199
200 func (p *Punchy) sendPunchToAllRemotes(hostinfo *HostInfo) {
201 hostinfo.remotes.ForEach(p.hm.GetPreferredRanges(), func(addr netip.AddrPort, preferred bool) {
202 p.metricPunchyTx.Inc(1)
203 p.punchConn.WriteTo([]byte{1}, addr)
204 })
205 }
206
207 // Start wires the runtime dependencies and spawns the scheduler worker.
208 func (p *Punchy) Start(ctx context.Context, ifce EncWriter, hm *HostMap, lh lighthouseChecker) {
209 p.ctx = ctx
210 p.ifce = ifce
211 p.hm = hm
212 p.lh = lh
213
214 nb := make([]byte, 12, 12)
215 out := make([]byte, mtu)
216 empty := []byte{0}
217
218 go p.sched.Run(ctx, func(job holepunchJob) {
219 switch {
220 case job.target.IsValid():
221 if p.l.Enabled(context.Background(), slog.LevelDebug) {
222 p.l.Debug("Punching", "target", job.target, "vpnAddr", job.vpnAddr)
223 }
224 p.metricHolepunchTx.Inc(1)
225 p.punchConn.WriteTo(empty, job.target)
226 case job.vpnAddr.IsValid():
227 // A nebula test packet to the host trying to contact us.
228 // In the case of a double nat or other difficult scenario, this may help establish a tunnel.
229 if p.l.Enabled(context.Background(), slog.LevelDebug) {
230 p.l.Debug("Sending a nebula test packet", "vpnAddr", job.vpnAddr)
231 }
232 p.ifce.SendMessageToVpnAddr(header.Test, header.TestRequest, job.vpnAddr, []byte(""), nb, out)
233 }
234 })
235 }