netstack.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package netstack wires up gVisor's netstack into Tailscale.
  5. package netstack
  6. import (
  7. "context"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "os"
  14. "os/exec"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "gvisor.dev/gvisor/pkg/refs"
  22. "gvisor.dev/gvisor/pkg/tcpip"
  23. "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
  24. "gvisor.dev/gvisor/pkg/tcpip/buffer"
  25. "gvisor.dev/gvisor/pkg/tcpip/header"
  26. "gvisor.dev/gvisor/pkg/tcpip/link/channel"
  27. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  28. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  29. "gvisor.dev/gvisor/pkg/tcpip/stack"
  30. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  31. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  32. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  33. "gvisor.dev/gvisor/pkg/waiter"
  34. "inet.af/netaddr"
  35. "tailscale.com/envknob"
  36. "tailscale.com/ipn/ipnlocal"
  37. "tailscale.com/net/dns"
  38. "tailscale.com/net/packet"
  39. "tailscale.com/net/tsaddr"
  40. "tailscale.com/net/tsdial"
  41. "tailscale.com/net/tstun"
  42. "tailscale.com/syncs"
  43. "tailscale.com/types/ipproto"
  44. "tailscale.com/types/logger"
  45. "tailscale.com/types/netmap"
  46. "tailscale.com/version/distro"
  47. "tailscale.com/wgengine"
  48. "tailscale.com/wgengine/filter"
  49. "tailscale.com/wgengine/magicsock"
  50. )
  51. const debugPackets = false
  52. var debugNetstack = envknob.Bool("TS_DEBUG_NETSTACK")
  53. var (
  54. magicDNSIP = tsaddr.TailscaleServiceIP()
  55. magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
  56. )
  57. func init() {
  58. var debugNetstackLeakMode = envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  59. // Note: netstacks refsvfs2 package that will eventually replace refs
  60. // consumes the refs.LeakMode setting, but enables some checks when set to
  61. // UninitializedLeakChecking which is what empty string becomes. This mode
  62. // is largely un-useful, so it is explicitly disabled here, and more useful
  63. // modes can be set via the envknob. See #4309 for more references.
  64. if debugNetstackLeakMode == "" {
  65. debugNetstackLeakMode = "disabled"
  66. }
  67. var lm refs.LeakMode
  68. lm.Set(debugNetstackLeakMode)
  69. refs.SetLeakMode(lm)
  70. }
  71. // Impl contains the state for the netstack implementation,
  72. // and implements wgengine.FakeImpl to act as a userspace network
  73. // stack when Tailscale is running in fake mode.
  74. type Impl struct {
  75. // ForwardTCPIn, if non-nil, handles forwarding an inbound TCP
  76. // connection.
  77. // TODO(bradfitz): provide mechanism for tsnet to reject a
  78. // port other than accepting it and closing it.
  79. ForwardTCPIn func(c net.Conn, port uint16)
  80. // ProcessLocalIPs is whether netstack should handle incoming
  81. // traffic directed at the Node.Addresses (local IPs).
  82. // It can only be set before calling Start.
  83. ProcessLocalIPs bool
  84. // ProcessSubnets is whether netstack should handle incoming
  85. // traffic destined to non-local IPs (i.e. whether it should
  86. // be a subnet router).
  87. // It can only be set before calling Start.
  88. ProcessSubnets bool
  89. ipstack *stack.Stack
  90. linkEP *channel.Endpoint
  91. tundev *tstun.Wrapper
  92. e wgengine.Engine
  93. mc *magicsock.Conn
  94. logf logger.Logf
  95. dialer *tsdial.Dialer
  96. ctx context.Context // alive until Close
  97. ctxCancel context.CancelFunc // called on Close
  98. lb *ipnlocal.LocalBackend // or nil
  99. dns *dns.Manager
  100. peerapiPort4Atomic uint32 // uint16 port number for IPv4 peerapi
  101. peerapiPort6Atomic uint32 // uint16 port number for IPv6 peerapi
  102. // atomicIsLocalIPFunc holds a func that reports whether an IP
  103. // is a local (non-subnet) Tailscale IP address of this
  104. // machine. It's always a non-nil func. It's changed on netmap
  105. // updates.
  106. atomicIsLocalIPFunc atomic.Value // of func(netaddr.IP) bool
  107. mu sync.Mutex
  108. // connsOpenBySubnetIP keeps track of number of connections open
  109. // for each subnet IP temporarily registered on netstack for active
  110. // TCP connections, so they can be unregistered when connections are
  111. // closed.
  112. connsOpenBySubnetIP map[netaddr.IP]int
  113. }
  114. // handleSSH is initialized in ssh.go (on Linux only) to register an SSH server
  115. // handler. See https://github.com/tailscale/tailscale/issues/3802.
  116. var handleSSH func(logger.Logf, *ipnlocal.LocalBackend, net.Conn) error
  117. const nicID = 1
  118. const mtu = 1500
  119. // Create creates and populates a new Impl.
  120. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer, dns *dns.Manager) (*Impl, error) {
  121. if mc == nil {
  122. return nil, errors.New("nil magicsock.Conn")
  123. }
  124. if tundev == nil {
  125. return nil, errors.New("nil tundev")
  126. }
  127. if logf == nil {
  128. return nil, errors.New("nil logger")
  129. }
  130. if e == nil {
  131. return nil, errors.New("nil Engine")
  132. }
  133. if dialer == nil {
  134. return nil, errors.New("nil Dialer")
  135. }
  136. ipstack := stack.New(stack.Options{
  137. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  138. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  139. })
  140. linkEP := channel.New(512, mtu, "")
  141. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  142. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  143. }
  144. // By default the netstack NIC will only accept packets for the IPs
  145. // registered to it. Since in some cases we dynamically register IPs
  146. // based on the packets that arrive, the NIC needs to accept all
  147. // incoming packets. The NIC won't receive anything it isn't meant to
  148. // since WireGuard will only send us packets that are meant for us.
  149. ipstack.SetPromiscuousMode(nicID, true)
  150. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  151. // are handled by the one fake NIC we use.
  152. ipv4Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 4)), tcpip.AddressMask(strings.Repeat("\x00", 4)))
  153. ipv6Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 16)), tcpip.AddressMask(strings.Repeat("\x00", 16)))
  154. ipstack.SetRouteTable([]tcpip.Route{
  155. {
  156. Destination: ipv4Subnet,
  157. NIC: nicID,
  158. },
  159. {
  160. Destination: ipv6Subnet,
  161. NIC: nicID,
  162. },
  163. })
  164. ns := &Impl{
  165. logf: logf,
  166. ipstack: ipstack,
  167. linkEP: linkEP,
  168. tundev: tundev,
  169. e: e,
  170. mc: mc,
  171. dialer: dialer,
  172. connsOpenBySubnetIP: make(map[netaddr.IP]int),
  173. dns: dns,
  174. }
  175. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  176. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nil))
  177. return ns, nil
  178. }
  179. func (ns *Impl) Close() error {
  180. ns.ctxCancel()
  181. return nil
  182. }
  183. // SetLocalBackend sets the LocalBackend; it should only be run before
  184. // the Start method is called.
  185. func (ns *Impl) SetLocalBackend(lb *ipnlocal.LocalBackend) {
  186. ns.lb = lb
  187. }
  188. // wrapProtoHandler returns protocol handler h wrapped in a version
  189. // that dynamically reconfigures ns's subnet addresses as needed for
  190. // outbound traffic.
  191. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, *stack.PacketBuffer) bool) func(stack.TransportEndpointID, *stack.PacketBuffer) bool {
  192. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) bool {
  193. addr := tei.LocalAddress
  194. ip, ok := netaddr.FromStdIP(net.IP(addr))
  195. if !ok {
  196. ns.logf("netstack: could not parse local address for incoming connection")
  197. return false
  198. }
  199. if !ns.isLocalIP(ip) {
  200. ns.addSubnetAddress(ip)
  201. }
  202. return h(tei, pb)
  203. }
  204. }
  205. // Start sets up all the handlers so netstack can start working. Implements
  206. // wgengine.FakeImpl.
  207. func (ns *Impl) Start() error {
  208. ns.e.AddNetworkMapCallback(ns.updateIPs)
  209. // size = 0 means use default buffer size
  210. const tcpReceiveBufferSize = 0
  211. const maxInFlightConnectionAttempts = 16
  212. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  213. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  214. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  215. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  216. go ns.inject()
  217. ns.tundev.PostFilterIn = ns.injectInbound
  218. ns.tundev.PreFilterFromTunToNetstack = ns.handleLocalPackets
  219. return nil
  220. }
  221. func (ns *Impl) addSubnetAddress(ip netaddr.IP) {
  222. ns.mu.Lock()
  223. ns.connsOpenBySubnetIP[ip]++
  224. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  225. ns.mu.Unlock()
  226. // Only register address into netstack for first concurrent connection.
  227. if needAdd {
  228. pa := tcpip.ProtocolAddress{
  229. AddressWithPrefix: tcpip.AddressWithPrefix{
  230. Address: tcpip.Address(ip.IPAddr().IP),
  231. PrefixLen: int(ip.BitLen()),
  232. },
  233. }
  234. if ip.Is4() {
  235. pa.Protocol = ipv4.ProtocolNumber
  236. } else if ip.Is6() {
  237. pa.Protocol = ipv6.ProtocolNumber
  238. }
  239. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  240. PEB: stack.CanBePrimaryEndpoint, // zero value default
  241. ConfigType: stack.AddressConfigStatic, // zero value default
  242. })
  243. }
  244. }
  245. func (ns *Impl) removeSubnetAddress(ip netaddr.IP) {
  246. ns.mu.Lock()
  247. defer ns.mu.Unlock()
  248. ns.connsOpenBySubnetIP[ip]--
  249. // Only unregister address from netstack after last concurrent connection.
  250. if ns.connsOpenBySubnetIP[ip] == 0 {
  251. ns.ipstack.RemoveAddress(nicID, tcpip.Address(ip.IPAddr().IP))
  252. delete(ns.connsOpenBySubnetIP, ip)
  253. }
  254. }
  255. func ipPrefixToAddressWithPrefix(ipp netaddr.IPPrefix) tcpip.AddressWithPrefix {
  256. return tcpip.AddressWithPrefix{
  257. Address: tcpip.Address(ipp.IP().IPAddr().IP),
  258. PrefixLen: int(ipp.Bits()),
  259. }
  260. }
  261. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  262. func (ns *Impl) updateIPs(nm *netmap.NetworkMap) {
  263. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.Addresses))
  264. oldIPs := make(map[tcpip.AddressWithPrefix]bool)
  265. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  266. ap := protocolAddr.AddressWithPrefix
  267. ip := netaddrIPFromNetstackIP(ap.Address)
  268. if ip == v4broadcast && ap.PrefixLen == 32 {
  269. // Don't add 255.255.255.255/32 to oldIPs so we don't
  270. // delete it later. We didn't install it, so it's not
  271. // ours to delete.
  272. continue
  273. }
  274. oldIPs[ap] = true
  275. }
  276. newIPs := make(map[tcpip.AddressWithPrefix]bool)
  277. isAddr := map[netaddr.IPPrefix]bool{}
  278. if nm.SelfNode != nil {
  279. for _, ipp := range nm.SelfNode.Addresses {
  280. isAddr[ipp] = true
  281. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  282. }
  283. for _, ipp := range nm.SelfNode.AllowedIPs {
  284. if !isAddr[ipp] && ns.ProcessSubnets {
  285. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  286. }
  287. }
  288. }
  289. ipsToBeAdded := make(map[tcpip.AddressWithPrefix]bool)
  290. for ipp := range newIPs {
  291. if !oldIPs[ipp] {
  292. ipsToBeAdded[ipp] = true
  293. }
  294. }
  295. ipsToBeRemoved := make(map[tcpip.AddressWithPrefix]bool)
  296. for ip := range oldIPs {
  297. if !newIPs[ip] {
  298. ipsToBeRemoved[ip] = true
  299. }
  300. }
  301. ns.mu.Lock()
  302. for ip := range ns.connsOpenBySubnetIP {
  303. ipp := tcpip.Address(ip.IPAddr().IP).WithPrefix()
  304. delete(ipsToBeRemoved, ipp)
  305. }
  306. ns.mu.Unlock()
  307. for ipp := range ipsToBeRemoved {
  308. err := ns.ipstack.RemoveAddress(nicID, ipp.Address)
  309. if err != nil {
  310. ns.logf("netstack: could not deregister IP %s: %v", ipp, err)
  311. } else {
  312. ns.logf("[v2] netstack: deregistered IP %s", ipp)
  313. }
  314. }
  315. for ipp := range ipsToBeAdded {
  316. pa := tcpip.ProtocolAddress{
  317. AddressWithPrefix: ipp,
  318. }
  319. if ipp.Address.To4() == "" {
  320. pa.Protocol = ipv6.ProtocolNumber
  321. } else {
  322. pa.Protocol = ipv4.ProtocolNumber
  323. }
  324. var err tcpip.Error
  325. err = ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  326. PEB: stack.CanBePrimaryEndpoint, // zero value default
  327. ConfigType: stack.AddressConfigStatic, // zero value default
  328. })
  329. if err != nil {
  330. ns.logf("netstack: could not register IP %s: %v", ipp, err)
  331. } else {
  332. ns.logf("[v2] netstack: registered IP %s", ipp)
  333. }
  334. }
  335. }
  336. // handleLocalPackets is hooked into the tun datapath for packets leaving
  337. // the host and arriving at tailscaled. This method returns filter.DropSilently
  338. // to intercept a packet for handling, for instance traffic to quad-100.
  339. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  340. // If it's not traffic to the service IP (i.e. magicDNS) we don't
  341. // care; resume processing.
  342. if dst := p.Dst.IP(); dst != magicDNSIP && dst != magicDNSIPv6 {
  343. return filter.Accept
  344. }
  345. // Of traffic to the service IP, we only care about UDP 53, and TCP
  346. // on port 80 & 53.
  347. switch p.IPProto {
  348. case ipproto.TCP:
  349. if port := p.Dst.Port(); port != 53 && port != 80 {
  350. return filter.Accept
  351. }
  352. case ipproto.UDP:
  353. if port := p.Dst.Port(); port != 53 {
  354. return filter.Accept
  355. }
  356. }
  357. var pn tcpip.NetworkProtocolNumber
  358. switch p.IPVersion {
  359. case 4:
  360. pn = header.IPv4ProtocolNumber
  361. case 6:
  362. pn = header.IPv6ProtocolNumber
  363. }
  364. if debugPackets {
  365. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  366. }
  367. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  368. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  369. Data: vv,
  370. })
  371. ns.linkEP.InjectInbound(pn, packetBuf)
  372. packetBuf.DecRef()
  373. return filter.DropSilently
  374. }
  375. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.TCPConn, error) {
  376. remoteAddress := tcpip.FullAddress{
  377. NIC: nicID,
  378. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  379. Port: ipp.Port(),
  380. }
  381. var ipType tcpip.NetworkProtocolNumber
  382. if ipp.IP().Is4() {
  383. ipType = ipv4.ProtocolNumber
  384. } else {
  385. ipType = ipv6.ProtocolNumber
  386. }
  387. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  388. }
  389. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netaddr.IPPort) (*gonet.UDPConn, error) {
  390. remoteAddress := &tcpip.FullAddress{
  391. NIC: nicID,
  392. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  393. Port: ipp.Port(),
  394. }
  395. var ipType tcpip.NetworkProtocolNumber
  396. if ipp.IP().Is4() {
  397. ipType = ipv4.ProtocolNumber
  398. } else {
  399. ipType = ipv6.ProtocolNumber
  400. }
  401. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  402. }
  403. // The inject goroutine reads in packets that netstack generated, and delivers
  404. // them to the correct path.
  405. func (ns *Impl) inject() {
  406. for {
  407. pkt := ns.linkEP.ReadContext(ns.ctx)
  408. if pkt == nil {
  409. if ns.ctx.Err() != nil {
  410. // Return without logging.
  411. return
  412. }
  413. ns.logf("[v2] ReadContext-for-write = ok=false")
  414. continue
  415. }
  416. if debugPackets {
  417. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  418. }
  419. // In the normal case, netstack synthesizes the bytes for
  420. // traffic which should transit back into WG and go to peers.
  421. // However, some uses of netstack (presently, magic DNS)
  422. // send traffic destined for the local device, hence must
  423. // be injected 'inbound'.
  424. sendToHost := false
  425. // Determine if the packet is from a service IP, in which case it
  426. // needs to go back into the machines network (inbound) instead of
  427. // out.
  428. // TODO(tom): Work out a way to avoid parsing packets to determine if
  429. // its from the service IP. Maybe gvisor netstack magic. I
  430. // went through the fields of PacketBuffer, and nop :/
  431. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  432. // the IP src/dest even if its missing the rest of the pkt.
  433. // That way we dont have to do this twitchy-af byte-yeeting.
  434. if b := pkt.NetworkHeader().View(); len(b) >= 20 { // min ipv4 header
  435. switch b[0] >> 4 { // ip proto field
  436. case 4:
  437. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  438. sendToHost = true
  439. }
  440. case 6:
  441. if len(b) >= 40 { // min ipv6 header
  442. if srcIP, ok := netaddr.FromStdIP(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  443. sendToHost = true
  444. }
  445. }
  446. }
  447. }
  448. // pkt has a non-zero refcount, so injection methods takes
  449. // ownership of one count and will decrement on completion.
  450. if sendToHost {
  451. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  452. log.Printf("netstack inject inbound: %v", err)
  453. return
  454. }
  455. } else {
  456. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  457. log.Printf("netstack inject outbound: %v", err)
  458. return
  459. }
  460. }
  461. }
  462. }
  463. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  464. // node directly (but not a subnet-routed IP).
  465. func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
  466. return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
  467. }
  468. func (ns *Impl) processSSH() bool {
  469. return ns.lb != nil && ns.lb.ShouldRunSSH()
  470. }
  471. func (ns *Impl) peerAPIPortAtomic(ip netaddr.IP) *uint32 {
  472. if ip.Is4() {
  473. return &ns.peerapiPort4Atomic
  474. } else {
  475. return &ns.peerapiPort6Atomic
  476. }
  477. }
  478. var viaRange = tsaddr.TailscaleViaRange()
  479. // shouldProcessInbound reports whether an inbound packet (a packet from a
  480. // WireGuard peer) should be handled by netstack.
  481. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  482. // Handle incoming peerapi connections in netstack.
  483. if ns.lb != nil && p.IPProto == ipproto.TCP {
  484. var peerAPIPort uint16
  485. dstIP := p.Dst.IP()
  486. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn && ns.isLocalIP(dstIP) {
  487. if port, ok := ns.lb.GetPeerAPIPort(p.Dst.IP()); ok {
  488. peerAPIPort = port
  489. atomic.StoreUint32(ns.peerAPIPortAtomic(dstIP), uint32(port))
  490. }
  491. } else {
  492. peerAPIPort = uint16(atomic.LoadUint32(ns.peerAPIPortAtomic(dstIP)))
  493. }
  494. if p.IPProto == ipproto.TCP && p.Dst.Port() == peerAPIPort {
  495. return true
  496. }
  497. }
  498. if ns.isInboundTSSH(p) && ns.processSSH() {
  499. return true
  500. }
  501. if p.IPVersion == 6 && viaRange.Contains(p.Dst.IP()) {
  502. return ns.lb != nil && ns.lb.ShouldHandleViaIP(p.Dst.IP())
  503. }
  504. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  505. // Fast path for common case (e.g. Linux server in TUN mode) where
  506. // netstack isn't used at all; don't even do an isLocalIP lookup.
  507. return false
  508. }
  509. isLocal := ns.isLocalIP(p.Dst.IP())
  510. if ns.ProcessLocalIPs && isLocal {
  511. return true
  512. }
  513. if ns.ProcessSubnets && !isLocal {
  514. return true
  515. }
  516. return false
  517. }
  518. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  519. // CAP_NET_RAW from tailscaled's binary.
  520. var setAmbientCapsRaw func(*exec.Cmd)
  521. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  522. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  523. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  524. // into the tundev.
  525. //
  526. // It's used in userspace/netstack mode when we don't have kernel
  527. // support or raw socket access. As such, this does the dumbest thing
  528. // that can work: runs the ping command. It's not super efficient, so
  529. // it bounds the number of pings going on at once. The idea is that
  530. // people only use ping occasionally to see if their internet's working
  531. // so this doesn't need to be great.
  532. //
  533. // TODO(bradfitz): when we're running on Windows as the system user, use
  534. // raw socket APIs instead of ping child processes.
  535. func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
  536. if !userPingSem.TryAcquire() {
  537. return
  538. }
  539. defer userPingSem.Release()
  540. t0 := time.Now()
  541. var err error
  542. switch runtime.GOOS {
  543. case "windows":
  544. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  545. case "darwin":
  546. // Note: 2000 ms is actually 1 second + 2,000
  547. // milliseconds extra for 3 seconds total.
  548. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  549. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  550. case "android":
  551. ping := "/system/bin/ping"
  552. if dstIP.Is6() {
  553. ping = "/system/bin/ping6"
  554. }
  555. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  556. default:
  557. ping := "ping"
  558. if isSynology {
  559. ping = "/bin/ping"
  560. }
  561. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  562. if isSynology && os.Getuid() != 0 {
  563. // On DSM7 we run as non-root and need to pass
  564. // CAP_NET_RAW if our binary has it.
  565. setAmbientCapsRaw(cmd)
  566. }
  567. err = cmd.Run()
  568. }
  569. d := time.Since(t0)
  570. if err != nil {
  571. if d < time.Second/2 {
  572. // If it failed quicker than the 3 second
  573. // timeout we gave above (500 ms is a
  574. // reasonable threshold), then assume the ping
  575. // failed for problems finding/running
  576. // ping. We don't want to log if the host is
  577. // just down.
  578. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  579. }
  580. return
  581. }
  582. if debugNetstack {
  583. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  584. }
  585. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  586. ns.logf("InjectOutbound ping response: %v", err)
  587. }
  588. }
  589. func (ns *Impl) isInboundTSSH(p *packet.Parsed) bool {
  590. return p.IPProto == ipproto.TCP &&
  591. p.Dst.Port() == 22 &&
  592. ns.isLocalIP(p.Dst.IP())
  593. }
  594. // injectInbound is installed as a packet hook on the 'inbound' (from a
  595. // WireGuard peer) path. Returning filter.Accept releases the packet to
  596. // continue normally (typically being delivered to the host networking stack),
  597. // whereas returning filter.DropSilently is done when netstack intercepts the
  598. // packet and no further processing towards to host should be done.
  599. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  600. if !ns.shouldProcessInbound(p, t) {
  601. // Let the host network stack (if any) deal with it.
  602. return filter.Accept
  603. }
  604. destIP := p.Dst.IP()
  605. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  606. var pong []byte // the reply to the ping, if our relayed ping works
  607. if destIP.Is4() {
  608. h := p.ICMP4Header()
  609. h.ToResponse()
  610. pong = packet.Generate(&h, p.Payload())
  611. } else if destIP.Is6() {
  612. h := p.ICMP6Header()
  613. h.ToResponse()
  614. pong = packet.Generate(&h, p.Payload())
  615. }
  616. go ns.userPing(destIP, pong)
  617. return filter.DropSilently
  618. }
  619. var pn tcpip.NetworkProtocolNumber
  620. switch p.IPVersion {
  621. case 4:
  622. pn = header.IPv4ProtocolNumber
  623. case 6:
  624. pn = header.IPv6ProtocolNumber
  625. }
  626. if debugPackets {
  627. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  628. }
  629. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  630. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  631. Data: vv,
  632. })
  633. ns.linkEP.InjectInbound(pn, packetBuf)
  634. packetBuf.DecRef()
  635. // We've now delivered this to netstack, so we're done.
  636. // Instead of returning a filter.Accept here (which would also
  637. // potentially deliver it to the host OS), and instead of
  638. // filter.Drop (which would log about rejected traffic),
  639. // instead return filter.DropSilently which just quietly stops
  640. // processing it in the tstun TUN wrapper.
  641. return filter.DropSilently
  642. }
  643. func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
  644. switch len(s) {
  645. case 4:
  646. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  647. case 16:
  648. var a [16]byte
  649. copy(a[:], s)
  650. return netaddr.IPFrom16(a)
  651. }
  652. return netaddr.IP{}
  653. }
  654. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  655. reqDetails := r.ID()
  656. if debugNetstack {
  657. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  658. }
  659. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  660. if !clientRemoteIP.IsValid() {
  661. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  662. r.Complete(true) // sends a RST
  663. return
  664. }
  665. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  666. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  667. if viaRange.Contains(dialIP) {
  668. isTailscaleIP = false
  669. dialIP = tsaddr.UnmapVia(dialIP)
  670. }
  671. defer func() {
  672. if !isTailscaleIP {
  673. // if this is a subnet IP, we added this in before the TCP handshake
  674. // so netstack is happy TCP-handshaking as a subnet IP
  675. ns.removeSubnetAddress(dialIP)
  676. }
  677. }()
  678. var wq waiter.Queue
  679. ep, err := r.CreateEndpoint(&wq)
  680. if err != nil {
  681. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  682. r.Complete(true) // sends a RST
  683. return
  684. }
  685. r.Complete(false)
  686. // SetKeepAlive so that idle connections to peers that have forgotten about
  687. // the connection or gone completely offline eventually time out.
  688. // Applications might be setting this on a forwarded connection, but from
  689. // userspace we can not see those, so the best we can do is to always
  690. // perform them with conservative timing.
  691. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  692. // defaults, and results in a little over two hours before the socket would
  693. // be closed due to keepalive. A shorter default might be better, or seeking
  694. // a default from the host IP stack. This also might be a useful
  695. // user-tunable, as in userspace mode this can have broad implications such
  696. // as lingering connections to fork style daemons. On the other side of the
  697. // fence, the long duration timers are low impact values for battery powered
  698. // peers.
  699. ep.SocketOptions().SetKeepAlive(true)
  700. // The ForwarderRequest.CreateEndpoint above asynchronously
  701. // starts the TCP handshake. Note that the gonet.TCPConn
  702. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  703. // until the handshake actually completes. But we have the
  704. // remote address in reqDetails instead, so we don't use
  705. // gonet.TCPConn.RemoteAddr. The byte copies in both
  706. // directions to/from the gonet.TCPConn in forwardTCP will
  707. // block until the TCP handshake is complete.
  708. c := gonet.NewTCPConn(&wq, ep)
  709. if reqDetails.LocalPort == 53 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  710. go ns.dns.HandleTCPConn(c, netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort))
  711. return
  712. }
  713. if ns.lb != nil {
  714. if reqDetails.LocalPort == 22 && ns.processSSH() && ns.isLocalIP(dialIP) {
  715. if err := ns.lb.HandleSSHConn(c); err != nil {
  716. ns.logf("ssh error: %v", err)
  717. }
  718. return
  719. }
  720. if port, ok := ns.lb.GetPeerAPIPort(dialIP); ok {
  721. if reqDetails.LocalPort == port && ns.isLocalIP(dialIP) {
  722. src := netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort)
  723. dst := netaddr.IPPortFrom(dialIP, port)
  724. ns.lb.ServePeerAPIConnection(src, dst, c)
  725. return
  726. }
  727. }
  728. if reqDetails.LocalPort == 80 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  729. ns.lb.HandleQuad100Port80Conn(c)
  730. return
  731. }
  732. }
  733. if ns.ForwardTCPIn != nil {
  734. ns.ForwardTCPIn(c, reqDetails.LocalPort)
  735. return
  736. }
  737. if isTailscaleIP {
  738. dialIP = netaddr.IPv4(127, 0, 0, 1)
  739. }
  740. dialAddr := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
  741. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  742. }
  743. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
  744. defer client.Close()
  745. dialAddrStr := dialAddr.String()
  746. if debugNetstack {
  747. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  748. }
  749. ctx, cancel := context.WithCancel(context.Background())
  750. defer cancel()
  751. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  752. wq.EventRegister(&waitEntry)
  753. defer wq.EventUnregister(&waitEntry)
  754. done := make(chan bool)
  755. // netstack doesn't close the notification channel automatically if there was no
  756. // hup signal, so we close done after we're done to not leak the goroutine below.
  757. defer close(done)
  758. go func() {
  759. select {
  760. case <-notifyCh:
  761. if debugNetstack {
  762. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  763. }
  764. case <-done:
  765. }
  766. cancel()
  767. }()
  768. var stdDialer net.Dialer
  769. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  770. if err != nil {
  771. ns.logf("netstack: could not connect to local server at %s: %v", dialAddrStr, err)
  772. return
  773. }
  774. defer server.Close()
  775. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  776. backendLocalIPPort, _ := netaddr.FromStdAddr(backendLocalAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  777. ns.e.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  778. defer ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  779. connClosed := make(chan error, 2)
  780. go func() {
  781. _, err := io.Copy(server, client)
  782. connClosed <- err
  783. }()
  784. go func() {
  785. _, err := io.Copy(client, server)
  786. connClosed <- err
  787. }()
  788. err = <-connClosed
  789. if err != nil {
  790. ns.logf("proxy connection closed with error: %v", err)
  791. }
  792. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  793. }
  794. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  795. sess := r.ID()
  796. if debugNetstack {
  797. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  798. }
  799. var wq waiter.Queue
  800. ep, err := r.CreateEndpoint(&wq)
  801. if err != nil {
  802. ns.logf("acceptUDP: could not create endpoint: %v", err)
  803. return
  804. }
  805. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  806. if !ok {
  807. return
  808. }
  809. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  810. if !ok {
  811. return
  812. }
  813. // Handle magicDNS traffic (via UDP) here.
  814. if dst := dstAddr.IP(); dst == magicDNSIP || dst == magicDNSIPv6 {
  815. if dstAddr.Port() != 53 {
  816. return // Only MagicDNS traffic runs on the service IPs for now.
  817. }
  818. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  819. go ns.handleMagicDNSUDP(srcAddr, c)
  820. return
  821. }
  822. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  823. go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
  824. }
  825. func (ns *Impl) handleMagicDNSUDP(srcAddr netaddr.IPPort, c *gonet.UDPConn) {
  826. // In practice, implementations are advised not to exceed 512 bytes
  827. // due to fragmenting. Just to be sure, we bump all the way to the MTU.
  828. const maxUDPReqSize = mtu
  829. // Packets are being generated by the local host, so there should be
  830. // very, very little latency. 150ms was chosen as something of an upper
  831. // bound on resource usage, while hopefully still being long enough for
  832. // a heavily loaded system.
  833. const readDeadline = 150 * time.Millisecond
  834. defer c.Close()
  835. q := make([]byte, maxUDPReqSize)
  836. // libresolv from glibc is quite adamant that transmitting multiple DNS
  837. // requests down the same UDP socket is valid. To support this, we read
  838. // in a loop (with a tight deadline so we don't chew too many resources).
  839. //
  840. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  841. for {
  842. c.SetReadDeadline(time.Now().Add(readDeadline))
  843. n, _, err := c.ReadFrom(q)
  844. if err != nil {
  845. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  846. ns.logf("dns udp read: %v", err) // log non-timeout errors
  847. }
  848. return
  849. }
  850. resp, err := ns.dns.Query(context.Background(), q[:n], srcAddr)
  851. if err != nil {
  852. ns.logf("dns udp query: %v", err)
  853. return
  854. }
  855. c.Write(resp)
  856. }
  857. }
  858. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  859. //
  860. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  861. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  862. // proxy to it directly.
  863. func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netaddr.IPPort) {
  864. port, srcPort := dstAddr.Port(), clientAddr.Port()
  865. if debugNetstack {
  866. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  867. }
  868. var backendListenAddr *net.UDPAddr
  869. var backendRemoteAddr *net.UDPAddr
  870. isLocal := ns.isLocalIP(dstAddr.IP())
  871. if isLocal {
  872. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  873. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  874. } else {
  875. if dstIP := dstAddr.IP(); viaRange.Contains(dstIP) {
  876. dstAddr = netaddr.IPPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  877. }
  878. backendRemoteAddr = dstAddr.UDPAddr()
  879. if dstAddr.IP().Is4() {
  880. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  881. } else {
  882. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  883. }
  884. }
  885. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  886. if err != nil {
  887. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  888. backendListenAddr.Port = 0
  889. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  890. if err != nil {
  891. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  892. return
  893. }
  894. }
  895. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  896. backendLocalIPPort, ok := netaddr.FromStdAddr(backendListenAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  897. if !ok {
  898. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  899. }
  900. if isLocal {
  901. ns.e.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.IP())
  902. }
  903. ctx, cancel := context.WithCancel(context.Background())
  904. idleTimeout := 2 * time.Minute
  905. if port == 53 {
  906. // Make DNS packet copies time out much sooner.
  907. //
  908. // TODO(bradfitz): make DNS queries over UDP forwarding even
  909. // cheaper by adding an additional idleTimeout post-DNS-reply.
  910. // For instance, after the DNS response goes back out, then only
  911. // wait a few seconds (or zero, really)
  912. idleTimeout = 30 * time.Second
  913. }
  914. timer := time.AfterFunc(idleTimeout, func() {
  915. if isLocal {
  916. ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  917. }
  918. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  919. cancel()
  920. client.Close()
  921. backendConn.Close()
  922. })
  923. extend := func() {
  924. timer.Reset(idleTimeout)
  925. }
  926. startPacketCopy(ctx, cancel, client, clientAddr.UDPAddr(), backendConn, ns.logf, extend)
  927. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  928. if isLocal {
  929. // Wait for the copies to be done before decrementing the
  930. // subnet address count to potentially remove the route.
  931. <-ctx.Done()
  932. ns.removeSubnetAddress(dstAddr.IP())
  933. }
  934. }
  935. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  936. if debugNetstack {
  937. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  938. }
  939. go func() {
  940. defer cancel() // tear down the other direction's copy
  941. pkt := make([]byte, mtu)
  942. for {
  943. select {
  944. case <-ctx.Done():
  945. return
  946. default:
  947. n, srcAddr, err := src.ReadFrom(pkt)
  948. if err != nil {
  949. if ctx.Err() == nil {
  950. logf("read packet from %s failed: %v", srcAddr, err)
  951. }
  952. return
  953. }
  954. _, err = dst.WriteTo(pkt[:n], dstAddr)
  955. if err != nil {
  956. if ctx.Err() == nil {
  957. logf("write packet to %s failed: %v", dstAddr, err)
  958. }
  959. return
  960. }
  961. if debugNetstack {
  962. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  963. }
  964. extend()
  965. }
  966. }
  967. }()
  968. }
  969. func stringifyTEI(tei stack.TransportEndpointID) string {
  970. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  971. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  972. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  973. }
  974. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netaddr.IPPort, ok bool) {
  975. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  976. }