1
0

interface.go 21 KB

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