transport.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906
  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. // HTTP client implementation. See RFC 7230 through 7235.
  5. //
  6. // This is the low-level Transport implementation of RoundTripper.
  7. // The high-level interface is in client.go.
  8. package http
  9. import (
  10. "bufio"
  11. "compress/gzip"
  12. "container/list"
  13. "context"
  14. "crypto/tls"
  15. "errors"
  16. "fmt"
  17. "internal/godebug"
  18. "io"
  19. "log"
  20. "net"
  21. "net/http/httptrace"
  22. "net/http/internal/ascii"
  23. "net/textproto"
  24. "net/url"
  25. "reflect"
  26. "strings"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "golang.org/x/net/http/httpguts"
  31. "golang.org/x/net/http/httpproxy"
  32. )
  33. // DefaultTransport is the default implementation of Transport and is
  34. // used by DefaultClient. It establishes network connections as needed
  35. // and caches them for reuse by subsequent calls. It uses HTTP proxies
  36. // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
  37. // $no_proxy) environment variables.
  38. var DefaultTransport RoundTripper = &Transport{
  39. Proxy: ProxyFromEnvironment,
  40. DialContext: defaultTransportDialContext(&net.Dialer{
  41. Timeout: 30 * time.Second,
  42. KeepAlive: 30 * time.Second,
  43. }),
  44. ForceAttemptHTTP2: true,
  45. MaxIdleConns: 100,
  46. IdleConnTimeout: 90 * time.Second,
  47. TLSHandshakeTimeout: 10 * time.Second,
  48. ExpectContinueTimeout: 1 * time.Second,
  49. }
  50. // DefaultMaxIdleConnsPerHost is the default value of Transport's
  51. // MaxIdleConnsPerHost.
  52. const DefaultMaxIdleConnsPerHost = 2
  53. // Transport is an implementation of RoundTripper that supports HTTP,
  54. // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
  55. //
  56. // By default, Transport caches connections for future re-use.
  57. // This may leave many open connections when accessing many hosts.
  58. // This behavior can be managed using Transport's CloseIdleConnections method
  59. // and the MaxIdleConnsPerHost and DisableKeepAlives fields.
  60. //
  61. // Transports should be reused instead of created as needed.
  62. // Transports are safe for concurrent use by multiple goroutines.
  63. //
  64. // A Transport is a low-level primitive for making HTTP and HTTPS requests.
  65. // For high-level functionality, such as cookies and redirects, see Client.
  66. //
  67. // Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
  68. // for HTTPS URLs, depending on whether the server supports HTTP/2,
  69. // and how the Transport is configured. The DefaultTransport supports HTTP/2.
  70. // To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
  71. // and call ConfigureTransport. See the package docs for more about HTTP/2.
  72. //
  73. // Responses with status codes in the 1xx range are either handled
  74. // automatically (100 expect-continue) or ignored. The one
  75. // exception is HTTP status code 101 (Switching Protocols), which is
  76. // considered a terminal status and returned by RoundTrip. To see the
  77. // ignored 1xx responses, use the httptrace trace package's
  78. // ClientTrace.Got1xxResponse.
  79. //
  80. // Transport only retries a request upon encountering a network error
  81. // if the request is idempotent and either has no body or has its
  82. // Request.GetBody defined. HTTP requests are considered idempotent if
  83. // they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their
  84. // Header map contains an "Idempotency-Key" or "X-Idempotency-Key"
  85. // entry. If the idempotency key value is a zero-length slice, the
  86. // request is treated as idempotent but the header is not sent on the
  87. // wire.
  88. type Transport struct {
  89. idleMu sync.Mutex
  90. closeIdle bool // user has requested to close all idle conns
  91. idleConn map[connectMethodKey][]*persistConn // most recently used at end
  92. idleConnWait map[connectMethodKey]wantConnQueue // waiting getConns
  93. idleLRU connLRU
  94. reqMu sync.Mutex
  95. reqCanceler map[cancelKey]func(error)
  96. altMu sync.Mutex // guards changing altProto only
  97. altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme
  98. connsPerHostMu sync.Mutex
  99. connsPerHost map[connectMethodKey]int
  100. connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns
  101. // Proxy specifies a function to return a proxy for a given
  102. // Request. If the function returns a non-nil error, the
  103. // request is aborted with the provided error.
  104. //
  105. // The proxy type is determined by the URL scheme. "http",
  106. // "https", and "socks5" are supported. If the scheme is empty,
  107. // "http" is assumed.
  108. //
  109. // If Proxy is nil or returns a nil *URL, no proxy is used.
  110. Proxy func(*Request) (*url.URL, error)
  111. // DialContext specifies the dial function for creating unencrypted TCP connections.
  112. // If DialContext is nil (and the deprecated Dial below is also nil),
  113. // then the transport dials using package net.
  114. //
  115. // DialContext runs concurrently with calls to RoundTrip.
  116. // A RoundTrip call that initiates a dial may end up using
  117. // a connection dialed previously when the earlier connection
  118. // becomes idle before the later DialContext completes.
  119. DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  120. // Dial specifies the dial function for creating unencrypted TCP connections.
  121. //
  122. // Dial runs concurrently with calls to RoundTrip.
  123. // A RoundTrip call that initiates a dial may end up using
  124. // a connection dialed previously when the earlier connection
  125. // becomes idle before the later Dial completes.
  126. //
  127. // Deprecated: Use DialContext instead, which allows the transport
  128. // to cancel dials as soon as they are no longer needed.
  129. // If both are set, DialContext takes priority.
  130. Dial func(network, addr string) (net.Conn, error)
  131. // DialTLSContext specifies an optional dial function for creating
  132. // TLS connections for non-proxied HTTPS requests.
  133. //
  134. // If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
  135. // DialContext and TLSClientConfig are used.
  136. //
  137. // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
  138. // requests and the TLSClientConfig and TLSHandshakeTimeout
  139. // are ignored. The returned net.Conn is assumed to already be
  140. // past the TLS handshake.
  141. DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
  142. // DialTLS specifies an optional dial function for creating
  143. // TLS connections for non-proxied HTTPS requests.
  144. //
  145. // Deprecated: Use DialTLSContext instead, which allows the transport
  146. // to cancel dials as soon as they are no longer needed.
  147. // If both are set, DialTLSContext takes priority.
  148. DialTLS func(network, addr string) (net.Conn, error)
  149. // TLSClientConfig specifies the TLS configuration to use with
  150. // tls.Client.
  151. // If nil, the default configuration is used.
  152. // If non-nil, HTTP/2 support may not be enabled by default.
  153. TLSClientConfig *tls.Config
  154. // TLSHandshakeTimeout specifies the maximum amount of time waiting to
  155. // wait for a TLS handshake. Zero means no timeout.
  156. TLSHandshakeTimeout time.Duration
  157. // DisableKeepAlives, if true, disables HTTP keep-alives and
  158. // will only use the connection to the server for a single
  159. // HTTP request.
  160. //
  161. // This is unrelated to the similarly named TCP keep-alives.
  162. DisableKeepAlives bool
  163. // DisableCompression, if true, prevents the Transport from
  164. // requesting compression with an "Accept-Encoding: gzip"
  165. // request header when the Request contains no existing
  166. // Accept-Encoding value. If the Transport requests gzip on
  167. // its own and gets a gzipped response, it's transparently
  168. // decoded in the Response.Body. However, if the user
  169. // explicitly requested gzip it is not automatically
  170. // uncompressed.
  171. DisableCompression bool
  172. // MaxIdleConns controls the maximum number of idle (keep-alive)
  173. // connections across all hosts. Zero means no limit.
  174. MaxIdleConns int
  175. // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
  176. // (keep-alive) connections to keep per-host. If zero,
  177. // DefaultMaxIdleConnsPerHost is used.
  178. MaxIdleConnsPerHost int
  179. // MaxConnsPerHost optionally limits the total number of
  180. // connections per host, including connections in the dialing,
  181. // active, and idle states. On limit violation, dials will block.
  182. //
  183. // Zero means no limit.
  184. MaxConnsPerHost int
  185. // IdleConnTimeout is the maximum amount of time an idle
  186. // (keep-alive) connection will remain idle before closing
  187. // itself.
  188. // Zero means no limit.
  189. IdleConnTimeout time.Duration
  190. // ResponseHeaderTimeout, if non-zero, specifies the amount of
  191. // time to wait for a server's response headers after fully
  192. // writing the request (including its body, if any). This
  193. // time does not include the time to read the response body.
  194. ResponseHeaderTimeout time.Duration
  195. // ExpectContinueTimeout, if non-zero, specifies the amount of
  196. // time to wait for a server's first response headers after fully
  197. // writing the request headers if the request has an
  198. // "Expect: 100-continue" header. Zero means no timeout and
  199. // causes the body to be sent immediately, without
  200. // waiting for the server to approve.
  201. // This time does not include the time to send the request header.
  202. ExpectContinueTimeout time.Duration
  203. // TLSNextProto specifies how the Transport switches to an
  204. // alternate protocol (such as HTTP/2) after a TLS ALPN
  205. // protocol negotiation. If Transport dials an TLS connection
  206. // with a non-empty protocol name and TLSNextProto contains a
  207. // map entry for that key (such as "h2"), then the func is
  208. // called with the request's authority (such as "example.com"
  209. // or "example.com:1234") and the TLS connection. The function
  210. // must return a RoundTripper that then handles the request.
  211. // If TLSNextProto is not nil, HTTP/2 support is not enabled
  212. // automatically.
  213. TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
  214. // ProxyConnectHeader optionally specifies headers to send to
  215. // proxies during CONNECT requests.
  216. // To set the header dynamically, see GetProxyConnectHeader.
  217. ProxyConnectHeader Header
  218. // GetProxyConnectHeader optionally specifies a func to return
  219. // headers to send to proxyURL during a CONNECT request to the
  220. // ip:port target.
  221. // If it returns an error, the Transport's RoundTrip fails with
  222. // that error. It can return (nil, nil) to not add headers.
  223. // If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
  224. // ignored.
  225. GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)
  226. // MaxResponseHeaderBytes specifies a limit on how many
  227. // response bytes are allowed in the server's response
  228. // header.
  229. //
  230. // Zero means to use a default limit.
  231. MaxResponseHeaderBytes int64
  232. // WriteBufferSize specifies the size of the write buffer used
  233. // when writing to the transport.
  234. // If zero, a default (currently 4KB) is used.
  235. WriteBufferSize int
  236. // ReadBufferSize specifies the size of the read buffer used
  237. // when reading from the transport.
  238. // If zero, a default (currently 4KB) is used.
  239. ReadBufferSize int
  240. // nextProtoOnce guards initialization of TLSNextProto and
  241. // h2transport (via onceSetNextProtoDefaults)
  242. nextProtoOnce sync.Once
  243. h2transport h2Transport // non-nil if http2 wired up
  244. tlsNextProtoWasNil bool // whether TLSNextProto was nil when the Once fired
  245. // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
  246. // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
  247. // By default, use of any those fields conservatively disables HTTP/2.
  248. // To use a custom dialer or TLS config and still attempt HTTP/2
  249. // upgrades, set this to true.
  250. ForceAttemptHTTP2 bool
  251. }
  252. // A cancelKey is the key of the reqCanceler map.
  253. // We wrap the *Request in this type since we want to use the original request,
  254. // not any transient one created by roundTrip.
  255. type cancelKey struct {
  256. req *Request
  257. }
  258. func (t *Transport) writeBufferSize() int {
  259. if t.WriteBufferSize > 0 {
  260. return t.WriteBufferSize
  261. }
  262. return 4 << 10
  263. }
  264. func (t *Transport) readBufferSize() int {
  265. if t.ReadBufferSize > 0 {
  266. return t.ReadBufferSize
  267. }
  268. return 4 << 10
  269. }
  270. // Clone returns a deep copy of t's exported fields.
  271. func (t *Transport) Clone() *Transport {
  272. t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
  273. t2 := &Transport{
  274. Proxy: t.Proxy,
  275. DialContext: t.DialContext,
  276. Dial: t.Dial,
  277. DialTLS: t.DialTLS,
  278. DialTLSContext: t.DialTLSContext,
  279. TLSHandshakeTimeout: t.TLSHandshakeTimeout,
  280. DisableKeepAlives: t.DisableKeepAlives,
  281. DisableCompression: t.DisableCompression,
  282. MaxIdleConns: t.MaxIdleConns,
  283. MaxIdleConnsPerHost: t.MaxIdleConnsPerHost,
  284. MaxConnsPerHost: t.MaxConnsPerHost,
  285. IdleConnTimeout: t.IdleConnTimeout,
  286. ResponseHeaderTimeout: t.ResponseHeaderTimeout,
  287. ExpectContinueTimeout: t.ExpectContinueTimeout,
  288. ProxyConnectHeader: t.ProxyConnectHeader.Clone(),
  289. GetProxyConnectHeader: t.GetProxyConnectHeader,
  290. MaxResponseHeaderBytes: t.MaxResponseHeaderBytes,
  291. ForceAttemptHTTP2: t.ForceAttemptHTTP2,
  292. WriteBufferSize: t.WriteBufferSize,
  293. ReadBufferSize: t.ReadBufferSize,
  294. }
  295. if t.TLSClientConfig != nil {
  296. t2.TLSClientConfig = t.TLSClientConfig.Clone()
  297. }
  298. if !t.tlsNextProtoWasNil {
  299. npm := map[string]func(authority string, c *tls.Conn) RoundTripper{}
  300. for k, v := range t.TLSNextProto {
  301. npm[k] = v
  302. }
  303. t2.TLSNextProto = npm
  304. }
  305. return t2
  306. }
  307. // h2Transport is the interface we expect to be able to call from
  308. // net/http against an *http2.Transport that's either bundled into
  309. // h2_bundle.go or supplied by the user via x/net/http2.
  310. //
  311. // We name it with the "h2" prefix to stay out of the "http2" prefix
  312. // namespace used by x/tools/cmd/bundle for h2_bundle.go.
  313. type h2Transport interface {
  314. CloseIdleConnections()
  315. }
  316. func (t *Transport) hasCustomTLSDialer() bool {
  317. return t.DialTLS != nil || t.DialTLSContext != nil
  318. }
  319. // onceSetNextProtoDefaults initializes TLSNextProto.
  320. // It must be called via t.nextProtoOnce.Do.
  321. func (t *Transport) onceSetNextProtoDefaults() {
  322. t.tlsNextProtoWasNil = (t.TLSNextProto == nil)
  323. if godebug.Get("http2client") == "0" {
  324. return
  325. }
  326. // If they've already configured http2 with
  327. // golang.org/x/net/http2 instead of the bundled copy, try to
  328. // get at its http2.Transport value (via the "https"
  329. // altproto map) so we can call CloseIdleConnections on it if
  330. // requested. (Issue 22891)
  331. altProto, _ := t.altProto.Load().(map[string]RoundTripper)
  332. if rv := reflect.ValueOf(altProto["https"]); rv.IsValid() && rv.Type().Kind() == reflect.Struct && rv.Type().NumField() == 1 {
  333. if v := rv.Field(0); v.CanInterface() {
  334. if h2i, ok := v.Interface().(h2Transport); ok {
  335. t.h2transport = h2i
  336. return
  337. }
  338. }
  339. }
  340. if t.TLSNextProto != nil {
  341. // This is the documented way to disable http2 on a
  342. // Transport.
  343. return
  344. }
  345. if !t.ForceAttemptHTTP2 && (t.TLSClientConfig != nil || t.Dial != nil || t.DialContext != nil || t.hasCustomTLSDialer()) {
  346. // Be conservative and don't automatically enable
  347. // http2 if they've specified a custom TLS config or
  348. // custom dialers. Let them opt-in themselves via
  349. // http2.ConfigureTransport so we don't surprise them
  350. // by modifying their tls.Config. Issue 14275.
  351. // However, if ForceAttemptHTTP2 is true, it overrides the above checks.
  352. return
  353. }
  354. if omitBundledHTTP2 {
  355. return
  356. }
  357. t2, err := http2configureTransports(t)
  358. if err != nil {
  359. log.Printf("Error enabling Transport HTTP/2 support: %v", err)
  360. return
  361. }
  362. t.h2transport = t2
  363. // Auto-configure the http2.Transport's MaxHeaderListSize from
  364. // the http.Transport's MaxResponseHeaderBytes. They don't
  365. // exactly mean the same thing, but they're close.
  366. //
  367. // TODO: also add this to x/net/http2.Configure Transport, behind
  368. // a +build go1.7 build tag:
  369. if limit1 := t.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 {
  370. const h2max = 1<<32 - 1
  371. if limit1 >= h2max {
  372. t2.MaxHeaderListSize = h2max
  373. } else {
  374. t2.MaxHeaderListSize = uint32(limit1)
  375. }
  376. }
  377. }
  378. // ProxyFromEnvironment returns the URL of the proxy to use for a
  379. // given request, as indicated by the environment variables
  380. // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
  381. // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
  382. // requests.
  383. //
  384. // The environment values may be either a complete URL or a
  385. // "host[:port]", in which case the "http" scheme is assumed.
  386. // The schemes "http", "https", and "socks5" are supported.
  387. // An error is returned if the value is a different form.
  388. //
  389. // A nil URL and nil error are returned if no proxy is defined in the
  390. // environment, or a proxy should not be used for the given request,
  391. // as defined by NO_PROXY.
  392. //
  393. // As a special case, if req.URL.Host is "localhost" (with or without
  394. // a port number), then a nil URL and nil error will be returned.
  395. func ProxyFromEnvironment(req *Request) (*url.URL, error) {
  396. return envProxyFunc()(req.URL)
  397. }
  398. // ProxyURL returns a proxy function (for use in a Transport)
  399. // that always returns the same URL.
  400. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
  401. return func(*Request) (*url.URL, error) {
  402. return fixedURL, nil
  403. }
  404. }
  405. // transportRequest is a wrapper around a *Request that adds
  406. // optional extra headers to write and stores any error to return
  407. // from roundTrip.
  408. type transportRequest struct {
  409. *Request // original request, not to be mutated
  410. extra Header // extra headers to write, or nil
  411. trace *httptrace.ClientTrace // optional
  412. cancelKey cancelKey
  413. mu sync.Mutex // guards err
  414. err error // first setError value for mapRoundTripError to consider
  415. }
  416. func (tr *transportRequest) extraHeaders() Header {
  417. if tr.extra == nil {
  418. tr.extra = make(Header)
  419. }
  420. return tr.extra
  421. }
  422. func (tr *transportRequest) setError(err error) {
  423. tr.mu.Lock()
  424. if tr.err == nil {
  425. tr.err = err
  426. }
  427. tr.mu.Unlock()
  428. }
  429. // useRegisteredProtocol reports whether an alternate protocol (as registered
  430. // with Transport.RegisterProtocol) should be respected for this request.
  431. func (t *Transport) useRegisteredProtocol(req *Request) bool {
  432. if req.URL.Scheme == "https" && req.requiresHTTP1() {
  433. // If this request requires HTTP/1, don't use the
  434. // "https" alternate protocol, which is used by the
  435. // HTTP/2 code to take over requests if there's an
  436. // existing cached HTTP/2 connection.
  437. return false
  438. }
  439. return true
  440. }
  441. // alternateRoundTripper returns the alternate RoundTripper to use
  442. // for this request if the Request's URL scheme requires one,
  443. // or nil for the normal case of using the Transport.
  444. func (t *Transport) alternateRoundTripper(req *Request) RoundTripper {
  445. if !t.useRegisteredProtocol(req) {
  446. return nil
  447. }
  448. altProto, _ := t.altProto.Load().(map[string]RoundTripper)
  449. return altProto[req.URL.Scheme]
  450. }
  451. // roundTrip implements a RoundTripper over HTTP.
  452. func (t *Transport) roundTrip(req *Request) (*Response, error) {
  453. t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
  454. ctx := req.Context()
  455. trace := httptrace.ContextClientTrace(ctx)
  456. if req.URL == nil {
  457. req.closeBody()
  458. return nil, errors.New("http: nil Request.URL")
  459. }
  460. if req.Header == nil {
  461. req.closeBody()
  462. return nil, errors.New("http: nil Request.Header")
  463. }
  464. scheme := req.URL.Scheme
  465. isHTTP := scheme == "http" || scheme == "https"
  466. if isHTTP {
  467. for k, vv := range req.Header {
  468. if !httpguts.ValidHeaderFieldName(k) {
  469. req.closeBody()
  470. return nil, fmt.Errorf("net/http: invalid header field name %q", k)
  471. }
  472. for _, v := range vv {
  473. if !httpguts.ValidHeaderFieldValue(v) {
  474. req.closeBody()
  475. return nil, fmt.Errorf("net/http: invalid header field value %q for key %v", v, k)
  476. }
  477. }
  478. }
  479. }
  480. origReq := req
  481. cancelKey := cancelKey{origReq}
  482. req = setupRewindBody(req)
  483. if altRT := t.alternateRoundTripper(req); altRT != nil {
  484. if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol {
  485. return resp, err
  486. }
  487. var err error
  488. req, err = rewindBody(req)
  489. if err != nil {
  490. return nil, err
  491. }
  492. }
  493. if !isHTTP {
  494. req.closeBody()
  495. return nil, badStringError("unsupported protocol scheme", scheme)
  496. }
  497. if req.Method != "" && !validMethod(req.Method) {
  498. req.closeBody()
  499. return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
  500. }
  501. if req.URL.Host == "" {
  502. req.closeBody()
  503. return nil, errors.New("http: no Host in request URL")
  504. }
  505. for {
  506. select {
  507. case <-ctx.Done():
  508. req.closeBody()
  509. return nil, ctx.Err()
  510. default:
  511. }
  512. // treq gets modified by roundTrip, so we need to recreate for each retry.
  513. treq := &transportRequest{Request: req, trace: trace, cancelKey: cancelKey}
  514. cm, err := t.connectMethodForRequest(treq)
  515. if err != nil {
  516. req.closeBody()
  517. return nil, err
  518. }
  519. // Get the cached or newly-created connection to either the
  520. // host (for http or https), the http proxy, or the http proxy
  521. // pre-CONNECTed to https server. In any case, we'll be ready
  522. // to send it requests.
  523. pconn, err := t.getConn(treq, cm)
  524. if err != nil {
  525. t.setReqCanceler(cancelKey, nil)
  526. req.closeBody()
  527. return nil, err
  528. }
  529. var resp *Response
  530. if pconn.alt != nil {
  531. // HTTP/2 path.
  532. t.setReqCanceler(cancelKey, nil) // not cancelable with CancelRequest
  533. resp, err = pconn.alt.RoundTrip(req)
  534. } else {
  535. resp, err = pconn.roundTrip(treq)
  536. }
  537. if err == nil {
  538. resp.Request = origReq
  539. return resp, nil
  540. }
  541. // Failed. Clean up and determine whether to retry.
  542. if http2isNoCachedConnError(err) {
  543. if t.removeIdleConn(pconn) {
  544. t.decConnsPerHost(pconn.cacheKey)
  545. }
  546. } else if !pconn.shouldRetryRequest(req, err) {
  547. // Issue 16465: return underlying net.Conn.Read error from peek,
  548. // as we've historically done.
  549. if e, ok := err.(nothingWrittenError); ok {
  550. err = e.error
  551. }
  552. if e, ok := err.(transportReadFromServerError); ok {
  553. err = e.err
  554. }
  555. return nil, err
  556. }
  557. testHookRoundTripRetried()
  558. // Rewind the body if we're able to.
  559. req, err = rewindBody(req)
  560. if err != nil {
  561. return nil, err
  562. }
  563. }
  564. }
  565. var errCannotRewind = errors.New("net/http: cannot rewind body after connection loss")
  566. type readTrackingBody struct {
  567. io.ReadCloser
  568. didRead bool
  569. didClose bool
  570. }
  571. func (r *readTrackingBody) Read(data []byte) (int, error) {
  572. r.didRead = true
  573. return r.ReadCloser.Read(data)
  574. }
  575. func (r *readTrackingBody) Close() error {
  576. r.didClose = true
  577. return r.ReadCloser.Close()
  578. }
  579. // setupRewindBody returns a new request with a custom body wrapper
  580. // that can report whether the body needs rewinding.
  581. // This lets rewindBody avoid an error result when the request
  582. // does not have GetBody but the body hasn't been read at all yet.
  583. func setupRewindBody(req *Request) *Request {
  584. if req.Body == nil || req.Body == NoBody {
  585. return req
  586. }
  587. newReq := *req
  588. newReq.Body = &readTrackingBody{ReadCloser: req.Body}
  589. return &newReq
  590. }
  591. // rewindBody returns a new request with the body rewound.
  592. // It returns req unmodified if the body does not need rewinding.
  593. // rewindBody takes care of closing req.Body when appropriate
  594. // (in all cases except when rewindBody returns req unmodified).
  595. func rewindBody(req *Request) (rewound *Request, err error) {
  596. if req.Body == nil || req.Body == NoBody || (!req.Body.(*readTrackingBody).didRead && !req.Body.(*readTrackingBody).didClose) {
  597. return req, nil // nothing to rewind
  598. }
  599. if !req.Body.(*readTrackingBody).didClose {
  600. req.closeBody()
  601. }
  602. if req.GetBody == nil {
  603. return nil, errCannotRewind
  604. }
  605. body, err := req.GetBody()
  606. if err != nil {
  607. return nil, err
  608. }
  609. newReq := *req
  610. newReq.Body = &readTrackingBody{ReadCloser: body}
  611. return &newReq, nil
  612. }
  613. // shouldRetryRequest reports whether we should retry sending a failed
  614. // HTTP request on a new connection. The non-nil input error is the
  615. // error from roundTrip.
  616. func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool {
  617. if http2isNoCachedConnError(err) {
  618. // Issue 16582: if the user started a bunch of
  619. // requests at once, they can all pick the same conn
  620. // and violate the server's max concurrent streams.
  621. // Instead, match the HTTP/1 behavior for now and dial
  622. // again to get a new TCP connection, rather than failing
  623. // this request.
  624. return true
  625. }
  626. if err == errMissingHost {
  627. // User error.
  628. return false
  629. }
  630. if !pc.isReused() {
  631. // This was a fresh connection. There's no reason the server
  632. // should've hung up on us.
  633. //
  634. // Also, if we retried now, we could loop forever
  635. // creating new connections and retrying if the server
  636. // is just hanging up on us because it doesn't like
  637. // our request (as opposed to sending an error).
  638. return false
  639. }
  640. if _, ok := err.(nothingWrittenError); ok {
  641. // We never wrote anything, so it's safe to retry, if there's no body or we
  642. // can "rewind" the body with GetBody.
  643. return req.outgoingLength() == 0 || req.GetBody != nil
  644. }
  645. if !req.isReplayable() {
  646. // Don't retry non-idempotent requests.
  647. return false
  648. }
  649. if _, ok := err.(transportReadFromServerError); ok {
  650. // We got some non-EOF net.Conn.Read failure reading
  651. // the 1st response byte from the server.
  652. return true
  653. }
  654. if err == errServerClosedIdle {
  655. // The server replied with io.EOF while we were trying to
  656. // read the response. Probably an unfortunately keep-alive
  657. // timeout, just as the client was writing a request.
  658. return true
  659. }
  660. return false // conservatively
  661. }
  662. // ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
  663. var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
  664. // RegisterProtocol registers a new protocol with scheme.
  665. // The Transport will pass requests using the given scheme to rt.
  666. // It is rt's responsibility to simulate HTTP request semantics.
  667. //
  668. // RegisterProtocol can be used by other packages to provide
  669. // implementations of protocol schemes like "ftp" or "file".
  670. //
  671. // If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will
  672. // handle the RoundTrip itself for that one request, as if the
  673. // protocol were not registered.
  674. func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
  675. t.altMu.Lock()
  676. defer t.altMu.Unlock()
  677. oldMap, _ := t.altProto.Load().(map[string]RoundTripper)
  678. if _, exists := oldMap[scheme]; exists {
  679. panic("protocol " + scheme + " already registered")
  680. }
  681. newMap := make(map[string]RoundTripper)
  682. for k, v := range oldMap {
  683. newMap[k] = v
  684. }
  685. newMap[scheme] = rt
  686. t.altProto.Store(newMap)
  687. }
  688. // CloseIdleConnections closes any connections which were previously
  689. // connected from previous requests but are now sitting idle in
  690. // a "keep-alive" state. It does not interrupt any connections currently
  691. // in use.
  692. func (t *Transport) CloseIdleConnections() {
  693. t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
  694. t.idleMu.Lock()
  695. m := t.idleConn
  696. t.idleConn = nil
  697. t.closeIdle = true // close newly idle connections
  698. t.idleLRU = connLRU{}
  699. t.idleMu.Unlock()
  700. for _, conns := range m {
  701. for _, pconn := range conns {
  702. pconn.close(errCloseIdleConns)
  703. }
  704. }
  705. if t2 := t.h2transport; t2 != nil {
  706. t2.CloseIdleConnections()
  707. }
  708. }
  709. // CancelRequest cancels an in-flight request by closing its connection.
  710. // CancelRequest should only be called after RoundTrip has returned.
  711. //
  712. // Deprecated: Use Request.WithContext to create a request with a
  713. // cancelable context instead. CancelRequest cannot cancel HTTP/2
  714. // requests.
  715. func (t *Transport) CancelRequest(req *Request) {
  716. t.cancelRequest(cancelKey{req}, errRequestCanceled)
  717. }
  718. // Cancel an in-flight request, recording the error value.
  719. // Returns whether the request was canceled.
  720. func (t *Transport) cancelRequest(key cancelKey, err error) bool {
  721. // This function must not return until the cancel func has completed.
  722. // See: https://golang.org/issue/34658
  723. t.reqMu.Lock()
  724. defer t.reqMu.Unlock()
  725. cancel := t.reqCanceler[key]
  726. delete(t.reqCanceler, key)
  727. if cancel != nil {
  728. cancel(err)
  729. }
  730. return cancel != nil
  731. }
  732. //
  733. // Private implementation past this point.
  734. //
  735. var (
  736. // proxyConfigOnce guards proxyConfig
  737. envProxyOnce sync.Once
  738. envProxyFuncValue func(*url.URL) (*url.URL, error)
  739. )
  740. // defaultProxyConfig returns a ProxyConfig value looked up
  741. // from the environment. This mitigates expensive lookups
  742. // on some platforms (e.g. Windows).
  743. func envProxyFunc() func(*url.URL) (*url.URL, error) {
  744. envProxyOnce.Do(func() {
  745. envProxyFuncValue = httpproxy.FromEnvironment().ProxyFunc()
  746. })
  747. return envProxyFuncValue
  748. }
  749. // resetProxyConfig is used by tests.
  750. func resetProxyConfig() {
  751. envProxyOnce = sync.Once{}
  752. envProxyFuncValue = nil
  753. }
  754. func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) {
  755. cm.targetScheme = treq.URL.Scheme
  756. cm.targetAddr = canonicalAddr(treq.URL)
  757. if t.Proxy != nil {
  758. cm.proxyURL, err = t.Proxy(treq.Request)
  759. }
  760. cm.onlyH1 = treq.requiresHTTP1()
  761. return cm, err
  762. }
  763. // proxyAuth returns the Proxy-Authorization header to set
  764. // on requests, if applicable.
  765. func (cm *connectMethod) proxyAuth() string {
  766. if cm.proxyURL == nil {
  767. return ""
  768. }
  769. if u := cm.proxyURL.User; u != nil {
  770. username := u.Username()
  771. password, _ := u.Password()
  772. return "Basic " + basicAuth(username, password)
  773. }
  774. return ""
  775. }
  776. // error values for debugging and testing, not seen by users.
  777. var (
  778. errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
  779. errConnBroken = errors.New("http: putIdleConn: connection is in bad state")
  780. errCloseIdle = errors.New("http: putIdleConn: CloseIdleConnections was called")
  781. errTooManyIdle = errors.New("http: putIdleConn: too many idle connections")
  782. errTooManyIdleHost = errors.New("http: putIdleConn: too many idle connections for host")
  783. errCloseIdleConns = errors.New("http: CloseIdleConnections called")
  784. errReadLoopExiting = errors.New("http: persistConn.readLoop exiting")
  785. errIdleConnTimeout = errors.New("http: idle connection timeout")
  786. // errServerClosedIdle is not seen by users for idempotent requests, but may be
  787. // seen by a user if the server shuts down an idle connection and sends its FIN
  788. // in flight with already-written POST body bytes from the client.
  789. // See https://github.com/golang/go/issues/19943#issuecomment-355607646
  790. errServerClosedIdle = errors.New("http: server closed idle connection")
  791. )
  792. // transportReadFromServerError is used by Transport.readLoop when the
  793. // 1 byte peek read fails and we're actually anticipating a response.
  794. // Usually this is just due to the inherent keep-alive shut down race,
  795. // where the server closed the connection at the same time the client
  796. // wrote. The underlying err field is usually io.EOF or some
  797. // ECONNRESET sort of thing which varies by platform. But it might be
  798. // the user's custom net.Conn.Read error too, so we carry it along for
  799. // them to return from Transport.RoundTrip.
  800. type transportReadFromServerError struct {
  801. err error
  802. }
  803. func (e transportReadFromServerError) Unwrap() error { return e.err }
  804. func (e transportReadFromServerError) Error() string {
  805. return fmt.Sprintf("net/http: Transport failed to read from server: %v", e.err)
  806. }
  807. func (t *Transport) putOrCloseIdleConn(pconn *persistConn) {
  808. if err := t.tryPutIdleConn(pconn); err != nil {
  809. pconn.close(err)
  810. }
  811. }
  812. func (t *Transport) maxIdleConnsPerHost() int {
  813. if v := t.MaxIdleConnsPerHost; v != 0 {
  814. return v
  815. }
  816. return DefaultMaxIdleConnsPerHost
  817. }
  818. // tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
  819. // a new request.
  820. // If pconn is no longer needed or not in a good state, tryPutIdleConn returns
  821. // an error explaining why it wasn't registered.
  822. // tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that.
  823. func (t *Transport) tryPutIdleConn(pconn *persistConn) error {
  824. if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
  825. return errKeepAlivesDisabled
  826. }
  827. if pconn.isBroken() {
  828. return errConnBroken
  829. }
  830. pconn.markReused()
  831. t.idleMu.Lock()
  832. defer t.idleMu.Unlock()
  833. // HTTP/2 (pconn.alt != nil) connections do not come out of the idle list,
  834. // because multiple goroutines can use them simultaneously.
  835. // If this is an HTTP/2 connection being “returned,” we're done.
  836. if pconn.alt != nil && t.idleLRU.m[pconn] != nil {
  837. return nil
  838. }
  839. // Deliver pconn to goroutine waiting for idle connection, if any.
  840. // (They may be actively dialing, but this conn is ready first.
  841. // Chrome calls this socket late binding.
  842. // See https://www.chromium.org/developers/design-documents/network-stack#TOC-Connection-Management.)
  843. key := pconn.cacheKey
  844. if q, ok := t.idleConnWait[key]; ok {
  845. done := false
  846. if pconn.alt == nil {
  847. // HTTP/1.
  848. // Loop over the waiting list until we find a w that isn't done already, and hand it pconn.
  849. for q.len() > 0 {
  850. w := q.popFront()
  851. if w.tryDeliver(pconn, nil) {
  852. done = true
  853. break
  854. }
  855. }
  856. } else {
  857. // HTTP/2.
  858. // Can hand the same pconn to everyone in the waiting list,
  859. // and we still won't be done: we want to put it in the idle
  860. // list unconditionally, for any future clients too.
  861. for q.len() > 0 {
  862. w := q.popFront()
  863. w.tryDeliver(pconn, nil)
  864. }
  865. }
  866. if q.len() == 0 {
  867. delete(t.idleConnWait, key)
  868. } else {
  869. t.idleConnWait[key] = q
  870. }
  871. if done {
  872. return nil
  873. }
  874. }
  875. if t.closeIdle {
  876. return errCloseIdle
  877. }
  878. if t.idleConn == nil {
  879. t.idleConn = make(map[connectMethodKey][]*persistConn)
  880. }
  881. idles := t.idleConn[key]
  882. if len(idles) >= t.maxIdleConnsPerHost() {
  883. return errTooManyIdleHost
  884. }
  885. for _, exist := range idles {
  886. if exist == pconn {
  887. log.Fatalf("dup idle pconn %p in freelist", pconn)
  888. }
  889. }
  890. t.idleConn[key] = append(idles, pconn)
  891. t.idleLRU.add(pconn)
  892. if t.MaxIdleConns != 0 && t.idleLRU.len() > t.MaxIdleConns {
  893. oldest := t.idleLRU.removeOldest()
  894. oldest.close(errTooManyIdle)
  895. t.removeIdleConnLocked(oldest)
  896. }
  897. // Set idle timer, but only for HTTP/1 (pconn.alt == nil).
  898. // The HTTP/2 implementation manages the idle timer itself
  899. // (see idleConnTimeout in h2_bundle.go).
  900. if t.IdleConnTimeout > 0 && pconn.alt == nil {
  901. if pconn.idleTimer != nil {
  902. pconn.idleTimer.Reset(t.IdleConnTimeout)
  903. } else {
  904. pconn.idleTimer = time.AfterFunc(t.IdleConnTimeout, pconn.closeConnIfStillIdle)
  905. }
  906. }
  907. pconn.idleAt = time.Now()
  908. return nil
  909. }
  910. // queueForIdleConn queues w to receive the next idle connection for w.cm.
  911. // As an optimization hint to the caller, queueForIdleConn reports whether
  912. // it successfully delivered an already-idle connection.
  913. func (t *Transport) queueForIdleConn(w *wantConn) (delivered bool) {
  914. if t.DisableKeepAlives {
  915. return false
  916. }
  917. t.idleMu.Lock()
  918. defer t.idleMu.Unlock()
  919. // Stop closing connections that become idle - we might want one.
  920. // (That is, undo the effect of t.CloseIdleConnections.)
  921. t.closeIdle = false
  922. if w == nil {
  923. // Happens in test hook.
  924. return false
  925. }
  926. // If IdleConnTimeout is set, calculate the oldest
  927. // persistConn.idleAt time we're willing to use a cached idle
  928. // conn.
  929. var oldTime time.Time
  930. if t.IdleConnTimeout > 0 {
  931. oldTime = time.Now().Add(-t.IdleConnTimeout)
  932. }
  933. // Look for most recently-used idle connection.
  934. if list, ok := t.idleConn[w.key]; ok {
  935. stop := false
  936. delivered := false
  937. for len(list) > 0 && !stop {
  938. pconn := list[len(list)-1]
  939. // See whether this connection has been idle too long, considering
  940. // only the wall time (the Round(0)), in case this is a laptop or VM
  941. // coming out of suspend with previously cached idle connections.
  942. tooOld := !oldTime.IsZero() && pconn.idleAt.Round(0).Before(oldTime)
  943. if tooOld {
  944. // Async cleanup. Launch in its own goroutine (as if a
  945. // time.AfterFunc called it); it acquires idleMu, which we're
  946. // holding, and does a synchronous net.Conn.Close.
  947. go pconn.closeConnIfStillIdle()
  948. }
  949. if pconn.isBroken() || tooOld {
  950. // If either persistConn.readLoop has marked the connection
  951. // broken, but Transport.removeIdleConn has not yet removed it
  952. // from the idle list, or if this persistConn is too old (it was
  953. // idle too long), then ignore it and look for another. In both
  954. // cases it's already in the process of being closed.
  955. list = list[:len(list)-1]
  956. continue
  957. }
  958. delivered = w.tryDeliver(pconn, nil)
  959. if delivered {
  960. if pconn.alt != nil {
  961. // HTTP/2: multiple clients can share pconn.
  962. // Leave it in the list.
  963. } else {
  964. // HTTP/1: only one client can use pconn.
  965. // Remove it from the list.
  966. t.idleLRU.remove(pconn)
  967. list = list[:len(list)-1]
  968. }
  969. }
  970. stop = true
  971. }
  972. if len(list) > 0 {
  973. t.idleConn[w.key] = list
  974. } else {
  975. delete(t.idleConn, w.key)
  976. }
  977. if stop {
  978. return delivered
  979. }
  980. }
  981. // Register to receive next connection that becomes idle.
  982. if t.idleConnWait == nil {
  983. t.idleConnWait = make(map[connectMethodKey]wantConnQueue)
  984. }
  985. q := t.idleConnWait[w.key]
  986. q.cleanFront()
  987. q.pushBack(w)
  988. t.idleConnWait[w.key] = q
  989. return false
  990. }
  991. // removeIdleConn marks pconn as dead.
  992. func (t *Transport) removeIdleConn(pconn *persistConn) bool {
  993. t.idleMu.Lock()
  994. defer t.idleMu.Unlock()
  995. return t.removeIdleConnLocked(pconn)
  996. }
  997. // t.idleMu must be held.
  998. func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool {
  999. if pconn.idleTimer != nil {
  1000. pconn.idleTimer.Stop()
  1001. }
  1002. t.idleLRU.remove(pconn)
  1003. key := pconn.cacheKey
  1004. pconns := t.idleConn[key]
  1005. var removed bool
  1006. switch len(pconns) {
  1007. case 0:
  1008. // Nothing
  1009. case 1:
  1010. if pconns[0] == pconn {
  1011. delete(t.idleConn, key)
  1012. removed = true
  1013. }
  1014. default:
  1015. for i, v := range pconns {
  1016. if v != pconn {
  1017. continue
  1018. }
  1019. // Slide down, keeping most recently-used
  1020. // conns at the end.
  1021. copy(pconns[i:], pconns[i+1:])
  1022. t.idleConn[key] = pconns[:len(pconns)-1]
  1023. removed = true
  1024. break
  1025. }
  1026. }
  1027. return removed
  1028. }
  1029. func (t *Transport) setReqCanceler(key cancelKey, fn func(error)) {
  1030. t.reqMu.Lock()
  1031. defer t.reqMu.Unlock()
  1032. if t.reqCanceler == nil {
  1033. t.reqCanceler = make(map[cancelKey]func(error))
  1034. }
  1035. if fn != nil {
  1036. t.reqCanceler[key] = fn
  1037. } else {
  1038. delete(t.reqCanceler, key)
  1039. }
  1040. }
  1041. // replaceReqCanceler replaces an existing cancel function. If there is no cancel function
  1042. // for the request, we don't set the function and return false.
  1043. // Since CancelRequest will clear the canceler, we can use the return value to detect if
  1044. // the request was canceled since the last setReqCancel call.
  1045. func (t *Transport) replaceReqCanceler(key cancelKey, fn func(error)) bool {
  1046. t.reqMu.Lock()
  1047. defer t.reqMu.Unlock()
  1048. _, ok := t.reqCanceler[key]
  1049. if !ok {
  1050. return false
  1051. }
  1052. if fn != nil {
  1053. t.reqCanceler[key] = fn
  1054. } else {
  1055. delete(t.reqCanceler, key)
  1056. }
  1057. return true
  1058. }
  1059. var zeroDialer net.Dialer
  1060. func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error) {
  1061. if t.DialContext != nil {
  1062. return t.DialContext(ctx, network, addr)
  1063. }
  1064. if t.Dial != nil {
  1065. c, err := t.Dial(network, addr)
  1066. if c == nil && err == nil {
  1067. err = errors.New("net/http: Transport.Dial hook returned (nil, nil)")
  1068. }
  1069. return c, err
  1070. }
  1071. return zeroDialer.DialContext(ctx, network, addr)
  1072. }
  1073. // A wantConn records state about a wanted connection
  1074. // (that is, an active call to getConn).
  1075. // The conn may be gotten by dialing or by finding an idle connection,
  1076. // or a cancellation may make the conn no longer wanted.
  1077. // These three options are racing against each other and use
  1078. // wantConn to coordinate and agree about the winning outcome.
  1079. type wantConn struct {
  1080. cm connectMethod
  1081. key connectMethodKey // cm.key()
  1082. ctx context.Context // context for dial
  1083. ready chan struct{} // closed when pc, err pair is delivered
  1084. // hooks for testing to know when dials are done
  1085. // beforeDial is called in the getConn goroutine when the dial is queued.
  1086. // afterDial is called when the dial is completed or canceled.
  1087. beforeDial func()
  1088. afterDial func()
  1089. mu sync.Mutex // protects pc, err, close(ready)
  1090. pc *persistConn
  1091. err error
  1092. }
  1093. // waiting reports whether w is still waiting for an answer (connection or error).
  1094. func (w *wantConn) waiting() bool {
  1095. select {
  1096. case <-w.ready:
  1097. return false
  1098. default:
  1099. return true
  1100. }
  1101. }
  1102. // tryDeliver attempts to deliver pc, err to w and reports whether it succeeded.
  1103. func (w *wantConn) tryDeliver(pc *persistConn, err error) bool {
  1104. w.mu.Lock()
  1105. defer w.mu.Unlock()
  1106. if w.pc != nil || w.err != nil {
  1107. return false
  1108. }
  1109. w.pc = pc
  1110. w.err = err
  1111. if w.pc == nil && w.err == nil {
  1112. panic("net/http: internal error: misuse of tryDeliver")
  1113. }
  1114. close(w.ready)
  1115. return true
  1116. }
  1117. // cancel marks w as no longer wanting a result (for example, due to cancellation).
  1118. // If a connection has been delivered already, cancel returns it with t.putOrCloseIdleConn.
  1119. func (w *wantConn) cancel(t *Transport, err error) {
  1120. w.mu.Lock()
  1121. if w.pc == nil && w.err == nil {
  1122. close(w.ready) // catch misbehavior in future delivery
  1123. }
  1124. pc := w.pc
  1125. w.pc = nil
  1126. w.err = err
  1127. w.mu.Unlock()
  1128. if pc != nil {
  1129. t.putOrCloseIdleConn(pc)
  1130. }
  1131. }
  1132. // A wantConnQueue is a queue of wantConns.
  1133. type wantConnQueue struct {
  1134. // This is a queue, not a deque.
  1135. // It is split into two stages - head[headPos:] and tail.
  1136. // popFront is trivial (headPos++) on the first stage, and
  1137. // pushBack is trivial (append) on the second stage.
  1138. // If the first stage is empty, popFront can swap the
  1139. // first and second stages to remedy the situation.
  1140. //
  1141. // This two-stage split is analogous to the use of two lists
  1142. // in Okasaki's purely functional queue but without the
  1143. // overhead of reversing the list when swapping stages.
  1144. head []*wantConn
  1145. headPos int
  1146. tail []*wantConn
  1147. }
  1148. // len returns the number of items in the queue.
  1149. func (q *wantConnQueue) len() int {
  1150. return len(q.head) - q.headPos + len(q.tail)
  1151. }
  1152. // pushBack adds w to the back of the queue.
  1153. func (q *wantConnQueue) pushBack(w *wantConn) {
  1154. q.tail = append(q.tail, w)
  1155. }
  1156. // popFront removes and returns the wantConn at the front of the queue.
  1157. func (q *wantConnQueue) popFront() *wantConn {
  1158. if q.headPos >= len(q.head) {
  1159. if len(q.tail) == 0 {
  1160. return nil
  1161. }
  1162. // Pick up tail as new head, clear tail.
  1163. q.head, q.headPos, q.tail = q.tail, 0, q.head[:0]
  1164. }
  1165. w := q.head[q.headPos]
  1166. q.head[q.headPos] = nil
  1167. q.headPos++
  1168. return w
  1169. }
  1170. // peekFront returns the wantConn at the front of the queue without removing it.
  1171. func (q *wantConnQueue) peekFront() *wantConn {
  1172. if q.headPos < len(q.head) {
  1173. return q.head[q.headPos]
  1174. }
  1175. if len(q.tail) > 0 {
  1176. return q.tail[0]
  1177. }
  1178. return nil
  1179. }
  1180. // cleanFront pops any wantConns that are no longer waiting from the head of the
  1181. // queue, reporting whether any were popped.
  1182. func (q *wantConnQueue) cleanFront() (cleaned bool) {
  1183. for {
  1184. w := q.peekFront()
  1185. if w == nil || w.waiting() {
  1186. return cleaned
  1187. }
  1188. q.popFront()
  1189. cleaned = true
  1190. }
  1191. }
  1192. func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error) {
  1193. if t.DialTLSContext != nil {
  1194. conn, err = t.DialTLSContext(ctx, network, addr)
  1195. } else {
  1196. conn, err = t.DialTLS(network, addr)
  1197. }
  1198. if conn == nil && err == nil {
  1199. err = errors.New("net/http: Transport.DialTLS or DialTLSContext returned (nil, nil)")
  1200. }
  1201. return
  1202. }
  1203. // getConn dials and creates a new persistConn to the target as
  1204. // specified in the connectMethod. This includes doing a proxy CONNECT
  1205. // and/or setting up TLS. If this doesn't return an error, the persistConn
  1206. // is ready to write requests to.
  1207. func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error) {
  1208. req := treq.Request
  1209. trace := treq.trace
  1210. ctx := req.Context()
  1211. if trace != nil && trace.GetConn != nil {
  1212. trace.GetConn(cm.addr())
  1213. }
  1214. w := &wantConn{
  1215. cm: cm,
  1216. key: cm.key(),
  1217. ctx: ctx,
  1218. ready: make(chan struct{}, 1),
  1219. beforeDial: testHookPrePendingDial,
  1220. afterDial: testHookPostPendingDial,
  1221. }
  1222. defer func() {
  1223. if err != nil {
  1224. w.cancel(t, err)
  1225. }
  1226. }()
  1227. // Queue for idle connection.
  1228. if delivered := t.queueForIdleConn(w); delivered {
  1229. pc := w.pc
  1230. // Trace only for HTTP/1.
  1231. // HTTP/2 calls trace.GotConn itself.
  1232. if pc.alt == nil && trace != nil && trace.GotConn != nil {
  1233. trace.GotConn(pc.gotIdleConnTrace(pc.idleAt))
  1234. }
  1235. // set request canceler to some non-nil function so we
  1236. // can detect whether it was cleared between now and when
  1237. // we enter roundTrip
  1238. t.setReqCanceler(treq.cancelKey, func(error) {})
  1239. return pc, nil
  1240. }
  1241. cancelc := make(chan error, 1)
  1242. t.setReqCanceler(treq.cancelKey, func(err error) { cancelc <- err })
  1243. // Queue for permission to dial.
  1244. t.queueForDial(w)
  1245. // Wait for completion or cancellation.
  1246. select {
  1247. case <-w.ready:
  1248. // Trace success but only for HTTP/1.
  1249. // HTTP/2 calls trace.GotConn itself.
  1250. if w.pc != nil && w.pc.alt == nil && trace != nil && trace.GotConn != nil {
  1251. trace.GotConn(httptrace.GotConnInfo{Conn: w.pc.conn, Reused: w.pc.isReused()})
  1252. }
  1253. if w.err != nil {
  1254. // If the request has been canceled, that's probably
  1255. // what caused w.err; if so, prefer to return the
  1256. // cancellation error (see golang.org/issue/16049).
  1257. select {
  1258. case <-req.Cancel:
  1259. return nil, errRequestCanceledConn
  1260. case <-req.Context().Done():
  1261. return nil, req.Context().Err()
  1262. case err := <-cancelc:
  1263. if err == errRequestCanceled {
  1264. err = errRequestCanceledConn
  1265. }
  1266. return nil, err
  1267. default:
  1268. // return below
  1269. }
  1270. }
  1271. return w.pc, w.err
  1272. case <-req.Cancel:
  1273. return nil, errRequestCanceledConn
  1274. case <-req.Context().Done():
  1275. return nil, req.Context().Err()
  1276. case err := <-cancelc:
  1277. if err == errRequestCanceled {
  1278. err = errRequestCanceledConn
  1279. }
  1280. return nil, err
  1281. }
  1282. }
  1283. // queueForDial queues w to wait for permission to begin dialing.
  1284. // Once w receives permission to dial, it will do so in a separate goroutine.
  1285. func (t *Transport) queueForDial(w *wantConn) {
  1286. w.beforeDial()
  1287. if t.MaxConnsPerHost <= 0 {
  1288. go t.dialConnFor(w)
  1289. return
  1290. }
  1291. t.connsPerHostMu.Lock()
  1292. defer t.connsPerHostMu.Unlock()
  1293. if n := t.connsPerHost[w.key]; n < t.MaxConnsPerHost {
  1294. if t.connsPerHost == nil {
  1295. t.connsPerHost = make(map[connectMethodKey]int)
  1296. }
  1297. t.connsPerHost[w.key] = n + 1
  1298. go t.dialConnFor(w)
  1299. return
  1300. }
  1301. if t.connsPerHostWait == nil {
  1302. t.connsPerHostWait = make(map[connectMethodKey]wantConnQueue)
  1303. }
  1304. q := t.connsPerHostWait[w.key]
  1305. q.cleanFront()
  1306. q.pushBack(w)
  1307. t.connsPerHostWait[w.key] = q
  1308. }
  1309. // dialConnFor dials on behalf of w and delivers the result to w.
  1310. // dialConnFor has received permission to dial w.cm and is counted in t.connCount[w.cm.key()].
  1311. // If the dial is canceled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()].
  1312. func (t *Transport) dialConnFor(w *wantConn) {
  1313. defer w.afterDial()
  1314. pc, err := t.dialConn(w.ctx, w.cm)
  1315. delivered := w.tryDeliver(pc, err)
  1316. if err == nil && (!delivered || pc.alt != nil) {
  1317. // pconn was not passed to w,
  1318. // or it is HTTP/2 and can be shared.
  1319. // Add to the idle connection pool.
  1320. t.putOrCloseIdleConn(pc)
  1321. }
  1322. if err != nil {
  1323. t.decConnsPerHost(w.key)
  1324. }
  1325. }
  1326. // decConnsPerHost decrements the per-host connection count for key,
  1327. // which may in turn give a different waiting goroutine permission to dial.
  1328. func (t *Transport) decConnsPerHost(key connectMethodKey) {
  1329. if t.MaxConnsPerHost <= 0 {
  1330. return
  1331. }
  1332. t.connsPerHostMu.Lock()
  1333. defer t.connsPerHostMu.Unlock()
  1334. n := t.connsPerHost[key]
  1335. if n == 0 {
  1336. // Shouldn't happen, but if it does, the counting is buggy and could
  1337. // easily lead to a silent deadlock, so report the problem loudly.
  1338. panic("net/http: internal error: connCount underflow")
  1339. }
  1340. // Can we hand this count to a goroutine still waiting to dial?
  1341. // (Some goroutines on the wait list may have timed out or
  1342. // gotten a connection another way. If they're all gone,
  1343. // we don't want to kick off any spurious dial operations.)
  1344. if q := t.connsPerHostWait[key]; q.len() > 0 {
  1345. done := false
  1346. for q.len() > 0 {
  1347. w := q.popFront()
  1348. if w.waiting() {
  1349. go t.dialConnFor(w)
  1350. done = true
  1351. break
  1352. }
  1353. }
  1354. if q.len() == 0 {
  1355. delete(t.connsPerHostWait, key)
  1356. } else {
  1357. // q is a value (like a slice), so we have to store
  1358. // the updated q back into the map.
  1359. t.connsPerHostWait[key] = q
  1360. }
  1361. if done {
  1362. return
  1363. }
  1364. }
  1365. // Otherwise, decrement the recorded count.
  1366. if n--; n == 0 {
  1367. delete(t.connsPerHost, key)
  1368. } else {
  1369. t.connsPerHost[key] = n
  1370. }
  1371. }
  1372. // Add TLS to a persistent connection, i.e. negotiate a TLS session. If pconn is already a TLS
  1373. // tunnel, this function establishes a nested TLS session inside the encrypted channel.
  1374. // The remote endpoint's name may be overridden by TLSClientConfig.ServerName.
  1375. func (pconn *persistConn) addTLS(ctx context.Context, name string, trace *httptrace.ClientTrace) error {
  1376. // Initiate TLS and check remote host name against certificate.
  1377. cfg := cloneTLSConfig(pconn.t.TLSClientConfig)
  1378. if cfg.ServerName == "" {
  1379. cfg.ServerName = name
  1380. }
  1381. if pconn.cacheKey.onlyH1 {
  1382. cfg.NextProtos = nil
  1383. }
  1384. plainConn := pconn.conn
  1385. tlsConn := tls.Client(plainConn, cfg)
  1386. errc := make(chan error, 2)
  1387. var timer *time.Timer // for canceling TLS handshake
  1388. if d := pconn.t.TLSHandshakeTimeout; d != 0 {
  1389. timer = time.AfterFunc(d, func() {
  1390. errc <- tlsHandshakeTimeoutError{}
  1391. })
  1392. }
  1393. go func() {
  1394. if trace != nil && trace.TLSHandshakeStart != nil {
  1395. trace.TLSHandshakeStart()
  1396. }
  1397. err := tlsConn.HandshakeContext(ctx)
  1398. if timer != nil {
  1399. timer.Stop()
  1400. }
  1401. errc <- err
  1402. }()
  1403. if err := <-errc; err != nil {
  1404. plainConn.Close()
  1405. if trace != nil && trace.TLSHandshakeDone != nil {
  1406. trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1407. }
  1408. return err
  1409. }
  1410. cs := tlsConn.ConnectionState()
  1411. if trace != nil && trace.TLSHandshakeDone != nil {
  1412. trace.TLSHandshakeDone(cs, nil)
  1413. }
  1414. pconn.tlsState = &cs
  1415. pconn.conn = tlsConn
  1416. return nil
  1417. }
  1418. type erringRoundTripper interface {
  1419. RoundTripErr() error
  1420. }
  1421. func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error) {
  1422. pconn = &persistConn{
  1423. t: t,
  1424. cacheKey: cm.key(),
  1425. reqch: make(chan requestAndChan, 1),
  1426. writech: make(chan writeRequest, 1),
  1427. closech: make(chan struct{}),
  1428. writeErrCh: make(chan error, 1),
  1429. writeLoopDone: make(chan struct{}),
  1430. }
  1431. trace := httptrace.ContextClientTrace(ctx)
  1432. wrapErr := func(err error) error {
  1433. if cm.proxyURL != nil {
  1434. // Return a typed error, per Issue 16997
  1435. return &net.OpError{Op: "proxyconnect", Net: "tcp", Err: err}
  1436. }
  1437. return err
  1438. }
  1439. if cm.scheme() == "https" && t.hasCustomTLSDialer() {
  1440. var err error
  1441. pconn.conn, err = t.customDialTLS(ctx, "tcp", cm.addr())
  1442. if err != nil {
  1443. return nil, wrapErr(err)
  1444. }
  1445. if tc, ok := pconn.conn.(*tls.Conn); ok {
  1446. // Handshake here, in case DialTLS didn't. TLSNextProto below
  1447. // depends on it for knowing the connection state.
  1448. if trace != nil && trace.TLSHandshakeStart != nil {
  1449. trace.TLSHandshakeStart()
  1450. }
  1451. if err := tc.HandshakeContext(ctx); err != nil {
  1452. go pconn.conn.Close()
  1453. if trace != nil && trace.TLSHandshakeDone != nil {
  1454. trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1455. }
  1456. return nil, err
  1457. }
  1458. cs := tc.ConnectionState()
  1459. if trace != nil && trace.TLSHandshakeDone != nil {
  1460. trace.TLSHandshakeDone(cs, nil)
  1461. }
  1462. pconn.tlsState = &cs
  1463. }
  1464. } else {
  1465. conn, err := t.dial(ctx, "tcp", cm.addr())
  1466. if err != nil {
  1467. return nil, wrapErr(err)
  1468. }
  1469. pconn.conn = conn
  1470. if cm.scheme() == "https" {
  1471. var firstTLSHost string
  1472. if firstTLSHost, _, err = net.SplitHostPort(cm.addr()); err != nil {
  1473. return nil, wrapErr(err)
  1474. }
  1475. if err = pconn.addTLS(ctx, firstTLSHost, trace); err != nil {
  1476. return nil, wrapErr(err)
  1477. }
  1478. }
  1479. }
  1480. // Proxy setup.
  1481. switch {
  1482. case cm.proxyURL == nil:
  1483. // Do nothing. Not using a proxy.
  1484. case cm.proxyURL.Scheme == "socks5":
  1485. conn := pconn.conn
  1486. d := socksNewDialer("tcp", conn.RemoteAddr().String())
  1487. if u := cm.proxyURL.User; u != nil {
  1488. auth := &socksUsernamePassword{
  1489. Username: u.Username(),
  1490. }
  1491. auth.Password, _ = u.Password()
  1492. d.AuthMethods = []socksAuthMethod{
  1493. socksAuthMethodNotRequired,
  1494. socksAuthMethodUsernamePassword,
  1495. }
  1496. d.Authenticate = auth.Authenticate
  1497. }
  1498. if _, err := d.DialWithConn(ctx, conn, "tcp", cm.targetAddr); err != nil {
  1499. conn.Close()
  1500. return nil, err
  1501. }
  1502. case cm.targetScheme == "http":
  1503. pconn.isProxy = true
  1504. if pa := cm.proxyAuth(); pa != "" {
  1505. pconn.mutateHeaderFunc = func(h Header) {
  1506. h.Set("Proxy-Authorization", pa)
  1507. }
  1508. }
  1509. case cm.targetScheme == "https":
  1510. conn := pconn.conn
  1511. var hdr Header
  1512. if t.GetProxyConnectHeader != nil {
  1513. var err error
  1514. hdr, err = t.GetProxyConnectHeader(ctx, cm.proxyURL, cm.targetAddr)
  1515. if err != nil {
  1516. conn.Close()
  1517. return nil, err
  1518. }
  1519. } else {
  1520. hdr = t.ProxyConnectHeader
  1521. }
  1522. if hdr == nil {
  1523. hdr = make(Header)
  1524. }
  1525. if pa := cm.proxyAuth(); pa != "" {
  1526. hdr = hdr.Clone()
  1527. hdr.Set("Proxy-Authorization", pa)
  1528. }
  1529. connectReq := &Request{
  1530. Method: "CONNECT",
  1531. URL: &url.URL{Opaque: cm.targetAddr},
  1532. Host: cm.targetAddr,
  1533. Header: hdr,
  1534. }
  1535. // If there's no done channel (no deadline or cancellation
  1536. // from the caller possible), at least set some (long)
  1537. // timeout here. This will make sure we don't block forever
  1538. // and leak a goroutine if the connection stops replying
  1539. // after the TCP connect.
  1540. connectCtx := ctx
  1541. if ctx.Done() == nil {
  1542. newCtx, cancel := context.WithTimeout(ctx, 1*time.Minute)
  1543. defer cancel()
  1544. connectCtx = newCtx
  1545. }
  1546. didReadResponse := make(chan struct{}) // closed after CONNECT write+read is done or fails
  1547. var (
  1548. resp *Response
  1549. err error // write or read error
  1550. )
  1551. // Write the CONNECT request & read the response.
  1552. go func() {
  1553. defer close(didReadResponse)
  1554. err = connectReq.Write(conn)
  1555. if err != nil {
  1556. return
  1557. }
  1558. // Okay to use and discard buffered reader here, because
  1559. // TLS server will not speak until spoken to.
  1560. br := bufio.NewReader(conn)
  1561. resp, err = ReadResponse(br, connectReq)
  1562. }()
  1563. select {
  1564. case <-connectCtx.Done():
  1565. conn.Close()
  1566. <-didReadResponse
  1567. return nil, connectCtx.Err()
  1568. case <-didReadResponse:
  1569. // resp or err now set
  1570. }
  1571. if err != nil {
  1572. conn.Close()
  1573. return nil, err
  1574. }
  1575. if resp.StatusCode != 200 {
  1576. _, text, ok := strings.Cut(resp.Status, " ")
  1577. conn.Close()
  1578. if !ok {
  1579. return nil, errors.New("unknown status code")
  1580. }
  1581. return nil, errors.New(text)
  1582. }
  1583. }
  1584. if cm.proxyURL != nil && cm.targetScheme == "https" {
  1585. if err := pconn.addTLS(ctx, cm.tlsHost(), trace); err != nil {
  1586. return nil, err
  1587. }
  1588. }
  1589. if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" {
  1590. if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; ok {
  1591. alt := next(cm.targetAddr, pconn.conn.(*tls.Conn))
  1592. if e, ok := alt.(erringRoundTripper); ok {
  1593. // pconn.conn was closed by next (http2configureTransports.upgradeFn).
  1594. return nil, e.RoundTripErr()
  1595. }
  1596. return &persistConn{t: t, cacheKey: pconn.cacheKey, alt: alt}, nil
  1597. }
  1598. }
  1599. pconn.br = bufio.NewReaderSize(pconn, t.readBufferSize())
  1600. pconn.bw = bufio.NewWriterSize(persistConnWriter{pconn}, t.writeBufferSize())
  1601. go pconn.readLoop()
  1602. go pconn.writeLoop()
  1603. return pconn, nil
  1604. }
  1605. // persistConnWriter is the io.Writer written to by pc.bw.
  1606. // It accumulates the number of bytes written to the underlying conn,
  1607. // so the retry logic can determine whether any bytes made it across
  1608. // the wire.
  1609. // This is exactly 1 pointer field wide so it can go into an interface
  1610. // without allocation.
  1611. type persistConnWriter struct {
  1612. pc *persistConn
  1613. }
  1614. func (w persistConnWriter) Write(p []byte) (n int, err error) {
  1615. n, err = w.pc.conn.Write(p)
  1616. w.pc.nwrite += int64(n)
  1617. return
  1618. }
  1619. // ReadFrom exposes persistConnWriter's underlying Conn to io.Copy and if
  1620. // the Conn implements io.ReaderFrom, it can take advantage of optimizations
  1621. // such as sendfile.
  1622. func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error) {
  1623. n, err = io.Copy(w.pc.conn, r)
  1624. w.pc.nwrite += n
  1625. return
  1626. }
  1627. var _ io.ReaderFrom = (*persistConnWriter)(nil)
  1628. // connectMethod is the map key (in its String form) for keeping persistent
  1629. // TCP connections alive for subsequent HTTP requests.
  1630. //
  1631. // A connect method may be of the following types:
  1632. //
  1633. // connectMethod.key().String() Description
  1634. // ------------------------------ -------------------------
  1635. // |http|foo.com http directly to server, no proxy
  1636. // |https|foo.com https directly to server, no proxy
  1637. // |https,h1|foo.com https directly to server w/o HTTP/2, no proxy
  1638. // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com
  1639. // http://proxy.com|http http to proxy, http to anywhere after that
  1640. // socks5://proxy.com|http|foo.com socks5 to proxy, then http to foo.com
  1641. // socks5://proxy.com|https|foo.com socks5 to proxy, then https to foo.com
  1642. // https://proxy.com|https|foo.com https to proxy, then CONNECT to foo.com
  1643. // https://proxy.com|http https to proxy, http to anywhere after that
  1644. //
  1645. type connectMethod struct {
  1646. _ incomparable
  1647. proxyURL *url.URL // nil for no proxy, else full proxy URL
  1648. targetScheme string // "http" or "https"
  1649. // If proxyURL specifies an http or https proxy, and targetScheme is http (not https),
  1650. // then targetAddr is not included in the connect method key, because the socket can
  1651. // be reused for different targetAddr values.
  1652. targetAddr string
  1653. onlyH1 bool // whether to disable HTTP/2 and force HTTP/1
  1654. }
  1655. func (cm *connectMethod) key() connectMethodKey {
  1656. proxyStr := ""
  1657. targetAddr := cm.targetAddr
  1658. if cm.proxyURL != nil {
  1659. proxyStr = cm.proxyURL.String()
  1660. if (cm.proxyURL.Scheme == "http" || cm.proxyURL.Scheme == "https") && cm.targetScheme == "http" {
  1661. targetAddr = ""
  1662. }
  1663. }
  1664. return connectMethodKey{
  1665. proxy: proxyStr,
  1666. scheme: cm.targetScheme,
  1667. addr: targetAddr,
  1668. onlyH1: cm.onlyH1,
  1669. }
  1670. }
  1671. // scheme returns the first hop scheme: http, https, or socks5
  1672. func (cm *connectMethod) scheme() string {
  1673. if cm.proxyURL != nil {
  1674. return cm.proxyURL.Scheme
  1675. }
  1676. return cm.targetScheme
  1677. }
  1678. // addr returns the first hop "host:port" to which we need to TCP connect.
  1679. func (cm *connectMethod) addr() string {
  1680. if cm.proxyURL != nil {
  1681. return canonicalAddr(cm.proxyURL)
  1682. }
  1683. return cm.targetAddr
  1684. }
  1685. // tlsHost returns the host name to match against the peer's
  1686. // TLS certificate.
  1687. func (cm *connectMethod) tlsHost() string {
  1688. h := cm.targetAddr
  1689. if hasPort(h) {
  1690. h = h[:strings.LastIndex(h, ":")]
  1691. }
  1692. return h
  1693. }
  1694. // connectMethodKey is the map key version of connectMethod, with a
  1695. // stringified proxy URL (or the empty string) instead of a pointer to
  1696. // a URL.
  1697. type connectMethodKey struct {
  1698. proxy, scheme, addr string
  1699. onlyH1 bool
  1700. }
  1701. func (k connectMethodKey) String() string {
  1702. // Only used by tests.
  1703. var h1 string
  1704. if k.onlyH1 {
  1705. h1 = ",h1"
  1706. }
  1707. return fmt.Sprintf("%s|%s%s|%s", k.proxy, k.scheme, h1, k.addr)
  1708. }
  1709. // persistConn wraps a connection, usually a persistent one
  1710. // (but may be used for non-keep-alive requests as well)
  1711. type persistConn struct {
  1712. // alt optionally specifies the TLS NextProto RoundTripper.
  1713. // This is used for HTTP/2 today and future protocols later.
  1714. // If it's non-nil, the rest of the fields are unused.
  1715. alt RoundTripper
  1716. t *Transport
  1717. cacheKey connectMethodKey
  1718. conn net.Conn
  1719. tlsState *tls.ConnectionState
  1720. br *bufio.Reader // from conn
  1721. bw *bufio.Writer // to conn
  1722. nwrite int64 // bytes written
  1723. reqch chan requestAndChan // written by roundTrip; read by readLoop
  1724. writech chan writeRequest // written by roundTrip; read by writeLoop
  1725. closech chan struct{} // closed when conn closed
  1726. isProxy bool
  1727. sawEOF bool // whether we've seen EOF from conn; owned by readLoop
  1728. readLimit int64 // bytes allowed to be read; owned by readLoop
  1729. // writeErrCh passes the request write error (usually nil)
  1730. // from the writeLoop goroutine to the readLoop which passes
  1731. // it off to the res.Body reader, which then uses it to decide
  1732. // whether or not a connection can be reused. Issue 7569.
  1733. writeErrCh chan error
  1734. writeLoopDone chan struct{} // closed when write loop ends
  1735. // Both guarded by Transport.idleMu:
  1736. idleAt time.Time // time it last become idle
  1737. idleTimer *time.Timer // holding an AfterFunc to close it
  1738. mu sync.Mutex // guards following fields
  1739. numExpectedResponses int
  1740. closed error // set non-nil when conn is closed, before closech is closed
  1741. canceledErr error // set non-nil if conn is canceled
  1742. broken bool // an error has happened on this connection; marked broken so it's not reused.
  1743. reused bool // whether conn has had successful request/response and is being reused.
  1744. // mutateHeaderFunc is an optional func to modify extra
  1745. // headers on each outbound request before it's written. (the
  1746. // original Request given to RoundTrip is not modified)
  1747. mutateHeaderFunc func(Header)
  1748. }
  1749. func (pc *persistConn) maxHeaderResponseSize() int64 {
  1750. if v := pc.t.MaxResponseHeaderBytes; v != 0 {
  1751. return v
  1752. }
  1753. return 10 << 20 // conservative default; same as http2
  1754. }
  1755. func (pc *persistConn) Read(p []byte) (n int, err error) {
  1756. if pc.readLimit <= 0 {
  1757. return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize())
  1758. }
  1759. if int64(len(p)) > pc.readLimit {
  1760. p = p[:pc.readLimit]
  1761. }
  1762. n, err = pc.conn.Read(p)
  1763. if err == io.EOF {
  1764. pc.sawEOF = true
  1765. }
  1766. pc.readLimit -= int64(n)
  1767. return
  1768. }
  1769. // isBroken reports whether this connection is in a known broken state.
  1770. func (pc *persistConn) isBroken() bool {
  1771. pc.mu.Lock()
  1772. b := pc.closed != nil
  1773. pc.mu.Unlock()
  1774. return b
  1775. }
  1776. // canceled returns non-nil if the connection was closed due to
  1777. // CancelRequest or due to context cancellation.
  1778. func (pc *persistConn) canceled() error {
  1779. pc.mu.Lock()
  1780. defer pc.mu.Unlock()
  1781. return pc.canceledErr
  1782. }
  1783. // isReused reports whether this connection has been used before.
  1784. func (pc *persistConn) isReused() bool {
  1785. pc.mu.Lock()
  1786. r := pc.reused
  1787. pc.mu.Unlock()
  1788. return r
  1789. }
  1790. func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo) {
  1791. pc.mu.Lock()
  1792. defer pc.mu.Unlock()
  1793. t.Reused = pc.reused
  1794. t.Conn = pc.conn
  1795. t.WasIdle = true
  1796. if !idleAt.IsZero() {
  1797. t.IdleTime = time.Since(idleAt)
  1798. }
  1799. return
  1800. }
  1801. func (pc *persistConn) cancelRequest(err error) {
  1802. pc.mu.Lock()
  1803. defer pc.mu.Unlock()
  1804. pc.canceledErr = err
  1805. pc.closeLocked(errRequestCanceled)
  1806. }
  1807. // closeConnIfStillIdle closes the connection if it's still sitting idle.
  1808. // This is what's called by the persistConn's idleTimer, and is run in its
  1809. // own goroutine.
  1810. func (pc *persistConn) closeConnIfStillIdle() {
  1811. t := pc.t
  1812. t.idleMu.Lock()
  1813. defer t.idleMu.Unlock()
  1814. if _, ok := t.idleLRU.m[pc]; !ok {
  1815. // Not idle.
  1816. return
  1817. }
  1818. t.removeIdleConnLocked(pc)
  1819. pc.close(errIdleConnTimeout)
  1820. }
  1821. // mapRoundTripError returns the appropriate error value for
  1822. // persistConn.roundTrip.
  1823. //
  1824. // The provided err is the first error that (*persistConn).roundTrip
  1825. // happened to receive from its select statement.
  1826. //
  1827. // The startBytesWritten value should be the value of pc.nwrite before the roundTrip
  1828. // started writing the request.
  1829. func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error {
  1830. if err == nil {
  1831. return nil
  1832. }
  1833. // Wait for the writeLoop goroutine to terminate to avoid data
  1834. // races on callers who mutate the request on failure.
  1835. //
  1836. // When resc in pc.roundTrip and hence rc.ch receives a responseAndError
  1837. // with a non-nil error it implies that the persistConn is either closed
  1838. // or closing. Waiting on pc.writeLoopDone is hence safe as all callers
  1839. // close closech which in turn ensures writeLoop returns.
  1840. <-pc.writeLoopDone
  1841. // If the request was canceled, that's better than network
  1842. // failures that were likely the result of tearing down the
  1843. // connection.
  1844. if cerr := pc.canceled(); cerr != nil {
  1845. return cerr
  1846. }
  1847. // See if an error was set explicitly.
  1848. req.mu.Lock()
  1849. reqErr := req.err
  1850. req.mu.Unlock()
  1851. if reqErr != nil {
  1852. return reqErr
  1853. }
  1854. if err == errServerClosedIdle {
  1855. // Don't decorate
  1856. return err
  1857. }
  1858. if _, ok := err.(transportReadFromServerError); ok {
  1859. if pc.nwrite == startBytesWritten {
  1860. return nothingWrittenError{err}
  1861. }
  1862. // Don't decorate
  1863. return err
  1864. }
  1865. if pc.isBroken() {
  1866. if pc.nwrite == startBytesWritten {
  1867. return nothingWrittenError{err}
  1868. }
  1869. return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %v", err)
  1870. }
  1871. return err
  1872. }
  1873. // errCallerOwnsConn is an internal sentinel error used when we hand
  1874. // off a writable response.Body to the caller. We use this to prevent
  1875. // closing a net.Conn that is now owned by the caller.
  1876. var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")
  1877. func (pc *persistConn) readLoop() {
  1878. closeErr := errReadLoopExiting // default value, if not changed below
  1879. defer func() {
  1880. pc.close(closeErr)
  1881. pc.t.removeIdleConn(pc)
  1882. }()
  1883. tryPutIdleConn := func(trace *httptrace.ClientTrace) bool {
  1884. if err := pc.t.tryPutIdleConn(pc); err != nil {
  1885. closeErr = err
  1886. if trace != nil && trace.PutIdleConn != nil && err != errKeepAlivesDisabled {
  1887. trace.PutIdleConn(err)
  1888. }
  1889. return false
  1890. }
  1891. if trace != nil && trace.PutIdleConn != nil {
  1892. trace.PutIdleConn(nil)
  1893. }
  1894. return true
  1895. }
  1896. // eofc is used to block caller goroutines reading from Response.Body
  1897. // at EOF until this goroutines has (potentially) added the connection
  1898. // back to the idle pool.
  1899. eofc := make(chan struct{})
  1900. defer close(eofc) // unblock reader on errors
  1901. // Read this once, before loop starts. (to avoid races in tests)
  1902. testHookMu.Lock()
  1903. testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead
  1904. testHookMu.Unlock()
  1905. alive := true
  1906. for alive {
  1907. pc.readLimit = pc.maxHeaderResponseSize()
  1908. _, err := pc.br.Peek(1)
  1909. pc.mu.Lock()
  1910. if pc.numExpectedResponses == 0 {
  1911. pc.readLoopPeekFailLocked(err)
  1912. pc.mu.Unlock()
  1913. return
  1914. }
  1915. pc.mu.Unlock()
  1916. rc := <-pc.reqch
  1917. trace := httptrace.ContextClientTrace(rc.req.Context())
  1918. var resp *Response
  1919. if err == nil {
  1920. resp, err = pc.readResponse(rc, trace)
  1921. } else {
  1922. err = transportReadFromServerError{err}
  1923. closeErr = err
  1924. }
  1925. if err != nil {
  1926. if pc.readLimit <= 0 {
  1927. err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize())
  1928. }
  1929. select {
  1930. case rc.ch <- responseAndError{err: err}:
  1931. case <-rc.callerGone:
  1932. return
  1933. }
  1934. return
  1935. }
  1936. pc.readLimit = maxInt64 // effectively no limit for response bodies
  1937. pc.mu.Lock()
  1938. pc.numExpectedResponses--
  1939. pc.mu.Unlock()
  1940. bodyWritable := resp.bodyIsWritable()
  1941. hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0
  1942. if resp.Close || rc.req.Close || resp.StatusCode <= 199 || bodyWritable {
  1943. // Don't do keep-alive on error if either party requested a close
  1944. // or we get an unexpected informational (1xx) response.
  1945. // StatusCode 100 is already handled above.
  1946. alive = false
  1947. }
  1948. if !hasBody || bodyWritable {
  1949. replaced := pc.t.replaceReqCanceler(rc.cancelKey, nil)
  1950. // Put the idle conn back into the pool before we send the response
  1951. // so if they process it quickly and make another request, they'll
  1952. // get this same conn. But we use the unbuffered channel 'rc'
  1953. // to guarantee that persistConn.roundTrip got out of its select
  1954. // potentially waiting for this persistConn to close.
  1955. alive = alive &&
  1956. !pc.sawEOF &&
  1957. pc.wroteRequest() &&
  1958. replaced && tryPutIdleConn(trace)
  1959. if bodyWritable {
  1960. closeErr = errCallerOwnsConn
  1961. }
  1962. select {
  1963. case rc.ch <- responseAndError{res: resp}:
  1964. case <-rc.callerGone:
  1965. return
  1966. }
  1967. // Now that they've read from the unbuffered channel, they're safely
  1968. // out of the select that also waits on this goroutine to die, so
  1969. // we're allowed to exit now if needed (if alive is false)
  1970. testHookReadLoopBeforeNextRead()
  1971. continue
  1972. }
  1973. waitForBodyRead := make(chan bool, 2)
  1974. body := &bodyEOFSignal{
  1975. body: resp.Body,
  1976. earlyCloseFn: func() error {
  1977. waitForBodyRead <- false
  1978. <-eofc // will be closed by deferred call at the end of the function
  1979. return nil
  1980. },
  1981. fn: func(err error) error {
  1982. isEOF := err == io.EOF
  1983. waitForBodyRead <- isEOF
  1984. if isEOF {
  1985. <-eofc // see comment above eofc declaration
  1986. } else if err != nil {
  1987. if cerr := pc.canceled(); cerr != nil {
  1988. return cerr
  1989. }
  1990. }
  1991. return err
  1992. },
  1993. }
  1994. resp.Body = body
  1995. if rc.addedGzip && ascii.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
  1996. resp.Body = &gzipReader{body: body}
  1997. resp.Header.Del("Content-Encoding")
  1998. resp.Header.Del("Content-Length")
  1999. resp.ContentLength = -1
  2000. resp.Uncompressed = true
  2001. }
  2002. select {
  2003. case rc.ch <- responseAndError{res: resp}:
  2004. case <-rc.callerGone:
  2005. return
  2006. }
  2007. // Before looping back to the top of this function and peeking on
  2008. // the bufio.Reader, wait for the caller goroutine to finish
  2009. // reading the response body. (or for cancellation or death)
  2010. select {
  2011. case bodyEOF := <-waitForBodyRead:
  2012. replaced := pc.t.replaceReqCanceler(rc.cancelKey, nil) // before pc might return to idle pool
  2013. alive = alive &&
  2014. bodyEOF &&
  2015. !pc.sawEOF &&
  2016. pc.wroteRequest() &&
  2017. replaced && tryPutIdleConn(trace)
  2018. if bodyEOF {
  2019. eofc <- struct{}{}
  2020. }
  2021. case <-rc.req.Cancel:
  2022. alive = false
  2023. pc.t.CancelRequest(rc.req)
  2024. case <-rc.req.Context().Done():
  2025. alive = false
  2026. pc.t.cancelRequest(rc.cancelKey, rc.req.Context().Err())
  2027. case <-pc.closech:
  2028. alive = false
  2029. }
  2030. testHookReadLoopBeforeNextRead()
  2031. }
  2032. }
  2033. func (pc *persistConn) readLoopPeekFailLocked(peekErr error) {
  2034. if pc.closed != nil {
  2035. return
  2036. }
  2037. if n := pc.br.Buffered(); n > 0 {
  2038. buf, _ := pc.br.Peek(n)
  2039. if is408Message(buf) {
  2040. pc.closeLocked(errServerClosedIdle)
  2041. return
  2042. } else {
  2043. log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr)
  2044. }
  2045. }
  2046. if peekErr == io.EOF {
  2047. // common case.
  2048. pc.closeLocked(errServerClosedIdle)
  2049. } else {
  2050. pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %v", peekErr))
  2051. }
  2052. }
  2053. // is408Message reports whether buf has the prefix of an
  2054. // HTTP 408 Request Timeout response.
  2055. // See golang.org/issue/32310.
  2056. func is408Message(buf []byte) bool {
  2057. if len(buf) < len("HTTP/1.x 408") {
  2058. return false
  2059. }
  2060. if string(buf[:7]) != "HTTP/1." {
  2061. return false
  2062. }
  2063. return string(buf[8:12]) == " 408"
  2064. }
  2065. // readResponse reads an HTTP response (or two, in the case of "Expect:
  2066. // 100-continue") from the server. It returns the final non-100 one.
  2067. // trace is optional.
  2068. func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error) {
  2069. if trace != nil && trace.GotFirstResponseByte != nil {
  2070. if peek, err := pc.br.Peek(1); err == nil && len(peek) == 1 {
  2071. trace.GotFirstResponseByte()
  2072. }
  2073. }
  2074. num1xx := 0 // number of informational 1xx headers received
  2075. const max1xxResponses = 5 // arbitrary bound on number of informational responses
  2076. continueCh := rc.continueCh
  2077. for {
  2078. resp, err = ReadResponse(pc.br, rc.req)
  2079. if err != nil {
  2080. return
  2081. }
  2082. resCode := resp.StatusCode
  2083. if continueCh != nil {
  2084. if resCode == 100 {
  2085. if trace != nil && trace.Got100Continue != nil {
  2086. trace.Got100Continue()
  2087. }
  2088. continueCh <- struct{}{}
  2089. continueCh = nil
  2090. } else if resCode >= 200 {
  2091. close(continueCh)
  2092. continueCh = nil
  2093. }
  2094. }
  2095. is1xx := 100 <= resCode && resCode <= 199
  2096. // treat 101 as a terminal status, see issue 26161
  2097. is1xxNonTerminal := is1xx && resCode != StatusSwitchingProtocols
  2098. if is1xxNonTerminal {
  2099. num1xx++
  2100. if num1xx > max1xxResponses {
  2101. return nil, errors.New("net/http: too many 1xx informational responses")
  2102. }
  2103. pc.readLimit = pc.maxHeaderResponseSize() // reset the limit
  2104. if trace != nil && trace.Got1xxResponse != nil {
  2105. if err := trace.Got1xxResponse(resCode, textproto.MIMEHeader(resp.Header)); err != nil {
  2106. return nil, err
  2107. }
  2108. }
  2109. continue
  2110. }
  2111. break
  2112. }
  2113. if resp.isProtocolSwitch() {
  2114. resp.Body = newReadWriteCloserBody(pc.br, pc.conn)
  2115. }
  2116. resp.TLS = pc.tlsState
  2117. return
  2118. }
  2119. // waitForContinue returns the function to block until
  2120. // any response, timeout or connection close. After any of them,
  2121. // the function returns a bool which indicates if the body should be sent.
  2122. func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool {
  2123. if continueCh == nil {
  2124. return nil
  2125. }
  2126. return func() bool {
  2127. timer := time.NewTimer(pc.t.ExpectContinueTimeout)
  2128. defer timer.Stop()
  2129. select {
  2130. case _, ok := <-continueCh:
  2131. return ok
  2132. case <-timer.C:
  2133. return true
  2134. case <-pc.closech:
  2135. return false
  2136. }
  2137. }
  2138. }
  2139. func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser {
  2140. body := &readWriteCloserBody{ReadWriteCloser: rwc}
  2141. if br.Buffered() != 0 {
  2142. body.br = br
  2143. }
  2144. return body
  2145. }
  2146. // readWriteCloserBody is the Response.Body type used when we want to
  2147. // give users write access to the Body through the underlying
  2148. // connection (TCP, unless using custom dialers). This is then
  2149. // the concrete type for a Response.Body on the 101 Switching
  2150. // Protocols response, as used by WebSockets, h2c, etc.
  2151. type readWriteCloserBody struct {
  2152. _ incomparable
  2153. br *bufio.Reader // used until empty
  2154. io.ReadWriteCloser
  2155. }
  2156. func (b *readWriteCloserBody) Read(p []byte) (n int, err error) {
  2157. if b.br != nil {
  2158. if n := b.br.Buffered(); len(p) > n {
  2159. p = p[:n]
  2160. }
  2161. n, err = b.br.Read(p)
  2162. if b.br.Buffered() == 0 {
  2163. b.br = nil
  2164. }
  2165. return n, err
  2166. }
  2167. return b.ReadWriteCloser.Read(p)
  2168. }
  2169. // nothingWrittenError wraps a write errors which ended up writing zero bytes.
  2170. type nothingWrittenError struct {
  2171. error
  2172. }
  2173. func (pc *persistConn) writeLoop() {
  2174. defer close(pc.writeLoopDone)
  2175. for {
  2176. select {
  2177. case wr := <-pc.writech:
  2178. startBytesWritten := pc.nwrite
  2179. err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh))
  2180. if bre, ok := err.(requestBodyReadError); ok {
  2181. err = bre.error
  2182. // Errors reading from the user's
  2183. // Request.Body are high priority.
  2184. // Set it here before sending on the
  2185. // channels below or calling
  2186. // pc.close() which tears down
  2187. // connections and causes other
  2188. // errors.
  2189. wr.req.setError(err)
  2190. }
  2191. if err == nil {
  2192. err = pc.bw.Flush()
  2193. }
  2194. if err != nil {
  2195. if pc.nwrite == startBytesWritten {
  2196. err = nothingWrittenError{err}
  2197. }
  2198. }
  2199. pc.writeErrCh <- err // to the body reader, which might recycle us
  2200. wr.ch <- err // to the roundTrip function
  2201. if err != nil {
  2202. pc.close(err)
  2203. return
  2204. }
  2205. case <-pc.closech:
  2206. return
  2207. }
  2208. }
  2209. }
  2210. // maxWriteWaitBeforeConnReuse is how long the a Transport RoundTrip
  2211. // will wait to see the Request's Body.Write result after getting a
  2212. // response from the server. See comments in (*persistConn).wroteRequest.
  2213. const maxWriteWaitBeforeConnReuse = 50 * time.Millisecond
  2214. // wroteRequest is a check before recycling a connection that the previous write
  2215. // (from writeLoop above) happened and was successful.
  2216. func (pc *persistConn) wroteRequest() bool {
  2217. select {
  2218. case err := <-pc.writeErrCh:
  2219. // Common case: the write happened well before the response, so
  2220. // avoid creating a timer.
  2221. return err == nil
  2222. default:
  2223. // Rare case: the request was written in writeLoop above but
  2224. // before it could send to pc.writeErrCh, the reader read it
  2225. // all, processed it, and called us here. In this case, give the
  2226. // write goroutine a bit of time to finish its send.
  2227. //
  2228. // Less rare case: We also get here in the legitimate case of
  2229. // Issue 7569, where the writer is still writing (or stalled),
  2230. // but the server has already replied. In this case, we don't
  2231. // want to wait too long, and we want to return false so this
  2232. // connection isn't re-used.
  2233. t := time.NewTimer(maxWriteWaitBeforeConnReuse)
  2234. defer t.Stop()
  2235. select {
  2236. case err := <-pc.writeErrCh:
  2237. return err == nil
  2238. case <-t.C:
  2239. return false
  2240. }
  2241. }
  2242. }
  2243. // responseAndError is how the goroutine reading from an HTTP/1 server
  2244. // communicates with the goroutine doing the RoundTrip.
  2245. type responseAndError struct {
  2246. _ incomparable
  2247. res *Response // else use this response (see res method)
  2248. err error
  2249. }
  2250. type requestAndChan struct {
  2251. _ incomparable
  2252. req *Request
  2253. cancelKey cancelKey
  2254. ch chan responseAndError // unbuffered; always send in select on callerGone
  2255. // whether the Transport (as opposed to the user client code)
  2256. // added the Accept-Encoding gzip header. If the Transport
  2257. // set it, only then do we transparently decode the gzip.
  2258. addedGzip bool
  2259. // Optional blocking chan for Expect: 100-continue (for send).
  2260. // If the request has an "Expect: 100-continue" header and
  2261. // the server responds 100 Continue, readLoop send a value
  2262. // to writeLoop via this chan.
  2263. continueCh chan<- struct{}
  2264. callerGone <-chan struct{} // closed when roundTrip caller has returned
  2265. }
  2266. // A writeRequest is sent by the caller's goroutine to the
  2267. // writeLoop's goroutine to write a request while the read loop
  2268. // concurrently waits on both the write response and the server's
  2269. // reply.
  2270. type writeRequest struct {
  2271. req *transportRequest
  2272. ch chan<- error
  2273. // Optional blocking chan for Expect: 100-continue (for receive).
  2274. // If not nil, writeLoop blocks sending request body until
  2275. // it receives from this chan.
  2276. continueCh <-chan struct{}
  2277. }
  2278. type httpError struct {
  2279. err string
  2280. timeout bool
  2281. }
  2282. func (e *httpError) Error() string { return e.err }
  2283. func (e *httpError) Timeout() bool { return e.timeout }
  2284. func (e *httpError) Temporary() bool { return true }
  2285. var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true}
  2286. // errRequestCanceled is set to be identical to the one from h2 to facilitate
  2287. // testing.
  2288. var errRequestCanceled = http2errRequestCanceled
  2289. var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?
  2290. func nop() {}
  2291. // testHooks. Always non-nil.
  2292. var (
  2293. testHookEnterRoundTrip = nop
  2294. testHookWaitResLoop = nop
  2295. testHookRoundTripRetried = nop
  2296. testHookPrePendingDial = nop
  2297. testHookPostPendingDial = nop
  2298. testHookMu sync.Locker = fakeLocker{} // guards following
  2299. testHookReadLoopBeforeNextRead = nop
  2300. )
  2301. func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
  2302. testHookEnterRoundTrip()
  2303. if !pc.t.replaceReqCanceler(req.cancelKey, pc.cancelRequest) {
  2304. pc.t.putOrCloseIdleConn(pc)
  2305. return nil, errRequestCanceled
  2306. }
  2307. pc.mu.Lock()
  2308. pc.numExpectedResponses++
  2309. headerFn := pc.mutateHeaderFunc
  2310. pc.mu.Unlock()
  2311. if headerFn != nil {
  2312. headerFn(req.extraHeaders())
  2313. }
  2314. // Ask for a compressed version if the caller didn't set their
  2315. // own value for Accept-Encoding. We only attempt to
  2316. // uncompress the gzip stream if we were the layer that
  2317. // requested it.
  2318. requestedGzip := false
  2319. if !pc.t.DisableCompression &&
  2320. req.Header.Get("Accept-Encoding") == "" &&
  2321. req.Header.Get("Range") == "" &&
  2322. req.Method != "HEAD" {
  2323. // Request gzip only, not deflate. Deflate is ambiguous and
  2324. // not as universally supported anyway.
  2325. // See: https://zlib.net/zlib_faq.html#faq39
  2326. //
  2327. // Note that we don't request this for HEAD requests,
  2328. // due to a bug in nginx:
  2329. // https://trac.nginx.org/nginx/ticket/358
  2330. // https://golang.org/issue/5522
  2331. //
  2332. // We don't request gzip if the request is for a range, since
  2333. // auto-decoding a portion of a gzipped document will just fail
  2334. // anyway. See https://golang.org/issue/8923
  2335. requestedGzip = true
  2336. req.extraHeaders().Set("Accept-Encoding", "gzip")
  2337. }
  2338. var continueCh chan struct{}
  2339. if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() {
  2340. continueCh = make(chan struct{}, 1)
  2341. }
  2342. if pc.t.DisableKeepAlives &&
  2343. !req.wantsClose() &&
  2344. !isProtocolSwitchHeader(req.Header) {
  2345. req.extraHeaders().Set("Connection", "close")
  2346. }
  2347. gone := make(chan struct{})
  2348. defer close(gone)
  2349. defer func() {
  2350. if err != nil {
  2351. pc.t.setReqCanceler(req.cancelKey, nil)
  2352. }
  2353. }()
  2354. const debugRoundTrip = false
  2355. // Write the request concurrently with waiting for a response,
  2356. // in case the server decides to reply before reading our full
  2357. // request body.
  2358. startBytesWritten := pc.nwrite
  2359. writeErrCh := make(chan error, 1)
  2360. pc.writech <- writeRequest{req, writeErrCh, continueCh}
  2361. resc := make(chan responseAndError)
  2362. pc.reqch <- requestAndChan{
  2363. req: req.Request,
  2364. cancelKey: req.cancelKey,
  2365. ch: resc,
  2366. addedGzip: requestedGzip,
  2367. continueCh: continueCh,
  2368. callerGone: gone,
  2369. }
  2370. var respHeaderTimer <-chan time.Time
  2371. cancelChan := req.Request.Cancel
  2372. ctxDoneChan := req.Context().Done()
  2373. pcClosed := pc.closech
  2374. canceled := false
  2375. for {
  2376. testHookWaitResLoop()
  2377. select {
  2378. case err := <-writeErrCh:
  2379. if debugRoundTrip {
  2380. req.logf("writeErrCh resv: %T/%#v", err, err)
  2381. }
  2382. if err != nil {
  2383. pc.close(fmt.Errorf("write error: %v", err))
  2384. return nil, pc.mapRoundTripError(req, startBytesWritten, err)
  2385. }
  2386. if d := pc.t.ResponseHeaderTimeout; d > 0 {
  2387. if debugRoundTrip {
  2388. req.logf("starting timer for %v", d)
  2389. }
  2390. timer := time.NewTimer(d)
  2391. defer timer.Stop() // prevent leaks
  2392. respHeaderTimer = timer.C
  2393. }
  2394. case <-pcClosed:
  2395. pcClosed = nil
  2396. if canceled || pc.t.replaceReqCanceler(req.cancelKey, nil) {
  2397. if debugRoundTrip {
  2398. req.logf("closech recv: %T %#v", pc.closed, pc.closed)
  2399. }
  2400. return nil, pc.mapRoundTripError(req, startBytesWritten, pc.closed)
  2401. }
  2402. case <-respHeaderTimer:
  2403. if debugRoundTrip {
  2404. req.logf("timeout waiting for response headers.")
  2405. }
  2406. pc.close(errTimeout)
  2407. return nil, errTimeout
  2408. case re := <-resc:
  2409. if (re.res == nil) == (re.err == nil) {
  2410. panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", re.res == nil))
  2411. }
  2412. if debugRoundTrip {
  2413. req.logf("resc recv: %p, %T/%#v", re.res, re.err, re.err)
  2414. }
  2415. if re.err != nil {
  2416. return nil, pc.mapRoundTripError(req, startBytesWritten, re.err)
  2417. }
  2418. return re.res, nil
  2419. case <-cancelChan:
  2420. canceled = pc.t.cancelRequest(req.cancelKey, errRequestCanceled)
  2421. cancelChan = nil
  2422. case <-ctxDoneChan:
  2423. canceled = pc.t.cancelRequest(req.cancelKey, req.Context().Err())
  2424. cancelChan = nil
  2425. ctxDoneChan = nil
  2426. }
  2427. }
  2428. }
  2429. // tLogKey is a context WithValue key for test debugging contexts containing
  2430. // a t.Logf func. See export_test.go's Request.WithT method.
  2431. type tLogKey struct{}
  2432. func (tr *transportRequest) logf(format string, args ...any) {
  2433. if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...any)); ok {
  2434. logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...)
  2435. }
  2436. }
  2437. // markReused marks this connection as having been successfully used for a
  2438. // request and response.
  2439. func (pc *persistConn) markReused() {
  2440. pc.mu.Lock()
  2441. pc.reused = true
  2442. pc.mu.Unlock()
  2443. }
  2444. // close closes the underlying TCP connection and closes
  2445. // the pc.closech channel.
  2446. //
  2447. // The provided err is only for testing and debugging; in normal
  2448. // circumstances it should never be seen by users.
  2449. func (pc *persistConn) close(err error) {
  2450. pc.mu.Lock()
  2451. defer pc.mu.Unlock()
  2452. pc.closeLocked(err)
  2453. }
  2454. func (pc *persistConn) closeLocked(err error) {
  2455. if err == nil {
  2456. panic("nil error")
  2457. }
  2458. pc.broken = true
  2459. if pc.closed == nil {
  2460. pc.closed = err
  2461. pc.t.decConnsPerHost(pc.cacheKey)
  2462. // Close HTTP/1 (pc.alt == nil) connection.
  2463. // HTTP/2 closes its connection itself.
  2464. if pc.alt == nil {
  2465. if err != errCallerOwnsConn {
  2466. pc.conn.Close()
  2467. }
  2468. close(pc.closech)
  2469. }
  2470. }
  2471. pc.mutateHeaderFunc = nil
  2472. }
  2473. var portMap = map[string]string{
  2474. "http": "80",
  2475. "https": "443",
  2476. "socks5": "1080",
  2477. }
  2478. // canonicalAddr returns url.Host but always with a ":port" suffix
  2479. func canonicalAddr(url *url.URL) string {
  2480. addr := url.Hostname()
  2481. if v, err := idnaASCII(addr); err == nil {
  2482. addr = v
  2483. }
  2484. port := url.Port()
  2485. if port == "" {
  2486. port = portMap[url.Scheme]
  2487. }
  2488. return net.JoinHostPort(addr, port)
  2489. }
  2490. // bodyEOFSignal is used by the HTTP/1 transport when reading response
  2491. // bodies to make sure we see the end of a response body before
  2492. // proceeding and reading on the connection again.
  2493. //
  2494. // It wraps a ReadCloser but runs fn (if non-nil) at most
  2495. // once, right before its final (error-producing) Read or Close call
  2496. // returns. fn should return the new error to return from Read or Close.
  2497. //
  2498. // If earlyCloseFn is non-nil and Close is called before io.EOF is
  2499. // seen, earlyCloseFn is called instead of fn, and its return value is
  2500. // the return value from Close.
  2501. type bodyEOFSignal struct {
  2502. body io.ReadCloser
  2503. mu sync.Mutex // guards following 4 fields
  2504. closed bool // whether Close has been called
  2505. rerr error // sticky Read error
  2506. fn func(error) error // err will be nil on Read io.EOF
  2507. earlyCloseFn func() error // optional alt Close func used if io.EOF not seen
  2508. }
  2509. var errReadOnClosedResBody = errors.New("http: read on closed response body")
  2510. func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
  2511. es.mu.Lock()
  2512. closed, rerr := es.closed, es.rerr
  2513. es.mu.Unlock()
  2514. if closed {
  2515. return 0, errReadOnClosedResBody
  2516. }
  2517. if rerr != nil {
  2518. return 0, rerr
  2519. }
  2520. n, err = es.body.Read(p)
  2521. if err != nil {
  2522. es.mu.Lock()
  2523. defer es.mu.Unlock()
  2524. if es.rerr == nil {
  2525. es.rerr = err
  2526. }
  2527. err = es.condfn(err)
  2528. }
  2529. return
  2530. }
  2531. func (es *bodyEOFSignal) Close() error {
  2532. es.mu.Lock()
  2533. defer es.mu.Unlock()
  2534. if es.closed {
  2535. return nil
  2536. }
  2537. es.closed = true
  2538. if es.earlyCloseFn != nil && es.rerr != io.EOF {
  2539. return es.earlyCloseFn()
  2540. }
  2541. err := es.body.Close()
  2542. return es.condfn(err)
  2543. }
  2544. // caller must hold es.mu.
  2545. func (es *bodyEOFSignal) condfn(err error) error {
  2546. if es.fn == nil {
  2547. return err
  2548. }
  2549. err = es.fn(err)
  2550. es.fn = nil
  2551. return err
  2552. }
  2553. // gzipReader wraps a response body so it can lazily
  2554. // call gzip.NewReader on the first call to Read
  2555. type gzipReader struct {
  2556. _ incomparable
  2557. body *bodyEOFSignal // underlying HTTP/1 response body framing
  2558. zr *gzip.Reader // lazily-initialized gzip reader
  2559. zerr error // any error from gzip.NewReader; sticky
  2560. }
  2561. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2562. if gz.zr == nil {
  2563. if gz.zerr == nil {
  2564. gz.zr, gz.zerr = gzip.NewReader(gz.body)
  2565. }
  2566. if gz.zerr != nil {
  2567. return 0, gz.zerr
  2568. }
  2569. }
  2570. gz.body.mu.Lock()
  2571. if gz.body.closed {
  2572. err = errReadOnClosedResBody
  2573. }
  2574. gz.body.mu.Unlock()
  2575. if err != nil {
  2576. return 0, err
  2577. }
  2578. return gz.zr.Read(p)
  2579. }
  2580. func (gz *gzipReader) Close() error {
  2581. return gz.body.Close()
  2582. }
  2583. type tlsHandshakeTimeoutError struct{}
  2584. func (tlsHandshakeTimeoutError) Timeout() bool { return true }
  2585. func (tlsHandshakeTimeoutError) Temporary() bool { return true }
  2586. func (tlsHandshakeTimeoutError) Error() string { return "net/http: TLS handshake timeout" }
  2587. // fakeLocker is a sync.Locker which does nothing. It's used to guard
  2588. // test-only fields when not under test, to avoid runtime atomic
  2589. // overhead.
  2590. type fakeLocker struct{}
  2591. func (fakeLocker) Lock() {}
  2592. func (fakeLocker) Unlock() {}
  2593. // cloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if
  2594. // cfg is nil. This is safe to call even if cfg is in active use by a TLS
  2595. // client or server.
  2596. func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  2597. if cfg == nil {
  2598. return &tls.Config{}
  2599. }
  2600. return cfg.Clone()
  2601. }
  2602. type connLRU struct {
  2603. ll *list.List // list.Element.Value type is of *persistConn
  2604. m map[*persistConn]*list.Element
  2605. }
  2606. // add adds pc to the head of the linked list.
  2607. func (cl *connLRU) add(pc *persistConn) {
  2608. if cl.ll == nil {
  2609. cl.ll = list.New()
  2610. cl.m = make(map[*persistConn]*list.Element)
  2611. }
  2612. ele := cl.ll.PushFront(pc)
  2613. if _, ok := cl.m[pc]; ok {
  2614. panic("persistConn was already in LRU")
  2615. }
  2616. cl.m[pc] = ele
  2617. }
  2618. func (cl *connLRU) removeOldest() *persistConn {
  2619. ele := cl.ll.Back()
  2620. pc := ele.Value.(*persistConn)
  2621. cl.ll.Remove(ele)
  2622. delete(cl.m, pc)
  2623. return pc
  2624. }
  2625. // remove removes pc from cl.
  2626. func (cl *connLRU) remove(pc *persistConn) {
  2627. if ele, ok := cl.m[pc]; ok {
  2628. cl.ll.Remove(ele)
  2629. delete(cl.m, pc)
  2630. }
  2631. }
  2632. // len returns the number of items in the cache.
  2633. func (cl *connLRU) len() int {
  2634. return len(cl.m)
  2635. }