tun_darwin.go 20 KB

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