server_test.go 107 KB

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