server_test.go 92 KB

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