1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http2
import (
"bufio"
"bytes"
"crypto/tls"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/net/http2/hpack"
)
var (
extNet = flag.Bool("extnet", false, "do external network tests")
transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport")
insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove?
)
var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true}
type testContext struct{}
func (testContext) Done() <-chan struct{} { return make(chan struct{}) }
func (testContext) Err() error { panic("should not be called") }
func (testContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false }
func (testContext) Value(key interface{}) interface{} { return nil }
func TestTransportExternal(t *testing.T) {
if !*extNet {
t.Skip("skipping external network test")
}
req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil)
rt := &Transport{TLSClientConfig: tlsConfigInsecure}
res, err := rt.RoundTrip(req)
if err != nil {
t.Fatalf("%v", err)
}
res.Write(os.Stdout)
}
type fakeTLSConn struct {
net.Conn
}
func (c *fakeTLSConn) ConnectionState() tls.ConnectionState {
return tls.ConnectionState{
Version: tls.VersionTLS12,
}
}
func startH2cServer(t *testing.T) net.Listener {
h2Server := &Server{}
l := newLocalListener(t)
go func() {
conn, err := l.Accept()
if err != nil {
t.Error(err)
return
}
h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil)
})})
}()
return l
}
func TestTransportH2c(t *testing.T) {
l := startH2cServer(t)
defer l.Close()
req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil)
if err != nil {
t.Fatal(err)
}
tr := &Transport{
AllowHTTP: true,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
if res.ProtoMajor != 2 {
t.Fatal("proto not h2c")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if got, want := string(body), "Hello, /foobar, http: true"; got != want {
t.Fatalf("response got %v, want %v", got, want)
}
}
func TestTransport(t *testing.T) {
const body = "sup"
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, body)
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
t.Logf("Got res: %+v", res)
if g, w := res.StatusCode, 200; g != w {
t.Errorf("StatusCode = %v; want %v", g, w)
}
if g, w := res.Status, "200 OK"; g != w {
t.Errorf("Status = %q; want %q", g, w)
}
wantHeader := http.Header{
"Content-Length": []string{"3"},
"Content-Type": []string{"text/plain; charset=utf-8"},
"Date": []string{"XXX"}, // see cleanDate
}
cleanDate(res)
if !reflect.DeepEqual(res.Header, wantHeader) {
t.Errorf("res Header = %v; want %v", res.Header, wantHeader)
}
if res.Request != req {
t.Errorf("Response.Request = %p; want %p", res.Request, req)
}
if res.TLS == nil {
t.Error("Response.TLS = nil; want non-nil")
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Errorf("Body read: %v", err)
} else if string(slurp) != body {
t.Errorf("Body = %q; want %q", slurp, body)
}
}
func onSameConn(t *testing.T, modReq func(*http.Request)) bool {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.RemoteAddr)
}, optOnlyServer, func(c net.Conn, st http.ConnState) {
t.Logf("conn %v is now state %v", c.RemoteAddr(), st)
})
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
get := func() string {
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
modReq(req)
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Body read: %v", err)
}
addr := strings.TrimSpace(string(slurp))
if addr == "" {
t.Fatalf("didn't get an addr in response")
}
return addr
}
first := get()
second := get()
return first == second
}
func TestTransportReusesConns(t *testing.T) {
if !onSameConn(t, func(*http.Request) {}) {
t.Errorf("first and second responses were on different connections")
}
}
func TestTransportReusesConn_RequestClose(t *testing.T) {
if onSameConn(t, func(r *http.Request) { r.Close = true }) {
t.Errorf("first and second responses were not on different connections")
}
}
func TestTransportReusesConn_ConnClose(t *testing.T) {
if onSameConn(t, func(r *http.Request) { r.Header.Set("Connection", "close") }) {
t.Errorf("first and second responses were not on different connections")
}
}
// Tests that the Transport only keeps one pending dial open per destination address.
// https://golang.org/issue/13397
func TestTransportGroupsPendingDials(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.RemoteAddr)
}, optOnlyServer)
defer st.Close()
tr := &Transport{
TLSClientConfig: tlsConfigInsecure,
}
defer tr.CloseIdleConnections()
var (
mu sync.Mutex
dials = map[string]int{}
)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Error(err)
return
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Error(err)
return
}
defer res.Body.Close()
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Errorf("Body read: %v", err)
}
addr := strings.TrimSpace(string(slurp))
if addr == "" {
t.Errorf("didn't get an addr in response")
}
mu.Lock()
dials[addr]++
mu.Unlock()
}()
}
wg.Wait()
if len(dials) != 1 {
t.Errorf("saw %d dials; want 1: %v", len(dials), dials)
}
tr.CloseIdleConnections()
if err := retry(50, 10*time.Millisecond, func() error {
cp, ok := tr.connPool().(*clientConnPool)
if !ok {
return fmt.Errorf("Conn pool is %T; want *clientConnPool", tr.connPool())
}
cp.mu.Lock()
defer cp.mu.Unlock()
if len(cp.dialing) != 0 {
return fmt.Errorf("dialing map = %v; want empty", cp.dialing)
}
if len(cp.conns) != 0 {
return fmt.Errorf("conns = %v; want empty", cp.conns)
}
if len(cp.keys) != 0 {
return fmt.Errorf("keys = %v; want empty", cp.keys)
}
return nil
}); err != nil {
t.Errorf("State of pool after CloseIdleConnections: %v", err)
}
}
func retry(tries int, delay time.Duration, fn func() error) error {
var err error
for i := 0; i < tries; i++ {
err = fn()
if err == nil {
return nil
}
time.Sleep(delay)
}
return err
}
func TestTransportAbortClosesPipes(t *testing.T) {
shutdown := make(chan struct{})
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
w.(http.Flusher).Flush()
<-shutdown
},
optOnlyServer,
)
defer st.Close()
defer close(shutdown) // we must shutdown before st.Close() to avoid hanging
done := make(chan struct{})
requestMade := make(chan struct{})
go func() {
defer close(done)
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
close(requestMade)
_, err = ioutil.ReadAll(res.Body)
if err == nil {
t.Error("expected error from res.Body.Read")
}
}()
<-requestMade
// Now force the serve loop to end, via closing the connection.
st.closeConn()
// deadlock? that's a bug.
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatal("timeout")
}
}
// TODO: merge this with TestTransportBody to make TestTransportRequest? This
// could be a table-driven test with extra goodies.
func TestTransportPath(t *testing.T) {
gotc := make(chan *url.URL, 1)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
gotc <- r.URL
},
optOnlyServer,
)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
const (
path = "/testpath"
query = "q=1"
)
surl := st.ts.URL + path + "?" + query
req, err := http.NewRequest("POST", surl, nil)
if err != nil {
t.Fatal(err)
}
c := &http.Client{Transport: tr}
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
got := <-gotc
if got.Path != path {
t.Errorf("Read Path = %q; want %q", got.Path, path)
}
if got.RawQuery != query {
t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query)
}
}
func randString(n int) string {
rnd := rand.New(rand.NewSource(int64(n)))
b := make([]byte, n)
for i := range b {
b[i] = byte(rnd.Intn(256))
}
return string(b)
}
func TestTransportBody(t *testing.T) {
bodyTests := []struct {
body string
noContentLen bool
}{
{body: "some message"},
{body: "some message", noContentLen: true},
{body: ""},
{body: "", noContentLen: true},
{body: strings.Repeat("a", 1<<20), noContentLen: true},
{body: strings.Repeat("a", 1<<20)},
{body: randString(16<<10 - 1)},
{body: randString(16 << 10)},
{body: randString(16<<10 + 1)},
{body: randString(512<<10 - 1)},
{body: randString(512 << 10)},
{body: randString(512<<10 + 1)},
{body: randString(1<<20 - 1)},
{body: randString(1 << 20)},
{body: randString(1<<20 + 2)},
}
type reqInfo struct {
req *http.Request
slurp []byte
err error
}
gotc := make(chan reqInfo, 1)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
slurp, err := ioutil.ReadAll(r.Body)
if err != nil {
gotc <- reqInfo{err: err}
} else {
gotc <- reqInfo{req: r, slurp: slurp}
}
},
optOnlyServer,
)
defer st.Close()
for i, tt := range bodyTests {
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
var body io.Reader = strings.NewReader(tt.body)
if tt.noContentLen {
body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods
}
req, err := http.NewRequest("POST", st.ts.URL, body)
if err != nil {
t.Fatalf("#%d: %v", i, err)
}
c := &http.Client{Transport: tr}
res, err := c.Do(req)
if err != nil {
t.Fatalf("#%d: %v", i, err)
}
defer res.Body.Close()
ri := <-gotc
if ri.err != nil {
t.Errorf("#%d: read error: %v", i, ri.err)
continue
}
if got := string(ri.slurp); got != tt.body {
t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body))
}
wantLen := int64(len(tt.body))
if tt.noContentLen && tt.body != "" {
wantLen = -1
}
if ri.req.ContentLength != wantLen {
t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen)
}
}
}
func shortString(v string) string {
const maxLen = 100
if len(v) <= maxLen {
return v
}
return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:])
}
func TestTransportDialTLS(t *testing.T) {
var mu sync.Mutex // guards following
var gotReq, didDial bool
ts := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
gotReq = true
mu.Unlock()
},
optOnlyServer,
)
defer ts.Close()
tr := &Transport{
DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {
mu.Lock()
didDial = true
mu.Unlock()
cfg.InsecureSkipVerify = true
c, err := tls.Dial(netw, addr, cfg)
if err != nil {
return nil, err
}
return c, c.Handshake()
},
}
defer tr.CloseIdleConnections()
client := &http.Client{Transport: tr}
res, err := client.Get(ts.ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
mu.Lock()
if !gotReq {
t.Error("didn't get request")
}
if !didDial {
t.Error("didn't use dial hook")
}
}
func TestConfigureTransport(t *testing.T) {
t1 := &http.Transport{}
err := ConfigureTransport(t1)
if err == errTransportVersion {
t.Skip(err)
}
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) {
// Laziness, to avoid buildtags.
t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got)
}
wantNextProtos := []string{"h2", "http/1.1"}
if t1.TLSClientConfig == nil {
t.Errorf("nil t1.TLSClientConfig")
} else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) {
t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos)
}
if err := ConfigureTransport(t1); err == nil {
t.Error("unexpected success on second call to ConfigureTransport")
}
// And does it work?
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.Proto)
}, optOnlyServer)
defer st.Close()
t1.TLSClientConfig.InsecureSkipVerify = true
c := &http.Client{Transport: t1}
res, err := c.Get(st.ts.URL)
if err != nil {
t.Fatal(err)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if got, want := string(slurp), "HTTP/2.0"; got != want {
t.Errorf("body = %q; want %q", got, want)
}
}
type capitalizeReader struct {
r io.Reader
}
func (cr capitalizeReader) Read(p []byte) (n int, err error) {
n, err = cr.r.Read(p)
for i, b := range p[:n] {
if b >= 'a' && b <= 'z' {
p[i] = b - ('a' - 'A')
}
}
return
}
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if f, ok := fw.w.(http.Flusher); ok {
f.Flush()
}
return
}
type clientTester struct {
t *testing.T
tr *Transport
sc, cc net.Conn // server and client conn
fr *Framer // server's framer
client func() error
server func() error
}
func newClientTester(t *testing.T) *clientTester {
var dialOnce struct {
sync.Mutex
dialed bool
}
ct := &clientTester{
t: t,
}
ct.tr = &Transport{
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
dialOnce.Lock()
defer dialOnce.Unlock()
if dialOnce.dialed {
return nil, errors.New("only one dial allowed in test mode")
}
dialOnce.dialed = true
return ct.cc, nil
},
}
ln := newLocalListener(t)
cc, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
sc, err := ln.Accept()
if err != nil {
t.Fatal(err)
}
ln.Close()
ct.cc = cc
ct.sc = sc
ct.fr = NewFramer(sc, sc)
return ct
}
func newLocalListener(t *testing.T) net.Listener {
ln, err := net.Listen("tcp4", "127.0.0.1:0")
if err == nil {
return ln
}
ln, err = net.Listen("tcp6", "[::1]:0")
if err != nil {
t.Fatal(err)
}
return ln
}
func (ct *clientTester) greet() {
buf := make([]byte, len(ClientPreface))
_, err := io.ReadFull(ct.sc, buf)
if err != nil {
ct.t.Fatalf("reading client preface: %v", err)
}
f, err := ct.fr.ReadFrame()
if err != nil {
ct.t.Fatalf("Reading client settings frame: %v", err)
}
if sf, ok := f.(*SettingsFrame); !ok {
ct.t.Fatalf("Wanted client settings frame; got %v", f)
_ = sf // stash it away?
}
if err := ct.fr.WriteSettings(); err != nil {
ct.t.Fatal(err)
}
if err := ct.fr.WriteSettingsAck(); err != nil {
ct.t.Fatal(err)
}
}
func (ct *clientTester) readNonSettingsFrame() (Frame, error) {
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return nil, err
}
if _, ok := f.(*SettingsFrame); ok {
continue
}
return f, nil
}
}
func (ct *clientTester) cleanup() {
ct.tr.CloseIdleConnections()
}
func (ct *clientTester) run() {
errc := make(chan error, 2)
ct.start("client", errc, ct.client)
ct.start("server", errc, ct.server)
defer ct.cleanup()
for i := 0; i < 2; i++ {
if err := <-errc; err != nil {
ct.t.Error(err)
return
}
}
}
func (ct *clientTester) start(which string, errc chan<- error, fn func() error) {
go func() {
finished := false
var err error
defer func() {
if !finished {
err = fmt.Errorf("%s goroutine didn't finish.", which)
} else if err != nil {
err = fmt.Errorf("%s: %v", which, err)
}
errc <- err
}()
err = fn()
finished = true
}()
}
func (ct *clientTester) readFrame() (Frame, error) {
return readFrameTimeout(ct.fr, 2*time.Second)
}
func (ct *clientTester) firstHeaders() (*HeadersFrame, error) {
for {
f, err := ct.readFrame()
if err != nil {
return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
}
switch f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
continue
}
hf, ok := f.(*HeadersFrame)
if !ok {
return nil, fmt.Errorf("Got %T; want HeadersFrame", f)
}
return hf, nil
}
}
type countingReader struct {
n *int64
}
func (r countingReader) Read(p []byte) (n int, err error) {
for i := range p {
p[i] = byte(i)
}
atomic.AddInt64(r.n, int64(len(p)))
return len(p), err
}
func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) }
func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) }
func testTransportReqBodyAfterResponse(t *testing.T, status int) {
const bodySize = 10 << 20
clientDone := make(chan struct{})
ct := newClientTester(t)
ct.client = func() error {
defer ct.cc.(*net.TCPConn).CloseWrite()
defer close(clientDone)
var n int64 // atomic
req, err := http.NewRequest("PUT", "https://dummy.tld/", io.LimitReader(countingReader{&n}, bodySize))
if err != nil {
return err
}
res, err := ct.tr.RoundTrip(req)
if err != nil {
return fmt.Errorf("RoundTrip: %v", err)
}
defer res.Body.Close()
if res.StatusCode != status {
return fmt.Errorf("status code = %v; want %v", res.StatusCode, status)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Slurp: %v", err)
}
if len(slurp) > 0 {
return fmt.Errorf("unexpected body: %q", slurp)
}
if status == 200 {
if got := atomic.LoadInt64(&n); got != bodySize {
return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize)
}
} else {
if got := atomic.LoadInt64(&n); got == 0 || got >= bodySize {
return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize)
}
}
return nil
}
ct.server = func() error {
ct.greet()
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
var dataRecv int64
var closed bool
for {
f, err := ct.fr.ReadFrame()
if err != nil {
select {
case <-clientDone:
// If the client's done, it
// will have reported any
// errors on its side.
return nil
default:
return err
}
}
//println(fmt.Sprintf("server got frame: %v", f))
switch f := f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
case *HeadersFrame:
if !f.HeadersEnded() {
return fmt.Errorf("headers should have END_HEADERS be ended: %v", f)
}
if f.StreamEnded() {
return fmt.Errorf("headers contains END_STREAM unexpectedly: %v", f)
}
case *DataFrame:
dataLen := len(f.Data())
if dataLen > 0 {
if dataRecv == 0 {
enc.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
}
if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil {
return err
}
if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil {
return err
}
}
dataRecv += int64(dataLen)
if !closed && ((status != 200 && dataRecv > 0) ||
(status == 200 && dataRecv == bodySize)) {
closed = true
if err := ct.fr.WriteData(f.StreamID, true, nil); err != nil {
return err
}
}
default:
return fmt.Errorf("Unexpected client frame %v", f)
}
}
}
ct.run()
}
// See golang.org/issue/13444
func TestTransportFullDuplex(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200) // redundant but for clarity
w.(http.Flusher).Flush()
io.Copy(flushWriter{w}, capitalizeReader{r.Body})
fmt.Fprintf(w, "bye.\n")
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
c := &http.Client{Transport: tr}
pr, pw := io.Pipe()
req, err := http.NewRequest("PUT", st.ts.URL, ioutil.NopCloser(pr))
if err != nil {
t.Fatal(err)
}
req.ContentLength = -1
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
t.Fatalf("StatusCode = %v; want %v", res.StatusCode, 200)
}
bs := bufio.NewScanner(res.Body)
want := func(v string) {
if !bs.Scan() {
t.Fatalf("wanted to read %q but Scan() = false, err = %v", v, bs.Err())
}
}
write := func(v string) {
_, err := io.WriteString(pw, v)
if err != nil {
t.Fatalf("pipe write: %v", err)
}
}
write("foo\n")
want("FOO")
write("bar\n")
want("BAR")
pw.Close()
want("bye.")
if err := bs.Err(); err != nil {
t.Fatal(err)
}
}
func TestTransportConnectRequest(t *testing.T) {
gotc := make(chan *http.Request, 1)
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
gotc <- r
}, optOnlyServer)
defer st.Close()
u, err := url.Parse(st.ts.URL)
if err != nil {
t.Fatal(err)
}
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
c := &http.Client{Transport: tr}
tests := []struct {
req *http.Request
want string
}{
{
req: &http.Request{
Method: "CONNECT",
Header: http.Header{},
URL: u,
},
want: u.Host,
},
{
req: &http.Request{
Method: "CONNECT",
Header: http.Header{},
URL: u,
Host: "example.com:123",
},
want: "example.com:123",
},
}
for i, tt := range tests {
res, err := c.Do(tt.req)
if err != nil {
t.Errorf("%d. RoundTrip = %v", i, err)
continue
}
res.Body.Close()
req := <-gotc
if req.Method != "CONNECT" {
t.Errorf("method = %q; want CONNECT", req.Method)
}
if req.Host != tt.want {
t.Errorf("Host = %q; want %q", req.Host, tt.want)
}
if req.URL.Host != tt.want {
t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want)
}
}
}
type headerType int
const (
noHeader headerType = iota // omitted
oneHeader
splitHeader // broken into continuation on purpose
)
const (
f0 = noHeader
f1 = oneHeader
f2 = splitHeader
d0 = false
d1 = true
)
// Test all 36 combinations of response frame orders:
// (3 ways of 100-continue) * (2 ways of headers) * (2 ways of data) * (3 ways of trailers):func TestTransportResponsePattern_00f0(t *testing.T) { testTransportResponsePattern(h0, h1, false, h0) }
// Generated by http://play.golang.org/p/SScqYKJYXd
func TestTransportResPattern_c0h1d0t0(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f0) }
func TestTransportResPattern_c0h1d0t1(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f1) }
func TestTransportResPattern_c0h1d0t2(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f2) }
func TestTransportResPattern_c0h1d1t0(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f0) }
func TestTransportResPattern_c0h1d1t1(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f1) }
func TestTransportResPattern_c0h1d1t2(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f2) }
func TestTransportResPattern_c0h2d0t0(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f0) }
func TestTransportResPattern_c0h2d0t1(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f1) }
func TestTransportResPattern_c0h2d0t2(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f2) }
func TestTransportResPattern_c0h2d1t0(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f0) }
func TestTransportResPattern_c0h2d1t1(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f1) }
func TestTransportResPattern_c0h2d1t2(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f2) }
func TestTransportResPattern_c1h1d0t0(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f0) }
func TestTransportResPattern_c1h1d0t1(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f1) }
func TestTransportResPattern_c1h1d0t2(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f2) }
func TestTransportResPattern_c1h1d1t0(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f0) }
func TestTransportResPattern_c1h1d1t1(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f1) }
func TestTransportResPattern_c1h1d1t2(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f2) }
func TestTransportResPattern_c1h2d0t0(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f0) }
func TestTransportResPattern_c1h2d0t1(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f1) }
func TestTransportResPattern_c1h2d0t2(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f2) }
func TestTransportResPattern_c1h2d1t0(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f0) }
func TestTransportResPattern_c1h2d1t1(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f1) }
func TestTransportResPattern_c1h2d1t2(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f2) }
func TestTransportResPattern_c2h1d0t0(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f0) }
func TestTransportResPattern_c2h1d0t1(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f1) }
func TestTransportResPattern_c2h1d0t2(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f2) }
func TestTransportResPattern_c2h1d1t0(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f0) }
func TestTransportResPattern_c2h1d1t1(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f1) }
func TestTransportResPattern_c2h1d1t2(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f2) }
func TestTransportResPattern_c2h2d0t0(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f0) }
func TestTransportResPattern_c2h2d0t1(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f1) }
func TestTransportResPattern_c2h2d0t2(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f2) }
func TestTransportResPattern_c2h2d1t0(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f0) }
func TestTransportResPattern_c2h2d1t1(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f1) }
func TestTransportResPattern_c2h2d1t2(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f2) }
func testTransportResPattern(t *testing.T, expect100Continue, resHeader headerType, withData bool, trailers headerType) {
const reqBody = "some request body"
const resBody = "some response body"
if resHeader == noHeader {
// TODO: test 100-continue followed by immediate
// server stream reset, without headers in the middle?
panic("invalid combination")
}
ct := newClientTester(t)
ct.client = func() error {
req, _ := http.NewRequest("POST", "https://dummy.tld/", strings.NewReader(reqBody))
if expect100Continue != noHeader {
req.Header.Set("Expect", "100-continue")
}
res, err := ct.tr.RoundTrip(req)
if err != nil {
return fmt.Errorf("RoundTrip: %v", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("status code = %v; want 200", res.StatusCode)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Slurp: %v", err)
}
wantBody := resBody
if !withData {
wantBody = ""
}
if string(slurp) != wantBody {
return fmt.Errorf("body = %q; want %q", slurp, wantBody)
}
if trailers == noHeader {
if len(res.Trailer) > 0 {
t.Errorf("Trailer = %v; want none", res.Trailer)
}
} else {
want := http.Header{"Some-Trailer": {"some-value"}}
if !reflect.DeepEqual(res.Trailer, want) {
t.Errorf("Trailer = %v; want %v", res.Trailer, want)
}
}
return nil
}
ct.server = func() error {
ct.greet()
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return err
}
endStream := false
send := func(mode headerType) {
hbf := buf.Bytes()
switch mode {
case oneHeader:
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.Header().StreamID,
EndHeaders: true,
EndStream: endStream,
BlockFragment: hbf,
})
case splitHeader:
if len(hbf) < 2 {
panic("too small")
}
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.Header().StreamID,
EndHeaders: false,
EndStream: endStream,
BlockFragment: hbf[:1],
})
ct.fr.WriteContinuation(f.Header().StreamID, true, hbf[1:])
default:
panic("bogus mode")
}
}
switch f := f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
case *DataFrame:
if !f.StreamEnded() {
// No need to send flow control tokens. The test request body is tiny.
continue
}
// Response headers (1+ frames; 1 or 2 in this test, but never 0)
{
buf.Reset()
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "x-foo", Value: "blah"})
enc.WriteField(hpack.HeaderField{Name: "x-bar", Value: "more"})
if trailers != noHeader {
enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "some-trailer"})
}
endStream = withData == false && trailers == noHeader
send(resHeader)
}
if withData {
endStream = trailers == noHeader
ct.fr.WriteData(f.StreamID, endStream, []byte(resBody))
}
if trailers != noHeader {
endStream = true
buf.Reset()
enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "some-value"})
send(trailers)
}
if endStream {
return nil
}
case *HeadersFrame:
if expect100Continue != noHeader {
buf.Reset()
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"})
send(expect100Continue)
}
}
}
}
ct.run()
}
func TestTransportReceiveUndeclaredTrailer(t *testing.T) {
ct := newClientTester(t)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != nil {
return fmt.Errorf("RoundTrip: %v", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("status code = %v; want 200", res.StatusCode)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("res.Body ReadAll error = %q, %v; want %v", slurp, err, nil)
}
if len(slurp) > 0 {
return fmt.Errorf("body = %q; want nothing", slurp)
}
if _, ok := res.Trailer["Some-Trailer"]; !ok {
return fmt.Errorf("expected Some-Trailer")
}
return nil
}
ct.server = func() error {
ct.greet()
var n int
var hf *HeadersFrame
for hf == nil && n < 10 {
f, err := ct.fr.ReadFrame()
if err != nil {
return err
}
hf, _ = f.(*HeadersFrame)
n++
}
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
// send headers without Trailer header
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
// send trailers
buf.Reset()
enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "I'm an undeclared Trailer!"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: true,
BlockFragment: buf.Bytes(),
})
return nil
}
ct.run()
}
func TestTransportInvalidTrailer_Pseudo1(t *testing.T) {
testTransportInvalidTrailer_Pseudo(t, oneHeader)
}
func TestTransportInvalidTrailer_Pseudo2(t *testing.T) {
testTransportInvalidTrailer_Pseudo(t, splitHeader)
}
func testTransportInvalidTrailer_Pseudo(t *testing.T, trailers headerType) {
testInvalidTrailer(t, trailers, pseudoHeaderError(":colon"), func(enc *hpack.Encoder) {
enc.WriteField(hpack.HeaderField{Name: ":colon", Value: "foo"})
enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"})
})
}
func TestTransportInvalidTrailer_Capital1(t *testing.T) {
testTransportInvalidTrailer_Capital(t, oneHeader)
}
func TestTransportInvalidTrailer_Capital2(t *testing.T) {
testTransportInvalidTrailer_Capital(t, splitHeader)
}
func testTransportInvalidTrailer_Capital(t *testing.T, trailers headerType) {
testInvalidTrailer(t, trailers, headerFieldNameError("Capital"), func(enc *hpack.Encoder) {
enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"})
enc.WriteField(hpack.HeaderField{Name: "Capital", Value: "bad"})
})
}
func TestTransportInvalidTrailer_EmptyFieldName(t *testing.T) {
testInvalidTrailer(t, oneHeader, headerFieldNameError(""), func(enc *hpack.Encoder) {
enc.WriteField(hpack.HeaderField{Name: "", Value: "bad"})
})
}
func TestTransportInvalidTrailer_BinaryFieldValue(t *testing.T) {
testInvalidTrailer(t, oneHeader, headerFieldValueError("has\nnewline"), func(enc *hpack.Encoder) {
enc.WriteField(hpack.HeaderField{Name: "x", Value: "has\nnewline"})
})
}
func testInvalidTrailer(t *testing.T, trailers headerType, wantErr error, writeTrailer func(*hpack.Encoder)) {
ct := newClientTester(t)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != nil {
return fmt.Errorf("RoundTrip: %v", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("status code = %v; want 200", res.StatusCode)
}
slurp, err := ioutil.ReadAll(res.Body)
se, ok := err.(StreamError)
if !ok || se.Cause != wantErr {
return fmt.Errorf("res.Body ReadAll error = %q, %#v; want StreamError with cause %T, %#v", slurp, err, wantErr, wantErr)
}
if len(slurp) > 0 {
return fmt.Errorf("body = %q; want nothing", slurp)
}
return nil
}
ct.server = func() error {
ct.greet()
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return err
}
switch f := f.(type) {
case *HeadersFrame:
var endStream bool
send := func(mode headerType) {
hbf := buf.Bytes()
switch mode {
case oneHeader:
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.StreamID,
EndHeaders: true,
EndStream: endStream,
BlockFragment: hbf,
})
case splitHeader:
if len(hbf) < 2 {
panic("too small")
}
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.StreamID,
EndHeaders: false,
EndStream: endStream,
BlockFragment: hbf[:1],
})
ct.fr.WriteContinuation(f.StreamID, true, hbf[1:])
default:
panic("bogus mode")
}
}
// Response headers (1+ frames; 1 or 2 in this test, but never 0)
{
buf.Reset()
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "declared"})
endStream = false
send(oneHeader)
}
// Trailers:
{
endStream = true
buf.Reset()
writeTrailer(enc)
send(trailers)
}
return nil
}
}
}
ct.run()
}
func TestTransportChecksResponseHeaderListSize(t *testing.T) {
ct := newClientTester(t)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != errResponseHeaderListSize {
if res != nil {
res.Body.Close()
}
size := int64(0)
for k, vv := range res.Header {
for _, v := range vv {
size += int64(len(k)) + int64(len(v)) + 32
}
}
return fmt.Errorf("RoundTrip Error = %v (and %d bytes of response headers); want errResponseHeaderListSize", err, size)
}
return nil
}
ct.server = func() error {
ct.greet()
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return err
}
switch f := f.(type) {
case *HeadersFrame:
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
large := strings.Repeat("a", 1<<10)
for i := 0; i < 5042; i++ {
enc.WriteField(hpack.HeaderField{Name: large, Value: large})
}
if size, want := buf.Len(), 6329; size != want {
// Note: this number might change if
// our hpack implementation
// changes. That's fine. This is
// just a sanity check that our
// response can fit in a single
// header block fragment frame.
return fmt.Errorf("encoding over 10MB of duplicate keypairs took %d bytes; expected %d", size, want)
}
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.StreamID,
EndHeaders: true,
EndStream: true,
BlockFragment: buf.Bytes(),
})
return nil
}
}
}
ct.run()
}
// Test that the the Transport returns a typed error from Response.Body.Read calls
// when the server sends an error. (here we use a panic, since that should generate
// a stream error, but others like cancel should be similar)
func TestTransportBodyReadErrorType(t *testing.T) {
doPanic := make(chan bool, 1)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
w.(http.Flusher).Flush() // force headers out
<-doPanic
panic("boom")
},
optOnlyServer,
optQuiet,
)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
c := &http.Client{Transport: tr}
res, err := c.Get(st.ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
doPanic <- true
buf := make([]byte, 100)
n, err := res.Body.Read(buf)
want := StreamError{StreamID: 0x1, Code: 0x2}
if !reflect.DeepEqual(want, err) {
t.Errorf("Read = %v, %#v; want error %#v", n, err, want)
}
}
// golang.org/issue/13924
// This used to fail after many iterations, especially with -race:
// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race
func TestTransportDoubleCloseOnWriteError(t *testing.T) {
var (
mu sync.Mutex
conn net.Conn // to close if set
)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
if conn != nil {
conn.Close()
}
},
optOnlyServer,
)
defer st.Close()
tr := &Transport{
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
tc, err := tls.Dial(network, addr, cfg)
if err != nil {
return nil, err
}
mu.Lock()
defer mu.Unlock()
conn = tc
return tc, nil
},
}
defer tr.CloseIdleConnections()
c := &http.Client{Transport: tr}
c.Get(st.ts.URL)
}
// Test that the http1 Transport.DisableKeepAlives option is respected
// and connections are closed as soon as idle.
// See golang.org/issue/14008
func TestTransportDisableKeepAlives(t *testing.T) {
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hi")
},
optOnlyServer,
)
defer st.Close()
connClosed := make(chan struct{}) // closed on tls.Conn.Close
tr := &Transport{
t1: &http.Transport{
DisableKeepAlives: true,
},
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
tc, err := tls.Dial(network, addr, cfg)
if err != nil {
return nil, err
}
return ¬eCloseConn{Conn: tc, closefn: func() { close(connClosed) }}, nil
},
}
c := &http.Client{Transport: tr}
res, err := c.Get(st.ts.URL)
if err != nil {
t.Fatal(err)
}
if _, err := ioutil.ReadAll(res.Body); err != nil {
t.Fatal(err)
}
defer res.Body.Close()
select {
case <-connClosed:
case <-time.After(1 * time.Second):
t.Errorf("timeout")
}
}
// Test concurrent requests with Transport.DisableKeepAlives. We can share connections,
// but when things are totally idle, it still needs to close.
func TestTransportDisableKeepAlives_Concurrency(t *testing.T) {
const D = 25 * time.Millisecond
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
time.Sleep(D)
io.WriteString(w, "hi")
},
optOnlyServer,
)
defer st.Close()
var dials int32
var conns sync.WaitGroup
tr := &Transport{
t1: &http.Transport{
DisableKeepAlives: true,
},
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
tc, err := tls.Dial(network, addr, cfg)
if err != nil {
return nil, err
}
atomic.AddInt32(&dials, 1)
conns.Add(1)
return ¬eCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil
},
}
c := &http.Client{Transport: tr}
var reqs sync.WaitGroup
const N = 20
for i := 0; i < N; i++ {
reqs.Add(1)
if i == N-1 {
// For the final request, try to make all the
// others close. This isn't verified in the
// count, other than the Log statement, since
// it's so timing dependent. This test is
// really to make sure we don't interrupt a
// valid request.
time.Sleep(D * 2)
}
go func() {
defer reqs.Done()
res, err := c.Get(st.ts.URL)
if err != nil {
t.Error(err)
return
}
if _, err := ioutil.ReadAll(res.Body); err != nil {
t.Error(err)
return
}
res.Body.Close()
}()
}
reqs.Wait()
conns.Wait()
t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N)
}
type noteCloseConn struct {
net.Conn
onceClose sync.Once
closefn func()
}
func (c *noteCloseConn) Close() error {
c.onceClose.Do(c.closefn)
return c.Conn.Close()
}
func isTimeout(err error) bool {
switch err := err.(type) {
case nil:
return false
case *url.Error:
return isTimeout(err.Err)
case net.Error:
return err.Timeout()
}
return false
}
// Test that the http1 Transport.ResponseHeaderTimeout option and cancel is sent.
func TestTransportResponseHeaderTimeout_NoBody(t *testing.T) {
testTransportResponseHeaderTimeout(t, false)
}
func TestTransportResponseHeaderTimeout_Body(t *testing.T) {
testTransportResponseHeaderTimeout(t, true)
}
func testTransportResponseHeaderTimeout(t *testing.T, body bool) {
ct := newClientTester(t)
ct.tr.t1 = &http.Transport{
ResponseHeaderTimeout: 5 * time.Millisecond,
}
ct.client = func() error {
c := &http.Client{Transport: ct.tr}
var err error
var n int64
const bodySize = 4 << 20
if body {
_, err = c.Post("https://dummy.tld/", "text/foo", io.LimitReader(countingReader{&n}, bodySize))
} else {
_, err = c.Get("https://dummy.tld/")
}
if !isTimeout(err) {
t.Errorf("client expected timeout error; got %#v", err)
}
if body && n != bodySize {
t.Errorf("only read %d bytes of body; want %d", n, bodySize)
}
return nil
}
ct.server = func() error {
ct.greet()
for {
f, err := ct.fr.ReadFrame()
if err != nil {
t.Logf("ReadFrame: %v", err)
return nil
}
switch f := f.(type) {
case *DataFrame:
dataLen := len(f.Data())
if dataLen > 0 {
if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil {
return err
}
if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil {
return err
}
}
case *RSTStreamFrame:
if f.StreamID == 1 && f.ErrCode == ErrCodeCancel {
return nil
}
}
}
}
ct.run()
}
func TestTransportDisableCompression(t *testing.T) {
const body = "sup"
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
want := http.Header{
"User-Agent": []string{"Go-http-client/2.0"},
}
if !reflect.DeepEqual(r.Header, want) {
t.Errorf("request headers = %v; want %v", r.Header, want)
}
}, optOnlyServer)
defer st.Close()
tr := &Transport{
TLSClientConfig: tlsConfigInsecure,
t1: &http.Transport{
DisableCompression: true,
},
}
defer tr.CloseIdleConnections()
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
}
// RFC 7540 section 8.1.2.2
func TestTransportRejectsConnHeaders(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
var got []string
for k := range r.Header {
got = append(got, k)
}
sort.Strings(got)
w.Header().Set("Got-Header", strings.Join(got, ","))
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
tests := []struct {
key string
value []string
want string
}{
{
key: "Upgrade",
value: []string{"anything"},
want: "ERROR: http2: invalid Upgrade request header: [\"anything\"]",
},
{
key: "Connection",
value: []string{"foo"},
want: "ERROR: http2: invalid Connection request header: [\"foo\"]",
},
{
key: "Connection",
value: []string{"close"},
want: "Accept-Encoding,User-Agent",
},
{
key: "Connection",
value: []string{"close", "something-else"},
want: "ERROR: http2: invalid Connection request header: [\"close\" \"something-else\"]",
},
{
key: "Connection",
value: []string{"keep-alive"},
want: "Accept-Encoding,User-Agent",
},
{
key: "Proxy-Connection", // just deleted and ignored
value: []string{"keep-alive"},
want: "Accept-Encoding,User-Agent",
},
{
key: "Transfer-Encoding",
value: []string{""},
want: "Accept-Encoding,User-Agent",
},
{
key: "Transfer-Encoding",
value: []string{"foo"},
want: "ERROR: http2: invalid Transfer-Encoding request header: [\"foo\"]",
},
{
key: "Transfer-Encoding",
value: []string{"chunked"},
want: "Accept-Encoding,User-Agent",
},
{
key: "Transfer-Encoding",
value: []string{"chunked", "other"},
want: "ERROR: http2: invalid Transfer-Encoding request header: [\"chunked\" \"other\"]",
},
{
key: "Content-Length",
value: []string{"123"},
want: "Accept-Encoding,User-Agent",
},
{
key: "Keep-Alive",
value: []string{"doop"},
want: "Accept-Encoding,User-Agent",
},
}
for _, tt := range tests {
req, _ := http.NewRequest("GET", st.ts.URL, nil)
req.Header[tt.key] = tt.value
res, err := tr.RoundTrip(req)
var got string
if err != nil {
got = fmt.Sprintf("ERROR: %v", err)
} else {
got = res.Header.Get("Got-Header")
res.Body.Close()
}
if got != tt.want {
t.Errorf("For key %q, value %q, got = %q; want %q", tt.key, tt.value, got, tt.want)
}
}
}
// golang.org/issue/14048
func TestTransportFailsOnInvalidHeaders(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
var got []string
for k := range r.Header {
got = append(got, k)
}
sort.Strings(got)
w.Header().Set("Got-Header", strings.Join(got, ","))
}, optOnlyServer)
defer st.Close()
tests := [...]struct {
h http.Header
wantErr string
}{
0: {
h: http.Header{"with space": {"foo"}},
wantErr: `invalid HTTP header name "with space"`,
},
1: {
h: http.Header{"name": {"Брэд"}},
wantErr: "", // okay
},
2: {
h: http.Header{"имя": {"Brad"}},
wantErr: `invalid HTTP header name "имя"`,
},
3: {
h: http.Header{"foo": {"foo\x01bar"}},
wantErr: `invalid HTTP header value "foo\x01bar" for header "foo"`,
},
}
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
for i, tt := range tests {
req, _ := http.NewRequest("GET", st.ts.URL, nil)
req.Header = tt.h
res, err := tr.RoundTrip(req)
var bad bool
if tt.wantErr == "" {
if err != nil {
bad = true
t.Errorf("case %d: error = %v; want no error", i, err)
}
} else {
if !strings.Contains(fmt.Sprint(err), tt.wantErr) {
bad = true
t.Errorf("case %d: error = %v; want error %q", i, err, tt.wantErr)
}
}
if err == nil {
if bad {
t.Logf("case %d: server got headers %q", i, res.Header.Get("Got-Header"))
}
res.Body.Close()
}
}
}
// Tests that gzipReader doesn't crash on a second Read call following
// the first Read call's gzip.NewReader returning an error.
func TestGzipReader_DoubleReadCrash(t *testing.T) {
gz := &gzipReader{
body: ioutil.NopCloser(strings.NewReader("0123456789")),
}
var buf [1]byte
n, err1 := gz.Read(buf[:])
if n != 0 || !strings.Contains(fmt.Sprint(err1), "invalid header") {
t.Fatalf("Read = %v, %v; want 0, invalid header", n, err1)
}
n, err2 := gz.Read(buf[:])
if n != 0 || err2 != err1 {
t.Fatalf("second Read = %v, %v; want 0, %v", n, err2, err1)
}
}
func TestTransportNewTLSConfig(t *testing.T) {
tests := [...]struct {
conf *tls.Config
host string
want *tls.Config
}{
// Normal case.
0: {
conf: nil,
host: "foo.com",
want: &tls.Config{
ServerName: "foo.com",
NextProtos: []string{NextProtoTLS},
},
},
// User-provided name (bar.com) takes precedence:
1: {
conf: &tls.Config{
ServerName: "bar.com",
},
host: "foo.com",
want: &tls.Config{
ServerName: "bar.com",
NextProtos: []string{NextProtoTLS},
},
},
// NextProto is prepended:
2: {
conf: &tls.Config{
NextProtos: []string{"foo", "bar"},
},
host: "example.com",
want: &tls.Config{
ServerName: "example.com",
NextProtos: []string{NextProtoTLS, "foo", "bar"},
},
},
// NextProto is not duplicated:
3: {
conf: &tls.Config{
NextProtos: []string{"foo", "bar", NextProtoTLS},
},
host: "example.com",
want: &tls.Config{
ServerName: "example.com",
NextProtos: []string{"foo", "bar", NextProtoTLS},
},
},
}
for i, tt := range tests {
tr := &Transport{TLSClientConfig: tt.conf}
got := tr.newTLSConfig(tt.host)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("%d. got %#v; want %#v", i, got, tt.want)
}
}
}
// The Google GFE responds to HEAD requests with a HEADERS frame
// without END_STREAM, followed by a 0-length DATA frame with
// END_STREAM. Make sure we don't get confused by that. (We did.)
func TestTransportReadHeadResponse(t *testing.T) {
ct := newClientTester(t)
clientDone := make(chan struct{})
ct.client = func() error {
defer close(clientDone)
req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != nil {
return err
}
if res.ContentLength != 123 {
return fmt.Errorf("Content-Length = %d; want 123", res.ContentLength)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("ReadAll: %v", err)
}
if len(slurp) > 0 {
return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp)
}
return nil
}
ct.server = func() error {
ct.greet()
for {
f, err := ct.fr.ReadFrame()
if err != nil {
t.Logf("ReadFrame: %v", err)
return nil
}
hf, ok := f.(*HeadersFrame)
if !ok {
continue
}
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false, // as the GFE does
BlockFragment: buf.Bytes(),
})
ct.fr.WriteData(hf.StreamID, true, nil)
<-clientDone
return nil
}
}
ct.run()
}
type neverEnding byte
func (b neverEnding) Read(p []byte) (int, error) {
for i := range p {
p[i] = byte(b)
}
return len(p), nil
}
// golang.org/issue/15425: test that a handler closing the request
// body doesn't terminate the stream to the peer. (It just stops
// readability from the handler's side, and eventually the client
// runs out of flow control tokens)
func TestTransportHandlerBodyClose(t *testing.T) {
const bodySize = 10 << 20
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
r.Body.Close()
io.Copy(w, io.LimitReader(neverEnding('A'), bodySize))
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
g0 := runtime.NumGoroutine()
const numReq = 10
for i := 0; i < numReq; i++ {
req, err := http.NewRequest("POST", st.ts.URL, struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)})
if err != nil {
t.Fatal(err)
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
n, err := io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
if n != bodySize || err != nil {
t.Fatalf("req#%d: Copy = %d, %v; want %d, nil", i, n, err, bodySize)
}
}
tr.CloseIdleConnections()
gd := runtime.NumGoroutine() - g0
if gd > numReq/2 {
t.Errorf("appeared to leak goroutines")
}
}
// https://golang.org/issue/15930
func TestTransportFlowControl(t *testing.T) {
const (
total = 100 << 20 // 100MB
bufLen = 1 << 16
)
var wrote int64 // updated atomically
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
b := make([]byte, bufLen)
for wrote < total {
n, err := w.Write(b)
atomic.AddInt64(&wrote, int64(n))
if err != nil {
t.Errorf("ResponseWriter.Write error: %v", err)
break
}
w.(http.Flusher).Flush()
}
}, optOnlyServer)
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal("NewRequest error:", err)
}
resp, err := tr.RoundTrip(req)
if err != nil {
t.Fatal("RoundTrip error:", err)
}
defer resp.Body.Close()
var read int64
b := make([]byte, bufLen)
for {
n, err := resp.Body.Read(b)
if err == io.EOF {
break
}
if err != nil {
t.Fatal("Read error:", err)
}
read += int64(n)
const max = transportDefaultStreamFlow
if w := atomic.LoadInt64(&wrote); -max > read-w || read-w > max {
t.Fatalf("Too much data inflight: server wrote %v bytes but client only received %v", w, read)
}
// Let the server get ahead of the client.
time.Sleep(1 * time.Millisecond)
}
}
// golang.org/issue/14627 -- if the server sends a GOAWAY frame, make
// the Transport remember it and return it back to users (via
// RoundTrip or request body reads) if needed (e.g. if the server
// proceeds to close the TCP connection before the client gets its
// response)
func TestTransportUsesGoAwayDebugError_RoundTrip(t *testing.T) {
testTransportUsesGoAwayDebugError(t, false)
}
func TestTransportUsesGoAwayDebugError_Body(t *testing.T) {
testTransportUsesGoAwayDebugError(t, true)
}
func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) {
ct := newClientTester(t)
clientDone := make(chan struct{})
const goAwayErrCode = ErrCodeHTTP11Required // arbitrary
const goAwayDebugData = "some debug data"
ct.client = func() error {
defer close(clientDone)
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if failMidBody {
if err != nil {
return fmt.Errorf("unexpected client RoundTrip error: %v", err)
}
_, err = io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
}
want := GoAwayError{
LastStreamID: 5,
ErrCode: goAwayErrCode,
DebugData: goAwayDebugData,
}
if !reflect.DeepEqual(err, want) {
t.Errorf("RoundTrip error = %T: %#v, want %T (%#v)", err, err, want, want)
}
return nil
}
ct.server = func() error {
ct.greet()
for {
f, err := ct.fr.ReadFrame()
if err != nil {
t.Logf("ReadFrame: %v", err)
return nil
}
hf, ok := f.(*HeadersFrame)
if !ok {
continue
}
if failMidBody {
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
}
// Write two GOAWAY frames, to test that the Transport takes
// the interesting parts of both.
ct.fr.WriteGoAway(5, ErrCodeNo, []byte(goAwayDebugData))
ct.fr.WriteGoAway(5, goAwayErrCode, nil)
ct.sc.(*net.TCPConn).CloseWrite()
<-clientDone
return nil
}
}
ct.run()
}
// See golang.org/issue/16481
func TestTransportReturnsUnusedFlowControl(t *testing.T) {
ct := newClientTester(t)
clientClosed := make(chan bool, 1)
serverWroteBody := make(chan bool, 1)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != nil {
return err
}
<-serverWroteBody
if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 {
return fmt.Errorf("body read = %v, %v; want 1, nil", n, err)
}
res.Body.Close() // leaving 4999 bytes unread
clientClosed <- true
return nil
}
ct.server = func() error {
ct.greet()
var hf *HeadersFrame
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
}
switch f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
continue
}
var ok bool
hf, ok = f.(*HeadersFrame)
if !ok {
return fmt.Errorf("Got %T; want HeadersFrame", f)
}
break
}
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
ct.fr.WriteData(hf.StreamID, false, make([]byte, 5000)) // without ending stream
serverWroteBody <- true
<-clientClosed
waitingFor := "RSTStreamFrame"
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return fmt.Errorf("ReadFrame while waiting for %s: %v", waitingFor, err)
}
if _, ok := f.(*SettingsFrame); ok {
continue
}
switch waitingFor {
case "RSTStreamFrame":
if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel {
return fmt.Errorf("Expected a WindowUpdateFrame with code cancel; got %v", summarizeFrame(f))
}
waitingFor = "WindowUpdateFrame"
case "WindowUpdateFrame":
if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != 4999 {
return fmt.Errorf("Expected WindowUpdateFrame for 4999 bytes; got %v", summarizeFrame(f))
}
return nil
}
}
}
ct.run()
}
// Issue 16612: adjust flow control on open streams when transport
// receives SETTINGS with INITIAL_WINDOW_SIZE from server.
func TestTransportAdjustsFlowControl(t *testing.T) {
ct := newClientTester(t)
clientDone := make(chan struct{})
const bodySize = 1 << 20
ct.client = func() error {
defer ct.cc.(*net.TCPConn).CloseWrite()
defer close(clientDone)
req, _ := http.NewRequest("POST", "https://dummy.tld/", struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)})
res, err := ct.tr.RoundTrip(req)
if err != nil {
return err
}
res.Body.Close()
return nil
}
ct.server = func() error {
_, err := io.ReadFull(ct.sc, make([]byte, len(ClientPreface)))
if err != nil {
return fmt.Errorf("reading client preface: %v", err)
}
var gotBytes int64
var sentSettings bool
for {
f, err := ct.fr.ReadFrame()
if err != nil {
select {
case <-clientDone:
return nil
default:
return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
}
}
switch f := f.(type) {
case *DataFrame:
gotBytes += int64(len(f.Data()))
// After we've got half the client's
// initial flow control window's worth
// of request body data, give it just
// enough flow control to finish.
if gotBytes >= initialWindowSize/2 && !sentSettings {
sentSettings = true
ct.fr.WriteSettings(Setting{ID: SettingInitialWindowSize, Val: bodySize})
ct.fr.WriteWindowUpdate(0, bodySize)
ct.fr.WriteSettingsAck()
}
if f.StreamEnded() {
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: f.StreamID,
EndHeaders: true,
EndStream: true,
BlockFragment: buf.Bytes(),
})
}
}
}
}
ct.run()
}
// See golang.org/issue/16556
func TestTransportReturnsDataPaddingFlowControl(t *testing.T) {
ct := newClientTester(t)
unblockClient := make(chan bool, 1)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err != nil {
return err
}
defer res.Body.Close()
<-unblockClient
return nil
}
ct.server = func() error {
ct.greet()
var hf *HeadersFrame
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
}
switch f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
continue
}
var ok bool
hf, ok = f.(*HeadersFrame)
if !ok {
return fmt.Errorf("Got %T; want HeadersFrame", f)
}
break
}
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"})
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
pad := []byte("12345")
ct.fr.WriteDataPadded(hf.StreamID, false, make([]byte, 5000), pad) // without ending stream
f, err := ct.readNonSettingsFrame()
if err != nil {
return fmt.Errorf("ReadFrame while waiting for first WindowUpdateFrame: %v", err)
}
wantBack := uint32(len(pad)) + 1 // one byte for the length of the padding
if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID != 0 {
return fmt.Errorf("Expected conn WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f))
}
f, err = ct.readNonSettingsFrame()
if err != nil {
return fmt.Errorf("ReadFrame while waiting for second WindowUpdateFrame: %v", err)
}
if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID == 0 {
return fmt.Errorf("Expected stream WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f))
}
unblockClient <- true
return nil
}
ct.run()
}
// golang.org/issue/16572 -- RoundTrip shouldn't hang when it gets a
// StreamError as a result of the response HEADERS
func TestTransportReturnsErrorOnBadResponseHeaders(t *testing.T) {
ct := newClientTester(t)
ct.client = func() error {
req, _ := http.NewRequest("GET", "https://dummy.tld/", nil)
res, err := ct.tr.RoundTrip(req)
if err == nil {
res.Body.Close()
return errors.New("unexpected successful GET")
}
want := StreamError{1, ErrCodeProtocol, headerFieldNameError(" content-type")}
if !reflect.DeepEqual(want, err) {
t.Errorf("RoundTrip error = %#v; want %#v", err, want)
}
return nil
}
ct.server = func() error {
ct.greet()
hf, err := ct.firstHeaders()
if err != nil {
return err
}
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
enc.WriteField(hpack.HeaderField{Name: " content-type", Value: "bogus"}) // bogus spaces
ct.fr.WriteHeaders(HeadersFrameParam{
StreamID: hf.StreamID,
EndHeaders: true,
EndStream: false,
BlockFragment: buf.Bytes(),
})
for {
fr, err := ct.readFrame()
if err != nil {
return fmt.Errorf("error waiting for RST_STREAM from client: %v", err)
}
if _, ok := fr.(*SettingsFrame); ok {
continue
}
if rst, ok := fr.(*RSTStreamFrame); !ok || rst.StreamID != 1 || rst.ErrCode != ErrCodeProtocol {
t.Errorf("Frame = %v; want RST_STREAM for stream 1 with ErrCodeProtocol", summarizeFrame(fr))
}
break
}
return nil
}
ct.run()
}
// byteAndEOFReader returns is in an io.Reader which reads one byte
// (the underlying byte) and io.EOF at once in its Read call.
type byteAndEOFReader byte
func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
if len(p) == 0 {
panic("unexpected useless call")
}
p[0] = byte(b)
return 1, io.EOF
}
// Issue 16788: the Transport had a regression where it started
// sending a spurious DATA frame with a duplicate END_STREAM bit after
// the request body writer goroutine had already read an EOF from the
// Request.Body and included the END_STREAM on a data-carrying DATA
// frame.
//
// Notably, to trigger this, the requests need to use a Request.Body
// which returns (non-0, io.EOF) and also needs to set the ContentLength
// explicitly.
func TestTransportBodyDoubleEndStream(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
// Nothing.
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
for i := 0; i < 2; i++ {
req, _ := http.NewRequest("POST", st.ts.URL, byteAndEOFReader('a'))
req.ContentLength = 1
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatalf("failure on req %d: %v", i+1, err)
}
defer res.Body.Close()
}
}
// golangorg/issue/16847
func TestTransportRequestPathPseudo(t *testing.T) {
type result struct {
path string
err string
}
tests := []struct {
req *http.Request
want result
}{
0: {
req: &http.Request{
Method: "GET",
URL: &url.URL{
Host: "foo.com",
Path: "/foo",
},
},
want: result{path: "/foo"},
},
// I guess we just don't let users request "//foo" as
// a path, since it's illegal to start with two
// slashes....
1: {
req: &http.Request{
Method: "GET",
URL: &url.URL{
Host: "foo.com",
Path: "//foo",
},
},
want: result{err: `invalid request :path "//foo"`},
},
// Opaque with //$Matching_Hostname/path
2: {
req: &http.Request{
Method: "GET",
URL: &url.URL{
Scheme: "https",
Opaque: "//foo.com/path",
Host: "foo.com",
Path: "/ignored",
},
},
want: result{path: "/path"},
},
// Opaque with some other Request.Host instead:
3: {
req: &http.Request{
Method: "GET",
Host: "bar.com",
URL: &url.URL{
Scheme: "https",
Opaque: "//bar.com/path",
Host: "foo.com",
Path: "/ignored",
},
},
want: result{path: "/path"},
},
// Opaque without the leading "//":
4: {
req: &http.Request{
Method: "GET",
URL: &url.URL{
Opaque: "/path",
Host: "foo.com",
Path: "/ignored",
},
},
want: result{path: "/path"},
},
// Opaque we can't handle:
5: {
req: &http.Request{
Method: "GET",
URL: &url.URL{
Scheme: "https",
Opaque: "//unknown_host/path",
Host: "foo.com",
Path: "/ignored",
},
},
want: result{err: `invalid request :path "https://unknown_host/path" from URL.Opaque = "//unknown_host/path"`},
},
// A CONNECT request:
6: {
req: &http.Request{
Method: "CONNECT",
URL: &url.URL{
Host: "foo.com",
},
},
want: result{},
},
}
for i, tt := range tests {
cc := &ClientConn{}
cc.henc = hpack.NewEncoder(&cc.hbuf)
cc.mu.Lock()
hdrs, err := cc.encodeHeaders(tt.req, false, "", -1)
cc.mu.Unlock()
var got result
hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) {
if f.Name == ":path" {
got.path = f.Value
}
})
if err != nil {
got.err = err.Error()
} else if len(hdrs) > 0 {
if _, err := hpackDec.Write(hdrs); err != nil {
t.Errorf("%d. bogus hpack: %v", i, err)
continue
}
}
if got != tt.want {
t.Errorf("%d. got %+v; want %+v", i, got, tt.want)
}
}
}
// golang.org/issue/17071 -- don't sniff the first byte of the request body
// before we've determined that the ClientConn is usable.
func TestRoundTripDoesntConsumeRequestBodyEarly(t *testing.T) {
const body = "foo"
req, _ := http.NewRequest("POST", "http://foo.com/", ioutil.NopCloser(strings.NewReader(body)))
cc := &ClientConn{
closed: true,
}
_, err := cc.RoundTrip(req)
if err != errClientConnUnusable {
t.Fatalf("RoundTrip = %v; want errClientConnUnusable", err)
}
slurp, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Errorf("ReadAll = %v", err)
}
if string(slurp) != body {
t.Errorf("Body = %q; want %q", slurp, body)
}
}
func TestClientConnPing(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false)
if err != nil {
t.Fatal(err)
}
if err = cc.Ping(testContext{}); err != nil {
t.Fatal(err)
}
}
|