hpack_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 hpack
  5. import (
  6. "bufio"
  7. "bytes"
  8. "encoding/hex"
  9. "fmt"
  10. "math/rand"
  11. "reflect"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "testing"
  16. "time"
  17. )
  18. func TestStaticTable(t *testing.T) {
  19. fromSpec := `
  20. +-------+-----------------------------+---------------+
  21. | 1 | :authority | |
  22. | 2 | :method | GET |
  23. | 3 | :method | POST |
  24. | 4 | :path | / |
  25. | 5 | :path | /index.html |
  26. | 6 | :scheme | http |
  27. | 7 | :scheme | https |
  28. | 8 | :status | 200 |
  29. | 9 | :status | 204 |
  30. | 10 | :status | 206 |
  31. | 11 | :status | 304 |
  32. | 12 | :status | 400 |
  33. | 13 | :status | 404 |
  34. | 14 | :status | 500 |
  35. | 15 | accept-charset | |
  36. | 16 | accept-encoding | gzip, deflate |
  37. | 17 | accept-language | |
  38. | 18 | accept-ranges | |
  39. | 19 | accept | |
  40. | 20 | access-control-allow-origin | |
  41. | 21 | age | |
  42. | 22 | allow | |
  43. | 23 | authorization | |
  44. | 24 | cache-control | |
  45. | 25 | content-disposition | |
  46. | 26 | content-encoding | |
  47. | 27 | content-language | |
  48. | 28 | content-length | |
  49. | 29 | content-location | |
  50. | 30 | content-range | |
  51. | 31 | content-type | |
  52. | 32 | cookie | |
  53. | 33 | date | |
  54. | 34 | etag | |
  55. | 35 | expect | |
  56. | 36 | expires | |
  57. | 37 | from | |
  58. | 38 | host | |
  59. | 39 | if-match | |
  60. | 40 | if-modified-since | |
  61. | 41 | if-none-match | |
  62. | 42 | if-range | |
  63. | 43 | if-unmodified-since | |
  64. | 44 | last-modified | |
  65. | 45 | link | |
  66. | 46 | location | |
  67. | 47 | max-forwards | |
  68. | 48 | proxy-authenticate | |
  69. | 49 | proxy-authorization | |
  70. | 50 | range | |
  71. | 51 | referer | |
  72. | 52 | refresh | |
  73. | 53 | retry-after | |
  74. | 54 | server | |
  75. | 55 | set-cookie | |
  76. | 56 | strict-transport-security | |
  77. | 57 | transfer-encoding | |
  78. | 58 | user-agent | |
  79. | 59 | vary | |
  80. | 60 | via | |
  81. | 61 | www-authenticate | |
  82. +-------+-----------------------------+---------------+
  83. `
  84. bs := bufio.NewScanner(strings.NewReader(fromSpec))
  85. re := regexp.MustCompile(`\| (\d+)\s+\| (\S+)\s*\| (\S(.*\S)?)?\s+\|`)
  86. for bs.Scan() {
  87. l := bs.Text()
  88. if !strings.Contains(l, "|") {
  89. continue
  90. }
  91. m := re.FindStringSubmatch(l)
  92. if m == nil {
  93. continue
  94. }
  95. i, err := strconv.Atoi(m[1])
  96. if err != nil {
  97. t.Errorf("Bogus integer on line %q", l)
  98. continue
  99. }
  100. if i < 1 || i > len(staticTable) {
  101. t.Errorf("Bogus index %d on line %q", i, l)
  102. continue
  103. }
  104. if got, want := staticTable[i-1].Name, m[2]; got != want {
  105. t.Errorf("header index %d name = %q; want %q", i, got, want)
  106. }
  107. if got, want := staticTable[i-1].Value, m[3]; got != want {
  108. t.Errorf("header index %d value = %q; want %q", i, got, want)
  109. }
  110. }
  111. if err := bs.Err(); err != nil {
  112. t.Error(err)
  113. }
  114. }
  115. func (d *Decoder) mustAt(idx int) HeaderField {
  116. if hf, ok := d.at(uint64(idx)); !ok {
  117. panic(fmt.Sprintf("bogus index %d", idx))
  118. } else {
  119. return hf
  120. }
  121. }
  122. func TestDynamicTableAt(t *testing.T) {
  123. d := NewDecoder(4096, nil)
  124. at := d.mustAt
  125. if got, want := at(2), (pair(":method", "GET")); got != want {
  126. t.Errorf("at(2) = %v; want %v", got, want)
  127. }
  128. d.dynTab.add(pair("foo", "bar"))
  129. d.dynTab.add(pair("blake", "miz"))
  130. if got, want := at(len(staticTable)+1), (pair("blake", "miz")); got != want {
  131. t.Errorf("at(dyn 1) = %v; want %v", got, want)
  132. }
  133. if got, want := at(len(staticTable)+2), (pair("foo", "bar")); got != want {
  134. t.Errorf("at(dyn 2) = %v; want %v", got, want)
  135. }
  136. if got, want := at(3), (pair(":method", "POST")); got != want {
  137. t.Errorf("at(3) = %v; want %v", got, want)
  138. }
  139. }
  140. func TestDynamicTableSearch(t *testing.T) {
  141. dt := dynamicTable{}
  142. dt.setMaxSize(4096)
  143. dt.add(pair("foo", "bar"))
  144. dt.add(pair("blake", "miz"))
  145. dt.add(pair(":method", "GET"))
  146. tests := []struct {
  147. hf HeaderField
  148. wantI uint64
  149. wantMatch bool
  150. }{
  151. // Name and Value match
  152. {pair("foo", "bar"), 3, true},
  153. {pair(":method", "GET"), 1, true},
  154. // Only name match because of Sensitive == true
  155. {HeaderField{"blake", "miz", true}, 2, false},
  156. // Only Name matches
  157. {pair("foo", "..."), 3, false},
  158. {pair("blake", "..."), 2, false},
  159. {pair(":method", "..."), 1, false},
  160. // None match
  161. {pair("foo-", "bar"), 0, false},
  162. }
  163. for _, tt := range tests {
  164. if gotI, gotMatch := dt.search(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch {
  165. t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch)
  166. }
  167. }
  168. }
  169. func TestDynamicTableSizeEvict(t *testing.T) {
  170. d := NewDecoder(4096, nil)
  171. if want := uint32(0); d.dynTab.size != want {
  172. t.Fatalf("size = %d; want %d", d.dynTab.size, want)
  173. }
  174. add := d.dynTab.add
  175. add(pair("blake", "eats pizza"))
  176. if want := uint32(15 + 32); d.dynTab.size != want {
  177. t.Fatalf("after pizza, size = %d; want %d", d.dynTab.size, want)
  178. }
  179. add(pair("foo", "bar"))
  180. if want := uint32(15 + 32 + 6 + 32); d.dynTab.size != want {
  181. t.Fatalf("after foo bar, size = %d; want %d", d.dynTab.size, want)
  182. }
  183. d.dynTab.setMaxSize(15 + 32 + 1 /* slop */)
  184. if want := uint32(6 + 32); d.dynTab.size != want {
  185. t.Fatalf("after setMaxSize, size = %d; want %d", d.dynTab.size, want)
  186. }
  187. if got, want := d.mustAt(len(staticTable)+1), (pair("foo", "bar")); got != want {
  188. t.Errorf("at(dyn 1) = %v; want %v", got, want)
  189. }
  190. add(pair("long", strings.Repeat("x", 500)))
  191. if want := uint32(0); d.dynTab.size != want {
  192. t.Fatalf("after big one, size = %d; want %d", d.dynTab.size, want)
  193. }
  194. }
  195. func TestDecoderDecode(t *testing.T) {
  196. tests := []struct {
  197. name string
  198. in []byte
  199. want []HeaderField
  200. wantDynTab []HeaderField // newest entry first
  201. }{
  202. // C.2.1 Literal Header Field with Indexing
  203. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.1
  204. {"C.2.1", dehex("400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"),
  205. []HeaderField{pair("custom-key", "custom-header")},
  206. []HeaderField{pair("custom-key", "custom-header")},
  207. },
  208. // C.2.2 Literal Header Field without Indexing
  209. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.2
  210. {"C.2.2", dehex("040c 2f73 616d 706c 652f 7061 7468"),
  211. []HeaderField{pair(":path", "/sample/path")},
  212. []HeaderField{}},
  213. // C.2.3 Literal Header Field never Indexed
  214. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.3
  215. {"C.2.3", dehex("1008 7061 7373 776f 7264 0673 6563 7265 74"),
  216. []HeaderField{{"password", "secret", true}},
  217. []HeaderField{}},
  218. // C.2.4 Indexed Header Field
  219. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.4
  220. {"C.2.4", []byte("\x82"),
  221. []HeaderField{pair(":method", "GET")},
  222. []HeaderField{}},
  223. }
  224. for _, tt := range tests {
  225. d := NewDecoder(4096, nil)
  226. hf, err := d.DecodeFull(tt.in)
  227. if err != nil {
  228. t.Errorf("%s: %v", tt.name, err)
  229. continue
  230. }
  231. if !reflect.DeepEqual(hf, tt.want) {
  232. t.Errorf("%s: Got %v; want %v", tt.name, hf, tt.want)
  233. }
  234. gotDynTab := d.dynTab.reverseCopy()
  235. if !reflect.DeepEqual(gotDynTab, tt.wantDynTab) {
  236. t.Errorf("%s: dynamic table after = %v; want %v", tt.name, gotDynTab, tt.wantDynTab)
  237. }
  238. }
  239. }
  240. func (dt *dynamicTable) reverseCopy() (hf []HeaderField) {
  241. hf = make([]HeaderField, len(dt.ents))
  242. for i := range hf {
  243. hf[i] = dt.ents[len(dt.ents)-1-i]
  244. }
  245. return
  246. }
  247. type encAndWant struct {
  248. enc []byte
  249. want []HeaderField
  250. wantDynTab []HeaderField
  251. wantDynSize uint32
  252. }
  253. // C.3 Request Examples without Huffman Coding
  254. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.3
  255. func TestDecodeC3_NoHuffman(t *testing.T) {
  256. testDecodeSeries(t, 4096, []encAndWant{
  257. {dehex("8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d"),
  258. []HeaderField{
  259. pair(":method", "GET"),
  260. pair(":scheme", "http"),
  261. pair(":path", "/"),
  262. pair(":authority", "www.example.com"),
  263. },
  264. []HeaderField{
  265. pair(":authority", "www.example.com"),
  266. },
  267. 57,
  268. },
  269. {dehex("8286 84be 5808 6e6f 2d63 6163 6865"),
  270. []HeaderField{
  271. pair(":method", "GET"),
  272. pair(":scheme", "http"),
  273. pair(":path", "/"),
  274. pair(":authority", "www.example.com"),
  275. pair("cache-control", "no-cache"),
  276. },
  277. []HeaderField{
  278. pair("cache-control", "no-cache"),
  279. pair(":authority", "www.example.com"),
  280. },
  281. 110,
  282. },
  283. {dehex("8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65"),
  284. []HeaderField{
  285. pair(":method", "GET"),
  286. pair(":scheme", "https"),
  287. pair(":path", "/index.html"),
  288. pair(":authority", "www.example.com"),
  289. pair("custom-key", "custom-value"),
  290. },
  291. []HeaderField{
  292. pair("custom-key", "custom-value"),
  293. pair("cache-control", "no-cache"),
  294. pair(":authority", "www.example.com"),
  295. },
  296. 164,
  297. },
  298. })
  299. }
  300. // C.4 Request Examples with Huffman Coding
  301. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.4
  302. func TestDecodeC4_Huffman(t *testing.T) {
  303. testDecodeSeries(t, 4096, []encAndWant{
  304. {dehex("8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff"),
  305. []HeaderField{
  306. pair(":method", "GET"),
  307. pair(":scheme", "http"),
  308. pair(":path", "/"),
  309. pair(":authority", "www.example.com"),
  310. },
  311. []HeaderField{
  312. pair(":authority", "www.example.com"),
  313. },
  314. 57,
  315. },
  316. {dehex("8286 84be 5886 a8eb 1064 9cbf"),
  317. []HeaderField{
  318. pair(":method", "GET"),
  319. pair(":scheme", "http"),
  320. pair(":path", "/"),
  321. pair(":authority", "www.example.com"),
  322. pair("cache-control", "no-cache"),
  323. },
  324. []HeaderField{
  325. pair("cache-control", "no-cache"),
  326. pair(":authority", "www.example.com"),
  327. },
  328. 110,
  329. },
  330. {dehex("8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf"),
  331. []HeaderField{
  332. pair(":method", "GET"),
  333. pair(":scheme", "https"),
  334. pair(":path", "/index.html"),
  335. pair(":authority", "www.example.com"),
  336. pair("custom-key", "custom-value"),
  337. },
  338. []HeaderField{
  339. pair("custom-key", "custom-value"),
  340. pair("cache-control", "no-cache"),
  341. pair(":authority", "www.example.com"),
  342. },
  343. 164,
  344. },
  345. })
  346. }
  347. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.5
  348. // "This section shows several consecutive header lists, corresponding
  349. // to HTTP responses, on the same connection. The HTTP/2 setting
  350. // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256
  351. // octets, causing some evictions to occur."
  352. func TestDecodeC5_ResponsesNoHuff(t *testing.T) {
  353. testDecodeSeries(t, 256, []encAndWant{
  354. {dehex(`
  355. 4803 3330 3258 0770 7269 7661 7465 611d
  356. 4d6f 6e2c 2032 3120 4f63 7420 3230 3133
  357. 2032 303a 3133 3a32 3120 474d 546e 1768
  358. 7474 7073 3a2f 2f77 7777 2e65 7861 6d70
  359. 6c65 2e63 6f6d
  360. `),
  361. []HeaderField{
  362. pair(":status", "302"),
  363. pair("cache-control", "private"),
  364. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  365. pair("location", "https://www.example.com"),
  366. },
  367. []HeaderField{
  368. pair("location", "https://www.example.com"),
  369. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  370. pair("cache-control", "private"),
  371. pair(":status", "302"),
  372. },
  373. 222,
  374. },
  375. {dehex("4803 3330 37c1 c0bf"),
  376. []HeaderField{
  377. pair(":status", "307"),
  378. pair("cache-control", "private"),
  379. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  380. pair("location", "https://www.example.com"),
  381. },
  382. []HeaderField{
  383. pair(":status", "307"),
  384. pair("location", "https://www.example.com"),
  385. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  386. pair("cache-control", "private"),
  387. },
  388. 222,
  389. },
  390. {dehex(`
  391. 88c1 611d 4d6f 6e2c 2032 3120 4f63 7420
  392. 3230 3133 2032 303a 3133 3a32 3220 474d
  393. 54c0 5a04 677a 6970 7738 666f 6f3d 4153
  394. 444a 4b48 514b 425a 584f 5157 454f 5049
  395. 5541 5851 5745 4f49 553b 206d 6178 2d61
  396. 6765 3d33 3630 303b 2076 6572 7369 6f6e
  397. 3d31
  398. `),
  399. []HeaderField{
  400. pair(":status", "200"),
  401. pair("cache-control", "private"),
  402. pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"),
  403. pair("location", "https://www.example.com"),
  404. pair("content-encoding", "gzip"),
  405. pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"),
  406. },
  407. []HeaderField{
  408. pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"),
  409. pair("content-encoding", "gzip"),
  410. pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"),
  411. },
  412. 215,
  413. },
  414. })
  415. }
  416. // http://http2.github.io/http2-spec/compression.html#rfc.section.C.6
  417. // "This section shows the same examples as the previous section, but
  418. // using Huffman encoding for the literal values. The HTTP/2 setting
  419. // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256
  420. // octets, causing some evictions to occur. The eviction mechanism
  421. // uses the length of the decoded literal values, so the same
  422. // evictions occurs as in the previous section."
  423. func TestDecodeC6_ResponsesHuffman(t *testing.T) {
  424. testDecodeSeries(t, 256, []encAndWant{
  425. {dehex(`
  426. 4882 6402 5885 aec3 771a 4b61 96d0 7abe
  427. 9410 54d4 44a8 2005 9504 0b81 66e0 82a6
  428. 2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8
  429. e9ae 82ae 43d3
  430. `),
  431. []HeaderField{
  432. pair(":status", "302"),
  433. pair("cache-control", "private"),
  434. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  435. pair("location", "https://www.example.com"),
  436. },
  437. []HeaderField{
  438. pair("location", "https://www.example.com"),
  439. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  440. pair("cache-control", "private"),
  441. pair(":status", "302"),
  442. },
  443. 222,
  444. },
  445. {dehex("4883 640e ffc1 c0bf"),
  446. []HeaderField{
  447. pair(":status", "307"),
  448. pair("cache-control", "private"),
  449. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  450. pair("location", "https://www.example.com"),
  451. },
  452. []HeaderField{
  453. pair(":status", "307"),
  454. pair("location", "https://www.example.com"),
  455. pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
  456. pair("cache-control", "private"),
  457. },
  458. 222,
  459. },
  460. {dehex(`
  461. 88c1 6196 d07a be94 1054 d444 a820 0595
  462. 040b 8166 e084 a62d 1bff c05a 839b d9ab
  463. 77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b
  464. 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f
  465. 9587 3160 65c0 03ed 4ee5 b106 3d50 07
  466. `),
  467. []HeaderField{
  468. pair(":status", "200"),
  469. pair("cache-control", "private"),
  470. pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"),
  471. pair("location", "https://www.example.com"),
  472. pair("content-encoding", "gzip"),
  473. pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"),
  474. },
  475. []HeaderField{
  476. pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"),
  477. pair("content-encoding", "gzip"),
  478. pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"),
  479. },
  480. 215,
  481. },
  482. })
  483. }
  484. func testDecodeSeries(t *testing.T, size uint32, steps []encAndWant) {
  485. d := NewDecoder(size, nil)
  486. for i, step := range steps {
  487. hf, err := d.DecodeFull(step.enc)
  488. if err != nil {
  489. t.Fatalf("Error at step index %d: %v", i, err)
  490. }
  491. if !reflect.DeepEqual(hf, step.want) {
  492. t.Fatalf("At step index %d: Got headers %v; want %v", i, hf, step.want)
  493. }
  494. gotDynTab := d.dynTab.reverseCopy()
  495. if !reflect.DeepEqual(gotDynTab, step.wantDynTab) {
  496. t.Errorf("After step index %d, dynamic table = %v; want %v", i, gotDynTab, step.wantDynTab)
  497. }
  498. if d.dynTab.size != step.wantDynSize {
  499. t.Errorf("After step index %d, dynamic table size = %v; want %v", i, d.dynTab.size, step.wantDynSize)
  500. }
  501. }
  502. }
  503. func TestHuffmanDecodeExcessPadding(t *testing.T) {
  504. tests := [][]byte{
  505. {0xff}, // Padding Exceeds 7 bits
  506. {0x1f, 0xff}, // {"a", 1 byte excess padding}
  507. {0x1f, 0xff, 0xff}, // {"a", 2 byte excess padding}
  508. {0x1f, 0xff, 0xff, 0xff}, // {"a", 3 byte excess padding}
  509. {0xff, 0x9f, 0xff, 0xff, 0xff}, // {"a", 29 bit excess padding}
  510. {'R', 0xbc, '0', 0xff, 0xff, 0xff, 0xff}, // Padding ends on partial symbol.
  511. }
  512. for i, in := range tests {
  513. var buf bytes.Buffer
  514. if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman {
  515. t.Errorf("test-%d: decode(%q) = %v; want ErrInvalidHuffman", i, in, err)
  516. }
  517. }
  518. }
  519. func TestHuffmanDecodeEOS(t *testing.T) {
  520. in := []byte{0xff, 0xff, 0xff, 0xff, 0xfc} // {EOS, "?"}
  521. var buf bytes.Buffer
  522. if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman {
  523. t.Errorf("error = %v; want ErrInvalidHuffman", err)
  524. }
  525. }
  526. func TestHuffmanDecodeMaxLengthOnTrailingByte(t *testing.T) {
  527. in := []byte{0x00, 0x01} // {"0", "0", "0"}
  528. var buf bytes.Buffer
  529. if err := huffmanDecode(&buf, 2, in); err != ErrStringLength {
  530. t.Errorf("error = %v; want ErrStringLength", err)
  531. }
  532. }
  533. func TestHuffmanDecodeCorruptPadding(t *testing.T) {
  534. in := []byte{0x00}
  535. var buf bytes.Buffer
  536. if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman {
  537. t.Errorf("error = %v; want ErrInvalidHuffman", err)
  538. }
  539. }
  540. func TestHuffmanDecode(t *testing.T) {
  541. tests := []struct {
  542. inHex, want string
  543. }{
  544. {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"},
  545. {"a8eb 1064 9cbf", "no-cache"},
  546. {"25a8 49e9 5ba9 7d7f", "custom-key"},
  547. {"25a8 49e9 5bb8 e8b4 bf", "custom-value"},
  548. {"6402", "302"},
  549. {"aec3 771a 4b", "private"},
  550. {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"},
  551. {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"},
  552. {"9bd9 ab", "gzip"},
  553. {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07",
  554. "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"},
  555. }
  556. for i, tt := range tests {
  557. var buf bytes.Buffer
  558. in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1))
  559. if err != nil {
  560. t.Errorf("%d. hex input error: %v", i, err)
  561. continue
  562. }
  563. if _, err := HuffmanDecode(&buf, in); err != nil {
  564. t.Errorf("%d. decode error: %v", i, err)
  565. continue
  566. }
  567. if got := buf.String(); tt.want != got {
  568. t.Errorf("%d. decode = %q; want %q", i, got, tt.want)
  569. }
  570. }
  571. }
  572. func TestAppendHuffmanString(t *testing.T) {
  573. tests := []struct {
  574. in, want string
  575. }{
  576. {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"},
  577. {"no-cache", "a8eb 1064 9cbf"},
  578. {"custom-key", "25a8 49e9 5ba9 7d7f"},
  579. {"custom-value", "25a8 49e9 5bb8 e8b4 bf"},
  580. {"302", "6402"},
  581. {"private", "aec3 771a 4b"},
  582. {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"},
  583. {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"},
  584. {"gzip", "9bd9 ab"},
  585. {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
  586. "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"},
  587. }
  588. for i, tt := range tests {
  589. buf := []byte{}
  590. want := strings.Replace(tt.want, " ", "", -1)
  591. buf = AppendHuffmanString(buf, tt.in)
  592. if got := hex.EncodeToString(buf); want != got {
  593. t.Errorf("%d. encode = %q; want %q", i, got, want)
  594. }
  595. }
  596. }
  597. func TestHuffmanMaxStrLen(t *testing.T) {
  598. const msg = "Some string"
  599. huff := AppendHuffmanString(nil, msg)
  600. testGood := func(max int) {
  601. var out bytes.Buffer
  602. if err := huffmanDecode(&out, max, huff); err != nil {
  603. t.Errorf("For maxLen=%d, unexpected error: %v", max, err)
  604. }
  605. if out.String() != msg {
  606. t.Errorf("For maxLen=%d, out = %q; want %q", max, out.String(), msg)
  607. }
  608. }
  609. testGood(0)
  610. testGood(len(msg))
  611. testGood(len(msg) + 1)
  612. var out bytes.Buffer
  613. if err := huffmanDecode(&out, len(msg)-1, huff); err != ErrStringLength {
  614. t.Errorf("err = %v; want ErrStringLength", err)
  615. }
  616. }
  617. func TestHuffmanRoundtripStress(t *testing.T) {
  618. const Len = 50 // of uncompressed string
  619. input := make([]byte, Len)
  620. var output bytes.Buffer
  621. var huff []byte
  622. n := 5000
  623. if testing.Short() {
  624. n = 100
  625. }
  626. seed := time.Now().UnixNano()
  627. t.Logf("Seed = %v", seed)
  628. src := rand.New(rand.NewSource(seed))
  629. var encSize int64
  630. for i := 0; i < n; i++ {
  631. for l := range input {
  632. input[l] = byte(src.Intn(256))
  633. }
  634. huff = AppendHuffmanString(huff[:0], string(input))
  635. encSize += int64(len(huff))
  636. output.Reset()
  637. if err := huffmanDecode(&output, 0, huff); err != nil {
  638. t.Errorf("Failed to decode %q -> %q -> error %v", input, huff, err)
  639. continue
  640. }
  641. if !bytes.Equal(output.Bytes(), input) {
  642. t.Errorf("Roundtrip failure on %q -> %q -> %q", input, huff, output.Bytes())
  643. }
  644. }
  645. t.Logf("Compressed size of original: %0.02f%% (%v -> %v)", 100*(float64(encSize)/(Len*float64(n))), Len*n, encSize)
  646. }
  647. func TestHuffmanDecodeFuzz(t *testing.T) {
  648. const Len = 50 // of compressed
  649. var buf, zbuf bytes.Buffer
  650. n := 5000
  651. if testing.Short() {
  652. n = 100
  653. }
  654. seed := time.Now().UnixNano()
  655. t.Logf("Seed = %v", seed)
  656. src := rand.New(rand.NewSource(seed))
  657. numFail := 0
  658. for i := 0; i < n; i++ {
  659. zbuf.Reset()
  660. if i == 0 {
  661. // Start with at least one invalid one.
  662. zbuf.WriteString("00\x91\xff\xff\xff\xff\xc8")
  663. } else {
  664. for l := 0; l < Len; l++ {
  665. zbuf.WriteByte(byte(src.Intn(256)))
  666. }
  667. }
  668. buf.Reset()
  669. if err := huffmanDecode(&buf, 0, zbuf.Bytes()); err != nil {
  670. if err == ErrInvalidHuffman {
  671. numFail++
  672. continue
  673. }
  674. t.Errorf("Failed to decode %q: %v", zbuf.Bytes(), err)
  675. continue
  676. }
  677. }
  678. t.Logf("%0.02f%% are invalid (%d / %d)", 100*float64(numFail)/float64(n), numFail, n)
  679. if numFail < 1 {
  680. t.Error("expected at least one invalid huffman encoding (test starts with one)")
  681. }
  682. }
  683. func TestReadVarInt(t *testing.T) {
  684. type res struct {
  685. i uint64
  686. consumed int
  687. err error
  688. }
  689. tests := []struct {
  690. n byte
  691. p []byte
  692. want res
  693. }{
  694. // Fits in a byte:
  695. {1, []byte{0}, res{0, 1, nil}},
  696. {2, []byte{2}, res{2, 1, nil}},
  697. {3, []byte{6}, res{6, 1, nil}},
  698. {4, []byte{14}, res{14, 1, nil}},
  699. {5, []byte{30}, res{30, 1, nil}},
  700. {6, []byte{62}, res{62, 1, nil}},
  701. {7, []byte{126}, res{126, 1, nil}},
  702. {8, []byte{254}, res{254, 1, nil}},
  703. // Doesn't fit in a byte:
  704. {1, []byte{1}, res{0, 0, errNeedMore}},
  705. {2, []byte{3}, res{0, 0, errNeedMore}},
  706. {3, []byte{7}, res{0, 0, errNeedMore}},
  707. {4, []byte{15}, res{0, 0, errNeedMore}},
  708. {5, []byte{31}, res{0, 0, errNeedMore}},
  709. {6, []byte{63}, res{0, 0, errNeedMore}},
  710. {7, []byte{127}, res{0, 0, errNeedMore}},
  711. {8, []byte{255}, res{0, 0, errNeedMore}},
  712. // Ignoring top bits:
  713. {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111
  714. {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100
  715. {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101
  716. // Extra byte:
  717. {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte
  718. // Short a byte:
  719. {5, []byte{191, 154}, res{0, 0, errNeedMore}},
  720. // integer overflow:
  721. {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}},
  722. }
  723. for _, tt := range tests {
  724. i, remain, err := readVarInt(tt.n, tt.p)
  725. consumed := len(tt.p) - len(remain)
  726. got := res{i, consumed, err}
  727. if got != tt.want {
  728. t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want)
  729. }
  730. }
  731. }
  732. // Fuzz crash, originally reported at https://github.com/bradfitz/http2/issues/56
  733. func TestHuffmanFuzzCrash(t *testing.T) {
  734. got, err := HuffmanDecodeToString([]byte("00\x91\xff\xff\xff\xff\xc8"))
  735. if got != "" {
  736. t.Errorf("Got %q; want empty string", got)
  737. }
  738. if err != ErrInvalidHuffman {
  739. t.Errorf("Err = %v; want ErrInvalidHuffman", err)
  740. }
  741. }
  742. func dehex(s string) []byte {
  743. s = strings.Replace(s, " ", "", -1)
  744. s = strings.Replace(s, "\n", "", -1)
  745. b, err := hex.DecodeString(s)
  746. if err != nil {
  747. panic(err)
  748. }
  749. return b
  750. }
  751. func TestEmitEnabled(t *testing.T) {
  752. var buf bytes.Buffer
  753. enc := NewEncoder(&buf)
  754. enc.WriteField(HeaderField{Name: "foo", Value: "bar"})
  755. enc.WriteField(HeaderField{Name: "foo", Value: "bar"})
  756. numCallback := 0
  757. var dec *Decoder
  758. dec = NewDecoder(8<<20, func(HeaderField) {
  759. numCallback++
  760. dec.SetEmitEnabled(false)
  761. })
  762. if !dec.EmitEnabled() {
  763. t.Errorf("initial emit enabled = false; want true")
  764. }
  765. if _, err := dec.Write(buf.Bytes()); err != nil {
  766. t.Error(err)
  767. }
  768. if numCallback != 1 {
  769. t.Errorf("num callbacks = %d; want 1", numCallback)
  770. }
  771. if dec.EmitEnabled() {
  772. t.Errorf("emit enabled = true; want false")
  773. }
  774. }
  775. func TestSaveBufLimit(t *testing.T) {
  776. const maxStr = 1 << 10
  777. var got []HeaderField
  778. dec := NewDecoder(initialHeaderTableSize, func(hf HeaderField) {
  779. got = append(got, hf)
  780. })
  781. dec.SetMaxStringLength(maxStr)
  782. var frag []byte
  783. frag = append(frag[:0], encodeTypeByte(false, false))
  784. frag = appendVarInt(frag, 7, 3)
  785. frag = append(frag, "foo"...)
  786. frag = appendVarInt(frag, 7, 3)
  787. frag = append(frag, "bar"...)
  788. if _, err := dec.Write(frag); err != nil {
  789. t.Fatal(err)
  790. }
  791. want := []HeaderField{{Name: "foo", Value: "bar"}}
  792. if !reflect.DeepEqual(got, want) {
  793. t.Errorf("After small writes, got %v; want %v", got, want)
  794. }
  795. frag = append(frag[:0], encodeTypeByte(false, false))
  796. frag = appendVarInt(frag, 7, maxStr*3)
  797. frag = append(frag, make([]byte, maxStr*3)...)
  798. _, err := dec.Write(frag)
  799. if err != ErrStringLength {
  800. t.Fatalf("Write error = %v; want ErrStringLength", err)
  801. }
  802. }