client.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build !js
  4. // Package controlhttp implements the Tailscale 2021 control protocol
  5. // base transport over HTTP.
  6. //
  7. // This tunnels the protocol in control/controlbase over HTTP with a
  8. // variety of compatibility fallbacks for handling picky or deep
  9. // inspecting proxies.
  10. //
  11. // In the happy path, a client makes a single cleartext HTTP request
  12. // to the server, the server responds with 101 Switching Protocols,
  13. // and the control base protocol takes place over plain TCP.
  14. //
  15. // In the compatibility path, the client does the above over HTTPS,
  16. // resulting in double encryption (once for the control transport, and
  17. // once for the outer TLS layer).
  18. package controlhttp
  19. import (
  20. "context"
  21. "crypto/tls"
  22. "encoding/base64"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "math"
  27. "net"
  28. "net/http"
  29. "net/http/httptrace"
  30. "net/netip"
  31. "net/url"
  32. "runtime"
  33. "sort"
  34. "sync/atomic"
  35. "time"
  36. "tailscale.com/control/controlbase"
  37. "tailscale.com/envknob"
  38. "tailscale.com/health"
  39. "tailscale.com/net/dnscache"
  40. "tailscale.com/net/dnsfallback"
  41. "tailscale.com/net/netutil"
  42. "tailscale.com/net/sockstats"
  43. "tailscale.com/net/tlsdial"
  44. "tailscale.com/net/tshttpproxy"
  45. "tailscale.com/syncs"
  46. "tailscale.com/tailcfg"
  47. "tailscale.com/tstime"
  48. "tailscale.com/util/multierr"
  49. )
  50. var stdDialer net.Dialer
  51. // Dial connects to the HTTP server at this Dialer's Host:HTTPPort, requests to
  52. // switch to the Tailscale control protocol, and returns an established control
  53. // protocol connection.
  54. //
  55. // If Dial fails to connect using HTTP, it also tries to tunnel over TLS to the
  56. // Dialer's Host:HTTPSPort as a compatibility fallback.
  57. //
  58. // The provided ctx is only used for the initial connection, until
  59. // Dial returns. It does not affect the connection once established.
  60. func (a *Dialer) Dial(ctx context.Context) (*ClientConn, error) {
  61. if a.Hostname == "" {
  62. return nil, errors.New("required Dialer.Hostname empty")
  63. }
  64. return a.dial(ctx)
  65. }
  66. func (a *Dialer) logf(format string, args ...any) {
  67. if a.Logf != nil {
  68. a.Logf(format, args...)
  69. }
  70. }
  71. func (a *Dialer) getProxyFunc() func(*http.Request) (*url.URL, error) {
  72. if a.proxyFunc != nil {
  73. return a.proxyFunc
  74. }
  75. return tshttpproxy.ProxyFromEnvironment
  76. }
  77. // httpsFallbackDelay is how long we'll wait for a.HTTPPort to work before
  78. // starting to try a.HTTPSPort.
  79. func (a *Dialer) httpsFallbackDelay() time.Duration {
  80. if v := a.testFallbackDelay; v != 0 {
  81. return v
  82. }
  83. return 500 * time.Millisecond
  84. }
  85. var _ = envknob.RegisterBool("TS_USE_CONTROL_DIAL_PLAN") // to record at init time whether it's in use
  86. func (a *Dialer) dial(ctx context.Context) (*ClientConn, error) {
  87. // If we don't have a dial plan, just fall back to dialing the single
  88. // host we know about.
  89. useDialPlan := envknob.BoolDefaultTrue("TS_USE_CONTROL_DIAL_PLAN")
  90. if !useDialPlan || a.DialPlan == nil || len(a.DialPlan.Candidates) == 0 {
  91. return a.dialHost(ctx, netip.Addr{})
  92. }
  93. candidates := a.DialPlan.Candidates
  94. // Otherwise, we try dialing per the plan. Store the highest priority
  95. // in the list, so that if we get a connection to one of those
  96. // candidates we can return quickly.
  97. var highestPriority int = math.MinInt
  98. for _, c := range candidates {
  99. if c.Priority > highestPriority {
  100. highestPriority = c.Priority
  101. }
  102. }
  103. // This context allows us to cancel in-flight connections if we get a
  104. // highest-priority connection before we're all done.
  105. ctx, cancel := context.WithCancel(ctx)
  106. defer cancel()
  107. // Now, for each candidate, kick off a dial in parallel.
  108. type dialResult struct {
  109. conn *ClientConn
  110. err error
  111. addr netip.Addr
  112. priority int
  113. }
  114. resultsCh := make(chan dialResult, len(candidates))
  115. var pending atomic.Int32
  116. pending.Store(int32(len(candidates)))
  117. for _, c := range candidates {
  118. go func(ctx context.Context, c tailcfg.ControlIPCandidate) {
  119. var (
  120. conn *ClientConn
  121. err error
  122. )
  123. // Always send results back to our channel.
  124. defer func() {
  125. resultsCh <- dialResult{conn, err, c.IP, c.Priority}
  126. if pending.Add(-1) == 0 {
  127. close(resultsCh)
  128. }
  129. }()
  130. // If non-zero, wait the configured start timeout
  131. // before we do anything.
  132. if c.DialStartDelaySec > 0 {
  133. a.logf("[v2] controlhttp: waiting %.2f seconds before dialing %q @ %v", c.DialStartDelaySec, a.Hostname, c.IP)
  134. tmr, tmrChannel := a.clock().NewTimer(time.Duration(c.DialStartDelaySec * float64(time.Second)))
  135. defer tmr.Stop()
  136. select {
  137. case <-ctx.Done():
  138. err = ctx.Err()
  139. return
  140. case <-tmrChannel:
  141. }
  142. }
  143. // Now, create a sub-context with the given timeout and
  144. // try dialing the provided host.
  145. ctx, cancel := context.WithTimeout(ctx, time.Duration(c.DialTimeoutSec*float64(time.Second)))
  146. defer cancel()
  147. // This will dial, and the defer above sends it back to our parent.
  148. a.logf("[v2] controlhttp: trying to dial %q @ %v", a.Hostname, c.IP)
  149. conn, err = a.dialHost(ctx, c.IP)
  150. }(ctx, c)
  151. }
  152. var results []dialResult
  153. for res := range resultsCh {
  154. // If we get a response that has the highest priority, we don't
  155. // need to wait for any of the other connections to finish; we
  156. // can just return this connection.
  157. //
  158. // TODO(andrew): we could make this better by keeping track of
  159. // the highest remaining priority dynamically, instead of just
  160. // checking for the highest total
  161. if res.priority == highestPriority && res.conn != nil {
  162. a.logf("[v1] controlhttp: high-priority success dialing %q @ %v from dial plan", a.Hostname, res.addr)
  163. // Drain the channel and any existing connections in
  164. // the background.
  165. go func() {
  166. for _, res := range results {
  167. if res.conn != nil {
  168. res.conn.Close()
  169. }
  170. }
  171. for res := range resultsCh {
  172. if res.conn != nil {
  173. res.conn.Close()
  174. }
  175. }
  176. if a.drainFinished != nil {
  177. close(a.drainFinished)
  178. }
  179. }()
  180. return res.conn, nil
  181. }
  182. // This isn't a highest-priority result, so just store it until
  183. // we're done.
  184. results = append(results, res)
  185. }
  186. // After we finish this function, close any remaining open connections.
  187. defer func() {
  188. for _, result := range results {
  189. // Note: below, we nil out the returned connection (if
  190. // any) in the slice so we don't close it.
  191. if result.conn != nil {
  192. result.conn.Close()
  193. }
  194. }
  195. // We don't drain asynchronously after this point, so notify our
  196. // channel when we return.
  197. if a.drainFinished != nil {
  198. close(a.drainFinished)
  199. }
  200. }()
  201. // Sort by priority, then take the first non-error response.
  202. sort.Slice(results, func(i, j int) bool {
  203. // NOTE: intentionally inverted so that the highest priority
  204. // item comes first
  205. return results[i].priority > results[j].priority
  206. })
  207. var (
  208. conn *ClientConn
  209. errs []error
  210. )
  211. for i, result := range results {
  212. if result.err != nil {
  213. errs = append(errs, result.err)
  214. continue
  215. }
  216. a.logf("[v1] controlhttp: succeeded dialing %q @ %v from dial plan", a.Hostname, result.addr)
  217. conn = result.conn
  218. results[i].conn = nil // so we don't close it in the defer
  219. return conn, nil
  220. }
  221. merr := multierr.New(errs...)
  222. // If we get here, then we didn't get anywhere with our dial plan; fall back to just using DNS.
  223. a.logf("controlhttp: failed dialing using DialPlan, falling back to DNS; errs=%s", merr.Error())
  224. return a.dialHost(ctx, netip.Addr{})
  225. }
  226. // The TS_FORCE_NOISE_443 envknob forces the controlclient noise dialer to
  227. // always use port 443 HTTPS connections to the controlplane and not try the
  228. // port 80 HTTP fast path.
  229. //
  230. // This is currently (2023-01-17) needed for Docker Desktop's "VPNKit" proxy
  231. // that breaks port 80 for us post-Noise-handshake, causing us to never try port
  232. // 443. Until one of Docker's proxy and/or this package's port 443 fallback is
  233. // fixed, this is a workaround. It might also be useful for future debugging.
  234. var forceNoise443 = envknob.RegisterBool("TS_FORCE_NOISE_443")
  235. // forceNoise443 reports whether the controlclient noise dialer should always
  236. // use HTTPS connections as its underlay connection (double crypto). This can
  237. // be necessary when networks or middle boxes are messing with port 80.
  238. func (d *Dialer) forceNoise443() bool {
  239. if forceNoise443() {
  240. return true
  241. }
  242. if d.HealthTracker.LastNoiseDialWasRecent() {
  243. // If we dialed recently, assume there was a recent failure and fall
  244. // back to HTTPS dials for the subsequent retries.
  245. //
  246. // This heuristic works around networks where port 80 is MITMed and
  247. // appears to work for a bit post-Upgrade but then gets closed,
  248. // such as seen in https://github.com/tailscale/tailscale/issues/13597.
  249. d.logf("controlhttp: forcing port 443 dial due to recent noise dial")
  250. return true
  251. }
  252. return false
  253. }
  254. func (d *Dialer) clock() tstime.Clock {
  255. if d.Clock != nil {
  256. return d.Clock
  257. }
  258. return tstime.StdClock{}
  259. }
  260. var debugNoiseDial = envknob.RegisterBool("TS_DEBUG_NOISE_DIAL")
  261. // dialHost connects to the configured Dialer.Hostname and upgrades the
  262. // connection into a controlbase.Conn.
  263. //
  264. // If optAddr is valid, then no DNS is used and the connection will be made to the
  265. // provided address.
  266. func (a *Dialer) dialHost(ctx context.Context, optAddr netip.Addr) (*ClientConn, error) {
  267. // Create one shared context used by both port 80 and port 443 dials.
  268. // If port 80 is still in flight when 443 returns, this deferred cancel
  269. // will stop the port 80 dial.
  270. ctx, cancel := context.WithCancel(ctx)
  271. defer cancel()
  272. ctx = sockstats.WithSockStats(ctx, sockstats.LabelControlClientDialer, a.logf)
  273. // u80 and u443 are the URLs we'll try to hit over HTTP or HTTPS,
  274. // respectively, in order to do the HTTP upgrade to a net.Conn over which
  275. // we'll speak Noise.
  276. u80 := &url.URL{
  277. Scheme: "http",
  278. Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPPort, "80")),
  279. Path: serverUpgradePath,
  280. }
  281. u443 := &url.URL{
  282. Scheme: "https",
  283. Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPSPort, "443")),
  284. Path: serverUpgradePath,
  285. }
  286. if a.HTTPSPort == NoPort {
  287. u443 = nil
  288. }
  289. type tryURLRes struct {
  290. u *url.URL // input (the URL conn+err are for/from)
  291. conn *ClientConn // result (mutually exclusive with err)
  292. err error
  293. }
  294. ch := make(chan tryURLRes) // must be unbuffered
  295. try := func(u *url.URL) {
  296. if debugNoiseDial() {
  297. a.logf("trying noise dial (%v, %v) ...", u, optAddr)
  298. }
  299. cbConn, err := a.dialURL(ctx, u, optAddr)
  300. if debugNoiseDial() {
  301. a.logf("noise dial (%v, %v) = (%v, %v)", u, optAddr, cbConn, err)
  302. }
  303. select {
  304. case ch <- tryURLRes{u, cbConn, err}:
  305. case <-ctx.Done():
  306. if cbConn != nil {
  307. cbConn.Close()
  308. }
  309. }
  310. }
  311. forceTLS := a.forceNoise443()
  312. // Start the plaintext HTTP attempt first, unless disabled by the envknob.
  313. if !forceTLS || u443 == nil {
  314. go try(u80)
  315. }
  316. // In case outbound port 80 blocked or MITM'ed poorly, start a backup timer
  317. // to dial port 443 if port 80 doesn't either succeed or fail quickly.
  318. var try443Timer tstime.TimerController
  319. if u443 != nil {
  320. delay := a.httpsFallbackDelay()
  321. if forceTLS {
  322. delay = 0
  323. }
  324. try443Timer = a.clock().AfterFunc(delay, func() { try(u443) })
  325. defer try443Timer.Stop()
  326. }
  327. var err80, err443 error
  328. for {
  329. select {
  330. case <-ctx.Done():
  331. return nil, fmt.Errorf("connection attempts aborted by context: %w", ctx.Err())
  332. case res := <-ch:
  333. if res.err == nil {
  334. return res.conn, nil
  335. }
  336. switch res.u {
  337. case u80:
  338. // Connecting over plain HTTP failed; assume it's an HTTP proxy
  339. // being difficult and see if we can get through over HTTPS.
  340. err80 = res.err
  341. // Stop the fallback timer and run it immediately. We don't use
  342. // Timer.Reset(0) here because on AfterFuncs, that can run it
  343. // again.
  344. if try443Timer != nil && try443Timer.Stop() {
  345. go try(u443)
  346. } // else we lost the race and it started already which is what we want
  347. case u443:
  348. err443 = res.err
  349. default:
  350. panic("invalid")
  351. }
  352. if err80 != nil && err443 != nil {
  353. return nil, fmt.Errorf("all connection attempts failed (HTTP: %v, HTTPS: %v)", err80, err443)
  354. }
  355. }
  356. }
  357. }
  358. // dialURL attempts to connect to the given URL.
  359. //
  360. // If optAddr is valid, then no DNS is used and the connection will be made to the
  361. // provided address.
  362. func (a *Dialer) dialURL(ctx context.Context, u *url.URL, optAddr netip.Addr) (*ClientConn, error) {
  363. init, cont, err := controlbase.ClientDeferred(a.MachineKey, a.ControlKey, a.ProtocolVersion)
  364. if err != nil {
  365. return nil, err
  366. }
  367. netConn, err := a.tryURLUpgrade(ctx, u, optAddr, init)
  368. if err != nil {
  369. return nil, err
  370. }
  371. cbConn, err := cont(ctx, netConn)
  372. if err != nil {
  373. netConn.Close()
  374. return nil, err
  375. }
  376. return &ClientConn{
  377. Conn: cbConn,
  378. }, nil
  379. }
  380. // resolver returns a.DNSCache if non-nil or a new *dnscache.Resolver
  381. // otherwise.
  382. func (a *Dialer) resolver() *dnscache.Resolver {
  383. if a.DNSCache != nil {
  384. return a.DNSCache
  385. }
  386. return &dnscache.Resolver{
  387. Forward: dnscache.Get().Forward,
  388. LookupIPFallback: dnsfallback.MakeLookupFunc(a.logf, a.NetMon),
  389. UseLastGood: true,
  390. Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
  391. }
  392. }
  393. func isLoopback(a net.Addr) bool {
  394. if ta, ok := a.(*net.TCPAddr); ok {
  395. return ta.IP.IsLoopback()
  396. }
  397. return false
  398. }
  399. var macOSScreenTime = health.Register(&health.Warnable{
  400. Code: "macos-screen-time",
  401. Severity: health.SeverityHigh,
  402. Title: "Tailscale blocked by Screen Time",
  403. Text: func(args health.Args) string {
  404. return "macOS Screen Time seems to be blocking Tailscale. Try disabling Screen Time in System Settings > Screen Time > Content & Privacy > Access to Web Content."
  405. },
  406. ImpactsConnectivity: true,
  407. })
  408. // tryURLUpgrade connects to u, and tries to upgrade it to a net.Conn.
  409. //
  410. // If optAddr is valid, then no DNS is used and the connection will be made to
  411. // the provided address.
  412. //
  413. // Only the provided ctx is used, not a.ctx.
  414. func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Addr, init []byte) (_ net.Conn, retErr error) {
  415. var dns *dnscache.Resolver
  416. // If we were provided an address to dial, then create a resolver that just
  417. // returns that value; otherwise, fall back to DNS.
  418. if optAddr.IsValid() {
  419. dns = &dnscache.Resolver{
  420. SingleHostStaticResult: []netip.Addr{optAddr},
  421. SingleHost: u.Hostname(),
  422. Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
  423. }
  424. } else {
  425. dns = a.resolver()
  426. }
  427. var dialer dnscache.DialContextFunc
  428. if a.Dialer != nil {
  429. dialer = a.Dialer
  430. } else {
  431. dialer = stdDialer.DialContext
  432. }
  433. // On macOS, see if Screen Time is blocking things.
  434. if runtime.GOOS == "darwin" {
  435. var proxydIntercepted atomic.Bool // intercepted by macOS webfilterproxyd
  436. origDialer := dialer
  437. dialer = func(ctx context.Context, network, address string) (net.Conn, error) {
  438. c, err := origDialer(ctx, network, address)
  439. if err != nil {
  440. return nil, err
  441. }
  442. if isLoopback(c.LocalAddr()) && isLoopback(c.RemoteAddr()) {
  443. proxydIntercepted.Store(true)
  444. }
  445. return c, nil
  446. }
  447. defer func() {
  448. if retErr != nil && proxydIntercepted.Load() {
  449. a.HealthTracker.SetUnhealthy(macOSScreenTime, nil)
  450. retErr = fmt.Errorf("macOS Screen Time is blocking network access: %w", retErr)
  451. } else {
  452. a.HealthTracker.SetHealthy(macOSScreenTime)
  453. }
  454. }()
  455. }
  456. tr := http.DefaultTransport.(*http.Transport).Clone()
  457. defer tr.CloseIdleConnections()
  458. tr.Proxy = a.getProxyFunc()
  459. tshttpproxy.SetTransportGetProxyConnectHeader(tr)
  460. tr.DialContext = dnscache.Dialer(dialer, dns)
  461. // Disable HTTP2, since h2 can't do protocol switching.
  462. tr.TLSClientConfig.NextProtos = []string{}
  463. tr.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
  464. tr.TLSClientConfig = tlsdial.Config(a.Hostname, a.HealthTracker, tr.TLSClientConfig)
  465. if !tr.TLSClientConfig.InsecureSkipVerify {
  466. panic("unexpected") // should be set by tlsdial.Config
  467. }
  468. verify := tr.TLSClientConfig.VerifyConnection
  469. if verify == nil {
  470. panic("unexpected") // should be set by tlsdial.Config
  471. }
  472. // Demote all cert verification errors to log messages. We don't actually
  473. // care about the TLS security (because we just do the Noise crypto atop whatever
  474. // connection we get, including HTTP port 80 plaintext) so this permits
  475. // middleboxes to MITM their users. All they'll see is some Noise.
  476. tr.TLSClientConfig.VerifyConnection = func(cs tls.ConnectionState) error {
  477. if err := verify(cs); err != nil && a.Logf != nil && !a.omitCertErrorLogging {
  478. a.Logf("warning: TLS cert verificication for %q failed: %v", a.Hostname, err)
  479. }
  480. return nil // regardless
  481. }
  482. tr.DialTLSContext = dnscache.TLSDialer(dialer, dns, tr.TLSClientConfig)
  483. tr.DisableCompression = true
  484. // (mis)use httptrace to extract the underlying net.Conn from the
  485. // transport. The transport handles 101 Switching Protocols correctly,
  486. // such that the Conn will not be reused or kept alive by the transport
  487. // once the response has been handed back from RoundTrip.
  488. //
  489. // In theory, the machinery of net/http should make it such that
  490. // the trace callback happens-before we get the response, but
  491. // there's no promise of that. So, to make sure, we use a buffered
  492. // channel as a synchronization step to avoid data races.
  493. //
  494. // Note that even though we're able to extract a net.Conn via this
  495. // mechanism, we must still keep using the eventual resp.Body to
  496. // read from, because it includes a buffer we can't get rid of. If
  497. // the server never sends any data after sending the HTTP
  498. // response, we could get away with it, but violating this
  499. // assumption leads to very mysterious transport errors (lockups,
  500. // unexpected EOFs...), and we're bound to forget someday and
  501. // introduce a protocol optimization at a higher level that starts
  502. // eagerly transmitting from the server.
  503. var lastConn syncs.AtomicValue[net.Conn]
  504. trace := httptrace.ClientTrace{
  505. // Even though we only make a single HTTP request which should
  506. // require a single connection, the context (with the attached
  507. // trace configuration) might be used by our custom dialer to
  508. // make other HTTP requests (e.g. BootstrapDNS). We only care
  509. // about the last connection made, which should be the one to
  510. // the control server.
  511. GotConn: func(info httptrace.GotConnInfo) {
  512. lastConn.Store(info.Conn)
  513. },
  514. }
  515. ctx = httptrace.WithClientTrace(ctx, &trace)
  516. req := &http.Request{
  517. Method: "POST",
  518. URL: u,
  519. Header: http.Header{
  520. "Upgrade": []string{upgradeHeaderValue},
  521. "Connection": []string{"upgrade"},
  522. handshakeHeaderName: []string{base64.StdEncoding.EncodeToString(init)},
  523. },
  524. }
  525. req = req.WithContext(ctx)
  526. resp, err := tr.RoundTrip(req)
  527. if err != nil {
  528. return nil, err
  529. }
  530. if resp.StatusCode != http.StatusSwitchingProtocols {
  531. return nil, fmt.Errorf("unexpected HTTP response: %s", resp.Status)
  532. }
  533. // From here on, the underlying net.Conn is ours to use, but there
  534. // is still a read buffer attached to it within resp.Body. So, we
  535. // must direct I/O through resp.Body, but we can still use the
  536. // underlying net.Conn for stuff like deadlines.
  537. switchedConn := lastConn.Load()
  538. if switchedConn == nil {
  539. resp.Body.Close()
  540. return nil, fmt.Errorf("httptrace didn't provide a connection")
  541. }
  542. if next := resp.Header.Get("Upgrade"); next != upgradeHeaderValue {
  543. resp.Body.Close()
  544. return nil, fmt.Errorf("server switched to unexpected protocol %q", next)
  545. }
  546. rwc, ok := resp.Body.(io.ReadWriteCloser)
  547. if !ok {
  548. resp.Body.Close()
  549. return nil, errors.New("http Transport did not provide a writable body")
  550. }
  551. return netutil.NewAltReadWriteCloserConn(rwc, switchedConn), nil
  552. }