server_test.go 84 KB

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