transport_test.go 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095
  1. // Copyright 2015 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. package http2
  5. import (
  6. "bufio"
  7. "bytes"
  8. "crypto/tls"
  9. "errors"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "math/rand"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "reflect"
  20. "runtime"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "sync/atomic"
  26. "testing"
  27. "time"
  28. "golang.org/x/net/http2/hpack"
  29. )
  30. var (
  31. extNet = flag.Bool("extnet", false, "do external network tests")
  32. transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport")
  33. insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove?
  34. )
  35. var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true}
  36. type testContext struct{}
  37. func (testContext) Done() <-chan struct{} { return make(chan struct{}) }
  38. func (testContext) Err() error { panic("should not be called") }
  39. func (testContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false }
  40. func (testContext) Value(key interface{}) interface{} { return nil }
  41. func TestTransportExternal(t *testing.T) {
  42. if !*extNet {
  43. t.Skip("skipping external network test")
  44. }
  45. req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil)
  46. rt := &Transport{TLSClientConfig: tlsConfigInsecure}
  47. res, err := rt.RoundTrip(req)
  48. if err != nil {
  49. t.Fatalf("%v", err)
  50. }
  51. res.Write(os.Stdout)
  52. }
  53. type fakeTLSConn struct {
  54. net.Conn
  55. }
  56. func (c *fakeTLSConn) ConnectionState() tls.ConnectionState {
  57. return tls.ConnectionState{
  58. Version: tls.VersionTLS12,
  59. CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  60. }
  61. }
  62. func startH2cServer(t *testing.T) net.Listener {
  63. h2Server := &Server{}
  64. l := newLocalListener(t)
  65. go func() {
  66. conn, err := l.Accept()
  67. if err != nil {
  68. t.Error(err)
  69. return
  70. }
  71. h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  72. fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil)
  73. })})
  74. }()
  75. return l
  76. }
  77. func TestTransportH2c(t *testing.T) {
  78. l := startH2cServer(t)
  79. defer l.Close()
  80. req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil)
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. tr := &Transport{
  85. AllowHTTP: true,
  86. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  87. return net.Dial(network, addr)
  88. },
  89. }
  90. res, err := tr.RoundTrip(req)
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. if res.ProtoMajor != 2 {
  95. t.Fatal("proto not h2c")
  96. }
  97. body, err := ioutil.ReadAll(res.Body)
  98. if err != nil {
  99. t.Fatal(err)
  100. }
  101. if got, want := string(body), "Hello, /foobar, http: true"; got != want {
  102. t.Fatalf("response got %v, want %v", got, want)
  103. }
  104. }
  105. func TestTransport(t *testing.T) {
  106. const body = "sup"
  107. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  108. io.WriteString(w, body)
  109. }, optOnlyServer)
  110. defer st.Close()
  111. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  112. defer tr.CloseIdleConnections()
  113. req, err := http.NewRequest("GET", st.ts.URL, nil)
  114. if err != nil {
  115. t.Fatal(err)
  116. }
  117. res, err := tr.RoundTrip(req)
  118. if err != nil {
  119. t.Fatal(err)
  120. }
  121. defer res.Body.Close()
  122. t.Logf("Got res: %+v", res)
  123. if g, w := res.StatusCode, 200; g != w {
  124. t.Errorf("StatusCode = %v; want %v", g, w)
  125. }
  126. if g, w := res.Status, "200 OK"; g != w {
  127. t.Errorf("Status = %q; want %q", g, w)
  128. }
  129. wantHeader := http.Header{
  130. "Content-Length": []string{"3"},
  131. "Content-Type": []string{"text/plain; charset=utf-8"},
  132. "Date": []string{"XXX"}, // see cleanDate
  133. }
  134. cleanDate(res)
  135. if !reflect.DeepEqual(res.Header, wantHeader) {
  136. t.Errorf("res Header = %v; want %v", res.Header, wantHeader)
  137. }
  138. if res.Request != req {
  139. t.Errorf("Response.Request = %p; want %p", res.Request, req)
  140. }
  141. if res.TLS == nil {
  142. t.Error("Response.TLS = nil; want non-nil")
  143. }
  144. slurp, err := ioutil.ReadAll(res.Body)
  145. if err != nil {
  146. t.Errorf("Body read: %v", err)
  147. } else if string(slurp) != body {
  148. t.Errorf("Body = %q; want %q", slurp, body)
  149. }
  150. }
  151. func onSameConn(t *testing.T, modReq func(*http.Request)) bool {
  152. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  153. io.WriteString(w, r.RemoteAddr)
  154. }, optOnlyServer, func(c net.Conn, st http.ConnState) {
  155. t.Logf("conn %v is now state %v", c.RemoteAddr(), st)
  156. })
  157. defer st.Close()
  158. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  159. defer tr.CloseIdleConnections()
  160. get := func() string {
  161. req, err := http.NewRequest("GET", st.ts.URL, nil)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. modReq(req)
  166. res, err := tr.RoundTrip(req)
  167. if err != nil {
  168. t.Fatal(err)
  169. }
  170. defer res.Body.Close()
  171. slurp, err := ioutil.ReadAll(res.Body)
  172. if err != nil {
  173. t.Fatalf("Body read: %v", err)
  174. }
  175. addr := strings.TrimSpace(string(slurp))
  176. if addr == "" {
  177. t.Fatalf("didn't get an addr in response")
  178. }
  179. return addr
  180. }
  181. first := get()
  182. second := get()
  183. return first == second
  184. }
  185. func TestTransportReusesConns(t *testing.T) {
  186. if !onSameConn(t, func(*http.Request) {}) {
  187. t.Errorf("first and second responses were on different connections")
  188. }
  189. }
  190. func TestTransportReusesConn_RequestClose(t *testing.T) {
  191. if onSameConn(t, func(r *http.Request) { r.Close = true }) {
  192. t.Errorf("first and second responses were not on different connections")
  193. }
  194. }
  195. func TestTransportReusesConn_ConnClose(t *testing.T) {
  196. if onSameConn(t, func(r *http.Request) { r.Header.Set("Connection", "close") }) {
  197. t.Errorf("first and second responses were not on different connections")
  198. }
  199. }
  200. // Tests that the Transport only keeps one pending dial open per destination address.
  201. // https://golang.org/issue/13397
  202. func TestTransportGroupsPendingDials(t *testing.T) {
  203. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  204. io.WriteString(w, r.RemoteAddr)
  205. }, optOnlyServer)
  206. defer st.Close()
  207. tr := &Transport{
  208. TLSClientConfig: tlsConfigInsecure,
  209. }
  210. defer tr.CloseIdleConnections()
  211. var (
  212. mu sync.Mutex
  213. dials = map[string]int{}
  214. )
  215. var wg sync.WaitGroup
  216. for i := 0; i < 10; i++ {
  217. wg.Add(1)
  218. go func() {
  219. defer wg.Done()
  220. req, err := http.NewRequest("GET", st.ts.URL, nil)
  221. if err != nil {
  222. t.Error(err)
  223. return
  224. }
  225. res, err := tr.RoundTrip(req)
  226. if err != nil {
  227. t.Error(err)
  228. return
  229. }
  230. defer res.Body.Close()
  231. slurp, err := ioutil.ReadAll(res.Body)
  232. if err != nil {
  233. t.Errorf("Body read: %v", err)
  234. }
  235. addr := strings.TrimSpace(string(slurp))
  236. if addr == "" {
  237. t.Errorf("didn't get an addr in response")
  238. }
  239. mu.Lock()
  240. dials[addr]++
  241. mu.Unlock()
  242. }()
  243. }
  244. wg.Wait()
  245. if len(dials) != 1 {
  246. t.Errorf("saw %d dials; want 1: %v", len(dials), dials)
  247. }
  248. tr.CloseIdleConnections()
  249. if err := retry(50, 10*time.Millisecond, func() error {
  250. cp, ok := tr.connPool().(*clientConnPool)
  251. if !ok {
  252. return fmt.Errorf("Conn pool is %T; want *clientConnPool", tr.connPool())
  253. }
  254. cp.mu.Lock()
  255. defer cp.mu.Unlock()
  256. if len(cp.dialing) != 0 {
  257. return fmt.Errorf("dialing map = %v; want empty", cp.dialing)
  258. }
  259. if len(cp.conns) != 0 {
  260. return fmt.Errorf("conns = %v; want empty", cp.conns)
  261. }
  262. if len(cp.keys) != 0 {
  263. return fmt.Errorf("keys = %v; want empty", cp.keys)
  264. }
  265. return nil
  266. }); err != nil {
  267. t.Errorf("State of pool after CloseIdleConnections: %v", err)
  268. }
  269. }
  270. func retry(tries int, delay time.Duration, fn func() error) error {
  271. var err error
  272. for i := 0; i < tries; i++ {
  273. err = fn()
  274. if err == nil {
  275. return nil
  276. }
  277. time.Sleep(delay)
  278. }
  279. return err
  280. }
  281. func TestTransportAbortClosesPipes(t *testing.T) {
  282. shutdown := make(chan struct{})
  283. st := newServerTester(t,
  284. func(w http.ResponseWriter, r *http.Request) {
  285. w.(http.Flusher).Flush()
  286. <-shutdown
  287. },
  288. optOnlyServer,
  289. )
  290. defer st.Close()
  291. defer close(shutdown) // we must shutdown before st.Close() to avoid hanging
  292. done := make(chan struct{})
  293. requestMade := make(chan struct{})
  294. go func() {
  295. defer close(done)
  296. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  297. req, err := http.NewRequest("GET", st.ts.URL, nil)
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. res, err := tr.RoundTrip(req)
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. defer res.Body.Close()
  306. close(requestMade)
  307. _, err = ioutil.ReadAll(res.Body)
  308. if err == nil {
  309. t.Error("expected error from res.Body.Read")
  310. }
  311. }()
  312. <-requestMade
  313. // Now force the serve loop to end, via closing the connection.
  314. st.closeConn()
  315. // deadlock? that's a bug.
  316. select {
  317. case <-done:
  318. case <-time.After(3 * time.Second):
  319. t.Fatal("timeout")
  320. }
  321. }
  322. // TODO: merge this with TestTransportBody to make TestTransportRequest? This
  323. // could be a table-driven test with extra goodies.
  324. func TestTransportPath(t *testing.T) {
  325. gotc := make(chan *url.URL, 1)
  326. st := newServerTester(t,
  327. func(w http.ResponseWriter, r *http.Request) {
  328. gotc <- r.URL
  329. },
  330. optOnlyServer,
  331. )
  332. defer st.Close()
  333. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  334. defer tr.CloseIdleConnections()
  335. const (
  336. path = "/testpath"
  337. query = "q=1"
  338. )
  339. surl := st.ts.URL + path + "?" + query
  340. req, err := http.NewRequest("POST", surl, nil)
  341. if err != nil {
  342. t.Fatal(err)
  343. }
  344. c := &http.Client{Transport: tr}
  345. res, err := c.Do(req)
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. defer res.Body.Close()
  350. got := <-gotc
  351. if got.Path != path {
  352. t.Errorf("Read Path = %q; want %q", got.Path, path)
  353. }
  354. if got.RawQuery != query {
  355. t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query)
  356. }
  357. }
  358. func randString(n int) string {
  359. rnd := rand.New(rand.NewSource(int64(n)))
  360. b := make([]byte, n)
  361. for i := range b {
  362. b[i] = byte(rnd.Intn(256))
  363. }
  364. return string(b)
  365. }
  366. type panicReader struct{}
  367. func (panicReader) Read([]byte) (int, error) { panic("unexpected Read") }
  368. func (panicReader) Close() error { panic("unexpected Close") }
  369. func TestActualContentLength(t *testing.T) {
  370. tests := []struct {
  371. req *http.Request
  372. want int64
  373. }{
  374. // Verify we don't read from Body:
  375. 0: {
  376. req: &http.Request{Body: panicReader{}},
  377. want: -1,
  378. },
  379. // nil Body means 0, regardless of ContentLength:
  380. 1: {
  381. req: &http.Request{Body: nil, ContentLength: 5},
  382. want: 0,
  383. },
  384. // ContentLength is used if set.
  385. 2: {
  386. req: &http.Request{Body: panicReader{}, ContentLength: 5},
  387. want: 5,
  388. },
  389. // http.NoBody means 0, not -1.
  390. 3: {
  391. req: &http.Request{Body: go18httpNoBody()},
  392. want: 0,
  393. },
  394. }
  395. for i, tt := range tests {
  396. got := actualContentLength(tt.req)
  397. if got != tt.want {
  398. t.Errorf("test[%d]: got %d; want %d", i, got, tt.want)
  399. }
  400. }
  401. }
  402. func TestTransportBody(t *testing.T) {
  403. bodyTests := []struct {
  404. body string
  405. noContentLen bool
  406. }{
  407. {body: "some message"},
  408. {body: "some message", noContentLen: true},
  409. {body: strings.Repeat("a", 1<<20), noContentLen: true},
  410. {body: strings.Repeat("a", 1<<20)},
  411. {body: randString(16<<10 - 1)},
  412. {body: randString(16 << 10)},
  413. {body: randString(16<<10 + 1)},
  414. {body: randString(512<<10 - 1)},
  415. {body: randString(512 << 10)},
  416. {body: randString(512<<10 + 1)},
  417. {body: randString(1<<20 - 1)},
  418. {body: randString(1 << 20)},
  419. {body: randString(1<<20 + 2)},
  420. }
  421. type reqInfo struct {
  422. req *http.Request
  423. slurp []byte
  424. err error
  425. }
  426. gotc := make(chan reqInfo, 1)
  427. st := newServerTester(t,
  428. func(w http.ResponseWriter, r *http.Request) {
  429. slurp, err := ioutil.ReadAll(r.Body)
  430. if err != nil {
  431. gotc <- reqInfo{err: err}
  432. } else {
  433. gotc <- reqInfo{req: r, slurp: slurp}
  434. }
  435. },
  436. optOnlyServer,
  437. )
  438. defer st.Close()
  439. for i, tt := range bodyTests {
  440. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  441. defer tr.CloseIdleConnections()
  442. var body io.Reader = strings.NewReader(tt.body)
  443. if tt.noContentLen {
  444. body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods
  445. }
  446. req, err := http.NewRequest("POST", st.ts.URL, body)
  447. if err != nil {
  448. t.Fatalf("#%d: %v", i, err)
  449. }
  450. c := &http.Client{Transport: tr}
  451. res, err := c.Do(req)
  452. if err != nil {
  453. t.Fatalf("#%d: %v", i, err)
  454. }
  455. defer res.Body.Close()
  456. ri := <-gotc
  457. if ri.err != nil {
  458. t.Errorf("#%d: read error: %v", i, ri.err)
  459. continue
  460. }
  461. if got := string(ri.slurp); got != tt.body {
  462. t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body))
  463. }
  464. wantLen := int64(len(tt.body))
  465. if tt.noContentLen && tt.body != "" {
  466. wantLen = -1
  467. }
  468. if ri.req.ContentLength != wantLen {
  469. t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen)
  470. }
  471. }
  472. }
  473. func shortString(v string) string {
  474. const maxLen = 100
  475. if len(v) <= maxLen {
  476. return v
  477. }
  478. return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:])
  479. }
  480. func TestTransportDialTLS(t *testing.T) {
  481. var mu sync.Mutex // guards following
  482. var gotReq, didDial bool
  483. ts := newServerTester(t,
  484. func(w http.ResponseWriter, r *http.Request) {
  485. mu.Lock()
  486. gotReq = true
  487. mu.Unlock()
  488. },
  489. optOnlyServer,
  490. )
  491. defer ts.Close()
  492. tr := &Transport{
  493. DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {
  494. mu.Lock()
  495. didDial = true
  496. mu.Unlock()
  497. cfg.InsecureSkipVerify = true
  498. c, err := tls.Dial(netw, addr, cfg)
  499. if err != nil {
  500. return nil, err
  501. }
  502. return c, c.Handshake()
  503. },
  504. }
  505. defer tr.CloseIdleConnections()
  506. client := &http.Client{Transport: tr}
  507. res, err := client.Get(ts.ts.URL)
  508. if err != nil {
  509. t.Fatal(err)
  510. }
  511. res.Body.Close()
  512. mu.Lock()
  513. if !gotReq {
  514. t.Error("didn't get request")
  515. }
  516. if !didDial {
  517. t.Error("didn't use dial hook")
  518. }
  519. }
  520. func TestConfigureTransport(t *testing.T) {
  521. t1 := &http.Transport{}
  522. err := ConfigureTransport(t1)
  523. if err == errTransportVersion {
  524. t.Skip(err)
  525. }
  526. if err != nil {
  527. t.Fatal(err)
  528. }
  529. if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) {
  530. // Laziness, to avoid buildtags.
  531. t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got)
  532. }
  533. wantNextProtos := []string{"h2", "http/1.1"}
  534. if t1.TLSClientConfig == nil {
  535. t.Errorf("nil t1.TLSClientConfig")
  536. } else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) {
  537. t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos)
  538. }
  539. if err := ConfigureTransport(t1); err == nil {
  540. t.Error("unexpected success on second call to ConfigureTransport")
  541. }
  542. // And does it work?
  543. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  544. io.WriteString(w, r.Proto)
  545. }, optOnlyServer)
  546. defer st.Close()
  547. t1.TLSClientConfig.InsecureSkipVerify = true
  548. c := &http.Client{Transport: t1}
  549. res, err := c.Get(st.ts.URL)
  550. if err != nil {
  551. t.Fatal(err)
  552. }
  553. slurp, err := ioutil.ReadAll(res.Body)
  554. if err != nil {
  555. t.Fatal(err)
  556. }
  557. if got, want := string(slurp), "HTTP/2.0"; got != want {
  558. t.Errorf("body = %q; want %q", got, want)
  559. }
  560. }
  561. type capitalizeReader struct {
  562. r io.Reader
  563. }
  564. func (cr capitalizeReader) Read(p []byte) (n int, err error) {
  565. n, err = cr.r.Read(p)
  566. for i, b := range p[:n] {
  567. if b >= 'a' && b <= 'z' {
  568. p[i] = b - ('a' - 'A')
  569. }
  570. }
  571. return
  572. }
  573. type flushWriter struct {
  574. w io.Writer
  575. }
  576. func (fw flushWriter) Write(p []byte) (n int, err error) {
  577. n, err = fw.w.Write(p)
  578. if f, ok := fw.w.(http.Flusher); ok {
  579. f.Flush()
  580. }
  581. return
  582. }
  583. type clientTester struct {
  584. t *testing.T
  585. tr *Transport
  586. sc, cc net.Conn // server and client conn
  587. fr *Framer // server's framer
  588. client func() error
  589. server func() error
  590. }
  591. func newClientTester(t *testing.T) *clientTester {
  592. var dialOnce struct {
  593. sync.Mutex
  594. dialed bool
  595. }
  596. ct := &clientTester{
  597. t: t,
  598. }
  599. ct.tr = &Transport{
  600. TLSClientConfig: tlsConfigInsecure,
  601. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  602. dialOnce.Lock()
  603. defer dialOnce.Unlock()
  604. if dialOnce.dialed {
  605. return nil, errors.New("only one dial allowed in test mode")
  606. }
  607. dialOnce.dialed = true
  608. return ct.cc, nil
  609. },
  610. }
  611. ln := newLocalListener(t)
  612. cc, err := net.Dial("tcp", ln.Addr().String())
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. sc, err := ln.Accept()
  617. if err != nil {
  618. t.Fatal(err)
  619. }
  620. ln.Close()
  621. ct.cc = cc
  622. ct.sc = sc
  623. ct.fr = NewFramer(sc, sc)
  624. return ct
  625. }
  626. func newLocalListener(t *testing.T) net.Listener {
  627. ln, err := net.Listen("tcp4", "127.0.0.1:0")
  628. if err == nil {
  629. return ln
  630. }
  631. ln, err = net.Listen("tcp6", "[::1]:0")
  632. if err != nil {
  633. t.Fatal(err)
  634. }
  635. return ln
  636. }
  637. func (ct *clientTester) greet() {
  638. buf := make([]byte, len(ClientPreface))
  639. _, err := io.ReadFull(ct.sc, buf)
  640. if err != nil {
  641. ct.t.Fatalf("reading client preface: %v", err)
  642. }
  643. f, err := ct.fr.ReadFrame()
  644. if err != nil {
  645. ct.t.Fatalf("Reading client settings frame: %v", err)
  646. }
  647. if sf, ok := f.(*SettingsFrame); !ok {
  648. ct.t.Fatalf("Wanted client settings frame; got %v", f)
  649. _ = sf // stash it away?
  650. }
  651. if err := ct.fr.WriteSettings(); err != nil {
  652. ct.t.Fatal(err)
  653. }
  654. if err := ct.fr.WriteSettingsAck(); err != nil {
  655. ct.t.Fatal(err)
  656. }
  657. }
  658. func (ct *clientTester) readNonSettingsFrame() (Frame, error) {
  659. for {
  660. f, err := ct.fr.ReadFrame()
  661. if err != nil {
  662. return nil, err
  663. }
  664. if _, ok := f.(*SettingsFrame); ok {
  665. continue
  666. }
  667. return f, nil
  668. }
  669. }
  670. func (ct *clientTester) cleanup() {
  671. ct.tr.CloseIdleConnections()
  672. }
  673. func (ct *clientTester) run() {
  674. errc := make(chan error, 2)
  675. ct.start("client", errc, ct.client)
  676. ct.start("server", errc, ct.server)
  677. defer ct.cleanup()
  678. for i := 0; i < 2; i++ {
  679. if err := <-errc; err != nil {
  680. ct.t.Error(err)
  681. return
  682. }
  683. }
  684. }
  685. func (ct *clientTester) start(which string, errc chan<- error, fn func() error) {
  686. go func() {
  687. finished := false
  688. var err error
  689. defer func() {
  690. if !finished {
  691. err = fmt.Errorf("%s goroutine didn't finish.", which)
  692. } else if err != nil {
  693. err = fmt.Errorf("%s: %v", which, err)
  694. }
  695. errc <- err
  696. }()
  697. err = fn()
  698. finished = true
  699. }()
  700. }
  701. func (ct *clientTester) readFrame() (Frame, error) {
  702. return readFrameTimeout(ct.fr, 2*time.Second)
  703. }
  704. func (ct *clientTester) firstHeaders() (*HeadersFrame, error) {
  705. for {
  706. f, err := ct.readFrame()
  707. if err != nil {
  708. return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
  709. }
  710. switch f.(type) {
  711. case *WindowUpdateFrame, *SettingsFrame:
  712. continue
  713. }
  714. hf, ok := f.(*HeadersFrame)
  715. if !ok {
  716. return nil, fmt.Errorf("Got %T; want HeadersFrame", f)
  717. }
  718. return hf, nil
  719. }
  720. }
  721. type countingReader struct {
  722. n *int64
  723. }
  724. func (r countingReader) Read(p []byte) (n int, err error) {
  725. for i := range p {
  726. p[i] = byte(i)
  727. }
  728. atomic.AddInt64(r.n, int64(len(p)))
  729. return len(p), err
  730. }
  731. func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) }
  732. func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) }
  733. func testTransportReqBodyAfterResponse(t *testing.T, status int) {
  734. const bodySize = 10 << 20
  735. clientDone := make(chan struct{})
  736. ct := newClientTester(t)
  737. ct.client = func() error {
  738. defer ct.cc.(*net.TCPConn).CloseWrite()
  739. defer close(clientDone)
  740. var n int64 // atomic
  741. req, err := http.NewRequest("PUT", "https://dummy.tld/", io.LimitReader(countingReader{&n}, bodySize))
  742. if err != nil {
  743. return err
  744. }
  745. res, err := ct.tr.RoundTrip(req)
  746. if err != nil {
  747. return fmt.Errorf("RoundTrip: %v", err)
  748. }
  749. defer res.Body.Close()
  750. if res.StatusCode != status {
  751. return fmt.Errorf("status code = %v; want %v", res.StatusCode, status)
  752. }
  753. slurp, err := ioutil.ReadAll(res.Body)
  754. if err != nil {
  755. return fmt.Errorf("Slurp: %v", err)
  756. }
  757. if len(slurp) > 0 {
  758. return fmt.Errorf("unexpected body: %q", slurp)
  759. }
  760. if status == 200 {
  761. if got := atomic.LoadInt64(&n); got != bodySize {
  762. return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize)
  763. }
  764. } else {
  765. if got := atomic.LoadInt64(&n); got == 0 || got >= bodySize {
  766. return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize)
  767. }
  768. }
  769. return nil
  770. }
  771. ct.server = func() error {
  772. ct.greet()
  773. var buf bytes.Buffer
  774. enc := hpack.NewEncoder(&buf)
  775. var dataRecv int64
  776. var closed bool
  777. for {
  778. f, err := ct.fr.ReadFrame()
  779. if err != nil {
  780. select {
  781. case <-clientDone:
  782. // If the client's done, it
  783. // will have reported any
  784. // errors on its side.
  785. return nil
  786. default:
  787. return err
  788. }
  789. }
  790. //println(fmt.Sprintf("server got frame: %v", f))
  791. switch f := f.(type) {
  792. case *WindowUpdateFrame, *SettingsFrame:
  793. case *HeadersFrame:
  794. if !f.HeadersEnded() {
  795. return fmt.Errorf("headers should have END_HEADERS be ended: %v", f)
  796. }
  797. if f.StreamEnded() {
  798. return fmt.Errorf("headers contains END_STREAM unexpectedly: %v", f)
  799. }
  800. case *DataFrame:
  801. dataLen := len(f.Data())
  802. if dataLen > 0 {
  803. if dataRecv == 0 {
  804. enc.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)})
  805. ct.fr.WriteHeaders(HeadersFrameParam{
  806. StreamID: f.StreamID,
  807. EndHeaders: true,
  808. EndStream: false,
  809. BlockFragment: buf.Bytes(),
  810. })
  811. }
  812. if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil {
  813. return err
  814. }
  815. if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil {
  816. return err
  817. }
  818. }
  819. dataRecv += int64(dataLen)
  820. if !closed && ((status != 200 && dataRecv > 0) ||
  821. (status == 200 && dataRecv == bodySize)) {
  822. closed = true
  823. if err := ct.fr.WriteData(f.StreamID, true, nil); err != nil {
  824. return err
  825. }
  826. }
  827. default:
  828. return fmt.Errorf("Unexpected client frame %v", f)
  829. }
  830. }
  831. }
  832. ct.run()
  833. }
  834. // See golang.org/issue/13444
  835. func TestTransportFullDuplex(t *testing.T) {
  836. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  837. w.WriteHeader(200) // redundant but for clarity
  838. w.(http.Flusher).Flush()
  839. io.Copy(flushWriter{w}, capitalizeReader{r.Body})
  840. fmt.Fprintf(w, "bye.\n")
  841. }, optOnlyServer)
  842. defer st.Close()
  843. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  844. defer tr.CloseIdleConnections()
  845. c := &http.Client{Transport: tr}
  846. pr, pw := io.Pipe()
  847. req, err := http.NewRequest("PUT", st.ts.URL, ioutil.NopCloser(pr))
  848. if err != nil {
  849. t.Fatal(err)
  850. }
  851. req.ContentLength = -1
  852. res, err := c.Do(req)
  853. if err != nil {
  854. t.Fatal(err)
  855. }
  856. defer res.Body.Close()
  857. if res.StatusCode != 200 {
  858. t.Fatalf("StatusCode = %v; want %v", res.StatusCode, 200)
  859. }
  860. bs := bufio.NewScanner(res.Body)
  861. want := func(v string) {
  862. if !bs.Scan() {
  863. t.Fatalf("wanted to read %q but Scan() = false, err = %v", v, bs.Err())
  864. }
  865. }
  866. write := func(v string) {
  867. _, err := io.WriteString(pw, v)
  868. if err != nil {
  869. t.Fatalf("pipe write: %v", err)
  870. }
  871. }
  872. write("foo\n")
  873. want("FOO")
  874. write("bar\n")
  875. want("BAR")
  876. pw.Close()
  877. want("bye.")
  878. if err := bs.Err(); err != nil {
  879. t.Fatal(err)
  880. }
  881. }
  882. func TestTransportConnectRequest(t *testing.T) {
  883. gotc := make(chan *http.Request, 1)
  884. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  885. gotc <- r
  886. }, optOnlyServer)
  887. defer st.Close()
  888. u, err := url.Parse(st.ts.URL)
  889. if err != nil {
  890. t.Fatal(err)
  891. }
  892. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  893. defer tr.CloseIdleConnections()
  894. c := &http.Client{Transport: tr}
  895. tests := []struct {
  896. req *http.Request
  897. want string
  898. }{
  899. {
  900. req: &http.Request{
  901. Method: "CONNECT",
  902. Header: http.Header{},
  903. URL: u,
  904. },
  905. want: u.Host,
  906. },
  907. {
  908. req: &http.Request{
  909. Method: "CONNECT",
  910. Header: http.Header{},
  911. URL: u,
  912. Host: "example.com:123",
  913. },
  914. want: "example.com:123",
  915. },
  916. }
  917. for i, tt := range tests {
  918. res, err := c.Do(tt.req)
  919. if err != nil {
  920. t.Errorf("%d. RoundTrip = %v", i, err)
  921. continue
  922. }
  923. res.Body.Close()
  924. req := <-gotc
  925. if req.Method != "CONNECT" {
  926. t.Errorf("method = %q; want CONNECT", req.Method)
  927. }
  928. if req.Host != tt.want {
  929. t.Errorf("Host = %q; want %q", req.Host, tt.want)
  930. }
  931. if req.URL.Host != tt.want {
  932. t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want)
  933. }
  934. }
  935. }
  936. type headerType int
  937. const (
  938. noHeader headerType = iota // omitted
  939. oneHeader
  940. splitHeader // broken into continuation on purpose
  941. )
  942. const (
  943. f0 = noHeader
  944. f1 = oneHeader
  945. f2 = splitHeader
  946. d0 = false
  947. d1 = true
  948. )
  949. // Test all 36 combinations of response frame orders:
  950. // (3 ways of 100-continue) * (2 ways of headers) * (2 ways of data) * (3 ways of trailers):func TestTransportResponsePattern_00f0(t *testing.T) { testTransportResponsePattern(h0, h1, false, h0) }
  951. // Generated by http://play.golang.org/p/SScqYKJYXd
  952. func TestTransportResPattern_c0h1d0t0(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f0) }
  953. func TestTransportResPattern_c0h1d0t1(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f1) }
  954. func TestTransportResPattern_c0h1d0t2(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f2) }
  955. func TestTransportResPattern_c0h1d1t0(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f0) }
  956. func TestTransportResPattern_c0h1d1t1(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f1) }
  957. func TestTransportResPattern_c0h1d1t2(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f2) }
  958. func TestTransportResPattern_c0h2d0t0(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f0) }
  959. func TestTransportResPattern_c0h2d0t1(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f1) }
  960. func TestTransportResPattern_c0h2d0t2(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f2) }
  961. func TestTransportResPattern_c0h2d1t0(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f0) }
  962. func TestTransportResPattern_c0h2d1t1(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f1) }
  963. func TestTransportResPattern_c0h2d1t2(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f2) }
  964. func TestTransportResPattern_c1h1d0t0(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f0) }
  965. func TestTransportResPattern_c1h1d0t1(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f1) }
  966. func TestTransportResPattern_c1h1d0t2(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f2) }
  967. func TestTransportResPattern_c1h1d1t0(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f0) }
  968. func TestTransportResPattern_c1h1d1t1(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f1) }
  969. func TestTransportResPattern_c1h1d1t2(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f2) }
  970. func TestTransportResPattern_c1h2d0t0(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f0) }
  971. func TestTransportResPattern_c1h2d0t1(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f1) }
  972. func TestTransportResPattern_c1h2d0t2(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f2) }
  973. func TestTransportResPattern_c1h2d1t0(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f0) }
  974. func TestTransportResPattern_c1h2d1t1(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f1) }
  975. func TestTransportResPattern_c1h2d1t2(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f2) }
  976. func TestTransportResPattern_c2h1d0t0(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f0) }
  977. func TestTransportResPattern_c2h1d0t1(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f1) }
  978. func TestTransportResPattern_c2h1d0t2(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f2) }
  979. func TestTransportResPattern_c2h1d1t0(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f0) }
  980. func TestTransportResPattern_c2h1d1t1(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f1) }
  981. func TestTransportResPattern_c2h1d1t2(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f2) }
  982. func TestTransportResPattern_c2h2d0t0(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f0) }
  983. func TestTransportResPattern_c2h2d0t1(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f1) }
  984. func TestTransportResPattern_c2h2d0t2(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f2) }
  985. func TestTransportResPattern_c2h2d1t0(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f0) }
  986. func TestTransportResPattern_c2h2d1t1(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f1) }
  987. func TestTransportResPattern_c2h2d1t2(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f2) }
  988. func testTransportResPattern(t *testing.T, expect100Continue, resHeader headerType, withData bool, trailers headerType) {
  989. const reqBody = "some request body"
  990. const resBody = "some response body"
  991. if resHeader == noHeader {
  992. // TODO: test 100-continue followed by immediate
  993. // server stream reset, without headers in the middle?
  994. panic("invalid combination")
  995. }
  996. ct := newClientTester(t)
  997. ct.client = func() error {
  998. req, _ := http.NewRequest("POST", "https://dummy.tld/", strings.NewReader(reqBody))
  999. if expect100Continue != noHeader {
  1000. req.Header.Set("Expect", "100-continue")
  1001. }
  1002. res, err := ct.tr.RoundTrip(req)
  1003. if err != nil {
  1004. return fmt.Errorf("RoundTrip: %v", err)
  1005. }
  1006. defer res.Body.Close()
  1007. if res.StatusCode != 200 {
  1008. return fmt.Errorf("status code = %v; want 200", res.StatusCode)
  1009. }
  1010. slurp, err := ioutil.ReadAll(res.Body)
  1011. if err != nil {
  1012. return fmt.Errorf("Slurp: %v", err)
  1013. }
  1014. wantBody := resBody
  1015. if !withData {
  1016. wantBody = ""
  1017. }
  1018. if string(slurp) != wantBody {
  1019. return fmt.Errorf("body = %q; want %q", slurp, wantBody)
  1020. }
  1021. if trailers == noHeader {
  1022. if len(res.Trailer) > 0 {
  1023. t.Errorf("Trailer = %v; want none", res.Trailer)
  1024. }
  1025. } else {
  1026. want := http.Header{"Some-Trailer": {"some-value"}}
  1027. if !reflect.DeepEqual(res.Trailer, want) {
  1028. t.Errorf("Trailer = %v; want %v", res.Trailer, want)
  1029. }
  1030. }
  1031. return nil
  1032. }
  1033. ct.server = func() error {
  1034. ct.greet()
  1035. var buf bytes.Buffer
  1036. enc := hpack.NewEncoder(&buf)
  1037. for {
  1038. f, err := ct.fr.ReadFrame()
  1039. if err != nil {
  1040. return err
  1041. }
  1042. endStream := false
  1043. send := func(mode headerType) {
  1044. hbf := buf.Bytes()
  1045. switch mode {
  1046. case oneHeader:
  1047. ct.fr.WriteHeaders(HeadersFrameParam{
  1048. StreamID: f.Header().StreamID,
  1049. EndHeaders: true,
  1050. EndStream: endStream,
  1051. BlockFragment: hbf,
  1052. })
  1053. case splitHeader:
  1054. if len(hbf) < 2 {
  1055. panic("too small")
  1056. }
  1057. ct.fr.WriteHeaders(HeadersFrameParam{
  1058. StreamID: f.Header().StreamID,
  1059. EndHeaders: false,
  1060. EndStream: endStream,
  1061. BlockFragment: hbf[:1],
  1062. })
  1063. ct.fr.WriteContinuation(f.Header().StreamID, true, hbf[1:])
  1064. default:
  1065. panic("bogus mode")
  1066. }
  1067. }
  1068. switch f := f.(type) {
  1069. case *WindowUpdateFrame, *SettingsFrame:
  1070. case *DataFrame:
  1071. if !f.StreamEnded() {
  1072. // No need to send flow control tokens. The test request body is tiny.
  1073. continue
  1074. }
  1075. // Response headers (1+ frames; 1 or 2 in this test, but never 0)
  1076. {
  1077. buf.Reset()
  1078. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1079. enc.WriteField(hpack.HeaderField{Name: "x-foo", Value: "blah"})
  1080. enc.WriteField(hpack.HeaderField{Name: "x-bar", Value: "more"})
  1081. if trailers != noHeader {
  1082. enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "some-trailer"})
  1083. }
  1084. endStream = withData == false && trailers == noHeader
  1085. send(resHeader)
  1086. }
  1087. if withData {
  1088. endStream = trailers == noHeader
  1089. ct.fr.WriteData(f.StreamID, endStream, []byte(resBody))
  1090. }
  1091. if trailers != noHeader {
  1092. endStream = true
  1093. buf.Reset()
  1094. enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "some-value"})
  1095. send(trailers)
  1096. }
  1097. if endStream {
  1098. return nil
  1099. }
  1100. case *HeadersFrame:
  1101. if expect100Continue != noHeader {
  1102. buf.Reset()
  1103. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"})
  1104. send(expect100Continue)
  1105. }
  1106. }
  1107. }
  1108. }
  1109. ct.run()
  1110. }
  1111. func TestTransportReceiveUndeclaredTrailer(t *testing.T) {
  1112. ct := newClientTester(t)
  1113. ct.client = func() error {
  1114. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  1115. res, err := ct.tr.RoundTrip(req)
  1116. if err != nil {
  1117. return fmt.Errorf("RoundTrip: %v", err)
  1118. }
  1119. defer res.Body.Close()
  1120. if res.StatusCode != 200 {
  1121. return fmt.Errorf("status code = %v; want 200", res.StatusCode)
  1122. }
  1123. slurp, err := ioutil.ReadAll(res.Body)
  1124. if err != nil {
  1125. return fmt.Errorf("res.Body ReadAll error = %q, %v; want %v", slurp, err, nil)
  1126. }
  1127. if len(slurp) > 0 {
  1128. return fmt.Errorf("body = %q; want nothing", slurp)
  1129. }
  1130. if _, ok := res.Trailer["Some-Trailer"]; !ok {
  1131. return fmt.Errorf("expected Some-Trailer")
  1132. }
  1133. return nil
  1134. }
  1135. ct.server = func() error {
  1136. ct.greet()
  1137. var n int
  1138. var hf *HeadersFrame
  1139. for hf == nil && n < 10 {
  1140. f, err := ct.fr.ReadFrame()
  1141. if err != nil {
  1142. return err
  1143. }
  1144. hf, _ = f.(*HeadersFrame)
  1145. n++
  1146. }
  1147. var buf bytes.Buffer
  1148. enc := hpack.NewEncoder(&buf)
  1149. // send headers without Trailer header
  1150. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1151. ct.fr.WriteHeaders(HeadersFrameParam{
  1152. StreamID: hf.StreamID,
  1153. EndHeaders: true,
  1154. EndStream: false,
  1155. BlockFragment: buf.Bytes(),
  1156. })
  1157. // send trailers
  1158. buf.Reset()
  1159. enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "I'm an undeclared Trailer!"})
  1160. ct.fr.WriteHeaders(HeadersFrameParam{
  1161. StreamID: hf.StreamID,
  1162. EndHeaders: true,
  1163. EndStream: true,
  1164. BlockFragment: buf.Bytes(),
  1165. })
  1166. return nil
  1167. }
  1168. ct.run()
  1169. }
  1170. func TestTransportInvalidTrailer_Pseudo1(t *testing.T) {
  1171. testTransportInvalidTrailer_Pseudo(t, oneHeader)
  1172. }
  1173. func TestTransportInvalidTrailer_Pseudo2(t *testing.T) {
  1174. testTransportInvalidTrailer_Pseudo(t, splitHeader)
  1175. }
  1176. func testTransportInvalidTrailer_Pseudo(t *testing.T, trailers headerType) {
  1177. testInvalidTrailer(t, trailers, pseudoHeaderError(":colon"), func(enc *hpack.Encoder) {
  1178. enc.WriteField(hpack.HeaderField{Name: ":colon", Value: "foo"})
  1179. enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"})
  1180. })
  1181. }
  1182. func TestTransportInvalidTrailer_Capital1(t *testing.T) {
  1183. testTransportInvalidTrailer_Capital(t, oneHeader)
  1184. }
  1185. func TestTransportInvalidTrailer_Capital2(t *testing.T) {
  1186. testTransportInvalidTrailer_Capital(t, splitHeader)
  1187. }
  1188. func testTransportInvalidTrailer_Capital(t *testing.T, trailers headerType) {
  1189. testInvalidTrailer(t, trailers, headerFieldNameError("Capital"), func(enc *hpack.Encoder) {
  1190. enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"})
  1191. enc.WriteField(hpack.HeaderField{Name: "Capital", Value: "bad"})
  1192. })
  1193. }
  1194. func TestTransportInvalidTrailer_EmptyFieldName(t *testing.T) {
  1195. testInvalidTrailer(t, oneHeader, headerFieldNameError(""), func(enc *hpack.Encoder) {
  1196. enc.WriteField(hpack.HeaderField{Name: "", Value: "bad"})
  1197. })
  1198. }
  1199. func TestTransportInvalidTrailer_BinaryFieldValue(t *testing.T) {
  1200. testInvalidTrailer(t, oneHeader, headerFieldValueError("has\nnewline"), func(enc *hpack.Encoder) {
  1201. enc.WriteField(hpack.HeaderField{Name: "x", Value: "has\nnewline"})
  1202. })
  1203. }
  1204. func testInvalidTrailer(t *testing.T, trailers headerType, wantErr error, writeTrailer func(*hpack.Encoder)) {
  1205. ct := newClientTester(t)
  1206. ct.client = func() error {
  1207. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  1208. res, err := ct.tr.RoundTrip(req)
  1209. if err != nil {
  1210. return fmt.Errorf("RoundTrip: %v", err)
  1211. }
  1212. defer res.Body.Close()
  1213. if res.StatusCode != 200 {
  1214. return fmt.Errorf("status code = %v; want 200", res.StatusCode)
  1215. }
  1216. slurp, err := ioutil.ReadAll(res.Body)
  1217. se, ok := err.(StreamError)
  1218. if !ok || se.Cause != wantErr {
  1219. return fmt.Errorf("res.Body ReadAll error = %q, %#v; want StreamError with cause %T, %#v", slurp, err, wantErr, wantErr)
  1220. }
  1221. if len(slurp) > 0 {
  1222. return fmt.Errorf("body = %q; want nothing", slurp)
  1223. }
  1224. return nil
  1225. }
  1226. ct.server = func() error {
  1227. ct.greet()
  1228. var buf bytes.Buffer
  1229. enc := hpack.NewEncoder(&buf)
  1230. for {
  1231. f, err := ct.fr.ReadFrame()
  1232. if err != nil {
  1233. return err
  1234. }
  1235. switch f := f.(type) {
  1236. case *HeadersFrame:
  1237. var endStream bool
  1238. send := func(mode headerType) {
  1239. hbf := buf.Bytes()
  1240. switch mode {
  1241. case oneHeader:
  1242. ct.fr.WriteHeaders(HeadersFrameParam{
  1243. StreamID: f.StreamID,
  1244. EndHeaders: true,
  1245. EndStream: endStream,
  1246. BlockFragment: hbf,
  1247. })
  1248. case splitHeader:
  1249. if len(hbf) < 2 {
  1250. panic("too small")
  1251. }
  1252. ct.fr.WriteHeaders(HeadersFrameParam{
  1253. StreamID: f.StreamID,
  1254. EndHeaders: false,
  1255. EndStream: endStream,
  1256. BlockFragment: hbf[:1],
  1257. })
  1258. ct.fr.WriteContinuation(f.StreamID, true, hbf[1:])
  1259. default:
  1260. panic("bogus mode")
  1261. }
  1262. }
  1263. // Response headers (1+ frames; 1 or 2 in this test, but never 0)
  1264. {
  1265. buf.Reset()
  1266. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1267. enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "declared"})
  1268. endStream = false
  1269. send(oneHeader)
  1270. }
  1271. // Trailers:
  1272. {
  1273. endStream = true
  1274. buf.Reset()
  1275. writeTrailer(enc)
  1276. send(trailers)
  1277. }
  1278. return nil
  1279. }
  1280. }
  1281. }
  1282. ct.run()
  1283. }
  1284. func TestTransportChecksResponseHeaderListSize(t *testing.T) {
  1285. ct := newClientTester(t)
  1286. ct.client = func() error {
  1287. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  1288. res, err := ct.tr.RoundTrip(req)
  1289. if err != errResponseHeaderListSize {
  1290. if res != nil {
  1291. res.Body.Close()
  1292. }
  1293. size := int64(0)
  1294. for k, vv := range res.Header {
  1295. for _, v := range vv {
  1296. size += int64(len(k)) + int64(len(v)) + 32
  1297. }
  1298. }
  1299. return fmt.Errorf("RoundTrip Error = %v (and %d bytes of response headers); want errResponseHeaderListSize", err, size)
  1300. }
  1301. return nil
  1302. }
  1303. ct.server = func() error {
  1304. ct.greet()
  1305. var buf bytes.Buffer
  1306. enc := hpack.NewEncoder(&buf)
  1307. for {
  1308. f, err := ct.fr.ReadFrame()
  1309. if err != nil {
  1310. return err
  1311. }
  1312. switch f := f.(type) {
  1313. case *HeadersFrame:
  1314. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1315. large := strings.Repeat("a", 1<<10)
  1316. for i := 0; i < 5042; i++ {
  1317. enc.WriteField(hpack.HeaderField{Name: large, Value: large})
  1318. }
  1319. if size, want := buf.Len(), 6329; size != want {
  1320. // Note: this number might change if
  1321. // our hpack implementation
  1322. // changes. That's fine. This is
  1323. // just a sanity check that our
  1324. // response can fit in a single
  1325. // header block fragment frame.
  1326. return fmt.Errorf("encoding over 10MB of duplicate keypairs took %d bytes; expected %d", size, want)
  1327. }
  1328. ct.fr.WriteHeaders(HeadersFrameParam{
  1329. StreamID: f.StreamID,
  1330. EndHeaders: true,
  1331. EndStream: true,
  1332. BlockFragment: buf.Bytes(),
  1333. })
  1334. return nil
  1335. }
  1336. }
  1337. }
  1338. ct.run()
  1339. }
  1340. // Test that the the Transport returns a typed error from Response.Body.Read calls
  1341. // when the server sends an error. (here we use a panic, since that should generate
  1342. // a stream error, but others like cancel should be similar)
  1343. func TestTransportBodyReadErrorType(t *testing.T) {
  1344. doPanic := make(chan bool, 1)
  1345. st := newServerTester(t,
  1346. func(w http.ResponseWriter, r *http.Request) {
  1347. w.(http.Flusher).Flush() // force headers out
  1348. <-doPanic
  1349. panic("boom")
  1350. },
  1351. optOnlyServer,
  1352. optQuiet,
  1353. )
  1354. defer st.Close()
  1355. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  1356. defer tr.CloseIdleConnections()
  1357. c := &http.Client{Transport: tr}
  1358. res, err := c.Get(st.ts.URL)
  1359. if err != nil {
  1360. t.Fatal(err)
  1361. }
  1362. defer res.Body.Close()
  1363. doPanic <- true
  1364. buf := make([]byte, 100)
  1365. n, err := res.Body.Read(buf)
  1366. want := StreamError{StreamID: 0x1, Code: 0x2}
  1367. if !reflect.DeepEqual(want, err) {
  1368. t.Errorf("Read = %v, %#v; want error %#v", n, err, want)
  1369. }
  1370. }
  1371. // golang.org/issue/13924
  1372. // This used to fail after many iterations, especially with -race:
  1373. // go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race
  1374. func TestTransportDoubleCloseOnWriteError(t *testing.T) {
  1375. var (
  1376. mu sync.Mutex
  1377. conn net.Conn // to close if set
  1378. )
  1379. st := newServerTester(t,
  1380. func(w http.ResponseWriter, r *http.Request) {
  1381. mu.Lock()
  1382. defer mu.Unlock()
  1383. if conn != nil {
  1384. conn.Close()
  1385. }
  1386. },
  1387. optOnlyServer,
  1388. )
  1389. defer st.Close()
  1390. tr := &Transport{
  1391. TLSClientConfig: tlsConfigInsecure,
  1392. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  1393. tc, err := tls.Dial(network, addr, cfg)
  1394. if err != nil {
  1395. return nil, err
  1396. }
  1397. mu.Lock()
  1398. defer mu.Unlock()
  1399. conn = tc
  1400. return tc, nil
  1401. },
  1402. }
  1403. defer tr.CloseIdleConnections()
  1404. c := &http.Client{Transport: tr}
  1405. c.Get(st.ts.URL)
  1406. }
  1407. // Test that the http1 Transport.DisableKeepAlives option is respected
  1408. // and connections are closed as soon as idle.
  1409. // See golang.org/issue/14008
  1410. func TestTransportDisableKeepAlives(t *testing.T) {
  1411. st := newServerTester(t,
  1412. func(w http.ResponseWriter, r *http.Request) {
  1413. io.WriteString(w, "hi")
  1414. },
  1415. optOnlyServer,
  1416. )
  1417. defer st.Close()
  1418. connClosed := make(chan struct{}) // closed on tls.Conn.Close
  1419. tr := &Transport{
  1420. t1: &http.Transport{
  1421. DisableKeepAlives: true,
  1422. },
  1423. TLSClientConfig: tlsConfigInsecure,
  1424. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  1425. tc, err := tls.Dial(network, addr, cfg)
  1426. if err != nil {
  1427. return nil, err
  1428. }
  1429. return &noteCloseConn{Conn: tc, closefn: func() { close(connClosed) }}, nil
  1430. },
  1431. }
  1432. c := &http.Client{Transport: tr}
  1433. res, err := c.Get(st.ts.URL)
  1434. if err != nil {
  1435. t.Fatal(err)
  1436. }
  1437. if _, err := ioutil.ReadAll(res.Body); err != nil {
  1438. t.Fatal(err)
  1439. }
  1440. defer res.Body.Close()
  1441. select {
  1442. case <-connClosed:
  1443. case <-time.After(1 * time.Second):
  1444. t.Errorf("timeout")
  1445. }
  1446. }
  1447. // Test concurrent requests with Transport.DisableKeepAlives. We can share connections,
  1448. // but when things are totally idle, it still needs to close.
  1449. func TestTransportDisableKeepAlives_Concurrency(t *testing.T) {
  1450. const D = 25 * time.Millisecond
  1451. st := newServerTester(t,
  1452. func(w http.ResponseWriter, r *http.Request) {
  1453. time.Sleep(D)
  1454. io.WriteString(w, "hi")
  1455. },
  1456. optOnlyServer,
  1457. )
  1458. defer st.Close()
  1459. var dials int32
  1460. var conns sync.WaitGroup
  1461. tr := &Transport{
  1462. t1: &http.Transport{
  1463. DisableKeepAlives: true,
  1464. },
  1465. TLSClientConfig: tlsConfigInsecure,
  1466. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  1467. tc, err := tls.Dial(network, addr, cfg)
  1468. if err != nil {
  1469. return nil, err
  1470. }
  1471. atomic.AddInt32(&dials, 1)
  1472. conns.Add(1)
  1473. return &noteCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil
  1474. },
  1475. }
  1476. c := &http.Client{Transport: tr}
  1477. var reqs sync.WaitGroup
  1478. const N = 20
  1479. for i := 0; i < N; i++ {
  1480. reqs.Add(1)
  1481. if i == N-1 {
  1482. // For the final request, try to make all the
  1483. // others close. This isn't verified in the
  1484. // count, other than the Log statement, since
  1485. // it's so timing dependent. This test is
  1486. // really to make sure we don't interrupt a
  1487. // valid request.
  1488. time.Sleep(D * 2)
  1489. }
  1490. go func() {
  1491. defer reqs.Done()
  1492. res, err := c.Get(st.ts.URL)
  1493. if err != nil {
  1494. t.Error(err)
  1495. return
  1496. }
  1497. if _, err := ioutil.ReadAll(res.Body); err != nil {
  1498. t.Error(err)
  1499. return
  1500. }
  1501. res.Body.Close()
  1502. }()
  1503. }
  1504. reqs.Wait()
  1505. conns.Wait()
  1506. t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N)
  1507. }
  1508. type noteCloseConn struct {
  1509. net.Conn
  1510. onceClose sync.Once
  1511. closefn func()
  1512. }
  1513. func (c *noteCloseConn) Close() error {
  1514. c.onceClose.Do(c.closefn)
  1515. return c.Conn.Close()
  1516. }
  1517. func isTimeout(err error) bool {
  1518. switch err := err.(type) {
  1519. case nil:
  1520. return false
  1521. case *url.Error:
  1522. return isTimeout(err.Err)
  1523. case net.Error:
  1524. return err.Timeout()
  1525. }
  1526. return false
  1527. }
  1528. // Test that the http1 Transport.ResponseHeaderTimeout option and cancel is sent.
  1529. func TestTransportResponseHeaderTimeout_NoBody(t *testing.T) {
  1530. testTransportResponseHeaderTimeout(t, false)
  1531. }
  1532. func TestTransportResponseHeaderTimeout_Body(t *testing.T) {
  1533. testTransportResponseHeaderTimeout(t, true)
  1534. }
  1535. func testTransportResponseHeaderTimeout(t *testing.T, body bool) {
  1536. ct := newClientTester(t)
  1537. ct.tr.t1 = &http.Transport{
  1538. ResponseHeaderTimeout: 5 * time.Millisecond,
  1539. }
  1540. ct.client = func() error {
  1541. c := &http.Client{Transport: ct.tr}
  1542. var err error
  1543. var n int64
  1544. const bodySize = 4 << 20
  1545. if body {
  1546. _, err = c.Post("https://dummy.tld/", "text/foo", io.LimitReader(countingReader{&n}, bodySize))
  1547. } else {
  1548. _, err = c.Get("https://dummy.tld/")
  1549. }
  1550. if !isTimeout(err) {
  1551. t.Errorf("client expected timeout error; got %#v", err)
  1552. }
  1553. if body && n != bodySize {
  1554. t.Errorf("only read %d bytes of body; want %d", n, bodySize)
  1555. }
  1556. return nil
  1557. }
  1558. ct.server = func() error {
  1559. ct.greet()
  1560. for {
  1561. f, err := ct.fr.ReadFrame()
  1562. if err != nil {
  1563. t.Logf("ReadFrame: %v", err)
  1564. return nil
  1565. }
  1566. switch f := f.(type) {
  1567. case *DataFrame:
  1568. dataLen := len(f.Data())
  1569. if dataLen > 0 {
  1570. if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil {
  1571. return err
  1572. }
  1573. if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil {
  1574. return err
  1575. }
  1576. }
  1577. case *RSTStreamFrame:
  1578. if f.StreamID == 1 && f.ErrCode == ErrCodeCancel {
  1579. return nil
  1580. }
  1581. }
  1582. }
  1583. }
  1584. ct.run()
  1585. }
  1586. func TestTransportDisableCompression(t *testing.T) {
  1587. const body = "sup"
  1588. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1589. want := http.Header{
  1590. "User-Agent": []string{"Go-http-client/2.0"},
  1591. }
  1592. if !reflect.DeepEqual(r.Header, want) {
  1593. t.Errorf("request headers = %v; want %v", r.Header, want)
  1594. }
  1595. }, optOnlyServer)
  1596. defer st.Close()
  1597. tr := &Transport{
  1598. TLSClientConfig: tlsConfigInsecure,
  1599. t1: &http.Transport{
  1600. DisableCompression: true,
  1601. },
  1602. }
  1603. defer tr.CloseIdleConnections()
  1604. req, err := http.NewRequest("GET", st.ts.URL, nil)
  1605. if err != nil {
  1606. t.Fatal(err)
  1607. }
  1608. res, err := tr.RoundTrip(req)
  1609. if err != nil {
  1610. t.Fatal(err)
  1611. }
  1612. defer res.Body.Close()
  1613. }
  1614. // RFC 7540 section 8.1.2.2
  1615. func TestTransportRejectsConnHeaders(t *testing.T) {
  1616. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1617. var got []string
  1618. for k := range r.Header {
  1619. got = append(got, k)
  1620. }
  1621. sort.Strings(got)
  1622. w.Header().Set("Got-Header", strings.Join(got, ","))
  1623. }, optOnlyServer)
  1624. defer st.Close()
  1625. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  1626. defer tr.CloseIdleConnections()
  1627. tests := []struct {
  1628. key string
  1629. value []string
  1630. want string
  1631. }{
  1632. {
  1633. key: "Upgrade",
  1634. value: []string{"anything"},
  1635. want: "ERROR: http2: invalid Upgrade request header: [\"anything\"]",
  1636. },
  1637. {
  1638. key: "Connection",
  1639. value: []string{"foo"},
  1640. want: "ERROR: http2: invalid Connection request header: [\"foo\"]",
  1641. },
  1642. {
  1643. key: "Connection",
  1644. value: []string{"close"},
  1645. want: "Accept-Encoding,User-Agent",
  1646. },
  1647. {
  1648. key: "Connection",
  1649. value: []string{"close", "something-else"},
  1650. want: "ERROR: http2: invalid Connection request header: [\"close\" \"something-else\"]",
  1651. },
  1652. {
  1653. key: "Connection",
  1654. value: []string{"keep-alive"},
  1655. want: "Accept-Encoding,User-Agent",
  1656. },
  1657. {
  1658. key: "Proxy-Connection", // just deleted and ignored
  1659. value: []string{"keep-alive"},
  1660. want: "Accept-Encoding,User-Agent",
  1661. },
  1662. {
  1663. key: "Transfer-Encoding",
  1664. value: []string{""},
  1665. want: "Accept-Encoding,User-Agent",
  1666. },
  1667. {
  1668. key: "Transfer-Encoding",
  1669. value: []string{"foo"},
  1670. want: "ERROR: http2: invalid Transfer-Encoding request header: [\"foo\"]",
  1671. },
  1672. {
  1673. key: "Transfer-Encoding",
  1674. value: []string{"chunked"},
  1675. want: "Accept-Encoding,User-Agent",
  1676. },
  1677. {
  1678. key: "Transfer-Encoding",
  1679. value: []string{"chunked", "other"},
  1680. want: "ERROR: http2: invalid Transfer-Encoding request header: [\"chunked\" \"other\"]",
  1681. },
  1682. {
  1683. key: "Content-Length",
  1684. value: []string{"123"},
  1685. want: "Accept-Encoding,User-Agent",
  1686. },
  1687. {
  1688. key: "Keep-Alive",
  1689. value: []string{"doop"},
  1690. want: "Accept-Encoding,User-Agent",
  1691. },
  1692. }
  1693. for _, tt := range tests {
  1694. req, _ := http.NewRequest("GET", st.ts.URL, nil)
  1695. req.Header[tt.key] = tt.value
  1696. res, err := tr.RoundTrip(req)
  1697. var got string
  1698. if err != nil {
  1699. got = fmt.Sprintf("ERROR: %v", err)
  1700. } else {
  1701. got = res.Header.Get("Got-Header")
  1702. res.Body.Close()
  1703. }
  1704. if got != tt.want {
  1705. t.Errorf("For key %q, value %q, got = %q; want %q", tt.key, tt.value, got, tt.want)
  1706. }
  1707. }
  1708. }
  1709. // golang.org/issue/14048
  1710. func TestTransportFailsOnInvalidHeaders(t *testing.T) {
  1711. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1712. var got []string
  1713. for k := range r.Header {
  1714. got = append(got, k)
  1715. }
  1716. sort.Strings(got)
  1717. w.Header().Set("Got-Header", strings.Join(got, ","))
  1718. }, optOnlyServer)
  1719. defer st.Close()
  1720. tests := [...]struct {
  1721. h http.Header
  1722. wantErr string
  1723. }{
  1724. 0: {
  1725. h: http.Header{"with space": {"foo"}},
  1726. wantErr: `invalid HTTP header name "with space"`,
  1727. },
  1728. 1: {
  1729. h: http.Header{"name": {"Брэд"}},
  1730. wantErr: "", // okay
  1731. },
  1732. 2: {
  1733. h: http.Header{"имя": {"Brad"}},
  1734. wantErr: `invalid HTTP header name "имя"`,
  1735. },
  1736. 3: {
  1737. h: http.Header{"foo": {"foo\x01bar"}},
  1738. wantErr: `invalid HTTP header value "foo\x01bar" for header "foo"`,
  1739. },
  1740. }
  1741. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  1742. defer tr.CloseIdleConnections()
  1743. for i, tt := range tests {
  1744. req, _ := http.NewRequest("GET", st.ts.URL, nil)
  1745. req.Header = tt.h
  1746. res, err := tr.RoundTrip(req)
  1747. var bad bool
  1748. if tt.wantErr == "" {
  1749. if err != nil {
  1750. bad = true
  1751. t.Errorf("case %d: error = %v; want no error", i, err)
  1752. }
  1753. } else {
  1754. if !strings.Contains(fmt.Sprint(err), tt.wantErr) {
  1755. bad = true
  1756. t.Errorf("case %d: error = %v; want error %q", i, err, tt.wantErr)
  1757. }
  1758. }
  1759. if err == nil {
  1760. if bad {
  1761. t.Logf("case %d: server got headers %q", i, res.Header.Get("Got-Header"))
  1762. }
  1763. res.Body.Close()
  1764. }
  1765. }
  1766. }
  1767. // Tests that gzipReader doesn't crash on a second Read call following
  1768. // the first Read call's gzip.NewReader returning an error.
  1769. func TestGzipReader_DoubleReadCrash(t *testing.T) {
  1770. gz := &gzipReader{
  1771. body: ioutil.NopCloser(strings.NewReader("0123456789")),
  1772. }
  1773. var buf [1]byte
  1774. n, err1 := gz.Read(buf[:])
  1775. if n != 0 || !strings.Contains(fmt.Sprint(err1), "invalid header") {
  1776. t.Fatalf("Read = %v, %v; want 0, invalid header", n, err1)
  1777. }
  1778. n, err2 := gz.Read(buf[:])
  1779. if n != 0 || err2 != err1 {
  1780. t.Fatalf("second Read = %v, %v; want 0, %v", n, err2, err1)
  1781. }
  1782. }
  1783. func TestTransportNewTLSConfig(t *testing.T) {
  1784. tests := [...]struct {
  1785. conf *tls.Config
  1786. host string
  1787. want *tls.Config
  1788. }{
  1789. // Normal case.
  1790. 0: {
  1791. conf: nil,
  1792. host: "foo.com",
  1793. want: &tls.Config{
  1794. ServerName: "foo.com",
  1795. NextProtos: []string{NextProtoTLS},
  1796. },
  1797. },
  1798. // User-provided name (bar.com) takes precedence:
  1799. 1: {
  1800. conf: &tls.Config{
  1801. ServerName: "bar.com",
  1802. },
  1803. host: "foo.com",
  1804. want: &tls.Config{
  1805. ServerName: "bar.com",
  1806. NextProtos: []string{NextProtoTLS},
  1807. },
  1808. },
  1809. // NextProto is prepended:
  1810. 2: {
  1811. conf: &tls.Config{
  1812. NextProtos: []string{"foo", "bar"},
  1813. },
  1814. host: "example.com",
  1815. want: &tls.Config{
  1816. ServerName: "example.com",
  1817. NextProtos: []string{NextProtoTLS, "foo", "bar"},
  1818. },
  1819. },
  1820. // NextProto is not duplicated:
  1821. 3: {
  1822. conf: &tls.Config{
  1823. NextProtos: []string{"foo", "bar", NextProtoTLS},
  1824. },
  1825. host: "example.com",
  1826. want: &tls.Config{
  1827. ServerName: "example.com",
  1828. NextProtos: []string{"foo", "bar", NextProtoTLS},
  1829. },
  1830. },
  1831. }
  1832. for i, tt := range tests {
  1833. // Ignore the session ticket keys part, which ends up populating
  1834. // unexported fields in the Config:
  1835. if tt.conf != nil {
  1836. tt.conf.SessionTicketsDisabled = true
  1837. }
  1838. tr := &Transport{TLSClientConfig: tt.conf}
  1839. got := tr.newTLSConfig(tt.host)
  1840. got.SessionTicketsDisabled = false
  1841. if !reflect.DeepEqual(got, tt.want) {
  1842. t.Errorf("%d. got %#v; want %#v", i, got, tt.want)
  1843. }
  1844. }
  1845. }
  1846. // The Google GFE responds to HEAD requests with a HEADERS frame
  1847. // without END_STREAM, followed by a 0-length DATA frame with
  1848. // END_STREAM. Make sure we don't get confused by that. (We did.)
  1849. func TestTransportReadHeadResponse(t *testing.T) {
  1850. ct := newClientTester(t)
  1851. clientDone := make(chan struct{})
  1852. ct.client = func() error {
  1853. defer close(clientDone)
  1854. req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil)
  1855. res, err := ct.tr.RoundTrip(req)
  1856. if err != nil {
  1857. return err
  1858. }
  1859. if res.ContentLength != 123 {
  1860. return fmt.Errorf("Content-Length = %d; want 123", res.ContentLength)
  1861. }
  1862. slurp, err := ioutil.ReadAll(res.Body)
  1863. if err != nil {
  1864. return fmt.Errorf("ReadAll: %v", err)
  1865. }
  1866. if len(slurp) > 0 {
  1867. return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp)
  1868. }
  1869. return nil
  1870. }
  1871. ct.server = func() error {
  1872. ct.greet()
  1873. for {
  1874. f, err := ct.fr.ReadFrame()
  1875. if err != nil {
  1876. t.Logf("ReadFrame: %v", err)
  1877. return nil
  1878. }
  1879. hf, ok := f.(*HeadersFrame)
  1880. if !ok {
  1881. continue
  1882. }
  1883. var buf bytes.Buffer
  1884. enc := hpack.NewEncoder(&buf)
  1885. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1886. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"})
  1887. ct.fr.WriteHeaders(HeadersFrameParam{
  1888. StreamID: hf.StreamID,
  1889. EndHeaders: true,
  1890. EndStream: false, // as the GFE does
  1891. BlockFragment: buf.Bytes(),
  1892. })
  1893. ct.fr.WriteData(hf.StreamID, true, nil)
  1894. <-clientDone
  1895. return nil
  1896. }
  1897. }
  1898. ct.run()
  1899. }
  1900. func TestTransportReadHeadResponseWithBody(t *testing.T) {
  1901. response := "redirecting to /elsewhere"
  1902. ct := newClientTester(t)
  1903. clientDone := make(chan struct{})
  1904. ct.client = func() error {
  1905. defer close(clientDone)
  1906. req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil)
  1907. res, err := ct.tr.RoundTrip(req)
  1908. if err != nil {
  1909. return err
  1910. }
  1911. if res.ContentLength != int64(len(response)) {
  1912. return fmt.Errorf("Content-Length = %d; want %d", res.ContentLength, len(response))
  1913. }
  1914. slurp, err := ioutil.ReadAll(res.Body)
  1915. if err != nil {
  1916. return fmt.Errorf("ReadAll: %v", err)
  1917. }
  1918. if len(slurp) > 0 {
  1919. return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp)
  1920. }
  1921. return nil
  1922. }
  1923. ct.server = func() error {
  1924. ct.greet()
  1925. for {
  1926. f, err := ct.fr.ReadFrame()
  1927. if err != nil {
  1928. t.Logf("ReadFrame: %v", err)
  1929. return nil
  1930. }
  1931. hf, ok := f.(*HeadersFrame)
  1932. if !ok {
  1933. continue
  1934. }
  1935. var buf bytes.Buffer
  1936. enc := hpack.NewEncoder(&buf)
  1937. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  1938. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: strconv.Itoa(len(response))})
  1939. ct.fr.WriteHeaders(HeadersFrameParam{
  1940. StreamID: hf.StreamID,
  1941. EndHeaders: true,
  1942. EndStream: false,
  1943. BlockFragment: buf.Bytes(),
  1944. })
  1945. ct.fr.WriteData(hf.StreamID, true, []byte(response))
  1946. <-clientDone
  1947. return nil
  1948. }
  1949. }
  1950. ct.run()
  1951. }
  1952. type neverEnding byte
  1953. func (b neverEnding) Read(p []byte) (int, error) {
  1954. for i := range p {
  1955. p[i] = byte(b)
  1956. }
  1957. return len(p), nil
  1958. }
  1959. // golang.org/issue/15425: test that a handler closing the request
  1960. // body doesn't terminate the stream to the peer. (It just stops
  1961. // readability from the handler's side, and eventually the client
  1962. // runs out of flow control tokens)
  1963. func TestTransportHandlerBodyClose(t *testing.T) {
  1964. const bodySize = 10 << 20
  1965. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1966. r.Body.Close()
  1967. io.Copy(w, io.LimitReader(neverEnding('A'), bodySize))
  1968. }, optOnlyServer)
  1969. defer st.Close()
  1970. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  1971. defer tr.CloseIdleConnections()
  1972. g0 := runtime.NumGoroutine()
  1973. const numReq = 10
  1974. for i := 0; i < numReq; i++ {
  1975. req, err := http.NewRequest("POST", st.ts.URL, struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)})
  1976. if err != nil {
  1977. t.Fatal(err)
  1978. }
  1979. res, err := tr.RoundTrip(req)
  1980. if err != nil {
  1981. t.Fatal(err)
  1982. }
  1983. n, err := io.Copy(ioutil.Discard, res.Body)
  1984. res.Body.Close()
  1985. if n != bodySize || err != nil {
  1986. t.Fatalf("req#%d: Copy = %d, %v; want %d, nil", i, n, err, bodySize)
  1987. }
  1988. }
  1989. tr.CloseIdleConnections()
  1990. gd := runtime.NumGoroutine() - g0
  1991. if gd > numReq/2 {
  1992. t.Errorf("appeared to leak goroutines")
  1993. }
  1994. }
  1995. // https://golang.org/issue/15930
  1996. func TestTransportFlowControl(t *testing.T) {
  1997. const bufLen = 64 << 10
  1998. var total int64 = 100 << 20 // 100MB
  1999. if testing.Short() {
  2000. total = 10 << 20
  2001. }
  2002. var wrote int64 // updated atomically
  2003. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2004. b := make([]byte, bufLen)
  2005. for wrote < total {
  2006. n, err := w.Write(b)
  2007. atomic.AddInt64(&wrote, int64(n))
  2008. if err != nil {
  2009. t.Errorf("ResponseWriter.Write error: %v", err)
  2010. break
  2011. }
  2012. w.(http.Flusher).Flush()
  2013. }
  2014. }, optOnlyServer)
  2015. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  2016. defer tr.CloseIdleConnections()
  2017. req, err := http.NewRequest("GET", st.ts.URL, nil)
  2018. if err != nil {
  2019. t.Fatal("NewRequest error:", err)
  2020. }
  2021. resp, err := tr.RoundTrip(req)
  2022. if err != nil {
  2023. t.Fatal("RoundTrip error:", err)
  2024. }
  2025. defer resp.Body.Close()
  2026. var read int64
  2027. b := make([]byte, bufLen)
  2028. for {
  2029. n, err := resp.Body.Read(b)
  2030. if err == io.EOF {
  2031. break
  2032. }
  2033. if err != nil {
  2034. t.Fatal("Read error:", err)
  2035. }
  2036. read += int64(n)
  2037. const max = transportDefaultStreamFlow
  2038. if w := atomic.LoadInt64(&wrote); -max > read-w || read-w > max {
  2039. t.Fatalf("Too much data inflight: server wrote %v bytes but client only received %v", w, read)
  2040. }
  2041. // Let the server get ahead of the client.
  2042. time.Sleep(1 * time.Millisecond)
  2043. }
  2044. }
  2045. // golang.org/issue/14627 -- if the server sends a GOAWAY frame, make
  2046. // the Transport remember it and return it back to users (via
  2047. // RoundTrip or request body reads) if needed (e.g. if the server
  2048. // proceeds to close the TCP connection before the client gets its
  2049. // response)
  2050. func TestTransportUsesGoAwayDebugError_RoundTrip(t *testing.T) {
  2051. testTransportUsesGoAwayDebugError(t, false)
  2052. }
  2053. func TestTransportUsesGoAwayDebugError_Body(t *testing.T) {
  2054. testTransportUsesGoAwayDebugError(t, true)
  2055. }
  2056. func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) {
  2057. ct := newClientTester(t)
  2058. clientDone := make(chan struct{})
  2059. const goAwayErrCode = ErrCodeHTTP11Required // arbitrary
  2060. const goAwayDebugData = "some debug data"
  2061. ct.client = func() error {
  2062. defer close(clientDone)
  2063. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  2064. res, err := ct.tr.RoundTrip(req)
  2065. if failMidBody {
  2066. if err != nil {
  2067. return fmt.Errorf("unexpected client RoundTrip error: %v", err)
  2068. }
  2069. _, err = io.Copy(ioutil.Discard, res.Body)
  2070. res.Body.Close()
  2071. }
  2072. want := GoAwayError{
  2073. LastStreamID: 5,
  2074. ErrCode: goAwayErrCode,
  2075. DebugData: goAwayDebugData,
  2076. }
  2077. if !reflect.DeepEqual(err, want) {
  2078. t.Errorf("RoundTrip error = %T: %#v, want %T (%#v)", err, err, want, want)
  2079. }
  2080. return nil
  2081. }
  2082. ct.server = func() error {
  2083. ct.greet()
  2084. for {
  2085. f, err := ct.fr.ReadFrame()
  2086. if err != nil {
  2087. t.Logf("ReadFrame: %v", err)
  2088. return nil
  2089. }
  2090. hf, ok := f.(*HeadersFrame)
  2091. if !ok {
  2092. continue
  2093. }
  2094. if failMidBody {
  2095. var buf bytes.Buffer
  2096. enc := hpack.NewEncoder(&buf)
  2097. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2098. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"})
  2099. ct.fr.WriteHeaders(HeadersFrameParam{
  2100. StreamID: hf.StreamID,
  2101. EndHeaders: true,
  2102. EndStream: false,
  2103. BlockFragment: buf.Bytes(),
  2104. })
  2105. }
  2106. // Write two GOAWAY frames, to test that the Transport takes
  2107. // the interesting parts of both.
  2108. ct.fr.WriteGoAway(5, ErrCodeNo, []byte(goAwayDebugData))
  2109. ct.fr.WriteGoAway(5, goAwayErrCode, nil)
  2110. ct.sc.(*net.TCPConn).CloseWrite()
  2111. <-clientDone
  2112. return nil
  2113. }
  2114. }
  2115. ct.run()
  2116. }
  2117. func testTransportReturnsUnusedFlowControl(t *testing.T, oneDataFrame bool) {
  2118. ct := newClientTester(t)
  2119. clientClosed := make(chan struct{})
  2120. serverWroteFirstByte := make(chan struct{})
  2121. ct.client = func() error {
  2122. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  2123. res, err := ct.tr.RoundTrip(req)
  2124. if err != nil {
  2125. return err
  2126. }
  2127. <-serverWroteFirstByte
  2128. if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 {
  2129. return fmt.Errorf("body read = %v, %v; want 1, nil", n, err)
  2130. }
  2131. res.Body.Close() // leaving 4999 bytes unread
  2132. close(clientClosed)
  2133. return nil
  2134. }
  2135. ct.server = func() error {
  2136. ct.greet()
  2137. var hf *HeadersFrame
  2138. for {
  2139. f, err := ct.fr.ReadFrame()
  2140. if err != nil {
  2141. return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
  2142. }
  2143. switch f.(type) {
  2144. case *WindowUpdateFrame, *SettingsFrame:
  2145. continue
  2146. }
  2147. var ok bool
  2148. hf, ok = f.(*HeadersFrame)
  2149. if !ok {
  2150. return fmt.Errorf("Got %T; want HeadersFrame", f)
  2151. }
  2152. break
  2153. }
  2154. var buf bytes.Buffer
  2155. enc := hpack.NewEncoder(&buf)
  2156. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2157. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"})
  2158. ct.fr.WriteHeaders(HeadersFrameParam{
  2159. StreamID: hf.StreamID,
  2160. EndHeaders: true,
  2161. EndStream: false,
  2162. BlockFragment: buf.Bytes(),
  2163. })
  2164. // Two cases:
  2165. // - Send one DATA frame with 5000 bytes.
  2166. // - Send two DATA frames with 1 and 4999 bytes each.
  2167. //
  2168. // In both cases, the client should consume one byte of data,
  2169. // refund that byte, then refund the following 4999 bytes.
  2170. //
  2171. // In the second case, the server waits for the client connection to
  2172. // close before seconding the second DATA frame. This tests the case
  2173. // where the client receives a DATA frame after it has reset the stream.
  2174. if oneDataFrame {
  2175. ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 5000))
  2176. close(serverWroteFirstByte)
  2177. <-clientClosed
  2178. } else {
  2179. ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 1))
  2180. close(serverWroteFirstByte)
  2181. <-clientClosed
  2182. ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 4999))
  2183. }
  2184. waitingFor := "RSTStreamFrame"
  2185. for {
  2186. f, err := ct.fr.ReadFrame()
  2187. if err != nil {
  2188. return fmt.Errorf("ReadFrame while waiting for %s: %v", waitingFor, err)
  2189. }
  2190. if _, ok := f.(*SettingsFrame); ok {
  2191. continue
  2192. }
  2193. switch waitingFor {
  2194. case "RSTStreamFrame":
  2195. if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel {
  2196. return fmt.Errorf("Expected a RSTStreamFrame with code cancel; got %v", summarizeFrame(f))
  2197. }
  2198. waitingFor = "WindowUpdateFrame"
  2199. case "WindowUpdateFrame":
  2200. if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != 4999 {
  2201. return fmt.Errorf("Expected WindowUpdateFrame for 4999 bytes; got %v", summarizeFrame(f))
  2202. }
  2203. return nil
  2204. }
  2205. }
  2206. }
  2207. ct.run()
  2208. }
  2209. // See golang.org/issue/16481
  2210. func TestTransportReturnsUnusedFlowControlSingleWrite(t *testing.T) {
  2211. testTransportReturnsUnusedFlowControl(t, true)
  2212. }
  2213. // See golang.org/issue/20469
  2214. func TestTransportReturnsUnusedFlowControlMultipleWrites(t *testing.T) {
  2215. testTransportReturnsUnusedFlowControl(t, false)
  2216. }
  2217. // Issue 16612: adjust flow control on open streams when transport
  2218. // receives SETTINGS with INITIAL_WINDOW_SIZE from server.
  2219. func TestTransportAdjustsFlowControl(t *testing.T) {
  2220. ct := newClientTester(t)
  2221. clientDone := make(chan struct{})
  2222. const bodySize = 1 << 20
  2223. ct.client = func() error {
  2224. defer ct.cc.(*net.TCPConn).CloseWrite()
  2225. defer close(clientDone)
  2226. req, _ := http.NewRequest("POST", "https://dummy.tld/", struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)})
  2227. res, err := ct.tr.RoundTrip(req)
  2228. if err != nil {
  2229. return err
  2230. }
  2231. res.Body.Close()
  2232. return nil
  2233. }
  2234. ct.server = func() error {
  2235. _, err := io.ReadFull(ct.sc, make([]byte, len(ClientPreface)))
  2236. if err != nil {
  2237. return fmt.Errorf("reading client preface: %v", err)
  2238. }
  2239. var gotBytes int64
  2240. var sentSettings bool
  2241. for {
  2242. f, err := ct.fr.ReadFrame()
  2243. if err != nil {
  2244. select {
  2245. case <-clientDone:
  2246. return nil
  2247. default:
  2248. return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
  2249. }
  2250. }
  2251. switch f := f.(type) {
  2252. case *DataFrame:
  2253. gotBytes += int64(len(f.Data()))
  2254. // After we've got half the client's
  2255. // initial flow control window's worth
  2256. // of request body data, give it just
  2257. // enough flow control to finish.
  2258. if gotBytes >= initialWindowSize/2 && !sentSettings {
  2259. sentSettings = true
  2260. ct.fr.WriteSettings(Setting{ID: SettingInitialWindowSize, Val: bodySize})
  2261. ct.fr.WriteWindowUpdate(0, bodySize)
  2262. ct.fr.WriteSettingsAck()
  2263. }
  2264. if f.StreamEnded() {
  2265. var buf bytes.Buffer
  2266. enc := hpack.NewEncoder(&buf)
  2267. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2268. ct.fr.WriteHeaders(HeadersFrameParam{
  2269. StreamID: f.StreamID,
  2270. EndHeaders: true,
  2271. EndStream: true,
  2272. BlockFragment: buf.Bytes(),
  2273. })
  2274. }
  2275. }
  2276. }
  2277. }
  2278. ct.run()
  2279. }
  2280. // See golang.org/issue/16556
  2281. func TestTransportReturnsDataPaddingFlowControl(t *testing.T) {
  2282. ct := newClientTester(t)
  2283. unblockClient := make(chan bool, 1)
  2284. ct.client = func() error {
  2285. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  2286. res, err := ct.tr.RoundTrip(req)
  2287. if err != nil {
  2288. return err
  2289. }
  2290. defer res.Body.Close()
  2291. <-unblockClient
  2292. return nil
  2293. }
  2294. ct.server = func() error {
  2295. ct.greet()
  2296. var hf *HeadersFrame
  2297. for {
  2298. f, err := ct.fr.ReadFrame()
  2299. if err != nil {
  2300. return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
  2301. }
  2302. switch f.(type) {
  2303. case *WindowUpdateFrame, *SettingsFrame:
  2304. continue
  2305. }
  2306. var ok bool
  2307. hf, ok = f.(*HeadersFrame)
  2308. if !ok {
  2309. return fmt.Errorf("Got %T; want HeadersFrame", f)
  2310. }
  2311. break
  2312. }
  2313. var buf bytes.Buffer
  2314. enc := hpack.NewEncoder(&buf)
  2315. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2316. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"})
  2317. ct.fr.WriteHeaders(HeadersFrameParam{
  2318. StreamID: hf.StreamID,
  2319. EndHeaders: true,
  2320. EndStream: false,
  2321. BlockFragment: buf.Bytes(),
  2322. })
  2323. pad := make([]byte, 5)
  2324. ct.fr.WriteDataPadded(hf.StreamID, false, make([]byte, 5000), pad) // without ending stream
  2325. f, err := ct.readNonSettingsFrame()
  2326. if err != nil {
  2327. return fmt.Errorf("ReadFrame while waiting for first WindowUpdateFrame: %v", err)
  2328. }
  2329. wantBack := uint32(len(pad)) + 1 // one byte for the length of the padding
  2330. if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID != 0 {
  2331. return fmt.Errorf("Expected conn WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f))
  2332. }
  2333. f, err = ct.readNonSettingsFrame()
  2334. if err != nil {
  2335. return fmt.Errorf("ReadFrame while waiting for second WindowUpdateFrame: %v", err)
  2336. }
  2337. if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID == 0 {
  2338. return fmt.Errorf("Expected stream WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f))
  2339. }
  2340. unblockClient <- true
  2341. return nil
  2342. }
  2343. ct.run()
  2344. }
  2345. // golang.org/issue/16572 -- RoundTrip shouldn't hang when it gets a
  2346. // StreamError as a result of the response HEADERS
  2347. func TestTransportReturnsErrorOnBadResponseHeaders(t *testing.T) {
  2348. ct := newClientTester(t)
  2349. ct.client = func() error {
  2350. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  2351. res, err := ct.tr.RoundTrip(req)
  2352. if err == nil {
  2353. res.Body.Close()
  2354. return errors.New("unexpected successful GET")
  2355. }
  2356. want := StreamError{1, ErrCodeProtocol, headerFieldNameError(" content-type")}
  2357. if !reflect.DeepEqual(want, err) {
  2358. t.Errorf("RoundTrip error = %#v; want %#v", err, want)
  2359. }
  2360. return nil
  2361. }
  2362. ct.server = func() error {
  2363. ct.greet()
  2364. hf, err := ct.firstHeaders()
  2365. if err != nil {
  2366. return err
  2367. }
  2368. var buf bytes.Buffer
  2369. enc := hpack.NewEncoder(&buf)
  2370. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2371. enc.WriteField(hpack.HeaderField{Name: " content-type", Value: "bogus"}) // bogus spaces
  2372. ct.fr.WriteHeaders(HeadersFrameParam{
  2373. StreamID: hf.StreamID,
  2374. EndHeaders: true,
  2375. EndStream: false,
  2376. BlockFragment: buf.Bytes(),
  2377. })
  2378. for {
  2379. fr, err := ct.readFrame()
  2380. if err != nil {
  2381. return fmt.Errorf("error waiting for RST_STREAM from client: %v", err)
  2382. }
  2383. if _, ok := fr.(*SettingsFrame); ok {
  2384. continue
  2385. }
  2386. if rst, ok := fr.(*RSTStreamFrame); !ok || rst.StreamID != 1 || rst.ErrCode != ErrCodeProtocol {
  2387. t.Errorf("Frame = %v; want RST_STREAM for stream 1 with ErrCodeProtocol", summarizeFrame(fr))
  2388. }
  2389. break
  2390. }
  2391. return nil
  2392. }
  2393. ct.run()
  2394. }
  2395. // byteAndEOFReader returns is in an io.Reader which reads one byte
  2396. // (the underlying byte) and io.EOF at once in its Read call.
  2397. type byteAndEOFReader byte
  2398. func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
  2399. if len(p) == 0 {
  2400. panic("unexpected useless call")
  2401. }
  2402. p[0] = byte(b)
  2403. return 1, io.EOF
  2404. }
  2405. // Issue 16788: the Transport had a regression where it started
  2406. // sending a spurious DATA frame with a duplicate END_STREAM bit after
  2407. // the request body writer goroutine had already read an EOF from the
  2408. // Request.Body and included the END_STREAM on a data-carrying DATA
  2409. // frame.
  2410. //
  2411. // Notably, to trigger this, the requests need to use a Request.Body
  2412. // which returns (non-0, io.EOF) and also needs to set the ContentLength
  2413. // explicitly.
  2414. func TestTransportBodyDoubleEndStream(t *testing.T) {
  2415. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2416. // Nothing.
  2417. }, optOnlyServer)
  2418. defer st.Close()
  2419. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  2420. defer tr.CloseIdleConnections()
  2421. for i := 0; i < 2; i++ {
  2422. req, _ := http.NewRequest("POST", st.ts.URL, byteAndEOFReader('a'))
  2423. req.ContentLength = 1
  2424. res, err := tr.RoundTrip(req)
  2425. if err != nil {
  2426. t.Fatalf("failure on req %d: %v", i+1, err)
  2427. }
  2428. defer res.Body.Close()
  2429. }
  2430. }
  2431. // golang.org/issue/16847, golang.org/issue/19103
  2432. func TestTransportRequestPathPseudo(t *testing.T) {
  2433. type result struct {
  2434. path string
  2435. err string
  2436. }
  2437. tests := []struct {
  2438. req *http.Request
  2439. want result
  2440. }{
  2441. 0: {
  2442. req: &http.Request{
  2443. Method: "GET",
  2444. URL: &url.URL{
  2445. Host: "foo.com",
  2446. Path: "/foo",
  2447. },
  2448. },
  2449. want: result{path: "/foo"},
  2450. },
  2451. // In Go 1.7, we accepted paths of "//foo".
  2452. // In Go 1.8, we rejected it (issue 16847).
  2453. // In Go 1.9, we accepted it again (issue 19103).
  2454. 1: {
  2455. req: &http.Request{
  2456. Method: "GET",
  2457. URL: &url.URL{
  2458. Host: "foo.com",
  2459. Path: "//foo",
  2460. },
  2461. },
  2462. want: result{path: "//foo"},
  2463. },
  2464. // Opaque with //$Matching_Hostname/path
  2465. 2: {
  2466. req: &http.Request{
  2467. Method: "GET",
  2468. URL: &url.URL{
  2469. Scheme: "https",
  2470. Opaque: "//foo.com/path",
  2471. Host: "foo.com",
  2472. Path: "/ignored",
  2473. },
  2474. },
  2475. want: result{path: "/path"},
  2476. },
  2477. // Opaque with some other Request.Host instead:
  2478. 3: {
  2479. req: &http.Request{
  2480. Method: "GET",
  2481. Host: "bar.com",
  2482. URL: &url.URL{
  2483. Scheme: "https",
  2484. Opaque: "//bar.com/path",
  2485. Host: "foo.com",
  2486. Path: "/ignored",
  2487. },
  2488. },
  2489. want: result{path: "/path"},
  2490. },
  2491. // Opaque without the leading "//":
  2492. 4: {
  2493. req: &http.Request{
  2494. Method: "GET",
  2495. URL: &url.URL{
  2496. Opaque: "/path",
  2497. Host: "foo.com",
  2498. Path: "/ignored",
  2499. },
  2500. },
  2501. want: result{path: "/path"},
  2502. },
  2503. // Opaque we can't handle:
  2504. 5: {
  2505. req: &http.Request{
  2506. Method: "GET",
  2507. URL: &url.URL{
  2508. Scheme: "https",
  2509. Opaque: "//unknown_host/path",
  2510. Host: "foo.com",
  2511. Path: "/ignored",
  2512. },
  2513. },
  2514. want: result{err: `invalid request :path "https://unknown_host/path" from URL.Opaque = "//unknown_host/path"`},
  2515. },
  2516. // A CONNECT request:
  2517. 6: {
  2518. req: &http.Request{
  2519. Method: "CONNECT",
  2520. URL: &url.URL{
  2521. Host: "foo.com",
  2522. },
  2523. },
  2524. want: result{},
  2525. },
  2526. }
  2527. for i, tt := range tests {
  2528. cc := &ClientConn{}
  2529. cc.henc = hpack.NewEncoder(&cc.hbuf)
  2530. cc.mu.Lock()
  2531. hdrs, err := cc.encodeHeaders(tt.req, false, "", -1)
  2532. cc.mu.Unlock()
  2533. var got result
  2534. hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) {
  2535. if f.Name == ":path" {
  2536. got.path = f.Value
  2537. }
  2538. })
  2539. if err != nil {
  2540. got.err = err.Error()
  2541. } else if len(hdrs) > 0 {
  2542. if _, err := hpackDec.Write(hdrs); err != nil {
  2543. t.Errorf("%d. bogus hpack: %v", i, err)
  2544. continue
  2545. }
  2546. }
  2547. if got != tt.want {
  2548. t.Errorf("%d. got %+v; want %+v", i, got, tt.want)
  2549. }
  2550. }
  2551. }
  2552. // golang.org/issue/17071 -- don't sniff the first byte of the request body
  2553. // before we've determined that the ClientConn is usable.
  2554. func TestRoundTripDoesntConsumeRequestBodyEarly(t *testing.T) {
  2555. const body = "foo"
  2556. req, _ := http.NewRequest("POST", "http://foo.com/", ioutil.NopCloser(strings.NewReader(body)))
  2557. cc := &ClientConn{
  2558. closed: true,
  2559. }
  2560. _, err := cc.RoundTrip(req)
  2561. if err != errClientConnUnusable {
  2562. t.Fatalf("RoundTrip = %v; want errClientConnUnusable", err)
  2563. }
  2564. slurp, err := ioutil.ReadAll(req.Body)
  2565. if err != nil {
  2566. t.Errorf("ReadAll = %v", err)
  2567. }
  2568. if string(slurp) != body {
  2569. t.Errorf("Body = %q; want %q", slurp, body)
  2570. }
  2571. }
  2572. func TestClientConnPing(t *testing.T) {
  2573. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}, optOnlyServer)
  2574. defer st.Close()
  2575. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  2576. defer tr.CloseIdleConnections()
  2577. cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false)
  2578. if err != nil {
  2579. t.Fatal(err)
  2580. }
  2581. if err = cc.Ping(testContext{}); err != nil {
  2582. t.Fatal(err)
  2583. }
  2584. }
  2585. // Issue 16974: if the server sent a DATA frame after the user
  2586. // canceled the Transport's Request, the Transport previously wrote to a
  2587. // closed pipe, got an error, and ended up closing the whole TCP
  2588. // connection.
  2589. func TestTransportCancelDataResponseRace(t *testing.T) {
  2590. cancel := make(chan struct{})
  2591. clientGotError := make(chan bool, 1)
  2592. const msg = "Hello."
  2593. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2594. if strings.Contains(r.URL.Path, "/hello") {
  2595. time.Sleep(50 * time.Millisecond)
  2596. io.WriteString(w, msg)
  2597. return
  2598. }
  2599. for i := 0; i < 50; i++ {
  2600. io.WriteString(w, "Some data.")
  2601. w.(http.Flusher).Flush()
  2602. if i == 2 {
  2603. close(cancel)
  2604. <-clientGotError
  2605. }
  2606. time.Sleep(10 * time.Millisecond)
  2607. }
  2608. }, optOnlyServer)
  2609. defer st.Close()
  2610. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  2611. defer tr.CloseIdleConnections()
  2612. c := &http.Client{Transport: tr}
  2613. req, _ := http.NewRequest("GET", st.ts.URL, nil)
  2614. req.Cancel = cancel
  2615. res, err := c.Do(req)
  2616. if err != nil {
  2617. t.Fatal(err)
  2618. }
  2619. if _, err = io.Copy(ioutil.Discard, res.Body); err == nil {
  2620. t.Fatal("unexpected success")
  2621. }
  2622. clientGotError <- true
  2623. res, err = c.Get(st.ts.URL + "/hello")
  2624. if err != nil {
  2625. t.Fatal(err)
  2626. }
  2627. slurp, err := ioutil.ReadAll(res.Body)
  2628. if err != nil {
  2629. t.Fatal(err)
  2630. }
  2631. if string(slurp) != msg {
  2632. t.Errorf("Got = %q; want %q", slurp, msg)
  2633. }
  2634. }
  2635. func TestTransportRetryAfterGOAWAY(t *testing.T) {
  2636. var dialer struct {
  2637. sync.Mutex
  2638. count int
  2639. }
  2640. ct1 := make(chan *clientTester)
  2641. ct2 := make(chan *clientTester)
  2642. ln := newLocalListener(t)
  2643. defer ln.Close()
  2644. tr := &Transport{
  2645. TLSClientConfig: tlsConfigInsecure,
  2646. }
  2647. tr.DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  2648. dialer.Lock()
  2649. defer dialer.Unlock()
  2650. dialer.count++
  2651. if dialer.count == 3 {
  2652. return nil, errors.New("unexpected number of dials")
  2653. }
  2654. cc, err := net.Dial("tcp", ln.Addr().String())
  2655. if err != nil {
  2656. return nil, fmt.Errorf("dial error: %v", err)
  2657. }
  2658. sc, err := ln.Accept()
  2659. if err != nil {
  2660. return nil, fmt.Errorf("accept error: %v", err)
  2661. }
  2662. ct := &clientTester{
  2663. t: t,
  2664. tr: tr,
  2665. cc: cc,
  2666. sc: sc,
  2667. fr: NewFramer(sc, sc),
  2668. }
  2669. switch dialer.count {
  2670. case 1:
  2671. ct1 <- ct
  2672. case 2:
  2673. ct2 <- ct
  2674. }
  2675. return cc, nil
  2676. }
  2677. errs := make(chan error, 3)
  2678. done := make(chan struct{})
  2679. defer close(done)
  2680. // Client.
  2681. go func() {
  2682. req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
  2683. res, err := tr.RoundTrip(req)
  2684. if res != nil {
  2685. res.Body.Close()
  2686. if got := res.Header.Get("Foo"); got != "bar" {
  2687. err = fmt.Errorf("foo header = %q; want bar", got)
  2688. }
  2689. }
  2690. if err != nil {
  2691. err = fmt.Errorf("RoundTrip: %v", err)
  2692. }
  2693. errs <- err
  2694. }()
  2695. connToClose := make(chan io.Closer, 2)
  2696. // Server for the first request.
  2697. go func() {
  2698. var ct *clientTester
  2699. select {
  2700. case ct = <-ct1:
  2701. case <-done:
  2702. return
  2703. }
  2704. connToClose <- ct.cc
  2705. ct.greet()
  2706. hf, err := ct.firstHeaders()
  2707. if err != nil {
  2708. errs <- fmt.Errorf("server1 failed reading HEADERS: %v", err)
  2709. return
  2710. }
  2711. t.Logf("server1 got %v", hf)
  2712. if err := ct.fr.WriteGoAway(0 /*max id*/, ErrCodeNo, nil); err != nil {
  2713. errs <- fmt.Errorf("server1 failed writing GOAWAY: %v", err)
  2714. return
  2715. }
  2716. errs <- nil
  2717. }()
  2718. // Server for the second request.
  2719. go func() {
  2720. var ct *clientTester
  2721. select {
  2722. case ct = <-ct2:
  2723. case <-done:
  2724. return
  2725. }
  2726. connToClose <- ct.cc
  2727. ct.greet()
  2728. hf, err := ct.firstHeaders()
  2729. if err != nil {
  2730. errs <- fmt.Errorf("server2 failed reading HEADERS: %v", err)
  2731. return
  2732. }
  2733. t.Logf("server2 got %v", hf)
  2734. var buf bytes.Buffer
  2735. enc := hpack.NewEncoder(&buf)
  2736. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
  2737. enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"})
  2738. err = ct.fr.WriteHeaders(HeadersFrameParam{
  2739. StreamID: hf.StreamID,
  2740. EndHeaders: true,
  2741. EndStream: false,
  2742. BlockFragment: buf.Bytes(),
  2743. })
  2744. if err != nil {
  2745. errs <- fmt.Errorf("server2 failed writing response HEADERS: %v", err)
  2746. } else {
  2747. errs <- nil
  2748. }
  2749. }()
  2750. for k := 0; k < 3; k++ {
  2751. select {
  2752. case err := <-errs:
  2753. if err != nil {
  2754. t.Error(err)
  2755. }
  2756. case <-time.After(1 * time.Second):
  2757. t.Errorf("timed out")
  2758. }
  2759. }
  2760. for {
  2761. select {
  2762. case c := <-connToClose:
  2763. c.Close()
  2764. default:
  2765. return
  2766. }
  2767. }
  2768. }
  2769. func TestAuthorityAddr(t *testing.T) {
  2770. tests := []struct {
  2771. scheme, authority string
  2772. want string
  2773. }{
  2774. {"http", "foo.com", "foo.com:80"},
  2775. {"https", "foo.com", "foo.com:443"},
  2776. {"https", "foo.com:1234", "foo.com:1234"},
  2777. {"https", "1.2.3.4:1234", "1.2.3.4:1234"},
  2778. {"https", "1.2.3.4", "1.2.3.4:443"},
  2779. {"https", "[::1]:1234", "[::1]:1234"},
  2780. {"https", "[::1]", "[::1]:443"},
  2781. }
  2782. for _, tt := range tests {
  2783. got := authorityAddr(tt.scheme, tt.authority)
  2784. if got != tt.want {
  2785. t.Errorf("authorityAddr(%q, %q) = %q; want %q", tt.scheme, tt.authority, got, tt.want)
  2786. }
  2787. }
  2788. }
  2789. // Issue 20448: stop allocating for DATA frames' payload after
  2790. // Response.Body.Close is called.
  2791. func TestTransportAllocationsAfterResponseBodyClose(t *testing.T) {
  2792. megabyteZero := make([]byte, 1<<20)
  2793. writeErr := make(chan error, 1)
  2794. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2795. w.(http.Flusher).Flush()
  2796. var sum int64
  2797. for i := 0; i < 100; i++ {
  2798. n, err := w.Write(megabyteZero)
  2799. sum += int64(n)
  2800. if err != nil {
  2801. writeErr <- err
  2802. return
  2803. }
  2804. }
  2805. t.Logf("wrote all %d bytes", sum)
  2806. writeErr <- nil
  2807. }, optOnlyServer)
  2808. defer st.Close()
  2809. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  2810. defer tr.CloseIdleConnections()
  2811. c := &http.Client{Transport: tr}
  2812. res, err := c.Get(st.ts.URL)
  2813. if err != nil {
  2814. t.Fatal(err)
  2815. }
  2816. var buf [1]byte
  2817. if _, err := res.Body.Read(buf[:]); err != nil {
  2818. t.Error(err)
  2819. }
  2820. if err := res.Body.Close(); err != nil {
  2821. t.Error(err)
  2822. }
  2823. trb, ok := res.Body.(transportResponseBody)
  2824. if !ok {
  2825. t.Fatalf("res.Body = %T; want transportResponseBody", res.Body)
  2826. }
  2827. if trb.cs.bufPipe.b != nil {
  2828. t.Errorf("response body pipe is still open")
  2829. }
  2830. gotErr := <-writeErr
  2831. if gotErr == nil {
  2832. t.Errorf("Handler unexpectedly managed to write its entire response without getting an error")
  2833. } else if gotErr != errStreamClosed {
  2834. t.Errorf("Handler Write err = %v; want errStreamClosed", gotErr)
  2835. }
  2836. }
  2837. // Issue 18891: make sure Request.Body == NoBody means no DATA frame
  2838. // is ever sent, even if empty.
  2839. func TestTransportNoBodyMeansNoDATA(t *testing.T) {
  2840. ct := newClientTester(t)
  2841. unblockClient := make(chan bool)
  2842. ct.client = func() error {
  2843. req, _ := http.NewRequest("GET", "https://dummy.tld/", go18httpNoBody())
  2844. ct.tr.RoundTrip(req)
  2845. <-unblockClient
  2846. return nil
  2847. }
  2848. ct.server = func() error {
  2849. defer close(unblockClient)
  2850. defer ct.cc.(*net.TCPConn).Close()
  2851. ct.greet()
  2852. for {
  2853. f, err := ct.fr.ReadFrame()
  2854. if err != nil {
  2855. return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
  2856. }
  2857. switch f := f.(type) {
  2858. default:
  2859. return fmt.Errorf("Got %T; want HeadersFrame", f)
  2860. case *WindowUpdateFrame, *SettingsFrame:
  2861. continue
  2862. case *HeadersFrame:
  2863. if !f.StreamEnded() {
  2864. return fmt.Errorf("got headers frame without END_STREAM")
  2865. }
  2866. return nil
  2867. }
  2868. }
  2869. }
  2870. ct.run()
  2871. }