server_test.go 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100
  1. // Copyright 2014 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. "bytes"
  7. "compress/gzip"
  8. "compress/zlib"
  9. "context"
  10. "crypto/tls"
  11. "errors"
  12. "flag"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/http/httptest"
  20. "os"
  21. "os/exec"
  22. "reflect"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "testing"
  29. "time"
  30. "golang.org/x/net/http2/hpack"
  31. )
  32. var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered")
  33. func stderrv() io.Writer {
  34. if *stderrVerbose {
  35. return os.Stderr
  36. }
  37. return ioutil.Discard
  38. }
  39. type serverTester struct {
  40. cc net.Conn // client conn
  41. t testing.TB
  42. ts *httptest.Server
  43. fr *Framer
  44. serverLogBuf bytes.Buffer // logger for httptest.Server
  45. logFilter []string // substrings to filter out
  46. scMu sync.Mutex // guards sc
  47. sc *serverConn
  48. hpackDec *hpack.Decoder
  49. decodedHeaders [][2]string
  50. // If http2debug!=2, then we capture Frame debug logs that will be written
  51. // to t.Log after a test fails. The read and write logs use separate locks
  52. // and buffers so we don't accidentally introduce synchronization between
  53. // the read and write goroutines, which may hide data races.
  54. frameReadLogMu sync.Mutex
  55. frameReadLogBuf bytes.Buffer
  56. frameWriteLogMu sync.Mutex
  57. frameWriteLogBuf bytes.Buffer
  58. // writing headers:
  59. headerBuf bytes.Buffer
  60. hpackEnc *hpack.Encoder
  61. }
  62. func init() {
  63. testHookOnPanicMu = new(sync.Mutex)
  64. goAwayTimeout = 25 * time.Millisecond
  65. }
  66. func resetHooks() {
  67. testHookOnPanicMu.Lock()
  68. testHookOnPanic = nil
  69. testHookOnPanicMu.Unlock()
  70. }
  71. type serverTesterOpt string
  72. var optOnlyServer = serverTesterOpt("only_server")
  73. var optQuiet = serverTesterOpt("quiet_logging")
  74. var optFramerReuseFrames = serverTesterOpt("frame_reuse_frames")
  75. func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester {
  76. resetHooks()
  77. ts := httptest.NewUnstartedServer(handler)
  78. tlsConfig := &tls.Config{
  79. InsecureSkipVerify: true,
  80. NextProtos: []string{NextProtoTLS},
  81. }
  82. var onlyServer, quiet, framerReuseFrames bool
  83. h2server := new(Server)
  84. for _, opt := range opts {
  85. switch v := opt.(type) {
  86. case func(*tls.Config):
  87. v(tlsConfig)
  88. case func(*httptest.Server):
  89. v(ts)
  90. case func(*Server):
  91. v(h2server)
  92. case serverTesterOpt:
  93. switch v {
  94. case optOnlyServer:
  95. onlyServer = true
  96. case optQuiet:
  97. quiet = true
  98. case optFramerReuseFrames:
  99. framerReuseFrames = true
  100. }
  101. case func(net.Conn, http.ConnState):
  102. ts.Config.ConnState = v
  103. default:
  104. t.Fatalf("unknown newServerTester option type %T", v)
  105. }
  106. }
  107. ConfigureServer(ts.Config, h2server)
  108. st := &serverTester{
  109. t: t,
  110. ts: ts,
  111. }
  112. st.hpackEnc = hpack.NewEncoder(&st.headerBuf)
  113. st.hpackDec = hpack.NewDecoder(initialHeaderTableSize, st.onHeaderField)
  114. ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
  115. if quiet {
  116. ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
  117. } else {
  118. ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv(), twriter{t: t, st: st}, &st.serverLogBuf), "", log.LstdFlags)
  119. }
  120. ts.StartTLS()
  121. if VerboseLogs {
  122. t.Logf("Running test server at: %s", ts.URL)
  123. }
  124. testHookGetServerConn = func(v *serverConn) {
  125. st.scMu.Lock()
  126. defer st.scMu.Unlock()
  127. st.sc = v
  128. }
  129. log.SetOutput(io.MultiWriter(stderrv(), twriter{t: t, st: st}))
  130. if !onlyServer {
  131. cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig)
  132. if err != nil {
  133. t.Fatal(err)
  134. }
  135. st.cc = cc
  136. st.fr = NewFramer(cc, cc)
  137. if framerReuseFrames {
  138. st.fr.SetReuseFrames()
  139. }
  140. if !logFrameReads && !logFrameWrites {
  141. st.fr.debugReadLoggerf = func(m string, v ...interface{}) {
  142. m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n"
  143. st.frameReadLogMu.Lock()
  144. fmt.Fprintf(&st.frameReadLogBuf, m, v...)
  145. st.frameReadLogMu.Unlock()
  146. }
  147. st.fr.debugWriteLoggerf = func(m string, v ...interface{}) {
  148. m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n"
  149. st.frameWriteLogMu.Lock()
  150. fmt.Fprintf(&st.frameWriteLogBuf, m, v...)
  151. st.frameWriteLogMu.Unlock()
  152. }
  153. st.fr.logReads = true
  154. st.fr.logWrites = true
  155. }
  156. }
  157. return st
  158. }
  159. func (st *serverTester) closeConn() {
  160. st.scMu.Lock()
  161. defer st.scMu.Unlock()
  162. st.sc.conn.Close()
  163. }
  164. func (st *serverTester) addLogFilter(phrase string) {
  165. st.logFilter = append(st.logFilter, phrase)
  166. }
  167. func (st *serverTester) stream(id uint32) *stream {
  168. ch := make(chan *stream, 1)
  169. st.sc.serveMsgCh <- func(int) {
  170. ch <- st.sc.streams[id]
  171. }
  172. return <-ch
  173. }
  174. func (st *serverTester) streamState(id uint32) streamState {
  175. ch := make(chan streamState, 1)
  176. st.sc.serveMsgCh <- func(int) {
  177. state, _ := st.sc.state(id)
  178. ch <- state
  179. }
  180. return <-ch
  181. }
  182. // loopNum reports how many times this conn's select loop has gone around.
  183. func (st *serverTester) loopNum() int {
  184. lastc := make(chan int, 1)
  185. st.sc.serveMsgCh <- func(loopNum int) {
  186. lastc <- loopNum
  187. }
  188. return <-lastc
  189. }
  190. // awaitIdle heuristically awaits for the server conn's select loop to be idle.
  191. // The heuristic is that the server connection's serve loop must schedule
  192. // 50 times in a row without any channel sends or receives occurring.
  193. func (st *serverTester) awaitIdle() {
  194. remain := 50
  195. last := st.loopNum()
  196. for remain > 0 {
  197. n := st.loopNum()
  198. if n == last+1 {
  199. remain--
  200. } else {
  201. remain = 50
  202. }
  203. last = n
  204. }
  205. }
  206. func (st *serverTester) Close() {
  207. if st.t.Failed() {
  208. st.frameReadLogMu.Lock()
  209. if st.frameReadLogBuf.Len() > 0 {
  210. st.t.Logf("Framer read log:\n%s", st.frameReadLogBuf.String())
  211. }
  212. st.frameReadLogMu.Unlock()
  213. st.frameWriteLogMu.Lock()
  214. if st.frameWriteLogBuf.Len() > 0 {
  215. st.t.Logf("Framer write log:\n%s", st.frameWriteLogBuf.String())
  216. }
  217. st.frameWriteLogMu.Unlock()
  218. // If we failed already (and are likely in a Fatal,
  219. // unwindowing), force close the connection, so the
  220. // httptest.Server doesn't wait forever for the conn
  221. // to close.
  222. if st.cc != nil {
  223. st.cc.Close()
  224. }
  225. }
  226. st.ts.Close()
  227. if st.cc != nil {
  228. st.cc.Close()
  229. }
  230. log.SetOutput(os.Stderr)
  231. }
  232. // greet initiates the client's HTTP/2 connection into a state where
  233. // frames may be sent.
  234. func (st *serverTester) greet() {
  235. st.greetAndCheckSettings(func(Setting) error { return nil })
  236. }
  237. func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error) {
  238. st.writePreface()
  239. st.writeInitialSettings()
  240. st.wantSettings().ForeachSetting(checkSetting)
  241. st.writeSettingsAck()
  242. // The initial WINDOW_UPDATE and SETTINGS ACK can come in any order.
  243. var gotSettingsAck bool
  244. var gotWindowUpdate bool
  245. for i := 0; i < 2; i++ {
  246. f, err := st.readFrame()
  247. if err != nil {
  248. st.t.Fatal(err)
  249. }
  250. switch f := f.(type) {
  251. case *SettingsFrame:
  252. if !f.Header().Flags.Has(FlagSettingsAck) {
  253. st.t.Fatal("Settings Frame didn't have ACK set")
  254. }
  255. gotSettingsAck = true
  256. case *WindowUpdateFrame:
  257. if f.FrameHeader.StreamID != 0 {
  258. st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID)
  259. }
  260. incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize)
  261. if f.Increment != incr {
  262. st.t.Fatalf("WindowUpdate increment = %d; want %d", f.Increment, incr)
  263. }
  264. gotWindowUpdate = true
  265. default:
  266. st.t.Fatalf("Wanting a settings ACK or window update, received a %T", f)
  267. }
  268. }
  269. if !gotSettingsAck {
  270. st.t.Fatalf("Didn't get a settings ACK")
  271. }
  272. if !gotWindowUpdate {
  273. st.t.Fatalf("Didn't get a window update")
  274. }
  275. }
  276. func (st *serverTester) writePreface() {
  277. n, err := st.cc.Write(clientPreface)
  278. if err != nil {
  279. st.t.Fatalf("Error writing client preface: %v", err)
  280. }
  281. if n != len(clientPreface) {
  282. st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface))
  283. }
  284. }
  285. func (st *serverTester) writeInitialSettings() {
  286. if err := st.fr.WriteSettings(); err != nil {
  287. st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err)
  288. }
  289. }
  290. func (st *serverTester) writeSettingsAck() {
  291. if err := st.fr.WriteSettingsAck(); err != nil {
  292. st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err)
  293. }
  294. }
  295. func (st *serverTester) writeHeaders(p HeadersFrameParam) {
  296. if err := st.fr.WriteHeaders(p); err != nil {
  297. st.t.Fatalf("Error writing HEADERS: %v", err)
  298. }
  299. }
  300. func (st *serverTester) writePriority(id uint32, p PriorityParam) {
  301. if err := st.fr.WritePriority(id, p); err != nil {
  302. st.t.Fatalf("Error writing PRIORITY: %v", err)
  303. }
  304. }
  305. func (st *serverTester) encodeHeaderField(k, v string) {
  306. err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v})
  307. if err != nil {
  308. st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
  309. }
  310. }
  311. // encodeHeaderRaw is the magic-free version of encodeHeader.
  312. // It takes 0 or more (k, v) pairs and encodes them.
  313. func (st *serverTester) encodeHeaderRaw(headers ...string) []byte {
  314. if len(headers)%2 == 1 {
  315. panic("odd number of kv args")
  316. }
  317. st.headerBuf.Reset()
  318. for len(headers) > 0 {
  319. k, v := headers[0], headers[1]
  320. st.encodeHeaderField(k, v)
  321. headers = headers[2:]
  322. }
  323. return st.headerBuf.Bytes()
  324. }
  325. // encodeHeader encodes headers and returns their HPACK bytes. headers
  326. // must contain an even number of key/value pairs. There may be
  327. // multiple pairs for keys (e.g. "cookie"). The :method, :path, and
  328. // :scheme headers default to GET, / and https. The :authority header
  329. // defaults to st.ts.Listener.Addr().
  330. func (st *serverTester) encodeHeader(headers ...string) []byte {
  331. if len(headers)%2 == 1 {
  332. panic("odd number of kv args")
  333. }
  334. st.headerBuf.Reset()
  335. defaultAuthority := st.ts.Listener.Addr().String()
  336. if len(headers) == 0 {
  337. // Fast path, mostly for benchmarks, so test code doesn't pollute
  338. // profiles when we're looking to improve server allocations.
  339. st.encodeHeaderField(":method", "GET")
  340. st.encodeHeaderField(":scheme", "https")
  341. st.encodeHeaderField(":authority", defaultAuthority)
  342. st.encodeHeaderField(":path", "/")
  343. return st.headerBuf.Bytes()
  344. }
  345. if len(headers) == 2 && headers[0] == ":method" {
  346. // Another fast path for benchmarks.
  347. st.encodeHeaderField(":method", headers[1])
  348. st.encodeHeaderField(":scheme", "https")
  349. st.encodeHeaderField(":authority", defaultAuthority)
  350. st.encodeHeaderField(":path", "/")
  351. return st.headerBuf.Bytes()
  352. }
  353. pseudoCount := map[string]int{}
  354. keys := []string{":method", ":scheme", ":authority", ":path"}
  355. vals := map[string][]string{
  356. ":method": {"GET"},
  357. ":scheme": {"https"},
  358. ":authority": {defaultAuthority},
  359. ":path": {"/"},
  360. }
  361. for len(headers) > 0 {
  362. k, v := headers[0], headers[1]
  363. headers = headers[2:]
  364. if _, ok := vals[k]; !ok {
  365. keys = append(keys, k)
  366. }
  367. if strings.HasPrefix(k, ":") {
  368. pseudoCount[k]++
  369. if pseudoCount[k] == 1 {
  370. vals[k] = []string{v}
  371. } else {
  372. // Allows testing of invalid headers w/ dup pseudo fields.
  373. vals[k] = append(vals[k], v)
  374. }
  375. } else {
  376. vals[k] = append(vals[k], v)
  377. }
  378. }
  379. for _, k := range keys {
  380. for _, v := range vals[k] {
  381. st.encodeHeaderField(k, v)
  382. }
  383. }
  384. return st.headerBuf.Bytes()
  385. }
  386. // bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set.
  387. func (st *serverTester) bodylessReq1(headers ...string) {
  388. st.writeHeaders(HeadersFrameParam{
  389. StreamID: 1, // clients send odd numbers
  390. BlockFragment: st.encodeHeader(headers...),
  391. EndStream: true,
  392. EndHeaders: true,
  393. })
  394. }
  395. func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) {
  396. if err := st.fr.WriteData(streamID, endStream, data); err != nil {
  397. st.t.Fatalf("Error writing DATA: %v", err)
  398. }
  399. }
  400. func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, pad []byte) {
  401. if err := st.fr.WriteDataPadded(streamID, endStream, data, pad); err != nil {
  402. st.t.Fatalf("Error writing DATA: %v", err)
  403. }
  404. }
  405. func readFrameTimeout(fr *Framer, wait time.Duration) (Frame, error) {
  406. ch := make(chan interface{}, 1)
  407. go func() {
  408. fr, err := fr.ReadFrame()
  409. if err != nil {
  410. ch <- err
  411. } else {
  412. ch <- fr
  413. }
  414. }()
  415. t := time.NewTimer(wait)
  416. select {
  417. case v := <-ch:
  418. t.Stop()
  419. if fr, ok := v.(Frame); ok {
  420. return fr, nil
  421. }
  422. return nil, v.(error)
  423. case <-t.C:
  424. return nil, errors.New("timeout waiting for frame")
  425. }
  426. }
  427. func (st *serverTester) readFrame() (Frame, error) {
  428. return readFrameTimeout(st.fr, 2*time.Second)
  429. }
  430. func (st *serverTester) wantHeaders() *HeadersFrame {
  431. f, err := st.readFrame()
  432. if err != nil {
  433. st.t.Fatalf("Error while expecting a HEADERS frame: %v", err)
  434. }
  435. hf, ok := f.(*HeadersFrame)
  436. if !ok {
  437. st.t.Fatalf("got a %T; want *HeadersFrame", f)
  438. }
  439. return hf
  440. }
  441. func (st *serverTester) wantContinuation() *ContinuationFrame {
  442. f, err := st.readFrame()
  443. if err != nil {
  444. st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err)
  445. }
  446. cf, ok := f.(*ContinuationFrame)
  447. if !ok {
  448. st.t.Fatalf("got a %T; want *ContinuationFrame", f)
  449. }
  450. return cf
  451. }
  452. func (st *serverTester) wantData() *DataFrame {
  453. f, err := st.readFrame()
  454. if err != nil {
  455. st.t.Fatalf("Error while expecting a DATA frame: %v", err)
  456. }
  457. df, ok := f.(*DataFrame)
  458. if !ok {
  459. st.t.Fatalf("got a %T; want *DataFrame", f)
  460. }
  461. return df
  462. }
  463. func (st *serverTester) wantSettings() *SettingsFrame {
  464. f, err := st.readFrame()
  465. if err != nil {
  466. st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err)
  467. }
  468. sf, ok := f.(*SettingsFrame)
  469. if !ok {
  470. st.t.Fatalf("got a %T; want *SettingsFrame", f)
  471. }
  472. return sf
  473. }
  474. func (st *serverTester) wantPing() *PingFrame {
  475. f, err := st.readFrame()
  476. if err != nil {
  477. st.t.Fatalf("Error while expecting a PING frame: %v", err)
  478. }
  479. pf, ok := f.(*PingFrame)
  480. if !ok {
  481. st.t.Fatalf("got a %T; want *PingFrame", f)
  482. }
  483. return pf
  484. }
  485. func (st *serverTester) wantGoAway() *GoAwayFrame {
  486. f, err := st.readFrame()
  487. if err != nil {
  488. st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err)
  489. }
  490. gf, ok := f.(*GoAwayFrame)
  491. if !ok {
  492. st.t.Fatalf("got a %T; want *GoAwayFrame", f)
  493. }
  494. return gf
  495. }
  496. func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) {
  497. f, err := st.readFrame()
  498. if err != nil {
  499. st.t.Fatalf("Error while expecting an RSTStream frame: %v", err)
  500. }
  501. rs, ok := f.(*RSTStreamFrame)
  502. if !ok {
  503. st.t.Fatalf("got a %T; want *RSTStreamFrame", f)
  504. }
  505. if rs.FrameHeader.StreamID != streamID {
  506. st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID)
  507. }
  508. if rs.ErrCode != errCode {
  509. st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode)
  510. }
  511. }
  512. func (st *serverTester) wantWindowUpdate(streamID, incr uint32) {
  513. f, err := st.readFrame()
  514. if err != nil {
  515. st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err)
  516. }
  517. wu, ok := f.(*WindowUpdateFrame)
  518. if !ok {
  519. st.t.Fatalf("got a %T; want *WindowUpdateFrame", f)
  520. }
  521. if wu.FrameHeader.StreamID != streamID {
  522. st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID)
  523. }
  524. if wu.Increment != incr {
  525. st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr)
  526. }
  527. }
  528. func (st *serverTester) wantSettingsAck() {
  529. f, err := st.readFrame()
  530. if err != nil {
  531. st.t.Fatal(err)
  532. }
  533. sf, ok := f.(*SettingsFrame)
  534. if !ok {
  535. st.t.Fatalf("Wanting a settings ACK, received a %T", f)
  536. }
  537. if !sf.Header().Flags.Has(FlagSettingsAck) {
  538. st.t.Fatal("Settings Frame didn't have ACK set")
  539. }
  540. }
  541. func (st *serverTester) wantPushPromise() *PushPromiseFrame {
  542. f, err := st.readFrame()
  543. if err != nil {
  544. st.t.Fatal(err)
  545. }
  546. ppf, ok := f.(*PushPromiseFrame)
  547. if !ok {
  548. st.t.Fatalf("Wanted PushPromise, received %T", ppf)
  549. }
  550. return ppf
  551. }
  552. func TestServer(t *testing.T) {
  553. gotReq := make(chan bool, 1)
  554. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  555. w.Header().Set("Foo", "Bar")
  556. gotReq <- true
  557. })
  558. defer st.Close()
  559. covers("3.5", `
  560. The server connection preface consists of a potentially empty
  561. SETTINGS frame ([SETTINGS]) that MUST be the first frame the
  562. server sends in the HTTP/2 connection.
  563. `)
  564. st.greet()
  565. st.writeHeaders(HeadersFrameParam{
  566. StreamID: 1, // clients send odd numbers
  567. BlockFragment: st.encodeHeader(),
  568. EndStream: true, // no DATA frames
  569. EndHeaders: true,
  570. })
  571. select {
  572. case <-gotReq:
  573. case <-time.After(2 * time.Second):
  574. t.Error("timeout waiting for request")
  575. }
  576. }
  577. func TestServer_Request_Get(t *testing.T) {
  578. testServerRequest(t, func(st *serverTester) {
  579. st.writeHeaders(HeadersFrameParam{
  580. StreamID: 1, // clients send odd numbers
  581. BlockFragment: st.encodeHeader("foo-bar", "some-value"),
  582. EndStream: true, // no DATA frames
  583. EndHeaders: true,
  584. })
  585. }, func(r *http.Request) {
  586. if r.Method != "GET" {
  587. t.Errorf("Method = %q; want GET", r.Method)
  588. }
  589. if r.URL.Path != "/" {
  590. t.Errorf("URL.Path = %q; want /", r.URL.Path)
  591. }
  592. if r.ContentLength != 0 {
  593. t.Errorf("ContentLength = %v; want 0", r.ContentLength)
  594. }
  595. if r.Close {
  596. t.Error("Close = true; want false")
  597. }
  598. if !strings.Contains(r.RemoteAddr, ":") {
  599. t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr)
  600. }
  601. if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 {
  602. t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor)
  603. }
  604. wantHeader := http.Header{
  605. "Foo-Bar": []string{"some-value"},
  606. }
  607. if !reflect.DeepEqual(r.Header, wantHeader) {
  608. t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
  609. }
  610. if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
  611. t.Errorf("Read = %d, %v; want 0, EOF", n, err)
  612. }
  613. })
  614. }
  615. func TestServer_Request_Get_PathSlashes(t *testing.T) {
  616. testServerRequest(t, func(st *serverTester) {
  617. st.writeHeaders(HeadersFrameParam{
  618. StreamID: 1, // clients send odd numbers
  619. BlockFragment: st.encodeHeader(":path", "/%2f/"),
  620. EndStream: true, // no DATA frames
  621. EndHeaders: true,
  622. })
  623. }, func(r *http.Request) {
  624. if r.RequestURI != "/%2f/" {
  625. t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI)
  626. }
  627. if r.URL.Path != "///" {
  628. t.Errorf("URL.Path = %q; want ///", r.URL.Path)
  629. }
  630. })
  631. }
  632. // TODO: add a test with EndStream=true on the HEADERS but setting a
  633. // Content-Length anyway. Should we just omit it and force it to
  634. // zero?
  635. func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) {
  636. testServerRequest(t, func(st *serverTester) {
  637. st.writeHeaders(HeadersFrameParam{
  638. StreamID: 1, // clients send odd numbers
  639. BlockFragment: st.encodeHeader(":method", "POST"),
  640. EndStream: true,
  641. EndHeaders: true,
  642. })
  643. }, func(r *http.Request) {
  644. if r.Method != "POST" {
  645. t.Errorf("Method = %q; want POST", r.Method)
  646. }
  647. if r.ContentLength != 0 {
  648. t.Errorf("ContentLength = %v; want 0", r.ContentLength)
  649. }
  650. if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
  651. t.Errorf("Read = %d, %v; want 0, EOF", n, err)
  652. }
  653. })
  654. }
  655. func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) {
  656. testBodyContents(t, -1, "", func(st *serverTester) {
  657. st.writeHeaders(HeadersFrameParam{
  658. StreamID: 1, // clients send odd numbers
  659. BlockFragment: st.encodeHeader(":method", "POST"),
  660. EndStream: false, // to say DATA frames are coming
  661. EndHeaders: true,
  662. })
  663. st.writeData(1, true, nil) // just kidding. empty body.
  664. })
  665. }
  666. func TestServer_Request_Post_Body_OneData(t *testing.T) {
  667. const content = "Some content"
  668. testBodyContents(t, -1, content, func(st *serverTester) {
  669. st.writeHeaders(HeadersFrameParam{
  670. StreamID: 1, // clients send odd numbers
  671. BlockFragment: st.encodeHeader(":method", "POST"),
  672. EndStream: false, // to say DATA frames are coming
  673. EndHeaders: true,
  674. })
  675. st.writeData(1, true, []byte(content))
  676. })
  677. }
  678. func TestServer_Request_Post_Body_TwoData(t *testing.T) {
  679. const content = "Some content"
  680. testBodyContents(t, -1, content, func(st *serverTester) {
  681. st.writeHeaders(HeadersFrameParam{
  682. StreamID: 1, // clients send odd numbers
  683. BlockFragment: st.encodeHeader(":method", "POST"),
  684. EndStream: false, // to say DATA frames are coming
  685. EndHeaders: true,
  686. })
  687. st.writeData(1, false, []byte(content[:5]))
  688. st.writeData(1, true, []byte(content[5:]))
  689. })
  690. }
  691. func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) {
  692. const content = "Some content"
  693. testBodyContents(t, int64(len(content)), content, func(st *serverTester) {
  694. st.writeHeaders(HeadersFrameParam{
  695. StreamID: 1, // clients send odd numbers
  696. BlockFragment: st.encodeHeader(
  697. ":method", "POST",
  698. "content-length", strconv.Itoa(len(content)),
  699. ),
  700. EndStream: false, // to say DATA frames are coming
  701. EndHeaders: true,
  702. })
  703. st.writeData(1, true, []byte(content))
  704. })
  705. }
  706. func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) {
  707. testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes",
  708. func(st *serverTester) {
  709. st.writeHeaders(HeadersFrameParam{
  710. StreamID: 1, // clients send odd numbers
  711. BlockFragment: st.encodeHeader(
  712. ":method", "POST",
  713. "content-length", "3",
  714. ),
  715. EndStream: false, // to say DATA frames are coming
  716. EndHeaders: true,
  717. })
  718. st.writeData(1, true, []byte("12"))
  719. })
  720. }
  721. func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) {
  722. testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes",
  723. func(st *serverTester) {
  724. st.writeHeaders(HeadersFrameParam{
  725. StreamID: 1, // clients send odd numbers
  726. BlockFragment: st.encodeHeader(
  727. ":method", "POST",
  728. "content-length", "4",
  729. ),
  730. EndStream: false, // to say DATA frames are coming
  731. EndHeaders: true,
  732. })
  733. st.writeData(1, true, []byte("12345"))
  734. })
  735. }
  736. func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) {
  737. testServerRequest(t, write, func(r *http.Request) {
  738. if r.Method != "POST" {
  739. t.Errorf("Method = %q; want POST", r.Method)
  740. }
  741. if r.ContentLength != wantContentLength {
  742. t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
  743. }
  744. all, err := ioutil.ReadAll(r.Body)
  745. if err != nil {
  746. t.Fatal(err)
  747. }
  748. if string(all) != wantBody {
  749. t.Errorf("Read = %q; want %q", all, wantBody)
  750. }
  751. if err := r.Body.Close(); err != nil {
  752. t.Fatalf("Close: %v", err)
  753. }
  754. })
  755. }
  756. func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) {
  757. testServerRequest(t, write, func(r *http.Request) {
  758. if r.Method != "POST" {
  759. t.Errorf("Method = %q; want POST", r.Method)
  760. }
  761. if r.ContentLength != wantContentLength {
  762. t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
  763. }
  764. all, err := ioutil.ReadAll(r.Body)
  765. if err == nil {
  766. t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.",
  767. wantReadError, all)
  768. }
  769. if !strings.Contains(err.Error(), wantReadError) {
  770. t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError)
  771. }
  772. if err := r.Body.Close(); err != nil {
  773. t.Fatalf("Close: %v", err)
  774. }
  775. })
  776. }
  777. // Using a Host header, instead of :authority
  778. func TestServer_Request_Get_Host(t *testing.T) {
  779. const host = "example.com"
  780. testServerRequest(t, func(st *serverTester) {
  781. st.writeHeaders(HeadersFrameParam{
  782. StreamID: 1, // clients send odd numbers
  783. BlockFragment: st.encodeHeader(":authority", "", "host", host),
  784. EndStream: true,
  785. EndHeaders: true,
  786. })
  787. }, func(r *http.Request) {
  788. if r.Host != host {
  789. t.Errorf("Host = %q; want %q", r.Host, host)
  790. }
  791. })
  792. }
  793. // Using an :authority pseudo-header, instead of Host
  794. func TestServer_Request_Get_Authority(t *testing.T) {
  795. const host = "example.com"
  796. testServerRequest(t, func(st *serverTester) {
  797. st.writeHeaders(HeadersFrameParam{
  798. StreamID: 1, // clients send odd numbers
  799. BlockFragment: st.encodeHeader(":authority", host),
  800. EndStream: true,
  801. EndHeaders: true,
  802. })
  803. }, func(r *http.Request) {
  804. if r.Host != host {
  805. t.Errorf("Host = %q; want %q", r.Host, host)
  806. }
  807. })
  808. }
  809. func TestServer_Request_WithContinuation(t *testing.T) {
  810. wantHeader := http.Header{
  811. "Foo-One": []string{"value-one"},
  812. "Foo-Two": []string{"value-two"},
  813. "Foo-Three": []string{"value-three"},
  814. }
  815. testServerRequest(t, func(st *serverTester) {
  816. fullHeaders := st.encodeHeader(
  817. "foo-one", "value-one",
  818. "foo-two", "value-two",
  819. "foo-three", "value-three",
  820. )
  821. remain := fullHeaders
  822. chunks := 0
  823. for len(remain) > 0 {
  824. const maxChunkSize = 5
  825. chunk := remain
  826. if len(chunk) > maxChunkSize {
  827. chunk = chunk[:maxChunkSize]
  828. }
  829. remain = remain[len(chunk):]
  830. if chunks == 0 {
  831. st.writeHeaders(HeadersFrameParam{
  832. StreamID: 1, // clients send odd numbers
  833. BlockFragment: chunk,
  834. EndStream: true, // no DATA frames
  835. EndHeaders: false, // we'll have continuation frames
  836. })
  837. } else {
  838. err := st.fr.WriteContinuation(1, len(remain) == 0, chunk)
  839. if err != nil {
  840. t.Fatal(err)
  841. }
  842. }
  843. chunks++
  844. }
  845. if chunks < 2 {
  846. t.Fatal("too few chunks")
  847. }
  848. }, func(r *http.Request) {
  849. if !reflect.DeepEqual(r.Header, wantHeader) {
  850. t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
  851. }
  852. })
  853. }
  854. // Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field")
  855. func TestServer_Request_CookieConcat(t *testing.T) {
  856. const host = "example.com"
  857. testServerRequest(t, func(st *serverTester) {
  858. st.bodylessReq1(
  859. ":authority", host,
  860. "cookie", "a=b",
  861. "cookie", "c=d",
  862. "cookie", "e=f",
  863. )
  864. }, func(r *http.Request) {
  865. const want = "a=b; c=d; e=f"
  866. if got := r.Header.Get("Cookie"); got != want {
  867. t.Errorf("Cookie = %q; want %q", got, want)
  868. }
  869. })
  870. }
  871. func TestServer_Request_Reject_CapitalHeader(t *testing.T) {
  872. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") })
  873. }
  874. func TestServer_Request_Reject_HeaderFieldNameColon(t *testing.T) {
  875. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has:colon", "v") })
  876. }
  877. func TestServer_Request_Reject_HeaderFieldNameNULL(t *testing.T) {
  878. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has\x00null", "v") })
  879. }
  880. func TestServer_Request_Reject_HeaderFieldNameEmpty(t *testing.T) {
  881. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("", "v") })
  882. }
  883. func TestServer_Request_Reject_HeaderFieldValueNewline(t *testing.T) {
  884. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\nnewline") })
  885. }
  886. func TestServer_Request_Reject_HeaderFieldValueCR(t *testing.T) {
  887. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\rcarriage") })
  888. }
  889. func TestServer_Request_Reject_HeaderFieldValueDEL(t *testing.T) {
  890. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\x7fdel") })
  891. }
  892. func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) {
  893. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") })
  894. }
  895. func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) {
  896. // 8.1.2.3 Request Pseudo-Header Fields
  897. // "All HTTP/2 requests MUST include exactly one valid value" ...
  898. testRejectRequest(t, func(st *serverTester) {
  899. st.addLogFilter("duplicate pseudo-header")
  900. st.bodylessReq1(":method", "GET", ":method", "POST")
  901. })
  902. }
  903. func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) {
  904. // 8.1.2.3 Request Pseudo-Header Fields
  905. // "All pseudo-header fields MUST appear in the header block
  906. // before regular header fields. Any request or response that
  907. // contains a pseudo-header field that appears in a header
  908. // block after a regular header field MUST be treated as
  909. // malformed (Section 8.1.2.6)."
  910. testRejectRequest(t, func(st *serverTester) {
  911. st.addLogFilter("pseudo-header after regular header")
  912. var buf bytes.Buffer
  913. enc := hpack.NewEncoder(&buf)
  914. enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"})
  915. enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"})
  916. enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"})
  917. enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"})
  918. st.writeHeaders(HeadersFrameParam{
  919. StreamID: 1, // clients send odd numbers
  920. BlockFragment: buf.Bytes(),
  921. EndStream: true,
  922. EndHeaders: true,
  923. })
  924. })
  925. }
  926. func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) {
  927. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") })
  928. }
  929. func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) {
  930. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") })
  931. }
  932. func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) {
  933. testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") })
  934. }
  935. func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) {
  936. testRejectRequest(t, func(st *serverTester) {
  937. st.addLogFilter(`invalid pseudo-header ":unknown_thing"`)
  938. st.bodylessReq1(":unknown_thing", "")
  939. })
  940. }
  941. func testRejectRequest(t *testing.T, send func(*serverTester)) {
  942. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  943. t.Error("server request made it to handler; should've been rejected")
  944. })
  945. defer st.Close()
  946. st.greet()
  947. send(st)
  948. st.wantRSTStream(1, ErrCodeProtocol)
  949. }
  950. func testRejectRequestWithProtocolError(t *testing.T, send func(*serverTester)) {
  951. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  952. t.Error("server request made it to handler; should've been rejected")
  953. }, optQuiet)
  954. defer st.Close()
  955. st.greet()
  956. send(st)
  957. gf := st.wantGoAway()
  958. if gf.ErrCode != ErrCodeProtocol {
  959. t.Errorf("err code = %v; want %v", gf.ErrCode, ErrCodeProtocol)
  960. }
  961. }
  962. // Section 5.1, on idle connections: "Receiving any frame other than
  963. // HEADERS or PRIORITY on a stream in this state MUST be treated as a
  964. // connection error (Section 5.4.1) of type PROTOCOL_ERROR."
  965. func TestRejectFrameOnIdle_WindowUpdate(t *testing.T) {
  966. testRejectRequestWithProtocolError(t, func(st *serverTester) {
  967. st.fr.WriteWindowUpdate(123, 456)
  968. })
  969. }
  970. func TestRejectFrameOnIdle_Data(t *testing.T) {
  971. testRejectRequestWithProtocolError(t, func(st *serverTester) {
  972. st.fr.WriteData(123, true, nil)
  973. })
  974. }
  975. func TestRejectFrameOnIdle_RSTStream(t *testing.T) {
  976. testRejectRequestWithProtocolError(t, func(st *serverTester) {
  977. st.fr.WriteRSTStream(123, ErrCodeCancel)
  978. })
  979. }
  980. func TestServer_Request_Connect(t *testing.T) {
  981. testServerRequest(t, func(st *serverTester) {
  982. st.writeHeaders(HeadersFrameParam{
  983. StreamID: 1,
  984. BlockFragment: st.encodeHeaderRaw(
  985. ":method", "CONNECT",
  986. ":authority", "example.com:123",
  987. ),
  988. EndStream: true,
  989. EndHeaders: true,
  990. })
  991. }, func(r *http.Request) {
  992. if g, w := r.Method, "CONNECT"; g != w {
  993. t.Errorf("Method = %q; want %q", g, w)
  994. }
  995. if g, w := r.RequestURI, "example.com:123"; g != w {
  996. t.Errorf("RequestURI = %q; want %q", g, w)
  997. }
  998. if g, w := r.URL.Host, "example.com:123"; g != w {
  999. t.Errorf("URL.Host = %q; want %q", g, w)
  1000. }
  1001. })
  1002. }
  1003. func TestServer_Request_Connect_InvalidPath(t *testing.T) {
  1004. testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1005. st.writeHeaders(HeadersFrameParam{
  1006. StreamID: 1,
  1007. BlockFragment: st.encodeHeaderRaw(
  1008. ":method", "CONNECT",
  1009. ":authority", "example.com:123",
  1010. ":path", "/bogus",
  1011. ),
  1012. EndStream: true,
  1013. EndHeaders: true,
  1014. })
  1015. })
  1016. }
  1017. func TestServer_Request_Connect_InvalidScheme(t *testing.T) {
  1018. testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1019. st.writeHeaders(HeadersFrameParam{
  1020. StreamID: 1,
  1021. BlockFragment: st.encodeHeaderRaw(
  1022. ":method", "CONNECT",
  1023. ":authority", "example.com:123",
  1024. ":scheme", "https",
  1025. ),
  1026. EndStream: true,
  1027. EndHeaders: true,
  1028. })
  1029. })
  1030. }
  1031. func TestServer_Ping(t *testing.T) {
  1032. st := newServerTester(t, nil)
  1033. defer st.Close()
  1034. st.greet()
  1035. // Server should ignore this one, since it has ACK set.
  1036. ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128}
  1037. if err := st.fr.WritePing(true, ackPingData); err != nil {
  1038. t.Fatal(err)
  1039. }
  1040. // But the server should reply to this one, since ACK is false.
  1041. pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
  1042. if err := st.fr.WritePing(false, pingData); err != nil {
  1043. t.Fatal(err)
  1044. }
  1045. pf := st.wantPing()
  1046. if !pf.Flags.Has(FlagPingAck) {
  1047. t.Error("response ping doesn't have ACK set")
  1048. }
  1049. if pf.Data != pingData {
  1050. t.Errorf("response ping has data %q; want %q", pf.Data, pingData)
  1051. }
  1052. }
  1053. func TestServer_MaxQueuedControlFrames(t *testing.T) {
  1054. if testing.Short() {
  1055. t.Skip("skipping in short mode")
  1056. }
  1057. st := newServerTester(t, nil)
  1058. defer st.Close()
  1059. st.greet()
  1060. const extraPings = 500000 // enough to fill the TCP buffers
  1061. for i := 0; i < maxQueuedControlFrames+extraPings; i++ {
  1062. pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
  1063. if err := st.fr.WritePing(false, pingData); err != nil {
  1064. if i == 0 {
  1065. t.Fatal(err)
  1066. }
  1067. // We expect the connection to get closed by the server when the TCP
  1068. // buffer fills up and the write queue reaches MaxQueuedControlFrames.
  1069. t.Logf("sent %d PING frames", i)
  1070. return
  1071. }
  1072. }
  1073. t.Errorf("unexpected success sending all PING frames")
  1074. }
  1075. func TestServer_RejectsLargeFrames(t *testing.T) {
  1076. if runtime.GOOS == "windows" {
  1077. t.Skip("see golang.org/issue/13434")
  1078. }
  1079. st := newServerTester(t, nil)
  1080. defer st.Close()
  1081. st.greet()
  1082. // Write too large of a frame (too large by one byte)
  1083. // We ignore the return value because it's expected that the server
  1084. // will only read the first 9 bytes (the headre) and then disconnect.
  1085. st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1))
  1086. gf := st.wantGoAway()
  1087. if gf.ErrCode != ErrCodeFrameSize {
  1088. t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize)
  1089. }
  1090. if st.serverLogBuf.Len() != 0 {
  1091. // Previously we spun here for a bit until the GOAWAY disconnect
  1092. // timer fired, logging while we fired.
  1093. t.Errorf("unexpected server output: %.500s\n", st.serverLogBuf.Bytes())
  1094. }
  1095. }
  1096. func TestServer_Handler_Sends_WindowUpdate(t *testing.T) {
  1097. puppet := newHandlerPuppet()
  1098. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1099. puppet.act(w, r)
  1100. })
  1101. defer st.Close()
  1102. defer puppet.done()
  1103. st.greet()
  1104. st.writeHeaders(HeadersFrameParam{
  1105. StreamID: 1, // clients send odd numbers
  1106. BlockFragment: st.encodeHeader(":method", "POST"),
  1107. EndStream: false, // data coming
  1108. EndHeaders: true,
  1109. })
  1110. st.writeData(1, false, []byte("abcdef"))
  1111. puppet.do(readBodyHandler(t, "abc"))
  1112. st.wantWindowUpdate(0, 3)
  1113. st.wantWindowUpdate(1, 3)
  1114. puppet.do(readBodyHandler(t, "def"))
  1115. st.wantWindowUpdate(0, 3)
  1116. st.wantWindowUpdate(1, 3)
  1117. st.writeData(1, true, []byte("ghijkl")) // END_STREAM here
  1118. puppet.do(readBodyHandler(t, "ghi"))
  1119. puppet.do(readBodyHandler(t, "jkl"))
  1120. st.wantWindowUpdate(0, 3)
  1121. st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM
  1122. }
  1123. // the version of the TestServer_Handler_Sends_WindowUpdate with padding.
  1124. // See golang.org/issue/16556
  1125. func TestServer_Handler_Sends_WindowUpdate_Padding(t *testing.T) {
  1126. puppet := newHandlerPuppet()
  1127. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1128. puppet.act(w, r)
  1129. })
  1130. defer st.Close()
  1131. defer puppet.done()
  1132. st.greet()
  1133. st.writeHeaders(HeadersFrameParam{
  1134. StreamID: 1,
  1135. BlockFragment: st.encodeHeader(":method", "POST"),
  1136. EndStream: false,
  1137. EndHeaders: true,
  1138. })
  1139. st.writeDataPadded(1, false, []byte("abcdef"), []byte{0, 0, 0, 0})
  1140. // Expect to immediately get our 5 bytes of padding back for
  1141. // both the connection and stream (4 bytes of padding + 1 byte of length)
  1142. st.wantWindowUpdate(0, 5)
  1143. st.wantWindowUpdate(1, 5)
  1144. puppet.do(readBodyHandler(t, "abc"))
  1145. st.wantWindowUpdate(0, 3)
  1146. st.wantWindowUpdate(1, 3)
  1147. puppet.do(readBodyHandler(t, "def"))
  1148. st.wantWindowUpdate(0, 3)
  1149. st.wantWindowUpdate(1, 3)
  1150. }
  1151. func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) {
  1152. st := newServerTester(t, nil)
  1153. defer st.Close()
  1154. st.greet()
  1155. if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil {
  1156. t.Fatal(err)
  1157. }
  1158. gf := st.wantGoAway()
  1159. if gf.ErrCode != ErrCodeFlowControl {
  1160. t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl)
  1161. }
  1162. if gf.LastStreamID != 0 {
  1163. t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0)
  1164. }
  1165. }
  1166. func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) {
  1167. inHandler := make(chan bool)
  1168. blockHandler := make(chan bool)
  1169. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1170. inHandler <- true
  1171. <-blockHandler
  1172. })
  1173. defer st.Close()
  1174. defer close(blockHandler)
  1175. st.greet()
  1176. st.writeHeaders(HeadersFrameParam{
  1177. StreamID: 1,
  1178. BlockFragment: st.encodeHeader(":method", "POST"),
  1179. EndStream: false, // keep it open
  1180. EndHeaders: true,
  1181. })
  1182. <-inHandler
  1183. // Send a bogus window update:
  1184. if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil {
  1185. t.Fatal(err)
  1186. }
  1187. st.wantRSTStream(1, ErrCodeFlowControl)
  1188. }
  1189. // testServerPostUnblock sends a hanging POST with unsent data to handler,
  1190. // then runs fn once in the handler, and verifies that the error returned from
  1191. // handler is acceptable. It fails if takes over 5 seconds for handler to exit.
  1192. func testServerPostUnblock(t *testing.T,
  1193. handler func(http.ResponseWriter, *http.Request) error,
  1194. fn func(*serverTester),
  1195. checkErr func(error),
  1196. otherHeaders ...string) {
  1197. inHandler := make(chan bool)
  1198. errc := make(chan error, 1)
  1199. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1200. inHandler <- true
  1201. errc <- handler(w, r)
  1202. })
  1203. defer st.Close()
  1204. st.greet()
  1205. st.writeHeaders(HeadersFrameParam{
  1206. StreamID: 1,
  1207. BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...),
  1208. EndStream: false, // keep it open
  1209. EndHeaders: true,
  1210. })
  1211. <-inHandler
  1212. fn(st)
  1213. select {
  1214. case err := <-errc:
  1215. if checkErr != nil {
  1216. checkErr(err)
  1217. }
  1218. case <-time.After(5 * time.Second):
  1219. t.Fatal("timeout waiting for Handler to return")
  1220. }
  1221. }
  1222. func TestServer_RSTStream_Unblocks_Read(t *testing.T) {
  1223. testServerPostUnblock(t,
  1224. func(w http.ResponseWriter, r *http.Request) (err error) {
  1225. _, err = r.Body.Read(make([]byte, 1))
  1226. return
  1227. },
  1228. func(st *serverTester) {
  1229. if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1230. t.Fatal(err)
  1231. }
  1232. },
  1233. func(err error) {
  1234. want := StreamError{StreamID: 0x1, Code: 0x8}
  1235. if !reflect.DeepEqual(err, want) {
  1236. t.Errorf("Read error = %v; want %v", err, want)
  1237. }
  1238. },
  1239. )
  1240. }
  1241. func TestServer_RSTStream_Unblocks_Header_Write(t *testing.T) {
  1242. // Run this test a bunch, because it doesn't always
  1243. // deadlock. But with a bunch, it did.
  1244. n := 50
  1245. if testing.Short() {
  1246. n = 5
  1247. }
  1248. for i := 0; i < n; i++ {
  1249. testServer_RSTStream_Unblocks_Header_Write(t)
  1250. }
  1251. }
  1252. func testServer_RSTStream_Unblocks_Header_Write(t *testing.T) {
  1253. inHandler := make(chan bool, 1)
  1254. unblockHandler := make(chan bool, 1)
  1255. headerWritten := make(chan bool, 1)
  1256. wroteRST := make(chan bool, 1)
  1257. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1258. inHandler <- true
  1259. <-wroteRST
  1260. w.Header().Set("foo", "bar")
  1261. w.WriteHeader(200)
  1262. w.(http.Flusher).Flush()
  1263. headerWritten <- true
  1264. <-unblockHandler
  1265. })
  1266. defer st.Close()
  1267. st.greet()
  1268. st.writeHeaders(HeadersFrameParam{
  1269. StreamID: 1,
  1270. BlockFragment: st.encodeHeader(":method", "POST"),
  1271. EndStream: false, // keep it open
  1272. EndHeaders: true,
  1273. })
  1274. <-inHandler
  1275. if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1276. t.Fatal(err)
  1277. }
  1278. wroteRST <- true
  1279. st.awaitIdle()
  1280. select {
  1281. case <-headerWritten:
  1282. case <-time.After(2 * time.Second):
  1283. t.Error("timeout waiting for header write")
  1284. }
  1285. unblockHandler <- true
  1286. }
  1287. func TestServer_DeadConn_Unblocks_Read(t *testing.T) {
  1288. testServerPostUnblock(t,
  1289. func(w http.ResponseWriter, r *http.Request) (err error) {
  1290. _, err = r.Body.Read(make([]byte, 1))
  1291. return
  1292. },
  1293. func(st *serverTester) { st.cc.Close() },
  1294. func(err error) {
  1295. if err == nil {
  1296. t.Error("unexpected nil error from Request.Body.Read")
  1297. }
  1298. },
  1299. )
  1300. }
  1301. var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error {
  1302. <-w.(http.CloseNotifier).CloseNotify()
  1303. return nil
  1304. }
  1305. func TestServer_CloseNotify_After_RSTStream(t *testing.T) {
  1306. testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) {
  1307. if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1308. t.Fatal(err)
  1309. }
  1310. }, nil)
  1311. }
  1312. func TestServer_CloseNotify_After_ConnClose(t *testing.T) {
  1313. testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil)
  1314. }
  1315. // that CloseNotify unblocks after a stream error due to the client's
  1316. // problem that's unrelated to them explicitly canceling it (which is
  1317. // TestServer_CloseNotify_After_RSTStream above)
  1318. func TestServer_CloseNotify_After_StreamError(t *testing.T) {
  1319. testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) {
  1320. // data longer than declared Content-Length => stream error
  1321. st.writeData(1, true, []byte("1234"))
  1322. }, nil, "content-length", "3")
  1323. }
  1324. func TestServer_StateTransitions(t *testing.T) {
  1325. var st *serverTester
  1326. inHandler := make(chan bool)
  1327. writeData := make(chan bool)
  1328. leaveHandler := make(chan bool)
  1329. st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1330. inHandler <- true
  1331. if st.stream(1) == nil {
  1332. t.Errorf("nil stream 1 in handler")
  1333. }
  1334. if got, want := st.streamState(1), stateOpen; got != want {
  1335. t.Errorf("in handler, state is %v; want %v", got, want)
  1336. }
  1337. writeData <- true
  1338. if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF {
  1339. t.Errorf("body read = %d, %v; want 0, EOF", n, err)
  1340. }
  1341. if got, want := st.streamState(1), stateHalfClosedRemote; got != want {
  1342. t.Errorf("in handler, state is %v; want %v", got, want)
  1343. }
  1344. <-leaveHandler
  1345. })
  1346. st.greet()
  1347. if st.stream(1) != nil {
  1348. t.Fatal("stream 1 should be empty")
  1349. }
  1350. if got := st.streamState(1); got != stateIdle {
  1351. t.Fatalf("stream 1 should be idle; got %v", got)
  1352. }
  1353. st.writeHeaders(HeadersFrameParam{
  1354. StreamID: 1,
  1355. BlockFragment: st.encodeHeader(":method", "POST"),
  1356. EndStream: false, // keep it open
  1357. EndHeaders: true,
  1358. })
  1359. <-inHandler
  1360. <-writeData
  1361. st.writeData(1, true, nil)
  1362. leaveHandler <- true
  1363. hf := st.wantHeaders()
  1364. if !hf.StreamEnded() {
  1365. t.Fatal("expected END_STREAM flag")
  1366. }
  1367. if got, want := st.streamState(1), stateClosed; got != want {
  1368. t.Errorf("at end, state is %v; want %v", got, want)
  1369. }
  1370. if st.stream(1) != nil {
  1371. t.Fatal("at end, stream 1 should be gone")
  1372. }
  1373. }
  1374. // test HEADERS w/o EndHeaders + another HEADERS (should get rejected)
  1375. func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) {
  1376. testServerRejectsConn(t, func(st *serverTester) {
  1377. st.writeHeaders(HeadersFrameParam{
  1378. StreamID: 1,
  1379. BlockFragment: st.encodeHeader(),
  1380. EndStream: true,
  1381. EndHeaders: false,
  1382. })
  1383. st.writeHeaders(HeadersFrameParam{ // Not a continuation.
  1384. StreamID: 3, // different stream.
  1385. BlockFragment: st.encodeHeader(),
  1386. EndStream: true,
  1387. EndHeaders: true,
  1388. })
  1389. })
  1390. }
  1391. // test HEADERS w/o EndHeaders + PING (should get rejected)
  1392. func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) {
  1393. testServerRejectsConn(t, func(st *serverTester) {
  1394. st.writeHeaders(HeadersFrameParam{
  1395. StreamID: 1,
  1396. BlockFragment: st.encodeHeader(),
  1397. EndStream: true,
  1398. EndHeaders: false,
  1399. })
  1400. if err := st.fr.WritePing(false, [8]byte{}); err != nil {
  1401. t.Fatal(err)
  1402. }
  1403. })
  1404. }
  1405. // test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected)
  1406. func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) {
  1407. testServerRejectsConn(t, func(st *serverTester) {
  1408. st.writeHeaders(HeadersFrameParam{
  1409. StreamID: 1,
  1410. BlockFragment: st.encodeHeader(),
  1411. EndStream: true,
  1412. EndHeaders: true,
  1413. })
  1414. st.wantHeaders()
  1415. if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil {
  1416. t.Fatal(err)
  1417. }
  1418. })
  1419. }
  1420. // test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID
  1421. func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) {
  1422. testServerRejectsConn(t, func(st *serverTester) {
  1423. st.writeHeaders(HeadersFrameParam{
  1424. StreamID: 1,
  1425. BlockFragment: st.encodeHeader(),
  1426. EndStream: true,
  1427. EndHeaders: false,
  1428. })
  1429. if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil {
  1430. t.Fatal(err)
  1431. }
  1432. })
  1433. }
  1434. // No HEADERS on stream 0.
  1435. func TestServer_Rejects_Headers0(t *testing.T) {
  1436. testServerRejectsConn(t, func(st *serverTester) {
  1437. st.fr.AllowIllegalWrites = true
  1438. st.writeHeaders(HeadersFrameParam{
  1439. StreamID: 0,
  1440. BlockFragment: st.encodeHeader(),
  1441. EndStream: true,
  1442. EndHeaders: true,
  1443. })
  1444. })
  1445. }
  1446. // No CONTINUATION on stream 0.
  1447. func TestServer_Rejects_Continuation0(t *testing.T) {
  1448. testServerRejectsConn(t, func(st *serverTester) {
  1449. st.fr.AllowIllegalWrites = true
  1450. if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil {
  1451. t.Fatal(err)
  1452. }
  1453. })
  1454. }
  1455. // No PRIORITY on stream 0.
  1456. func TestServer_Rejects_Priority0(t *testing.T) {
  1457. testServerRejectsConn(t, func(st *serverTester) {
  1458. st.fr.AllowIllegalWrites = true
  1459. st.writePriority(0, PriorityParam{StreamDep: 1})
  1460. })
  1461. }
  1462. // No HEADERS frame with a self-dependence.
  1463. func TestServer_Rejects_HeadersSelfDependence(t *testing.T) {
  1464. testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1465. st.fr.AllowIllegalWrites = true
  1466. st.writeHeaders(HeadersFrameParam{
  1467. StreamID: 1,
  1468. BlockFragment: st.encodeHeader(),
  1469. EndStream: true,
  1470. EndHeaders: true,
  1471. Priority: PriorityParam{StreamDep: 1},
  1472. })
  1473. })
  1474. }
  1475. // No PRIORTY frame with a self-dependence.
  1476. func TestServer_Rejects_PrioritySelfDependence(t *testing.T) {
  1477. testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1478. st.fr.AllowIllegalWrites = true
  1479. st.writePriority(1, PriorityParam{StreamDep: 1})
  1480. })
  1481. }
  1482. func TestServer_Rejects_PushPromise(t *testing.T) {
  1483. testServerRejectsConn(t, func(st *serverTester) {
  1484. pp := PushPromiseParam{
  1485. StreamID: 1,
  1486. PromiseID: 3,
  1487. }
  1488. if err := st.fr.WritePushPromise(pp); err != nil {
  1489. t.Fatal(err)
  1490. }
  1491. })
  1492. }
  1493. // testServerRejectsConn tests that the server hangs up with a GOAWAY
  1494. // frame and a server close after the client does something
  1495. // deserving a CONNECTION_ERROR.
  1496. func testServerRejectsConn(t *testing.T, writeReq func(*serverTester)) {
  1497. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  1498. st.addLogFilter("connection error: PROTOCOL_ERROR")
  1499. defer st.Close()
  1500. st.greet()
  1501. writeReq(st)
  1502. st.wantGoAway()
  1503. errc := make(chan error, 1)
  1504. go func() {
  1505. fr, err := st.fr.ReadFrame()
  1506. if err == nil {
  1507. err = fmt.Errorf("got frame of type %T", fr)
  1508. }
  1509. errc <- err
  1510. }()
  1511. select {
  1512. case err := <-errc:
  1513. if err != io.EOF {
  1514. t.Errorf("ReadFrame = %v; want io.EOF", err)
  1515. }
  1516. case <-time.After(2 * time.Second):
  1517. t.Error("timeout waiting for disconnect")
  1518. }
  1519. }
  1520. // testServerRejectsStream tests that the server sends a RST_STREAM with the provided
  1521. // error code after a client sends a bogus request.
  1522. func testServerRejectsStream(t *testing.T, code ErrCode, writeReq func(*serverTester)) {
  1523. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  1524. defer st.Close()
  1525. st.greet()
  1526. writeReq(st)
  1527. st.wantRSTStream(1, code)
  1528. }
  1529. // testServerRequest sets up an idle HTTP/2 connection and lets you
  1530. // write a single request with writeReq, and then verify that the
  1531. // *http.Request is built correctly in checkReq.
  1532. func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) {
  1533. gotReq := make(chan bool, 1)
  1534. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1535. if r.Body == nil {
  1536. t.Fatal("nil Body")
  1537. }
  1538. checkReq(r)
  1539. gotReq <- true
  1540. })
  1541. defer st.Close()
  1542. st.greet()
  1543. writeReq(st)
  1544. select {
  1545. case <-gotReq:
  1546. case <-time.After(2 * time.Second):
  1547. t.Error("timeout waiting for request")
  1548. }
  1549. }
  1550. func getSlash(st *serverTester) { st.bodylessReq1() }
  1551. func TestServer_Response_NoData(t *testing.T) {
  1552. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1553. // Nothing.
  1554. return nil
  1555. }, func(st *serverTester) {
  1556. getSlash(st)
  1557. hf := st.wantHeaders()
  1558. if !hf.StreamEnded() {
  1559. t.Fatal("want END_STREAM flag")
  1560. }
  1561. if !hf.HeadersEnded() {
  1562. t.Fatal("want END_HEADERS flag")
  1563. }
  1564. })
  1565. }
  1566. func TestServer_Response_NoData_Header_FooBar(t *testing.T) {
  1567. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1568. w.Header().Set("Foo-Bar", "some-value")
  1569. return nil
  1570. }, func(st *serverTester) {
  1571. getSlash(st)
  1572. hf := st.wantHeaders()
  1573. if !hf.StreamEnded() {
  1574. t.Fatal("want END_STREAM flag")
  1575. }
  1576. if !hf.HeadersEnded() {
  1577. t.Fatal("want END_HEADERS flag")
  1578. }
  1579. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1580. wanth := [][2]string{
  1581. {":status", "200"},
  1582. {"foo-bar", "some-value"},
  1583. {"content-length", "0"},
  1584. }
  1585. if !reflect.DeepEqual(goth, wanth) {
  1586. t.Errorf("Got headers %v; want %v", goth, wanth)
  1587. }
  1588. })
  1589. }
  1590. func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) {
  1591. const msg = "<html>this is HTML."
  1592. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1593. w.Header().Set("Content-Type", "foo/bar")
  1594. io.WriteString(w, msg)
  1595. return nil
  1596. }, func(st *serverTester) {
  1597. getSlash(st)
  1598. hf := st.wantHeaders()
  1599. if hf.StreamEnded() {
  1600. t.Fatal("don't want END_STREAM, expecting data")
  1601. }
  1602. if !hf.HeadersEnded() {
  1603. t.Fatal("want END_HEADERS flag")
  1604. }
  1605. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1606. wanth := [][2]string{
  1607. {":status", "200"},
  1608. {"content-type", "foo/bar"},
  1609. {"content-length", strconv.Itoa(len(msg))},
  1610. }
  1611. if !reflect.DeepEqual(goth, wanth) {
  1612. t.Errorf("Got headers %v; want %v", goth, wanth)
  1613. }
  1614. df := st.wantData()
  1615. if !df.StreamEnded() {
  1616. t.Error("expected DATA to have END_STREAM flag")
  1617. }
  1618. if got := string(df.Data()); got != msg {
  1619. t.Errorf("got DATA %q; want %q", got, msg)
  1620. }
  1621. })
  1622. }
  1623. func TestServer_Response_TransferEncoding_chunked(t *testing.T) {
  1624. const msg = "hi"
  1625. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1626. w.Header().Set("Transfer-Encoding", "chunked") // should be stripped
  1627. io.WriteString(w, msg)
  1628. return nil
  1629. }, func(st *serverTester) {
  1630. getSlash(st)
  1631. hf := st.wantHeaders()
  1632. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1633. wanth := [][2]string{
  1634. {":status", "200"},
  1635. {"content-type", "text/plain; charset=utf-8"},
  1636. {"content-length", strconv.Itoa(len(msg))},
  1637. }
  1638. if !reflect.DeepEqual(goth, wanth) {
  1639. t.Errorf("Got headers %v; want %v", goth, wanth)
  1640. }
  1641. })
  1642. }
  1643. // Header accessed only after the initial write.
  1644. func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) {
  1645. const msg = "<html>this is HTML."
  1646. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1647. io.WriteString(w, msg)
  1648. w.Header().Set("foo", "should be ignored")
  1649. return nil
  1650. }, func(st *serverTester) {
  1651. getSlash(st)
  1652. hf := st.wantHeaders()
  1653. if hf.StreamEnded() {
  1654. t.Fatal("unexpected END_STREAM")
  1655. }
  1656. if !hf.HeadersEnded() {
  1657. t.Fatal("want END_HEADERS flag")
  1658. }
  1659. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1660. wanth := [][2]string{
  1661. {":status", "200"},
  1662. {"content-type", "text/html; charset=utf-8"},
  1663. {"content-length", strconv.Itoa(len(msg))},
  1664. }
  1665. if !reflect.DeepEqual(goth, wanth) {
  1666. t.Errorf("Got headers %v; want %v", goth, wanth)
  1667. }
  1668. })
  1669. }
  1670. // Header accessed before the initial write and later mutated.
  1671. func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) {
  1672. const msg = "<html>this is HTML."
  1673. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1674. w.Header().Set("foo", "proper value")
  1675. io.WriteString(w, msg)
  1676. w.Header().Set("foo", "should be ignored")
  1677. return nil
  1678. }, func(st *serverTester) {
  1679. getSlash(st)
  1680. hf := st.wantHeaders()
  1681. if hf.StreamEnded() {
  1682. t.Fatal("unexpected END_STREAM")
  1683. }
  1684. if !hf.HeadersEnded() {
  1685. t.Fatal("want END_HEADERS flag")
  1686. }
  1687. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1688. wanth := [][2]string{
  1689. {":status", "200"},
  1690. {"foo", "proper value"},
  1691. {"content-type", "text/html; charset=utf-8"},
  1692. {"content-length", strconv.Itoa(len(msg))},
  1693. }
  1694. if !reflect.DeepEqual(goth, wanth) {
  1695. t.Errorf("Got headers %v; want %v", goth, wanth)
  1696. }
  1697. })
  1698. }
  1699. func TestServer_Response_Data_SniffLenType(t *testing.T) {
  1700. const msg = "<html>this is HTML."
  1701. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1702. io.WriteString(w, msg)
  1703. return nil
  1704. }, func(st *serverTester) {
  1705. getSlash(st)
  1706. hf := st.wantHeaders()
  1707. if hf.StreamEnded() {
  1708. t.Fatal("don't want END_STREAM, expecting data")
  1709. }
  1710. if !hf.HeadersEnded() {
  1711. t.Fatal("want END_HEADERS flag")
  1712. }
  1713. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1714. wanth := [][2]string{
  1715. {":status", "200"},
  1716. {"content-type", "text/html; charset=utf-8"},
  1717. {"content-length", strconv.Itoa(len(msg))},
  1718. }
  1719. if !reflect.DeepEqual(goth, wanth) {
  1720. t.Errorf("Got headers %v; want %v", goth, wanth)
  1721. }
  1722. df := st.wantData()
  1723. if !df.StreamEnded() {
  1724. t.Error("expected DATA to have END_STREAM flag")
  1725. }
  1726. if got := string(df.Data()); got != msg {
  1727. t.Errorf("got DATA %q; want %q", got, msg)
  1728. }
  1729. })
  1730. }
  1731. func TestServer_Response_Header_Flush_MidWrite(t *testing.T) {
  1732. const msg = "<html>this is HTML"
  1733. const msg2 = ", and this is the next chunk"
  1734. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1735. io.WriteString(w, msg)
  1736. w.(http.Flusher).Flush()
  1737. io.WriteString(w, msg2)
  1738. return nil
  1739. }, func(st *serverTester) {
  1740. getSlash(st)
  1741. hf := st.wantHeaders()
  1742. if hf.StreamEnded() {
  1743. t.Fatal("unexpected END_STREAM flag")
  1744. }
  1745. if !hf.HeadersEnded() {
  1746. t.Fatal("want END_HEADERS flag")
  1747. }
  1748. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1749. wanth := [][2]string{
  1750. {":status", "200"},
  1751. {"content-type", "text/html; charset=utf-8"}, // sniffed
  1752. // and no content-length
  1753. }
  1754. if !reflect.DeepEqual(goth, wanth) {
  1755. t.Errorf("Got headers %v; want %v", goth, wanth)
  1756. }
  1757. {
  1758. df := st.wantData()
  1759. if df.StreamEnded() {
  1760. t.Error("unexpected END_STREAM flag")
  1761. }
  1762. if got := string(df.Data()); got != msg {
  1763. t.Errorf("got DATA %q; want %q", got, msg)
  1764. }
  1765. }
  1766. {
  1767. df := st.wantData()
  1768. if !df.StreamEnded() {
  1769. t.Error("wanted END_STREAM flag on last data chunk")
  1770. }
  1771. if got := string(df.Data()); got != msg2 {
  1772. t.Errorf("got DATA %q; want %q", got, msg2)
  1773. }
  1774. }
  1775. })
  1776. }
  1777. func TestServer_Response_LargeWrite(t *testing.T) {
  1778. const size = 1 << 20
  1779. const maxFrameSize = 16 << 10
  1780. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1781. n, err := w.Write(bytes.Repeat([]byte("a"), size))
  1782. if err != nil {
  1783. return fmt.Errorf("Write error: %v", err)
  1784. }
  1785. if n != size {
  1786. return fmt.Errorf("wrong size %d from Write", n)
  1787. }
  1788. return nil
  1789. }, func(st *serverTester) {
  1790. if err := st.fr.WriteSettings(
  1791. Setting{SettingInitialWindowSize, 0},
  1792. Setting{SettingMaxFrameSize, maxFrameSize},
  1793. ); err != nil {
  1794. t.Fatal(err)
  1795. }
  1796. st.wantSettingsAck()
  1797. getSlash(st) // make the single request
  1798. // Give the handler quota to write:
  1799. if err := st.fr.WriteWindowUpdate(1, size); err != nil {
  1800. t.Fatal(err)
  1801. }
  1802. // Give the handler quota to write to connection-level
  1803. // window as well
  1804. if err := st.fr.WriteWindowUpdate(0, size); err != nil {
  1805. t.Fatal(err)
  1806. }
  1807. hf := st.wantHeaders()
  1808. if hf.StreamEnded() {
  1809. t.Fatal("unexpected END_STREAM flag")
  1810. }
  1811. if !hf.HeadersEnded() {
  1812. t.Fatal("want END_HEADERS flag")
  1813. }
  1814. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1815. wanth := [][2]string{
  1816. {":status", "200"},
  1817. {"content-type", "text/plain; charset=utf-8"}, // sniffed
  1818. // and no content-length
  1819. }
  1820. if !reflect.DeepEqual(goth, wanth) {
  1821. t.Errorf("Got headers %v; want %v", goth, wanth)
  1822. }
  1823. var bytes, frames int
  1824. for {
  1825. df := st.wantData()
  1826. bytes += len(df.Data())
  1827. frames++
  1828. for _, b := range df.Data() {
  1829. if b != 'a' {
  1830. t.Fatal("non-'a' byte seen in DATA")
  1831. }
  1832. }
  1833. if df.StreamEnded() {
  1834. break
  1835. }
  1836. }
  1837. if bytes != size {
  1838. t.Errorf("Got %d bytes; want %d", bytes, size)
  1839. }
  1840. if want := int(size / maxFrameSize); frames < want || frames > want*2 {
  1841. t.Errorf("Got %d frames; want %d", frames, size)
  1842. }
  1843. })
  1844. }
  1845. // Test that the handler can't write more than the client allows
  1846. func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) {
  1847. // Make these reads. Before each read, the client adds exactly enough
  1848. // flow-control to satisfy the read. Numbers chosen arbitrarily.
  1849. reads := []int{123, 1, 13, 127}
  1850. size := 0
  1851. for _, n := range reads {
  1852. size += n
  1853. }
  1854. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1855. w.(http.Flusher).Flush()
  1856. n, err := w.Write(bytes.Repeat([]byte("a"), size))
  1857. if err != nil {
  1858. return fmt.Errorf("Write error: %v", err)
  1859. }
  1860. if n != size {
  1861. return fmt.Errorf("wrong size %d from Write", n)
  1862. }
  1863. return nil
  1864. }, func(st *serverTester) {
  1865. // Set the window size to something explicit for this test.
  1866. // It's also how much initial data we expect.
  1867. if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil {
  1868. t.Fatal(err)
  1869. }
  1870. st.wantSettingsAck()
  1871. getSlash(st) // make the single request
  1872. hf := st.wantHeaders()
  1873. if hf.StreamEnded() {
  1874. t.Fatal("unexpected END_STREAM flag")
  1875. }
  1876. if !hf.HeadersEnded() {
  1877. t.Fatal("want END_HEADERS flag")
  1878. }
  1879. df := st.wantData()
  1880. if got := len(df.Data()); got != reads[0] {
  1881. t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got)
  1882. }
  1883. for _, quota := range reads[1:] {
  1884. if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil {
  1885. t.Fatal(err)
  1886. }
  1887. df := st.wantData()
  1888. if int(quota) != len(df.Data()) {
  1889. t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota)
  1890. }
  1891. }
  1892. })
  1893. }
  1894. // Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM.
  1895. func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) {
  1896. const size = 1 << 20
  1897. const maxFrameSize = 16 << 10
  1898. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1899. w.(http.Flusher).Flush()
  1900. errc := make(chan error, 1)
  1901. go func() {
  1902. _, err := w.Write(bytes.Repeat([]byte("a"), size))
  1903. errc <- err
  1904. }()
  1905. select {
  1906. case err := <-errc:
  1907. if err == nil {
  1908. return errors.New("unexpected nil error from Write in handler")
  1909. }
  1910. return nil
  1911. case <-time.After(2 * time.Second):
  1912. return errors.New("timeout waiting for Write in handler")
  1913. }
  1914. }, func(st *serverTester) {
  1915. if err := st.fr.WriteSettings(
  1916. Setting{SettingInitialWindowSize, 0},
  1917. Setting{SettingMaxFrameSize, maxFrameSize},
  1918. ); err != nil {
  1919. t.Fatal(err)
  1920. }
  1921. st.wantSettingsAck()
  1922. getSlash(st) // make the single request
  1923. hf := st.wantHeaders()
  1924. if hf.StreamEnded() {
  1925. t.Fatal("unexpected END_STREAM flag")
  1926. }
  1927. if !hf.HeadersEnded() {
  1928. t.Fatal("want END_HEADERS flag")
  1929. }
  1930. if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1931. t.Fatal(err)
  1932. }
  1933. })
  1934. }
  1935. func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) {
  1936. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1937. w.(http.Flusher).Flush()
  1938. // Nothing; send empty DATA
  1939. return nil
  1940. }, func(st *serverTester) {
  1941. // Handler gets no data quota:
  1942. if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil {
  1943. t.Fatal(err)
  1944. }
  1945. st.wantSettingsAck()
  1946. getSlash(st) // make the single request
  1947. hf := st.wantHeaders()
  1948. if hf.StreamEnded() {
  1949. t.Fatal("unexpected END_STREAM flag")
  1950. }
  1951. if !hf.HeadersEnded() {
  1952. t.Fatal("want END_HEADERS flag")
  1953. }
  1954. df := st.wantData()
  1955. if got := len(df.Data()); got != 0 {
  1956. t.Fatalf("unexpected %d DATA bytes; want 0", got)
  1957. }
  1958. if !df.StreamEnded() {
  1959. t.Fatal("DATA didn't have END_STREAM")
  1960. }
  1961. })
  1962. }
  1963. func TestServer_Response_Automatic100Continue(t *testing.T) {
  1964. const msg = "foo"
  1965. const reply = "bar"
  1966. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1967. if v := r.Header.Get("Expect"); v != "" {
  1968. t.Errorf("Expect header = %q; want empty", v)
  1969. }
  1970. buf := make([]byte, len(msg))
  1971. // This read should trigger the 100-continue being sent.
  1972. if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg {
  1973. return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg)
  1974. }
  1975. _, err := io.WriteString(w, reply)
  1976. return err
  1977. }, func(st *serverTester) {
  1978. st.writeHeaders(HeadersFrameParam{
  1979. StreamID: 1, // clients send odd numbers
  1980. BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"),
  1981. EndStream: false,
  1982. EndHeaders: true,
  1983. })
  1984. hf := st.wantHeaders()
  1985. if hf.StreamEnded() {
  1986. t.Fatal("unexpected END_STREAM flag")
  1987. }
  1988. if !hf.HeadersEnded() {
  1989. t.Fatal("want END_HEADERS flag")
  1990. }
  1991. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1992. wanth := [][2]string{
  1993. {":status", "100"},
  1994. }
  1995. if !reflect.DeepEqual(goth, wanth) {
  1996. t.Fatalf("Got headers %v; want %v", goth, wanth)
  1997. }
  1998. // Okay, they sent status 100, so we can send our
  1999. // gigantic and/or sensitive "foo" payload now.
  2000. st.writeData(1, true, []byte(msg))
  2001. st.wantWindowUpdate(0, uint32(len(msg)))
  2002. hf = st.wantHeaders()
  2003. if hf.StreamEnded() {
  2004. t.Fatal("expected data to follow")
  2005. }
  2006. if !hf.HeadersEnded() {
  2007. t.Fatal("want END_HEADERS flag")
  2008. }
  2009. goth = st.decodeHeader(hf.HeaderBlockFragment())
  2010. wanth = [][2]string{
  2011. {":status", "200"},
  2012. {"content-type", "text/plain; charset=utf-8"},
  2013. {"content-length", strconv.Itoa(len(reply))},
  2014. }
  2015. if !reflect.DeepEqual(goth, wanth) {
  2016. t.Errorf("Got headers %v; want %v", goth, wanth)
  2017. }
  2018. df := st.wantData()
  2019. if string(df.Data()) != reply {
  2020. t.Errorf("Client read %q; want %q", df.Data(), reply)
  2021. }
  2022. if !df.StreamEnded() {
  2023. t.Errorf("expect data stream end")
  2024. }
  2025. })
  2026. }
  2027. func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) {
  2028. errc := make(chan error, 1)
  2029. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2030. p := []byte("some data.\n")
  2031. for {
  2032. _, err := w.Write(p)
  2033. if err != nil {
  2034. errc <- err
  2035. return nil
  2036. }
  2037. }
  2038. }, func(st *serverTester) {
  2039. st.writeHeaders(HeadersFrameParam{
  2040. StreamID: 1,
  2041. BlockFragment: st.encodeHeader(),
  2042. EndStream: false,
  2043. EndHeaders: true,
  2044. })
  2045. hf := st.wantHeaders()
  2046. if hf.StreamEnded() {
  2047. t.Fatal("unexpected END_STREAM flag")
  2048. }
  2049. if !hf.HeadersEnded() {
  2050. t.Fatal("want END_HEADERS flag")
  2051. }
  2052. // Close the connection and wait for the handler to (hopefully) notice.
  2053. st.cc.Close()
  2054. select {
  2055. case <-errc:
  2056. case <-time.After(5 * time.Second):
  2057. t.Error("timeout")
  2058. }
  2059. })
  2060. }
  2061. func TestServer_Rejects_Too_Many_Streams(t *testing.T) {
  2062. const testPath = "/some/path"
  2063. inHandler := make(chan uint32)
  2064. leaveHandler := make(chan bool)
  2065. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2066. id := w.(*responseWriter).rws.stream.id
  2067. inHandler <- id
  2068. if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath {
  2069. t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath)
  2070. }
  2071. <-leaveHandler
  2072. })
  2073. defer st.Close()
  2074. st.greet()
  2075. nextStreamID := uint32(1)
  2076. streamID := func() uint32 {
  2077. defer func() { nextStreamID += 2 }()
  2078. return nextStreamID
  2079. }
  2080. sendReq := func(id uint32, headers ...string) {
  2081. st.writeHeaders(HeadersFrameParam{
  2082. StreamID: id,
  2083. BlockFragment: st.encodeHeader(headers...),
  2084. EndStream: true,
  2085. EndHeaders: true,
  2086. })
  2087. }
  2088. for i := 0; i < defaultMaxStreams; i++ {
  2089. sendReq(streamID())
  2090. <-inHandler
  2091. }
  2092. defer func() {
  2093. for i := 0; i < defaultMaxStreams; i++ {
  2094. leaveHandler <- true
  2095. }
  2096. }()
  2097. // And this one should cross the limit:
  2098. // (It's also sent as a CONTINUATION, to verify we still track the decoder context,
  2099. // even if we're rejecting it)
  2100. rejectID := streamID()
  2101. headerBlock := st.encodeHeader(":path", testPath)
  2102. frag1, frag2 := headerBlock[:3], headerBlock[3:]
  2103. st.writeHeaders(HeadersFrameParam{
  2104. StreamID: rejectID,
  2105. BlockFragment: frag1,
  2106. EndStream: true,
  2107. EndHeaders: false, // CONTINUATION coming
  2108. })
  2109. if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil {
  2110. t.Fatal(err)
  2111. }
  2112. st.wantRSTStream(rejectID, ErrCodeProtocol)
  2113. // But let a handler finish:
  2114. leaveHandler <- true
  2115. st.wantHeaders()
  2116. // And now another stream should be able to start:
  2117. goodID := streamID()
  2118. sendReq(goodID, ":path", testPath)
  2119. select {
  2120. case got := <-inHandler:
  2121. if got != goodID {
  2122. t.Errorf("Got stream %d; want %d", got, goodID)
  2123. }
  2124. case <-time.After(3 * time.Second):
  2125. t.Error("timeout waiting for handler")
  2126. }
  2127. }
  2128. // So many response headers that the server needs to use CONTINUATION frames:
  2129. func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) {
  2130. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2131. h := w.Header()
  2132. for i := 0; i < 5000; i++ {
  2133. h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i))
  2134. }
  2135. return nil
  2136. }, func(st *serverTester) {
  2137. getSlash(st)
  2138. hf := st.wantHeaders()
  2139. if hf.HeadersEnded() {
  2140. t.Fatal("got unwanted END_HEADERS flag")
  2141. }
  2142. n := 0
  2143. for {
  2144. n++
  2145. cf := st.wantContinuation()
  2146. if cf.HeadersEnded() {
  2147. break
  2148. }
  2149. }
  2150. if n < 5 {
  2151. t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n)
  2152. }
  2153. })
  2154. }
  2155. // This previously crashed (reported by Mathieu Lonjaret as observed
  2156. // while using Camlistore) because we got a DATA frame from the client
  2157. // after the handler exited and our logic at the time was wrong,
  2158. // keeping a stream in the map in stateClosed, which tickled an
  2159. // invariant check later when we tried to remove that stream (via
  2160. // defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop
  2161. // ended.
  2162. func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) {
  2163. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2164. // nothing
  2165. return nil
  2166. }, func(st *serverTester) {
  2167. st.writeHeaders(HeadersFrameParam{
  2168. StreamID: 1,
  2169. BlockFragment: st.encodeHeader(),
  2170. EndStream: false, // DATA is coming
  2171. EndHeaders: true,
  2172. })
  2173. hf := st.wantHeaders()
  2174. if !hf.HeadersEnded() || !hf.StreamEnded() {
  2175. t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf)
  2176. }
  2177. // Sent when the a Handler closes while a client has
  2178. // indicated it's still sending DATA:
  2179. st.wantRSTStream(1, ErrCodeNo)
  2180. // Now the handler has ended, so it's ended its
  2181. // stream, but the client hasn't closed its side
  2182. // (stateClosedLocal). So send more data and verify
  2183. // it doesn't crash with an internal invariant panic, like
  2184. // it did before.
  2185. st.writeData(1, true, []byte("foo"))
  2186. // Get our flow control bytes back, since the handler didn't get them.
  2187. st.wantWindowUpdate(0, uint32(len("foo")))
  2188. // Sent after a peer sends data anyway (admittedly the
  2189. // previous RST_STREAM might've still been in-flight),
  2190. // but they'll get the more friendly 'cancel' code
  2191. // first.
  2192. st.wantRSTStream(1, ErrCodeStreamClosed)
  2193. // Set up a bunch of machinery to record the panic we saw
  2194. // previously.
  2195. var (
  2196. panMu sync.Mutex
  2197. panicVal interface{}
  2198. )
  2199. testHookOnPanicMu.Lock()
  2200. testHookOnPanic = func(sc *serverConn, pv interface{}) bool {
  2201. panMu.Lock()
  2202. panicVal = pv
  2203. panMu.Unlock()
  2204. return true
  2205. }
  2206. testHookOnPanicMu.Unlock()
  2207. // Now force the serve loop to end, via closing the connection.
  2208. st.cc.Close()
  2209. select {
  2210. case <-st.sc.doneServing:
  2211. // Loop has exited.
  2212. panMu.Lock()
  2213. got := panicVal
  2214. panMu.Unlock()
  2215. if got != nil {
  2216. t.Errorf("Got panic: %v", got)
  2217. }
  2218. case <-time.After(5 * time.Second):
  2219. t.Error("timeout")
  2220. }
  2221. })
  2222. }
  2223. func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) }
  2224. func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) }
  2225. func testRejectTLS(t *testing.T, max uint16) {
  2226. st := newServerTester(t, nil, func(c *tls.Config) {
  2227. c.MaxVersion = max
  2228. })
  2229. defer st.Close()
  2230. gf := st.wantGoAway()
  2231. if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2232. t.Errorf("Got error code %v; want %v", got, want)
  2233. }
  2234. }
  2235. func TestServer_Rejects_TLSBadCipher(t *testing.T) {
  2236. st := newServerTester(t, nil, func(c *tls.Config) {
  2237. // All TLS 1.3 ciphers are good. Test with TLS 1.2.
  2238. c.MaxVersion = tls.VersionTLS12
  2239. // Only list bad ones:
  2240. c.CipherSuites = []uint16{
  2241. tls.TLS_RSA_WITH_RC4_128_SHA,
  2242. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  2243. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  2244. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  2245. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  2246. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  2247. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  2248. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  2249. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  2250. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  2251. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  2252. cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
  2253. }
  2254. })
  2255. defer st.Close()
  2256. gf := st.wantGoAway()
  2257. if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2258. t.Errorf("Got error code %v; want %v", got, want)
  2259. }
  2260. }
  2261. func TestServer_Advertises_Common_Cipher(t *testing.T) {
  2262. const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  2263. st := newServerTester(t, nil, func(c *tls.Config) {
  2264. // Have the client only support the one required by the spec.
  2265. c.CipherSuites = []uint16{requiredSuite}
  2266. }, func(ts *httptest.Server) {
  2267. var srv *http.Server = ts.Config
  2268. // Have the server configured with no specific cipher suites.
  2269. // This tests that Go's defaults include the required one.
  2270. srv.TLSConfig = nil
  2271. })
  2272. defer st.Close()
  2273. st.greet()
  2274. }
  2275. func (st *serverTester) onHeaderField(f hpack.HeaderField) {
  2276. if f.Name == "date" {
  2277. return
  2278. }
  2279. st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value})
  2280. }
  2281. func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) {
  2282. st.decodedHeaders = nil
  2283. if _, err := st.hpackDec.Write(headerBlock); err != nil {
  2284. st.t.Fatalf("hpack decoding error: %v", err)
  2285. }
  2286. if err := st.hpackDec.Close(); err != nil {
  2287. st.t.Fatalf("hpack decoding error: %v", err)
  2288. }
  2289. return st.decodedHeaders
  2290. }
  2291. // testServerResponse sets up an idle HTTP/2 connection. The client function should
  2292. // write a single request that must be handled by the handler. This waits up to 5s
  2293. // for client to return, then up to an additional 2s for the handler to return.
  2294. func testServerResponse(t testing.TB,
  2295. handler func(http.ResponseWriter, *http.Request) error,
  2296. client func(*serverTester),
  2297. ) {
  2298. errc := make(chan error, 1)
  2299. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2300. if r.Body == nil {
  2301. t.Fatal("nil Body")
  2302. }
  2303. errc <- handler(w, r)
  2304. })
  2305. defer st.Close()
  2306. donec := make(chan bool)
  2307. go func() {
  2308. defer close(donec)
  2309. st.greet()
  2310. client(st)
  2311. }()
  2312. select {
  2313. case <-donec:
  2314. case <-time.After(5 * time.Second):
  2315. t.Fatal("timeout in client")
  2316. }
  2317. select {
  2318. case err := <-errc:
  2319. if err != nil {
  2320. t.Fatalf("Error in handler: %v", err)
  2321. }
  2322. case <-time.After(2 * time.Second):
  2323. t.Fatal("timeout in handler")
  2324. }
  2325. }
  2326. // readBodyHandler returns an http Handler func that reads len(want)
  2327. // bytes from r.Body and fails t if the contents read were not
  2328. // the value of want.
  2329. func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) {
  2330. return func(w http.ResponseWriter, r *http.Request) {
  2331. buf := make([]byte, len(want))
  2332. _, err := io.ReadFull(r.Body, buf)
  2333. if err != nil {
  2334. t.Error(err)
  2335. return
  2336. }
  2337. if string(buf) != want {
  2338. t.Errorf("read %q; want %q", buf, want)
  2339. }
  2340. }
  2341. }
  2342. // TestServerWithCurl currently fails, hence the LenientCipherSuites test. See:
  2343. // https://github.com/tatsuhiro-t/nghttp2/issues/140 &
  2344. // http://sourceforge.net/p/curl/bugs/1472/
  2345. func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) }
  2346. func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) }
  2347. func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) {
  2348. if runtime.GOOS != "linux" {
  2349. t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2350. }
  2351. if testing.Short() {
  2352. t.Skip("skipping curl test in short mode")
  2353. }
  2354. requireCurl(t)
  2355. var gotConn int32
  2356. testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) }
  2357. const msg = "Hello from curl!\n"
  2358. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2359. w.Header().Set("Foo", "Bar")
  2360. w.Header().Set("Client-Proto", r.Proto)
  2361. io.WriteString(w, msg)
  2362. }))
  2363. ConfigureServer(ts.Config, &Server{
  2364. PermitProhibitedCipherSuites: permitProhibitedCipherSuites,
  2365. })
  2366. ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
  2367. ts.StartTLS()
  2368. defer ts.Close()
  2369. t.Logf("Running test server for curl to hit at: %s", ts.URL)
  2370. container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL)
  2371. defer kill(container)
  2372. resc := make(chan interface{}, 1)
  2373. go func() {
  2374. res, err := dockerLogs(container)
  2375. if err != nil {
  2376. resc <- err
  2377. } else {
  2378. resc <- res
  2379. }
  2380. }()
  2381. select {
  2382. case res := <-resc:
  2383. if err, ok := res.(error); ok {
  2384. t.Fatal(err)
  2385. }
  2386. body := string(res.([]byte))
  2387. // Search for both "key: value" and "key:value", since curl changed their format
  2388. // Our Dockerfile contains the latest version (no space), but just in case people
  2389. // didn't rebuild, check both.
  2390. if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") {
  2391. t.Errorf("didn't see foo: Bar header")
  2392. t.Logf("Got: %s", body)
  2393. }
  2394. if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") {
  2395. t.Errorf("didn't see client-proto: HTTP/2 header")
  2396. t.Logf("Got: %s", res)
  2397. }
  2398. if !strings.Contains(string(res.([]byte)), msg) {
  2399. t.Errorf("didn't see %q content", msg)
  2400. t.Logf("Got: %s", res)
  2401. }
  2402. case <-time.After(3 * time.Second):
  2403. t.Errorf("timeout waiting for curl")
  2404. }
  2405. if atomic.LoadInt32(&gotConn) == 0 {
  2406. t.Error("never saw an http2 connection")
  2407. }
  2408. }
  2409. var doh2load = flag.Bool("h2load", false, "Run h2load test")
  2410. func TestServerWithH2Load(t *testing.T) {
  2411. if !*doh2load {
  2412. t.Skip("Skipping without --h2load flag.")
  2413. }
  2414. if runtime.GOOS != "linux" {
  2415. t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2416. }
  2417. requireH2load(t)
  2418. msg := strings.Repeat("Hello, h2load!\n", 5000)
  2419. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2420. io.WriteString(w, msg)
  2421. w.(http.Flusher).Flush()
  2422. io.WriteString(w, msg)
  2423. }))
  2424. ts.StartTLS()
  2425. defer ts.Close()
  2426. cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl",
  2427. "-n100000", "-c100", "-m100", ts.URL)
  2428. cmd.Stdout = os.Stdout
  2429. cmd.Stderr = os.Stderr
  2430. if err := cmd.Run(); err != nil {
  2431. t.Fatal(err)
  2432. }
  2433. }
  2434. // Issue 12843
  2435. func TestServerDoS_MaxHeaderListSize(t *testing.T) {
  2436. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  2437. defer st.Close()
  2438. // shake hands
  2439. frameSize := defaultMaxReadFrameSize
  2440. var advHeaderListSize *uint32
  2441. st.greetAndCheckSettings(func(s Setting) error {
  2442. switch s.ID {
  2443. case SettingMaxFrameSize:
  2444. if s.Val < minMaxFrameSize {
  2445. frameSize = minMaxFrameSize
  2446. } else if s.Val > maxFrameSize {
  2447. frameSize = maxFrameSize
  2448. } else {
  2449. frameSize = int(s.Val)
  2450. }
  2451. case SettingMaxHeaderListSize:
  2452. advHeaderListSize = &s.Val
  2453. }
  2454. return nil
  2455. })
  2456. if advHeaderListSize == nil {
  2457. t.Errorf("server didn't advertise a max header list size")
  2458. } else if *advHeaderListSize == 0 {
  2459. t.Errorf("server advertised a max header list size of 0")
  2460. }
  2461. st.encodeHeaderField(":method", "GET")
  2462. st.encodeHeaderField(":path", "/")
  2463. st.encodeHeaderField(":scheme", "https")
  2464. cookie := strings.Repeat("*", 4058)
  2465. st.encodeHeaderField("cookie", cookie)
  2466. st.writeHeaders(HeadersFrameParam{
  2467. StreamID: 1,
  2468. BlockFragment: st.headerBuf.Bytes(),
  2469. EndStream: true,
  2470. EndHeaders: false,
  2471. })
  2472. // Capture the short encoding of a duplicate ~4K cookie, now
  2473. // that we've already sent it once.
  2474. st.headerBuf.Reset()
  2475. st.encodeHeaderField("cookie", cookie)
  2476. // Now send 1MB of it.
  2477. const size = 1 << 20
  2478. b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len())
  2479. for len(b) > 0 {
  2480. chunk := b
  2481. if len(chunk) > frameSize {
  2482. chunk = chunk[:frameSize]
  2483. }
  2484. b = b[len(chunk):]
  2485. st.fr.WriteContinuation(1, len(b) == 0, chunk)
  2486. }
  2487. h := st.wantHeaders()
  2488. if !h.HeadersEnded() {
  2489. t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2490. }
  2491. headers := st.decodeHeader(h.HeaderBlockFragment())
  2492. want := [][2]string{
  2493. {":status", "431"},
  2494. {"content-type", "text/html; charset=utf-8"},
  2495. {"content-length", "63"},
  2496. }
  2497. if !reflect.DeepEqual(headers, want) {
  2498. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2499. }
  2500. }
  2501. func TestServer_Response_Stream_With_Missing_Trailer(t *testing.T) {
  2502. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2503. w.Header().Set("Trailer", "test-trailer")
  2504. return nil
  2505. }, func(st *serverTester) {
  2506. getSlash(st)
  2507. hf := st.wantHeaders()
  2508. if !hf.HeadersEnded() {
  2509. t.Fatal("want END_HEADERS flag")
  2510. }
  2511. df := st.wantData()
  2512. if len(df.data) != 0 {
  2513. t.Fatal("did not want data")
  2514. }
  2515. if !df.StreamEnded() {
  2516. t.Fatal("want END_STREAM flag")
  2517. }
  2518. })
  2519. }
  2520. func TestCompressionErrorOnWrite(t *testing.T) {
  2521. const maxStrLen = 8 << 10
  2522. var serverConfig *http.Server
  2523. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2524. // No response body.
  2525. }, func(ts *httptest.Server) {
  2526. serverConfig = ts.Config
  2527. serverConfig.MaxHeaderBytes = maxStrLen
  2528. })
  2529. st.addLogFilter("connection error: COMPRESSION_ERROR")
  2530. defer st.Close()
  2531. st.greet()
  2532. maxAllowed := st.sc.framer.maxHeaderStringLen()
  2533. // Crank this up, now that we have a conn connected with the
  2534. // hpack.Decoder's max string length set has been initialized
  2535. // from the earlier low ~8K value. We want this higher so don't
  2536. // hit the max header list size. We only want to test hitting
  2537. // the max string size.
  2538. serverConfig.MaxHeaderBytes = 1 << 20
  2539. // First a request with a header that's exactly the max allowed size
  2540. // for the hpack compression. It's still too long for the header list
  2541. // size, so we'll get the 431 error, but that keeps the compression
  2542. // context still valid.
  2543. hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed))
  2544. st.writeHeaders(HeadersFrameParam{
  2545. StreamID: 1,
  2546. BlockFragment: hbf,
  2547. EndStream: true,
  2548. EndHeaders: true,
  2549. })
  2550. h := st.wantHeaders()
  2551. if !h.HeadersEnded() {
  2552. t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2553. }
  2554. headers := st.decodeHeader(h.HeaderBlockFragment())
  2555. want := [][2]string{
  2556. {":status", "431"},
  2557. {"content-type", "text/html; charset=utf-8"},
  2558. {"content-length", "63"},
  2559. }
  2560. if !reflect.DeepEqual(headers, want) {
  2561. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2562. }
  2563. df := st.wantData()
  2564. if !strings.Contains(string(df.Data()), "HTTP Error 431") {
  2565. t.Errorf("Unexpected data body: %q", df.Data())
  2566. }
  2567. if !df.StreamEnded() {
  2568. t.Fatalf("expect data stream end")
  2569. }
  2570. // And now send one that's just one byte too big.
  2571. hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1))
  2572. st.writeHeaders(HeadersFrameParam{
  2573. StreamID: 3,
  2574. BlockFragment: hbf,
  2575. EndStream: true,
  2576. EndHeaders: true,
  2577. })
  2578. ga := st.wantGoAway()
  2579. if ga.ErrCode != ErrCodeCompression {
  2580. t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2581. }
  2582. }
  2583. func TestCompressionErrorOnClose(t *testing.T) {
  2584. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2585. // No response body.
  2586. })
  2587. st.addLogFilter("connection error: COMPRESSION_ERROR")
  2588. defer st.Close()
  2589. st.greet()
  2590. hbf := st.encodeHeader("foo", "bar")
  2591. hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails.
  2592. st.writeHeaders(HeadersFrameParam{
  2593. StreamID: 1,
  2594. BlockFragment: hbf,
  2595. EndStream: true,
  2596. EndHeaders: true,
  2597. })
  2598. ga := st.wantGoAway()
  2599. if ga.ErrCode != ErrCodeCompression {
  2600. t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2601. }
  2602. }
  2603. // test that a server handler can read trailers from a client
  2604. func TestServerReadsTrailers(t *testing.T) {
  2605. const testBody = "some test body"
  2606. writeReq := func(st *serverTester) {
  2607. st.writeHeaders(HeadersFrameParam{
  2608. StreamID: 1, // clients send odd numbers
  2609. BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"),
  2610. EndStream: false,
  2611. EndHeaders: true,
  2612. })
  2613. st.writeData(1, false, []byte(testBody))
  2614. st.writeHeaders(HeadersFrameParam{
  2615. StreamID: 1, // clients send odd numbers
  2616. BlockFragment: st.encodeHeaderRaw(
  2617. "foo", "foov",
  2618. "bar", "barv",
  2619. "baz", "bazv",
  2620. "surprise", "wasn't declared; shouldn't show up",
  2621. ),
  2622. EndStream: true,
  2623. EndHeaders: true,
  2624. })
  2625. }
  2626. checkReq := func(r *http.Request) {
  2627. wantTrailer := http.Header{
  2628. "Foo": nil,
  2629. "Bar": nil,
  2630. "Baz": nil,
  2631. }
  2632. if !reflect.DeepEqual(r.Trailer, wantTrailer) {
  2633. t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer)
  2634. }
  2635. slurp, err := ioutil.ReadAll(r.Body)
  2636. if string(slurp) != testBody {
  2637. t.Errorf("read body %q; want %q", slurp, testBody)
  2638. }
  2639. if err != nil {
  2640. t.Fatalf("Body slurp: %v", err)
  2641. }
  2642. wantTrailerAfter := http.Header{
  2643. "Foo": {"foov"},
  2644. "Bar": {"barv"},
  2645. "Baz": {"bazv"},
  2646. }
  2647. if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) {
  2648. t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter)
  2649. }
  2650. }
  2651. testServerRequest(t, writeReq, checkReq)
  2652. }
  2653. // test that a server handler can send trailers
  2654. func TestServerWritesTrailers_WithFlush(t *testing.T) { testServerWritesTrailers(t, true) }
  2655. func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) }
  2656. func testServerWritesTrailers(t *testing.T, withFlush bool) {
  2657. // See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3
  2658. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2659. w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
  2660. w.Header().Add("Trailer", "Server-Trailer-C")
  2661. w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered
  2662. // Regular headers:
  2663. w.Header().Set("Foo", "Bar")
  2664. w.Header().Set("Content-Length", "5") // len("Hello")
  2665. io.WriteString(w, "Hello")
  2666. if withFlush {
  2667. w.(http.Flusher).Flush()
  2668. }
  2669. w.Header().Set("Server-Trailer-A", "valuea")
  2670. w.Header().Set("Server-Trailer-C", "valuec") // skipping B
  2671. // After a flush, random keys like Server-Surprise shouldn't show up:
  2672. w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!")
  2673. // But we do permit promoting keys to trailers after a
  2674. // flush if they start with the magic
  2675. // otherwise-invalid "Trailer:" prefix:
  2676. w.Header().Set("Trailer:Post-Header-Trailer", "hi1")
  2677. w.Header().Set("Trailer:post-header-trailer2", "hi2")
  2678. w.Header().Set("Trailer:Range", "invalid")
  2679. w.Header().Set("Trailer:Foo\x01Bogus", "invalid")
  2680. w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 7230 4.1.2")
  2681. w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 7230 4.1.2")
  2682. w.Header().Set("Trailer", "should not be included; Forbidden by RFC 7230 4.1.2")
  2683. return nil
  2684. }, func(st *serverTester) {
  2685. getSlash(st)
  2686. hf := st.wantHeaders()
  2687. if hf.StreamEnded() {
  2688. t.Fatal("response HEADERS had END_STREAM")
  2689. }
  2690. if !hf.HeadersEnded() {
  2691. t.Fatal("response HEADERS didn't have END_HEADERS")
  2692. }
  2693. goth := st.decodeHeader(hf.HeaderBlockFragment())
  2694. wanth := [][2]string{
  2695. {":status", "200"},
  2696. {"foo", "Bar"},
  2697. {"trailer", "Server-Trailer-A, Server-Trailer-B"},
  2698. {"trailer", "Server-Trailer-C"},
  2699. {"trailer", "Transfer-Encoding, Content-Length, Trailer"},
  2700. {"content-type", "text/plain; charset=utf-8"},
  2701. {"content-length", "5"},
  2702. }
  2703. if !reflect.DeepEqual(goth, wanth) {
  2704. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2705. }
  2706. df := st.wantData()
  2707. if string(df.Data()) != "Hello" {
  2708. t.Fatalf("Client read %q; want Hello", df.Data())
  2709. }
  2710. if df.StreamEnded() {
  2711. t.Fatalf("data frame had STREAM_ENDED")
  2712. }
  2713. tf := st.wantHeaders() // for the trailers
  2714. if !tf.StreamEnded() {
  2715. t.Fatalf("trailers HEADERS lacked END_STREAM")
  2716. }
  2717. if !tf.HeadersEnded() {
  2718. t.Fatalf("trailers HEADERS lacked END_HEADERS")
  2719. }
  2720. wanth = [][2]string{
  2721. {"post-header-trailer", "hi1"},
  2722. {"post-header-trailer2", "hi2"},
  2723. {"server-trailer-a", "valuea"},
  2724. {"server-trailer-c", "valuec"},
  2725. }
  2726. goth = st.decodeHeader(tf.HeaderBlockFragment())
  2727. if !reflect.DeepEqual(goth, wanth) {
  2728. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2729. }
  2730. })
  2731. }
  2732. // validate transmitted header field names & values
  2733. // golang.org/issue/14048
  2734. func TestServerDoesntWriteInvalidHeaders(t *testing.T) {
  2735. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2736. w.Header().Add("OK1", "x")
  2737. w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key
  2738. w.Header().Add("Bad1\x00", "x") // null in key
  2739. w.Header().Add("Bad2", "x\x00y") // null in value
  2740. return nil
  2741. }, func(st *serverTester) {
  2742. getSlash(st)
  2743. hf := st.wantHeaders()
  2744. if !hf.StreamEnded() {
  2745. t.Error("response HEADERS lacked END_STREAM")
  2746. }
  2747. if !hf.HeadersEnded() {
  2748. t.Fatal("response HEADERS didn't have END_HEADERS")
  2749. }
  2750. goth := st.decodeHeader(hf.HeaderBlockFragment())
  2751. wanth := [][2]string{
  2752. {":status", "200"},
  2753. {"ok1", "x"},
  2754. {"content-length", "0"},
  2755. }
  2756. if !reflect.DeepEqual(goth, wanth) {
  2757. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2758. }
  2759. })
  2760. }
  2761. func BenchmarkServerGets(b *testing.B) {
  2762. defer disableGoroutineTracking()()
  2763. b.ReportAllocs()
  2764. const msg = "Hello, world"
  2765. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2766. io.WriteString(w, msg)
  2767. })
  2768. defer st.Close()
  2769. st.greet()
  2770. // Give the server quota to reply. (plus it has the 64KB)
  2771. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  2772. b.Fatal(err)
  2773. }
  2774. for i := 0; i < b.N; i++ {
  2775. id := 1 + uint32(i)*2
  2776. st.writeHeaders(HeadersFrameParam{
  2777. StreamID: id,
  2778. BlockFragment: st.encodeHeader(),
  2779. EndStream: true,
  2780. EndHeaders: true,
  2781. })
  2782. st.wantHeaders()
  2783. df := st.wantData()
  2784. if !df.StreamEnded() {
  2785. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  2786. }
  2787. }
  2788. }
  2789. func BenchmarkServerPosts(b *testing.B) {
  2790. defer disableGoroutineTracking()()
  2791. b.ReportAllocs()
  2792. const msg = "Hello, world"
  2793. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2794. // Consume the (empty) body from th peer before replying, otherwise
  2795. // the server will sometimes (depending on scheduling) send the peer a
  2796. // a RST_STREAM with the CANCEL error code.
  2797. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  2798. b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  2799. }
  2800. io.WriteString(w, msg)
  2801. })
  2802. defer st.Close()
  2803. st.greet()
  2804. // Give the server quota to reply. (plus it has the 64KB)
  2805. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  2806. b.Fatal(err)
  2807. }
  2808. for i := 0; i < b.N; i++ {
  2809. id := 1 + uint32(i)*2
  2810. st.writeHeaders(HeadersFrameParam{
  2811. StreamID: id,
  2812. BlockFragment: st.encodeHeader(":method", "POST"),
  2813. EndStream: false,
  2814. EndHeaders: true,
  2815. })
  2816. st.writeData(id, true, nil)
  2817. st.wantHeaders()
  2818. df := st.wantData()
  2819. if !df.StreamEnded() {
  2820. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  2821. }
  2822. }
  2823. }
  2824. // Send a stream of messages from server to client in separate data frames.
  2825. // Brings up performance issues seen in long streams.
  2826. // Created to show problem in go issue #18502
  2827. func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) {
  2828. benchmarkServerToClientStream(b)
  2829. }
  2830. // Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8
  2831. // Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer.
  2832. func BenchmarkServerToClientStreamReuseFrames(b *testing.B) {
  2833. benchmarkServerToClientStream(b, optFramerReuseFrames)
  2834. }
  2835. func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) {
  2836. defer disableGoroutineTracking()()
  2837. b.ReportAllocs()
  2838. const msgLen = 1
  2839. // default window size
  2840. const windowSize = 1<<16 - 1
  2841. // next message to send from the server and for the client to expect
  2842. nextMsg := func(i int) []byte {
  2843. msg := make([]byte, msgLen)
  2844. msg[0] = byte(i)
  2845. if len(msg) != msgLen {
  2846. panic("invalid test setup msg length")
  2847. }
  2848. return msg
  2849. }
  2850. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2851. // Consume the (empty) body from th peer before replying, otherwise
  2852. // the server will sometimes (depending on scheduling) send the peer a
  2853. // a RST_STREAM with the CANCEL error code.
  2854. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  2855. b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  2856. }
  2857. for i := 0; i < b.N; i += 1 {
  2858. w.Write(nextMsg(i))
  2859. w.(http.Flusher).Flush()
  2860. }
  2861. }, newServerOpts...)
  2862. defer st.Close()
  2863. st.greet()
  2864. const id = uint32(1)
  2865. st.writeHeaders(HeadersFrameParam{
  2866. StreamID: id,
  2867. BlockFragment: st.encodeHeader(":method", "POST"),
  2868. EndStream: false,
  2869. EndHeaders: true,
  2870. })
  2871. st.writeData(id, true, nil)
  2872. st.wantHeaders()
  2873. var pendingWindowUpdate = uint32(0)
  2874. for i := 0; i < b.N; i += 1 {
  2875. expected := nextMsg(i)
  2876. df := st.wantData()
  2877. if bytes.Compare(expected, df.data) != 0 {
  2878. b.Fatalf("Bad message received; want %v; got %v", expected, df.data)
  2879. }
  2880. // try to send infrequent but large window updates so they don't overwhelm the test
  2881. pendingWindowUpdate += uint32(len(df.data))
  2882. if pendingWindowUpdate >= windowSize/2 {
  2883. if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil {
  2884. b.Fatal(err)
  2885. }
  2886. if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil {
  2887. b.Fatal(err)
  2888. }
  2889. pendingWindowUpdate = 0
  2890. }
  2891. }
  2892. df := st.wantData()
  2893. if !df.StreamEnded() {
  2894. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  2895. }
  2896. }
  2897. // go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53
  2898. // Verify we don't hang.
  2899. func TestIssue53(t *testing.T) {
  2900. const data = "PRI * HTTP/2.0\r\n\r\nSM" +
  2901. "\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad"
  2902. s := &http.Server{
  2903. ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags),
  2904. Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  2905. w.Write([]byte("hello"))
  2906. }),
  2907. }
  2908. s2 := &Server{
  2909. MaxReadFrameSize: 1 << 16,
  2910. PermitProhibitedCipherSuites: true,
  2911. }
  2912. c := &issue53Conn{[]byte(data), false, false}
  2913. s2.ServeConn(c, &ServeConnOpts{BaseConfig: s})
  2914. if !c.closed {
  2915. t.Fatal("connection is not closed")
  2916. }
  2917. }
  2918. type issue53Conn struct {
  2919. data []byte
  2920. closed bool
  2921. written bool
  2922. }
  2923. func (c *issue53Conn) Read(b []byte) (n int, err error) {
  2924. if len(c.data) == 0 {
  2925. return 0, io.EOF
  2926. }
  2927. n = copy(b, c.data)
  2928. c.data = c.data[n:]
  2929. return
  2930. }
  2931. func (c *issue53Conn) Write(b []byte) (n int, err error) {
  2932. c.written = true
  2933. return len(b), nil
  2934. }
  2935. func (c *issue53Conn) Close() error {
  2936. c.closed = true
  2937. return nil
  2938. }
  2939. func (c *issue53Conn) LocalAddr() net.Addr {
  2940. return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  2941. }
  2942. func (c *issue53Conn) RemoteAddr() net.Addr {
  2943. return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  2944. }
  2945. func (c *issue53Conn) SetDeadline(t time.Time) error { return nil }
  2946. func (c *issue53Conn) SetReadDeadline(t time.Time) error { return nil }
  2947. func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil }
  2948. // golang.org/issue/33839
  2949. func TestServeConnOptsNilReceiverBehavior(t *testing.T) {
  2950. defer func() {
  2951. if r := recover(); r != nil {
  2952. t.Errorf("got a panic that should not happen: %v", r)
  2953. }
  2954. }()
  2955. var o *ServeConnOpts
  2956. if o.context() == nil {
  2957. t.Error("o.context should not return nil")
  2958. }
  2959. if o.baseConfig() == nil {
  2960. t.Error("o.baseConfig should not return nil")
  2961. }
  2962. if o.handler() == nil {
  2963. t.Error("o.handler should not return nil")
  2964. }
  2965. }
  2966. // golang.org/issue/12895
  2967. func TestConfigureServer(t *testing.T) {
  2968. tests := []struct {
  2969. name string
  2970. tlsConfig *tls.Config
  2971. wantErr string
  2972. }{
  2973. {
  2974. name: "empty server",
  2975. },
  2976. {
  2977. name: "just the required cipher suite",
  2978. tlsConfig: &tls.Config{
  2979. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  2980. },
  2981. },
  2982. {
  2983. name: "just the alternative required cipher suite",
  2984. tlsConfig: &tls.Config{
  2985. CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  2986. },
  2987. },
  2988. {
  2989. name: "missing required cipher suite",
  2990. tlsConfig: &tls.Config{
  2991. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
  2992. },
  2993. wantErr: "is missing an HTTP/2-required",
  2994. },
  2995. {
  2996. name: "required after bad",
  2997. tlsConfig: &tls.Config{
  2998. CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  2999. },
  3000. wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after",
  3001. },
  3002. {
  3003. name: "bad after required",
  3004. tlsConfig: &tls.Config{
  3005. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA},
  3006. },
  3007. },
  3008. }
  3009. for _, tt := range tests {
  3010. srv := &http.Server{TLSConfig: tt.tlsConfig}
  3011. err := ConfigureServer(srv, nil)
  3012. if (err != nil) != (tt.wantErr != "") {
  3013. if tt.wantErr != "" {
  3014. t.Errorf("%s: success, but want error", tt.name)
  3015. } else {
  3016. t.Errorf("%s: unexpected error: %v", tt.name, err)
  3017. }
  3018. }
  3019. if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) {
  3020. t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr)
  3021. }
  3022. if err == nil && !srv.TLSConfig.PreferServerCipherSuites {
  3023. t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name)
  3024. }
  3025. }
  3026. }
  3027. func TestServerRejectHeadWithBody(t *testing.T) {
  3028. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3029. // No response body.
  3030. })
  3031. defer st.Close()
  3032. st.greet()
  3033. st.writeHeaders(HeadersFrameParam{
  3034. StreamID: 1, // clients send odd numbers
  3035. BlockFragment: st.encodeHeader(":method", "HEAD"),
  3036. EndStream: false, // what we're testing, a bogus HEAD request with body
  3037. EndHeaders: true,
  3038. })
  3039. st.wantRSTStream(1, ErrCodeProtocol)
  3040. }
  3041. func TestServerNoAutoContentLengthOnHead(t *testing.T) {
  3042. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3043. // No response body. (or smaller than one frame)
  3044. })
  3045. defer st.Close()
  3046. st.greet()
  3047. st.writeHeaders(HeadersFrameParam{
  3048. StreamID: 1, // clients send odd numbers
  3049. BlockFragment: st.encodeHeader(":method", "HEAD"),
  3050. EndStream: true,
  3051. EndHeaders: true,
  3052. })
  3053. h := st.wantHeaders()
  3054. headers := st.decodeHeader(h.HeaderBlockFragment())
  3055. want := [][2]string{
  3056. {":status", "200"},
  3057. }
  3058. if !reflect.DeepEqual(headers, want) {
  3059. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3060. }
  3061. }
  3062. // golang.org/issue/13495
  3063. func TestServerNoDuplicateContentType(t *testing.T) {
  3064. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3065. w.Header()["Content-Type"] = []string{""}
  3066. fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
  3067. })
  3068. defer st.Close()
  3069. st.greet()
  3070. st.writeHeaders(HeadersFrameParam{
  3071. StreamID: 1,
  3072. BlockFragment: st.encodeHeader(),
  3073. EndStream: true,
  3074. EndHeaders: true,
  3075. })
  3076. h := st.wantHeaders()
  3077. headers := st.decodeHeader(h.HeaderBlockFragment())
  3078. want := [][2]string{
  3079. {":status", "200"},
  3080. {"content-type", ""},
  3081. {"content-length", "41"},
  3082. }
  3083. if !reflect.DeepEqual(headers, want) {
  3084. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3085. }
  3086. }
  3087. func disableGoroutineTracking() (restore func()) {
  3088. old := DebugGoroutines
  3089. DebugGoroutines = false
  3090. return func() { DebugGoroutines = old }
  3091. }
  3092. func BenchmarkServer_GetRequest(b *testing.B) {
  3093. defer disableGoroutineTracking()()
  3094. b.ReportAllocs()
  3095. const msg = "Hello, world."
  3096. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3097. n, err := io.Copy(ioutil.Discard, r.Body)
  3098. if err != nil || n > 0 {
  3099. b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3100. }
  3101. io.WriteString(w, msg)
  3102. })
  3103. defer st.Close()
  3104. st.greet()
  3105. // Give the server quota to reply. (plus it has the 64KB)
  3106. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3107. b.Fatal(err)
  3108. }
  3109. hbf := st.encodeHeader(":method", "GET")
  3110. for i := 0; i < b.N; i++ {
  3111. streamID := uint32(1 + 2*i)
  3112. st.writeHeaders(HeadersFrameParam{
  3113. StreamID: streamID,
  3114. BlockFragment: hbf,
  3115. EndStream: true,
  3116. EndHeaders: true,
  3117. })
  3118. st.wantHeaders()
  3119. st.wantData()
  3120. }
  3121. }
  3122. func BenchmarkServer_PostRequest(b *testing.B) {
  3123. defer disableGoroutineTracking()()
  3124. b.ReportAllocs()
  3125. const msg = "Hello, world."
  3126. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3127. n, err := io.Copy(ioutil.Discard, r.Body)
  3128. if err != nil || n > 0 {
  3129. b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3130. }
  3131. io.WriteString(w, msg)
  3132. })
  3133. defer st.Close()
  3134. st.greet()
  3135. // Give the server quota to reply. (plus it has the 64KB)
  3136. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3137. b.Fatal(err)
  3138. }
  3139. hbf := st.encodeHeader(":method", "POST")
  3140. for i := 0; i < b.N; i++ {
  3141. streamID := uint32(1 + 2*i)
  3142. st.writeHeaders(HeadersFrameParam{
  3143. StreamID: streamID,
  3144. BlockFragment: hbf,
  3145. EndStream: false,
  3146. EndHeaders: true,
  3147. })
  3148. st.writeData(streamID, true, nil)
  3149. st.wantHeaders()
  3150. st.wantData()
  3151. }
  3152. }
  3153. type connStateConn struct {
  3154. net.Conn
  3155. cs tls.ConnectionState
  3156. }
  3157. func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs }
  3158. // golang.org/issue/12737 -- handle any net.Conn, not just
  3159. // *tls.Conn.
  3160. func TestServerHandleCustomConn(t *testing.T) {
  3161. var s Server
  3162. c1, c2 := net.Pipe()
  3163. clientDone := make(chan struct{})
  3164. handlerDone := make(chan struct{})
  3165. var req *http.Request
  3166. go func() {
  3167. defer close(clientDone)
  3168. defer c2.Close()
  3169. fr := NewFramer(c2, c2)
  3170. io.WriteString(c2, ClientPreface)
  3171. fr.WriteSettings()
  3172. fr.WriteSettingsAck()
  3173. f, err := fr.ReadFrame()
  3174. if err != nil {
  3175. t.Error(err)
  3176. return
  3177. }
  3178. if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() {
  3179. t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f))
  3180. return
  3181. }
  3182. f, err = fr.ReadFrame()
  3183. if err != nil {
  3184. t.Error(err)
  3185. return
  3186. }
  3187. if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() {
  3188. t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f))
  3189. return
  3190. }
  3191. var henc hpackEncoder
  3192. fr.WriteHeaders(HeadersFrameParam{
  3193. StreamID: 1,
  3194. BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"),
  3195. EndStream: true,
  3196. EndHeaders: true,
  3197. })
  3198. go io.Copy(ioutil.Discard, c2)
  3199. <-handlerDone
  3200. }()
  3201. const testString = "my custom ConnectionState"
  3202. fakeConnState := tls.ConnectionState{
  3203. ServerName: testString,
  3204. Version: tls.VersionTLS12,
  3205. CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  3206. }
  3207. go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{
  3208. BaseConfig: &http.Server{
  3209. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3210. defer close(handlerDone)
  3211. req = r
  3212. }),
  3213. }})
  3214. select {
  3215. case <-clientDone:
  3216. case <-time.After(5 * time.Second):
  3217. t.Fatal("timeout waiting for handler")
  3218. }
  3219. if req.TLS == nil {
  3220. t.Fatalf("Request.TLS is nil. Got: %#v", req)
  3221. }
  3222. if req.TLS.ServerName != testString {
  3223. t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString)
  3224. }
  3225. }
  3226. // golang.org/issue/14214
  3227. func TestServer_Rejects_ConnHeaders(t *testing.T) {
  3228. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3229. t.Error("should not get to Handler")
  3230. })
  3231. defer st.Close()
  3232. st.greet()
  3233. st.bodylessReq1("connection", "foo")
  3234. hf := st.wantHeaders()
  3235. goth := st.decodeHeader(hf.HeaderBlockFragment())
  3236. wanth := [][2]string{
  3237. {":status", "400"},
  3238. {"content-type", "text/plain; charset=utf-8"},
  3239. {"x-content-type-options", "nosniff"},
  3240. {"content-length", "51"},
  3241. }
  3242. if !reflect.DeepEqual(goth, wanth) {
  3243. t.Errorf("Got headers %v; want %v", goth, wanth)
  3244. }
  3245. }
  3246. type hpackEncoder struct {
  3247. enc *hpack.Encoder
  3248. buf bytes.Buffer
  3249. }
  3250. func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte {
  3251. if len(headers)%2 == 1 {
  3252. panic("odd number of kv args")
  3253. }
  3254. he.buf.Reset()
  3255. if he.enc == nil {
  3256. he.enc = hpack.NewEncoder(&he.buf)
  3257. }
  3258. for len(headers) > 0 {
  3259. k, v := headers[0], headers[1]
  3260. err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  3261. if err != nil {
  3262. t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
  3263. }
  3264. headers = headers[2:]
  3265. }
  3266. return he.buf.Bytes()
  3267. }
  3268. func TestCheckValidHTTP2Request(t *testing.T) {
  3269. tests := []struct {
  3270. h http.Header
  3271. want error
  3272. }{
  3273. {
  3274. h: http.Header{"Te": {"trailers"}},
  3275. want: nil,
  3276. },
  3277. {
  3278. h: http.Header{"Te": {"trailers", "bogus"}},
  3279. want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`),
  3280. },
  3281. {
  3282. h: http.Header{"Foo": {""}},
  3283. want: nil,
  3284. },
  3285. {
  3286. h: http.Header{"Connection": {""}},
  3287. want: errors.New(`request header "Connection" is not valid in HTTP/2`),
  3288. },
  3289. {
  3290. h: http.Header{"Proxy-Connection": {""}},
  3291. want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`),
  3292. },
  3293. {
  3294. h: http.Header{"Keep-Alive": {""}},
  3295. want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`),
  3296. },
  3297. {
  3298. h: http.Header{"Upgrade": {""}},
  3299. want: errors.New(`request header "Upgrade" is not valid in HTTP/2`),
  3300. },
  3301. }
  3302. for i, tt := range tests {
  3303. got := checkValidHTTP2RequestHeaders(tt.h)
  3304. if !equalError(got, tt.want) {
  3305. t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want)
  3306. }
  3307. }
  3308. }
  3309. // golang.org/issue/14030
  3310. func TestExpect100ContinueAfterHandlerWrites(t *testing.T) {
  3311. const msg = "Hello"
  3312. const msg2 = "World"
  3313. doRead := make(chan bool, 1)
  3314. defer close(doRead) // fallback cleanup
  3315. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3316. io.WriteString(w, msg)
  3317. w.(http.Flusher).Flush()
  3318. // Do a read, which might force a 100-continue status to be sent.
  3319. <-doRead
  3320. r.Body.Read(make([]byte, 10))
  3321. io.WriteString(w, msg2)
  3322. }, optOnlyServer)
  3323. defer st.Close()
  3324. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3325. defer tr.CloseIdleConnections()
  3326. req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20))
  3327. req.Header.Set("Expect", "100-continue")
  3328. res, err := tr.RoundTrip(req)
  3329. if err != nil {
  3330. t.Fatal(err)
  3331. }
  3332. defer res.Body.Close()
  3333. buf := make([]byte, len(msg))
  3334. if _, err := io.ReadFull(res.Body, buf); err != nil {
  3335. t.Fatal(err)
  3336. }
  3337. if string(buf) != msg {
  3338. t.Fatalf("msg = %q; want %q", buf, msg)
  3339. }
  3340. doRead <- true
  3341. if _, err := io.ReadFull(res.Body, buf); err != nil {
  3342. t.Fatal(err)
  3343. }
  3344. if string(buf) != msg2 {
  3345. t.Fatalf("second msg = %q; want %q", buf, msg2)
  3346. }
  3347. }
  3348. type funcReader func([]byte) (n int, err error)
  3349. func (f funcReader) Read(p []byte) (n int, err error) { return f(p) }
  3350. // golang.org/issue/16481 -- return flow control when streams close with unread data.
  3351. // (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport)
  3352. func TestUnreadFlowControlReturned_Server(t *testing.T) {
  3353. for _, tt := range []struct {
  3354. name string
  3355. reqFn func(r *http.Request)
  3356. }{
  3357. {
  3358. "body-open",
  3359. func(r *http.Request) {},
  3360. },
  3361. {
  3362. "body-closed",
  3363. func(r *http.Request) {
  3364. r.Body.Close()
  3365. },
  3366. },
  3367. {
  3368. "read-1-byte-and-close",
  3369. func(r *http.Request) {
  3370. b := make([]byte, 1)
  3371. r.Body.Read(b)
  3372. r.Body.Close()
  3373. },
  3374. },
  3375. } {
  3376. t.Run(tt.name, func(t *testing.T) {
  3377. unblock := make(chan bool, 1)
  3378. defer close(unblock)
  3379. timeOut := time.NewTimer(5 * time.Second)
  3380. defer timeOut.Stop()
  3381. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3382. // Don't read the 16KB request body. Wait until the client's
  3383. // done sending it and then return. This should cause the Server
  3384. // to then return those 16KB of flow control to the client.
  3385. tt.reqFn(r)
  3386. select {
  3387. case <-unblock:
  3388. case <-timeOut.C:
  3389. t.Fatal(tt.name, "timedout")
  3390. }
  3391. }, optOnlyServer)
  3392. defer st.Close()
  3393. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3394. defer tr.CloseIdleConnections()
  3395. // This previously hung on the 4th iteration.
  3396. iters := 100
  3397. if testing.Short() {
  3398. iters = 20
  3399. }
  3400. for i := 0; i < iters; i++ {
  3401. body := io.MultiReader(
  3402. io.LimitReader(neverEnding('A'), 16<<10),
  3403. funcReader(func([]byte) (n int, err error) {
  3404. unblock <- true
  3405. return 0, io.EOF
  3406. }),
  3407. )
  3408. req, _ := http.NewRequest("POST", st.ts.URL, body)
  3409. res, err := tr.RoundTrip(req)
  3410. if err != nil {
  3411. t.Fatal(tt.name, err)
  3412. }
  3413. res.Body.Close()
  3414. }
  3415. })
  3416. }
  3417. }
  3418. func TestServerIdleTimeout(t *testing.T) {
  3419. if testing.Short() {
  3420. t.Skip("skipping in short mode")
  3421. }
  3422. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3423. }, func(h2s *Server) {
  3424. h2s.IdleTimeout = 500 * time.Millisecond
  3425. })
  3426. defer st.Close()
  3427. st.greet()
  3428. ga := st.wantGoAway()
  3429. if ga.ErrCode != ErrCodeNo {
  3430. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3431. }
  3432. }
  3433. func TestServerIdleTimeout_AfterRequest(t *testing.T) {
  3434. if testing.Short() {
  3435. t.Skip("skipping in short mode")
  3436. }
  3437. const timeout = 250 * time.Millisecond
  3438. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3439. time.Sleep(timeout * 2)
  3440. }, func(h2s *Server) {
  3441. h2s.IdleTimeout = timeout
  3442. })
  3443. defer st.Close()
  3444. st.greet()
  3445. // Send a request which takes twice the timeout. Verifies the
  3446. // idle timeout doesn't fire while we're in a request:
  3447. st.bodylessReq1()
  3448. st.wantHeaders()
  3449. // But the idle timeout should be rearmed after the request
  3450. // is done:
  3451. ga := st.wantGoAway()
  3452. if ga.ErrCode != ErrCodeNo {
  3453. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3454. }
  3455. }
  3456. // grpc-go closes the Request.Body currently with a Read.
  3457. // Verify that it doesn't race.
  3458. // See https://github.com/grpc/grpc-go/pull/938
  3459. func TestRequestBodyReadCloseRace(t *testing.T) {
  3460. for i := 0; i < 100; i++ {
  3461. body := &requestBody{
  3462. pipe: &pipe{
  3463. b: new(bytes.Buffer),
  3464. },
  3465. }
  3466. body.pipe.CloseWithError(io.EOF)
  3467. done := make(chan bool, 1)
  3468. buf := make([]byte, 10)
  3469. go func() {
  3470. time.Sleep(1 * time.Millisecond)
  3471. body.Close()
  3472. done <- true
  3473. }()
  3474. body.Read(buf)
  3475. <-done
  3476. }
  3477. }
  3478. func TestIssue20704Race(t *testing.T) {
  3479. if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
  3480. t.Skip("skipping in short mode")
  3481. }
  3482. const (
  3483. itemSize = 1 << 10
  3484. itemCount = 100
  3485. )
  3486. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3487. for i := 0; i < itemCount; i++ {
  3488. _, err := w.Write(make([]byte, itemSize))
  3489. if err != nil {
  3490. return
  3491. }
  3492. }
  3493. }, optOnlyServer)
  3494. defer st.Close()
  3495. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3496. defer tr.CloseIdleConnections()
  3497. cl := &http.Client{Transport: tr}
  3498. for i := 0; i < 1000; i++ {
  3499. resp, err := cl.Get(st.ts.URL)
  3500. if err != nil {
  3501. t.Fatal(err)
  3502. }
  3503. // Force a RST stream to the server by closing without
  3504. // reading the body:
  3505. resp.Body.Close()
  3506. }
  3507. }
  3508. func TestServer_Rejects_TooSmall(t *testing.T) {
  3509. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3510. ioutil.ReadAll(r.Body)
  3511. return nil
  3512. }, func(st *serverTester) {
  3513. st.writeHeaders(HeadersFrameParam{
  3514. StreamID: 1, // clients send odd numbers
  3515. BlockFragment: st.encodeHeader(
  3516. ":method", "POST",
  3517. "content-length", "4",
  3518. ),
  3519. EndStream: false, // to say DATA frames are coming
  3520. EndHeaders: true,
  3521. })
  3522. st.writeData(1, true, []byte("12345"))
  3523. st.wantRSTStream(1, ErrCodeProtocol)
  3524. })
  3525. }
  3526. // Tests that a handler setting "Connection: close" results in a GOAWAY being sent,
  3527. // and the connection still completing.
  3528. func TestServerHandlerConnectionClose(t *testing.T) {
  3529. unblockHandler := make(chan bool, 1)
  3530. defer close(unblockHandler) // backup; in case of errors
  3531. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3532. w.Header().Set("Connection", "close")
  3533. w.Header().Set("Foo", "bar")
  3534. w.(http.Flusher).Flush()
  3535. <-unblockHandler
  3536. return nil
  3537. }, func(st *serverTester) {
  3538. st.writeHeaders(HeadersFrameParam{
  3539. StreamID: 1,
  3540. BlockFragment: st.encodeHeader(),
  3541. EndStream: true,
  3542. EndHeaders: true,
  3543. })
  3544. var sawGoAway bool
  3545. var sawRes bool
  3546. for {
  3547. f, err := st.readFrame()
  3548. if err == io.EOF {
  3549. break
  3550. }
  3551. if err != nil {
  3552. t.Fatal(err)
  3553. }
  3554. switch f := f.(type) {
  3555. case *GoAwayFrame:
  3556. sawGoAway = true
  3557. unblockHandler <- true
  3558. if f.LastStreamID != 1 || f.ErrCode != ErrCodeNo {
  3559. t.Errorf("unexpected GOAWAY frame: %v", summarizeFrame(f))
  3560. }
  3561. case *HeadersFrame:
  3562. goth := st.decodeHeader(f.HeaderBlockFragment())
  3563. wanth := [][2]string{
  3564. {":status", "200"},
  3565. {"foo", "bar"},
  3566. }
  3567. if !reflect.DeepEqual(goth, wanth) {
  3568. t.Errorf("got headers %v; want %v", goth, wanth)
  3569. }
  3570. sawRes = true
  3571. case *DataFrame:
  3572. if f.StreamID != 1 || !f.StreamEnded() || len(f.Data()) != 0 {
  3573. t.Errorf("unexpected DATA frame: %v", summarizeFrame(f))
  3574. }
  3575. default:
  3576. t.Logf("unexpected frame: %v", summarizeFrame(f))
  3577. }
  3578. }
  3579. if !sawGoAway {
  3580. t.Errorf("didn't see GOAWAY")
  3581. }
  3582. if !sawRes {
  3583. t.Errorf("didn't see response")
  3584. }
  3585. })
  3586. }
  3587. func TestServer_Headers_HalfCloseRemote(t *testing.T) {
  3588. var st *serverTester
  3589. writeData := make(chan bool)
  3590. writeHeaders := make(chan bool)
  3591. leaveHandler := make(chan bool)
  3592. st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3593. if st.stream(1) == nil {
  3594. t.Errorf("nil stream 1 in handler")
  3595. }
  3596. if got, want := st.streamState(1), stateOpen; got != want {
  3597. t.Errorf("in handler, state is %v; want %v", got, want)
  3598. }
  3599. writeData <- true
  3600. if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF {
  3601. t.Errorf("body read = %d, %v; want 0, EOF", n, err)
  3602. }
  3603. if got, want := st.streamState(1), stateHalfClosedRemote; got != want {
  3604. t.Errorf("in handler, state is %v; want %v", got, want)
  3605. }
  3606. writeHeaders <- true
  3607. <-leaveHandler
  3608. })
  3609. st.greet()
  3610. st.writeHeaders(HeadersFrameParam{
  3611. StreamID: 1,
  3612. BlockFragment: st.encodeHeader(),
  3613. EndStream: false, // keep it open
  3614. EndHeaders: true,
  3615. })
  3616. <-writeData
  3617. st.writeData(1, true, nil)
  3618. <-writeHeaders
  3619. st.writeHeaders(HeadersFrameParam{
  3620. StreamID: 1,
  3621. BlockFragment: st.encodeHeader(),
  3622. EndStream: false, // keep it open
  3623. EndHeaders: true,
  3624. })
  3625. defer close(leaveHandler)
  3626. st.wantRSTStream(1, ErrCodeStreamClosed)
  3627. }
  3628. func TestServerGracefulShutdown(t *testing.T) {
  3629. var st *serverTester
  3630. handlerDone := make(chan struct{})
  3631. st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3632. defer close(handlerDone)
  3633. go st.ts.Config.Shutdown(context.Background())
  3634. ga := st.wantGoAway()
  3635. if ga.ErrCode != ErrCodeNo {
  3636. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3637. }
  3638. if ga.LastStreamID != 1 {
  3639. t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID)
  3640. }
  3641. w.Header().Set("x-foo", "bar")
  3642. })
  3643. defer st.Close()
  3644. st.greet()
  3645. st.bodylessReq1()
  3646. select {
  3647. case <-handlerDone:
  3648. case <-time.After(5 * time.Second):
  3649. t.Fatalf("server did not shutdown?")
  3650. }
  3651. hf := st.wantHeaders()
  3652. goth := st.decodeHeader(hf.HeaderBlockFragment())
  3653. wanth := [][2]string{
  3654. {":status", "200"},
  3655. {"x-foo", "bar"},
  3656. {"content-length", "0"},
  3657. }
  3658. if !reflect.DeepEqual(goth, wanth) {
  3659. t.Errorf("Got headers %v; want %v", goth, wanth)
  3660. }
  3661. n, err := st.cc.Read([]byte{0})
  3662. if n != 0 || err == nil {
  3663. t.Errorf("Read = %v, %v; want 0, non-nil", n, err)
  3664. }
  3665. }
  3666. // Issue 31753: don't sniff when Content-Encoding is set
  3667. func TestContentEncodingNoSniffing(t *testing.T) {
  3668. type resp struct {
  3669. name string
  3670. body []byte
  3671. // setting Content-Encoding as an interface instead of a string
  3672. // directly, so as to differentiate between 3 states:
  3673. // unset, empty string "" and set string "foo/bar".
  3674. contentEncoding interface{}
  3675. wantContentType string
  3676. }
  3677. resps := []*resp{
  3678. {
  3679. name: "gzip content-encoding, gzipped", // don't sniff.
  3680. contentEncoding: "application/gzip",
  3681. wantContentType: "",
  3682. body: func() []byte {
  3683. buf := new(bytes.Buffer)
  3684. gzw := gzip.NewWriter(buf)
  3685. gzw.Write([]byte("doctype html><p>Hello</p>"))
  3686. gzw.Close()
  3687. return buf.Bytes()
  3688. }(),
  3689. },
  3690. {
  3691. name: "zlib content-encoding, zlibbed", // don't sniff.
  3692. contentEncoding: "application/zlib",
  3693. wantContentType: "",
  3694. body: func() []byte {
  3695. buf := new(bytes.Buffer)
  3696. zw := zlib.NewWriter(buf)
  3697. zw.Write([]byte("doctype html><p>Hello</p>"))
  3698. zw.Close()
  3699. return buf.Bytes()
  3700. }(),
  3701. },
  3702. {
  3703. name: "no content-encoding", // must sniff.
  3704. wantContentType: "application/x-gzip",
  3705. body: func() []byte {
  3706. buf := new(bytes.Buffer)
  3707. gzw := gzip.NewWriter(buf)
  3708. gzw.Write([]byte("doctype html><p>Hello</p>"))
  3709. gzw.Close()
  3710. return buf.Bytes()
  3711. }(),
  3712. },
  3713. {
  3714. name: "phony content-encoding", // don't sniff.
  3715. contentEncoding: "foo/bar",
  3716. body: []byte("doctype html><p>Hello</p>"),
  3717. },
  3718. {
  3719. name: "empty but set content-encoding",
  3720. contentEncoding: "",
  3721. wantContentType: "audio/mpeg",
  3722. body: []byte("ID3"),
  3723. },
  3724. }
  3725. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3726. defer tr.CloseIdleConnections()
  3727. for _, tt := range resps {
  3728. t.Run(tt.name, func(t *testing.T) {
  3729. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3730. if tt.contentEncoding != nil {
  3731. w.Header().Set("Content-Encoding", tt.contentEncoding.(string))
  3732. }
  3733. w.Write(tt.body)
  3734. }, optOnlyServer)
  3735. defer st.Close()
  3736. req, _ := http.NewRequest("GET", st.ts.URL, nil)
  3737. res, err := tr.RoundTrip(req)
  3738. if err != nil {
  3739. t.Fatalf("Failed to fetch URL: %v", err)
  3740. }
  3741. defer res.Body.Close()
  3742. if g, w := res.Header.Get("Content-Encoding"), tt.contentEncoding; g != w {
  3743. if w != nil { // The case where contentEncoding was set explicitly.
  3744. t.Errorf("Content-Encoding mismatch\n\tgot: %q\n\twant: %q", g, w)
  3745. } else if g != "" { // "" should be the equivalent when the contentEncoding is unset.
  3746. t.Errorf("Unexpected Content-Encoding %q", g)
  3747. }
  3748. }
  3749. if g, w := res.Header.Get("Content-Type"), tt.wantContentType; g != w {
  3750. t.Errorf("Content-Type mismatch\n\tgot: %q\n\twant: %q", g, w)
  3751. }
  3752. })
  3753. }
  3754. }