transport_test.go 99 KB

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