server_test.go 101 KB

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