interface.go 18 KB

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