server_test.go 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211
  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" || runtime.GOOS == "plan9" {
  1077. t.Skip("see golang.org/issue/13434, golang.org/issue/37321")
  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. // Reject content-length headers containing a sign.
  1591. // See https://golang.org/issue/39017
  1592. func TestServerIgnoresContentLengthSignWhenWritingChunks(t *testing.T) {
  1593. tests := []struct {
  1594. name string
  1595. cl string
  1596. wantCL string
  1597. }{
  1598. {
  1599. name: "proper content-length",
  1600. cl: "3",
  1601. wantCL: "3",
  1602. },
  1603. {
  1604. name: "ignore cl with plus sign",
  1605. cl: "+3",
  1606. wantCL: "0",
  1607. },
  1608. {
  1609. name: "ignore cl with minus sign",
  1610. cl: "-3",
  1611. wantCL: "0",
  1612. },
  1613. {
  1614. name: "max int64, for safe uint64->int64 conversion",
  1615. cl: "9223372036854775807",
  1616. wantCL: "9223372036854775807",
  1617. },
  1618. {
  1619. name: "overflows int64, so ignored",
  1620. cl: "9223372036854775808",
  1621. wantCL: "0",
  1622. },
  1623. }
  1624. for _, tt := range tests {
  1625. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1626. w.Header().Set("content-length", tt.cl)
  1627. return nil
  1628. }, func(st *serverTester) {
  1629. getSlash(st)
  1630. hf := st.wantHeaders()
  1631. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1632. wanth := [][2]string{
  1633. {":status", "200"},
  1634. {"content-length", tt.wantCL},
  1635. }
  1636. if !reflect.DeepEqual(goth, wanth) {
  1637. t.Errorf("For case %q, value %q, got = %q; want %q", tt.name, tt.cl, goth, wanth)
  1638. }
  1639. })
  1640. }
  1641. }
  1642. // Reject content-length headers containing a sign.
  1643. // See https://golang.org/issue/39017
  1644. func TestServerRejectsContentLengthWithSignNewRequests(t *testing.T) {
  1645. tests := []struct {
  1646. name string
  1647. cl string
  1648. wantCL int64
  1649. }{
  1650. {
  1651. name: "proper content-length",
  1652. cl: "3",
  1653. wantCL: 3,
  1654. },
  1655. {
  1656. name: "ignore cl with plus sign",
  1657. cl: "+3",
  1658. wantCL: 0,
  1659. },
  1660. {
  1661. name: "ignore cl with minus sign",
  1662. cl: "-3",
  1663. wantCL: 0,
  1664. },
  1665. {
  1666. name: "max int64, for safe uint64->int64 conversion",
  1667. cl: "9223372036854775807",
  1668. wantCL: 9223372036854775807,
  1669. },
  1670. {
  1671. name: "overflows int64, so ignored",
  1672. cl: "9223372036854775808",
  1673. wantCL: 0,
  1674. },
  1675. }
  1676. for _, tt := range tests {
  1677. tt := tt
  1678. t.Run(tt.name, func(t *testing.T) {
  1679. writeReq := func(st *serverTester) {
  1680. st.writeHeaders(HeadersFrameParam{
  1681. StreamID: 1, // clients send odd numbers
  1682. BlockFragment: st.encodeHeader("content-length", tt.cl),
  1683. EndStream: false,
  1684. EndHeaders: true,
  1685. })
  1686. st.writeData(1, false, []byte(""))
  1687. }
  1688. checkReq := func(r *http.Request) {
  1689. if r.ContentLength != tt.wantCL {
  1690. t.Fatalf("Got: %q\nWant: %q", r.ContentLength, tt.wantCL)
  1691. }
  1692. }
  1693. testServerRequest(t, writeReq, checkReq)
  1694. })
  1695. }
  1696. }
  1697. func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) {
  1698. const msg = "<html>this is HTML."
  1699. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1700. w.Header().Set("Content-Type", "foo/bar")
  1701. io.WriteString(w, msg)
  1702. return nil
  1703. }, func(st *serverTester) {
  1704. getSlash(st)
  1705. hf := st.wantHeaders()
  1706. if hf.StreamEnded() {
  1707. t.Fatal("don't want END_STREAM, expecting data")
  1708. }
  1709. if !hf.HeadersEnded() {
  1710. t.Fatal("want END_HEADERS flag")
  1711. }
  1712. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1713. wanth := [][2]string{
  1714. {":status", "200"},
  1715. {"content-type", "foo/bar"},
  1716. {"content-length", strconv.Itoa(len(msg))},
  1717. }
  1718. if !reflect.DeepEqual(goth, wanth) {
  1719. t.Errorf("Got headers %v; want %v", goth, wanth)
  1720. }
  1721. df := st.wantData()
  1722. if !df.StreamEnded() {
  1723. t.Error("expected DATA to have END_STREAM flag")
  1724. }
  1725. if got := string(df.Data()); got != msg {
  1726. t.Errorf("got DATA %q; want %q", got, msg)
  1727. }
  1728. })
  1729. }
  1730. func TestServer_Response_TransferEncoding_chunked(t *testing.T) {
  1731. const msg = "hi"
  1732. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1733. w.Header().Set("Transfer-Encoding", "chunked") // should be stripped
  1734. io.WriteString(w, msg)
  1735. return nil
  1736. }, func(st *serverTester) {
  1737. getSlash(st)
  1738. hf := st.wantHeaders()
  1739. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1740. wanth := [][2]string{
  1741. {":status", "200"},
  1742. {"content-type", "text/plain; charset=utf-8"},
  1743. {"content-length", strconv.Itoa(len(msg))},
  1744. }
  1745. if !reflect.DeepEqual(goth, wanth) {
  1746. t.Errorf("Got headers %v; want %v", goth, wanth)
  1747. }
  1748. })
  1749. }
  1750. // Header accessed only after the initial write.
  1751. func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) {
  1752. const msg = "<html>this is HTML."
  1753. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1754. io.WriteString(w, msg)
  1755. w.Header().Set("foo", "should be ignored")
  1756. return nil
  1757. }, func(st *serverTester) {
  1758. getSlash(st)
  1759. hf := st.wantHeaders()
  1760. if hf.StreamEnded() {
  1761. t.Fatal("unexpected END_STREAM")
  1762. }
  1763. if !hf.HeadersEnded() {
  1764. t.Fatal("want END_HEADERS flag")
  1765. }
  1766. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1767. wanth := [][2]string{
  1768. {":status", "200"},
  1769. {"content-type", "text/html; charset=utf-8"},
  1770. {"content-length", strconv.Itoa(len(msg))},
  1771. }
  1772. if !reflect.DeepEqual(goth, wanth) {
  1773. t.Errorf("Got headers %v; want %v", goth, wanth)
  1774. }
  1775. })
  1776. }
  1777. // Header accessed before the initial write and later mutated.
  1778. func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) {
  1779. const msg = "<html>this is HTML."
  1780. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1781. w.Header().Set("foo", "proper value")
  1782. io.WriteString(w, msg)
  1783. w.Header().Set("foo", "should be ignored")
  1784. return nil
  1785. }, func(st *serverTester) {
  1786. getSlash(st)
  1787. hf := st.wantHeaders()
  1788. if hf.StreamEnded() {
  1789. t.Fatal("unexpected END_STREAM")
  1790. }
  1791. if !hf.HeadersEnded() {
  1792. t.Fatal("want END_HEADERS flag")
  1793. }
  1794. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1795. wanth := [][2]string{
  1796. {":status", "200"},
  1797. {"foo", "proper value"},
  1798. {"content-type", "text/html; charset=utf-8"},
  1799. {"content-length", strconv.Itoa(len(msg))},
  1800. }
  1801. if !reflect.DeepEqual(goth, wanth) {
  1802. t.Errorf("Got headers %v; want %v", goth, wanth)
  1803. }
  1804. })
  1805. }
  1806. func TestServer_Response_Data_SniffLenType(t *testing.T) {
  1807. const msg = "<html>this is HTML."
  1808. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1809. io.WriteString(w, msg)
  1810. return nil
  1811. }, func(st *serverTester) {
  1812. getSlash(st)
  1813. hf := st.wantHeaders()
  1814. if hf.StreamEnded() {
  1815. t.Fatal("don't want END_STREAM, expecting data")
  1816. }
  1817. if !hf.HeadersEnded() {
  1818. t.Fatal("want END_HEADERS flag")
  1819. }
  1820. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1821. wanth := [][2]string{
  1822. {":status", "200"},
  1823. {"content-type", "text/html; charset=utf-8"},
  1824. {"content-length", strconv.Itoa(len(msg))},
  1825. }
  1826. if !reflect.DeepEqual(goth, wanth) {
  1827. t.Errorf("Got headers %v; want %v", goth, wanth)
  1828. }
  1829. df := st.wantData()
  1830. if !df.StreamEnded() {
  1831. t.Error("expected DATA to have END_STREAM flag")
  1832. }
  1833. if got := string(df.Data()); got != msg {
  1834. t.Errorf("got DATA %q; want %q", got, msg)
  1835. }
  1836. })
  1837. }
  1838. func TestServer_Response_Header_Flush_MidWrite(t *testing.T) {
  1839. const msg = "<html>this is HTML"
  1840. const msg2 = ", and this is the next chunk"
  1841. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1842. io.WriteString(w, msg)
  1843. w.(http.Flusher).Flush()
  1844. io.WriteString(w, msg2)
  1845. return nil
  1846. }, func(st *serverTester) {
  1847. getSlash(st)
  1848. hf := st.wantHeaders()
  1849. if hf.StreamEnded() {
  1850. t.Fatal("unexpected END_STREAM flag")
  1851. }
  1852. if !hf.HeadersEnded() {
  1853. t.Fatal("want END_HEADERS flag")
  1854. }
  1855. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1856. wanth := [][2]string{
  1857. {":status", "200"},
  1858. {"content-type", "text/html; charset=utf-8"}, // sniffed
  1859. // and no content-length
  1860. }
  1861. if !reflect.DeepEqual(goth, wanth) {
  1862. t.Errorf("Got headers %v; want %v", goth, wanth)
  1863. }
  1864. {
  1865. df := st.wantData()
  1866. if df.StreamEnded() {
  1867. t.Error("unexpected END_STREAM flag")
  1868. }
  1869. if got := string(df.Data()); got != msg {
  1870. t.Errorf("got DATA %q; want %q", got, msg)
  1871. }
  1872. }
  1873. {
  1874. df := st.wantData()
  1875. if !df.StreamEnded() {
  1876. t.Error("wanted END_STREAM flag on last data chunk")
  1877. }
  1878. if got := string(df.Data()); got != msg2 {
  1879. t.Errorf("got DATA %q; want %q", got, msg2)
  1880. }
  1881. }
  1882. })
  1883. }
  1884. func TestServer_Response_LargeWrite(t *testing.T) {
  1885. const size = 1 << 20
  1886. const maxFrameSize = 16 << 10
  1887. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1888. n, err := w.Write(bytes.Repeat([]byte("a"), size))
  1889. if err != nil {
  1890. return fmt.Errorf("Write error: %v", err)
  1891. }
  1892. if n != size {
  1893. return fmt.Errorf("wrong size %d from Write", n)
  1894. }
  1895. return nil
  1896. }, func(st *serverTester) {
  1897. if err := st.fr.WriteSettings(
  1898. Setting{SettingInitialWindowSize, 0},
  1899. Setting{SettingMaxFrameSize, maxFrameSize},
  1900. ); err != nil {
  1901. t.Fatal(err)
  1902. }
  1903. st.wantSettingsAck()
  1904. getSlash(st) // make the single request
  1905. // Give the handler quota to write:
  1906. if err := st.fr.WriteWindowUpdate(1, size); err != nil {
  1907. t.Fatal(err)
  1908. }
  1909. // Give the handler quota to write to connection-level
  1910. // window as well
  1911. if err := st.fr.WriteWindowUpdate(0, size); err != nil {
  1912. t.Fatal(err)
  1913. }
  1914. hf := st.wantHeaders()
  1915. if hf.StreamEnded() {
  1916. t.Fatal("unexpected END_STREAM flag")
  1917. }
  1918. if !hf.HeadersEnded() {
  1919. t.Fatal("want END_HEADERS flag")
  1920. }
  1921. goth := st.decodeHeader(hf.HeaderBlockFragment())
  1922. wanth := [][2]string{
  1923. {":status", "200"},
  1924. {"content-type", "text/plain; charset=utf-8"}, // sniffed
  1925. // and no content-length
  1926. }
  1927. if !reflect.DeepEqual(goth, wanth) {
  1928. t.Errorf("Got headers %v; want %v", goth, wanth)
  1929. }
  1930. var bytes, frames int
  1931. for {
  1932. df := st.wantData()
  1933. bytes += len(df.Data())
  1934. frames++
  1935. for _, b := range df.Data() {
  1936. if b != 'a' {
  1937. t.Fatal("non-'a' byte seen in DATA")
  1938. }
  1939. }
  1940. if df.StreamEnded() {
  1941. break
  1942. }
  1943. }
  1944. if bytes != size {
  1945. t.Errorf("Got %d bytes; want %d", bytes, size)
  1946. }
  1947. if want := int(size / maxFrameSize); frames < want || frames > want*2 {
  1948. t.Errorf("Got %d frames; want %d", frames, size)
  1949. }
  1950. })
  1951. }
  1952. // Test that the handler can't write more than the client allows
  1953. func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) {
  1954. // Make these reads. Before each read, the client adds exactly enough
  1955. // flow-control to satisfy the read. Numbers chosen arbitrarily.
  1956. reads := []int{123, 1, 13, 127}
  1957. size := 0
  1958. for _, n := range reads {
  1959. size += n
  1960. }
  1961. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1962. w.(http.Flusher).Flush()
  1963. n, err := w.Write(bytes.Repeat([]byte("a"), size))
  1964. if err != nil {
  1965. return fmt.Errorf("Write error: %v", err)
  1966. }
  1967. if n != size {
  1968. return fmt.Errorf("wrong size %d from Write", n)
  1969. }
  1970. return nil
  1971. }, func(st *serverTester) {
  1972. // Set the window size to something explicit for this test.
  1973. // It's also how much initial data we expect.
  1974. if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil {
  1975. t.Fatal(err)
  1976. }
  1977. st.wantSettingsAck()
  1978. getSlash(st) // make the single request
  1979. hf := st.wantHeaders()
  1980. if hf.StreamEnded() {
  1981. t.Fatal("unexpected END_STREAM flag")
  1982. }
  1983. if !hf.HeadersEnded() {
  1984. t.Fatal("want END_HEADERS flag")
  1985. }
  1986. df := st.wantData()
  1987. if got := len(df.Data()); got != reads[0] {
  1988. t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got)
  1989. }
  1990. for _, quota := range reads[1:] {
  1991. if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil {
  1992. t.Fatal(err)
  1993. }
  1994. df := st.wantData()
  1995. if int(quota) != len(df.Data()) {
  1996. t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota)
  1997. }
  1998. }
  1999. })
  2000. }
  2001. // Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM.
  2002. func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) {
  2003. const size = 1 << 20
  2004. const maxFrameSize = 16 << 10
  2005. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2006. w.(http.Flusher).Flush()
  2007. errc := make(chan error, 1)
  2008. go func() {
  2009. _, err := w.Write(bytes.Repeat([]byte("a"), size))
  2010. errc <- err
  2011. }()
  2012. select {
  2013. case err := <-errc:
  2014. if err == nil {
  2015. return errors.New("unexpected nil error from Write in handler")
  2016. }
  2017. return nil
  2018. case <-time.After(2 * time.Second):
  2019. return errors.New("timeout waiting for Write in handler")
  2020. }
  2021. }, func(st *serverTester) {
  2022. if err := st.fr.WriteSettings(
  2023. Setting{SettingInitialWindowSize, 0},
  2024. Setting{SettingMaxFrameSize, maxFrameSize},
  2025. ); err != nil {
  2026. t.Fatal(err)
  2027. }
  2028. st.wantSettingsAck()
  2029. getSlash(st) // make the single request
  2030. hf := st.wantHeaders()
  2031. if hf.StreamEnded() {
  2032. t.Fatal("unexpected END_STREAM flag")
  2033. }
  2034. if !hf.HeadersEnded() {
  2035. t.Fatal("want END_HEADERS flag")
  2036. }
  2037. if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  2038. t.Fatal(err)
  2039. }
  2040. })
  2041. }
  2042. func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) {
  2043. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2044. w.(http.Flusher).Flush()
  2045. // Nothing; send empty DATA
  2046. return nil
  2047. }, func(st *serverTester) {
  2048. // Handler gets no data quota:
  2049. if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil {
  2050. t.Fatal(err)
  2051. }
  2052. st.wantSettingsAck()
  2053. getSlash(st) // make the single request
  2054. hf := st.wantHeaders()
  2055. if hf.StreamEnded() {
  2056. t.Fatal("unexpected END_STREAM flag")
  2057. }
  2058. if !hf.HeadersEnded() {
  2059. t.Fatal("want END_HEADERS flag")
  2060. }
  2061. df := st.wantData()
  2062. if got := len(df.Data()); got != 0 {
  2063. t.Fatalf("unexpected %d DATA bytes; want 0", got)
  2064. }
  2065. if !df.StreamEnded() {
  2066. t.Fatal("DATA didn't have END_STREAM")
  2067. }
  2068. })
  2069. }
  2070. func TestServer_Response_Automatic100Continue(t *testing.T) {
  2071. const msg = "foo"
  2072. const reply = "bar"
  2073. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2074. if v := r.Header.Get("Expect"); v != "" {
  2075. t.Errorf("Expect header = %q; want empty", v)
  2076. }
  2077. buf := make([]byte, len(msg))
  2078. // This read should trigger the 100-continue being sent.
  2079. if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg {
  2080. return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg)
  2081. }
  2082. _, err := io.WriteString(w, reply)
  2083. return err
  2084. }, func(st *serverTester) {
  2085. st.writeHeaders(HeadersFrameParam{
  2086. StreamID: 1, // clients send odd numbers
  2087. BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"),
  2088. EndStream: false,
  2089. EndHeaders: true,
  2090. })
  2091. hf := st.wantHeaders()
  2092. if hf.StreamEnded() {
  2093. t.Fatal("unexpected END_STREAM flag")
  2094. }
  2095. if !hf.HeadersEnded() {
  2096. t.Fatal("want END_HEADERS flag")
  2097. }
  2098. goth := st.decodeHeader(hf.HeaderBlockFragment())
  2099. wanth := [][2]string{
  2100. {":status", "100"},
  2101. }
  2102. if !reflect.DeepEqual(goth, wanth) {
  2103. t.Fatalf("Got headers %v; want %v", goth, wanth)
  2104. }
  2105. // Okay, they sent status 100, so we can send our
  2106. // gigantic and/or sensitive "foo" payload now.
  2107. st.writeData(1, true, []byte(msg))
  2108. st.wantWindowUpdate(0, uint32(len(msg)))
  2109. hf = st.wantHeaders()
  2110. if hf.StreamEnded() {
  2111. t.Fatal("expected data to follow")
  2112. }
  2113. if !hf.HeadersEnded() {
  2114. t.Fatal("want END_HEADERS flag")
  2115. }
  2116. goth = st.decodeHeader(hf.HeaderBlockFragment())
  2117. wanth = [][2]string{
  2118. {":status", "200"},
  2119. {"content-type", "text/plain; charset=utf-8"},
  2120. {"content-length", strconv.Itoa(len(reply))},
  2121. }
  2122. if !reflect.DeepEqual(goth, wanth) {
  2123. t.Errorf("Got headers %v; want %v", goth, wanth)
  2124. }
  2125. df := st.wantData()
  2126. if string(df.Data()) != reply {
  2127. t.Errorf("Client read %q; want %q", df.Data(), reply)
  2128. }
  2129. if !df.StreamEnded() {
  2130. t.Errorf("expect data stream end")
  2131. }
  2132. })
  2133. }
  2134. func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) {
  2135. errc := make(chan error, 1)
  2136. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2137. p := []byte("some data.\n")
  2138. for {
  2139. _, err := w.Write(p)
  2140. if err != nil {
  2141. errc <- err
  2142. return nil
  2143. }
  2144. }
  2145. }, func(st *serverTester) {
  2146. st.writeHeaders(HeadersFrameParam{
  2147. StreamID: 1,
  2148. BlockFragment: st.encodeHeader(),
  2149. EndStream: false,
  2150. EndHeaders: true,
  2151. })
  2152. hf := st.wantHeaders()
  2153. if hf.StreamEnded() {
  2154. t.Fatal("unexpected END_STREAM flag")
  2155. }
  2156. if !hf.HeadersEnded() {
  2157. t.Fatal("want END_HEADERS flag")
  2158. }
  2159. // Close the connection and wait for the handler to (hopefully) notice.
  2160. st.cc.Close()
  2161. select {
  2162. case <-errc:
  2163. case <-time.After(5 * time.Second):
  2164. t.Error("timeout")
  2165. }
  2166. })
  2167. }
  2168. func TestServer_Rejects_Too_Many_Streams(t *testing.T) {
  2169. const testPath = "/some/path"
  2170. inHandler := make(chan uint32)
  2171. leaveHandler := make(chan bool)
  2172. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2173. id := w.(*responseWriter).rws.stream.id
  2174. inHandler <- id
  2175. if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath {
  2176. t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath)
  2177. }
  2178. <-leaveHandler
  2179. })
  2180. defer st.Close()
  2181. st.greet()
  2182. nextStreamID := uint32(1)
  2183. streamID := func() uint32 {
  2184. defer func() { nextStreamID += 2 }()
  2185. return nextStreamID
  2186. }
  2187. sendReq := func(id uint32, headers ...string) {
  2188. st.writeHeaders(HeadersFrameParam{
  2189. StreamID: id,
  2190. BlockFragment: st.encodeHeader(headers...),
  2191. EndStream: true,
  2192. EndHeaders: true,
  2193. })
  2194. }
  2195. for i := 0; i < defaultMaxStreams; i++ {
  2196. sendReq(streamID())
  2197. <-inHandler
  2198. }
  2199. defer func() {
  2200. for i := 0; i < defaultMaxStreams; i++ {
  2201. leaveHandler <- true
  2202. }
  2203. }()
  2204. // And this one should cross the limit:
  2205. // (It's also sent as a CONTINUATION, to verify we still track the decoder context,
  2206. // even if we're rejecting it)
  2207. rejectID := streamID()
  2208. headerBlock := st.encodeHeader(":path", testPath)
  2209. frag1, frag2 := headerBlock[:3], headerBlock[3:]
  2210. st.writeHeaders(HeadersFrameParam{
  2211. StreamID: rejectID,
  2212. BlockFragment: frag1,
  2213. EndStream: true,
  2214. EndHeaders: false, // CONTINUATION coming
  2215. })
  2216. if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil {
  2217. t.Fatal(err)
  2218. }
  2219. st.wantRSTStream(rejectID, ErrCodeProtocol)
  2220. // But let a handler finish:
  2221. leaveHandler <- true
  2222. st.wantHeaders()
  2223. // And now another stream should be able to start:
  2224. goodID := streamID()
  2225. sendReq(goodID, ":path", testPath)
  2226. select {
  2227. case got := <-inHandler:
  2228. if got != goodID {
  2229. t.Errorf("Got stream %d; want %d", got, goodID)
  2230. }
  2231. case <-time.After(3 * time.Second):
  2232. t.Error("timeout waiting for handler")
  2233. }
  2234. }
  2235. // So many response headers that the server needs to use CONTINUATION frames:
  2236. func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) {
  2237. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2238. h := w.Header()
  2239. for i := 0; i < 5000; i++ {
  2240. h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i))
  2241. }
  2242. return nil
  2243. }, func(st *serverTester) {
  2244. getSlash(st)
  2245. hf := st.wantHeaders()
  2246. if hf.HeadersEnded() {
  2247. t.Fatal("got unwanted END_HEADERS flag")
  2248. }
  2249. n := 0
  2250. for {
  2251. n++
  2252. cf := st.wantContinuation()
  2253. if cf.HeadersEnded() {
  2254. break
  2255. }
  2256. }
  2257. if n < 5 {
  2258. t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n)
  2259. }
  2260. })
  2261. }
  2262. // This previously crashed (reported by Mathieu Lonjaret as observed
  2263. // while using Camlistore) because we got a DATA frame from the client
  2264. // after the handler exited and our logic at the time was wrong,
  2265. // keeping a stream in the map in stateClosed, which tickled an
  2266. // invariant check later when we tried to remove that stream (via
  2267. // defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop
  2268. // ended.
  2269. func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) {
  2270. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2271. // nothing
  2272. return nil
  2273. }, func(st *serverTester) {
  2274. st.writeHeaders(HeadersFrameParam{
  2275. StreamID: 1,
  2276. BlockFragment: st.encodeHeader(),
  2277. EndStream: false, // DATA is coming
  2278. EndHeaders: true,
  2279. })
  2280. hf := st.wantHeaders()
  2281. if !hf.HeadersEnded() || !hf.StreamEnded() {
  2282. t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf)
  2283. }
  2284. // Sent when the a Handler closes while a client has
  2285. // indicated it's still sending DATA:
  2286. st.wantRSTStream(1, ErrCodeNo)
  2287. // Now the handler has ended, so it's ended its
  2288. // stream, but the client hasn't closed its side
  2289. // (stateClosedLocal). So send more data and verify
  2290. // it doesn't crash with an internal invariant panic, like
  2291. // it did before.
  2292. st.writeData(1, true, []byte("foo"))
  2293. // Get our flow control bytes back, since the handler didn't get them.
  2294. st.wantWindowUpdate(0, uint32(len("foo")))
  2295. // Sent after a peer sends data anyway (admittedly the
  2296. // previous RST_STREAM might've still been in-flight),
  2297. // but they'll get the more friendly 'cancel' code
  2298. // first.
  2299. st.wantRSTStream(1, ErrCodeStreamClosed)
  2300. // Set up a bunch of machinery to record the panic we saw
  2301. // previously.
  2302. var (
  2303. panMu sync.Mutex
  2304. panicVal interface{}
  2305. )
  2306. testHookOnPanicMu.Lock()
  2307. testHookOnPanic = func(sc *serverConn, pv interface{}) bool {
  2308. panMu.Lock()
  2309. panicVal = pv
  2310. panMu.Unlock()
  2311. return true
  2312. }
  2313. testHookOnPanicMu.Unlock()
  2314. // Now force the serve loop to end, via closing the connection.
  2315. st.cc.Close()
  2316. select {
  2317. case <-st.sc.doneServing:
  2318. // Loop has exited.
  2319. panMu.Lock()
  2320. got := panicVal
  2321. panMu.Unlock()
  2322. if got != nil {
  2323. t.Errorf("Got panic: %v", got)
  2324. }
  2325. case <-time.After(5 * time.Second):
  2326. t.Error("timeout")
  2327. }
  2328. })
  2329. }
  2330. func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) }
  2331. func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) }
  2332. func testRejectTLS(t *testing.T, max uint16) {
  2333. st := newServerTester(t, nil, func(c *tls.Config) {
  2334. c.MaxVersion = max
  2335. })
  2336. defer st.Close()
  2337. gf := st.wantGoAway()
  2338. if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2339. t.Errorf("Got error code %v; want %v", got, want)
  2340. }
  2341. }
  2342. func TestServer_Rejects_TLSBadCipher(t *testing.T) {
  2343. st := newServerTester(t, nil, func(c *tls.Config) {
  2344. // All TLS 1.3 ciphers are good. Test with TLS 1.2.
  2345. c.MaxVersion = tls.VersionTLS12
  2346. // Only list bad ones:
  2347. c.CipherSuites = []uint16{
  2348. tls.TLS_RSA_WITH_RC4_128_SHA,
  2349. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  2350. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  2351. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  2352. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  2353. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  2354. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  2355. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  2356. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  2357. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  2358. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  2359. cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
  2360. }
  2361. })
  2362. defer st.Close()
  2363. gf := st.wantGoAway()
  2364. if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2365. t.Errorf("Got error code %v; want %v", got, want)
  2366. }
  2367. }
  2368. func TestServer_Advertises_Common_Cipher(t *testing.T) {
  2369. const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  2370. st := newServerTester(t, nil, func(c *tls.Config) {
  2371. // Have the client only support the one required by the spec.
  2372. c.CipherSuites = []uint16{requiredSuite}
  2373. }, func(ts *httptest.Server) {
  2374. var srv *http.Server = ts.Config
  2375. // Have the server configured with no specific cipher suites.
  2376. // This tests that Go's defaults include the required one.
  2377. srv.TLSConfig = nil
  2378. })
  2379. defer st.Close()
  2380. st.greet()
  2381. }
  2382. func (st *serverTester) onHeaderField(f hpack.HeaderField) {
  2383. if f.Name == "date" {
  2384. return
  2385. }
  2386. st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value})
  2387. }
  2388. func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) {
  2389. st.decodedHeaders = nil
  2390. if _, err := st.hpackDec.Write(headerBlock); err != nil {
  2391. st.t.Fatalf("hpack decoding error: %v", err)
  2392. }
  2393. if err := st.hpackDec.Close(); err != nil {
  2394. st.t.Fatalf("hpack decoding error: %v", err)
  2395. }
  2396. return st.decodedHeaders
  2397. }
  2398. // testServerResponse sets up an idle HTTP/2 connection. The client function should
  2399. // write a single request that must be handled by the handler. This waits up to 5s
  2400. // for client to return, then up to an additional 2s for the handler to return.
  2401. func testServerResponse(t testing.TB,
  2402. handler func(http.ResponseWriter, *http.Request) error,
  2403. client func(*serverTester),
  2404. ) {
  2405. errc := make(chan error, 1)
  2406. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2407. if r.Body == nil {
  2408. t.Fatal("nil Body")
  2409. }
  2410. errc <- handler(w, r)
  2411. })
  2412. defer st.Close()
  2413. donec := make(chan bool)
  2414. go func() {
  2415. defer close(donec)
  2416. st.greet()
  2417. client(st)
  2418. }()
  2419. select {
  2420. case <-donec:
  2421. case <-time.After(5 * time.Second):
  2422. t.Fatal("timeout in client")
  2423. }
  2424. select {
  2425. case err := <-errc:
  2426. if err != nil {
  2427. t.Fatalf("Error in handler: %v", err)
  2428. }
  2429. case <-time.After(2 * time.Second):
  2430. t.Fatal("timeout in handler")
  2431. }
  2432. }
  2433. // readBodyHandler returns an http Handler func that reads len(want)
  2434. // bytes from r.Body and fails t if the contents read were not
  2435. // the value of want.
  2436. func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) {
  2437. return func(w http.ResponseWriter, r *http.Request) {
  2438. buf := make([]byte, len(want))
  2439. _, err := io.ReadFull(r.Body, buf)
  2440. if err != nil {
  2441. t.Error(err)
  2442. return
  2443. }
  2444. if string(buf) != want {
  2445. t.Errorf("read %q; want %q", buf, want)
  2446. }
  2447. }
  2448. }
  2449. // TestServerWithCurl currently fails, hence the LenientCipherSuites test. See:
  2450. // https://github.com/tatsuhiro-t/nghttp2/issues/140 &
  2451. // http://sourceforge.net/p/curl/bugs/1472/
  2452. func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) }
  2453. func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) }
  2454. func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) {
  2455. if runtime.GOOS != "linux" {
  2456. t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2457. }
  2458. if testing.Short() {
  2459. t.Skip("skipping curl test in short mode")
  2460. }
  2461. requireCurl(t)
  2462. var gotConn int32
  2463. testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) }
  2464. const msg = "Hello from curl!\n"
  2465. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2466. w.Header().Set("Foo", "Bar")
  2467. w.Header().Set("Client-Proto", r.Proto)
  2468. io.WriteString(w, msg)
  2469. }))
  2470. ConfigureServer(ts.Config, &Server{
  2471. PermitProhibitedCipherSuites: permitProhibitedCipherSuites,
  2472. })
  2473. ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
  2474. ts.StartTLS()
  2475. defer ts.Close()
  2476. t.Logf("Running test server for curl to hit at: %s", ts.URL)
  2477. container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL)
  2478. defer kill(container)
  2479. resc := make(chan interface{}, 1)
  2480. go func() {
  2481. res, err := dockerLogs(container)
  2482. if err != nil {
  2483. resc <- err
  2484. } else {
  2485. resc <- res
  2486. }
  2487. }()
  2488. select {
  2489. case res := <-resc:
  2490. if err, ok := res.(error); ok {
  2491. t.Fatal(err)
  2492. }
  2493. body := string(res.([]byte))
  2494. // Search for both "key: value" and "key:value", since curl changed their format
  2495. // Our Dockerfile contains the latest version (no space), but just in case people
  2496. // didn't rebuild, check both.
  2497. if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") {
  2498. t.Errorf("didn't see foo: Bar header")
  2499. t.Logf("Got: %s", body)
  2500. }
  2501. if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") {
  2502. t.Errorf("didn't see client-proto: HTTP/2 header")
  2503. t.Logf("Got: %s", res)
  2504. }
  2505. if !strings.Contains(string(res.([]byte)), msg) {
  2506. t.Errorf("didn't see %q content", msg)
  2507. t.Logf("Got: %s", res)
  2508. }
  2509. case <-time.After(3 * time.Second):
  2510. t.Errorf("timeout waiting for curl")
  2511. }
  2512. if atomic.LoadInt32(&gotConn) == 0 {
  2513. t.Error("never saw an http2 connection")
  2514. }
  2515. }
  2516. var doh2load = flag.Bool("h2load", false, "Run h2load test")
  2517. func TestServerWithH2Load(t *testing.T) {
  2518. if !*doh2load {
  2519. t.Skip("Skipping without --h2load flag.")
  2520. }
  2521. if runtime.GOOS != "linux" {
  2522. t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2523. }
  2524. requireH2load(t)
  2525. msg := strings.Repeat("Hello, h2load!\n", 5000)
  2526. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2527. io.WriteString(w, msg)
  2528. w.(http.Flusher).Flush()
  2529. io.WriteString(w, msg)
  2530. }))
  2531. ts.StartTLS()
  2532. defer ts.Close()
  2533. cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl",
  2534. "-n100000", "-c100", "-m100", ts.URL)
  2535. cmd.Stdout = os.Stdout
  2536. cmd.Stderr = os.Stderr
  2537. if err := cmd.Run(); err != nil {
  2538. t.Fatal(err)
  2539. }
  2540. }
  2541. // Issue 12843
  2542. func TestServerDoS_MaxHeaderListSize(t *testing.T) {
  2543. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  2544. defer st.Close()
  2545. // shake hands
  2546. frameSize := defaultMaxReadFrameSize
  2547. var advHeaderListSize *uint32
  2548. st.greetAndCheckSettings(func(s Setting) error {
  2549. switch s.ID {
  2550. case SettingMaxFrameSize:
  2551. if s.Val < minMaxFrameSize {
  2552. frameSize = minMaxFrameSize
  2553. } else if s.Val > maxFrameSize {
  2554. frameSize = maxFrameSize
  2555. } else {
  2556. frameSize = int(s.Val)
  2557. }
  2558. case SettingMaxHeaderListSize:
  2559. advHeaderListSize = &s.Val
  2560. }
  2561. return nil
  2562. })
  2563. if advHeaderListSize == nil {
  2564. t.Errorf("server didn't advertise a max header list size")
  2565. } else if *advHeaderListSize == 0 {
  2566. t.Errorf("server advertised a max header list size of 0")
  2567. }
  2568. st.encodeHeaderField(":method", "GET")
  2569. st.encodeHeaderField(":path", "/")
  2570. st.encodeHeaderField(":scheme", "https")
  2571. cookie := strings.Repeat("*", 4058)
  2572. st.encodeHeaderField("cookie", cookie)
  2573. st.writeHeaders(HeadersFrameParam{
  2574. StreamID: 1,
  2575. BlockFragment: st.headerBuf.Bytes(),
  2576. EndStream: true,
  2577. EndHeaders: false,
  2578. })
  2579. // Capture the short encoding of a duplicate ~4K cookie, now
  2580. // that we've already sent it once.
  2581. st.headerBuf.Reset()
  2582. st.encodeHeaderField("cookie", cookie)
  2583. // Now send 1MB of it.
  2584. const size = 1 << 20
  2585. b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len())
  2586. for len(b) > 0 {
  2587. chunk := b
  2588. if len(chunk) > frameSize {
  2589. chunk = chunk[:frameSize]
  2590. }
  2591. b = b[len(chunk):]
  2592. st.fr.WriteContinuation(1, len(b) == 0, chunk)
  2593. }
  2594. h := st.wantHeaders()
  2595. if !h.HeadersEnded() {
  2596. t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2597. }
  2598. headers := st.decodeHeader(h.HeaderBlockFragment())
  2599. want := [][2]string{
  2600. {":status", "431"},
  2601. {"content-type", "text/html; charset=utf-8"},
  2602. {"content-length", "63"},
  2603. }
  2604. if !reflect.DeepEqual(headers, want) {
  2605. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2606. }
  2607. }
  2608. func TestServer_Response_Stream_With_Missing_Trailer(t *testing.T) {
  2609. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2610. w.Header().Set("Trailer", "test-trailer")
  2611. return nil
  2612. }, func(st *serverTester) {
  2613. getSlash(st)
  2614. hf := st.wantHeaders()
  2615. if !hf.HeadersEnded() {
  2616. t.Fatal("want END_HEADERS flag")
  2617. }
  2618. df := st.wantData()
  2619. if len(df.data) != 0 {
  2620. t.Fatal("did not want data")
  2621. }
  2622. if !df.StreamEnded() {
  2623. t.Fatal("want END_STREAM flag")
  2624. }
  2625. })
  2626. }
  2627. func TestCompressionErrorOnWrite(t *testing.T) {
  2628. const maxStrLen = 8 << 10
  2629. var serverConfig *http.Server
  2630. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2631. // No response body.
  2632. }, func(ts *httptest.Server) {
  2633. serverConfig = ts.Config
  2634. serverConfig.MaxHeaderBytes = maxStrLen
  2635. })
  2636. st.addLogFilter("connection error: COMPRESSION_ERROR")
  2637. defer st.Close()
  2638. st.greet()
  2639. maxAllowed := st.sc.framer.maxHeaderStringLen()
  2640. // Crank this up, now that we have a conn connected with the
  2641. // hpack.Decoder's max string length set has been initialized
  2642. // from the earlier low ~8K value. We want this higher so don't
  2643. // hit the max header list size. We only want to test hitting
  2644. // the max string size.
  2645. serverConfig.MaxHeaderBytes = 1 << 20
  2646. // First a request with a header that's exactly the max allowed size
  2647. // for the hpack compression. It's still too long for the header list
  2648. // size, so we'll get the 431 error, but that keeps the compression
  2649. // context still valid.
  2650. hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed))
  2651. st.writeHeaders(HeadersFrameParam{
  2652. StreamID: 1,
  2653. BlockFragment: hbf,
  2654. EndStream: true,
  2655. EndHeaders: true,
  2656. })
  2657. h := st.wantHeaders()
  2658. if !h.HeadersEnded() {
  2659. t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2660. }
  2661. headers := st.decodeHeader(h.HeaderBlockFragment())
  2662. want := [][2]string{
  2663. {":status", "431"},
  2664. {"content-type", "text/html; charset=utf-8"},
  2665. {"content-length", "63"},
  2666. }
  2667. if !reflect.DeepEqual(headers, want) {
  2668. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2669. }
  2670. df := st.wantData()
  2671. if !strings.Contains(string(df.Data()), "HTTP Error 431") {
  2672. t.Errorf("Unexpected data body: %q", df.Data())
  2673. }
  2674. if !df.StreamEnded() {
  2675. t.Fatalf("expect data stream end")
  2676. }
  2677. // And now send one that's just one byte too big.
  2678. hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1))
  2679. st.writeHeaders(HeadersFrameParam{
  2680. StreamID: 3,
  2681. BlockFragment: hbf,
  2682. EndStream: true,
  2683. EndHeaders: true,
  2684. })
  2685. ga := st.wantGoAway()
  2686. if ga.ErrCode != ErrCodeCompression {
  2687. t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2688. }
  2689. }
  2690. func TestCompressionErrorOnClose(t *testing.T) {
  2691. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2692. // No response body.
  2693. })
  2694. st.addLogFilter("connection error: COMPRESSION_ERROR")
  2695. defer st.Close()
  2696. st.greet()
  2697. hbf := st.encodeHeader("foo", "bar")
  2698. hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails.
  2699. st.writeHeaders(HeadersFrameParam{
  2700. StreamID: 1,
  2701. BlockFragment: hbf,
  2702. EndStream: true,
  2703. EndHeaders: true,
  2704. })
  2705. ga := st.wantGoAway()
  2706. if ga.ErrCode != ErrCodeCompression {
  2707. t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2708. }
  2709. }
  2710. // test that a server handler can read trailers from a client
  2711. func TestServerReadsTrailers(t *testing.T) {
  2712. const testBody = "some test body"
  2713. writeReq := func(st *serverTester) {
  2714. st.writeHeaders(HeadersFrameParam{
  2715. StreamID: 1, // clients send odd numbers
  2716. BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"),
  2717. EndStream: false,
  2718. EndHeaders: true,
  2719. })
  2720. st.writeData(1, false, []byte(testBody))
  2721. st.writeHeaders(HeadersFrameParam{
  2722. StreamID: 1, // clients send odd numbers
  2723. BlockFragment: st.encodeHeaderRaw(
  2724. "foo", "foov",
  2725. "bar", "barv",
  2726. "baz", "bazv",
  2727. "surprise", "wasn't declared; shouldn't show up",
  2728. ),
  2729. EndStream: true,
  2730. EndHeaders: true,
  2731. })
  2732. }
  2733. checkReq := func(r *http.Request) {
  2734. wantTrailer := http.Header{
  2735. "Foo": nil,
  2736. "Bar": nil,
  2737. "Baz": nil,
  2738. }
  2739. if !reflect.DeepEqual(r.Trailer, wantTrailer) {
  2740. t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer)
  2741. }
  2742. slurp, err := ioutil.ReadAll(r.Body)
  2743. if string(slurp) != testBody {
  2744. t.Errorf("read body %q; want %q", slurp, testBody)
  2745. }
  2746. if err != nil {
  2747. t.Fatalf("Body slurp: %v", err)
  2748. }
  2749. wantTrailerAfter := http.Header{
  2750. "Foo": {"foov"},
  2751. "Bar": {"barv"},
  2752. "Baz": {"bazv"},
  2753. }
  2754. if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) {
  2755. t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter)
  2756. }
  2757. }
  2758. testServerRequest(t, writeReq, checkReq)
  2759. }
  2760. // test that a server handler can send trailers
  2761. func TestServerWritesTrailers_WithFlush(t *testing.T) { testServerWritesTrailers(t, true) }
  2762. func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) }
  2763. func testServerWritesTrailers(t *testing.T, withFlush bool) {
  2764. // See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3
  2765. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2766. w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
  2767. w.Header().Add("Trailer", "Server-Trailer-C")
  2768. w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered
  2769. // Regular headers:
  2770. w.Header().Set("Foo", "Bar")
  2771. w.Header().Set("Content-Length", "5") // len("Hello")
  2772. io.WriteString(w, "Hello")
  2773. if withFlush {
  2774. w.(http.Flusher).Flush()
  2775. }
  2776. w.Header().Set("Server-Trailer-A", "valuea")
  2777. w.Header().Set("Server-Trailer-C", "valuec") // skipping B
  2778. // After a flush, random keys like Server-Surprise shouldn't show up:
  2779. w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!")
  2780. // But we do permit promoting keys to trailers after a
  2781. // flush if they start with the magic
  2782. // otherwise-invalid "Trailer:" prefix:
  2783. w.Header().Set("Trailer:Post-Header-Trailer", "hi1")
  2784. w.Header().Set("Trailer:post-header-trailer2", "hi2")
  2785. w.Header().Set("Trailer:Range", "invalid")
  2786. w.Header().Set("Trailer:Foo\x01Bogus", "invalid")
  2787. w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 7230 4.1.2")
  2788. w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 7230 4.1.2")
  2789. w.Header().Set("Trailer", "should not be included; Forbidden by RFC 7230 4.1.2")
  2790. return nil
  2791. }, func(st *serverTester) {
  2792. getSlash(st)
  2793. hf := st.wantHeaders()
  2794. if hf.StreamEnded() {
  2795. t.Fatal("response HEADERS had END_STREAM")
  2796. }
  2797. if !hf.HeadersEnded() {
  2798. t.Fatal("response HEADERS didn't have END_HEADERS")
  2799. }
  2800. goth := st.decodeHeader(hf.HeaderBlockFragment())
  2801. wanth := [][2]string{
  2802. {":status", "200"},
  2803. {"foo", "Bar"},
  2804. {"trailer", "Server-Trailer-A, Server-Trailer-B"},
  2805. {"trailer", "Server-Trailer-C"},
  2806. {"trailer", "Transfer-Encoding, Content-Length, Trailer"},
  2807. {"content-type", "text/plain; charset=utf-8"},
  2808. {"content-length", "5"},
  2809. }
  2810. if !reflect.DeepEqual(goth, wanth) {
  2811. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2812. }
  2813. df := st.wantData()
  2814. if string(df.Data()) != "Hello" {
  2815. t.Fatalf("Client read %q; want Hello", df.Data())
  2816. }
  2817. if df.StreamEnded() {
  2818. t.Fatalf("data frame had STREAM_ENDED")
  2819. }
  2820. tf := st.wantHeaders() // for the trailers
  2821. if !tf.StreamEnded() {
  2822. t.Fatalf("trailers HEADERS lacked END_STREAM")
  2823. }
  2824. if !tf.HeadersEnded() {
  2825. t.Fatalf("trailers HEADERS lacked END_HEADERS")
  2826. }
  2827. wanth = [][2]string{
  2828. {"post-header-trailer", "hi1"},
  2829. {"post-header-trailer2", "hi2"},
  2830. {"server-trailer-a", "valuea"},
  2831. {"server-trailer-c", "valuec"},
  2832. }
  2833. goth = st.decodeHeader(tf.HeaderBlockFragment())
  2834. if !reflect.DeepEqual(goth, wanth) {
  2835. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2836. }
  2837. })
  2838. }
  2839. // validate transmitted header field names & values
  2840. // golang.org/issue/14048
  2841. func TestServerDoesntWriteInvalidHeaders(t *testing.T) {
  2842. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2843. w.Header().Add("OK1", "x")
  2844. w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key
  2845. w.Header().Add("Bad1\x00", "x") // null in key
  2846. w.Header().Add("Bad2", "x\x00y") // null in value
  2847. return nil
  2848. }, func(st *serverTester) {
  2849. getSlash(st)
  2850. hf := st.wantHeaders()
  2851. if !hf.StreamEnded() {
  2852. t.Error("response HEADERS lacked END_STREAM")
  2853. }
  2854. if !hf.HeadersEnded() {
  2855. t.Fatal("response HEADERS didn't have END_HEADERS")
  2856. }
  2857. goth := st.decodeHeader(hf.HeaderBlockFragment())
  2858. wanth := [][2]string{
  2859. {":status", "200"},
  2860. {"ok1", "x"},
  2861. {"content-length", "0"},
  2862. }
  2863. if !reflect.DeepEqual(goth, wanth) {
  2864. t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2865. }
  2866. })
  2867. }
  2868. func BenchmarkServerGets(b *testing.B) {
  2869. defer disableGoroutineTracking()()
  2870. b.ReportAllocs()
  2871. const msg = "Hello, world"
  2872. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2873. io.WriteString(w, msg)
  2874. })
  2875. defer st.Close()
  2876. st.greet()
  2877. // Give the server quota to reply. (plus it has the 64KB)
  2878. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  2879. b.Fatal(err)
  2880. }
  2881. for i := 0; i < b.N; i++ {
  2882. id := 1 + uint32(i)*2
  2883. st.writeHeaders(HeadersFrameParam{
  2884. StreamID: id,
  2885. BlockFragment: st.encodeHeader(),
  2886. EndStream: true,
  2887. EndHeaders: true,
  2888. })
  2889. st.wantHeaders()
  2890. df := st.wantData()
  2891. if !df.StreamEnded() {
  2892. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  2893. }
  2894. }
  2895. }
  2896. func BenchmarkServerPosts(b *testing.B) {
  2897. defer disableGoroutineTracking()()
  2898. b.ReportAllocs()
  2899. const msg = "Hello, world"
  2900. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2901. // Consume the (empty) body from th peer before replying, otherwise
  2902. // the server will sometimes (depending on scheduling) send the peer a
  2903. // a RST_STREAM with the CANCEL error code.
  2904. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  2905. b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  2906. }
  2907. io.WriteString(w, msg)
  2908. })
  2909. defer st.Close()
  2910. st.greet()
  2911. // Give the server quota to reply. (plus it has the 64KB)
  2912. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  2913. b.Fatal(err)
  2914. }
  2915. for i := 0; i < b.N; i++ {
  2916. id := 1 + uint32(i)*2
  2917. st.writeHeaders(HeadersFrameParam{
  2918. StreamID: id,
  2919. BlockFragment: st.encodeHeader(":method", "POST"),
  2920. EndStream: false,
  2921. EndHeaders: true,
  2922. })
  2923. st.writeData(id, true, nil)
  2924. st.wantHeaders()
  2925. df := st.wantData()
  2926. if !df.StreamEnded() {
  2927. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  2928. }
  2929. }
  2930. }
  2931. // Send a stream of messages from server to client in separate data frames.
  2932. // Brings up performance issues seen in long streams.
  2933. // Created to show problem in go issue #18502
  2934. func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) {
  2935. benchmarkServerToClientStream(b)
  2936. }
  2937. // Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8
  2938. // Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer.
  2939. func BenchmarkServerToClientStreamReuseFrames(b *testing.B) {
  2940. benchmarkServerToClientStream(b, optFramerReuseFrames)
  2941. }
  2942. func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) {
  2943. defer disableGoroutineTracking()()
  2944. b.ReportAllocs()
  2945. const msgLen = 1
  2946. // default window size
  2947. const windowSize = 1<<16 - 1
  2948. // next message to send from the server and for the client to expect
  2949. nextMsg := func(i int) []byte {
  2950. msg := make([]byte, msgLen)
  2951. msg[0] = byte(i)
  2952. if len(msg) != msgLen {
  2953. panic("invalid test setup msg length")
  2954. }
  2955. return msg
  2956. }
  2957. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2958. // Consume the (empty) body from th peer before replying, otherwise
  2959. // the server will sometimes (depending on scheduling) send the peer a
  2960. // a RST_STREAM with the CANCEL error code.
  2961. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  2962. b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  2963. }
  2964. for i := 0; i < b.N; i += 1 {
  2965. w.Write(nextMsg(i))
  2966. w.(http.Flusher).Flush()
  2967. }
  2968. }, newServerOpts...)
  2969. defer st.Close()
  2970. st.greet()
  2971. const id = uint32(1)
  2972. st.writeHeaders(HeadersFrameParam{
  2973. StreamID: id,
  2974. BlockFragment: st.encodeHeader(":method", "POST"),
  2975. EndStream: false,
  2976. EndHeaders: true,
  2977. })
  2978. st.writeData(id, true, nil)
  2979. st.wantHeaders()
  2980. var pendingWindowUpdate = uint32(0)
  2981. for i := 0; i < b.N; i += 1 {
  2982. expected := nextMsg(i)
  2983. df := st.wantData()
  2984. if bytes.Compare(expected, df.data) != 0 {
  2985. b.Fatalf("Bad message received; want %v; got %v", expected, df.data)
  2986. }
  2987. // try to send infrequent but large window updates so they don't overwhelm the test
  2988. pendingWindowUpdate += uint32(len(df.data))
  2989. if pendingWindowUpdate >= windowSize/2 {
  2990. if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil {
  2991. b.Fatal(err)
  2992. }
  2993. if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil {
  2994. b.Fatal(err)
  2995. }
  2996. pendingWindowUpdate = 0
  2997. }
  2998. }
  2999. df := st.wantData()
  3000. if !df.StreamEnded() {
  3001. b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  3002. }
  3003. }
  3004. // go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53
  3005. // Verify we don't hang.
  3006. func TestIssue53(t *testing.T) {
  3007. const data = "PRI * HTTP/2.0\r\n\r\nSM" +
  3008. "\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad"
  3009. s := &http.Server{
  3010. ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags),
  3011. Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  3012. w.Write([]byte("hello"))
  3013. }),
  3014. }
  3015. s2 := &Server{
  3016. MaxReadFrameSize: 1 << 16,
  3017. PermitProhibitedCipherSuites: true,
  3018. }
  3019. c := &issue53Conn{[]byte(data), false, false}
  3020. s2.ServeConn(c, &ServeConnOpts{BaseConfig: s})
  3021. if !c.closed {
  3022. t.Fatal("connection is not closed")
  3023. }
  3024. }
  3025. type issue53Conn struct {
  3026. data []byte
  3027. closed bool
  3028. written bool
  3029. }
  3030. func (c *issue53Conn) Read(b []byte) (n int, err error) {
  3031. if len(c.data) == 0 {
  3032. return 0, io.EOF
  3033. }
  3034. n = copy(b, c.data)
  3035. c.data = c.data[n:]
  3036. return
  3037. }
  3038. func (c *issue53Conn) Write(b []byte) (n int, err error) {
  3039. c.written = true
  3040. return len(b), nil
  3041. }
  3042. func (c *issue53Conn) Close() error {
  3043. c.closed = true
  3044. return nil
  3045. }
  3046. func (c *issue53Conn) LocalAddr() net.Addr {
  3047. return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  3048. }
  3049. func (c *issue53Conn) RemoteAddr() net.Addr {
  3050. return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  3051. }
  3052. func (c *issue53Conn) SetDeadline(t time.Time) error { return nil }
  3053. func (c *issue53Conn) SetReadDeadline(t time.Time) error { return nil }
  3054. func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil }
  3055. // golang.org/issue/33839
  3056. func TestServeConnOptsNilReceiverBehavior(t *testing.T) {
  3057. defer func() {
  3058. if r := recover(); r != nil {
  3059. t.Errorf("got a panic that should not happen: %v", r)
  3060. }
  3061. }()
  3062. var o *ServeConnOpts
  3063. if o.context() == nil {
  3064. t.Error("o.context should not return nil")
  3065. }
  3066. if o.baseConfig() == nil {
  3067. t.Error("o.baseConfig should not return nil")
  3068. }
  3069. if o.handler() == nil {
  3070. t.Error("o.handler should not return nil")
  3071. }
  3072. }
  3073. // golang.org/issue/12895
  3074. func TestConfigureServer(t *testing.T) {
  3075. tests := []struct {
  3076. name string
  3077. tlsConfig *tls.Config
  3078. wantErr string
  3079. }{
  3080. {
  3081. name: "empty server",
  3082. },
  3083. {
  3084. name: "just the required cipher suite",
  3085. tlsConfig: &tls.Config{
  3086. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  3087. },
  3088. },
  3089. {
  3090. name: "just the alternative required cipher suite",
  3091. tlsConfig: &tls.Config{
  3092. CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  3093. },
  3094. },
  3095. {
  3096. name: "missing required cipher suite",
  3097. tlsConfig: &tls.Config{
  3098. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
  3099. },
  3100. wantErr: "is missing an HTTP/2-required",
  3101. },
  3102. {
  3103. name: "required after bad",
  3104. tlsConfig: &tls.Config{
  3105. CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  3106. },
  3107. wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after",
  3108. },
  3109. {
  3110. name: "bad after required",
  3111. tlsConfig: &tls.Config{
  3112. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA},
  3113. },
  3114. },
  3115. }
  3116. for _, tt := range tests {
  3117. srv := &http.Server{TLSConfig: tt.tlsConfig}
  3118. err := ConfigureServer(srv, nil)
  3119. if (err != nil) != (tt.wantErr != "") {
  3120. if tt.wantErr != "" {
  3121. t.Errorf("%s: success, but want error", tt.name)
  3122. } else {
  3123. t.Errorf("%s: unexpected error: %v", tt.name, err)
  3124. }
  3125. }
  3126. if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) {
  3127. t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr)
  3128. }
  3129. if err == nil && !srv.TLSConfig.PreferServerCipherSuites {
  3130. t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name)
  3131. }
  3132. }
  3133. }
  3134. func TestServerRejectHeadWithBody(t *testing.T) {
  3135. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3136. // No response body.
  3137. })
  3138. defer st.Close()
  3139. st.greet()
  3140. st.writeHeaders(HeadersFrameParam{
  3141. StreamID: 1, // clients send odd numbers
  3142. BlockFragment: st.encodeHeader(":method", "HEAD"),
  3143. EndStream: false, // what we're testing, a bogus HEAD request with body
  3144. EndHeaders: true,
  3145. })
  3146. st.wantRSTStream(1, ErrCodeProtocol)
  3147. }
  3148. func TestServerNoAutoContentLengthOnHead(t *testing.T) {
  3149. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3150. // No response body. (or smaller than one frame)
  3151. })
  3152. defer st.Close()
  3153. st.greet()
  3154. st.writeHeaders(HeadersFrameParam{
  3155. StreamID: 1, // clients send odd numbers
  3156. BlockFragment: st.encodeHeader(":method", "HEAD"),
  3157. EndStream: true,
  3158. EndHeaders: true,
  3159. })
  3160. h := st.wantHeaders()
  3161. headers := st.decodeHeader(h.HeaderBlockFragment())
  3162. want := [][2]string{
  3163. {":status", "200"},
  3164. }
  3165. if !reflect.DeepEqual(headers, want) {
  3166. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3167. }
  3168. }
  3169. // golang.org/issue/13495
  3170. func TestServerNoDuplicateContentType(t *testing.T) {
  3171. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3172. w.Header()["Content-Type"] = []string{""}
  3173. fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
  3174. })
  3175. defer st.Close()
  3176. st.greet()
  3177. st.writeHeaders(HeadersFrameParam{
  3178. StreamID: 1,
  3179. BlockFragment: st.encodeHeader(),
  3180. EndStream: true,
  3181. EndHeaders: true,
  3182. })
  3183. h := st.wantHeaders()
  3184. headers := st.decodeHeader(h.HeaderBlockFragment())
  3185. want := [][2]string{
  3186. {":status", "200"},
  3187. {"content-type", ""},
  3188. {"content-length", "41"},
  3189. }
  3190. if !reflect.DeepEqual(headers, want) {
  3191. t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3192. }
  3193. }
  3194. func disableGoroutineTracking() (restore func()) {
  3195. old := DebugGoroutines
  3196. DebugGoroutines = false
  3197. return func() { DebugGoroutines = old }
  3198. }
  3199. func BenchmarkServer_GetRequest(b *testing.B) {
  3200. defer disableGoroutineTracking()()
  3201. b.ReportAllocs()
  3202. const msg = "Hello, world."
  3203. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3204. n, err := io.Copy(ioutil.Discard, r.Body)
  3205. if err != nil || n > 0 {
  3206. b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3207. }
  3208. io.WriteString(w, msg)
  3209. })
  3210. defer st.Close()
  3211. st.greet()
  3212. // Give the server quota to reply. (plus it has the 64KB)
  3213. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3214. b.Fatal(err)
  3215. }
  3216. hbf := st.encodeHeader(":method", "GET")
  3217. for i := 0; i < b.N; i++ {
  3218. streamID := uint32(1 + 2*i)
  3219. st.writeHeaders(HeadersFrameParam{
  3220. StreamID: streamID,
  3221. BlockFragment: hbf,
  3222. EndStream: true,
  3223. EndHeaders: true,
  3224. })
  3225. st.wantHeaders()
  3226. st.wantData()
  3227. }
  3228. }
  3229. func BenchmarkServer_PostRequest(b *testing.B) {
  3230. defer disableGoroutineTracking()()
  3231. b.ReportAllocs()
  3232. const msg = "Hello, world."
  3233. st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3234. n, err := io.Copy(ioutil.Discard, r.Body)
  3235. if err != nil || n > 0 {
  3236. b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3237. }
  3238. io.WriteString(w, msg)
  3239. })
  3240. defer st.Close()
  3241. st.greet()
  3242. // Give the server quota to reply. (plus it has the 64KB)
  3243. if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3244. b.Fatal(err)
  3245. }
  3246. hbf := st.encodeHeader(":method", "POST")
  3247. for i := 0; i < b.N; i++ {
  3248. streamID := uint32(1 + 2*i)
  3249. st.writeHeaders(HeadersFrameParam{
  3250. StreamID: streamID,
  3251. BlockFragment: hbf,
  3252. EndStream: false,
  3253. EndHeaders: true,
  3254. })
  3255. st.writeData(streamID, true, nil)
  3256. st.wantHeaders()
  3257. st.wantData()
  3258. }
  3259. }
  3260. type connStateConn struct {
  3261. net.Conn
  3262. cs tls.ConnectionState
  3263. }
  3264. func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs }
  3265. // golang.org/issue/12737 -- handle any net.Conn, not just
  3266. // *tls.Conn.
  3267. func TestServerHandleCustomConn(t *testing.T) {
  3268. var s Server
  3269. c1, c2 := net.Pipe()
  3270. clientDone := make(chan struct{})
  3271. handlerDone := make(chan struct{})
  3272. var req *http.Request
  3273. go func() {
  3274. defer close(clientDone)
  3275. defer c2.Close()
  3276. fr := NewFramer(c2, c2)
  3277. io.WriteString(c2, ClientPreface)
  3278. fr.WriteSettings()
  3279. fr.WriteSettingsAck()
  3280. f, err := fr.ReadFrame()
  3281. if err != nil {
  3282. t.Error(err)
  3283. return
  3284. }
  3285. if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() {
  3286. t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f))
  3287. return
  3288. }
  3289. f, err = fr.ReadFrame()
  3290. if err != nil {
  3291. t.Error(err)
  3292. return
  3293. }
  3294. if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() {
  3295. t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f))
  3296. return
  3297. }
  3298. var henc hpackEncoder
  3299. fr.WriteHeaders(HeadersFrameParam{
  3300. StreamID: 1,
  3301. BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"),
  3302. EndStream: true,
  3303. EndHeaders: true,
  3304. })
  3305. go io.Copy(ioutil.Discard, c2)
  3306. <-handlerDone
  3307. }()
  3308. const testString = "my custom ConnectionState"
  3309. fakeConnState := tls.ConnectionState{
  3310. ServerName: testString,
  3311. Version: tls.VersionTLS12,
  3312. CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  3313. }
  3314. go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{
  3315. BaseConfig: &http.Server{
  3316. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3317. defer close(handlerDone)
  3318. req = r
  3319. }),
  3320. }})
  3321. select {
  3322. case <-clientDone:
  3323. case <-time.After(5 * time.Second):
  3324. t.Fatal("timeout waiting for handler")
  3325. }
  3326. if req.TLS == nil {
  3327. t.Fatalf("Request.TLS is nil. Got: %#v", req)
  3328. }
  3329. if req.TLS.ServerName != testString {
  3330. t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString)
  3331. }
  3332. }
  3333. // golang.org/issue/14214
  3334. func TestServer_Rejects_ConnHeaders(t *testing.T) {
  3335. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3336. t.Error("should not get to Handler")
  3337. })
  3338. defer st.Close()
  3339. st.greet()
  3340. st.bodylessReq1("connection", "foo")
  3341. hf := st.wantHeaders()
  3342. goth := st.decodeHeader(hf.HeaderBlockFragment())
  3343. wanth := [][2]string{
  3344. {":status", "400"},
  3345. {"content-type", "text/plain; charset=utf-8"},
  3346. {"x-content-type-options", "nosniff"},
  3347. {"content-length", "51"},
  3348. }
  3349. if !reflect.DeepEqual(goth, wanth) {
  3350. t.Errorf("Got headers %v; want %v", goth, wanth)
  3351. }
  3352. }
  3353. type hpackEncoder struct {
  3354. enc *hpack.Encoder
  3355. buf bytes.Buffer
  3356. }
  3357. func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte {
  3358. if len(headers)%2 == 1 {
  3359. panic("odd number of kv args")
  3360. }
  3361. he.buf.Reset()
  3362. if he.enc == nil {
  3363. he.enc = hpack.NewEncoder(&he.buf)
  3364. }
  3365. for len(headers) > 0 {
  3366. k, v := headers[0], headers[1]
  3367. err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  3368. if err != nil {
  3369. t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
  3370. }
  3371. headers = headers[2:]
  3372. }
  3373. return he.buf.Bytes()
  3374. }
  3375. func TestCheckValidHTTP2Request(t *testing.T) {
  3376. tests := []struct {
  3377. h http.Header
  3378. want error
  3379. }{
  3380. {
  3381. h: http.Header{"Te": {"trailers"}},
  3382. want: nil,
  3383. },
  3384. {
  3385. h: http.Header{"Te": {"trailers", "bogus"}},
  3386. want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`),
  3387. },
  3388. {
  3389. h: http.Header{"Foo": {""}},
  3390. want: nil,
  3391. },
  3392. {
  3393. h: http.Header{"Connection": {""}},
  3394. want: errors.New(`request header "Connection" is not valid in HTTP/2`),
  3395. },
  3396. {
  3397. h: http.Header{"Proxy-Connection": {""}},
  3398. want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`),
  3399. },
  3400. {
  3401. h: http.Header{"Keep-Alive": {""}},
  3402. want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`),
  3403. },
  3404. {
  3405. h: http.Header{"Upgrade": {""}},
  3406. want: errors.New(`request header "Upgrade" is not valid in HTTP/2`),
  3407. },
  3408. }
  3409. for i, tt := range tests {
  3410. got := checkValidHTTP2RequestHeaders(tt.h)
  3411. if !equalError(got, tt.want) {
  3412. t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want)
  3413. }
  3414. }
  3415. }
  3416. // golang.org/issue/14030
  3417. func TestExpect100ContinueAfterHandlerWrites(t *testing.T) {
  3418. const msg = "Hello"
  3419. const msg2 = "World"
  3420. doRead := make(chan bool, 1)
  3421. defer close(doRead) // fallback cleanup
  3422. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3423. io.WriteString(w, msg)
  3424. w.(http.Flusher).Flush()
  3425. // Do a read, which might force a 100-continue status to be sent.
  3426. <-doRead
  3427. r.Body.Read(make([]byte, 10))
  3428. io.WriteString(w, msg2)
  3429. }, optOnlyServer)
  3430. defer st.Close()
  3431. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3432. defer tr.CloseIdleConnections()
  3433. req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20))
  3434. req.Header.Set("Expect", "100-continue")
  3435. res, err := tr.RoundTrip(req)
  3436. if err != nil {
  3437. t.Fatal(err)
  3438. }
  3439. defer res.Body.Close()
  3440. buf := make([]byte, len(msg))
  3441. if _, err := io.ReadFull(res.Body, buf); err != nil {
  3442. t.Fatal(err)
  3443. }
  3444. if string(buf) != msg {
  3445. t.Fatalf("msg = %q; want %q", buf, msg)
  3446. }
  3447. doRead <- true
  3448. if _, err := io.ReadFull(res.Body, buf); err != nil {
  3449. t.Fatal(err)
  3450. }
  3451. if string(buf) != msg2 {
  3452. t.Fatalf("second msg = %q; want %q", buf, msg2)
  3453. }
  3454. }
  3455. type funcReader func([]byte) (n int, err error)
  3456. func (f funcReader) Read(p []byte) (n int, err error) { return f(p) }
  3457. // golang.org/issue/16481 -- return flow control when streams close with unread data.
  3458. // (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport)
  3459. func TestUnreadFlowControlReturned_Server(t *testing.T) {
  3460. for _, tt := range []struct {
  3461. name string
  3462. reqFn func(r *http.Request)
  3463. }{
  3464. {
  3465. "body-open",
  3466. func(r *http.Request) {},
  3467. },
  3468. {
  3469. "body-closed",
  3470. func(r *http.Request) {
  3471. r.Body.Close()
  3472. },
  3473. },
  3474. {
  3475. "read-1-byte-and-close",
  3476. func(r *http.Request) {
  3477. b := make([]byte, 1)
  3478. r.Body.Read(b)
  3479. r.Body.Close()
  3480. },
  3481. },
  3482. } {
  3483. t.Run(tt.name, func(t *testing.T) {
  3484. unblock := make(chan bool, 1)
  3485. defer close(unblock)
  3486. timeOut := time.NewTimer(5 * time.Second)
  3487. defer timeOut.Stop()
  3488. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3489. // Don't read the 16KB request body. Wait until the client's
  3490. // done sending it and then return. This should cause the Server
  3491. // to then return those 16KB of flow control to the client.
  3492. tt.reqFn(r)
  3493. select {
  3494. case <-unblock:
  3495. case <-timeOut.C:
  3496. t.Fatal(tt.name, "timedout")
  3497. }
  3498. }, optOnlyServer)
  3499. defer st.Close()
  3500. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3501. defer tr.CloseIdleConnections()
  3502. // This previously hung on the 4th iteration.
  3503. iters := 100
  3504. if testing.Short() {
  3505. iters = 20
  3506. }
  3507. for i := 0; i < iters; i++ {
  3508. body := io.MultiReader(
  3509. io.LimitReader(neverEnding('A'), 16<<10),
  3510. funcReader(func([]byte) (n int, err error) {
  3511. unblock <- true
  3512. return 0, io.EOF
  3513. }),
  3514. )
  3515. req, _ := http.NewRequest("POST", st.ts.URL, body)
  3516. res, err := tr.RoundTrip(req)
  3517. if err != nil {
  3518. t.Fatal(tt.name, err)
  3519. }
  3520. res.Body.Close()
  3521. }
  3522. })
  3523. }
  3524. }
  3525. func TestServerIdleTimeout(t *testing.T) {
  3526. if testing.Short() {
  3527. t.Skip("skipping in short mode")
  3528. }
  3529. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3530. }, func(h2s *Server) {
  3531. h2s.IdleTimeout = 500 * time.Millisecond
  3532. })
  3533. defer st.Close()
  3534. st.greet()
  3535. ga := st.wantGoAway()
  3536. if ga.ErrCode != ErrCodeNo {
  3537. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3538. }
  3539. }
  3540. func TestServerIdleTimeout_AfterRequest(t *testing.T) {
  3541. if testing.Short() {
  3542. t.Skip("skipping in short mode")
  3543. }
  3544. const timeout = 250 * time.Millisecond
  3545. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3546. time.Sleep(timeout * 2)
  3547. }, func(h2s *Server) {
  3548. h2s.IdleTimeout = timeout
  3549. })
  3550. defer st.Close()
  3551. st.greet()
  3552. // Send a request which takes twice the timeout. Verifies the
  3553. // idle timeout doesn't fire while we're in a request:
  3554. st.bodylessReq1()
  3555. st.wantHeaders()
  3556. // But the idle timeout should be rearmed after the request
  3557. // is done:
  3558. ga := st.wantGoAway()
  3559. if ga.ErrCode != ErrCodeNo {
  3560. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3561. }
  3562. }
  3563. // grpc-go closes the Request.Body currently with a Read.
  3564. // Verify that it doesn't race.
  3565. // See https://github.com/grpc/grpc-go/pull/938
  3566. func TestRequestBodyReadCloseRace(t *testing.T) {
  3567. for i := 0; i < 100; i++ {
  3568. body := &requestBody{
  3569. pipe: &pipe{
  3570. b: new(bytes.Buffer),
  3571. },
  3572. }
  3573. body.pipe.CloseWithError(io.EOF)
  3574. done := make(chan bool, 1)
  3575. buf := make([]byte, 10)
  3576. go func() {
  3577. time.Sleep(1 * time.Millisecond)
  3578. body.Close()
  3579. done <- true
  3580. }()
  3581. body.Read(buf)
  3582. <-done
  3583. }
  3584. }
  3585. func TestIssue20704Race(t *testing.T) {
  3586. if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
  3587. t.Skip("skipping in short mode")
  3588. }
  3589. const (
  3590. itemSize = 1 << 10
  3591. itemCount = 100
  3592. )
  3593. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3594. for i := 0; i < itemCount; i++ {
  3595. _, err := w.Write(make([]byte, itemSize))
  3596. if err != nil {
  3597. return
  3598. }
  3599. }
  3600. }, optOnlyServer)
  3601. defer st.Close()
  3602. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3603. defer tr.CloseIdleConnections()
  3604. cl := &http.Client{Transport: tr}
  3605. for i := 0; i < 1000; i++ {
  3606. resp, err := cl.Get(st.ts.URL)
  3607. if err != nil {
  3608. t.Fatal(err)
  3609. }
  3610. // Force a RST stream to the server by closing without
  3611. // reading the body:
  3612. resp.Body.Close()
  3613. }
  3614. }
  3615. func TestServer_Rejects_TooSmall(t *testing.T) {
  3616. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3617. ioutil.ReadAll(r.Body)
  3618. return nil
  3619. }, func(st *serverTester) {
  3620. st.writeHeaders(HeadersFrameParam{
  3621. StreamID: 1, // clients send odd numbers
  3622. BlockFragment: st.encodeHeader(
  3623. ":method", "POST",
  3624. "content-length", "4",
  3625. ),
  3626. EndStream: false, // to say DATA frames are coming
  3627. EndHeaders: true,
  3628. })
  3629. st.writeData(1, true, []byte("12345"))
  3630. st.wantRSTStream(1, ErrCodeProtocol)
  3631. })
  3632. }
  3633. // Tests that a handler setting "Connection: close" results in a GOAWAY being sent,
  3634. // and the connection still completing.
  3635. func TestServerHandlerConnectionClose(t *testing.T) {
  3636. unblockHandler := make(chan bool, 1)
  3637. defer close(unblockHandler) // backup; in case of errors
  3638. testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3639. w.Header().Set("Connection", "close")
  3640. w.Header().Set("Foo", "bar")
  3641. w.(http.Flusher).Flush()
  3642. <-unblockHandler
  3643. return nil
  3644. }, func(st *serverTester) {
  3645. st.writeHeaders(HeadersFrameParam{
  3646. StreamID: 1,
  3647. BlockFragment: st.encodeHeader(),
  3648. EndStream: true,
  3649. EndHeaders: true,
  3650. })
  3651. var sawGoAway bool
  3652. var sawRes bool
  3653. for {
  3654. f, err := st.readFrame()
  3655. if err == io.EOF {
  3656. break
  3657. }
  3658. if err != nil {
  3659. t.Fatal(err)
  3660. }
  3661. switch f := f.(type) {
  3662. case *GoAwayFrame:
  3663. sawGoAway = true
  3664. unblockHandler <- true
  3665. if f.LastStreamID != 1 || f.ErrCode != ErrCodeNo {
  3666. t.Errorf("unexpected GOAWAY frame: %v", summarizeFrame(f))
  3667. }
  3668. case *HeadersFrame:
  3669. goth := st.decodeHeader(f.HeaderBlockFragment())
  3670. wanth := [][2]string{
  3671. {":status", "200"},
  3672. {"foo", "bar"},
  3673. }
  3674. if !reflect.DeepEqual(goth, wanth) {
  3675. t.Errorf("got headers %v; want %v", goth, wanth)
  3676. }
  3677. sawRes = true
  3678. case *DataFrame:
  3679. if f.StreamID != 1 || !f.StreamEnded() || len(f.Data()) != 0 {
  3680. t.Errorf("unexpected DATA frame: %v", summarizeFrame(f))
  3681. }
  3682. default:
  3683. t.Logf("unexpected frame: %v", summarizeFrame(f))
  3684. }
  3685. }
  3686. if !sawGoAway {
  3687. t.Errorf("didn't see GOAWAY")
  3688. }
  3689. if !sawRes {
  3690. t.Errorf("didn't see response")
  3691. }
  3692. })
  3693. }
  3694. func TestServer_Headers_HalfCloseRemote(t *testing.T) {
  3695. var st *serverTester
  3696. writeData := make(chan bool)
  3697. writeHeaders := make(chan bool)
  3698. leaveHandler := make(chan bool)
  3699. st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3700. if st.stream(1) == nil {
  3701. t.Errorf("nil stream 1 in handler")
  3702. }
  3703. if got, want := st.streamState(1), stateOpen; got != want {
  3704. t.Errorf("in handler, state is %v; want %v", got, want)
  3705. }
  3706. writeData <- true
  3707. if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF {
  3708. t.Errorf("body read = %d, %v; want 0, EOF", n, err)
  3709. }
  3710. if got, want := st.streamState(1), stateHalfClosedRemote; got != want {
  3711. t.Errorf("in handler, state is %v; want %v", got, want)
  3712. }
  3713. writeHeaders <- true
  3714. <-leaveHandler
  3715. })
  3716. st.greet()
  3717. st.writeHeaders(HeadersFrameParam{
  3718. StreamID: 1,
  3719. BlockFragment: st.encodeHeader(),
  3720. EndStream: false, // keep it open
  3721. EndHeaders: true,
  3722. })
  3723. <-writeData
  3724. st.writeData(1, true, nil)
  3725. <-writeHeaders
  3726. st.writeHeaders(HeadersFrameParam{
  3727. StreamID: 1,
  3728. BlockFragment: st.encodeHeader(),
  3729. EndStream: false, // keep it open
  3730. EndHeaders: true,
  3731. })
  3732. defer close(leaveHandler)
  3733. st.wantRSTStream(1, ErrCodeStreamClosed)
  3734. }
  3735. func TestServerGracefulShutdown(t *testing.T) {
  3736. var st *serverTester
  3737. handlerDone := make(chan struct{})
  3738. st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3739. defer close(handlerDone)
  3740. go st.ts.Config.Shutdown(context.Background())
  3741. ga := st.wantGoAway()
  3742. if ga.ErrCode != ErrCodeNo {
  3743. t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3744. }
  3745. if ga.LastStreamID != 1 {
  3746. t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID)
  3747. }
  3748. w.Header().Set("x-foo", "bar")
  3749. })
  3750. defer st.Close()
  3751. st.greet()
  3752. st.bodylessReq1()
  3753. select {
  3754. case <-handlerDone:
  3755. case <-time.After(5 * time.Second):
  3756. t.Fatalf("server did not shutdown?")
  3757. }
  3758. hf := st.wantHeaders()
  3759. goth := st.decodeHeader(hf.HeaderBlockFragment())
  3760. wanth := [][2]string{
  3761. {":status", "200"},
  3762. {"x-foo", "bar"},
  3763. {"content-length", "0"},
  3764. }
  3765. if !reflect.DeepEqual(goth, wanth) {
  3766. t.Errorf("Got headers %v; want %v", goth, wanth)
  3767. }
  3768. n, err := st.cc.Read([]byte{0})
  3769. if n != 0 || err == nil {
  3770. t.Errorf("Read = %v, %v; want 0, non-nil", n, err)
  3771. }
  3772. }
  3773. // Issue 31753: don't sniff when Content-Encoding is set
  3774. func TestContentEncodingNoSniffing(t *testing.T) {
  3775. type resp struct {
  3776. name string
  3777. body []byte
  3778. // setting Content-Encoding as an interface instead of a string
  3779. // directly, so as to differentiate between 3 states:
  3780. // unset, empty string "" and set string "foo/bar".
  3781. contentEncoding interface{}
  3782. wantContentType string
  3783. }
  3784. resps := []*resp{
  3785. {
  3786. name: "gzip content-encoding, gzipped", // don't sniff.
  3787. contentEncoding: "application/gzip",
  3788. wantContentType: "",
  3789. body: func() []byte {
  3790. buf := new(bytes.Buffer)
  3791. gzw := gzip.NewWriter(buf)
  3792. gzw.Write([]byte("doctype html><p>Hello</p>"))
  3793. gzw.Close()
  3794. return buf.Bytes()
  3795. }(),
  3796. },
  3797. {
  3798. name: "zlib content-encoding, zlibbed", // don't sniff.
  3799. contentEncoding: "application/zlib",
  3800. wantContentType: "",
  3801. body: func() []byte {
  3802. buf := new(bytes.Buffer)
  3803. zw := zlib.NewWriter(buf)
  3804. zw.Write([]byte("doctype html><p>Hello</p>"))
  3805. zw.Close()
  3806. return buf.Bytes()
  3807. }(),
  3808. },
  3809. {
  3810. name: "no content-encoding", // must sniff.
  3811. wantContentType: "application/x-gzip",
  3812. body: func() []byte {
  3813. buf := new(bytes.Buffer)
  3814. gzw := gzip.NewWriter(buf)
  3815. gzw.Write([]byte("doctype html><p>Hello</p>"))
  3816. gzw.Close()
  3817. return buf.Bytes()
  3818. }(),
  3819. },
  3820. {
  3821. name: "phony content-encoding", // don't sniff.
  3822. contentEncoding: "foo/bar",
  3823. body: []byte("doctype html><p>Hello</p>"),
  3824. },
  3825. {
  3826. name: "empty but set content-encoding",
  3827. contentEncoding: "",
  3828. wantContentType: "audio/mpeg",
  3829. body: []byte("ID3"),
  3830. },
  3831. }
  3832. tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3833. defer tr.CloseIdleConnections()
  3834. for _, tt := range resps {
  3835. t.Run(tt.name, func(t *testing.T) {
  3836. st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3837. if tt.contentEncoding != nil {
  3838. w.Header().Set("Content-Encoding", tt.contentEncoding.(string))
  3839. }
  3840. w.Write(tt.body)
  3841. }, optOnlyServer)
  3842. defer st.Close()
  3843. req, _ := http.NewRequest("GET", st.ts.URL, nil)
  3844. res, err := tr.RoundTrip(req)
  3845. if err != nil {
  3846. t.Fatalf("Failed to fetch URL: %v", err)
  3847. }
  3848. defer res.Body.Close()
  3849. if g, w := res.Header.Get("Content-Encoding"), tt.contentEncoding; g != w {
  3850. if w != nil { // The case where contentEncoding was set explicitly.
  3851. t.Errorf("Content-Encoding mismatch\n\tgot: %q\n\twant: %q", g, w)
  3852. } else if g != "" { // "" should be the equivalent when the contentEncoding is unset.
  3853. t.Errorf("Unexpected Content-Encoding %q", g)
  3854. }
  3855. }
  3856. if g, w := res.Header.Get("Content-Type"), tt.wantContentType; g != w {
  3857. t.Errorf("Content-Type mismatch\n\tgot: %q\n\twant: %q", g, w)
  3858. }
  3859. })
  3860. }
  3861. }