interface.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/netip"
  8. "runtime"
  9. "slices"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/gaissmai/bart"
  14. "github.com/rcrowley/go-metrics"
  15. "github.com/slackhq/nebula/util"
  16. "github.com/slackhq/nebula/cert"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/firewall"
  19. "github.com/slackhq/nebula/header"
  20. "github.com/slackhq/nebula/overlay"
  21. "github.com/slackhq/nebula/overlay/batch"
  22. "github.com/slackhq/nebula/overlay/tio"
  23. "github.com/slackhq/nebula/udp"
  24. )
  25. const mtu = 9001
  26. type InterfaceConfig struct {
  27. HostMap *HostMap
  28. Outside udp.Conn
  29. Inside overlay.Device
  30. pki *PKI
  31. Cipher string
  32. Firewall *Firewall
  33. DnsServer *dnsServer
  34. HandshakeManager *HandshakeManager
  35. lightHouse *LightHouse
  36. connectionManager *connectionManager
  37. DropLocalBroadcast bool
  38. DropMulticast bool
  39. routines int
  40. MessageMetrics *MessageMetrics
  41. version string
  42. relayManager *relayManager
  43. punchy *Punchy
  44. tryPromoteEvery uint32
  45. reQueryEvery uint32
  46. reQueryWait time.Duration
  47. ConntrackCacheTimeout time.Duration
  48. // CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  49. // should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
  50. // shorter lists than `routines` cycle. Empty list keeps the default
  51. // pin-to-(i % NumCPU) behavior. Only consulted when PinThreads is true.
  52. CpuAffinity []int
  53. // PinThreads controls whether each TUN reader OS thread is pinned to a
  54. // single CPU (via tun.pin_threads, default true). Pinning keeps each
  55. // goroutine's sendmmsg on one XPS-selected NIC TX ring so per-flow
  56. // packets stay ordered on the wire.
  57. PinThreads bool
  58. l *slog.Logger
  59. }
  60. type Interface struct {
  61. hostMap *HostMap
  62. outside udp.Conn
  63. inside overlay.Device
  64. pki *PKI
  65. firewall *Firewall
  66. connectionManager *connectionManager
  67. handshakeManager *HandshakeManager
  68. dnsServer *dnsServer
  69. createTime time.Time
  70. lightHouse *LightHouse
  71. myBroadcastAddrsTable *bart.Lite
  72. myVpnAddrs []netip.Addr // A list of addresses assigned to us via our certificate
  73. myVpnAddrsTable *bart.Lite
  74. myVpnNetworks []netip.Prefix // A list of networks assigned to us via our certificate
  75. myVpnNetworksTable *bart.Lite
  76. dropLocalBroadcast bool
  77. dropMulticast bool
  78. routines int
  79. disconnectInvalid atomic.Bool
  80. closed atomic.Bool
  81. // cpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  82. // should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
  83. // Empty falls back to the default pin-to-(allowed CPU) behavior.
  84. // Only consulted when pinThreads is true.
  85. cpuAffinity []int
  86. // pinThreads controls whether listenIn pins each TUN reader OS thread to
  87. // a CPU at all (tun.pin_threads, default true). When false, threads are
  88. // left free to migrate as on stock nebula.
  89. pinThreads bool
  90. // ecnEnabled gates RFC 6040 underlay ECN propagation. When true,
  91. // inside.go copies the inner ECN onto the outer carrier on encap and
  92. // decryptToTun folds outer CE into the inner header on decap. Toggle
  93. // via tunnels.ecn (default true).
  94. ecnEnabled atomic.Bool
  95. relayManager *relayManager
  96. tryPromoteEvery atomic.Uint32
  97. reQueryEvery atomic.Uint32
  98. reQueryWait atomic.Int64
  99. sendRecvErrorConfig recvErrorConfig
  100. acceptRecvErrorConfig recvErrorConfig
  101. // rebindCount is used to decide if an active tunnel should trigger a punch notification through a lighthouse
  102. rebindCount int8
  103. version string
  104. conntrackCacheTimeout time.Duration
  105. ctx context.Context
  106. writers []udp.Conn
  107. queues []tio.Queue
  108. // batchers is one per tun queue, wrapping queues[i].
  109. // decryptToTun sends plaintext into the batch.RxBatcher;
  110. // listenOut calls its Flush at the end of each UDP recvmmsg batch.
  111. batchers []batch.RxBatcher
  112. wg sync.WaitGroup
  113. // fatalErr holds the first unexpected reader error that caused shutdown.
  114. // nil means "no fatal error" (yet)
  115. fatalErr atomic.Pointer[error]
  116. // triggerShutdown is a function that will be run exactly once, when onFatal swaps something non-nil into fatalErr
  117. triggerShutdown func()
  118. metricHandshakes metrics.Histogram
  119. messageMetrics *MessageMetrics
  120. cachedPacketMetrics *cachedPacketMetrics
  121. l *slog.Logger
  122. }
  123. type EncWriter interface {
  124. SendVia(via *HostInfo,
  125. relay *Relay,
  126. ad,
  127. nb,
  128. out []byte,
  129. nocopy bool,
  130. )
  131. SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
  132. SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
  133. Handshake(vpnAddr netip.Addr)
  134. GetHostInfo(vpnAddr netip.Addr) *HostInfo
  135. GetCertState() *CertState
  136. }
  137. type recvErrorConfig uint8
  138. const (
  139. recvErrorAlways recvErrorConfig = iota
  140. recvErrorNever
  141. recvErrorPrivate
  142. )
  143. func (s recvErrorConfig) ShouldRecvError(endpoint netip.AddrPort) bool {
  144. switch s {
  145. case recvErrorPrivate:
  146. return endpoint.Addr().IsPrivate()
  147. case recvErrorAlways:
  148. return true
  149. case recvErrorNever:
  150. return false
  151. default:
  152. panic(fmt.Errorf("invalid recvErrorConfig value: %d", s))
  153. }
  154. }
  155. func (s recvErrorConfig) String() string {
  156. switch s {
  157. case recvErrorAlways:
  158. return "always"
  159. case recvErrorNever:
  160. return "never"
  161. case recvErrorPrivate:
  162. return "private"
  163. default:
  164. return fmt.Sprintf("invalid(%d)", s)
  165. }
  166. }
  167. func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
  168. if c.Outside == nil {
  169. return nil, errors.New("no outside connection")
  170. }
  171. if c.Inside == nil {
  172. return nil, errors.New("no inside interface (tun)")
  173. }
  174. if c.pki == nil {
  175. return nil, errors.New("no certificate state")
  176. }
  177. if c.Firewall == nil {
  178. return nil, errors.New("no firewall rules")
  179. }
  180. if c.connectionManager == nil {
  181. return nil, errors.New("no connection manager")
  182. }
  183. cs := c.pki.getCertState()
  184. ifce := &Interface{
  185. ctx: ctx,
  186. pki: c.pki,
  187. hostMap: c.HostMap,
  188. outside: c.Outside,
  189. inside: c.Inside,
  190. firewall: c.Firewall,
  191. dnsServer: c.DnsServer,
  192. handshakeManager: c.HandshakeManager,
  193. createTime: time.Now(),
  194. lightHouse: c.lightHouse,
  195. dropLocalBroadcast: c.DropLocalBroadcast,
  196. dropMulticast: c.DropMulticast,
  197. routines: c.routines,
  198. version: c.version,
  199. writers: make([]udp.Conn, c.routines),
  200. batchers: make([]batch.RxBatcher, c.routines),
  201. myVpnNetworks: cs.myVpnNetworks,
  202. myVpnNetworksTable: cs.myVpnNetworksTable,
  203. myVpnAddrs: cs.myVpnAddrs,
  204. myVpnAddrsTable: cs.myVpnAddrsTable,
  205. myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
  206. relayManager: c.relayManager,
  207. connectionManager: c.connectionManager,
  208. conntrackCacheTimeout: c.ConntrackCacheTimeout,
  209. cpuAffinity: c.CpuAffinity,
  210. pinThreads: c.PinThreads,
  211. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  212. messageMetrics: c.MessageMetrics,
  213. cachedPacketMetrics: &cachedPacketMetrics{
  214. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  215. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  216. },
  217. l: c.l,
  218. }
  219. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  220. ifce.reQueryEvery.Store(c.reQueryEvery)
  221. ifce.reQueryWait.Store(int64(c.reQueryWait))
  222. ifce.connectionManager.intf = ifce
  223. // Held until Close so waiting on the interface blocks until the resources are actually released
  224. ifce.wg.Add(1)
  225. return ifce, nil
  226. }
  227. // activate creates the interface on the host. After the interface is created, any
  228. // other services that want to bind listeners to its IP may do so successfully. However,
  229. // the interface isn't going to process anything until run() is called.
  230. func (f *Interface) activate() error {
  231. // actually turn on tun dev
  232. addr, err := f.outside.LocalAddr()
  233. if err != nil {
  234. f.l.Error("Failed to get udp listen address", "error", err)
  235. }
  236. f.l.Info("Nebula interface is active",
  237. "interface", f.inside.Name(),
  238. "networks", f.myVpnNetworks,
  239. "build", f.version,
  240. "udpAddr", addr,
  241. "boringcrypto", boringEnabled(),
  242. )
  243. if f.routines > 1 && !f.outside.SupportsMultipleReaders() {
  244. f.routines = 1
  245. f.l.Warn("multiple udp readers are not supported on this platform, falling back to a single routine")
  246. }
  247. // Prepare the tun queues. A device that can't open that many hands back
  248. // fewer (a single queue on platforms without multiqueue support) and we
  249. // size the reader routines to what we actually got.
  250. queues, err := f.inside.Queues(f.routines)
  251. if err != nil {
  252. return err
  253. }
  254. if len(queues) < f.routines {
  255. f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
  256. "requested", f.routines, "opened", len(queues))
  257. f.routines = len(queues)
  258. }
  259. f.queues = queues
  260. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  261. for i := range f.queues {
  262. caps := tio.QueueCapabilities(f.queues[i])
  263. if caps.TSO || caps.USO {
  264. // Multi-lane: TCP gets coalesced when TSO is on, UDP when USO
  265. // is on, everything else (and either lane disabled) falls
  266. // through to passthrough so non-IP / non-TCP-UDP traffic still
  267. // reaches the TUN.
  268. arena := batch.NewArena(batch.DefaultMultiArenaCap)
  269. f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l, arena, caps.TSO, caps.USO)
  270. } else {
  271. arena := batch.NewArena(batch.DefaultPassthroughArenaCap)
  272. f.batchers[i] = batch.NewPassthrough(f.queues[i], arena)
  273. }
  274. }
  275. // On error the caller owns the cleanup, Control.Start cancels the service context
  276. // before releasing our resources so a waiter never observes a live context
  277. if err = f.inside.Activate(); err != nil {
  278. return err
  279. }
  280. return nil
  281. }
  282. func (f *Interface) run() {
  283. // Launch n queues to read packets from udp
  284. for i := 0; i < f.routines; i++ {
  285. f.wg.Go(func() {
  286. f.listenOut(i)
  287. })
  288. }
  289. // Launch n queues to read packets from tun dev
  290. for i := 0; i < f.routines; i++ {
  291. f.wg.Go(func() {
  292. f.listenIn(f.queues[i], i)
  293. })
  294. }
  295. }
  296. func (f *Interface) wait() error {
  297. f.wg.Wait()
  298. if e := f.fatalErr.Load(); e != nil {
  299. return *e
  300. }
  301. return nil
  302. }
  303. // onFatal stores the first fatal reader error, and calls triggerShutdown if it was the first one
  304. func (f *Interface) onFatal(err error) {
  305. swapped := f.fatalErr.CompareAndSwap(nil, &err)
  306. if !swapped {
  307. return
  308. }
  309. if f.triggerShutdown != nil {
  310. f.triggerShutdown()
  311. }
  312. }
  313. func (f *Interface) listenOut(i int) {
  314. var li udp.Conn
  315. if i > 0 {
  316. li = f.writers[i]
  317. } else {
  318. li = f.outside
  319. }
  320. ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  321. lhh := f.lightHouse.NewRequestHandler()
  322. h := &header.H{}
  323. fwPacket := &firewall.Packet{}
  324. nb := make([]byte, 12, 12)
  325. listener := func(fromUdpAddr netip.AddrPort, payload []byte, meta udp.RxMeta) {
  326. plaintext := f.batchers[i].Reserve(len(payload))
  327. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, plaintext[:0], payload, h, fwPacket, lhh, nb, i, ctCache.Get(), meta)
  328. }
  329. flusher := func() {
  330. if err := f.batchers[i].Flush(); err != nil {
  331. f.l.Error("Failed to flush tun coalescer", "error", err)
  332. }
  333. }
  334. err := li.ListenOut(listener, flusher)
  335. // An error after teardown began is shutdown noise, the closed flag covers resources
  336. // Close releases itself and the cancelled ctx covers ones torn down by their owners
  337. // reacting to it, like the user device pipes
  338. if err != nil && !f.closed.Load() && f.ctx.Err() == nil {
  339. f.l.Error("Error while reading inbound packet, closing", "error", err)
  340. f.onFatal(err)
  341. }
  342. f.l.Debug("underlay reader is done", "reader", i)
  343. }
  344. func (f *Interface) listenIn(queue tio.Queue, i int) {
  345. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  346. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  347. if f.pinThreads {
  348. var cpu int
  349. if n := len(f.cpuAffinity); n > 0 {
  350. // Explicit tun.cpu_affinity list wins; parseCpuAffinity already
  351. // validated the entries against the allowed CPU set.
  352. cpu = f.cpuAffinity[i%n]
  353. } else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
  354. // Default: spread queues across the CPUs we're actually allowed to
  355. // run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
  356. // i % NumCPU would pick unrunnable IDs and every pin would fail.
  357. cpu = allowed[i%len(allowed)]
  358. } else {
  359. cpu = i % runtime.NumCPU()
  360. }
  361. if err := util.PinThreadToCPU(cpu); err != nil {
  362. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  363. }
  364. }
  365. rejectBuf := make([]byte, mtu)
  366. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  367. sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
  368. fwPacket := &firewall.Packet{}
  369. nb := make([]byte, 12, 12)
  370. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  371. for {
  372. pkts, err := queue.Read()
  373. if err != nil {
  374. // Same shutdown noise handling as listenOut
  375. if !f.closed.Load() && f.ctx.Err() == nil {
  376. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  377. f.onFatal(err)
  378. }
  379. break
  380. }
  381. for _, pkt := range pkts {
  382. f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
  383. // Flush incrementally once a full sendmmsg batch has
  384. // accumulated so the first packets of a deep read drain
  385. // hit the wire while the rest are still being encrypted.
  386. if sb.Len() >= batch.SendBatchCap {
  387. if err := sb.Flush(); err != nil {
  388. f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
  389. }
  390. }
  391. }
  392. if err := sb.Flush(); err != nil {
  393. f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
  394. }
  395. }
  396. f.l.Debug("overlay reader is done", "reader", i)
  397. }
  398. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  399. c.RegisterReloadCallback(f.reloadFirewall)
  400. c.RegisterReloadCallback(f.reloadSendRecvError)
  401. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  402. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  403. c.RegisterReloadCallback(f.reloadMisc)
  404. c.RegisterReloadCallback(f.reloadEcn)
  405. for _, udpConn := range f.writers {
  406. c.RegisterReloadCallback(udpConn.ReloadConfig)
  407. }
  408. }
  409. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  410. initial := c.InitialLoad()
  411. if initial || c.HasChanged("pki.disconnect_invalid") {
  412. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  413. if !initial {
  414. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  415. }
  416. }
  417. }
  418. func (f *Interface) reloadFirewall(c *config.C) {
  419. cs := f.pki.getCertState()
  420. curCert := cs.getCertificate(cert.Version2)
  421. if curCert == nil {
  422. curCert = cs.getCertificate(cert.Version1)
  423. }
  424. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  425. // Check to see if that set has changed, and if so, rebuild the firewall.
  426. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  427. if !c.HasChanged("firewall") && !certUnsafeChanged {
  428. f.l.Debug("No firewall config change detected")
  429. return
  430. }
  431. fw, err := NewFirewallFromConfig(f.l, cs, c)
  432. if err != nil {
  433. f.l.Error("Error while creating firewall during reload", "error", err)
  434. return
  435. }
  436. oldFw := f.firewall
  437. conntrack := oldFw.Conntrack
  438. conntrack.Lock()
  439. defer conntrack.Unlock()
  440. fw.rulesVersion = oldFw.rulesVersion + 1
  441. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  442. // safe and just reset conntrack in this case.
  443. if fw.rulesVersion == 0 {
  444. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  445. "firewallHashes", fw.GetRuleHashes(),
  446. "oldFirewallHashes", oldFw.GetRuleHashes(),
  447. "rulesVersion", fw.rulesVersion,
  448. )
  449. } else {
  450. fw.Conntrack = conntrack
  451. }
  452. f.firewall = fw
  453. oldFw.Destroy()
  454. f.l.Info("New firewall has been installed",
  455. "firewallHashes", fw.GetRuleHashes(),
  456. "oldFirewallHashes", oldFw.GetRuleHashes(),
  457. "rulesVersion", fw.rulesVersion,
  458. )
  459. }
  460. func (f *Interface) reloadSendRecvError(c *config.C) {
  461. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  462. stringValue := c.GetString("listen.send_recv_error", "always")
  463. switch stringValue {
  464. case "always":
  465. f.sendRecvErrorConfig = recvErrorAlways
  466. case "never":
  467. f.sendRecvErrorConfig = recvErrorNever
  468. case "private":
  469. f.sendRecvErrorConfig = recvErrorPrivate
  470. default:
  471. if c.GetBool("listen.send_recv_error", true) {
  472. f.sendRecvErrorConfig = recvErrorAlways
  473. } else {
  474. f.sendRecvErrorConfig = recvErrorNever
  475. }
  476. }
  477. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  478. }
  479. }
  480. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  481. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  482. stringValue := c.GetString("listen.accept_recv_error", "always")
  483. switch stringValue {
  484. case "always":
  485. f.acceptRecvErrorConfig = recvErrorAlways
  486. case "never":
  487. f.acceptRecvErrorConfig = recvErrorNever
  488. case "private":
  489. f.acceptRecvErrorConfig = recvErrorPrivate
  490. default:
  491. if c.GetBool("listen.accept_recv_error", true) {
  492. f.acceptRecvErrorConfig = recvErrorAlways
  493. } else {
  494. f.acceptRecvErrorConfig = recvErrorNever
  495. }
  496. }
  497. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  498. }
  499. }
  500. func (f *Interface) reloadMisc(c *config.C) {
  501. if c.HasChanged("counters.try_promote") {
  502. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  503. f.tryPromoteEvery.Store(n)
  504. f.l.Info("counters.try_promote has changed")
  505. }
  506. if c.HasChanged("counters.requery_every_packets") {
  507. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  508. f.reQueryEvery.Store(n)
  509. f.l.Info("counters.requery_every_packets has changed")
  510. }
  511. if c.HasChanged("timers.requery_wait_duration") {
  512. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  513. f.reQueryWait.Store(int64(n))
  514. f.l.Info("timers.requery_wait_duration has changed")
  515. }
  516. }
  517. // reloadEcn syncs Interface.ecnEnabled with the tunnels.ecn config knob.
  518. // Default is enabled (RFC 6040 normal mode); set false on the rare path
  519. // where an underlay middlebox rewrites or drops ECN bits unpredictably.
  520. func (f *Interface) reloadEcn(c *config.C) {
  521. initial := c.InitialLoad()
  522. if initial || c.HasChanged("tunnels.ecn") {
  523. v := c.GetBool("tunnels.ecn", true)
  524. changed := f.ecnEnabled.Swap(v) != v
  525. if !initial {
  526. f.l.Info("tunnels.ecn changed", "enabled", v)
  527. if changed {
  528. f.l.Warn("tunnels.ecn datapath toggled, but route-level ECN negotiation (RTAX_FEATURE_ECN) retains its previous state until nebula is restarted", "enabled", v)
  529. }
  530. }
  531. }
  532. }
  533. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  534. ticker := time.NewTicker(i)
  535. defer ticker.Stop()
  536. udpStats := udp.NewUDPStatsEmitter(f.writers)
  537. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  538. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  539. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  540. emit := func() {
  541. f.firewall.EmitStats()
  542. f.handshakeManager.EmitStats()
  543. udpStats()
  544. certState := f.pki.getCertState()
  545. defaultCrt := certState.GetDefaultCertificate()
  546. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  547. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  548. // Report the max certificate version we are capable of using
  549. if certState.v2Cert != nil {
  550. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  551. } else {
  552. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  553. }
  554. }
  555. // Prime gauges so a Prometheus scrape that lands before the first tick
  556. // sees real values instead of the zero defaults (issue #907).
  557. emit()
  558. for {
  559. select {
  560. case <-ctx.Done():
  561. return
  562. case <-ticker.C:
  563. emit()
  564. }
  565. }
  566. }
  567. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  568. return f.hostMap.QueryVpnAddr(vpnIp)
  569. }
  570. func (f *Interface) GetCertState() *CertState {
  571. return f.pki.getCertState()
  572. }
  573. // Close releases the interface's resources: the udp sockets and the tun device.
  574. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  575. // calls after the first return nil without doing anything.
  576. func (f *Interface) Close() error {
  577. if !f.closed.CompareAndSwap(false, true) {
  578. return nil
  579. }
  580. var errs []error
  581. // Release the udp readers
  582. for i, u := range f.writers {
  583. err := u.Close()
  584. if err != nil {
  585. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  586. errs = append(errs, err)
  587. }
  588. }
  589. // Release the tun device (closing the tun also closes all readers)
  590. closeErr := f.inside.Close()
  591. if closeErr != nil {
  592. errs = append(errs, closeErr)
  593. }
  594. // Release the construction token so waiters know the resources are gone
  595. f.wg.Done()
  596. return errors.Join(errs...)
  597. }