interface.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. readers []tio.Queue
  108. // batchers is one per tun queue, wrapping readers[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. readers: make([]tio.Queue, c.routines),
  201. batchers: make([]batch.RxBatcher, c.routines),
  202. myVpnNetworks: cs.myVpnNetworks,
  203. myVpnNetworksTable: cs.myVpnNetworksTable,
  204. myVpnAddrs: cs.myVpnAddrs,
  205. myVpnAddrsTable: cs.myVpnAddrsTable,
  206. myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
  207. relayManager: c.relayManager,
  208. connectionManager: c.connectionManager,
  209. conntrackCacheTimeout: c.ConntrackCacheTimeout,
  210. cpuAffinity: c.CpuAffinity,
  211. pinThreads: c.PinThreads,
  212. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  213. messageMetrics: c.MessageMetrics,
  214. cachedPacketMetrics: &cachedPacketMetrics{
  215. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  216. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  217. },
  218. l: c.l,
  219. }
  220. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  221. ifce.reQueryEvery.Store(c.reQueryEvery)
  222. ifce.reQueryWait.Store(int64(c.reQueryWait))
  223. ifce.connectionManager.intf = ifce
  224. // Held until Close so waiting on the interface blocks until the resources are actually released
  225. ifce.wg.Add(1)
  226. return ifce, nil
  227. }
  228. // activate creates the interface on the host. After the interface is created, any
  229. // other services that want to bind listeners to its IP may do so successfully. However,
  230. // the interface isn't going to process anything until run() is called.
  231. func (f *Interface) activate() error {
  232. // actually turn on tun dev
  233. addr, err := f.outside.LocalAddr()
  234. if err != nil {
  235. f.l.Error("Failed to get udp listen address", "error", err)
  236. }
  237. f.l.Info("Nebula interface is active",
  238. "interface", f.inside.Name(),
  239. "networks", f.myVpnNetworks,
  240. "build", f.version,
  241. "udpAddr", addr,
  242. "boringcrypto", boringEnabled(),
  243. )
  244. if f.routines > 1 {
  245. if !f.inside.SupportsMultiqueue() || !f.outside.SupportsMultipleReaders() {
  246. f.routines = 1
  247. f.l.Warn("routines is not supported on this platform, falling back to a single routine")
  248. }
  249. }
  250. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  251. // Prepare n tun queues
  252. for i := 0; i < f.routines; i++ {
  253. if i > 0 {
  254. if err = f.inside.NewMultiQueueReader(); err != nil {
  255. return err
  256. }
  257. }
  258. }
  259. f.readers = f.inside.Readers()
  260. for i := range f.readers {
  261. caps := tio.QueueCapabilities(f.readers[i])
  262. if caps.TSO || caps.USO {
  263. // Multi-lane: TCP gets coalesced when TSO is on, UDP when USO
  264. // is on, everything else (and either lane disabled) falls
  265. // through to passthrough so non-IP / non-TCP-UDP traffic still
  266. // reaches the TUN.
  267. arena := batch.NewArena(batch.DefaultMultiArenaCap)
  268. f.batchers[i] = batch.NewMultiCoalescer(f.readers[i], f.l, arena, caps.TSO, caps.USO)
  269. } else {
  270. arena := batch.NewArena(batch.DefaultPassthroughArenaCap)
  271. f.batchers[i] = batch.NewPassthrough(f.readers[i], arena)
  272. }
  273. }
  274. // On error the caller owns the cleanup, Control.Start cancels the service context
  275. // before releasing our resources so a waiter never observes a live context
  276. if err = f.inside.Activate(); err != nil {
  277. return err
  278. }
  279. return nil
  280. }
  281. func (f *Interface) run() {
  282. // Launch n queues to read packets from udp
  283. for i := 0; i < f.routines; i++ {
  284. f.wg.Go(func() {
  285. f.listenOut(i)
  286. })
  287. }
  288. // Launch n queues to read packets from tun dev
  289. for i := 0; i < f.routines; i++ {
  290. f.wg.Go(func() {
  291. f.listenIn(f.readers[i], i)
  292. })
  293. }
  294. }
  295. func (f *Interface) wait() error {
  296. f.wg.Wait()
  297. if e := f.fatalErr.Load(); e != nil {
  298. return *e
  299. }
  300. return nil
  301. }
  302. // onFatal stores the first fatal reader error, and calls triggerShutdown if it was the first one
  303. func (f *Interface) onFatal(err error) {
  304. swapped := f.fatalErr.CompareAndSwap(nil, &err)
  305. if !swapped {
  306. return
  307. }
  308. if f.triggerShutdown != nil {
  309. f.triggerShutdown()
  310. }
  311. }
  312. func (f *Interface) listenOut(i int) {
  313. var li udp.Conn
  314. if i > 0 {
  315. li = f.writers[i]
  316. } else {
  317. li = f.outside
  318. }
  319. ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  320. lhh := f.lightHouse.NewRequestHandler()
  321. h := &header.H{}
  322. fwPacket := &firewall.Packet{}
  323. nb := make([]byte, 12, 12)
  324. listener := func(fromUdpAddr netip.AddrPort, payload []byte, meta udp.RxMeta) {
  325. plaintext := f.batchers[i].Reserve(len(payload))
  326. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, plaintext[:0], payload, h, fwPacket, lhh, nb, i, ctCache.Get(), meta)
  327. }
  328. flusher := func() {
  329. if err := f.batchers[i].Flush(); err != nil {
  330. f.l.Error("Failed to flush tun coalescer", "error", err)
  331. }
  332. }
  333. err := li.ListenOut(listener, flusher)
  334. // An error after teardown began is shutdown noise, the closed flag covers resources
  335. // Close releases itself and the cancelled ctx covers ones torn down by their owners
  336. // reacting to it, like the user device pipes
  337. if err != nil && !f.closed.Load() && f.ctx.Err() == nil {
  338. f.l.Error("Error while reading inbound packet, closing", "error", err)
  339. f.onFatal(err)
  340. }
  341. f.l.Debug("underlay reader is done", "reader", i)
  342. }
  343. func (f *Interface) listenIn(reader tio.Queue, i int) {
  344. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  345. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  346. if f.pinThreads {
  347. var cpu int
  348. if n := len(f.cpuAffinity); n > 0 {
  349. // Explicit tun.cpu_affinity list wins; parseCpuAffinity already
  350. // validated the entries against the allowed CPU set.
  351. cpu = f.cpuAffinity[i%n]
  352. } else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
  353. // Default: spread queues across the CPUs we're actually allowed to
  354. // run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
  355. // i % NumCPU would pick unrunnable IDs and every pin would fail.
  356. cpu = allowed[i%len(allowed)]
  357. } else {
  358. cpu = i % runtime.NumCPU()
  359. }
  360. if err := util.PinThreadToCPU(cpu); err != nil {
  361. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  362. }
  363. }
  364. rejectBuf := make([]byte, mtu)
  365. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  366. sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
  367. fwPacket := &firewall.Packet{}
  368. nb := make([]byte, 12, 12)
  369. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  370. for {
  371. pkts, err := reader.Read()
  372. if err != nil {
  373. // Same shutdown noise handling as listenOut
  374. if !f.closed.Load() && f.ctx.Err() == nil {
  375. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  376. f.onFatal(err)
  377. }
  378. break
  379. }
  380. for _, pkt := range pkts {
  381. f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
  382. // Flush incrementally once a full sendmmsg batch has
  383. // accumulated so the first packets of a deep read drain
  384. // hit the wire while the rest are still being encrypted.
  385. if sb.Len() >= batch.SendBatchCap {
  386. if err := sb.Flush(); err != nil {
  387. f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
  388. }
  389. }
  390. }
  391. if err := sb.Flush(); err != nil {
  392. f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
  393. }
  394. }
  395. f.l.Debug("overlay reader is done", "reader", i)
  396. }
  397. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  398. c.RegisterReloadCallback(f.reloadFirewall)
  399. c.RegisterReloadCallback(f.reloadSendRecvError)
  400. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  401. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  402. c.RegisterReloadCallback(f.reloadMisc)
  403. c.RegisterReloadCallback(f.reloadEcn)
  404. for _, udpConn := range f.writers {
  405. c.RegisterReloadCallback(udpConn.ReloadConfig)
  406. }
  407. }
  408. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  409. initial := c.InitialLoad()
  410. if initial || c.HasChanged("pki.disconnect_invalid") {
  411. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  412. if !initial {
  413. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  414. }
  415. }
  416. }
  417. func (f *Interface) reloadFirewall(c *config.C) {
  418. cs := f.pki.getCertState()
  419. curCert := cs.getCertificate(cert.Version2)
  420. if curCert == nil {
  421. curCert = cs.getCertificate(cert.Version1)
  422. }
  423. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  424. // Check to see if that set has changed, and if so, rebuild the firewall.
  425. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  426. if !c.HasChanged("firewall") && !certUnsafeChanged {
  427. f.l.Debug("No firewall config change detected")
  428. return
  429. }
  430. fw, err := NewFirewallFromConfig(f.l, cs, c)
  431. if err != nil {
  432. f.l.Error("Error while creating firewall during reload", "error", err)
  433. return
  434. }
  435. oldFw := f.firewall
  436. conntrack := oldFw.Conntrack
  437. conntrack.Lock()
  438. defer conntrack.Unlock()
  439. fw.rulesVersion = oldFw.rulesVersion + 1
  440. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  441. // safe and just reset conntrack in this case.
  442. if fw.rulesVersion == 0 {
  443. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  444. "firewallHashes", fw.GetRuleHashes(),
  445. "oldFirewallHashes", oldFw.GetRuleHashes(),
  446. "rulesVersion", fw.rulesVersion,
  447. )
  448. } else {
  449. fw.Conntrack = conntrack
  450. }
  451. f.firewall = fw
  452. oldFw.Destroy()
  453. f.l.Info("New firewall has been installed",
  454. "firewallHashes", fw.GetRuleHashes(),
  455. "oldFirewallHashes", oldFw.GetRuleHashes(),
  456. "rulesVersion", fw.rulesVersion,
  457. )
  458. }
  459. func (f *Interface) reloadSendRecvError(c *config.C) {
  460. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  461. stringValue := c.GetString("listen.send_recv_error", "always")
  462. switch stringValue {
  463. case "always":
  464. f.sendRecvErrorConfig = recvErrorAlways
  465. case "never":
  466. f.sendRecvErrorConfig = recvErrorNever
  467. case "private":
  468. f.sendRecvErrorConfig = recvErrorPrivate
  469. default:
  470. if c.GetBool("listen.send_recv_error", true) {
  471. f.sendRecvErrorConfig = recvErrorAlways
  472. } else {
  473. f.sendRecvErrorConfig = recvErrorNever
  474. }
  475. }
  476. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  477. }
  478. }
  479. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  480. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  481. stringValue := c.GetString("listen.accept_recv_error", "always")
  482. switch stringValue {
  483. case "always":
  484. f.acceptRecvErrorConfig = recvErrorAlways
  485. case "never":
  486. f.acceptRecvErrorConfig = recvErrorNever
  487. case "private":
  488. f.acceptRecvErrorConfig = recvErrorPrivate
  489. default:
  490. if c.GetBool("listen.accept_recv_error", true) {
  491. f.acceptRecvErrorConfig = recvErrorAlways
  492. } else {
  493. f.acceptRecvErrorConfig = recvErrorNever
  494. }
  495. }
  496. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  497. }
  498. }
  499. func (f *Interface) reloadMisc(c *config.C) {
  500. if c.HasChanged("counters.try_promote") {
  501. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  502. f.tryPromoteEvery.Store(n)
  503. f.l.Info("counters.try_promote has changed")
  504. }
  505. if c.HasChanged("counters.requery_every_packets") {
  506. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  507. f.reQueryEvery.Store(n)
  508. f.l.Info("counters.requery_every_packets has changed")
  509. }
  510. if c.HasChanged("timers.requery_wait_duration") {
  511. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  512. f.reQueryWait.Store(int64(n))
  513. f.l.Info("timers.requery_wait_duration has changed")
  514. }
  515. }
  516. // reloadEcn syncs Interface.ecnEnabled with the tunnels.ecn config knob.
  517. // Default is enabled (RFC 6040 normal mode); set false on the rare path
  518. // where an underlay middlebox rewrites or drops ECN bits unpredictably.
  519. func (f *Interface) reloadEcn(c *config.C) {
  520. initial := c.InitialLoad()
  521. if initial || c.HasChanged("tunnels.ecn") {
  522. v := c.GetBool("tunnels.ecn", true)
  523. changed := f.ecnEnabled.Swap(v) != v
  524. if !initial {
  525. f.l.Info("tunnels.ecn changed", "enabled", v)
  526. if changed {
  527. 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)
  528. }
  529. }
  530. }
  531. }
  532. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  533. ticker := time.NewTicker(i)
  534. defer ticker.Stop()
  535. udpStats := udp.NewUDPStatsEmitter(f.writers)
  536. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  537. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  538. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  539. emit := func() {
  540. f.firewall.EmitStats()
  541. f.handshakeManager.EmitStats()
  542. udpStats()
  543. certState := f.pki.getCertState()
  544. defaultCrt := certState.GetDefaultCertificate()
  545. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  546. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  547. // Report the max certificate version we are capable of using
  548. if certState.v2Cert != nil {
  549. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  550. } else {
  551. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  552. }
  553. }
  554. // Prime gauges so a Prometheus scrape that lands before the first tick
  555. // sees real values instead of the zero defaults (issue #907).
  556. emit()
  557. for {
  558. select {
  559. case <-ctx.Done():
  560. return
  561. case <-ticker.C:
  562. emit()
  563. }
  564. }
  565. }
  566. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  567. return f.hostMap.QueryVpnAddr(vpnIp)
  568. }
  569. func (f *Interface) GetCertState() *CertState {
  570. return f.pki.getCertState()
  571. }
  572. // Close releases the interface's resources: the udp sockets and the tun device.
  573. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  574. // calls after the first return nil without doing anything.
  575. func (f *Interface) Close() error {
  576. if !f.closed.CompareAndSwap(false, true) {
  577. return nil
  578. }
  579. var errs []error
  580. // Release the udp readers
  581. for i, u := range f.writers {
  582. err := u.Close()
  583. if err != nil {
  584. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  585. errs = append(errs, err)
  586. }
  587. }
  588. // Release the tun device (closing the tun also closes all readers)
  589. closeErr := f.inside.Close()
  590. if closeErr != nil {
  591. errs = append(errs, closeErr)
  592. }
  593. // Release the construction token so waiters know the resources are gone
  594. f.wg.Done()
  595. return errors.Join(errs...)
  596. }