interface.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. // relayBatch holds forwarded relay packets, which borrow their receive buffers until flushed
  339. relayBatch *batch.SendBatch
  340. }
  341. func newRxContext(f *Interface, q int) *rxContext {
  342. return &rxContext{
  343. q: q,
  344. scratch: make([]byte, mtu),
  345. nb: make([]byte, 12, 12),
  346. h: &header.H{},
  347. fwPacket: &firewall.ParsedPacket{},
  348. hostmapCache: map[uint32]*HostInfo{},
  349. lhh: f.lightHouse.NewRequestHandler(),
  350. ctCache: firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout),
  351. relayBatch: batch.NewSendBatch(f.writers[q], batch.SendBatchCap, 0),
  352. }
  353. }
  354. func (f *Interface) listenOut(i int) {
  355. var li udp.Conn
  356. if i > 0 {
  357. li = f.writers[i]
  358. } else {
  359. li = f.outside
  360. }
  361. rxc := newRxContext(f, i)
  362. listener := func(fromUdpAddr netip.AddrPort, payload []byte) {
  363. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, payload, rxc)
  364. }
  365. flusher := func() {
  366. f.flushSendBatch(rxc.relayBatch, i)
  367. if err := f.batchers[i].Flush(); err != nil {
  368. f.l.Error("Failed to flush tun coalescer", "error", err)
  369. }
  370. clear(rxc.hostmapCache)
  371. }
  372. err := li.ListenOut(listener, flusher)
  373. // An error after teardown began is shutdown noise, the closed flag covers resources
  374. // Close releases itself and the cancelled ctx covers ones torn down by their owners
  375. // reacting to it, like the user device pipes
  376. if err != nil && !f.closed.Load() && f.ctx.Err() == nil {
  377. f.l.Error("Error while reading inbound packet, closing", "error", err)
  378. f.onFatal(err)
  379. }
  380. f.l.Debug("underlay reader is done", "reader", i)
  381. }
  382. func (f *Interface) pinThisThread(i int) {
  383. var cpu int
  384. if n := len(f.cpuAffinity); n > 0 {
  385. // Explicit tun.cpu_affinity list wins; parseCpuAffinity already
  386. // validated the entries against the allowed CPU set.
  387. cpu = f.cpuAffinity[i%n]
  388. } else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
  389. // Default: spread queues across the CPUs we're actually allowed to
  390. // run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
  391. // i % NumCPU would pick unrunnable IDs and every pin would fail.
  392. cpu = allowed[i%len(allowed)]
  393. } else {
  394. cpu = i % runtime.NumCPU()
  395. }
  396. if err := util.PinThreadToCPU(cpu); err != nil {
  397. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  398. }
  399. }
  400. func (f *Interface) listenIn(queue tio.Queue, i int) {
  401. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  402. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  403. if f.pinThreads {
  404. f.pinThisThread(i)
  405. }
  406. rejectBuf := make([]byte, mtu)
  407. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  408. sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
  409. fwPacket := &firewall.ParsedPacket{}
  410. nb := make([]byte, 12, 12)
  411. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  412. for {
  413. pkts, err := queue.Read()
  414. if err != nil {
  415. // Same shutdown noise handling as listenOut
  416. if !f.closed.Load() && f.ctx.Err() == nil {
  417. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  418. f.onFatal(err)
  419. }
  420. break
  421. }
  422. for _, pkt := range pkts {
  423. f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
  424. // Flush incrementally once a full sendmmsg batch has
  425. // accumulated so the first packets of a deep read drain
  426. // hit the wire while the rest are still being encrypted.
  427. if sb.Len() >= batch.SendBatchCap {
  428. f.flushSendBatch(sb, i)
  429. }
  430. }
  431. f.flushSendBatch(sb, i)
  432. }
  433. f.l.Debug("overlay reader is done", "reader", i)
  434. }
  435. // flushSendBatch drains sb to the underlay and accounts for anything it could not deliver. A shortfall means
  436. // specific destinations were undeliverable (a stale remote, a reject rule), which the backend logs per peer at
  437. // debug; here it is only a counter, so one unreachable peer cannot spam a log line per batch.
  438. func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
  439. queued := sb.Len()
  440. written, err := sb.Flush()
  441. if err != nil {
  442. f.l.Error("Failed to write outgoing batch", "error", err, "writer", q)
  443. }
  444. if dropped := queued - written; dropped > 0 {
  445. f.metricTxDropped.Inc(int64(dropped))
  446. }
  447. }
  448. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  449. c.RegisterReloadCallback(f.reloadFirewall)
  450. for _, reload := range []func(*config.C){
  451. f.reloadSendRecvError, f.reloadAcceptRecvError, f.reloadDisconnectInvalid, f.reloadMisc,
  452. } {
  453. c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) { reload(c) })
  454. }
  455. for _, udpConn := range f.writers {
  456. c.RegisterReloadCallback(udpConn.ReloadConfig)
  457. }
  458. }
  459. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  460. initial := c.InitialLoad()
  461. if initial || c.HasChanged("pki.disconnect_invalid") {
  462. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  463. if !initial {
  464. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  465. }
  466. }
  467. }
  468. func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
  469. cs := f.pki.getCertState()
  470. curCert := cs.getCertificate(cert.Version2)
  471. if curCert == nil {
  472. curCert = cs.getCertificate(cert.Version1)
  473. }
  474. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  475. // Check to see if that set has changed, and if so, rebuild the firewall.
  476. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  477. if !c.HasChanged("firewall") && !certUnsafeChanged {
  478. f.l.Debug("No firewall config change detected")
  479. return
  480. }
  481. fw, err := NewFirewallFromConfig(f.l, cs, c)
  482. if err != nil {
  483. f.l.Error("Error while creating firewall during reload", "error", err)
  484. r.Failed()
  485. return
  486. }
  487. oldFw := f.firewall
  488. conntrack := oldFw.Conntrack
  489. conntrack.Lock()
  490. defer conntrack.Unlock()
  491. fw.rulesVersion = oldFw.rulesVersion + 1
  492. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  493. // safe and just reset conntrack in this case.
  494. if fw.rulesVersion == 0 {
  495. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  496. "firewallHashes", fw.GetRuleHashes(),
  497. "oldFirewallHashes", oldFw.GetRuleHashes(),
  498. "rulesVersion", fw.rulesVersion,
  499. )
  500. } else {
  501. fw.Conntrack = conntrack
  502. }
  503. f.firewall = fw
  504. oldFw.Destroy()
  505. f.l.Info("New firewall has been installed",
  506. "firewallHashes", fw.GetRuleHashes(),
  507. "oldFirewallHashes", oldFw.GetRuleHashes(),
  508. "rulesVersion", fw.rulesVersion,
  509. )
  510. }
  511. func (f *Interface) reloadSendRecvError(c *config.C) {
  512. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  513. stringValue := c.GetString("listen.send_recv_error", "always")
  514. switch stringValue {
  515. case "always":
  516. f.sendRecvErrorConfig = recvErrorAlways
  517. case "never":
  518. f.sendRecvErrorConfig = recvErrorNever
  519. case "private":
  520. f.sendRecvErrorConfig = recvErrorPrivate
  521. default:
  522. if c.GetBool("listen.send_recv_error", true) {
  523. f.sendRecvErrorConfig = recvErrorAlways
  524. } else {
  525. f.sendRecvErrorConfig = recvErrorNever
  526. }
  527. }
  528. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  529. }
  530. }
  531. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  532. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  533. stringValue := c.GetString("listen.accept_recv_error", "always")
  534. switch stringValue {
  535. case "always":
  536. f.acceptRecvErrorConfig = recvErrorAlways
  537. case "never":
  538. f.acceptRecvErrorConfig = recvErrorNever
  539. case "private":
  540. f.acceptRecvErrorConfig = recvErrorPrivate
  541. default:
  542. if c.GetBool("listen.accept_recv_error", true) {
  543. f.acceptRecvErrorConfig = recvErrorAlways
  544. } else {
  545. f.acceptRecvErrorConfig = recvErrorNever
  546. }
  547. }
  548. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  549. }
  550. }
  551. func (f *Interface) reloadMisc(c *config.C) {
  552. if c.HasChanged("counters.try_promote") {
  553. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  554. f.tryPromoteEvery.Store(n)
  555. f.l.Info("counters.try_promote has changed")
  556. }
  557. if c.HasChanged("counters.requery_every_packets") {
  558. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  559. f.reQueryEvery.Store(n)
  560. f.l.Info("counters.requery_every_packets has changed")
  561. }
  562. if c.HasChanged("timers.requery_wait_duration") {
  563. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  564. f.reQueryWait.Store(int64(n))
  565. f.l.Info("timers.requery_wait_duration has changed")
  566. }
  567. }
  568. // statsEmitter updates the interface's gauges, the stats server runs it on its capture loop.
  569. func (f *Interface) statsEmitter() func() {
  570. udpStats := udp.NewUDPStatsEmitter(f.writers)
  571. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  572. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  573. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  574. return func() {
  575. f.firewall.EmitStats()
  576. f.handshakeManager.EmitStats()
  577. udpStats()
  578. certState := f.pki.getCertState()
  579. defaultCrt := certState.GetDefaultCertificate()
  580. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  581. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  582. // Report the max certificate version we are capable of using
  583. if certState.v2Cert != nil {
  584. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  585. } else {
  586. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  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. }