server_test.go 102 KB

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