server_test.go 99 KB

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