| 1 | // Copyright 2011 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // HTTP client implementation. See RFC 2616. |
| 6 | // |
| 7 | // This is the low-level Transport implementation of RoundTripper. |
| 8 | // The high-level interface is in client.go. |
| 9 | |
| 10 | // This file is DEPRECATED and keep solely for backward compatibility. |
| 11 | |
| 12 | package transport |
| 13 | |
| 14 | import ( |
| 15 | "bufio" |
| 16 | "compress/gzip" |
| 17 | "crypto/tls" |
| 18 | "encoding/base64" |
| 19 | "errors" |
| 20 | "fmt" |
| 21 | "io" |
| 22 | "io/ioutil" |
| 23 | "log" |
| 24 | "net" |
| 25 | "net/http" |
| 26 | "net/url" |
| 27 | "os" |
| 28 | "strings" |
| 29 | "sync" |
| 30 | ) |
| 31 | |
| 32 | // DefaultTransport is the default implementation of Transport and is |
| 33 | // used by DefaultClient. It establishes a new network connection for |
| 34 | // each call to Do and uses HTTP proxies as directed by the |
| 35 | // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) |
| 36 | // environment variables. |
| 37 | var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} |
| 38 | |
| 39 | // DefaultMaxIdleConnsPerHost is the default value of Transport's |
| 40 | // MaxIdleConnsPerHost. |
| 41 | const DefaultMaxIdleConnsPerHost = 2 |
| 42 | |
| 43 | // Transport is an implementation of RoundTripper that supports http, |
| 44 | // https, and http proxies (for either http or https with CONNECT). |
| 45 | // Transport can also cache connections for future re-use. |
| 46 | type Transport struct { |
| 47 | lk sync.Mutex |
| 48 | idleConn map[string][]*persistConn |
| 49 | altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper |
| 50 | |
| 51 | // TODO: tunable on global max cached connections |
| 52 | // TODO: tunable on timeout on cached connections |
| 53 | // TODO: optional pipelining |
| 54 | |
| 55 | // Proxy specifies a function to return a proxy for a given |
| 56 | // Request. If the function returns a non-nil error, the |
| 57 | // request is aborted with the provided error. |
| 58 | // If Proxy is nil or returns a nil *URL, no proxy is used. |
| 59 | Proxy func(*http.Request) (*url.URL, error) |
| 60 | |
| 61 | // Dial specifies the dial function for creating TCP |
| 62 | // connections. |
| 63 | // If Dial is nil, net.Dial is used. |
| 64 | Dial func(net, addr string) (c net.Conn, err error) |
| 65 | |
| 66 | // TLSClientConfig specifies the TLS configuration to use with |
| 67 | // tls.Client. If nil, the default configuration is used. |
| 68 | TLSClientConfig *tls.Config |
| 69 | |
| 70 | DisableKeepAlives bool |
| 71 | DisableCompression bool |
| 72 | |
| 73 | // MaxIdleConnsPerHost, if non-zero, controls the maximum idle |
| 74 | // (keep-alive) to keep to keep per-host. If zero, |
| 75 | // DefaultMaxIdleConnsPerHost is used. |
| 76 | MaxIdleConnsPerHost int |
| 77 | } |
| 78 | |
| 79 | // ProxyFromEnvironment returns the URL of the proxy to use for a |
| 80 | // given request, as indicated by the environment variables |
| 81 | // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). |
| 82 | // An error is returned if the proxy environment is invalid. |
| 83 | // A nil URL and nil error are returned if no proxy is defined in the |
| 84 | // environment, or a proxy should not be used for the given request. |
| 85 | func ProxyFromEnvironment(req *http.Request) (*url.URL, error) { |
| 86 | proxy := getenvEitherCase("HTTP_PROXY") |
| 87 | if proxy == "" { |
| 88 | return nil, nil |
| 89 | } |
| 90 | if !useProxy(canonicalAddr(req.URL)) { |
| 91 | return nil, nil |
| 92 | } |
| 93 | proxyURL, err := url.Parse(proxy) |
| 94 | if err != nil || proxyURL.Scheme == "" { |
| 95 | if u, err := url.Parse("http://" + proxy); err == nil { |
| 96 | proxyURL = u |
| 97 | err = nil |
| 98 | } |
| 99 | } |
| 100 | if err != nil { |
| 101 | return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) |
| 102 | } |
| 103 | return proxyURL, nil |
| 104 | } |
| 105 | |
| 106 | // ProxyURL returns a proxy function (for use in a Transport) |
| 107 | // that always returns the same URL. |
| 108 | func ProxyURL(fixedURL *url.URL) func(*http.Request) (*url.URL, error) { |
| 109 | return func(*http.Request) (*url.URL, error) { |
| 110 | return fixedURL, nil |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // transportRequest is a wrapper around a *Request that adds |
| 115 | // optional extra headers to write. |
| 116 | type transportRequest struct { |
| 117 | *http.Request // original request, not to be mutated |
| 118 | extra http.Header // extra headers to write, or nil |
| 119 | } |
| 120 | |
| 121 | func (tr *transportRequest) extraHeaders() http.Header { |
| 122 | if tr.extra == nil { |
| 123 | tr.extra = make(http.Header) |
| 124 | } |
| 125 | return tr.extra |
| 126 | } |
| 127 | |
| 128 | type RoundTripDetails struct { |
| 129 | Host string |
| 130 | TCPAddr *net.TCPAddr |
| 131 | IsProxy bool |
| 132 | Error error |
| 133 | } |
| 134 | |
| 135 | func (t *Transport) DetailedRoundTrip(req *http.Request) (details *RoundTripDetails, resp *http.Response, err error) { |
| 136 | if req.URL == nil { |
| 137 | return nil, nil, errors.New("http: nil Request.URL") |
| 138 | } |
| 139 | if req.Header == nil { |
| 140 | return nil, nil, errors.New("http: nil Request.Header") |
| 141 | } |
| 142 | if req.URL.Scheme != "http" && req.URL.Scheme != "https" { |
| 143 | t.lk.Lock() |
| 144 | var rt RoundTripper |
| 145 | if t.altProto != nil { |
| 146 | rt = t.altProto[req.URL.Scheme] |
| 147 | } |
| 148 | t.lk.Unlock() |
| 149 | if rt == nil { |
| 150 | return nil, nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} |
| 151 | } |
| 152 | return rt.DetailedRoundTrip(req) |
| 153 | } |
| 154 | treq := &transportRequest{Request: req} |
| 155 | cm, err := t.connectMethodForRequest(treq) |
| 156 | if err != nil { |
| 157 | return nil, nil, err |
| 158 | } |
| 159 | |
| 160 | // Get the cached or newly-created connection to either the |
| 161 | // host (for http or https), the http proxy, or the http proxy |
| 162 | // pre-CONNECTed to https server. In any case, we'll be ready |
| 163 | // to send it requests. |
| 164 | pconn, err := t.getConn(cm) |
| 165 | if err != nil { |
| 166 | return nil, nil, err |
| 167 | } |
| 168 | |
| 169 | resp, err = pconn.roundTrip(treq) |
| 170 | return &RoundTripDetails{pconn.host, pconn.ip, pconn.isProxy, err}, resp, err |
| 171 | } |
| 172 | |
| 173 | // RoundTrip implements the RoundTripper interface. |
| 174 | func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { |
| 175 | _, resp, err = t.DetailedRoundTrip(req) |
| 176 | return |
| 177 | } |
| 178 | |
| 179 | // RegisterProtocol registers a new protocol with scheme. |
| 180 | // The Transport will pass requests using the given scheme to rt. |
| 181 | // It is rt's responsibility to simulate HTTP request semantics. |
| 182 | // |
| 183 | // RegisterProtocol can be used by other packages to provide |
| 184 | // implementations of protocol schemes like "ftp" or "file". |
| 185 | func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { |
| 186 | if scheme == "http" || scheme == "https" { |
| 187 | panic("protocol " + scheme + " already registered") |
| 188 | } |
| 189 | t.lk.Lock() |
| 190 | defer t.lk.Unlock() |
| 191 | if t.altProto == nil { |
| 192 | t.altProto = make(map[string]RoundTripper) |
| 193 | } |
| 194 | if _, exists := t.altProto[scheme]; exists { |
| 195 | panic("protocol " + scheme + " already registered") |
| 196 | } |
| 197 | t.altProto[scheme] = rt |
| 198 | } |
| 199 | |
| 200 | // CloseIdleConnections closes any connections which were previously |
| 201 | // connected from previous requests but are now sitting idle in |
| 202 | // a "keep-alive" state. It does not interrupt any connections currently |
| 203 | // in use. |
| 204 | func (t *Transport) CloseIdleConnections() { |
| 205 | t.lk.Lock() |
| 206 | defer t.lk.Unlock() |
| 207 | if t.idleConn == nil { |
| 208 | return |
| 209 | } |
| 210 | for _, conns := range t.idleConn { |
| 211 | for _, pconn := range conns { |
| 212 | pconn.close() |
| 213 | } |
| 214 | } |
| 215 | t.idleConn = make(map[string][]*persistConn) |
| 216 | } |
| 217 | |
| 218 | // |
| 219 | // Private implementation past this point. |
| 220 | // |
| 221 | |
| 222 | func getenvEitherCase(k string) string { |
| 223 | if v := os.Getenv(strings.ToUpper(k)); v != "" { |
| 224 | return v |
| 225 | } |
| 226 | return os.Getenv(strings.ToLower(k)) |
| 227 | } |
| 228 | |
| 229 | func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) { |
| 230 | cm := &connectMethod{ |
| 231 | targetScheme: treq.URL.Scheme, |
| 232 | targetAddr: canonicalAddr(treq.URL), |
| 233 | } |
| 234 | if t.Proxy != nil { |
| 235 | var err error |
| 236 | cm.proxyURL, err = t.Proxy(treq.Request) |
| 237 | if err != nil { |
| 238 | return nil, err |
| 239 | } |
| 240 | } |
| 241 | return cm, nil |
| 242 | } |
| 243 | |
| 244 | // proxyAuth returns the Proxy-Authorization header to set |
| 245 | // on requests, if applicable. |
| 246 | func (cm *connectMethod) proxyAuth() string { |
| 247 | if cm.proxyURL == nil { |
| 248 | return "" |
| 249 | } |
| 250 | if u := cm.proxyURL.User; u != nil { |
| 251 | return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String())) |
| 252 | } |
| 253 | return "" |
| 254 | } |
| 255 | |
| 256 | // putIdleConn adds pconn to the list of idle persistent connections awaiting |
| 257 | // a new request. |
| 258 | // If pconn is no longer needed or not in a good state, putIdleConn |
| 259 | // returns false. |
| 260 | func (t *Transport) putIdleConn(pconn *persistConn) bool { |
| 261 | t.lk.Lock() |
| 262 | defer t.lk.Unlock() |
| 263 | if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { |
| 264 | pconn.close() |
| 265 | return false |
| 266 | } |
| 267 | if pconn.isBroken() { |
| 268 | return false |
| 269 | } |
| 270 | key := pconn.cacheKey |
| 271 | max := t.MaxIdleConnsPerHost |
| 272 | if max == 0 { |
| 273 | max = DefaultMaxIdleConnsPerHost |
| 274 | } |
| 275 | if len(t.idleConn[key]) >= max { |
| 276 | pconn.close() |
| 277 | return false |
| 278 | } |
| 279 | t.idleConn[key] = append(t.idleConn[key], pconn) |
| 280 | return true |
| 281 | } |
| 282 | |
| 283 | func (t *Transport) getIdleConn(cm *connectMethod) (pconn *persistConn) { |
| 284 | t.lk.Lock() |
| 285 | defer t.lk.Unlock() |
| 286 | if t.idleConn == nil { |
| 287 | t.idleConn = make(map[string][]*persistConn) |
| 288 | } |
| 289 | key := cm.String() |
| 290 | for { |
| 291 | pconns, ok := t.idleConn[key] |
| 292 | if !ok { |
| 293 | return nil |
| 294 | } |
| 295 | if len(pconns) == 1 { |
| 296 | pconn = pconns[0] |
| 297 | delete(t.idleConn, key) |
| 298 | } else { |
| 299 | // 2 or more cached connections; pop last |
| 300 | // TODO: queue? |
| 301 | pconn = pconns[len(pconns)-1] |
| 302 | t.idleConn[key] = pconns[0 : len(pconns)-1] |
| 303 | } |
| 304 | if !pconn.isBroken() { |
| 305 | return |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | func (t *Transport) dial(network, addr string) (c net.Conn, raddr string, ip *net.TCPAddr, err error) { |
| 311 | if t.Dial != nil { |
| 312 | ip, err = net.ResolveTCPAddr("tcp", addr) |
| 313 | if err != nil { |
| 314 | return |
| 315 | } |
| 316 | c, err = t.Dial(network, addr) |
| 317 | raddr = addr |
| 318 | return |
| 319 | } |
| 320 | addri, err := net.ResolveTCPAddr("tcp", addr) |
| 321 | if err != nil { |
| 322 | return |
| 323 | } |
| 324 | c, err = net.DialTCP("tcp", nil, addri) |
| 325 | raddr = addr |
| 326 | ip = addri |
| 327 | return |
| 328 | } |
| 329 | |
| 330 | // getConn dials and creates a new persistConn to the target as |
| 331 | // specified in the connectMethod. This includes doing a proxy CONNECT |
| 332 | // and/or setting up TLS. If this doesn't return an error, the persistConn |
| 333 | // is ready to write requests to. |
| 334 | func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) { |
| 335 | if pc := t.getIdleConn(cm); pc != nil { |
| 336 | return pc, nil |
| 337 | } |
| 338 | |
| 339 | conn, raddr, ip, err := t.dial("tcp", cm.addr()) |
| 340 | if err != nil { |
| 341 | if cm.proxyURL != nil { |
| 342 | err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) |
| 343 | } |
| 344 | return nil, err |
| 345 | } |
| 346 | |
| 347 | pa := cm.proxyAuth() |
| 348 | |
| 349 | pconn := &persistConn{ |
| 350 | t: t, |
| 351 | cacheKey: cm.String(), |
| 352 | conn: conn, |
| 353 | reqch: make(chan requestAndChan, 50), |
| 354 | host: raddr, |
| 355 | ip: ip, |
| 356 | } |
| 357 | |
| 358 | switch { |
| 359 | case cm.proxyURL == nil: |
| 360 | // Do nothing. |
| 361 | case cm.targetScheme == "http": |
| 362 | pconn.isProxy = true |
| 363 | if pa != "" { |
| 364 | pconn.mutateHeaderFunc = func(h http.Header) { |
| 365 | h.Set("Proxy-Authorization", pa) |
| 366 | } |
| 367 | } |
| 368 | case cm.targetScheme == "https": |
| 369 | connectReq := &http.Request{ |
| 370 | Method: "CONNECT", |
| 371 | URL: &url.URL{Opaque: cm.targetAddr}, |
| 372 | Host: cm.targetAddr, |
| 373 | Header: make(http.Header), |
| 374 | } |
| 375 | if pa != "" { |
| 376 | connectReq.Header.Set("Proxy-Authorization", pa) |
| 377 | } |
| 378 | connectReq.Write(conn) |
| 379 | |
| 380 | // Read response. |
| 381 | // Okay to use and discard buffered reader here, because |
| 382 | // TLS server will not speak until spoken to. |
| 383 | br := bufio.NewReader(conn) |
| 384 | resp, err := http.ReadResponse(br, connectReq) |
| 385 | if err != nil { |
| 386 | conn.Close() |
| 387 | return nil, err |
| 388 | } |
| 389 | if resp.StatusCode != 200 { |
| 390 | f := strings.SplitN(resp.Status, " ", 2) |
| 391 | conn.Close() |
| 392 | return nil, errors.New(f[1]) |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | if cm.targetScheme == "https" { |
| 397 | // Initiate TLS and check remote host name against certificate. |
| 398 | conn = tls.Client(conn, t.TLSClientConfig) |
| 399 | if err = conn.(*tls.Conn).Handshake(); err != nil { |
| 400 | return nil, err |
| 401 | } |
| 402 | if t.TLSClientConfig == nil || !t.TLSClientConfig.InsecureSkipVerify { |
| 403 | if err = conn.(*tls.Conn).VerifyHostname(cm.tlsHost()); err != nil { |
| 404 | return nil, err |
| 405 | } |
| 406 | } |
| 407 | pconn.conn = conn |
| 408 | } |
| 409 | |
| 410 | pconn.br = bufio.NewReader(pconn.conn) |
| 411 | pconn.bw = bufio.NewWriter(pconn.conn) |
| 412 | go pconn.readLoop() |
| 413 | return pconn, nil |
| 414 | } |
| 415 | |
| 416 | // useProxy returns true if requests to addr should use a proxy, |
| 417 | // according to the NO_PROXY or no_proxy environment variable. |
| 418 | // addr is always a canonicalAddr with a host and port. |
| 419 | func useProxy(addr string) bool { |
| 420 | if len(addr) == 0 { |
| 421 | return true |
| 422 | } |
| 423 | host, _, err := net.SplitHostPort(addr) |
| 424 | if err != nil { |
| 425 | return false |
| 426 | } |
| 427 | if host == "localhost" { |
| 428 | return false |
| 429 | } |
| 430 | if ip := net.ParseIP(host); ip != nil { |
| 431 | if ip.IsLoopback() { |
| 432 | return false |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | no_proxy := getenvEitherCase("NO_PROXY") |
| 437 | if no_proxy == "*" { |
| 438 | return false |
| 439 | } |
| 440 | |
| 441 | addr = strings.ToLower(strings.TrimSpace(addr)) |
| 442 | if hasPort(addr) { |
| 443 | addr = addr[:strings.LastIndex(addr, ":")] |
| 444 | } |
| 445 | |
| 446 | for _, p := range strings.Split(no_proxy, ",") { |
| 447 | p = strings.ToLower(strings.TrimSpace(p)) |
| 448 | if len(p) == 0 { |
| 449 | continue |
| 450 | } |
| 451 | if hasPort(p) { |
| 452 | p = p[:strings.LastIndex(p, ":")] |
| 453 | } |
| 454 | if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) { |
| 455 | return false |
| 456 | } |
| 457 | } |
| 458 | return true |
| 459 | } |
| 460 | |
| 461 | // connectMethod is the map key (in its String form) for keeping persistent |
| 462 | // TCP connections alive for subsequent HTTP requests. |
| 463 | // |
| 464 | // A connect method may be of the following types: |
| 465 | // |
| 466 | // Cache key form Description |
| 467 | // ----------------- ------------------------- |
| 468 | // ||http|foo.com http directly to server, no proxy |
| 469 | // ||https|foo.com https directly to server, no proxy |
| 470 | // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com |
| 471 | // http://proxy.com|http http to proxy, http to anywhere after that |
| 472 | // |
| 473 | // Note: no support to https to the proxy yet. |
| 474 | // |
| 475 | type connectMethod struct { |
| 476 | proxyURL *url.URL // nil for no proxy, else full proxy URL |
| 477 | targetScheme string // "http" or "https" |
| 478 | targetAddr string // Not used if proxy + http targetScheme (4th example in table) |
| 479 | } |
| 480 | |
| 481 | func (cm *connectMethod) String() string { |
| 482 | proxyStr := "" |
| 483 | if cm.proxyURL != nil { |
| 484 | proxyStr = cm.proxyURL.String() |
| 485 | } |
| 486 | return strings.Join([]string{proxyStr, cm.targetScheme, cm.targetAddr}, "|") |
| 487 | } |
| 488 | |
| 489 | // addr returns the first hop "host:port" to which we need to TCP connect. |
| 490 | func (cm *connectMethod) addr() string { |
| 491 | if cm.proxyURL != nil { |
| 492 | return canonicalAddr(cm.proxyURL) |
| 493 | } |
| 494 | return cm.targetAddr |
| 495 | } |
| 496 | |
| 497 | // tlsHost returns the host name to match against the peer's |
| 498 | // TLS certificate. |
| 499 | func (cm *connectMethod) tlsHost() string { |
| 500 | h := cm.targetAddr |
| 501 | if hasPort(h) { |
| 502 | h = h[:strings.LastIndex(h, ":")] |
| 503 | } |
| 504 | return h |
| 505 | } |
| 506 | |
| 507 | // persistConn wraps a connection, usually a persistent one |
| 508 | // (but may be used for non-keep-alive requests as well) |
| 509 | type persistConn struct { |
| 510 | t *Transport |
| 511 | cacheKey string // its connectMethod.String() |
| 512 | conn net.Conn |
| 513 | br *bufio.Reader // from conn |
| 514 | bw *bufio.Writer // to conn |
| 515 | reqch chan requestAndChan // written by roundTrip(); read by readLoop() |
| 516 | isProxy bool |
| 517 | |
| 518 | // mutateHeaderFunc is an optional func to modify extra |
| 519 | // headers on each outbound request before it's written. (the |
| 520 | // original Request given to RoundTrip is not modified) |
| 521 | mutateHeaderFunc func(http.Header) |
| 522 | |
| 523 | lk sync.Mutex // guards numExpectedResponses and broken |
| 524 | numExpectedResponses int |
| 525 | broken bool // an error has happened on this connection; marked broken so it's not reused. |
| 526 | |
| 527 | host string |
| 528 | ip *net.TCPAddr |
| 529 | } |
| 530 | |
| 531 | func (pc *persistConn) isBroken() bool { |
| 532 | pc.lk.Lock() |
| 533 | defer pc.lk.Unlock() |
| 534 | return pc.broken |
| 535 | } |
| 536 | |
| 537 | var remoteSideClosedFunc func(error) bool // or nil to use default |
| 538 | |
| 539 | func remoteSideClosed(err error) bool { |
| 540 | if err == io.EOF { |
| 541 | return true |
| 542 | } |
| 543 | if remoteSideClosedFunc != nil { |
| 544 | return remoteSideClosedFunc(err) |
| 545 | } |
| 546 | return false |
| 547 | } |
| 548 | |
| 549 | func (pc *persistConn) readLoop() { |
| 550 | alive := true |
| 551 | var lastbody io.ReadCloser // last response body, if any, read on this connection |
| 552 | |
| 553 | for alive { |
| 554 | pb, err := pc.br.Peek(1) |
| 555 | |
| 556 | pc.lk.Lock() |
| 557 | if pc.numExpectedResponses == 0 { |
| 558 | pc.closeLocked() |
| 559 | pc.lk.Unlock() |
| 560 | if len(pb) > 0 { |
| 561 | log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", |
| 562 | string(pb), err) |
| 563 | } |
| 564 | return |
| 565 | } |
| 566 | pc.lk.Unlock() |
| 567 | |
| 568 | rc := <-pc.reqch |
| 569 | |
| 570 | // Advance past the previous response's body, if the |
| 571 | // caller hasn't done so. |
| 572 | if lastbody != nil { |
| 573 | lastbody.Close() // assumed idempotent |
| 574 | lastbody = nil |
| 575 | } |
| 576 | resp, err := http.ReadResponse(pc.br, rc.req) |
| 577 | |
| 578 | if err != nil { |
| 579 | pc.close() |
| 580 | } else { |
| 581 | hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 |
| 582 | if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { |
| 583 | resp.Header.Del("Content-Encoding") |
| 584 | resp.Header.Del("Content-Length") |
| 585 | resp.ContentLength = -1 |
| 586 | gzReader, zerr := gzip.NewReader(resp.Body) |
| 587 | if zerr != nil { |
| 588 | pc.close() |
| 589 | err = zerr |
| 590 | } else { |
| 591 | resp.Body = &readFirstCloseBoth{&discardOnCloseReadCloser{gzReader}, resp.Body} |
| 592 | } |
| 593 | } |
| 594 | resp.Body = &bodyEOFSignal{body: resp.Body} |
| 595 | } |
| 596 | |
| 597 | if err != nil || resp.Close || rc.req.Close { |
| 598 | alive = false |
| 599 | } |
| 600 | |
| 601 | hasBody := resp != nil && resp.ContentLength != 0 |
| 602 | var waitForBodyRead chan bool |
| 603 | if alive { |
| 604 | if hasBody { |
| 605 | lastbody = resp.Body |
| 606 | waitForBodyRead = make(chan bool) |
| 607 | resp.Body.(*bodyEOFSignal).fn = func() { |
| 608 | if !pc.t.putIdleConn(pc) { |
| 609 | alive = false |
| 610 | } |
| 611 | waitForBodyRead <- true |
| 612 | } |
| 613 | } else { |
| 614 | // When there's no response body, we immediately |
| 615 | // reuse the TCP connection (putIdleConn), but |
| 616 | // we need to prevent ClientConn.Read from |
| 617 | // closing the Response.Body on the next |
| 618 | // loop, otherwise it might close the body |
| 619 | // before the client code has had a chance to |
| 620 | // read it (even though it'll just be 0, EOF). |
| 621 | lastbody = nil |
| 622 | |
| 623 | if !pc.t.putIdleConn(pc) { |
| 624 | alive = false |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | rc.ch <- responseAndError{resp, err} |
| 630 | |
| 631 | // Wait for the just-returned response body to be fully consumed |
| 632 | // before we race and peek on the underlying bufio reader. |
| 633 | if waitForBodyRead != nil { |
| 634 | <-waitForBodyRead |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | type responseAndError struct { |
| 640 | res *http.Response |
| 641 | err error |
| 642 | } |
| 643 | |
| 644 | type requestAndChan struct { |
| 645 | req *http.Request |
| 646 | ch chan responseAndError |
| 647 | |
| 648 | // did the Transport (as opposed to the client code) add an |
| 649 | // Accept-Encoding gzip header? only if it we set it do |
| 650 | // we transparently decode the gzip. |
| 651 | addedGzip bool |
| 652 | } |
| 653 | |
| 654 | func (pc *persistConn) roundTrip(req *transportRequest) (resp *http.Response, err error) { |
| 655 | if pc.mutateHeaderFunc != nil { |
| 656 | panic("mutateHeaderFunc not supported in modified Transport") |
| 657 | } |
| 658 | |
| 659 | // Ask for a compressed version if the caller didn't set their |
| 660 | // own value for Accept-Encoding. We only attempted to |
| 661 | // uncompress the gzip stream if we were the layer that |
| 662 | // requested it. |
| 663 | requestedGzip := false |
| 664 | if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" { |
| 665 | // Request gzip only, not deflate. Deflate is ambiguous and |
| 666 | // not as universally supported anyway. |
| 667 | // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 |
| 668 | requestedGzip = true |
| 669 | req.extraHeaders().Set("Accept-Encoding", "gzip") |
| 670 | } |
| 671 | |
| 672 | pc.lk.Lock() |
| 673 | pc.numExpectedResponses++ |
| 674 | pc.lk.Unlock() |
| 675 | |
| 676 | // orig: err = req.Request.write(pc.bw, pc.isProxy, req.extra) |
| 677 | if pc.isProxy { |
| 678 | err = req.Request.WriteProxy(pc.bw) |
| 679 | } else { |
| 680 | err = req.Request.Write(pc.bw) |
| 681 | } |
| 682 | if err != nil { |
| 683 | pc.close() |
| 684 | return |
| 685 | } |
| 686 | pc.bw.Flush() |
| 687 | |
| 688 | ch := make(chan responseAndError, 1) |
| 689 | pc.reqch <- requestAndChan{req.Request, ch, requestedGzip} |
| 690 | re := <-ch |
| 691 | pc.lk.Lock() |
| 692 | pc.numExpectedResponses-- |
| 693 | pc.lk.Unlock() |
| 694 | |
| 695 | return re.res, re.err |
| 696 | } |
| 697 | |
| 698 | func (pc *persistConn) close() { |
| 699 | pc.lk.Lock() |
| 700 | defer pc.lk.Unlock() |
| 701 | pc.closeLocked() |
| 702 | } |
| 703 | |
| 704 | func (pc *persistConn) closeLocked() { |
| 705 | pc.broken = true |
| 706 | pc.conn.Close() |
| 707 | pc.mutateHeaderFunc = nil |
| 708 | } |
| 709 | |
| 710 | var portMap = map[string]string{ |
| 711 | "http": "80", |
| 712 | "https": "443", |
| 713 | } |
| 714 | |
| 715 | // canonicalAddr returns url.Host but always with a ":port" suffix |
| 716 | func canonicalAddr(url *url.URL) string { |
| 717 | addr := url.Host |
| 718 | if !hasPort(addr) { |
| 719 | return addr + ":" + portMap[url.Scheme] |
| 720 | } |
| 721 | return addr |
| 722 | } |
| 723 | |
| 724 | func responseIsKeepAlive(res *http.Response) bool { |
| 725 | // TODO: implement. for now just always shutting down the connection. |
| 726 | return false |
| 727 | } |
| 728 | |
| 729 | // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most |
| 730 | // once, right before the final Read() or Close() call returns, but after |
| 731 | // EOF has been seen. |
| 732 | type bodyEOFSignal struct { |
| 733 | body io.ReadCloser |
| 734 | fn func() |
| 735 | isClosed bool |
| 736 | } |
| 737 | |
| 738 | func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { |
| 739 | n, err = es.body.Read(p) |
| 740 | if es.isClosed && n > 0 { |
| 741 | panic("http: unexpected bodyEOFSignal Read after Close; see issue 1725") |
| 742 | } |
| 743 | if err == io.EOF && es.fn != nil { |
| 744 | es.fn() |
| 745 | es.fn = nil |
| 746 | } |
| 747 | return |
| 748 | } |
| 749 | |
| 750 | func (es *bodyEOFSignal) Close() (err error) { |
| 751 | if es.isClosed { |
| 752 | return nil |
| 753 | } |
| 754 | es.isClosed = true |
| 755 | err = es.body.Close() |
| 756 | if err == nil && es.fn != nil { |
| 757 | es.fn() |
| 758 | es.fn = nil |
| 759 | } |
| 760 | return |
| 761 | } |
| 762 | |
| 763 | type readFirstCloseBoth struct { |
| 764 | io.ReadCloser |
| 765 | io.Closer |
| 766 | } |
| 767 | |
| 768 | func (r *readFirstCloseBoth) Close() error { |
| 769 | if err := r.ReadCloser.Close(); err != nil { |
| 770 | r.Closer.Close() |
| 771 | return err |
| 772 | } |
| 773 | if err := r.Closer.Close(); err != nil { |
| 774 | return err |
| 775 | } |
| 776 | return nil |
| 777 | } |
| 778 | |
| 779 | // discardOnCloseReadCloser consumes all its input on Close. |
| 780 | type discardOnCloseReadCloser struct { |
| 781 | io.ReadCloser |
| 782 | } |
| 783 | |
| 784 | func (d *discardOnCloseReadCloser) Close() error { |
| 785 | io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed |
| 786 | return d.ReadCloser.Close() |
| 787 | } |