interface.go 22 KB

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