netstack.go 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package netstack wires up gVisor's netstack into Tailscale.
  4. package netstack
  5. import (
  6. "bytes"
  7. "context"
  8. "errors"
  9. "expvar"
  10. "fmt"
  11. "io"
  12. "math"
  13. "net"
  14. "net/netip"
  15. "runtime"
  16. "strconv"
  17. "sync"
  18. "sync/atomic"
  19. "time"
  20. "github.com/tailscale/wireguard-go/conn"
  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/header"
  25. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  26. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  27. "gvisor.dev/gvisor/pkg/tcpip/stack"
  28. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  29. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  30. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  31. "gvisor.dev/gvisor/pkg/waiter"
  32. "tailscale.com/envknob"
  33. "tailscale.com/feature/buildfeatures"
  34. "tailscale.com/ipn/ipnlocal"
  35. "tailscale.com/metrics"
  36. "tailscale.com/net/dns"
  37. "tailscale.com/net/ipset"
  38. "tailscale.com/net/netaddr"
  39. "tailscale.com/net/netx"
  40. "tailscale.com/net/packet"
  41. "tailscale.com/net/tsaddr"
  42. "tailscale.com/net/tsdial"
  43. "tailscale.com/net/tstun"
  44. "tailscale.com/proxymap"
  45. "tailscale.com/syncs"
  46. "tailscale.com/tailcfg"
  47. "tailscale.com/types/ipproto"
  48. "tailscale.com/types/logger"
  49. "tailscale.com/types/netmap"
  50. "tailscale.com/types/nettype"
  51. "tailscale.com/util/clientmetric"
  52. "tailscale.com/util/set"
  53. "tailscale.com/version"
  54. "tailscale.com/wgengine"
  55. "tailscale.com/wgengine/filter"
  56. "tailscale.com/wgengine/magicsock"
  57. "tailscale.com/wgengine/netstack/gro"
  58. )
  59. const debugPackets = false
  60. // If non-zero, these override the values returned from the corresponding
  61. // functions, below.
  62. var (
  63. maxInFlightConnectionAttemptsForTest int
  64. maxInFlightConnectionAttemptsPerClientForTest int
  65. )
  66. // maxInFlightConnectionAttempts returns the global number of in-flight
  67. // connection attempts that we allow for a single netstack Impl. Any new
  68. // forwarded TCP connections that are opened after the limit has been hit are
  69. // rejected until the number of in-flight connections drops below the limit
  70. // again.
  71. //
  72. // Each in-flight connection attempt is a new goroutine and an open TCP
  73. // connection, so we want to ensure that we don't allow an unbounded number of
  74. // connections.
  75. func maxInFlightConnectionAttempts() int {
  76. if n := maxInFlightConnectionAttemptsForTest; n > 0 {
  77. return n
  78. }
  79. if version.IsMobile() {
  80. return 1024 // previous global value
  81. }
  82. switch version.OS() {
  83. case "linux":
  84. // On the assumption that most subnet routers deployed in
  85. // production are running on Linux, we return a higher value.
  86. //
  87. // TODO(andrew-d): tune this based on the amount of system
  88. // memory instead of a fixed limit.
  89. return 8192
  90. default:
  91. // On all other platforms, return a reasonably high value that
  92. // most users won't hit.
  93. return 2048
  94. }
  95. }
  96. // maxInFlightConnectionAttemptsPerClient is the same as
  97. // maxInFlightConnectionAttempts, but applies on a per-client basis
  98. // (i.e. keyed by the remote Tailscale IP).
  99. func maxInFlightConnectionAttemptsPerClient() int {
  100. if n := maxInFlightConnectionAttemptsPerClientForTest; n > 0 {
  101. return n
  102. }
  103. // For now, allow each individual client at most 2/3rds of the global
  104. // limit. On all platforms except mobile, this won't be a visible
  105. // change for users since this limit was added at the same time as we
  106. // bumped the global limit, above.
  107. return maxInFlightConnectionAttempts() * 2 / 3
  108. }
  109. var debugNetstack = envknob.RegisterBool("TS_DEBUG_NETSTACK")
  110. var (
  111. serviceIP = tsaddr.TailscaleServiceIP()
  112. serviceIPv6 = tsaddr.TailscaleServiceIPv6()
  113. )
  114. func init() {
  115. mode := envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  116. if mode == "" {
  117. return
  118. }
  119. var lm refs.LeakMode
  120. if err := lm.Set(mode); err != nil {
  121. panic(err)
  122. }
  123. refs.SetLeakMode(lm)
  124. }
  125. // Impl contains the state for the netstack implementation,
  126. // and implements wgengine.FakeImpl to act as a userspace network
  127. // stack when Tailscale is running in fake mode.
  128. type Impl struct {
  129. // GetTCPHandlerForFlow conditionally handles an incoming TCP flow for the
  130. // provided (src/port, dst/port) 4-tuple.
  131. //
  132. // A nil value is equivalent to a func returning (nil, false).
  133. //
  134. // If func returns intercept=false, the default forwarding behavior (if
  135. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  136. //
  137. // When intercept=true, the behavior depends on whether the returned handler
  138. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  139. // over the TCP conn.
  140. GetTCPHandlerForFlow func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool)
  141. // GetUDPHandlerForFlow conditionally handles an incoming UDP flow for the
  142. // provided (src/port, dst/port) 4-tuple.
  143. //
  144. // A nil value is equivalent to a func returning (nil, false).
  145. //
  146. // If func returns intercept=false, the default forwarding behavior (if
  147. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  148. //
  149. // When intercept=true, the behavior depends on whether the returned handler
  150. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  151. // over the UDP flow.
  152. GetUDPHandlerForFlow func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool)
  153. // ProcessLocalIPs is whether netstack should handle incoming
  154. // traffic directed at the Node.Addresses (local IPs).
  155. // It can only be set before calling Start.
  156. ProcessLocalIPs bool
  157. // ProcessSubnets is whether netstack should handle incoming
  158. // traffic destined to non-local IPs (i.e. whether it should
  159. // be a subnet router).
  160. // It can only be set before calling Start.
  161. ProcessSubnets bool
  162. ipstack *stack.Stack
  163. linkEP *linkEndpoint
  164. tundev *tstun.Wrapper
  165. e wgengine.Engine
  166. pm *proxymap.Mapper
  167. mc *magicsock.Conn
  168. logf logger.Logf
  169. dialer *tsdial.Dialer
  170. ctx context.Context // alive until Close
  171. ctxCancel context.CancelFunc // called on Close
  172. lb *ipnlocal.LocalBackend // or nil
  173. dns *dns.Manager
  174. // loopbackPort, if non-nil, will enable Impl to loop back (dnat to
  175. // <address-family-loopback>:loopbackPort) TCP & UDP flows originally
  176. // destined to serviceIP{v6}:loopbackPort.
  177. loopbackPort *int
  178. peerapiPort4Atomic atomic.Uint32 // uint16 port number for IPv4 peerapi
  179. peerapiPort6Atomic atomic.Uint32 // uint16 port number for IPv6 peerapi
  180. // atomicIsLocalIPFunc holds a func that reports whether an IP
  181. // is a local (non-subnet) Tailscale IP address of this
  182. // machine. It's always a non-nil func. It's changed on netmap
  183. // updates.
  184. atomicIsLocalIPFunc syncs.AtomicValue[func(netip.Addr) bool]
  185. atomicIsVIPServiceIPFunc syncs.AtomicValue[func(netip.Addr) bool]
  186. // forwardDialFunc, if non-nil, is the net.Dialer.DialContext-style
  187. // function that is used to make outgoing connections when forwarding a
  188. // TCP connection to another host (e.g. in subnet router mode).
  189. //
  190. // This is currently only used in tests.
  191. forwardDialFunc netx.DialFunc
  192. // forwardInFlightPerClientDropped is a metric that tracks how many
  193. // in-flight TCP forward requests were dropped due to the per-client
  194. // limit.
  195. forwardInFlightPerClientDropped expvar.Int
  196. mu sync.Mutex
  197. // connsOpenBySubnetIP keeps track of number of connections open
  198. // for each subnet IP temporarily registered on netstack for active
  199. // TCP connections, so they can be unregistered when connections are
  200. // closed.
  201. connsOpenBySubnetIP map[netip.Addr]int
  202. // connsInFlightByClient keeps track of the number of in-flight
  203. // connections by the client ("Tailscale") IP. This is used to apply a
  204. // per-client limit on in-flight connections that's smaller than the
  205. // global limit, preventing a misbehaving client from starving the
  206. // global limit.
  207. connsInFlightByClient map[netip.Addr]int
  208. // packetsInFlight tracks whether we're already handling a packet by
  209. // the given endpoint ID; clients can send repeated SYN packets while
  210. // trying to establish a connection (and while we're dialing the
  211. // upstream address). If we don't deduplicate based on the endpoint,
  212. // each SYN retransmit results in us incrementing
  213. // connsInFlightByClient, and not decrementing them because the
  214. // underlying TCP forwarder returns 'true' to indicate that the packet
  215. // is handled but never actually launches our acceptTCP function.
  216. //
  217. // This mimics the 'inFlight' map in the TCP forwarder; it's
  218. // unfortunate that we have to track this all twice, but thankfully the
  219. // map only holds pending (in-flight) packets, and it's reasonably cheap.
  220. packetsInFlight map[stack.TransportEndpointID]struct{}
  221. }
  222. const nicID = 1
  223. // maxUDPPacketSize is the maximum size of a UDP packet we copy in
  224. // startPacketCopy when relaying UDP packets. The user can configure
  225. // the tailscale MTU to anything up to this size so we can potentially
  226. // have a UDP packet as big as the MTU.
  227. const maxUDPPacketSize = tstun.MaxPacketSize
  228. func setTCPBufSizes(ipstack *stack.Stack) error {
  229. // tcpip.TCP{Receive,Send}BufferSizeRangeOption is gVisor's version of
  230. // Linux's tcp_{r,w}mem. Application within gVisor differs as some Linux
  231. // features are not (yet) implemented, and socket buffer memory is not
  232. // controlled within gVisor, e.g. we allocate *stack.PacketBuffer's for the
  233. // write path within Tailscale. Therefore, we loosen our understanding of
  234. // the relationship between these Linux and gVisor tunables. The chosen
  235. // values are biased towards higher throughput on high bandwidth-delay
  236. // product paths, except on memory-constrained platforms.
  237. tcpRXBufOpt := tcpip.TCPReceiveBufferSizeRangeOption{
  238. // Min is unused by gVisor at the time of writing, but partially plumbed
  239. // for application by the TCP_WINDOW_CLAMP socket option.
  240. Min: tcpRXBufMinSize,
  241. // Default is used by gVisor at socket creation.
  242. Default: tcpRXBufDefSize,
  243. // Max is used by gVisor to cap the advertised receive window post-read.
  244. // (tcp_moderate_rcvbuf=true, the default).
  245. Max: tcpRXBufMaxSize,
  246. }
  247. tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRXBufOpt)
  248. if tcpipErr != nil {
  249. return fmt.Errorf("could not set TCP RX buf size: %v", tcpipErr)
  250. }
  251. tcpTXBufOpt := tcpip.TCPSendBufferSizeRangeOption{
  252. // Min in unused by gVisor at the time of writing.
  253. Min: tcpTXBufMinSize,
  254. // Default is used by gVisor at socket creation.
  255. Default: tcpTXBufDefSize,
  256. // Max is used by gVisor to cap the send window.
  257. Max: tcpTXBufMaxSize,
  258. }
  259. tcpipErr = ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpTXBufOpt)
  260. if tcpipErr != nil {
  261. return fmt.Errorf("could not set TCP TX buf size: %v", tcpipErr)
  262. }
  263. return nil
  264. }
  265. // Create creates and populates a new Impl.
  266. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer, dns *dns.Manager, pm *proxymap.Mapper) (*Impl, error) {
  267. if mc == nil {
  268. return nil, errors.New("nil magicsock.Conn")
  269. }
  270. if tundev == nil {
  271. return nil, errors.New("nil tundev")
  272. }
  273. if logf == nil {
  274. return nil, errors.New("nil logger")
  275. }
  276. if e == nil {
  277. return nil, errors.New("nil Engine")
  278. }
  279. if pm == nil {
  280. return nil, errors.New("nil proxymap.Mapper")
  281. }
  282. if dialer == nil {
  283. return nil, errors.New("nil Dialer")
  284. }
  285. ipstack := stack.New(stack.Options{
  286. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  287. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  288. })
  289. sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
  290. tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
  291. if tcpipErr != nil {
  292. return nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
  293. }
  294. // See https://github.com/tailscale/tailscale/issues/9707
  295. // gVisor's RACK performs poorly. ACKs do not appear to be handled in a
  296. // timely manner, leading to spurious retransmissions and a reduced
  297. // congestion window.
  298. tcpRecoveryOpt := tcpip.TCPRecovery(0)
  299. tcpipErr = ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRecoveryOpt)
  300. if tcpipErr != nil {
  301. return nil, fmt.Errorf("could not disable TCP RACK: %v", tcpipErr)
  302. }
  303. // gVisor defaults to reno at the time of writing. We explicitly set reno
  304. // congestion control in order to prevent unexpected changes. Netstack
  305. // has an int overflow in sender congestion window arithmetic that is more
  306. // prone to trigger with cubic congestion control.
  307. // See https://github.com/google/gvisor/issues/11632
  308. renoOpt := tcpip.CongestionControlOption("reno")
  309. tcpipErr = ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &renoOpt)
  310. if tcpipErr != nil {
  311. return nil, fmt.Errorf("could not set reno congestion control: %v", tcpipErr)
  312. }
  313. err := setTCPBufSizes(ipstack)
  314. if err != nil {
  315. return nil, err
  316. }
  317. supportedGSOKind := stack.GSONotSupported
  318. supportedGROKind := groNotSupported
  319. if runtime.GOOS == "linux" && buildfeatures.HasGRO {
  320. // TODO(jwhited): add Windows support https://github.com/tailscale/corp/issues/21874
  321. supportedGROKind = tcpGROSupported
  322. supportedGSOKind = stack.HostGSOSupported
  323. }
  324. linkEP := newLinkEndpoint(512, uint32(tstun.DefaultTUNMTU()), "", supportedGROKind)
  325. linkEP.SupportedGSOKind = supportedGSOKind
  326. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  327. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  328. }
  329. // By default the netstack NIC will only accept packets for the IPs
  330. // registered to it. Since in some cases we dynamically register IPs
  331. // based on the packets that arrive, the NIC needs to accept all
  332. // incoming packets. The NIC won't receive anything it isn't meant to
  333. // since WireGuard will only send us packets that are meant for us.
  334. ipstack.SetPromiscuousMode(nicID, true)
  335. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  336. // are handled by the one fake NIC we use.
  337. ipv4Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 4)), tcpip.MaskFromBytes(make([]byte, 4)))
  338. if err != nil {
  339. return nil, fmt.Errorf("could not create IPv4 subnet: %v", err)
  340. }
  341. ipv6Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 16)), tcpip.MaskFromBytes(make([]byte, 16)))
  342. if err != nil {
  343. return nil, fmt.Errorf("could not create IPv6 subnet: %v", err)
  344. }
  345. ipstack.SetRouteTable([]tcpip.Route{
  346. {
  347. Destination: ipv4Subnet,
  348. NIC: nicID,
  349. },
  350. {
  351. Destination: ipv6Subnet,
  352. NIC: nicID,
  353. },
  354. })
  355. ns := &Impl{
  356. logf: logf,
  357. ipstack: ipstack,
  358. linkEP: linkEP,
  359. tundev: tundev,
  360. e: e,
  361. pm: pm,
  362. mc: mc,
  363. dialer: dialer,
  364. connsOpenBySubnetIP: make(map[netip.Addr]int),
  365. connsInFlightByClient: make(map[netip.Addr]int),
  366. packetsInFlight: make(map[stack.TransportEndpointID]struct{}),
  367. dns: dns,
  368. }
  369. loopbackPort, ok := envknob.LookupInt("TS_DEBUG_NETSTACK_LOOPBACK_PORT")
  370. if ok && loopbackPort >= 0 && loopbackPort <= math.MaxUint16 {
  371. ns.loopbackPort = &loopbackPort
  372. }
  373. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  374. ns.atomicIsLocalIPFunc.Store(ipset.FalseContainsIPFunc())
  375. ns.atomicIsVIPServiceIPFunc.Store(ipset.FalseContainsIPFunc())
  376. ns.tundev.PostFilterPacketInboundFromWireGuard = ns.injectInbound
  377. ns.tundev.PreFilterPacketOutboundToWireGuardNetstackIntercept = ns.handleLocalPackets
  378. stacksForMetrics.Store(ns, struct{}{})
  379. return ns, nil
  380. }
  381. func (ns *Impl) Close() error {
  382. stacksForMetrics.Delete(ns)
  383. ns.ctxCancel()
  384. ns.ipstack.Close()
  385. ns.ipstack.Wait()
  386. return nil
  387. }
  388. // SetTransportProtocolOption forwards to the underlying
  389. // [stack.Stack.SetTransportProtocolOption]. Callers are responsible for
  390. // ensuring that the options are valid, compatible and appropriate for their use
  391. // case. Compatibility may change at any version.
  392. func (ns *Impl) SetTransportProtocolOption(transport tcpip.TransportProtocolNumber, option tcpip.SettableTransportProtocolOption) tcpip.Error {
  393. return ns.ipstack.SetTransportProtocolOption(transport, option)
  394. }
  395. // A single process might have several netstacks running at the same time.
  396. // Exported clientmetric counters will have a sum of counters of all of them.
  397. var stacksForMetrics syncs.Map[*Impl, struct{}]
  398. func init() {
  399. // Please take care to avoid exporting clientmetrics with the same metric
  400. // names as the ones used by Impl.ExpVar. Both get exposed via the same HTTP
  401. // endpoint, and name collisions will result in Prometheus scraping errors.
  402. clientmetric.NewCounterFunc("netstack_tcp_forward_dropped_attempts", func() int64 {
  403. var total uint64
  404. for ns := range stacksForMetrics.Keys() {
  405. delta := ns.ipstack.Stats().TCP.ForwardMaxInFlightDrop.Value()
  406. if total+delta > math.MaxInt64 {
  407. total = math.MaxInt64
  408. break
  409. }
  410. total += delta
  411. }
  412. return int64(total)
  413. })
  414. }
  415. type protocolHandlerFunc func(stack.TransportEndpointID, *stack.PacketBuffer) bool
  416. // wrapUDPProtocolHandler wraps the protocol handler we pass to netstack for UDP.
  417. func (ns *Impl) wrapUDPProtocolHandler(h protocolHandlerFunc) protocolHandlerFunc {
  418. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) bool {
  419. addr := tei.LocalAddress
  420. ip, ok := netip.AddrFromSlice(addr.AsSlice())
  421. if !ok {
  422. ns.logf("netstack: could not parse local address for incoming connection")
  423. return false
  424. }
  425. // Dynamically reconfigure ns's subnet addresses as needed for
  426. // outbound traffic.
  427. ip = ip.Unmap()
  428. if !ns.isLocalIP(ip) {
  429. ns.addSubnetAddress(ip)
  430. }
  431. return h(tei, pb)
  432. }
  433. }
  434. var (
  435. metricPerClientForwardLimit = clientmetric.NewCounter("netstack_tcp_forward_dropped_attempts_per_client")
  436. )
  437. // wrapTCPProtocolHandler wraps the protocol handler we pass to netstack for TCP.
  438. func (ns *Impl) wrapTCPProtocolHandler(h protocolHandlerFunc) protocolHandlerFunc {
  439. // 'handled' is whether the packet should be accepted by netstack; if
  440. // true, then the TCP connection is accepted by the transport layer and
  441. // passes through our acceptTCP handler/etc. If false, then the packet
  442. // is dropped and the TCP connection is rejected (typically with an
  443. // ICMP Port Unreachable or ICMP Protocol Unreachable message).
  444. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) (handled bool) {
  445. localIP, ok := netip.AddrFromSlice(tei.LocalAddress.AsSlice())
  446. if !ok {
  447. ns.logf("netstack: could not parse local address for incoming connection")
  448. return false
  449. }
  450. localIP = localIP.Unmap()
  451. remoteIP, ok := netip.AddrFromSlice(tei.RemoteAddress.AsSlice())
  452. if !ok {
  453. ns.logf("netstack: could not parse remote address for incoming connection")
  454. return false
  455. }
  456. // If we have too many in-flight connections for this client, abort
  457. // early and don't open a new one.
  458. //
  459. // NOTE: the counter is decremented in
  460. // decrementInFlightTCPForward, called from the acceptTCP
  461. // function, below.
  462. ns.mu.Lock()
  463. if _, ok := ns.packetsInFlight[tei]; ok {
  464. // We're already handling this packet; just bail early
  465. // (this is also what would happen in the TCP
  466. // forwarder).
  467. ns.mu.Unlock()
  468. return true
  469. }
  470. // Check the per-client limit.
  471. inFlight := ns.connsInFlightByClient[remoteIP]
  472. tooManyInFlight := inFlight >= maxInFlightConnectionAttemptsPerClient()
  473. if !tooManyInFlight {
  474. ns.connsInFlightByClient[remoteIP]++
  475. }
  476. // We're handling this packet now; see the comment on the
  477. // packetsInFlight field for more details.
  478. ns.packetsInFlight[tei] = struct{}{}
  479. ns.mu.Unlock()
  480. if debugNetstack() {
  481. ns.logf("[v2] netstack: in-flight connections for client %v: %d", remoteIP, inFlight)
  482. }
  483. if tooManyInFlight {
  484. ns.logf("netstack: ignoring a new TCP connection from %v to %v because the client already has %d in-flight connections", localIP, remoteIP, inFlight)
  485. metricPerClientForwardLimit.Add(1)
  486. ns.forwardInFlightPerClientDropped.Add(1)
  487. return false // unhandled
  488. }
  489. // On return, if this packet isn't handled by the inner handler
  490. // we're wrapping (`h`), we need to decrement the per-client
  491. // in-flight count and remove the ID from our tracking map.
  492. // This can happen if the underlying forwarder's limit has been
  493. // reached, at which point it will return false to indicate
  494. // that it's not handling the packet, and it will not run
  495. // acceptTCP. If we don't decrement here, then we would
  496. // eventually increment the per-client counter up to the limit
  497. // and never decrement because we'd never hit the codepath in
  498. // acceptTCP, below, or just drop all packets from the same
  499. // endpoint due to the packetsInFlight check.
  500. defer func() {
  501. if !handled {
  502. ns.mu.Lock()
  503. delete(ns.packetsInFlight, tei)
  504. ns.connsInFlightByClient[remoteIP]--
  505. new := ns.connsInFlightByClient[remoteIP]
  506. ns.mu.Unlock()
  507. ns.logf("netstack: decrementing connsInFlightByClient[%v] because the packet was not handled; new value is %d", remoteIP, new)
  508. }
  509. }()
  510. // Dynamically reconfigure ns's subnet addresses as needed for
  511. // outbound traffic.
  512. if !ns.isLocalIP(localIP) && !ns.isVIPServiceIP(localIP) {
  513. ns.addSubnetAddress(localIP)
  514. }
  515. return h(tei, pb)
  516. }
  517. }
  518. func (ns *Impl) decrementInFlightTCPForward(tei stack.TransportEndpointID, remoteAddr netip.Addr) {
  519. ns.mu.Lock()
  520. defer ns.mu.Unlock()
  521. // Remove this packet so future SYNs from this address will be handled.
  522. delete(ns.packetsInFlight, tei)
  523. was := ns.connsInFlightByClient[remoteAddr]
  524. newVal := was - 1
  525. if newVal == 0 {
  526. delete(ns.connsInFlightByClient, remoteAddr) // free up space in the map
  527. } else {
  528. ns.connsInFlightByClient[remoteAddr] = newVal
  529. }
  530. }
  531. // LocalBackend is a fake name for *ipnlocal.LocalBackend to avoid an import cycle.
  532. type LocalBackend = any
  533. // Start sets up all the handlers so netstack can start working. Implements
  534. // wgengine.FakeImpl.
  535. func (ns *Impl) Start(b LocalBackend) error {
  536. if b == nil {
  537. panic("nil LocalBackend interface")
  538. }
  539. lb := b.(*ipnlocal.LocalBackend)
  540. if lb == nil {
  541. panic("nil LocalBackend")
  542. }
  543. ns.lb = lb
  544. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpRXBufDefSize, maxInFlightConnectionAttempts(), ns.acceptTCP)
  545. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  546. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapTCPProtocolHandler(tcpFwd.HandlePacket))
  547. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapUDPProtocolHandler(udpFwd.HandlePacket))
  548. go ns.inject()
  549. return nil
  550. }
  551. func (ns *Impl) addSubnetAddress(ip netip.Addr) {
  552. ns.mu.Lock()
  553. ns.connsOpenBySubnetIP[ip]++
  554. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  555. ns.mu.Unlock()
  556. // Only register address into netstack for first concurrent connection.
  557. if needAdd {
  558. pa := tcpip.ProtocolAddress{
  559. AddressWithPrefix: tcpip.AddrFromSlice(ip.AsSlice()).WithPrefix(),
  560. }
  561. if ip.Is4() {
  562. pa.Protocol = ipv4.ProtocolNumber
  563. } else if ip.Is6() {
  564. pa.Protocol = ipv6.ProtocolNumber
  565. }
  566. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  567. PEB: stack.CanBePrimaryEndpoint, // zero value default
  568. ConfigType: stack.AddressConfigStatic, // zero value default
  569. })
  570. }
  571. }
  572. func (ns *Impl) removeSubnetAddress(ip netip.Addr) {
  573. ns.mu.Lock()
  574. defer ns.mu.Unlock()
  575. ns.connsOpenBySubnetIP[ip]--
  576. // Only unregister address from netstack after last concurrent connection.
  577. if ns.connsOpenBySubnetIP[ip] == 0 {
  578. ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(ip.AsSlice()))
  579. delete(ns.connsOpenBySubnetIP, ip)
  580. }
  581. }
  582. func ipPrefixToAddressWithPrefix(ipp netip.Prefix) tcpip.AddressWithPrefix {
  583. return tcpip.AddressWithPrefix{
  584. Address: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  585. PrefixLen: int(ipp.Bits()),
  586. }
  587. }
  588. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  589. // UpdateNetstackIPs updates the set of local IPs that netstack should handle
  590. // from nm.
  591. //
  592. // TODO(bradfitz): don't pass the whole netmap here; just pass the two
  593. // address slice views.
  594. func (ns *Impl) UpdateNetstackIPs(nm *netmap.NetworkMap) {
  595. var selfNode tailcfg.NodeView
  596. var serviceAddrSet set.Set[netip.Addr]
  597. if nm != nil {
  598. ns.atomicIsLocalIPFunc.Store(ipset.NewContainsIPFunc(nm.GetAddresses()))
  599. if buildfeatures.HasServe {
  600. vipServiceIPMap := nm.GetVIPServiceIPMap()
  601. serviceAddrSet = make(set.Set[netip.Addr], len(vipServiceIPMap)*2)
  602. for _, addrs := range vipServiceIPMap {
  603. serviceAddrSet.AddSlice(addrs)
  604. }
  605. ns.atomicIsVIPServiceIPFunc.Store(serviceAddrSet.Contains)
  606. }
  607. selfNode = nm.SelfNode
  608. } else {
  609. ns.atomicIsLocalIPFunc.Store(ipset.FalseContainsIPFunc())
  610. ns.atomicIsVIPServiceIPFunc.Store(ipset.FalseContainsIPFunc())
  611. }
  612. oldPfx := make(map[netip.Prefix]bool)
  613. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  614. ap := protocolAddr.AddressWithPrefix
  615. ip := netaddrIPFromNetstackIP(ap.Address)
  616. if ip == v4broadcast && ap.PrefixLen == 32 {
  617. // Don't add 255.255.255.255/32 to oldIPs so we don't
  618. // delete it later. We didn't install it, so it's not
  619. // ours to delete.
  620. continue
  621. }
  622. p := netip.PrefixFrom(ip, ap.PrefixLen)
  623. oldPfx[p] = true
  624. }
  625. newPfx := make(map[netip.Prefix]bool)
  626. if selfNode.Valid() {
  627. for _, p := range selfNode.Addresses().All() {
  628. newPfx[p] = true
  629. }
  630. if ns.ProcessSubnets {
  631. for _, p := range selfNode.AllowedIPs().All() {
  632. newPfx[p] = true
  633. }
  634. }
  635. }
  636. for addr := range serviceAddrSet {
  637. p := netip.PrefixFrom(addr, addr.BitLen())
  638. newPfx[p] = true
  639. }
  640. pfxToAdd := make(map[netip.Prefix]bool)
  641. for p := range newPfx {
  642. if !oldPfx[p] {
  643. pfxToAdd[p] = true
  644. }
  645. }
  646. pfxToRemove := make(map[netip.Prefix]bool)
  647. for p := range oldPfx {
  648. if !newPfx[p] {
  649. pfxToRemove[p] = true
  650. }
  651. }
  652. ns.mu.Lock()
  653. for ip := range ns.connsOpenBySubnetIP {
  654. // TODO(maisem): this looks like a bug, remove or document. It seems as
  655. // though we might end up either leaking the address on the netstack
  656. // NIC, or where we do accounting for connsOpenBySubnetIP from 1 to 0,
  657. // we might end up removing the address from the netstack NIC that was
  658. // still being advertised.
  659. delete(pfxToRemove, netip.PrefixFrom(ip, ip.BitLen()))
  660. }
  661. ns.mu.Unlock()
  662. for p := range pfxToRemove {
  663. err := ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(p.Addr().AsSlice()))
  664. if err != nil {
  665. ns.logf("netstack: could not deregister IP %s: %v", p, err)
  666. } else {
  667. ns.logf("[v2] netstack: deregistered IP %s", p)
  668. }
  669. }
  670. for p := range pfxToAdd {
  671. if !p.IsValid() {
  672. ns.logf("netstack: [unexpected] skipping invalid IP (%v/%v)", p.Addr(), p.Bits())
  673. continue
  674. }
  675. tcpAddr := tcpip.ProtocolAddress{
  676. AddressWithPrefix: ipPrefixToAddressWithPrefix(p),
  677. }
  678. if p.Addr().Is6() {
  679. tcpAddr.Protocol = ipv6.ProtocolNumber
  680. } else {
  681. tcpAddr.Protocol = ipv4.ProtocolNumber
  682. }
  683. var tcpErr tcpip.Error // not error
  684. tcpErr = ns.ipstack.AddProtocolAddress(nicID, tcpAddr, stack.AddressProperties{
  685. PEB: stack.CanBePrimaryEndpoint, // zero value default
  686. ConfigType: stack.AddressConfigStatic, // zero value default
  687. })
  688. if tcpErr != nil {
  689. ns.logf("netstack: could not register IP %s: %v", p, tcpErr)
  690. } else {
  691. ns.logf("[v2] netstack: registered IP %s", p)
  692. }
  693. }
  694. }
  695. func (ns *Impl) isLoopbackPort(port uint16) bool {
  696. if ns.loopbackPort != nil && int(port) == *ns.loopbackPort {
  697. return true
  698. }
  699. return false
  700. }
  701. // handleLocalPackets is hooked into the tun datapath for packets leaving
  702. // the host and arriving at tailscaled. This method returns filter.DropSilently
  703. // to intercept a packet for handling, for instance traffic to quad-100.
  704. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper, gro *gro.GRO) (filter.Response, *gro.GRO) {
  705. if ns.ctx.Err() != nil {
  706. return filter.DropSilently, gro
  707. }
  708. // Determine if we care about this local packet.
  709. dst := p.Dst.Addr()
  710. switch {
  711. case dst == serviceIP || dst == serviceIPv6:
  712. // We want to intercept some traffic to the "service IP" (e.g.
  713. // 100.100.100.100 for IPv4). However, of traffic to the
  714. // service IP, we only care about UDP 53, and TCP on port 53,
  715. // 80, and 8080.
  716. switch p.IPProto {
  717. case ipproto.TCP:
  718. if port := p.Dst.Port(); port != 53 && port != 80 && port != 8080 && !ns.isLoopbackPort(port) {
  719. return filter.Accept, gro
  720. }
  721. case ipproto.UDP:
  722. if port := p.Dst.Port(); port != 53 && !ns.isLoopbackPort(port) {
  723. return filter.Accept, gro
  724. }
  725. }
  726. case viaRange.Contains(dst):
  727. // We need to handle 4via6 packets leaving the host if the via
  728. // route is for this host; otherwise the packet will be dropped
  729. // because nothing will translate it.
  730. var shouldHandle bool
  731. if p.IPVersion == 6 && !ns.isLocalIP(dst) {
  732. shouldHandle = ns.lb != nil && ns.lb.ShouldHandleViaIP(dst)
  733. }
  734. if !shouldHandle {
  735. // Unhandled means that we let the regular processing
  736. // occur without doing anything ourselves.
  737. return filter.Accept, gro
  738. }
  739. if debugNetstack() {
  740. ns.logf("netstack: handling local 4via6 packet: version=%d proto=%v dst=%v src=%v",
  741. p.IPVersion, p.IPProto, p.Dst, p.Src)
  742. }
  743. // If this is a ping message, handle it and don't pass to
  744. // netstack.
  745. pingIP, handlePing := ns.shouldHandlePing(p)
  746. if handlePing {
  747. ns.logf("netstack: handling local 4via6 ping: dst=%v pingIP=%v", dst, pingIP)
  748. var pong []byte // the reply to the ping, if our relayed ping works
  749. if dst.Is4() {
  750. h := p.ICMP4Header()
  751. h.ToResponse()
  752. pong = packet.Generate(&h, p.Payload())
  753. } else if dst.Is6() {
  754. h := p.ICMP6Header()
  755. h.ToResponse()
  756. pong = packet.Generate(&h, p.Payload())
  757. }
  758. go ns.userPing(pingIP, pong, userPingDirectionInbound)
  759. return filter.DropSilently, gro
  760. }
  761. // Fall through to writing inbound so netstack handles the
  762. // 4via6 via connection.
  763. default:
  764. // Not traffic to the service IP or a 4via6 IP, so we don't
  765. // care about the packet; resume processing.
  766. return filter.Accept, gro
  767. }
  768. if debugPackets {
  769. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  770. }
  771. gro = ns.linkEP.gro(p, gro)
  772. return filter.DropSilently, gro
  773. }
  774. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netip.AddrPort) (*gonet.TCPConn, error) {
  775. remoteAddress := tcpip.FullAddress{
  776. NIC: nicID,
  777. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  778. Port: ipp.Port(),
  779. }
  780. var ipType tcpip.NetworkProtocolNumber
  781. if ipp.Addr().Is4() {
  782. ipType = ipv4.ProtocolNumber
  783. } else {
  784. ipType = ipv6.ProtocolNumber
  785. }
  786. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  787. }
  788. // DialContextTCPWithBind creates a new gonet.TCPConn connected to the specified
  789. // remoteAddress with its local address bound to localAddr on an available port.
  790. func (ns *Impl) DialContextTCPWithBind(ctx context.Context, localAddr netip.Addr, remoteAddr netip.AddrPort) (*gonet.TCPConn, error) {
  791. remoteAddress := tcpip.FullAddress{
  792. NIC: nicID,
  793. Addr: tcpip.AddrFromSlice(remoteAddr.Addr().AsSlice()),
  794. Port: remoteAddr.Port(),
  795. }
  796. localAddress := tcpip.FullAddress{
  797. NIC: nicID,
  798. Addr: tcpip.AddrFromSlice(localAddr.AsSlice()),
  799. }
  800. var ipType tcpip.NetworkProtocolNumber
  801. if remoteAddr.Addr().Is4() {
  802. ipType = ipv4.ProtocolNumber
  803. } else {
  804. ipType = ipv6.ProtocolNumber
  805. }
  806. return gonet.DialTCPWithBind(ctx, ns.ipstack, localAddress, remoteAddress, ipType)
  807. }
  808. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netip.AddrPort) (*gonet.UDPConn, error) {
  809. remoteAddress := &tcpip.FullAddress{
  810. NIC: nicID,
  811. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  812. Port: ipp.Port(),
  813. }
  814. var ipType tcpip.NetworkProtocolNumber
  815. if ipp.Addr().Is4() {
  816. ipType = ipv4.ProtocolNumber
  817. } else {
  818. ipType = ipv6.ProtocolNumber
  819. }
  820. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  821. }
  822. // DialContextUDPWithBind creates a new gonet.UDPConn. Connected to remoteAddr.
  823. // With its local address bound to localAddr on an available port.
  824. func (ns *Impl) DialContextUDPWithBind(ctx context.Context, localAddr netip.Addr, remoteAddr netip.AddrPort) (*gonet.UDPConn, error) {
  825. remoteAddress := &tcpip.FullAddress{
  826. NIC: nicID,
  827. Addr: tcpip.AddrFromSlice(remoteAddr.Addr().AsSlice()),
  828. Port: remoteAddr.Port(),
  829. }
  830. localAddress := &tcpip.FullAddress{
  831. NIC: nicID,
  832. Addr: tcpip.AddrFromSlice(localAddr.AsSlice()),
  833. }
  834. var ipType tcpip.NetworkProtocolNumber
  835. if remoteAddr.Addr().Is4() {
  836. ipType = ipv4.ProtocolNumber
  837. } else {
  838. ipType = ipv6.ProtocolNumber
  839. }
  840. return gonet.DialUDP(ns.ipstack, localAddress, remoteAddress, ipType)
  841. }
  842. // getInjectInboundBuffsSizes returns packet memory and a sizes slice for usage
  843. // when calling tstun.Wrapper.InjectInboundPacketBuffer(). These are sized with
  844. // consideration for MTU and GSO support on ns.linkEP. They should be recycled
  845. // across subsequent inbound packet injection calls.
  846. func (ns *Impl) getInjectInboundBuffsSizes() (buffs [][]byte, sizes []int) {
  847. batchSize := 1
  848. gsoEnabled := ns.linkEP.SupportedGSO() == stack.HostGSOSupported
  849. if gsoEnabled {
  850. batchSize = conn.IdealBatchSize
  851. }
  852. buffs = make([][]byte, batchSize)
  853. sizes = make([]int, batchSize)
  854. for i := 0; i < batchSize; i++ {
  855. if i == 0 && gsoEnabled {
  856. buffs[i] = make([]byte, tstun.PacketStartOffset+ns.linkEP.GSOMaxSize())
  857. } else {
  858. buffs[i] = make([]byte, tstun.PacketStartOffset+tstun.DefaultTUNMTU())
  859. }
  860. }
  861. return buffs, sizes
  862. }
  863. // The inject goroutine reads in packets that netstack generated, and delivers
  864. // them to the correct path.
  865. func (ns *Impl) inject() {
  866. inboundBuffs, inboundBuffsSizes := ns.getInjectInboundBuffsSizes()
  867. for {
  868. pkt := ns.linkEP.ReadContext(ns.ctx)
  869. if pkt == nil {
  870. if ns.ctx.Err() != nil {
  871. // Return without logging.
  872. return
  873. }
  874. ns.logf("[v2] ReadContext-for-write = ok=false")
  875. continue
  876. }
  877. if debugPackets {
  878. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()).AsSlice())
  879. }
  880. // In the normal case, netstack synthesizes the bytes for
  881. // traffic which should transit back into WG and go to peers.
  882. // However, some uses of netstack (presently, magic DNS)
  883. // send traffic destined for the local device, hence must
  884. // be injected 'inbound'.
  885. sendToHost := ns.shouldSendToHost(pkt)
  886. // pkt has a non-zero refcount, so injection methods takes
  887. // ownership of one count and will decrement on completion.
  888. if sendToHost {
  889. if err := ns.tundev.InjectInboundPacketBuffer(pkt, inboundBuffs, inboundBuffsSizes); err != nil {
  890. ns.logf("netstack inject inbound: %v", err)
  891. return
  892. }
  893. } else {
  894. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  895. ns.logf("netstack inject outbound: %v", err)
  896. return
  897. }
  898. }
  899. }
  900. }
  901. // shouldSendToHost determines if the provided packet should be sent to the
  902. // host (i.e the current machine running Tailscale), in which case it will
  903. // return true. It will return false if the packet should be sent outbound, for
  904. // transit via WireGuard to another Tailscale node.
  905. func (ns *Impl) shouldSendToHost(pkt *stack.PacketBuffer) bool {
  906. // Determine if the packet is from a service IP (100.100.100.100 or the
  907. // IPv6 variant), in which case it needs to go back into the machine's
  908. // network (inbound) instead of out.
  909. hdr := pkt.Network()
  910. switch v := hdr.(type) {
  911. case header.IPv4:
  912. srcIP := netip.AddrFrom4(v.SourceAddress().As4())
  913. if serviceIP == srcIP {
  914. return true
  915. }
  916. case header.IPv6:
  917. srcIP := netip.AddrFrom16(v.SourceAddress().As16())
  918. if srcIP == serviceIPv6 {
  919. return true
  920. }
  921. if viaRange.Contains(srcIP) {
  922. // Only send to the host if this 4via6 route is
  923. // something this node handles.
  924. if ns.lb != nil && ns.lb.ShouldHandleViaIP(srcIP) {
  925. dstIP := netip.AddrFrom16(v.DestinationAddress().As16())
  926. // Also, only forward to the host if the packet
  927. // is destined for a local IP; otherwise, we'd
  928. // send traffic that's intended for another
  929. // peer from the local 4via6 address to the
  930. // host instead of outbound to WireGuard. See:
  931. // https://github.com/tailscale/tailscale/issues/12448
  932. if ns.isLocalIP(dstIP) {
  933. return true
  934. }
  935. if debugNetstack() {
  936. ns.logf("netstack: sending 4via6 packet to host: src=%v dst=%v", srcIP, dstIP)
  937. }
  938. }
  939. }
  940. default:
  941. // unknown; don't forward to host
  942. if debugNetstack() {
  943. ns.logf("netstack: unexpected packet in shouldSendToHost: %T", v)
  944. }
  945. }
  946. return false
  947. }
  948. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  949. // node directly (but not a subnet-routed IP).
  950. func (ns *Impl) isLocalIP(ip netip.Addr) bool {
  951. return ns.atomicIsLocalIPFunc.Load()(ip)
  952. }
  953. // isVIPServiceIP reports whether ip is an IP address that's
  954. // assigned to a VIP service.
  955. func (ns *Impl) isVIPServiceIP(ip netip.Addr) bool {
  956. if !buildfeatures.HasServe {
  957. return false
  958. }
  959. return ns.atomicIsVIPServiceIPFunc.Load()(ip)
  960. }
  961. func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *atomic.Uint32 {
  962. if ip.Is4() {
  963. return &ns.peerapiPort4Atomic
  964. } else {
  965. return &ns.peerapiPort6Atomic
  966. }
  967. }
  968. var viaRange = tsaddr.TailscaleViaRange()
  969. // shouldProcessInbound reports whether an inbound packet (a packet from a
  970. // WireGuard peer) should be handled by netstack.
  971. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  972. // Handle incoming peerapi connections in netstack.
  973. dstIP := p.Dst.Addr()
  974. isLocal := ns.isLocalIP(dstIP)
  975. isService := ns.isVIPServiceIP(dstIP)
  976. // Handle TCP connection to the Tailscale IP(s) in some cases:
  977. if ns.lb != nil && p.IPProto == ipproto.TCP && isLocal {
  978. var peerAPIPort uint16
  979. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn {
  980. if port, ok := ns.lb.GetPeerAPIPort(dstIP); ok {
  981. peerAPIPort = port
  982. ns.peerAPIPortAtomic(dstIP).Store(uint32(port))
  983. }
  984. } else {
  985. peerAPIPort = uint16(ns.peerAPIPortAtomic(dstIP).Load())
  986. }
  987. dport := p.Dst.Port()
  988. if dport == peerAPIPort {
  989. return true
  990. }
  991. // Also handle SSH connections, webserver, etc, if enabled:
  992. if ns.lb.ShouldInterceptTCPPort(dport) {
  993. return true
  994. }
  995. }
  996. if buildfeatures.HasServe && isService {
  997. if p.IsEchoRequest() {
  998. return true
  999. }
  1000. if ns.lb != nil && p.IPProto == ipproto.TCP {
  1001. // An assumption holds for this to work: when tun mode is on for a service,
  1002. // its tcp and web are not set. This is enforced in b.setServeConfigLocked.
  1003. if ns.lb.ShouldInterceptVIPServiceTCPPort(p.Dst) {
  1004. return true
  1005. }
  1006. }
  1007. return false
  1008. }
  1009. if p.IPVersion == 6 && !isLocal && viaRange.Contains(dstIP) {
  1010. return ns.lb != nil && ns.lb.ShouldHandleViaIP(dstIP)
  1011. }
  1012. if ns.ProcessLocalIPs && isLocal {
  1013. return true
  1014. }
  1015. if ns.ProcessSubnets && !isLocal {
  1016. return true
  1017. }
  1018. return false
  1019. }
  1020. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  1021. type userPingDirection int
  1022. const (
  1023. // userPingDirectionOutbound is used when the pong packet is to be sent
  1024. // "outbound"–i.e. from this node to a peer via WireGuard.
  1025. userPingDirectionOutbound userPingDirection = iota
  1026. // userPingDirectionInbound is used when the pong packet is to be sent
  1027. // "inbound"–i.e. from Tailscale to another process on this host.
  1028. userPingDirectionInbound
  1029. )
  1030. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  1031. // into the tundev.
  1032. //
  1033. // It's used in userspace/netstack mode when we don't have kernel
  1034. // support or raw socket access. As such, this does the dumbest thing
  1035. // that can work: runs the ping command. It's not super efficient, so
  1036. // it bounds the number of pings going on at once. The idea is that
  1037. // people only use ping occasionally to see if their internet's working
  1038. // so this doesn't need to be great.
  1039. // On Apple platforms, this function doesn't run the ping command. Instead,
  1040. // it sends a non-privileged ping.
  1041. //
  1042. // The 'direction' parameter is used to determine where the response "pong"
  1043. // packet should be written, if the ping succeeds. See the documentation on the
  1044. // constants for more details.
  1045. //
  1046. // TODO(bradfitz): when we're running on Windows as the system user, use
  1047. // raw socket APIs instead of ping child processes.
  1048. func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte, direction userPingDirection) {
  1049. if !userPingSem.TryAcquire() {
  1050. return
  1051. }
  1052. defer userPingSem.Release()
  1053. t0 := time.Now()
  1054. err := ns.sendOutboundUserPing(dstIP, 3*time.Second)
  1055. d := time.Since(t0)
  1056. if err != nil {
  1057. if d < time.Second/2 {
  1058. // If it failed quicker than the 3 second
  1059. // timeout we gave above (500 ms is a
  1060. // reasonable threshold), then assume the ping
  1061. // failed for problems finding/running
  1062. // ping. We don't want to log if the host is
  1063. // just down.
  1064. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  1065. }
  1066. return
  1067. }
  1068. if debugNetstack() {
  1069. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  1070. }
  1071. if direction == userPingDirectionOutbound {
  1072. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  1073. ns.logf("InjectOutbound ping response: %v", err)
  1074. }
  1075. } else if direction == userPingDirectionInbound {
  1076. if err := ns.tundev.InjectInboundCopy(pingResPkt); err != nil {
  1077. ns.logf("InjectInboundCopy ping response: %v", err)
  1078. }
  1079. }
  1080. }
  1081. // injectInbound is installed as a packet hook on the 'inbound' (from a
  1082. // WireGuard peer) path. Returning filter.Accept releases the packet to
  1083. // continue normally (typically being delivered to the host networking stack),
  1084. // whereas returning filter.DropSilently is done when netstack intercepts the
  1085. // packet and no further processing towards to host should be done.
  1086. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper, gro *gro.GRO) (filter.Response, *gro.GRO) {
  1087. if ns.ctx.Err() != nil {
  1088. return filter.DropSilently, gro
  1089. }
  1090. if !ns.shouldProcessInbound(p, t) {
  1091. // Let the host network stack (if any) deal with it.
  1092. return filter.Accept, gro
  1093. }
  1094. destIP := p.Dst.Addr()
  1095. // If this is an echo request and we're a subnet router, handle pings
  1096. // ourselves instead of forwarding the packet on.
  1097. pingIP, handlePing := ns.shouldHandlePing(p)
  1098. if handlePing {
  1099. var pong []byte // the reply to the ping, if our relayed ping works
  1100. if destIP.Is4() {
  1101. h := p.ICMP4Header()
  1102. h.ToResponse()
  1103. pong = packet.Generate(&h, p.Payload())
  1104. } else if destIP.Is6() {
  1105. h := p.ICMP6Header()
  1106. h.ToResponse()
  1107. pong = packet.Generate(&h, p.Payload())
  1108. }
  1109. go ns.userPing(pingIP, pong, userPingDirectionOutbound)
  1110. return filter.DropSilently, gro
  1111. }
  1112. if debugPackets {
  1113. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  1114. }
  1115. gro = ns.linkEP.gro(p, gro)
  1116. // We've now delivered this to netstack, so we're done.
  1117. // Instead of returning a filter.Accept here (which would also
  1118. // potentially deliver it to the host OS), and instead of
  1119. // filter.Drop (which would log about rejected traffic),
  1120. // instead return filter.DropSilently which just quietly stops
  1121. // processing it in the tstun TUN wrapper.
  1122. return filter.DropSilently, gro
  1123. }
  1124. // shouldHandlePing returns whether or not netstack should handle an incoming
  1125. // ICMP echo request packet, and the IP address that should be pinged from this
  1126. // process. The IP address can be different from the destination in the packet
  1127. // if the destination is a 4via6 address.
  1128. func (ns *Impl) shouldHandlePing(p *packet.Parsed) (_ netip.Addr, ok bool) {
  1129. if !p.IsEchoRequest() {
  1130. return netip.Addr{}, false
  1131. }
  1132. destIP := p.Dst.Addr()
  1133. // We need to handle pings for all 4via6 addresses, even if this
  1134. // netstack instance normally isn't responsible for processing subnets.
  1135. //
  1136. // For example, on Linux, subnet router traffic could be handled via
  1137. // tun+iptables rules for most packets, but we still need to handle
  1138. // ICMP echo requests over 4via6 since the host networking stack
  1139. // doesn't know what to do with a 4via6 address.
  1140. //
  1141. // shouldProcessInbound returns 'true' to say that we should process
  1142. // all IPv6 packets with a destination address in the 'via' range, so
  1143. // check before we check the "ProcessSubnets" boolean below.
  1144. if viaRange.Contains(destIP) {
  1145. // The input echo request was to a 4via6 address, which we cannot
  1146. // simply ping as-is from this process. Translate the destination to an
  1147. // IPv4 address, so that our relayed ping (in userPing) is pinging the
  1148. // underlying destination IP.
  1149. //
  1150. // ICMPv4 and ICMPv6 are different protocols with different on-the-wire
  1151. // representations, so normally you can't send an ICMPv6 message over
  1152. // IPv4 and expect to get a useful result. However, in this specific
  1153. // case things are safe because the 'userPing' function doesn't make
  1154. // use of the input packet.
  1155. return tsaddr.UnmapVia(destIP), true
  1156. }
  1157. // If we get here, we don't do anything unless this netstack instance
  1158. // is responsible for processing subnet traffic.
  1159. if !ns.ProcessSubnets {
  1160. return netip.Addr{}, false
  1161. }
  1162. // For non-4via6 addresses, we don't handle pings if they're destined
  1163. // for a Tailscale IP.
  1164. if tsaddr.IsTailscaleIP(destIP) {
  1165. return netip.Addr{}, false
  1166. }
  1167. // This netstack instance is processing subnet traffic, so handle the
  1168. // ping ourselves.
  1169. return destIP, true
  1170. }
  1171. func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
  1172. switch s.Len() {
  1173. case 4:
  1174. return netip.AddrFrom4(s.As4())
  1175. case 16:
  1176. return netip.AddrFrom16(s.As16()).Unmap()
  1177. }
  1178. return netip.Addr{}
  1179. }
  1180. var (
  1181. ipv4Loopback = netip.MustParseAddr("127.0.0.1")
  1182. ipv6Loopback = netip.MustParseAddr("::1")
  1183. )
  1184. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  1185. reqDetails := r.ID()
  1186. if debugNetstack() {
  1187. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  1188. }
  1189. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  1190. if !clientRemoteIP.IsValid() {
  1191. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  1192. r.Complete(true) // sends a RST
  1193. return
  1194. }
  1195. // After we've returned from this function or have otherwise reached a
  1196. // non-pending state, decrement the per-client in-flight count and
  1197. // remove this endpoint from our packet tracking map so future TCP
  1198. // connections aren't dropped.
  1199. inFlightCompleted := false
  1200. tei := r.ID()
  1201. defer func() {
  1202. if !inFlightCompleted {
  1203. ns.decrementInFlightTCPForward(tei, clientRemoteIP)
  1204. }
  1205. }()
  1206. clientRemotePort := reqDetails.RemotePort
  1207. clientRemoteAddrPort := netip.AddrPortFrom(clientRemoteIP, clientRemotePort)
  1208. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  1209. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  1210. dstAddrPort := netip.AddrPortFrom(dialIP, reqDetails.LocalPort)
  1211. if viaRange.Contains(dialIP) {
  1212. isTailscaleIP = false
  1213. dialIP = tsaddr.UnmapVia(dialIP)
  1214. }
  1215. defer func() {
  1216. if !isTailscaleIP {
  1217. // if this is a subnet IP, we added this in before the TCP handshake
  1218. // so netstack is happy TCP-handshaking as a subnet IP
  1219. ns.removeSubnetAddress(dialIP)
  1220. }
  1221. }()
  1222. var wq waiter.Queue
  1223. // We can't actually create the endpoint or complete the inbound
  1224. // request until we're sure that the connection can be handled by this
  1225. // endpoint. This function sets up the TCP connection and should be
  1226. // called immediately before a connection is handled.
  1227. getConnOrReset := func(opts ...tcpip.SettableSocketOption) *gonet.TCPConn {
  1228. ep, err := r.CreateEndpoint(&wq)
  1229. if err != nil {
  1230. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  1231. r.Complete(true) // sends a RST
  1232. return nil
  1233. }
  1234. r.Complete(false)
  1235. for _, opt := range opts {
  1236. ep.SetSockOpt(opt)
  1237. }
  1238. // SetKeepAlive so that idle connections to peers that have forgotten about
  1239. // the connection or gone completely offline eventually time out.
  1240. // Applications might be setting this on a forwarded connection, but from
  1241. // userspace we can not see those, so the best we can do is to always
  1242. // perform them with conservative timing.
  1243. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  1244. // defaults, and results in a little over two hours before the socket would
  1245. // be closed due to keepalive. A shorter default might be better, or seeking
  1246. // a default from the host IP stack. This also might be a useful
  1247. // user-tunable, as in userspace mode this can have broad implications such
  1248. // as lingering connections to fork style daemons. On the other side of the
  1249. // fence, the long duration timers are low impact values for battery powered
  1250. // peers.
  1251. ep.SocketOptions().SetKeepAlive(true)
  1252. // This function is called when we're ready to use the
  1253. // underlying connection, and thus it's no longer in a
  1254. // "in-flight" state; decrement our per-client limit right now,
  1255. // and tell the defer in acceptTCP that it doesn't need to do
  1256. // so upon return.
  1257. ns.decrementInFlightTCPForward(tei, clientRemoteIP)
  1258. inFlightCompleted = true
  1259. // The ForwarderRequest.CreateEndpoint above asynchronously
  1260. // starts the TCP handshake. Note that the gonet.TCPConn
  1261. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  1262. // until the handshake actually completes. But we have the
  1263. // remote address in reqDetails instead, so we don't use
  1264. // gonet.TCPConn.RemoteAddr. The byte copies in both
  1265. // directions to/from the gonet.TCPConn in forwardTCP will
  1266. // block until the TCP handshake is complete.
  1267. return gonet.NewTCPConn(&wq, ep)
  1268. }
  1269. // Local Services (DNS and WebDAV)
  1270. hittingServiceIP := dialIP == serviceIP || dialIP == serviceIPv6
  1271. hittingDNS := hittingServiceIP && reqDetails.LocalPort == 53
  1272. if hittingDNS {
  1273. c := getConnOrReset()
  1274. if c == nil {
  1275. return
  1276. }
  1277. addrPort := netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort)
  1278. go ns.dns.HandleTCPConn(c, addrPort)
  1279. return
  1280. }
  1281. if ns.lb != nil {
  1282. handler, opts := ns.lb.TCPHandlerForDst(clientRemoteAddrPort, dstAddrPort)
  1283. if handler != nil {
  1284. c := getConnOrReset(opts...) // will send a RST if it fails
  1285. if c == nil {
  1286. return
  1287. }
  1288. handler(c)
  1289. return
  1290. }
  1291. }
  1292. if ns.GetTCPHandlerForFlow != nil {
  1293. handler, ok := ns.GetTCPHandlerForFlow(clientRemoteAddrPort, dstAddrPort)
  1294. if ok {
  1295. if handler == nil {
  1296. r.Complete(true)
  1297. return
  1298. }
  1299. c := getConnOrReset() // will send a RST if it fails
  1300. if c == nil {
  1301. return
  1302. }
  1303. handler(c)
  1304. return
  1305. }
  1306. }
  1307. switch {
  1308. case hittingServiceIP && ns.isLoopbackPort(reqDetails.LocalPort):
  1309. if dialIP == serviceIPv6 {
  1310. dialIP = ipv6Loopback
  1311. } else {
  1312. dialIP = ipv4Loopback
  1313. }
  1314. case isTailscaleIP:
  1315. dialIP = ipv4Loopback
  1316. }
  1317. dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
  1318. if !ns.forwardTCP(getConnOrReset, clientRemoteIP, &wq, dialAddr) {
  1319. r.Complete(true) // sends a RST
  1320. }
  1321. }
  1322. // tcpCloser is an interface to abstract around various TCPConn types that
  1323. // allow closing of the read and write streams independently of each other.
  1324. type tcpCloser interface {
  1325. CloseRead() error
  1326. CloseWrite() error
  1327. }
  1328. func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) (handled bool) {
  1329. dialAddrStr := dialAddr.String()
  1330. if debugNetstack() {
  1331. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  1332. }
  1333. ctx, cancel := context.WithCancel(context.Background())
  1334. defer cancel()
  1335. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  1336. wq.EventRegister(&waitEntry)
  1337. defer wq.EventUnregister(&waitEntry)
  1338. done := make(chan bool)
  1339. // netstack doesn't close the notification channel automatically if there was no
  1340. // hup signal, so we close done after we're done to not leak the goroutine below.
  1341. defer close(done)
  1342. go func() {
  1343. select {
  1344. case <-notifyCh:
  1345. if debugNetstack() {
  1346. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  1347. }
  1348. case <-done:
  1349. }
  1350. cancel()
  1351. }()
  1352. // Attempt to dial the outbound connection before we accept the inbound one.
  1353. var dialFunc netx.DialFunc
  1354. if ns.forwardDialFunc != nil {
  1355. dialFunc = ns.forwardDialFunc
  1356. } else {
  1357. var stdDialer net.Dialer
  1358. dialFunc = stdDialer.DialContext
  1359. }
  1360. // TODO: this is racy, dialing before we register our local address. See
  1361. // https://github.com/tailscale/tailscale/issues/1616.
  1362. backend, err := dialFunc(ctx, "tcp", dialAddrStr)
  1363. if err != nil {
  1364. ns.logf("netstack: could not connect to local backend server at %s: %v", dialAddr.String(), err)
  1365. return
  1366. }
  1367. defer backend.Close()
  1368. backendLocalAddr := backend.LocalAddr().(*net.TCPAddr)
  1369. backendLocalIPPort := netaddr.Unmap(backendLocalAddr.AddrPort())
  1370. if err := ns.pm.RegisterIPPortIdentity("tcp", backendLocalIPPort, clientRemoteIP); err != nil {
  1371. ns.logf("netstack: could not register TCP mapping %s: %v", backendLocalIPPort, err)
  1372. return
  1373. }
  1374. defer ns.pm.UnregisterIPPortIdentity("tcp", backendLocalIPPort)
  1375. // If we get here, either the getClient call below will succeed and
  1376. // return something we can Close, or it will fail and will properly
  1377. // respond to the client with a RST. Either way, the caller no longer
  1378. // needs to clean up the client connection.
  1379. handled = true
  1380. // We dialed the connection; we can complete the client's TCP handshake.
  1381. client := getClient()
  1382. if client == nil {
  1383. return
  1384. }
  1385. defer client.Close()
  1386. // As of 2025-07-03, backend is always either a net.TCPConn
  1387. // from stdDialer.DialContext (which has the requisite functions),
  1388. // or nil from hangDialer in tests (in which case we would have
  1389. // errored out by now), so this conversion should always succeed.
  1390. backendTCPCloser, backendIsTCPCloser := backend.(tcpCloser)
  1391. connClosed := make(chan error, 2)
  1392. go func() {
  1393. _, err := io.Copy(backend, client)
  1394. if err != nil {
  1395. err = fmt.Errorf("client -> backend: %w", err)
  1396. }
  1397. connClosed <- err
  1398. err = nil
  1399. if backendIsTCPCloser {
  1400. err = backendTCPCloser.CloseWrite()
  1401. }
  1402. err = errors.Join(err, client.CloseRead())
  1403. if err != nil {
  1404. ns.logf("client -> backend close connection: %v", err)
  1405. }
  1406. }()
  1407. go func() {
  1408. _, err := io.Copy(client, backend)
  1409. if err != nil {
  1410. err = fmt.Errorf("backend -> client: %w", err)
  1411. }
  1412. connClosed <- err
  1413. err = nil
  1414. if backendIsTCPCloser {
  1415. err = backendTCPCloser.CloseRead()
  1416. }
  1417. err = errors.Join(err, client.CloseWrite())
  1418. if err != nil {
  1419. ns.logf("backend -> client close connection: %v", err)
  1420. }
  1421. }()
  1422. // Wait for both ends of the connection to close.
  1423. for range 2 {
  1424. err = <-connClosed
  1425. if err != nil {
  1426. ns.logf("proxy connection closed with error: %v", err)
  1427. }
  1428. }
  1429. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  1430. return
  1431. }
  1432. // ListenPacket listens for incoming packets for the given network and address.
  1433. // Address must be of the form "ip:port" or "[ip]:port".
  1434. //
  1435. // As of 2024-05-18, only udp4 and udp6 are supported.
  1436. func (ns *Impl) ListenPacket(network, address string) (net.PacketConn, error) {
  1437. ap, err := netip.ParseAddrPort(address)
  1438. if err != nil {
  1439. return nil, fmt.Errorf("netstack: ParseAddrPort(%q): %v", address, err)
  1440. }
  1441. var networkProto tcpip.NetworkProtocolNumber
  1442. switch network {
  1443. case "udp":
  1444. return nil, fmt.Errorf("netstack: udp not supported; use udp4 or udp6")
  1445. case "udp4":
  1446. networkProto = ipv4.ProtocolNumber
  1447. if !ap.Addr().Is4() {
  1448. return nil, fmt.Errorf("netstack: udp4 requires an IPv4 address")
  1449. }
  1450. case "udp6":
  1451. networkProto = ipv6.ProtocolNumber
  1452. if !ap.Addr().Is6() {
  1453. return nil, fmt.Errorf("netstack: udp6 requires an IPv6 address")
  1454. }
  1455. default:
  1456. return nil, fmt.Errorf("netstack: unsupported network %q", network)
  1457. }
  1458. var wq waiter.Queue
  1459. ep, nserr := ns.ipstack.NewEndpoint(udp.ProtocolNumber, networkProto, &wq)
  1460. if nserr != nil {
  1461. return nil, fmt.Errorf("netstack: NewEndpoint: %v", nserr)
  1462. }
  1463. localAddress := tcpip.FullAddress{
  1464. NIC: nicID,
  1465. Addr: tcpip.AddrFromSlice(ap.Addr().AsSlice()),
  1466. Port: ap.Port(),
  1467. }
  1468. if err := ep.Bind(localAddress); err != nil {
  1469. ep.Close()
  1470. return nil, fmt.Errorf("netstack: Bind(%v): %v", localAddress, err)
  1471. }
  1472. return gonet.NewUDPConn(&wq, ep), nil
  1473. }
  1474. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  1475. sess := r.ID()
  1476. if debugNetstack() {
  1477. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  1478. }
  1479. var wq waiter.Queue
  1480. ep, err := r.CreateEndpoint(&wq)
  1481. if err != nil {
  1482. ns.logf("acceptUDP: could not create endpoint: %v", err)
  1483. return
  1484. }
  1485. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  1486. if !ok {
  1487. ep.Close()
  1488. return
  1489. }
  1490. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  1491. if !ok {
  1492. ep.Close()
  1493. return
  1494. }
  1495. // Handle magicDNS and loopback traffic (via UDP) here.
  1496. if dst := dstAddr.Addr(); dst == serviceIP || dst == serviceIPv6 {
  1497. switch {
  1498. case dstAddr.Port() == 53:
  1499. c := gonet.NewUDPConn(&wq, ep)
  1500. go ns.handleMagicDNSUDP(srcAddr, c)
  1501. return
  1502. case ns.isLoopbackPort(dstAddr.Port()):
  1503. if dst == serviceIPv6 {
  1504. dstAddr = netip.AddrPortFrom(ipv6Loopback, dstAddr.Port())
  1505. } else {
  1506. dstAddr = netip.AddrPortFrom(ipv4Loopback, dstAddr.Port())
  1507. }
  1508. default:
  1509. ep.Close()
  1510. return // Only MagicDNS and loopback traffic runs on the service IPs for now.
  1511. }
  1512. }
  1513. if get := ns.GetUDPHandlerForFlow; get != nil {
  1514. h, intercept := get(srcAddr, dstAddr)
  1515. if intercept {
  1516. if h == nil {
  1517. ep.Close()
  1518. return
  1519. }
  1520. go h(gonet.NewUDPConn(&wq, ep))
  1521. return
  1522. }
  1523. }
  1524. c := gonet.NewUDPConn(&wq, ep)
  1525. go ns.forwardUDP(c, srcAddr, dstAddr)
  1526. }
  1527. // Buffer pool for forwarding UDP packets. Implementations are advised not to
  1528. // exceed 512 bytes per DNS request due to fragmenting but in reality can and do
  1529. // send much larger packets, so use the maximum possible UDP packet size.
  1530. var udpBufPool = &sync.Pool{
  1531. New: func() any {
  1532. b := make([]byte, maxUDPPacketSize)
  1533. return &b
  1534. },
  1535. }
  1536. func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
  1537. // Packets are being generated by the local host, so there should be
  1538. // very, very little latency. 150ms was chosen as something of an upper
  1539. // bound on resource usage, while hopefully still being long enough for
  1540. // a heavily loaded system.
  1541. const readDeadline = 150 * time.Millisecond
  1542. defer c.Close()
  1543. bufp := udpBufPool.Get().(*[]byte)
  1544. defer udpBufPool.Put(bufp)
  1545. q := *bufp
  1546. // libresolv from glibc is quite adamant that transmitting multiple DNS
  1547. // requests down the same UDP socket is valid. To support this, we read
  1548. // in a loop (with a tight deadline so we don't chew too many resources).
  1549. //
  1550. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  1551. for {
  1552. c.SetReadDeadline(time.Now().Add(readDeadline))
  1553. n, _, err := c.ReadFrom(q)
  1554. if err != nil {
  1555. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  1556. ns.logf("dns udp read: %v", err) // log non-timeout errors
  1557. }
  1558. return
  1559. }
  1560. resp, err := ns.dns.Query(context.Background(), q[:n], "udp", srcAddr)
  1561. if err != nil {
  1562. ns.logf("dns udp query: %v", err)
  1563. return
  1564. }
  1565. c.Write(resp)
  1566. }
  1567. }
  1568. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  1569. //
  1570. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  1571. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  1572. // proxy to it directly.
  1573. func (ns *Impl) forwardUDP(client *gonet.UDPConn, clientAddr, dstAddr netip.AddrPort) {
  1574. port, srcPort := dstAddr.Port(), clientAddr.Port()
  1575. if debugNetstack() {
  1576. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  1577. }
  1578. var backendListenAddr *net.UDPAddr
  1579. var backendRemoteAddr *net.UDPAddr
  1580. isLocal := ns.isLocalIP(dstAddr.Addr())
  1581. isLoopback := dstAddr.Addr() == ipv4Loopback || dstAddr.Addr() == ipv6Loopback
  1582. if isLocal {
  1583. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  1584. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  1585. } else if isLoopback {
  1586. ip := net.IP(ipv4Loopback.AsSlice())
  1587. if dstAddr.Addr() == ipv6Loopback {
  1588. ip = ipv6Loopback.AsSlice()
  1589. }
  1590. backendRemoteAddr = &net.UDPAddr{IP: ip, Port: int(port)}
  1591. backendListenAddr = &net.UDPAddr{IP: ip, Port: int(srcPort)}
  1592. } else {
  1593. if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
  1594. dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  1595. }
  1596. backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
  1597. if dstAddr.Addr().Is4() {
  1598. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  1599. } else {
  1600. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  1601. }
  1602. }
  1603. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  1604. if err != nil {
  1605. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  1606. backendListenAddr.Port = 0
  1607. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  1608. if err != nil {
  1609. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  1610. return
  1611. }
  1612. }
  1613. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  1614. backendLocalIPPort := netip.AddrPortFrom(backendListenAddr.AddrPort().Addr().Unmap().WithZone(backendLocalAddr.Zone), backendLocalAddr.AddrPort().Port())
  1615. if !backendLocalIPPort.IsValid() {
  1616. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  1617. }
  1618. if isLocal {
  1619. if err := ns.pm.RegisterIPPortIdentity("udp", backendLocalIPPort, clientAddr.Addr()); err != nil {
  1620. ns.logf("netstack: could not register UDP mapping %s: %v", backendLocalIPPort, err)
  1621. return
  1622. }
  1623. }
  1624. ctx, cancel := context.WithCancel(context.Background())
  1625. idleTimeout := 2 * time.Minute
  1626. if port == 53 {
  1627. // Make DNS packet copies time out much sooner.
  1628. //
  1629. // TODO(bradfitz): make DNS queries over UDP forwarding even
  1630. // cheaper by adding an additional idleTimeout post-DNS-reply.
  1631. // For instance, after the DNS response goes back out, then only
  1632. // wait a few seconds (or zero, really)
  1633. idleTimeout = 30 * time.Second
  1634. }
  1635. timer := time.AfterFunc(idleTimeout, func() {
  1636. if isLocal {
  1637. ns.pm.UnregisterIPPortIdentity("udp", backendLocalIPPort)
  1638. }
  1639. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  1640. cancel()
  1641. client.Close()
  1642. backendConn.Close()
  1643. })
  1644. extend := func() {
  1645. timer.Reset(idleTimeout)
  1646. }
  1647. startPacketCopy(ctx, cancel, client, net.UDPAddrFromAddrPort(clientAddr), backendConn, ns.logf, extend)
  1648. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  1649. if isLocal {
  1650. // Wait for the copies to be done before decrementing the
  1651. // subnet address count to potentially remove the route.
  1652. <-ctx.Done()
  1653. ns.removeSubnetAddress(dstAddr.Addr())
  1654. }
  1655. }
  1656. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  1657. if debugNetstack() {
  1658. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  1659. }
  1660. go func() {
  1661. defer cancel() // tear down the other direction's copy
  1662. bufp := udpBufPool.Get().(*[]byte)
  1663. defer udpBufPool.Put(bufp)
  1664. pkt := *bufp
  1665. for {
  1666. select {
  1667. case <-ctx.Done():
  1668. return
  1669. default:
  1670. n, srcAddr, err := src.ReadFrom(pkt)
  1671. if err != nil {
  1672. if ctx.Err() == nil {
  1673. logf("read packet from %s failed: %v", srcAddr, err)
  1674. }
  1675. return
  1676. }
  1677. _, err = dst.WriteTo(pkt[:n], dstAddr)
  1678. if err != nil {
  1679. if ctx.Err() == nil {
  1680. logf("write packet to %s failed: %v", dstAddr, err)
  1681. }
  1682. return
  1683. }
  1684. if debugNetstack() {
  1685. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  1686. }
  1687. extend()
  1688. }
  1689. }
  1690. }()
  1691. }
  1692. func stringifyTEI(tei stack.TransportEndpointID) string {
  1693. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  1694. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  1695. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  1696. }
  1697. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
  1698. if addr, ok := netip.AddrFromSlice(a.AsSlice()); ok {
  1699. return netip.AddrPortFrom(addr, port), true
  1700. }
  1701. return netip.AddrPort{}, false
  1702. }
  1703. func readStatCounter(sc *tcpip.StatCounter) int64 {
  1704. vv := sc.Value()
  1705. if vv > math.MaxInt64 {
  1706. return int64(math.MaxInt64)
  1707. }
  1708. return int64(vv)
  1709. }
  1710. // ExpVar returns an expvar variable suitable for registering with expvar.Publish.
  1711. func (ns *Impl) ExpVar() expvar.Var {
  1712. m := new(metrics.Set)
  1713. // Global metrics
  1714. stats := ns.ipstack.Stats()
  1715. m.Set("counter_dropped_packets", expvar.Func(func() any {
  1716. return readStatCounter(stats.DroppedPackets)
  1717. }))
  1718. // IP statistics
  1719. ipStats := ns.ipstack.Stats().IP
  1720. ipMetrics := []struct {
  1721. name string
  1722. field *tcpip.StatCounter
  1723. }{
  1724. {"packets_received", ipStats.PacketsReceived},
  1725. {"valid_packets_received", ipStats.ValidPacketsReceived},
  1726. {"disabled_packets_received", ipStats.DisabledPacketsReceived},
  1727. {"invalid_destination_addresses_received", ipStats.InvalidDestinationAddressesReceived},
  1728. {"invalid_source_addresses_received", ipStats.InvalidSourceAddressesReceived},
  1729. {"packets_delivered", ipStats.PacketsDelivered},
  1730. {"packets_sent", ipStats.PacketsSent},
  1731. {"outgoing_packet_errors", ipStats.OutgoingPacketErrors},
  1732. {"malformed_packets_received", ipStats.MalformedPacketsReceived},
  1733. {"malformed_fragments_received", ipStats.MalformedFragmentsReceived},
  1734. {"iptables_prerouting_dropped", ipStats.IPTablesPreroutingDropped},
  1735. {"iptables_input_dropped", ipStats.IPTablesInputDropped},
  1736. {"iptables_forward_dropped", ipStats.IPTablesForwardDropped},
  1737. {"iptables_output_dropped", ipStats.IPTablesOutputDropped},
  1738. {"iptables_postrouting_dropped", ipStats.IPTablesPostroutingDropped},
  1739. {"option_timestamp_received", ipStats.OptionTimestampReceived},
  1740. {"option_record_route_received", ipStats.OptionRecordRouteReceived},
  1741. {"option_router_alert_received", ipStats.OptionRouterAlertReceived},
  1742. {"option_unknown_received", ipStats.OptionUnknownReceived},
  1743. }
  1744. for _, metric := range ipMetrics {
  1745. m.Set("counter_ip_"+metric.name, expvar.Func(func() any {
  1746. return readStatCounter(metric.field)
  1747. }))
  1748. }
  1749. // IP forwarding statistics
  1750. fwdStats := ipStats.Forwarding
  1751. fwdMetrics := []struct {
  1752. name string
  1753. field *tcpip.StatCounter
  1754. }{
  1755. {"unrouteable", fwdStats.Unrouteable},
  1756. {"exhausted_ttl", fwdStats.ExhaustedTTL},
  1757. {"initializing_source", fwdStats.InitializingSource},
  1758. {"link_local_source", fwdStats.LinkLocalSource},
  1759. {"link_local_destination", fwdStats.LinkLocalDestination},
  1760. {"packet_too_big", fwdStats.PacketTooBig},
  1761. {"host_unreachable", fwdStats.HostUnreachable},
  1762. {"extension_header_problem", fwdStats.ExtensionHeaderProblem},
  1763. {"unexpected_multicast_input_interface", fwdStats.UnexpectedMulticastInputInterface},
  1764. {"unknown_output_endpoint", fwdStats.UnknownOutputEndpoint},
  1765. {"no_multicast_pending_queue_buffer_space", fwdStats.NoMulticastPendingQueueBufferSpace},
  1766. {"outgoing_device_no_buffer_space", fwdStats.OutgoingDeviceNoBufferSpace},
  1767. {"errors", fwdStats.Errors},
  1768. }
  1769. for _, metric := range fwdMetrics {
  1770. m.Set("counter_ip_forward_"+metric.name, expvar.Func(func() any {
  1771. return readStatCounter(metric.field)
  1772. }))
  1773. }
  1774. // TCP metrics
  1775. tcpStats := ns.ipstack.Stats().TCP
  1776. tcpMetrics := []struct {
  1777. name string
  1778. field *tcpip.StatCounter
  1779. }{
  1780. {"active_connection_openings", tcpStats.ActiveConnectionOpenings},
  1781. {"passive_connection_openings", tcpStats.PassiveConnectionOpenings},
  1782. {"established_resets", tcpStats.EstablishedResets},
  1783. {"established_closed", tcpStats.EstablishedClosed},
  1784. {"established_timeout", tcpStats.EstablishedTimedout},
  1785. {"listen_overflow_syn_drop", tcpStats.ListenOverflowSynDrop},
  1786. {"listen_overflow_ack_drop", tcpStats.ListenOverflowAckDrop},
  1787. {"listen_overflow_syn_cookie_sent", tcpStats.ListenOverflowSynCookieSent},
  1788. {"listen_overflow_syn_cookie_rcvd", tcpStats.ListenOverflowSynCookieRcvd},
  1789. {"listen_overflow_invalid_syn_cookie_rcvd", tcpStats.ListenOverflowInvalidSynCookieRcvd},
  1790. {"failed_connection_attempts", tcpStats.FailedConnectionAttempts},
  1791. {"valid_segments_received", tcpStats.ValidSegmentsReceived},
  1792. {"invalid_segments_received", tcpStats.InvalidSegmentsReceived},
  1793. {"segments_sent", tcpStats.SegmentsSent},
  1794. {"segment_send_errors", tcpStats.SegmentSendErrors},
  1795. {"resets_sent", tcpStats.ResetsSent},
  1796. {"resets_received", tcpStats.ResetsReceived},
  1797. {"retransmits", tcpStats.Retransmits},
  1798. {"fast_recovery", tcpStats.FastRecovery},
  1799. {"sack_recovery", tcpStats.SACKRecovery},
  1800. {"tlp_recovery", tcpStats.TLPRecovery},
  1801. {"slow_start_retransmits", tcpStats.SlowStartRetransmits},
  1802. {"fast_retransmit", tcpStats.FastRetransmit},
  1803. {"timeouts", tcpStats.Timeouts},
  1804. {"checksum_errors", tcpStats.ChecksumErrors},
  1805. {"failed_port_reservations", tcpStats.FailedPortReservations},
  1806. {"segments_acked_with_dsack", tcpStats.SegmentsAckedWithDSACK},
  1807. {"spurious_recovery", tcpStats.SpuriousRecovery},
  1808. {"spurious_rto_recovery", tcpStats.SpuriousRTORecovery},
  1809. {"forward_max_in_flight_drop", tcpStats.ForwardMaxInFlightDrop},
  1810. }
  1811. for _, metric := range tcpMetrics {
  1812. m.Set("counter_tcp_"+metric.name, expvar.Func(func() any {
  1813. return readStatCounter(metric.field)
  1814. }))
  1815. }
  1816. m.Set("gauge_tcp_current_established", expvar.Func(func() any {
  1817. return readStatCounter(tcpStats.CurrentEstablished)
  1818. }))
  1819. m.Set("gauge_tcp_current_connected", expvar.Func(func() any {
  1820. return readStatCounter(tcpStats.CurrentConnected)
  1821. }))
  1822. // UDP metrics
  1823. udpStats := ns.ipstack.Stats().UDP
  1824. udpMetrics := []struct {
  1825. name string
  1826. field *tcpip.StatCounter
  1827. }{
  1828. {"packets_received", udpStats.PacketsReceived},
  1829. {"unknown_port_errors", udpStats.UnknownPortErrors},
  1830. {"receive_buffer_errors", udpStats.ReceiveBufferErrors},
  1831. {"malformed_packets_received", udpStats.MalformedPacketsReceived},
  1832. {"packets_sent", udpStats.PacketsSent},
  1833. {"packet_send_errors", udpStats.PacketSendErrors},
  1834. {"checksum_errors", udpStats.ChecksumErrors},
  1835. }
  1836. for _, metric := range udpMetrics {
  1837. m.Set("counter_udp_"+metric.name, expvar.Func(func() any {
  1838. return readStatCounter(metric.field)
  1839. }))
  1840. }
  1841. // Export gauges that show the current TCP forwarding limits.
  1842. m.Set("gauge_tcp_forward_in_flight_limit", expvar.Func(func() any {
  1843. return maxInFlightConnectionAttempts()
  1844. }))
  1845. m.Set("gauge_tcp_forward_in_flight_per_client_limit", expvar.Func(func() any {
  1846. return maxInFlightConnectionAttemptsPerClient()
  1847. }))
  1848. // This metric tracks the number of in-flight TCP forwarding
  1849. // connections that are "in-flight"–i.e. waiting to complete.
  1850. m.Set("gauge_tcp_forward_in_flight", expvar.Func(func() any {
  1851. ns.mu.Lock()
  1852. defer ns.mu.Unlock()
  1853. var sum int64
  1854. for _, n := range ns.connsInFlightByClient {
  1855. sum += int64(n)
  1856. }
  1857. return sum
  1858. }))
  1859. m.Set("counter_tcp_forward_max_in_flight_per_client_drop", &ns.forwardInFlightPerClientDropped)
  1860. // This metric tracks how many (if any) of the per-client limit on
  1861. // in-flight TCP forwarding requests have been reached.
  1862. m.Set("gauge_tcp_forward_in_flight_per_client_limit_reached", expvar.Func(func() any {
  1863. ns.mu.Lock()
  1864. defer ns.mu.Unlock()
  1865. limit := maxInFlightConnectionAttemptsPerClient()
  1866. var count int64
  1867. for _, n := range ns.connsInFlightByClient {
  1868. if n == limit {
  1869. count++
  1870. }
  1871. }
  1872. return count
  1873. }))
  1874. return m
  1875. }
  1876. // windowsPingOutputIsSuccess reports whether the ping.exe output b contains a
  1877. // success ping response for ip.
  1878. //
  1879. // See https://github.com/tailscale/tailscale/issues/13654
  1880. //
  1881. // TODO(bradfitz,nickkhyl): delete this and use the proper Windows APIs.
  1882. func windowsPingOutputIsSuccess(ip netip.Addr, b []byte) bool {
  1883. // Look for a line that contains " <ip>: " and then three equal signs.
  1884. // As a special case, the 2nd equal sign may be a '<' character
  1885. // for sub-millisecond pings.
  1886. // This heuristic seems to match the ping.exe output in any language.
  1887. sub := fmt.Appendf(nil, " %s: ", ip)
  1888. eqSigns := func(bb []byte) (n int) {
  1889. for _, b := range bb {
  1890. if b == '=' || (b == '<' && n == 1) {
  1891. n++
  1892. }
  1893. }
  1894. return
  1895. }
  1896. for len(b) > 0 {
  1897. var line []byte
  1898. line, b, _ = bytes.Cut(b, []byte("\n"))
  1899. if _, rest, ok := bytes.Cut(line, sub); ok && eqSigns(rest) == 3 {
  1900. return true
  1901. }
  1902. }
  1903. return false
  1904. }