interface.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/netip"
  8. "runtime"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/gaissmai/bart"
  13. "github.com/rcrowley/go-metrics"
  14. "github.com/slackhq/nebula/config"
  15. "github.com/slackhq/nebula/firewall"
  16. "github.com/slackhq/nebula/header"
  17. "github.com/slackhq/nebula/overlay"
  18. "github.com/slackhq/nebula/overlay/batch"
  19. "github.com/slackhq/nebula/overlay/tio"
  20. "github.com/slackhq/nebula/udp"
  21. )
  22. const mtu = 9001
  23. type InterfaceConfig struct {
  24. HostMap *HostMap
  25. Outside udp.Conn
  26. Inside overlay.Device
  27. pki *PKI
  28. Cipher string
  29. Firewall *Firewall
  30. DnsServer *dnsServer
  31. HandshakeManager *HandshakeManager
  32. lightHouse *LightHouse
  33. connectionManager *connectionManager
  34. DropLocalBroadcast bool
  35. DropMulticast bool
  36. routines int
  37. MessageMetrics *MessageMetrics
  38. version string
  39. relayManager *relayManager
  40. punchy *Punchy
  41. tryPromoteEvery uint32
  42. reQueryEvery uint32
  43. reQueryWait time.Duration
  44. ConntrackCacheTimeout time.Duration
  45. // CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  46. // should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
  47. // shorter lists than `routines` cycle. Empty list keeps the default
  48. // pin-to-(i % NumCPU) behavior.
  49. CpuAffinity []int
  50. l *slog.Logger
  51. }
  52. type Interface struct {
  53. hostMap *HostMap
  54. outside udp.Conn
  55. inside overlay.Device
  56. pki *PKI
  57. firewall *Firewall
  58. connectionManager *connectionManager
  59. handshakeManager *HandshakeManager
  60. dnsServer *dnsServer
  61. createTime time.Time
  62. lightHouse *LightHouse
  63. myBroadcastAddrsTable *bart.Lite
  64. myVpnAddrs []netip.Addr // A list of addresses assigned to us via our certificate
  65. myVpnAddrsTable *bart.Lite
  66. myVpnNetworks []netip.Prefix // A list of networks assigned to us via our certificate
  67. myVpnNetworksTable *bart.Lite
  68. dropLocalBroadcast bool
  69. dropMulticast bool
  70. routines int
  71. disconnectInvalid atomic.Bool
  72. closed atomic.Bool
  73. // cpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  74. // should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
  75. // Empty falls back to the default pin-to-(i % NumCPU) behavior.
  76. cpuAffinity []int
  77. // ecnEnabled gates RFC 6040 underlay ECN propagation. When true,
  78. // inside.go copies the inner ECN onto the outer carrier on encap and
  79. // decryptToTun folds outer CE into the inner header on decap. Toggle
  80. // via tunnels.ecn (default true).
  81. ecnEnabled atomic.Bool
  82. relayManager *relayManager
  83. tryPromoteEvery atomic.Uint32
  84. reQueryEvery atomic.Uint32
  85. reQueryWait atomic.Int64
  86. sendRecvErrorConfig recvErrorConfig
  87. acceptRecvErrorConfig recvErrorConfig
  88. // rebindCount is used to decide if an active tunnel should trigger a punch notification through a lighthouse
  89. rebindCount int8
  90. version string
  91. conntrackCacheTimeout time.Duration
  92. ctx context.Context
  93. writers []udp.Conn
  94. readers []tio.Queue
  95. // batchers is one per tun queue, wrapping readers[i].
  96. // decryptToTun sends plaintext into the batch.RxBatcher;
  97. // listenOut calls its Flush at the end of each UDP recvmmsg batch.
  98. batchers []batch.RxBatcher
  99. wg sync.WaitGroup
  100. // fatalErr holds the first unexpected reader error that caused shutdown.
  101. // nil means "no fatal error" (yet)
  102. fatalErr atomic.Pointer[error]
  103. // triggerShutdown is a function that will be run exactly once, when onFatal swaps something non-nil into fatalErr
  104. triggerShutdown func()
  105. metricHandshakes metrics.Histogram
  106. messageMetrics *MessageMetrics
  107. cachedPacketMetrics *cachedPacketMetrics
  108. l *slog.Logger
  109. }
  110. type EncWriter interface {
  111. SendVia(via *HostInfo,
  112. relay *Relay,
  113. ad,
  114. nb,
  115. out []byte,
  116. nocopy bool,
  117. )
  118. SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
  119. SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
  120. Handshake(vpnAddr netip.Addr)
  121. GetHostInfo(vpnAddr netip.Addr) *HostInfo
  122. GetCertState() *CertState
  123. }
  124. type recvErrorConfig uint8
  125. const (
  126. recvErrorAlways recvErrorConfig = iota
  127. recvErrorNever
  128. recvErrorPrivate
  129. )
  130. func (s recvErrorConfig) ShouldRecvError(endpoint netip.AddrPort) bool {
  131. switch s {
  132. case recvErrorPrivate:
  133. return endpoint.Addr().IsPrivate()
  134. case recvErrorAlways:
  135. return true
  136. case recvErrorNever:
  137. return false
  138. default:
  139. panic(fmt.Errorf("invalid recvErrorConfig value: %d", s))
  140. }
  141. }
  142. func (s recvErrorConfig) String() string {
  143. switch s {
  144. case recvErrorAlways:
  145. return "always"
  146. case recvErrorNever:
  147. return "never"
  148. case recvErrorPrivate:
  149. return "private"
  150. default:
  151. return fmt.Sprintf("invalid(%d)", s)
  152. }
  153. }
  154. func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
  155. if c.Outside == nil {
  156. return nil, errors.New("no outside connection")
  157. }
  158. if c.Inside == nil {
  159. return nil, errors.New("no inside interface (tun)")
  160. }
  161. if c.pki == nil {
  162. return nil, errors.New("no certificate state")
  163. }
  164. if c.Firewall == nil {
  165. return nil, errors.New("no firewall rules")
  166. }
  167. if c.connectionManager == nil {
  168. return nil, errors.New("no connection manager")
  169. }
  170. cs := c.pki.getCertState()
  171. ifce := &Interface{
  172. ctx: ctx,
  173. pki: c.pki,
  174. hostMap: c.HostMap,
  175. outside: c.Outside,
  176. inside: c.Inside,
  177. firewall: c.Firewall,
  178. dnsServer: c.DnsServer,
  179. handshakeManager: c.HandshakeManager,
  180. createTime: time.Now(),
  181. lightHouse: c.lightHouse,
  182. dropLocalBroadcast: c.DropLocalBroadcast,
  183. dropMulticast: c.DropMulticast,
  184. routines: c.routines,
  185. version: c.version,
  186. writers: make([]udp.Conn, c.routines),
  187. readers: make([]tio.Queue, c.routines),
  188. batchers: make([]batch.RxBatcher, c.routines),
  189. myVpnNetworks: cs.myVpnNetworks,
  190. myVpnNetworksTable: cs.myVpnNetworksTable,
  191. myVpnAddrs: cs.myVpnAddrs,
  192. myVpnAddrsTable: cs.myVpnAddrsTable,
  193. myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
  194. relayManager: c.relayManager,
  195. connectionManager: c.connectionManager,
  196. conntrackCacheTimeout: c.ConntrackCacheTimeout,
  197. cpuAffinity: c.CpuAffinity,
  198. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  199. messageMetrics: c.MessageMetrics,
  200. cachedPacketMetrics: &cachedPacketMetrics{
  201. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  202. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  203. },
  204. l: c.l,
  205. }
  206. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  207. ifce.reQueryEvery.Store(c.reQueryEvery)
  208. ifce.reQueryWait.Store(int64(c.reQueryWait))
  209. ifce.connectionManager.intf = ifce
  210. return ifce, nil
  211. }
  212. // activate creates the interface on the host. After the interface is created, any
  213. // other services that want to bind listeners to its IP may do so successfully. However,
  214. // the interface isn't going to process anything until run() is called.
  215. func (f *Interface) activate() error {
  216. // actually turn on tun dev
  217. addr, err := f.outside.LocalAddr()
  218. if err != nil {
  219. f.l.Error("Failed to get udp listen address", "error", err)
  220. }
  221. f.l.Info("Nebula interface is active",
  222. "interface", f.inside.Name(),
  223. "networks", f.myVpnNetworks,
  224. "build", f.version,
  225. "udpAddr", addr,
  226. "boringcrypto", boringEnabled(),
  227. )
  228. if f.routines > 1 {
  229. if !f.inside.SupportsMultiqueue() || !f.outside.SupportsMultipleReaders() {
  230. f.routines = 1
  231. f.l.Warn("routines is not supported on this platform, falling back to a single routine")
  232. }
  233. }
  234. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  235. // Prepare n tun queues
  236. for i := 0; i < f.routines; i++ {
  237. if i > 0 {
  238. if err = f.inside.NewMultiQueueReader(); err != nil {
  239. return err
  240. }
  241. }
  242. }
  243. f.readers = f.inside.Readers()
  244. for i := range f.readers {
  245. caps := tio.QueueCapabilities(f.readers[i])
  246. if caps.TSO || caps.USO {
  247. // Multi-lane: TCP gets coalesced when TSO is on, UDP when USO
  248. // is on, everything else (and either lane disabled) falls
  249. // through to passthrough so non-IP / non-TCP-UDP traffic still
  250. // reaches the TUN.
  251. f.batchers[i] = batch.NewMultiCoalescer(f.readers[i], caps.TSO, caps.USO)
  252. } else {
  253. f.batchers[i] = batch.NewPassthrough(f.readers[i])
  254. }
  255. }
  256. f.wg.Add(1) // for us to wait on Close() to return
  257. if err = f.inside.Activate(); err != nil {
  258. f.wg.Done()
  259. f.inside.Close()
  260. return err
  261. }
  262. return nil
  263. }
  264. func (f *Interface) run() (func() error, error) {
  265. // Launch n queues to read packets from udp
  266. for i := 0; i < f.routines; i++ {
  267. f.wg.Go(func() {
  268. f.listenOut(i)
  269. })
  270. }
  271. // Launch n queues to read packets from tun dev
  272. for i := 0; i < f.routines; i++ {
  273. f.wg.Go(func() {
  274. f.listenIn(f.readers[i], i)
  275. })
  276. }
  277. return func() error {
  278. f.wg.Wait()
  279. if e := f.fatalErr.Load(); e != nil {
  280. return *e
  281. }
  282. return nil
  283. }, nil
  284. }
  285. // onFatal stores the first fatal reader error, and calls triggerShutdown if it was the first one
  286. func (f *Interface) onFatal(err error) {
  287. swapped := f.fatalErr.CompareAndSwap(nil, &err)
  288. if !swapped {
  289. return
  290. }
  291. if f.triggerShutdown != nil {
  292. f.triggerShutdown()
  293. }
  294. }
  295. func (f *Interface) listenOut(i int) {
  296. var li udp.Conn
  297. if i > 0 {
  298. li = f.writers[i]
  299. } else {
  300. li = f.outside
  301. }
  302. ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  303. lhh := f.lightHouse.NewRequestHandler()
  304. h := &header.H{}
  305. fwPacket := &firewall.Packet{}
  306. nb := make([]byte, 12, 12)
  307. listener := func(fromUdpAddr netip.AddrPort, payload []byte, meta udp.RxMeta) {
  308. plaintext := f.batchers[i].Reserve(len(payload))
  309. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, plaintext[:0], payload, h, fwPacket, lhh, nb, i, ctCache.Get(), meta)
  310. }
  311. flusher := func() {
  312. if err := f.batchers[i].Flush(); err != nil {
  313. f.l.Error("Failed to flush tun coalescer", "error", err)
  314. }
  315. }
  316. err := li.ListenOut(listener, flusher)
  317. if err != nil && !f.closed.Load() {
  318. f.l.Error("Error while reading inbound packet, closing", "error", err)
  319. f.onFatal(err)
  320. }
  321. f.l.Debug("underlay reader is done", "reader", i)
  322. }
  323. func (f *Interface) listenIn(reader tio.Queue, i int) {
  324. // Pin this goroutine to one CPU. LockOSThread alone keeps the goroutine
  325. // on a single OS thread but the kernel can still migrate that thread
  326. // across CPUs — XPS reads smp_processor_id() at sendmmsg time and picks
  327. // the TX ring from the current CPU's xps_cpus map, so an unpinned
  328. // thread bouncing between CPUs spreads one nebula flow's packets across
  329. // multiple TX rings, which the rings then drain at independent rates
  330. // and the wire delivers reordered.
  331. //
  332. // Pinning keeps every sendmmsg from this goroutine going through the
  333. // same TX ring, so the wire sees per-flow order. Cost: less scheduler
  334. // flexibility — if i % NumCPU collides between two TUN reader
  335. // goroutines they share a CPU.
  336. cpu := i % runtime.NumCPU()
  337. if n := len(f.cpuAffinity); n > 0 {
  338. cpu = f.cpuAffinity[i%n]
  339. }
  340. if err := pinThreadToCPU(cpu); err != nil {
  341. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  342. }
  343. rejectBuf := make([]byte, mtu)
  344. sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, udp.MTU+32)
  345. fwPacket := &firewall.Packet{}
  346. nb := make([]byte, 12, 12)
  347. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  348. for {
  349. pkts, err := reader.Read()
  350. if err != nil {
  351. if !f.closed.Load() {
  352. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  353. f.onFatal(err)
  354. }
  355. break
  356. }
  357. for _, pkt := range pkts {
  358. f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
  359. }
  360. if err := sb.Flush(); err != nil {
  361. f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
  362. }
  363. }
  364. f.l.Debug("overlay reader is done", "reader", i)
  365. }
  366. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  367. c.RegisterReloadCallback(f.reloadFirewall)
  368. c.RegisterReloadCallback(f.reloadSendRecvError)
  369. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  370. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  371. c.RegisterReloadCallback(f.reloadMisc)
  372. c.RegisterReloadCallback(f.reloadEcn)
  373. for _, udpConn := range f.writers {
  374. c.RegisterReloadCallback(udpConn.ReloadConfig)
  375. }
  376. }
  377. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  378. initial := c.InitialLoad()
  379. if initial || c.HasChanged("pki.disconnect_invalid") {
  380. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  381. if !initial {
  382. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  383. }
  384. }
  385. }
  386. func (f *Interface) reloadFirewall(c *config.C) {
  387. //TODO: need to trigger/detect if the certificate changed too
  388. if c.HasChanged("firewall") == false {
  389. f.l.Debug("No firewall config change detected")
  390. return
  391. }
  392. fw, err := NewFirewallFromConfig(f.l, f.pki.getCertState(), c)
  393. if err != nil {
  394. f.l.Error("Error while creating firewall during reload", "error", err)
  395. return
  396. }
  397. oldFw := f.firewall
  398. conntrack := oldFw.Conntrack
  399. conntrack.Lock()
  400. defer conntrack.Unlock()
  401. fw.rulesVersion = oldFw.rulesVersion + 1
  402. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  403. // safe and just reset conntrack in this case.
  404. if fw.rulesVersion == 0 {
  405. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  406. "firewallHashes", fw.GetRuleHashes(),
  407. "oldFirewallHashes", oldFw.GetRuleHashes(),
  408. "rulesVersion", fw.rulesVersion,
  409. )
  410. } else {
  411. fw.Conntrack = conntrack
  412. }
  413. f.firewall = fw
  414. oldFw.Destroy()
  415. f.l.Info("New firewall has been installed",
  416. "firewallHashes", fw.GetRuleHashes(),
  417. "oldFirewallHashes", oldFw.GetRuleHashes(),
  418. "rulesVersion", fw.rulesVersion,
  419. )
  420. }
  421. func (f *Interface) reloadSendRecvError(c *config.C) {
  422. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  423. stringValue := c.GetString("listen.send_recv_error", "always")
  424. switch stringValue {
  425. case "always":
  426. f.sendRecvErrorConfig = recvErrorAlways
  427. case "never":
  428. f.sendRecvErrorConfig = recvErrorNever
  429. case "private":
  430. f.sendRecvErrorConfig = recvErrorPrivate
  431. default:
  432. if c.GetBool("listen.send_recv_error", true) {
  433. f.sendRecvErrorConfig = recvErrorAlways
  434. } else {
  435. f.sendRecvErrorConfig = recvErrorNever
  436. }
  437. }
  438. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  439. }
  440. }
  441. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  442. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  443. stringValue := c.GetString("listen.accept_recv_error", "always")
  444. switch stringValue {
  445. case "always":
  446. f.acceptRecvErrorConfig = recvErrorAlways
  447. case "never":
  448. f.acceptRecvErrorConfig = recvErrorNever
  449. case "private":
  450. f.acceptRecvErrorConfig = recvErrorPrivate
  451. default:
  452. if c.GetBool("listen.accept_recv_error", true) {
  453. f.acceptRecvErrorConfig = recvErrorAlways
  454. } else {
  455. f.acceptRecvErrorConfig = recvErrorNever
  456. }
  457. }
  458. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  459. }
  460. }
  461. func (f *Interface) reloadMisc(c *config.C) {
  462. if c.HasChanged("counters.try_promote") {
  463. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  464. f.tryPromoteEvery.Store(n)
  465. f.l.Info("counters.try_promote has changed")
  466. }
  467. if c.HasChanged("counters.requery_every_packets") {
  468. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  469. f.reQueryEvery.Store(n)
  470. f.l.Info("counters.requery_every_packets has changed")
  471. }
  472. if c.HasChanged("timers.requery_wait_duration") {
  473. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  474. f.reQueryWait.Store(int64(n))
  475. f.l.Info("timers.requery_wait_duration has changed")
  476. }
  477. }
  478. // reloadEcn syncs Interface.ecnEnabled with the tunnels.ecn config knob.
  479. // Default is enabled (RFC 6040 normal mode); set false on the rare path
  480. // where an underlay middlebox rewrites or drops ECN bits unpredictably.
  481. func (f *Interface) reloadEcn(c *config.C) {
  482. initial := c.InitialLoad()
  483. if initial || c.HasChanged("tunnels.ecn") {
  484. v := c.GetBool("tunnels.ecn", true)
  485. f.ecnEnabled.Store(v)
  486. if !initial {
  487. f.l.Info("tunnels.ecn changed", "enabled", v)
  488. }
  489. }
  490. }
  491. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  492. ticker := time.NewTicker(i)
  493. defer ticker.Stop()
  494. udpStats := udp.NewUDPStatsEmitter(f.writers)
  495. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  496. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  497. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  498. for {
  499. select {
  500. case <-ctx.Done():
  501. return
  502. case <-ticker.C:
  503. f.firewall.EmitStats()
  504. f.handshakeManager.EmitStats()
  505. udpStats()
  506. certState := f.pki.getCertState()
  507. defaultCrt := certState.GetDefaultCertificate()
  508. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  509. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  510. // Report the max certificate version we are capable of using
  511. if certState.v2Cert != nil {
  512. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  513. } else {
  514. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  515. }
  516. }
  517. }
  518. }
  519. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  520. return f.hostMap.QueryVpnAddr(vpnIp)
  521. }
  522. func (f *Interface) GetCertState() *CertState {
  523. return f.pki.getCertState()
  524. }
  525. func (f *Interface) Close() error {
  526. var errs []error
  527. f.closed.Store(true)
  528. // Release the udp readers
  529. for i, u := range f.writers {
  530. err := u.Close()
  531. if err != nil {
  532. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  533. errs = append(errs, err)
  534. }
  535. }
  536. // Release the tun device (closing the tun also closes all readers)
  537. closeErr := f.inside.Close()
  538. if closeErr != nil {
  539. errs = append(errs, closeErr)
  540. }
  541. f.wg.Done()
  542. return errors.Join(errs...)
  543. }