tun_linux.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package overlay
  4. import (
  5. "encoding/binary"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/netip"
  10. "os"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "syscall"
  16. "time"
  17. "unsafe"
  18. "github.com/gaissmai/bart"
  19. "github.com/sirupsen/logrus"
  20. "github.com/slackhq/nebula/config"
  21. "github.com/slackhq/nebula/routing"
  22. "github.com/slackhq/nebula/util"
  23. "github.com/vishvananda/netlink"
  24. "golang.org/x/sys/unix"
  25. )
  26. // tunFile wraps a TUN file descriptor with poll-based reads. The FD provided will be changed to non-blocking.
  27. // A shared eventfd allows Close to wake all readers blocked in poll.
  28. type tunFile struct {
  29. fd int
  30. shutdownFd int
  31. lastOne bool
  32. readPoll [2]unix.PollFd
  33. writePoll [2]unix.PollFd
  34. closed bool
  35. // vnetHdr is true when this fd was opened with IFF_VNET_HDR and the
  36. // kernel successfully accepted TUNSETOFFLOAD. Reads include a leading
  37. // virtio_net_hdr and may carry a TSO superpacket we must segment;
  38. // writes must prepend a zeroed virtio_net_hdr.
  39. vnetHdr bool
  40. readBuf []byte // scratch for a single raw read (virtio hdr + superpacket)
  41. segBuf []byte // backing store for segmented output
  42. segOff int // cursor into segBuf for the current Read drain
  43. pending [][]byte // segments returned from the most recent Read
  44. writeIovs [2]unix.Iovec // preallocated iovecs for Write (coalescer passthrough); iovs[0] is fixed to validVnetHdr
  45. // rejectIovs is a second preallocated iovec scratch used exclusively by
  46. // WriteReject (reject + self-forward from the inside path). It mirrors
  47. // writeIovs but lets listenIn goroutines emit reject packets without
  48. // racing with the listenOut coalescer that owns writeIovs.
  49. rejectIovs [2]unix.Iovec
  50. // gsoHdrBuf is a per-queue 10-byte scratch for the virtio_net_hdr emitted
  51. // by WriteGSO. Separate from validVnetHdr so a concurrent non-GSO Write on
  52. // another queue never observes a half-written header.
  53. gsoHdrBuf [virtioNetHdrLen]byte
  54. // gsoIovs is the writev iovec scratch for WriteGSO. Sized to hold the
  55. // virtio header + IP/TCP header + up to gsoInitialPayIovs payload
  56. // fragments; grown on demand if a coalescer pushes more.
  57. gsoIovs []unix.Iovec
  58. }
  59. // gsoInitialPayIovs is the starting capacity (in payload fragments) of
  60. // tunFile.gsoIovs. Sized to cover the default coalesce segment cap without
  61. // any reallocations.
  62. const gsoInitialPayIovs = 66
  63. // validVnetHdr is the 10-byte virtio_net_hdr we prepend to every non-GSO TUN
  64. // write. Only flag set is VIRTIO_NET_HDR_F_DATA_VALID, which marks the skb
  65. // CHECKSUM_UNNECESSARY so the receiving network stack skips L4 checksum
  66. // verification. All packets that reach the plain Write / WriteReject paths
  67. // already carry a valid L4 checksum (either supplied by a remote peer whose
  68. // ciphertext we AEAD-authenticated, or produced by finishChecksum during TSO
  69. // segmentation, or built locally by CreateRejectPacket), so trusting them is
  70. // safe.
  71. var validVnetHdr = [virtioNetHdrLen]byte{unix.VIRTIO_NET_HDR_F_DATA_VALID}
  72. // newFriend makes a tunFile for a MultiQueueReader that copies the shutdown eventfd from the parent tun
  73. func (r *tunFile) newFriend(fd int) (*tunFile, error) {
  74. if err := unix.SetNonblock(fd, true); err != nil {
  75. return nil, fmt.Errorf("failed to set tun fd non-blocking: %w", err)
  76. }
  77. out := &tunFile{
  78. fd: fd,
  79. shutdownFd: r.shutdownFd,
  80. vnetHdr: r.vnetHdr,
  81. readBuf: make([]byte, tunReadBufSize),
  82. readPoll: [2]unix.PollFd{
  83. {Fd: int32(fd), Events: unix.POLLIN},
  84. {Fd: int32(r.shutdownFd), Events: unix.POLLIN},
  85. },
  86. writePoll: [2]unix.PollFd{
  87. {Fd: int32(fd), Events: unix.POLLOUT},
  88. {Fd: int32(r.shutdownFd), Events: unix.POLLIN},
  89. },
  90. }
  91. if r.vnetHdr {
  92. out.segBuf = make([]byte, tunSegBufCap)
  93. out.writeIovs[0].Base = &validVnetHdr[0]
  94. out.writeIovs[0].SetLen(virtioNetHdrLen)
  95. out.rejectIovs[0].Base = &validVnetHdr[0]
  96. out.rejectIovs[0].SetLen(virtioNetHdrLen)
  97. out.gsoIovs = make([]unix.Iovec, 2, 2+gsoInitialPayIovs)
  98. out.gsoIovs[0].Base = &out.gsoHdrBuf[0]
  99. out.gsoIovs[0].SetLen(virtioNetHdrLen)
  100. }
  101. return out, nil
  102. }
  103. func newTunFd(fd int, vnetHdr bool) (*tunFile, error) {
  104. if err := unix.SetNonblock(fd, true); err != nil {
  105. return nil, fmt.Errorf("failed to set tun fd non-blocking: %w", err)
  106. }
  107. shutdownFd, err := unix.Eventfd(0, unix.EFD_NONBLOCK|unix.EFD_CLOEXEC)
  108. if err != nil {
  109. return nil, fmt.Errorf("failed to create eventfd: %w", err)
  110. }
  111. out := &tunFile{
  112. fd: fd,
  113. shutdownFd: shutdownFd,
  114. lastOne: true,
  115. vnetHdr: vnetHdr,
  116. readBuf: make([]byte, tunReadBufSize),
  117. readPoll: [2]unix.PollFd{
  118. {Fd: int32(fd), Events: unix.POLLIN},
  119. {Fd: int32(shutdownFd), Events: unix.POLLIN},
  120. },
  121. writePoll: [2]unix.PollFd{
  122. {Fd: int32(fd), Events: unix.POLLOUT},
  123. {Fd: int32(shutdownFd), Events: unix.POLLIN},
  124. },
  125. }
  126. if vnetHdr {
  127. out.segBuf = make([]byte, tunSegBufCap)
  128. out.writeIovs[0].Base = &validVnetHdr[0]
  129. out.writeIovs[0].SetLen(virtioNetHdrLen)
  130. out.rejectIovs[0].Base = &validVnetHdr[0]
  131. out.rejectIovs[0].SetLen(virtioNetHdrLen)
  132. out.gsoIovs = make([]unix.Iovec, 2, 2+gsoInitialPayIovs)
  133. out.gsoIovs[0].Base = &out.gsoHdrBuf[0]
  134. out.gsoIovs[0].SetLen(virtioNetHdrLen)
  135. }
  136. return out, nil
  137. }
  138. func (r *tunFile) blockOnRead() error {
  139. const problemFlags = unix.POLLHUP | unix.POLLNVAL | unix.POLLERR
  140. var err error
  141. for {
  142. _, err = unix.Poll(r.readPoll[:], -1)
  143. if err != unix.EINTR {
  144. break
  145. }
  146. }
  147. //always reset these!
  148. tunEvents := r.readPoll[0].Revents
  149. shutdownEvents := r.readPoll[1].Revents
  150. r.readPoll[0].Revents = 0
  151. r.readPoll[1].Revents = 0
  152. //do the err check before trusting the potentially bogus bits we just got
  153. if err != nil {
  154. return err
  155. }
  156. if shutdownEvents&(unix.POLLIN|problemFlags) != 0 {
  157. return os.ErrClosed
  158. } else if tunEvents&problemFlags != 0 {
  159. return os.ErrClosed
  160. }
  161. return nil
  162. }
  163. func (r *tunFile) blockOnWrite() error {
  164. const problemFlags = unix.POLLHUP | unix.POLLNVAL | unix.POLLERR
  165. var err error
  166. for {
  167. _, err = unix.Poll(r.writePoll[:], -1)
  168. if err != unix.EINTR {
  169. break
  170. }
  171. }
  172. //always reset these!
  173. tunEvents := r.writePoll[0].Revents
  174. shutdownEvents := r.writePoll[1].Revents
  175. r.writePoll[0].Revents = 0
  176. r.writePoll[1].Revents = 0
  177. //do the err check before trusting the potentially bogus bits we just got
  178. if err != nil {
  179. return err
  180. }
  181. if shutdownEvents&(unix.POLLIN|problemFlags) != 0 {
  182. return os.ErrClosed
  183. } else if tunEvents&problemFlags != 0 {
  184. return os.ErrClosed
  185. }
  186. return nil
  187. }
  188. func (r *tunFile) readRaw(buf []byte) (int, error) {
  189. for {
  190. if n, err := unix.Read(r.fd, buf); err == nil {
  191. return n, nil
  192. } else if err == unix.EAGAIN {
  193. if err = r.blockOnRead(); err != nil {
  194. return 0, err
  195. }
  196. continue
  197. } else {
  198. return 0, err
  199. }
  200. }
  201. }
  202. // Read reads one or more superpackets from the tun and returns the
  203. // resulting packets. The first read blocks via poll; once the fd is known
  204. // readable we drain additional packets non-blocking until the kernel queue
  205. // is empty (EAGAIN), we've collected tunDrainCap packets, or we're out of
  206. // segBuf headroom. This amortizes the poll wake over bursts of small
  207. // packets (e.g. TCP ACKs). Slices point into the tunFile's internal buffers
  208. // and are only valid until the next Read or Close on this Queue.
  209. func (r *tunFile) Read() ([][]byte, error) {
  210. r.pending = r.pending[:0]
  211. r.segOff = 0
  212. // Initial (blocking) read. Retry on decode errors so a single bad
  213. // packet does not stall the reader.
  214. for {
  215. n, err := r.readRaw(r.readBuf)
  216. if err != nil {
  217. return nil, err
  218. }
  219. if !r.vnetHdr {
  220. r.pending = append(r.pending, r.readBuf[:n])
  221. // Non-vnetHdr mode shares one readBuf so we can't drain safely
  222. // without copying; return the single packet as before.
  223. return r.pending, nil
  224. }
  225. if err := r.decodeRead(n); err != nil {
  226. // Drop and read again — a bad packet should not kill the reader.
  227. continue
  228. }
  229. break
  230. }
  231. // Drain: non-blocking reads until the kernel queue is empty, the drain
  232. // cap is reached, or segBuf no longer has room for another worst-case
  233. // superpacket.
  234. for len(r.pending) < tunDrainCap && tunSegBufCap-r.segOff >= tunSegBufSize {
  235. n, err := unix.Read(r.fd, r.readBuf)
  236. if err != nil {
  237. // EAGAIN / EINTR / anything else: stop draining. We already
  238. // have a valid batch from the first read.
  239. break
  240. }
  241. if n <= 0 {
  242. break
  243. }
  244. if err := r.decodeRead(n); err != nil {
  245. // Drop this packet and stop the drain; we'd rather hand off
  246. // what we have than keep spinning here.
  247. break
  248. }
  249. }
  250. return r.pending, nil
  251. }
  252. // decodeRead decodes the virtio header plus payload in r.readBuf[:n], appends
  253. // the segments to r.pending, and advances r.segOff by the total scratch used.
  254. // Caller must have already ensured r.vnetHdr is true.
  255. func (r *tunFile) decodeRead(n int) error {
  256. if n < virtioNetHdrLen {
  257. return fmt.Errorf("short tun read: %d < %d", n, virtioNetHdrLen)
  258. }
  259. var hdr virtioNetHdr
  260. hdr.decode(r.readBuf[:virtioNetHdrLen])
  261. before := len(r.pending)
  262. if err := segmentInto(r.readBuf[virtioNetHdrLen:n], hdr, &r.pending, r.segBuf[r.segOff:]); err != nil {
  263. return err
  264. }
  265. for k := before; k < len(r.pending); k++ {
  266. r.segOff += len(r.pending[k])
  267. }
  268. return nil
  269. }
  270. func (r *tunFile) Write(buf []byte) (int, error) {
  271. return r.writeWithScratch(buf, &r.writeIovs)
  272. }
  273. // WriteReject emits a packet using a dedicated iovec scratch (rejectIovs)
  274. // distinct from the one used by the coalescer's Write path. This avoids a
  275. // data race between the inside (listenIn) goroutine emitting reject or
  276. // self-forward packets and the outside (listenOut) goroutine flushing TCP
  277. // coalescer passthroughs on the same tunFile.
  278. func (r *tunFile) WriteReject(buf []byte) (int, error) {
  279. return r.writeWithScratch(buf, &r.rejectIovs)
  280. }
  281. func (r *tunFile) writeWithScratch(buf []byte, iovs *[2]unix.Iovec) (int, error) {
  282. if !r.vnetHdr {
  283. for {
  284. if n, err := unix.Write(r.fd, buf); err == nil {
  285. return n, nil
  286. } else if err == unix.EAGAIN {
  287. if err = r.blockOnWrite(); err != nil {
  288. return 0, err
  289. }
  290. continue
  291. } else if err == unix.EINTR {
  292. continue
  293. } else {
  294. return 0, err
  295. }
  296. }
  297. }
  298. if len(buf) == 0 {
  299. return 0, nil
  300. }
  301. // Point the payload iovec at the caller's buffer. iovs[0] is pre-wired
  302. // to validVnetHdr during tunFile construction so we don't rebuild it here.
  303. iovs[1].Base = &buf[0]
  304. iovs[1].SetLen(len(buf))
  305. iovPtr := uintptr(unsafe.Pointer(&iovs[0]))
  306. // The TUN fd is non-blocking (set in newTunFd / newFriend), so writev
  307. // either completes promptly or returns EAGAIN — it cannot park the
  308. // goroutine inside the kernel. That lets us use syscall.RawSyscall and
  309. // skip the runtime.entersyscall / exitsyscall bookkeeping on every
  310. // packet; we only pay that cost when we fall through to blockOnWrite.
  311. for {
  312. n, _, errno := syscall.RawSyscall(unix.SYS_WRITEV, uintptr(r.fd), iovPtr, 2)
  313. if errno == 0 {
  314. runtime.KeepAlive(buf)
  315. if int(n) < virtioNetHdrLen {
  316. return 0, io.ErrShortWrite
  317. }
  318. return int(n) - virtioNetHdrLen, nil
  319. }
  320. if errno == unix.EAGAIN {
  321. runtime.KeepAlive(buf)
  322. if err := r.blockOnWrite(); err != nil {
  323. return 0, err
  324. }
  325. continue
  326. }
  327. if errno == unix.EINTR {
  328. continue
  329. }
  330. runtime.KeepAlive(buf)
  331. return 0, errno
  332. }
  333. }
  334. // GSOSupported reports whether this queue was opened with IFF_VNET_HDR and
  335. // can accept WriteGSO. When false, callers should fall back to per-segment
  336. // Write calls.
  337. func (r *tunFile) GSOSupported() bool { return r.vnetHdr }
  338. // WriteGSO emits a TCP TSO superpacket in a single writev. hdr is the
  339. // IPv4/IPv6 + TCP header prefix (already finalized — total length, IP csum,
  340. // and TCP pseudo-header partial set by the caller). pays are payload
  341. // fragments whose concatenation forms the full coalesced payload; each
  342. // slice is read-only and must stay valid until return. gsoSize is the MSS;
  343. // every segment except possibly the last is exactly gsoSize bytes.
  344. // csumStart is the byte offset where the TCP header begins within hdr.
  345. func (r *tunFile) WriteGSO(hdr []byte, pays [][]byte, gsoSize uint16, isV6 bool, csumStart uint16) error {
  346. if !r.vnetHdr {
  347. return fmt.Errorf("WriteGSO called on tun without IFF_VNET_HDR")
  348. }
  349. if len(hdr) == 0 || len(pays) == 0 {
  350. return nil
  351. }
  352. // Build the virtio_net_hdr. When pays total to <= gsoSize the kernel
  353. // would produce a single segment; keep NEEDS_CSUM semantics but skip
  354. // the GSO type so the kernel doesn't spuriously mark this as TSO.
  355. vhdr := virtioNetHdr{
  356. Flags: unix.VIRTIO_NET_HDR_F_NEEDS_CSUM,
  357. HdrLen: uint16(len(hdr)),
  358. GSOSize: gsoSize,
  359. CsumStart: csumStart,
  360. CsumOffset: 16, // TCP checksum field lives 16 bytes into the TCP header
  361. }
  362. var totalPay int
  363. for _, p := range pays {
  364. totalPay += len(p)
  365. }
  366. if totalPay > int(gsoSize) {
  367. if isV6 {
  368. vhdr.GSOType = unix.VIRTIO_NET_HDR_GSO_TCPV6
  369. } else {
  370. vhdr.GSOType = unix.VIRTIO_NET_HDR_GSO_TCPV4
  371. }
  372. } else {
  373. vhdr.GSOType = unix.VIRTIO_NET_HDR_GSO_NONE
  374. vhdr.GSOSize = 0
  375. }
  376. vhdr.encode(r.gsoHdrBuf[:])
  377. // Build the iovec array: [virtio_hdr, hdr, pays...]. r.gsoIovs[0] is
  378. // wired to gsoHdrBuf at construction and never changes.
  379. need := 2 + len(pays)
  380. if cap(r.gsoIovs) < need {
  381. grown := make([]unix.Iovec, need)
  382. grown[0] = r.gsoIovs[0]
  383. r.gsoIovs = grown
  384. } else {
  385. r.gsoIovs = r.gsoIovs[:need]
  386. }
  387. r.gsoIovs[1].Base = &hdr[0]
  388. r.gsoIovs[1].SetLen(len(hdr))
  389. for i, p := range pays {
  390. r.gsoIovs[2+i].Base = &p[0]
  391. r.gsoIovs[2+i].SetLen(len(p))
  392. }
  393. iovPtr := uintptr(unsafe.Pointer(&r.gsoIovs[0]))
  394. iovCnt := uintptr(len(r.gsoIovs))
  395. for {
  396. n, _, errno := syscall.RawSyscall(unix.SYS_WRITEV, uintptr(r.fd), iovPtr, iovCnt)
  397. if errno == 0 {
  398. runtime.KeepAlive(hdr)
  399. runtime.KeepAlive(pays)
  400. if int(n) < virtioNetHdrLen {
  401. return io.ErrShortWrite
  402. }
  403. return nil
  404. }
  405. if errno == unix.EAGAIN {
  406. runtime.KeepAlive(hdr)
  407. runtime.KeepAlive(pays)
  408. if err := r.blockOnWrite(); err != nil {
  409. return err
  410. }
  411. continue
  412. }
  413. if errno == unix.EINTR {
  414. continue
  415. }
  416. runtime.KeepAlive(hdr)
  417. runtime.KeepAlive(pays)
  418. return errno
  419. }
  420. }
  421. func (r *tunFile) wakeForShutdown() error {
  422. var buf [8]byte
  423. binary.NativeEndian.PutUint64(buf[:], 1)
  424. _, err := unix.Write(int(r.readPoll[1].Fd), buf[:])
  425. return err
  426. }
  427. func (r *tunFile) Close() error {
  428. if r.closed { // avoid closing more than once. Technically a fd could get re-used, which would be a problem
  429. return nil
  430. }
  431. r.closed = true
  432. if r.lastOne {
  433. _ = unix.Close(r.shutdownFd)
  434. }
  435. return unix.Close(r.fd)
  436. }
  437. type tun struct {
  438. *tunFile
  439. readers []*tunFile
  440. closeLock sync.Mutex
  441. Device string
  442. vpnNetworks []netip.Prefix
  443. MaxMTU int
  444. DefaultMTU int
  445. TXQueueLen int
  446. deviceIndex int
  447. ioctlFd uintptr
  448. Routes atomic.Pointer[[]Route]
  449. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  450. routeChan chan struct{}
  451. useSystemRoutes bool
  452. useSystemRoutesBufferSize int
  453. // These are routes learned from `tun.use_system_route_table`
  454. // stored here to make it easier to restore them after a reload
  455. routesFromSystem map[netip.Prefix]routing.Gateways
  456. routesFromSystemLock sync.Mutex
  457. l *logrus.Logger
  458. }
  459. func (t *tun) Networks() []netip.Prefix {
  460. return t.vpnNetworks
  461. }
  462. type ifReq struct {
  463. Name [16]byte
  464. Flags uint16
  465. pad [8]byte
  466. }
  467. type ifreqMTU struct {
  468. Name [16]byte
  469. MTU int32
  470. pad [8]byte
  471. }
  472. type ifreqQLEN struct {
  473. Name [16]byte
  474. Value int32
  475. pad [8]byte
  476. }
  477. func newTunFromFd(c *config.C, l *logrus.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
  478. // We don't know what flags the caller opened this fd with and can't turn
  479. // on IFF_VNET_HDR after TUNSETIFF, so skip offload on inherited fds.
  480. t, err := newTunGeneric(c, l, deviceFd, false, vpnNetworks)
  481. if err != nil {
  482. return nil, err
  483. }
  484. t.Device = "tun0"
  485. return t, nil
  486. }
  487. // openTunDev opens /dev/net/tun, creating the device node first if it's
  488. // missing (docker containers occasionally omit it).
  489. func openTunDev() (int, error) {
  490. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  491. if err == nil {
  492. return fd, nil
  493. }
  494. if !os.IsNotExist(err) {
  495. return -1, err
  496. }
  497. if err = os.MkdirAll("/dev/net", 0755); err != nil {
  498. return -1, fmt.Errorf("/dev/net/tun doesn't exist, failed to mkdir -p /dev/net: %w", err)
  499. }
  500. if err = unix.Mknod("/dev/net/tun", unix.S_IFCHR|0600, int(unix.Mkdev(10, 200))); err != nil {
  501. return -1, fmt.Errorf("failed to create /dev/net/tun: %w", err)
  502. }
  503. fd, err = unix.Open("/dev/net/tun", os.O_RDWR, 0)
  504. if err != nil {
  505. return -1, fmt.Errorf("created /dev/net/tun, but still failed: %w", err)
  506. }
  507. return fd, nil
  508. }
  509. // tunSetIff runs TUNSETIFF with the given flags and returns the kernel-chosen
  510. // device name on success.
  511. func tunSetIff(fd int, name string, flags uint16) (string, error) {
  512. var req ifReq
  513. req.Flags = flags
  514. copy(req.Name[:], name)
  515. if err := ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  516. return "", err
  517. }
  518. return strings.Trim(string(req.Name[:]), "\x00"), nil
  519. }
  520. // tsoOffloadFlags are the TUN_F_* bits we ask the kernel to enable when a
  521. // TSO-capable TUN is available. CSUM is required as a prerequisite for TSO.
  522. const tsoOffloadFlags = unix.TUN_F_CSUM | unix.TUN_F_TSO4 | unix.TUN_F_TSO6
  523. func newTun(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, multiqueue bool) (*tun, error) {
  524. baseFlags := uint16(unix.IFF_TUN | unix.IFF_NO_PI)
  525. if multiqueue {
  526. baseFlags |= unix.IFF_MULTI_QUEUE
  527. }
  528. nameStr := c.GetString("tun.dev", "")
  529. // First try to open with IFF_VNET_HDR + TUNSETOFFLOAD so we can receive
  530. // TSO superpackets. If either step fails (older kernel, unprivileged
  531. // container, etc.) we close and fall back to a plain TUN.
  532. fd, err := openTunDev()
  533. if err != nil {
  534. return nil, err
  535. }
  536. vnetHdr := true
  537. name, err := tunSetIff(fd, nameStr, baseFlags|unix.IFF_VNET_HDR|unix.IFF_NAPI)
  538. if err != nil {
  539. _ = unix.Close(fd)
  540. vnetHdr = false
  541. } else if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(tsoOffloadFlags)); err != nil {
  542. l.WithError(err).Warn("Failed to enable TUN offload (TSO); proceeding without virtio headers")
  543. _ = unix.Close(fd)
  544. vnetHdr = false
  545. }
  546. if !vnetHdr {
  547. fd, err = openTunDev()
  548. if err != nil {
  549. return nil, err
  550. }
  551. name, err = tunSetIff(fd, nameStr, baseFlags)
  552. if err != nil {
  553. _ = unix.Close(fd)
  554. return nil, &NameError{Name: nameStr, Underlying: err}
  555. }
  556. }
  557. t, err := newTunGeneric(c, l, fd, vnetHdr, vpnNetworks)
  558. if err != nil {
  559. return nil, err
  560. }
  561. t.Device = name
  562. return t, nil
  563. }
  564. // newTunGeneric does all the stuff common to different tun initialization paths. It will close your files on error.
  565. func newTunGeneric(c *config.C, l *logrus.Logger, fd int, vnetHdr bool, vpnNetworks []netip.Prefix) (*tun, error) {
  566. tfd, err := newTunFd(fd, vnetHdr)
  567. if err != nil {
  568. _ = unix.Close(fd)
  569. return nil, err
  570. }
  571. t := &tun{
  572. tunFile: tfd,
  573. readers: []*tunFile{tfd},
  574. closeLock: sync.Mutex{},
  575. vpnNetworks: vpnNetworks,
  576. TXQueueLen: c.GetInt("tun.tx_queue", 500),
  577. useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
  578. useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
  579. routesFromSystem: map[netip.Prefix]routing.Gateways{},
  580. l: l,
  581. }
  582. if err = t.reload(c, true); err != nil {
  583. _ = t.Close()
  584. return nil, err
  585. }
  586. c.RegisterReloadCallback(func(c *config.C) {
  587. err := t.reload(c, false)
  588. if err != nil {
  589. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  590. }
  591. })
  592. return t, nil
  593. }
  594. func (t *tun) reload(c *config.C, initial bool) error {
  595. routeChange, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
  596. if err != nil {
  597. return err
  598. }
  599. if !initial && !routeChange && !c.HasChanged("tun.mtu") {
  600. return nil
  601. }
  602. routeTree, err := makeRouteTree(t.l, routes, true)
  603. if err != nil {
  604. return err
  605. }
  606. // Bring along any routes learned from the system route table on reload
  607. t.routesFromSystemLock.Lock()
  608. for dst, gw := range t.routesFromSystem {
  609. routeTree.Insert(dst, gw)
  610. }
  611. t.routesFromSystemLock.Unlock()
  612. oldDefaultMTU := t.DefaultMTU
  613. oldMaxMTU := t.MaxMTU
  614. newDefaultMTU := c.GetInt("tun.mtu", DefaultMTU)
  615. newMaxMTU := newDefaultMTU
  616. for i, r := range routes {
  617. if r.MTU == 0 {
  618. routes[i].MTU = newDefaultMTU
  619. }
  620. if r.MTU > t.MaxMTU {
  621. newMaxMTU = r.MTU
  622. }
  623. }
  624. t.MaxMTU = newMaxMTU
  625. t.DefaultMTU = newDefaultMTU
  626. // Teach nebula how to handle the routes before establishing them in the system table
  627. oldRoutes := t.Routes.Swap(&routes)
  628. t.routeTree.Store(routeTree)
  629. if !initial {
  630. if oldMaxMTU != newMaxMTU {
  631. t.setMTU()
  632. t.l.Infof("Set max MTU to %v was %v", t.MaxMTU, oldMaxMTU)
  633. }
  634. if oldDefaultMTU != newDefaultMTU {
  635. for i := range t.vpnNetworks {
  636. err := t.setDefaultRoute(t.vpnNetworks[i])
  637. if err != nil {
  638. t.l.Warn(err)
  639. } else {
  640. t.l.Infof("Set default MTU to %v was %v", t.DefaultMTU, oldDefaultMTU)
  641. }
  642. }
  643. }
  644. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  645. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  646. // Ensure any routes we actually want are installed
  647. err = t.addRoutes(true)
  648. if err != nil {
  649. // This should never be called since addRoutes should log its own errors in a reload condition
  650. util.LogWithContextIfNeeded("Failed to refresh routes", err, t.l)
  651. }
  652. }
  653. return nil
  654. }
  655. func (t *tun) SupportsMultiqueue() bool {
  656. return true
  657. }
  658. func (t *tun) NewMultiQueueReader() (Queue, error) {
  659. t.closeLock.Lock()
  660. defer t.closeLock.Unlock()
  661. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  662. if err != nil {
  663. return nil, err
  664. }
  665. flags := uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_MULTI_QUEUE)
  666. if t.vnetHdr {
  667. flags |= unix.IFF_VNET_HDR | unix.IFF_NAPI
  668. }
  669. if _, err = tunSetIff(fd, t.Device, flags); err != nil {
  670. _ = unix.Close(fd)
  671. return nil, err
  672. }
  673. if t.vnetHdr {
  674. if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(tsoOffloadFlags)); err != nil {
  675. _ = unix.Close(fd)
  676. return nil, fmt.Errorf("failed to enable offload on multiqueue tun fd: %w", err)
  677. }
  678. }
  679. out, err := t.tunFile.newFriend(fd)
  680. if err != nil {
  681. _ = unix.Close(fd)
  682. return nil, err
  683. }
  684. t.readers = append(t.readers, out)
  685. return out, nil
  686. }
  687. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  688. r, _ := t.routeTree.Load().Lookup(ip)
  689. return r
  690. }
  691. func (t *tun) deviceBytes() (o [16]byte) {
  692. for i, c := range t.Device {
  693. o[i] = byte(c)
  694. }
  695. return
  696. }
  697. func hasNetlinkAddr(al []*netlink.Addr, x netlink.Addr) bool {
  698. for i := range al {
  699. if al[i].Equal(x) {
  700. return true
  701. }
  702. }
  703. return false
  704. }
  705. // addIPs uses netlink to add all addresses that don't exist, then it removes ones that should not be there
  706. func (t *tun) addIPs(link netlink.Link) error {
  707. newAddrs := make([]*netlink.Addr, len(t.vpnNetworks))
  708. for i := range t.vpnNetworks {
  709. newAddrs[i] = &netlink.Addr{
  710. IPNet: &net.IPNet{
  711. IP: t.vpnNetworks[i].Addr().AsSlice(),
  712. Mask: net.CIDRMask(t.vpnNetworks[i].Bits(), t.vpnNetworks[i].Addr().BitLen()),
  713. },
  714. Label: t.vpnNetworks[i].Addr().Zone(),
  715. }
  716. }
  717. //add all new addresses
  718. for i := range newAddrs {
  719. //AddrReplace still adds new IPs, but if their properties change it will change them as well
  720. if err := netlink.AddrReplace(link, newAddrs[i]); err != nil {
  721. return err
  722. }
  723. }
  724. //iterate over remainder, remove whoever shouldn't be there
  725. al, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  726. if err != nil {
  727. return fmt.Errorf("failed to get tun address list: %s", err)
  728. }
  729. for i := range al {
  730. if hasNetlinkAddr(newAddrs, al[i]) {
  731. continue
  732. }
  733. err = netlink.AddrDel(link, &al[i])
  734. if err != nil {
  735. t.l.WithError(err).Error("failed to remove address from tun address list")
  736. } else {
  737. t.l.WithField("removed", al[i].String()).Info("removed address not listed in cert(s)")
  738. }
  739. }
  740. return nil
  741. }
  742. func (t *tun) Activate() error {
  743. devName := t.deviceBytes()
  744. if t.useSystemRoutes {
  745. t.watchRoutes()
  746. }
  747. s, err := unix.Socket(
  748. unix.AF_INET, //because everything we use t.ioctlFd for is address family independent, this is fine
  749. unix.SOCK_DGRAM,
  750. unix.IPPROTO_IP,
  751. )
  752. if err != nil {
  753. return err
  754. }
  755. t.ioctlFd = uintptr(s)
  756. // Set the device name
  757. ifrf := ifReq{Name: devName}
  758. if err = ioctl(t.ioctlFd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  759. return fmt.Errorf("failed to set tun device name: %s", err)
  760. }
  761. link, err := netlink.LinkByName(t.Device)
  762. if err != nil {
  763. return fmt.Errorf("failed to get tun device link: %s", err)
  764. }
  765. t.deviceIndex = link.Attrs().Index
  766. // Setup our default MTU
  767. t.setMTU()
  768. // Set the transmit queue length
  769. ifrq := ifreqQLEN{Name: devName, Value: int32(t.TXQueueLen)}
  770. if err = ioctl(t.ioctlFd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  771. // If we can't set the queue length nebula will still work but it may lead to packet loss
  772. t.l.WithError(err).Error("Failed to set tun tx queue length")
  773. }
  774. const modeNone = 1
  775. if err = netlink.LinkSetIP6AddrGenMode(link, modeNone); err != nil {
  776. t.l.WithError(err).Warn("Failed to disable link local address generation")
  777. }
  778. if err = t.addIPs(link); err != nil {
  779. return err
  780. }
  781. // Bring up the interface
  782. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  783. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  784. return fmt.Errorf("failed to bring the tun device up: %s", err)
  785. }
  786. //set route MTU
  787. for i := range t.vpnNetworks {
  788. if err = t.setDefaultRoute(t.vpnNetworks[i]); err != nil {
  789. return fmt.Errorf("failed to set default route MTU: %w", err)
  790. }
  791. }
  792. // Set the routes
  793. if err = t.addRoutes(false); err != nil {
  794. return err
  795. }
  796. // Run the interface
  797. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  798. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  799. return fmt.Errorf("failed to run tun device: %s", err)
  800. }
  801. return nil
  802. }
  803. func (t *tun) setMTU() {
  804. // Set the MTU on the device
  805. ifm := ifreqMTU{Name: t.deviceBytes(), MTU: int32(t.MaxMTU)}
  806. if err := ioctl(t.ioctlFd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  807. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  808. t.l.WithError(err).Error("Failed to set tun mtu")
  809. }
  810. }
  811. func (t *tun) setDefaultRoute(cidr netip.Prefix) error {
  812. dr := &net.IPNet{
  813. IP: cidr.Masked().Addr().AsSlice(),
  814. Mask: net.CIDRMask(cidr.Bits(), cidr.Addr().BitLen()),
  815. }
  816. nr := netlink.Route{
  817. LinkIndex: t.deviceIndex,
  818. Dst: dr,
  819. MTU: t.DefaultMTU,
  820. AdvMSS: t.advMSS(Route{}),
  821. Scope: unix.RT_SCOPE_LINK,
  822. Src: net.IP(cidr.Addr().AsSlice()),
  823. Protocol: unix.RTPROT_KERNEL,
  824. Table: unix.RT_TABLE_MAIN,
  825. Type: unix.RTN_UNICAST,
  826. }
  827. err := netlink.RouteReplace(&nr)
  828. if err != nil {
  829. t.l.WithError(err).WithField("cidr", cidr).Warn("Failed to set default route MTU, retrying")
  830. //retry twice more -- on some systems there appears to be a race condition where if we set routes too soon, netlink says `invalid argument`
  831. for i := 0; i < 2; i++ {
  832. time.Sleep(100 * time.Millisecond)
  833. err = netlink.RouteReplace(&nr)
  834. if err == nil {
  835. break
  836. } else {
  837. t.l.WithError(err).WithField("cidr", cidr).WithField("mtu", t.DefaultMTU).Warn("Failed to set default route MTU, retrying")
  838. }
  839. }
  840. if err != nil {
  841. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", t.DefaultMTU, dr, err)
  842. }
  843. }
  844. return nil
  845. }
  846. func (t *tun) addRoutes(logErrors bool) error {
  847. // Path routes
  848. routes := *t.Routes.Load()
  849. for _, r := range routes {
  850. if !r.Install {
  851. continue
  852. }
  853. dr := &net.IPNet{
  854. IP: r.Cidr.Masked().Addr().AsSlice(),
  855. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  856. }
  857. nr := netlink.Route{
  858. LinkIndex: t.deviceIndex,
  859. Dst: dr,
  860. MTU: r.MTU,
  861. AdvMSS: t.advMSS(r),
  862. Scope: unix.RT_SCOPE_LINK,
  863. }
  864. if r.Metric > 0 {
  865. nr.Priority = r.Metric
  866. }
  867. err := netlink.RouteReplace(&nr)
  868. if err != nil {
  869. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  870. if logErrors {
  871. retErr.Log(t.l)
  872. } else {
  873. return retErr
  874. }
  875. } else {
  876. t.l.WithField("route", r).Info("Added route")
  877. }
  878. }
  879. return nil
  880. }
  881. func (t *tun) removeRoutes(routes []Route) {
  882. for _, r := range routes {
  883. if !r.Install {
  884. continue
  885. }
  886. dr := &net.IPNet{
  887. IP: r.Cidr.Masked().Addr().AsSlice(),
  888. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  889. }
  890. nr := netlink.Route{
  891. LinkIndex: t.deviceIndex,
  892. Dst: dr,
  893. MTU: r.MTU,
  894. AdvMSS: t.advMSS(r),
  895. Scope: unix.RT_SCOPE_LINK,
  896. }
  897. if r.Metric > 0 {
  898. nr.Priority = r.Metric
  899. }
  900. err := netlink.RouteDel(&nr)
  901. if err != nil {
  902. t.l.WithError(err).WithField("route", r).Error("Failed to remove route")
  903. } else {
  904. t.l.WithField("route", r).Info("Removed route")
  905. }
  906. }
  907. }
  908. func (t *tun) Name() string {
  909. return t.Device
  910. }
  911. func (t *tun) advMSS(r Route) int {
  912. mtu := r.MTU
  913. if r.MTU == 0 {
  914. mtu = t.DefaultMTU
  915. }
  916. // We only need to set advmss if the route MTU does not match the device MTU
  917. if mtu != t.MaxMTU {
  918. return mtu - 40
  919. }
  920. return 0
  921. }
  922. func (t *tun) watchRoutes() {
  923. rch := make(chan netlink.RouteUpdate)
  924. doneChan := make(chan struct{})
  925. netlinkOptions := netlink.RouteSubscribeOptions{
  926. ReceiveBufferSize: t.useSystemRoutesBufferSize,
  927. ReceiveBufferForceSize: t.useSystemRoutesBufferSize != 0,
  928. ErrorCallback: func(e error) { t.l.WithError(e).Errorf("netlink error") },
  929. }
  930. if err := netlink.RouteSubscribeWithOptions(rch, doneChan, netlinkOptions); err != nil {
  931. t.l.WithError(err).Errorf("failed to subscribe to system route changes")
  932. return
  933. }
  934. t.routeChan = doneChan
  935. go func() {
  936. for {
  937. select {
  938. case r, ok := <-rch:
  939. if ok {
  940. t.updateRoutes(r)
  941. } else {
  942. // may be should do something here as
  943. // netlink stops sending updates
  944. return
  945. }
  946. case <-doneChan:
  947. // netlink.RouteSubscriber will close the rch for us
  948. return
  949. }
  950. }
  951. }()
  952. }
  953. func (t *tun) isGatewayInVpnNetworks(gwAddr netip.Addr) bool {
  954. withinNetworks := false
  955. for i := range t.vpnNetworks {
  956. if t.vpnNetworks[i].Contains(gwAddr) {
  957. withinNetworks = true
  958. break
  959. }
  960. }
  961. return withinNetworks
  962. }
  963. func (t *tun) getGatewaysFromRoute(r *netlink.Route) routing.Gateways {
  964. var gateways routing.Gateways
  965. link, err := netlink.LinkByName(t.Device)
  966. if err != nil {
  967. t.l.WithField("deviceName", t.Device).Error("Ignoring route update: failed to get link by name")
  968. return gateways
  969. }
  970. // If this route is relevant to our interface and there is a gateway then add it
  971. if r.LinkIndex == link.Attrs().Index {
  972. gwAddr, ok := getGatewayAddr(r.Gw, r.Via)
  973. if ok {
  974. if t.isGatewayInVpnNetworks(gwAddr) {
  975. gateways = append(gateways, routing.NewGateway(gwAddr, 1))
  976. } else {
  977. // Gateway isn't in our overlay network, ignore
  978. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  979. }
  980. } else {
  981. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  982. }
  983. }
  984. for _, p := range r.MultiPath {
  985. // If this route is relevant to our interface and there is a gateway then add it
  986. if p.LinkIndex == link.Attrs().Index {
  987. gwAddr, ok := getGatewayAddr(p.Gw, p.Via)
  988. if ok {
  989. if t.isGatewayInVpnNetworks(gwAddr) {
  990. gateways = append(gateways, routing.NewGateway(gwAddr, p.Hops+1))
  991. } else {
  992. // Gateway isn't in our overlay network, ignore
  993. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  994. }
  995. } else {
  996. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  997. }
  998. }
  999. }
  1000. routing.CalculateBucketsForGateways(gateways)
  1001. return gateways
  1002. }
  1003. func getGatewayAddr(gw net.IP, via netlink.Destination) (netip.Addr, bool) {
  1004. // Try to use the old RTA_GATEWAY first
  1005. gwAddr, ok := netip.AddrFromSlice(gw)
  1006. if !ok {
  1007. // Fallback to the new RTA_VIA
  1008. rVia, ok := via.(*netlink.Via)
  1009. if ok {
  1010. gwAddr, ok = netip.AddrFromSlice(rVia.Addr)
  1011. }
  1012. }
  1013. if gwAddr.IsValid() {
  1014. gwAddr = gwAddr.Unmap()
  1015. return gwAddr, true
  1016. }
  1017. return netip.Addr{}, false
  1018. }
  1019. func (t *tun) updateRoutes(r netlink.RouteUpdate) {
  1020. gateways := t.getGatewaysFromRoute(&r.Route)
  1021. if len(gateways) == 0 {
  1022. // No gateways relevant to our network, no routing changes required.
  1023. t.l.WithField("route", r).Debug("Ignoring route update, no gateways")
  1024. return
  1025. }
  1026. if r.Dst == nil {
  1027. t.l.WithField("route", r).Debug("Ignoring route update, no destination address")
  1028. return
  1029. }
  1030. dstAddr, ok := netip.AddrFromSlice(r.Dst.IP)
  1031. if !ok {
  1032. t.l.WithField("route", r).Debug("Ignoring route update, invalid destination address")
  1033. return
  1034. }
  1035. ones, _ := r.Dst.Mask.Size()
  1036. dst := netip.PrefixFrom(dstAddr, ones)
  1037. newTree := t.routeTree.Load().Clone()
  1038. t.routesFromSystemLock.Lock()
  1039. if r.Type == unix.RTM_NEWROUTE {
  1040. t.l.WithField("destination", dst).WithField("via", gateways).Info("Adding route")
  1041. t.routesFromSystem[dst] = gateways
  1042. newTree.Insert(dst, gateways)
  1043. } else {
  1044. t.l.WithField("destination", dst).WithField("via", gateways).Info("Removing route")
  1045. delete(t.routesFromSystem, dst)
  1046. newTree.Delete(dst)
  1047. }
  1048. t.routesFromSystemLock.Unlock()
  1049. t.routeTree.Store(newTree)
  1050. }
  1051. func (t *tun) Close() error {
  1052. t.closeLock.Lock()
  1053. defer t.closeLock.Unlock()
  1054. if t.routeChan != nil {
  1055. close(t.routeChan)
  1056. t.routeChan = nil
  1057. }
  1058. // Signal all readers blocked in poll to wake up and exit
  1059. _ = t.tunFile.wakeForShutdown()
  1060. if t.ioctlFd > 0 {
  1061. _ = unix.Close(int(t.ioctlFd))
  1062. t.ioctlFd = 0
  1063. }
  1064. for i := range t.readers {
  1065. if i == 0 {
  1066. continue //we want to close the zeroth reader last
  1067. }
  1068. err := t.readers[i].Close()
  1069. if err != nil {
  1070. t.l.WithField("reader", i).WithError(err).Error("error closing tun reader")
  1071. } else {
  1072. t.l.WithField("reader", i).Info("closed tun reader")
  1073. }
  1074. }
  1075. //this is t.readers[0] too
  1076. err := t.tunFile.Close()
  1077. if err != nil {
  1078. t.l.WithField("reader", 0).WithError(err).Error("error closing tun reader")
  1079. } else {
  1080. t.l.WithField("reader", 0).Info("closed tun reader")
  1081. }
  1082. return err
  1083. }