tun_darwin.go 20 KB

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