tun_darwin.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. //go:build !ios && !e2e_testing
  2. package overlay
  3. import (
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "math/bits"
  8. "net/netip"
  9. "os"
  10. "sync"
  11. "sync/atomic"
  12. "syscall"
  13. "unsafe"
  14. "github.com/gaissmai/bart"
  15. "github.com/slackhq/nebula/config"
  16. "github.com/slackhq/nebula/overlay/tio"
  17. "github.com/slackhq/nebula/routing"
  18. "github.com/slackhq/nebula/util"
  19. netroute "golang.org/x/net/route"
  20. "golang.org/x/sys/unix"
  21. )
  22. type tun struct {
  23. f *os.File
  24. Device string
  25. vpnNetworks []netip.Prefix
  26. DefaultMTU int
  27. Routes atomic.Pointer[[]Route]
  28. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  29. linkAddr atomic.Pointer[netroute.LinkAddr]
  30. // hostOwned means the fd arrived from the OS, which has already configured addressing, mtu
  31. // and routes for it. NEPacketTunnelProvider on darwin does this.
  32. hostOwned bool
  33. l *slog.Logger
  34. }
  35. type ifReq struct {
  36. Name [unix.IFNAMSIZ]byte
  37. Flags uint16
  38. pad [8]byte
  39. }
  40. const (
  41. _SIOCAIFADDR_IN6 = 2155899162
  42. _UTUN_OPT_IFNAME = 2
  43. _IN6_IFF_NODAD = 0x0020
  44. _IN6_IFF_SECURED = 0x0400
  45. utunControlName = "com.apple.net.utun_control"
  46. )
  47. type ifreqMTU struct {
  48. Name [16]byte
  49. MTU int32
  50. pad [8]byte
  51. }
  52. type addrLifetime struct {
  53. Expire float64
  54. Preferred float64
  55. Vltime uint32
  56. Pltime uint32
  57. }
  58. type ifreqAlias4 struct {
  59. Name [unix.IFNAMSIZ]byte
  60. Addr unix.RawSockaddrInet4
  61. DstAddr unix.RawSockaddrInet4
  62. MaskAddr unix.RawSockaddrInet4
  63. }
  64. type ifreqAlias6 struct {
  65. Name [unix.IFNAMSIZ]byte
  66. Addr unix.RawSockaddrInet6
  67. DstAddr unix.RawSockaddrInet6
  68. PrefixMask unix.RawSockaddrInet6
  69. Flags uint32
  70. Lifetime addrLifetime
  71. }
  72. func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*tun, error) {
  73. name := c.GetString("tun.dev", "")
  74. ifIndex := -1
  75. if name != "" && name != "utun" {
  76. _, err := fmt.Sscanf(name, "utun%d", &ifIndex)
  77. if err != nil || ifIndex < 0 {
  78. // NOTE: we don't make this error so we don't break existing
  79. // configs that set a name before it was used.
  80. l.Warn("interface name must be utun[0-9]+ on Darwin, ignoring")
  81. ifIndex = -1
  82. }
  83. }
  84. fd, err := unix.Socket(unix.AF_SYSTEM, unix.SOCK_DGRAM, unix.AF_SYS_CONTROL)
  85. if err != nil {
  86. return nil, fmt.Errorf("system socket: %v", err)
  87. }
  88. var ctlInfo = &unix.CtlInfo{}
  89. copy(ctlInfo.Name[:], utunControlName)
  90. err = unix.IoctlCtlInfo(fd, ctlInfo)
  91. if err != nil {
  92. return nil, fmt.Errorf("CTLIOCGINFO: %v", err)
  93. }
  94. err = unix.Connect(fd, &unix.SockaddrCtl{
  95. ID: ctlInfo.Id,
  96. Unit: uint32(ifIndex) + 1,
  97. })
  98. if err != nil {
  99. return nil, fmt.Errorf("SYS_CONNECT: %v", err)
  100. }
  101. name, err = unix.GetsockoptString(fd, unix.AF_SYS_CONTROL, _UTUN_OPT_IFNAME)
  102. if err != nil {
  103. return nil, fmt.Errorf("failed to retrieve tun name: %w", err)
  104. }
  105. err = unix.SetNonblock(fd, true)
  106. if err != nil {
  107. return nil, fmt.Errorf("SetNonblock: %v", err)
  108. }
  109. t := &tun{
  110. f: os.NewFile(uintptr(fd), ""),
  111. Device: name,
  112. vpnNetworks: vpnNetworks,
  113. DefaultMTU: getMTU(l, c),
  114. l: l,
  115. }
  116. err = t.reload(c, true)
  117. if err != nil {
  118. return nil, err
  119. }
  120. c.RegisterReloadCallback(func(c *config.C) {
  121. err := t.reload(c, false)
  122. if err != nil {
  123. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  124. }
  125. })
  126. return t, nil
  127. }
  128. func (t *tun) deviceBytes() (o [16]byte) {
  129. for i, c := range t.Device {
  130. o[i] = byte(c)
  131. }
  132. return
  133. }
  134. // newTunFromFd adopts a utun the host already created and configured, which is how a darwin
  135. // network extension is handed its device. Everything about moving packets is shared with newTun,
  136. // only the setup differs: the host owns addressing and routing here.
  137. func newTunFromFd(c *config.C, l *slog.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
  138. if err := unix.SetNonblock(deviceFd, true); err != nil {
  139. // We own the fd from the moment it is handed to us
  140. _ = unix.Close(deviceFd)
  141. return nil, fmt.Errorf("failed to set the tun fd to non-blocking mode: %w", err)
  142. }
  143. file := os.NewFile(uintptr(deviceFd), "/dev/tun")
  144. t := &tun{
  145. f: file,
  146. Device: utunNameFromFd(deviceFd),
  147. vpnNetworks: vpnNetworks,
  148. DefaultMTU: getMTU(l, c),
  149. hostOwned: true,
  150. l: l,
  151. }
  152. if err := t.reload(c, true); err != nil {
  153. _ = file.Close()
  154. return nil, err
  155. }
  156. c.RegisterReloadCallback(func(c *config.C) {
  157. if err := t.reload(c, false); err != nil {
  158. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  159. }
  160. })
  161. return t, nil
  162. }
  163. // utunNameFromFd asks the socket what interface it is, for logs. A blank name is not worth
  164. // failing a tunnel over, so an error just leaves it empty.
  165. func utunNameFromFd(fd int) string {
  166. name, err := unix.GetsockoptString(fd, unix.AF_SYS_CONTROL, _UTUN_OPT_IFNAME)
  167. if err != nil {
  168. return ""
  169. }
  170. return name
  171. }
  172. func (t *tun) Close() error {
  173. if t.f != nil {
  174. return t.f.Close()
  175. }
  176. return nil
  177. }
  178. func (t *tun) Activate() error {
  179. // The host handed us a configured device. Its addresses, mtu and routes come from the network
  180. // settings it applied, and a sandboxed extension cannot change them anyway.
  181. if t.hostOwned {
  182. return nil
  183. }
  184. devName := t.deviceBytes()
  185. s, err := unix.Socket(
  186. unix.AF_INET,
  187. unix.SOCK_DGRAM,
  188. unix.IPPROTO_IP,
  189. )
  190. if err != nil {
  191. return err
  192. }
  193. defer unix.Close(s)
  194. fd := uintptr(s)
  195. // Set the MTU on the device
  196. ifm := ifreqMTU{Name: devName, MTU: int32(t.DefaultMTU)}
  197. if err = ioctl(fd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  198. return fmt.Errorf("failed to set tun mtu: %v", err)
  199. }
  200. // Get the device flags
  201. ifrf := ifReq{Name: devName}
  202. if err = ioctl(fd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  203. return fmt.Errorf("failed to get tun flags: %s", err)
  204. }
  205. linkAddr, err := getLinkAddr(t.Device)
  206. if err != nil {
  207. return err
  208. }
  209. if linkAddr == nil {
  210. return fmt.Errorf("unable to discover link_addr for tun interface")
  211. }
  212. t.linkAddr.Store(linkAddr)
  213. for _, network := range t.vpnNetworks {
  214. if network.Addr().Is4() {
  215. err = t.activate4(network)
  216. if err != nil {
  217. return err
  218. }
  219. } else {
  220. err = t.activate6(network)
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. }
  226. // Run the interface
  227. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  228. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  229. return fmt.Errorf("failed to run tun device: %s", err)
  230. }
  231. // Unsafe path routes
  232. return t.addRoutes(false)
  233. }
  234. // activate4 assigns our vpn address as a /32 and routes the vpn network to the tun explicitly.
  235. func (t *tun) activate4(network netip.Prefix) error {
  236. s, err := unix.Socket(
  237. unix.AF_INET,
  238. unix.SOCK_DGRAM,
  239. unix.IPPROTO_IP,
  240. )
  241. if err != nil {
  242. return err
  243. }
  244. defer unix.Close(s)
  245. ifr := ifreqAlias4{
  246. Name: t.deviceBytes(),
  247. Addr: unix.RawSockaddrInet4{
  248. Len: unix.SizeofSockaddrInet4,
  249. Family: unix.AF_INET,
  250. Addr: network.Addr().As4(),
  251. },
  252. DstAddr: unix.RawSockaddrInet4{
  253. Len: unix.SizeofSockaddrInet4,
  254. Family: unix.AF_INET,
  255. Addr: network.Addr().As4(),
  256. },
  257. MaskAddr: unix.RawSockaddrInet4{
  258. Len: unix.SizeofSockaddrInet4,
  259. Family: unix.AF_INET,
  260. Addr: [4]byte{255, 255, 255, 255}, //always make the address a /32
  261. },
  262. }
  263. // On Darwin, VPNs don't edit the routing table directly.
  264. // A network extension hands its routes to the system, and configd installs them.
  265. // configd replaces any route already holding the same prefix, including ours.
  266. // As an example, Tailscale with an exit node treats any interface prefix wider than one address as a LAN.
  267. // With LAN access off, it routes each LAN into Tailscale's utun.
  268. // With LAN access on, it excludes each LAN from its tunnel.
  269. // configd routes an excluded prefix like its own routes would, ignoring ours, so it goes out the default route.
  270. // Either way our route is replaced, and traffic for the vpn network no longer reaches nebula.
  271. // A single address isn't a LAN to Tailscale, so our route is left alone.
  272. // We route the vpn network to the tun explicitly instead.
  273. if err := ioctl(uintptr(s), unix.SIOCAIFADDR, uintptr(unsafe.Pointer(&ifr))); err != nil {
  274. return fmt.Errorf("failed to set tun v4 address: %s", err)
  275. }
  276. if err := addRoute(network, t.linkAddr.Load()); err != nil {
  277. return fmt.Errorf("failed to add route for %v: %w", network.Masked(), err)
  278. }
  279. return nil
  280. }
  281. // activate6 is activate4 for IPv6
  282. func (t *tun) activate6(network netip.Prefix) error {
  283. s, err := unix.Socket(
  284. unix.AF_INET6,
  285. unix.SOCK_DGRAM,
  286. unix.IPPROTO_IP,
  287. )
  288. if err != nil {
  289. return err
  290. }
  291. defer unix.Close(s)
  292. ifr := ifreqAlias6{
  293. Name: t.deviceBytes(),
  294. Addr: unix.RawSockaddrInet6{
  295. Len: unix.SizeofSockaddrInet6,
  296. Family: unix.AF_INET6,
  297. Addr: network.Addr().As16(),
  298. },
  299. PrefixMask: unix.RawSockaddrInet6{
  300. Len: unix.SizeofSockaddrInet6,
  301. Family: unix.AF_INET6,
  302. // Always set the netmask to be a /128. See activate4 for why we do this.
  303. Addr: [16]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
  304. },
  305. Lifetime: addrLifetime{
  306. // never expires
  307. Vltime: 0xffffffff,
  308. Pltime: 0xffffffff,
  309. },
  310. Flags: _IN6_IFF_NODAD, // No DAD, a utun has no neighbors.
  311. }
  312. if err := ioctl(uintptr(s), _SIOCAIFADDR_IN6, uintptr(unsafe.Pointer(&ifr))); err != nil {
  313. return fmt.Errorf("failed to set tun address: %s", err)
  314. }
  315. if err := addRoute(network, t.linkAddr.Load()); err != nil {
  316. return fmt.Errorf("failed to add route for %v: %w", network.Masked(), err)
  317. }
  318. return nil
  319. }
  320. func (t *tun) reload(c *config.C, initial bool) error {
  321. change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
  322. if err != nil {
  323. return err
  324. }
  325. if !initial && !change {
  326. return nil
  327. }
  328. routeTree, err := makeRouteTree(t.l, routes, false)
  329. if err != nil {
  330. return err
  331. }
  332. // Teach nebula how to handle the routes before establishing them in the system table
  333. oldRoutes := t.Routes.Swap(&routes)
  334. t.routeTree.Store(routeTree)
  335. if !initial {
  336. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  337. err := t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  338. if err != nil {
  339. util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
  340. }
  341. // Ensure any routes we actually want are installed
  342. err = t.addRoutes(true)
  343. if err != nil {
  344. // Catch any stray logs
  345. util.LogWithContextIfNeeded("Failed to add routes", err, t.l)
  346. }
  347. }
  348. return nil
  349. }
  350. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  351. r, ok := t.routeTree.Load().Lookup(ip)
  352. if ok {
  353. return r
  354. }
  355. return routing.Gateways{}
  356. }
  357. func fetchRoutes() ([]netroute.Message, error) {
  358. rib, err := netroute.FetchRIB(unix.AF_UNSPEC, unix.NET_RT_DUMP, 0)
  359. if err != nil {
  360. return nil, err
  361. }
  362. return netroute.ParseRIB(unix.NET_RT_DUMP, rib)
  363. }
  364. // routeInterfaceIn returns the index of the interface prefix is routed through, or 0 if msgs has no route for exactly
  365. // that prefix. Routes scoped to an interface are skipped, they don't stop us adding ours.
  366. func routeInterfaceIn(msgs []netroute.Message, prefix netip.Prefix) int {
  367. for _, msg := range msgs {
  368. m, ok := msg.(*netroute.RouteMessage)
  369. if !ok || len(m.Addrs) <= unix.RTAX_NETMASK || m.Flags&unix.RTF_IFSCOPE != 0 {
  370. continue
  371. }
  372. if p, ok := routePrefix(m.Addrs[unix.RTAX_DST], m.Addrs[unix.RTAX_NETMASK]); ok && p == prefix.Masked() {
  373. return m.Index
  374. }
  375. }
  376. return 0
  377. }
  378. // routePrefix returns the prefix a route covers. Host routes have no netmask.
  379. func routePrefix(dst, mask netroute.Addr) (netip.Prefix, bool) {
  380. switch d := dst.(type) {
  381. case *netroute.Inet4Addr:
  382. bits := 32
  383. if m, ok := mask.(*netroute.Inet4Addr); ok {
  384. bits = maskBits(m.IP[:])
  385. }
  386. return netip.PrefixFrom(netip.AddrFrom4(d.IP), bits), true
  387. case *netroute.Inet6Addr:
  388. bits := 128
  389. if m, ok := mask.(*netroute.Inet6Addr); ok {
  390. bits = maskBits(m.IP[:])
  391. }
  392. return netip.PrefixFrom(netip.AddrFrom16(d.IP), bits), true
  393. }
  394. return netip.Prefix{}, false
  395. }
  396. func maskBits(mask []byte) int {
  397. n := 0
  398. for _, b := range mask {
  399. n += bits.OnesCount8(b)
  400. }
  401. return n
  402. }
  403. // Get the LinkAddr for the interface of the given name
  404. // Is there an easier way to fetch this when we create the interface?
  405. // Maybe SIOCGIFINDEX? but this doesn't appear to exist in the darwin headers.
  406. func getLinkAddr(name string) (*netroute.LinkAddr, error) {
  407. rib, err := netroute.FetchRIB(unix.AF_UNSPEC, unix.NET_RT_IFLIST, 0)
  408. if err != nil {
  409. return nil, err
  410. }
  411. msgs, err := netroute.ParseRIB(unix.NET_RT_IFLIST, rib)
  412. if err != nil {
  413. return nil, err
  414. }
  415. for _, m := range msgs {
  416. switch m := m.(type) {
  417. case *netroute.InterfaceMessage:
  418. if m.Name == name {
  419. sa, ok := m.Addrs[unix.RTAX_IFP].(*netroute.LinkAddr)
  420. if ok {
  421. return sa, nil
  422. }
  423. }
  424. }
  425. }
  426. return nil, nil
  427. }
  428. func (t *tun) addRoutes(logErrors bool) error {
  429. // The route tree is still ours, the system routing table is not
  430. if t.hostOwned {
  431. return nil
  432. }
  433. // Activate hasn't run yet, it will install the routes
  434. linkAddr := t.linkAddr.Load()
  435. if linkAddr == nil {
  436. return nil
  437. }
  438. routes := *t.Routes.Load()
  439. systemRoutes := sync.OnceValues(fetchRoutes)
  440. for _, r := range routes {
  441. if len(r.Via) == 0 || !r.Install {
  442. // We don't allow route MTUs so only install routes with a via
  443. continue
  444. }
  445. err := addRoute(r.Cidr, linkAddr)
  446. if err != nil {
  447. if errors.Is(err, unix.EEXIST) {
  448. // Every route we added already exists on a reload, only warn about someone else's
  449. msgs, err := systemRoutes()
  450. if err != nil {
  451. t.l.Warn("unable to add unsafe_route, a route already exists but its interface could not be determined", "route", r.Cidr, "error", err)
  452. } else if routeInterfaceIn(msgs, r.Cidr) != linkAddr.Index {
  453. t.l.Warn("unable to add unsafe_route, the destination is already routed through another interface", "route", r.Cidr)
  454. }
  455. } else {
  456. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  457. if logErrors {
  458. retErr.Log(t.l)
  459. } else {
  460. return retErr
  461. }
  462. }
  463. } else {
  464. t.l.Info("Added route", "route", r)
  465. // A cidr listed twice would otherwise find our own route missing from an older fetch
  466. systemRoutes = sync.OnceValues(fetchRoutes)
  467. }
  468. }
  469. return nil
  470. }
  471. func (t *tun) removeRoutes(routes []Route) error {
  472. linkAddr := t.linkAddr.Load()
  473. if t.hostOwned || linkAddr == nil {
  474. return nil
  475. }
  476. for _, r := range routes {
  477. if len(r.Via) == 0 || !r.Install {
  478. // addRoutes never installs these
  479. continue
  480. }
  481. err := delRoute(r.Cidr, linkAddr)
  482. if err != nil {
  483. t.l.Error("Failed to remove route", "error", err, "route", r)
  484. } else {
  485. t.l.Info("Removed route", "route", r)
  486. }
  487. }
  488. return nil
  489. }
  490. func addRoute(prefix netip.Prefix, gateway netroute.Addr) error {
  491. sock, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC)
  492. if err != nil {
  493. return fmt.Errorf("unable to create AF_ROUTE socket: %v", err)
  494. }
  495. defer unix.Close(sock)
  496. route := &netroute.RouteMessage{
  497. Version: unix.RTM_VERSION,
  498. Type: unix.RTM_ADD,
  499. Flags: unix.RTF_UP,
  500. Seq: 1,
  501. }
  502. if prefix.Addr().Is4() {
  503. route.Addrs = []netroute.Addr{
  504. unix.RTAX_DST: &netroute.Inet4Addr{IP: prefix.Masked().Addr().As4()},
  505. unix.RTAX_NETMASK: &netroute.Inet4Addr{IP: prefixToMask(prefix).As4()},
  506. unix.RTAX_GATEWAY: gateway,
  507. }
  508. } else {
  509. route.Addrs = []netroute.Addr{
  510. unix.RTAX_DST: &netroute.Inet6Addr{IP: prefix.Masked().Addr().As16()},
  511. unix.RTAX_NETMASK: &netroute.Inet6Addr{IP: prefixToMask(prefix).As16()},
  512. unix.RTAX_GATEWAY: gateway,
  513. }
  514. }
  515. data, err := route.Marshal()
  516. if err != nil {
  517. return fmt.Errorf("failed to create route.RouteMessage: %w", err)
  518. }
  519. _, err = unix.Write(sock, data[:])
  520. if err != nil {
  521. return fmt.Errorf("failed to write route.RouteMessage to socket: %w", err)
  522. }
  523. return nil
  524. }
  525. func delRoute(prefix netip.Prefix, gateway netroute.Addr) error {
  526. sock, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC)
  527. if err != nil {
  528. return fmt.Errorf("unable to create AF_ROUTE socket: %v", err)
  529. }
  530. defer unix.Close(sock)
  531. route := netroute.RouteMessage{
  532. Version: unix.RTM_VERSION,
  533. Type: unix.RTM_DELETE,
  534. Seq: 1,
  535. }
  536. if prefix.Addr().Is4() {
  537. route.Addrs = []netroute.Addr{
  538. unix.RTAX_DST: &netroute.Inet4Addr{IP: prefix.Masked().Addr().As4()},
  539. unix.RTAX_NETMASK: &netroute.Inet4Addr{IP: prefixToMask(prefix).As4()},
  540. unix.RTAX_GATEWAY: gateway,
  541. }
  542. } else {
  543. route.Addrs = []netroute.Addr{
  544. unix.RTAX_DST: &netroute.Inet6Addr{IP: prefix.Masked().Addr().As16()},
  545. unix.RTAX_NETMASK: &netroute.Inet6Addr{IP: prefixToMask(prefix).As16()},
  546. unix.RTAX_GATEWAY: gateway,
  547. }
  548. }
  549. data, err := route.Marshal()
  550. if err != nil {
  551. return fmt.Errorf("failed to create route.RouteMessage: %w", err)
  552. }
  553. _, err = unix.Write(sock, data[:])
  554. if err != nil {
  555. return fmt.Errorf("failed to write route.RouteMessage to socket: %w", err)
  556. }
  557. return nil
  558. }
  559. // tunWritev and tunReadv are linkname'd to x/sys/unix's libc-routed writev/readv stubs so the
  560. // calls go through libSystem's pinned trampoline. A raw syscall.Syscall(SYS_WRITEV/SYS_READV, ...)
  561. // on darwin/arm64 emits an SVC #0x80 trap (see $GOROOT/src/syscall/asm_darwin_arm64.s), the path
  562. // Apple keeps warning they will eventually disallow. We pull the low-level stubs instead of calling
  563. // unix.Writev/unix.Readv because those take [][]byte and rebuild the []Iovec every call, which
  564. // heap-allocates the header; linkname'ing the stubs lets us hand them our own stack-allocated
  565. // iovecs. See golang/go#78049.
  566. //go:linkname tunWritev golang.org/x/sys/unix.writev
  567. //go:noescape
  568. func tunWritev(fd int, iovecs []unix.Iovec) (n int, err error)
  569. //go:linkname tunReadv golang.org/x/sys/unix.readv
  570. //go:noescape
  571. func tunReadv(fd int, iovecs []unix.Iovec) (n int, err error)
  572. // Read pulls one IP packet off the utun device, scattering the 4 byte protocol header away from
  573. // the packet so the payload lands directly in to.
  574. func (t *tun) Read(to []byte) (int, error) {
  575. var head [4]byte
  576. rc, err := t.f.SyscallConn()
  577. if err != nil {
  578. return 0, err
  579. }
  580. var n int
  581. var callErr error
  582. err = rc.Read(func(fd uintptr) bool {
  583. iovecs := []unix.Iovec{
  584. {Base: &head[0], Len: 4},
  585. {Base: &to[0], Len: uint64(len(to))},
  586. }
  587. n, callErr = tunReadv(int(fd), iovecs)
  588. if errno, ok := callErr.(syscall.Errno); ok && errno.Temporary() {
  589. return false
  590. }
  591. return true
  592. })
  593. if err != nil {
  594. return 0, err
  595. }
  596. if callErr != nil {
  597. return 0, callErr
  598. }
  599. if n < 4 {
  600. return 0, nil
  601. }
  602. return n - 4, nil
  603. }
  604. // Write pushes one IP packet onto the utun device. Safe for concurrent use:
  605. // the AF prefix and iovecs are per-call stack state, and the fd write itself
  606. // serializes on the runtime's fd mutex (see the Queue contract in tio.go).
  607. func (t *tun) Write(from []byte) (int, error) {
  608. if len(from) == 0 {
  609. return 0, syscall.EIO
  610. }
  611. ipVer := from[0] >> 4
  612. var head [4]byte
  613. switch ipVer {
  614. case 4:
  615. head[3] = syscall.AF_INET
  616. case 6:
  617. head[3] = syscall.AF_INET6
  618. default:
  619. return 0, fmt.Errorf("unable to determine IP version from packet")
  620. }
  621. // Grab rc as a local so the compiler can devirtualize the call and keep the closure on the stack.
  622. rc, err := t.f.SyscallConn()
  623. if err != nil {
  624. return 0, err
  625. }
  626. var n int
  627. var callErr error
  628. err = rc.Write(func(fd uintptr) bool {
  629. iovecs := []unix.Iovec{
  630. {Base: &head[0], Len: 4},
  631. {Base: &from[0], Len: uint64(len(from))},
  632. }
  633. n, callErr = tunWritev(int(fd), iovecs)
  634. // Type-assert to syscall.Errno so the EAGAIN/EWOULDBLOCK/EINTR check doesn't box the errno
  635. // constants into error interfaces on every call.
  636. if errno, ok := callErr.(syscall.Errno); ok && errno.Temporary() {
  637. return false
  638. }
  639. return true
  640. })
  641. if err != nil {
  642. return 0, err
  643. }
  644. if callErr != nil {
  645. return 0, callErr
  646. }
  647. return n - 4, nil
  648. }
  649. func (t *tun) Networks() []netip.Prefix {
  650. return t.vpnNetworks
  651. }
  652. func (t *tun) Name() string {
  653. return t.Device
  654. }
  655. func (t *tun) Queues(int) ([]tio.Queue, error) {
  656. return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
  657. }