client.go 19 KB

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