interface.go 22 KB

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