interface.go 22 KB

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