transport_test.go 117 KB

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