interface.go 21 KB

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