1
0

tun_linux.go 34 KB

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