hpack_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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 TestHuffmanDecode(t *testing.T) {
  504. tests := []struct {
  505. inHex, want string
  506. }{
  507. {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"},
  508. {"a8eb 1064 9cbf", "no-cache"},
  509. {"25a8 49e9 5ba9 7d7f", "custom-key"},
  510. {"25a8 49e9 5bb8 e8b4 bf", "custom-value"},
  511. {"6402", "302"},
  512. {"aec3 771a 4b", "private"},
  513. {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"},
  514. {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"},
  515. {"9bd9 ab", "gzip"},
  516. {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07",
  517. "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"},
  518. }
  519. for i, tt := range tests {
  520. var buf bytes.Buffer
  521. in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1))
  522. if err != nil {
  523. t.Errorf("%d. hex input error: %v", i, err)
  524. continue
  525. }
  526. if _, err := HuffmanDecode(&buf, in); err != nil {
  527. t.Errorf("%d. decode error: %v", i, err)
  528. continue
  529. }
  530. if got := buf.String(); tt.want != got {
  531. t.Errorf("%d. decode = %q; want %q", i, got, tt.want)
  532. }
  533. }
  534. }
  535. func TestAppendHuffmanString(t *testing.T) {
  536. tests := []struct {
  537. in, want string
  538. }{
  539. {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"},
  540. {"no-cache", "a8eb 1064 9cbf"},
  541. {"custom-key", "25a8 49e9 5ba9 7d7f"},
  542. {"custom-value", "25a8 49e9 5bb8 e8b4 bf"},
  543. {"302", "6402"},
  544. {"private", "aec3 771a 4b"},
  545. {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"},
  546. {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"},
  547. {"gzip", "9bd9 ab"},
  548. {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
  549. "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"},
  550. }
  551. for i, tt := range tests {
  552. buf := []byte{}
  553. want := strings.Replace(tt.want, " ", "", -1)
  554. buf = AppendHuffmanString(buf, tt.in)
  555. if got := hex.EncodeToString(buf); want != got {
  556. t.Errorf("%d. encode = %q; want %q", i, got, want)
  557. }
  558. }
  559. }
  560. func TestHuffmanMaxStrLen(t *testing.T) {
  561. const msg = "Some string"
  562. huff := AppendHuffmanString(nil, msg)
  563. testGood := func(max int) {
  564. var out bytes.Buffer
  565. if err := huffmanDecode(&out, max, huff); err != nil {
  566. t.Errorf("For maxLen=%d, unexpected error: %v", max, err)
  567. }
  568. if out.String() != msg {
  569. t.Errorf("For maxLen=%d, out = %q; want %q", max, out.String(), msg)
  570. }
  571. }
  572. testGood(0)
  573. testGood(len(msg))
  574. testGood(len(msg) + 1)
  575. var out bytes.Buffer
  576. if err := huffmanDecode(&out, len(msg)-1, huff); err != ErrStringLength {
  577. t.Errorf("err = %v; want ErrStringLength", err)
  578. }
  579. }
  580. func TestHuffmanRoundtripStress(t *testing.T) {
  581. const Len = 50 // of uncompressed string
  582. input := make([]byte, Len)
  583. var output bytes.Buffer
  584. var huff []byte
  585. n := 5000
  586. if testing.Short() {
  587. n = 100
  588. }
  589. seed := time.Now().UnixNano()
  590. t.Logf("Seed = %v", seed)
  591. src := rand.New(rand.NewSource(seed))
  592. var encSize int64
  593. for i := 0; i < n; i++ {
  594. for l := range input {
  595. input[l] = byte(src.Intn(256))
  596. }
  597. huff = AppendHuffmanString(huff[:0], string(input))
  598. encSize += int64(len(huff))
  599. output.Reset()
  600. if err := huffmanDecode(&output, 0, huff); err != nil {
  601. t.Errorf("Failed to decode %q -> %q -> error %v", input, huff, err)
  602. continue
  603. }
  604. if !bytes.Equal(output.Bytes(), input) {
  605. t.Errorf("Roundtrip failure on %q -> %q -> %q", input, huff, output.Bytes())
  606. }
  607. }
  608. t.Logf("Compressed size of original: %0.02f%% (%v -> %v)", 100*(float64(encSize)/(Len*float64(n))), Len*n, encSize)
  609. }
  610. func TestHuffmanDecodeFuzz(t *testing.T) {
  611. const Len = 50 // of compressed
  612. var buf, zbuf bytes.Buffer
  613. n := 5000
  614. if testing.Short() {
  615. n = 100
  616. }
  617. seed := time.Now().UnixNano()
  618. t.Logf("Seed = %v", seed)
  619. src := rand.New(rand.NewSource(seed))
  620. numFail := 0
  621. for i := 0; i < n; i++ {
  622. zbuf.Reset()
  623. if i == 0 {
  624. // Start with at least one invalid one.
  625. zbuf.WriteString("00\x91\xff\xff\xff\xff\xc8")
  626. } else {
  627. for l := 0; l < Len; l++ {
  628. zbuf.WriteByte(byte(src.Intn(256)))
  629. }
  630. }
  631. buf.Reset()
  632. if err := huffmanDecode(&buf, 0, zbuf.Bytes()); err != nil {
  633. if err == ErrInvalidHuffman {
  634. numFail++
  635. continue
  636. }
  637. t.Errorf("Failed to decode %q: %v", zbuf.Bytes(), err)
  638. continue
  639. }
  640. }
  641. t.Logf("%0.02f%% are invalid (%d / %d)", 100*float64(numFail)/float64(n), numFail, n)
  642. if numFail < 1 {
  643. t.Error("expected at least one invalid huffman encoding (test starts with one)")
  644. }
  645. }
  646. func TestReadVarInt(t *testing.T) {
  647. type res struct {
  648. i uint64
  649. consumed int
  650. err error
  651. }
  652. tests := []struct {
  653. n byte
  654. p []byte
  655. want res
  656. }{
  657. // Fits in a byte:
  658. {1, []byte{0}, res{0, 1, nil}},
  659. {2, []byte{2}, res{2, 1, nil}},
  660. {3, []byte{6}, res{6, 1, nil}},
  661. {4, []byte{14}, res{14, 1, nil}},
  662. {5, []byte{30}, res{30, 1, nil}},
  663. {6, []byte{62}, res{62, 1, nil}},
  664. {7, []byte{126}, res{126, 1, nil}},
  665. {8, []byte{254}, res{254, 1, nil}},
  666. // Doesn't fit in a byte:
  667. {1, []byte{1}, res{0, 0, errNeedMore}},
  668. {2, []byte{3}, res{0, 0, errNeedMore}},
  669. {3, []byte{7}, res{0, 0, errNeedMore}},
  670. {4, []byte{15}, res{0, 0, errNeedMore}},
  671. {5, []byte{31}, res{0, 0, errNeedMore}},
  672. {6, []byte{63}, res{0, 0, errNeedMore}},
  673. {7, []byte{127}, res{0, 0, errNeedMore}},
  674. {8, []byte{255}, res{0, 0, errNeedMore}},
  675. // Ignoring top bits:
  676. {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111
  677. {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100
  678. {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101
  679. // Extra byte:
  680. {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte
  681. // Short a byte:
  682. {5, []byte{191, 154}, res{0, 0, errNeedMore}},
  683. // integer overflow:
  684. {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}},
  685. }
  686. for _, tt := range tests {
  687. i, remain, err := readVarInt(tt.n, tt.p)
  688. consumed := len(tt.p) - len(remain)
  689. got := res{i, consumed, err}
  690. if got != tt.want {
  691. t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want)
  692. }
  693. }
  694. }
  695. // Fuzz crash, originally reported at https://github.com/bradfitz/http2/issues/56
  696. func TestHuffmanFuzzCrash(t *testing.T) {
  697. got, err := HuffmanDecodeToString([]byte("00\x91\xff\xff\xff\xff\xc8"))
  698. if got != "" {
  699. t.Errorf("Got %q; want empty string", got)
  700. }
  701. if err != ErrInvalidHuffman {
  702. t.Errorf("Err = %v; want ErrInvalidHuffman", err)
  703. }
  704. }
  705. func dehex(s string) []byte {
  706. s = strings.Replace(s, " ", "", -1)
  707. s = strings.Replace(s, "\n", "", -1)
  708. b, err := hex.DecodeString(s)
  709. if err != nil {
  710. panic(err)
  711. }
  712. return b
  713. }
  714. func TestEmitEnabled(t *testing.T) {
  715. var buf bytes.Buffer
  716. enc := NewEncoder(&buf)
  717. enc.WriteField(HeaderField{Name: "foo", Value: "bar"})
  718. enc.WriteField(HeaderField{Name: "foo", Value: "bar"})
  719. numCallback := 0
  720. var dec *Decoder
  721. dec = NewDecoder(8<<20, func(HeaderField) {
  722. numCallback++
  723. dec.SetEmitEnabled(false)
  724. })
  725. if !dec.EmitEnabled() {
  726. t.Errorf("initial emit enabled = false; want true")
  727. }
  728. if _, err := dec.Write(buf.Bytes()); err != nil {
  729. t.Error(err)
  730. }
  731. if numCallback != 1 {
  732. t.Errorf("num callbacks = %d; want 1", numCallback)
  733. }
  734. if dec.EmitEnabled() {
  735. t.Errorf("emit enabled = true; want false")
  736. }
  737. }
  738. func TestSaveBufLimit(t *testing.T) {
  739. const maxStr = 1 << 10
  740. var got []HeaderField
  741. dec := NewDecoder(initialHeaderTableSize, func(hf HeaderField) {
  742. got = append(got, hf)
  743. })
  744. dec.SetMaxStringLength(maxStr)
  745. var frag []byte
  746. frag = append(frag[:0], encodeTypeByte(false, false))
  747. frag = appendVarInt(frag, 7, 3)
  748. frag = append(frag, "foo"...)
  749. frag = appendVarInt(frag, 7, 3)
  750. frag = append(frag, "bar"...)
  751. if _, err := dec.Write(frag); err != nil {
  752. t.Fatal(err)
  753. }
  754. want := []HeaderField{{Name: "foo", Value: "bar"}}
  755. if !reflect.DeepEqual(got, want) {
  756. t.Errorf("After small writes, got %v; want %v", got, want)
  757. }
  758. frag = append(frag[:0], encodeTypeByte(false, false))
  759. frag = appendVarInt(frag, 7, maxStr*3)
  760. frag = append(frag, make([]byte, maxStr*3)...)
  761. _, err := dec.Write(frag)
  762. if err != ErrStringLength {
  763. t.Fatalf("Write error = %v; want ErrStringLength", err)
  764. }
  765. }