quiche/h3/mod.rs
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 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196
// Copyright (C) 2019, Cloudflare, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//! HTTP/3 wire protocol and QPACK implementation.
//!
//! This module provides a high level API for sending and receiving HTTP/3
//! requests and responses on top of the QUIC transport protocol.
//!
//! ## Connection setup
//!
//! HTTP/3 connections require a QUIC transport-layer connection, see
//! [Connection setup] for a full description of the setup process.
//!
//! To use HTTP/3, the QUIC connection must be configured with a suitable
//! Application Layer Protocol Negotiation (ALPN) Protocol ID:
//!
//! ```
//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
//! config.set_application_protos(quiche::h3::APPLICATION_PROTOCOL)?;
//! # Ok::<(), quiche::Error>(())
//! ```
//!
//! The QUIC handshake is driven by [sending] and [receiving] QUIC packets.
//!
//! Once the handshake has completed, the first step in establishing an HTTP/3
//! connection is creating its configuration object:
//!
//! ```
//! let h3_config = quiche::h3::Config::new()?;
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! HTTP/3 client and server connections are both created using the
//! [`with_transport()`] function, the role is inferred from the type of QUIC
//! connection:
//!
//! ```no_run
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
//! # let peer = "127.0.0.1:1234".parse().unwrap();
//! # let local = "127.0.0.1:4321".parse().unwrap();
//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! let h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! ## Sending a request
//!
//! An HTTP/3 client can send a request by using the connection's
//! [`send_request()`] method to queue request headers; [sending] QUIC packets
//! causes the requests to get sent to the peer:
//!
//! ```no_run
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
//! # let peer = "127.0.0.1:1234".parse().unwrap();
//! # let local = "127.0.0.1:4321".parse().unwrap();
//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! let req = vec![
//! quiche::h3::Header::new(b":method", b"GET"),
//! quiche::h3::Header::new(b":scheme", b"https"),
//! quiche::h3::Header::new(b":authority", b"quic.tech"),
//! quiche::h3::Header::new(b":path", b"/"),
//! quiche::h3::Header::new(b"user-agent", b"quiche"),
//! ];
//!
//! h3_conn.send_request(&mut conn, &req, true)?;
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! An HTTP/3 client can send a request with additional body data by using
//! the connection's [`send_body()`] method:
//!
//! ```no_run
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
//! # let peer = "127.0.0.1:1234".parse().unwrap();
//! # let local = "127.0.0.1:4321".parse().unwrap();
//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! let req = vec![
//! quiche::h3::Header::new(b":method", b"GET"),
//! quiche::h3::Header::new(b":scheme", b"https"),
//! quiche::h3::Header::new(b":authority", b"quic.tech"),
//! quiche::h3::Header::new(b":path", b"/"),
//! quiche::h3::Header::new(b"user-agent", b"quiche"),
//! ];
//!
//! let stream_id = h3_conn.send_request(&mut conn, &req, false)?;
//! h3_conn.send_body(&mut conn, stream_id, b"Hello World!", true)?;
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! ## Handling requests and responses
//!
//! After [receiving] QUIC packets, HTTP/3 data is processed using the
//! connection's [`poll()`] method. On success, this returns an [`Event`] object
//! and an ID corresponding to the stream where the `Event` originated.
//!
//! An HTTP/3 server uses [`poll()`] to read requests and responds to them using
//! [`send_response()`] and [`send_body()`]:
//!
//! ```no_run
//! use quiche::h3::NameValue;
//!
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
//! # let peer = "127.0.0.1:1234".parse().unwrap();
//! # let local = "127.0.0.1:1234".parse().unwrap();
//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! loop {
//! match h3_conn.poll(&mut conn) {
//! Ok((stream_id, quiche::h3::Event::Headers{list, more_frames})) => {
//! let mut headers = list.into_iter();
//!
//! // Look for the request's method.
//! let method = headers.find(|h| h.name() == b":method").unwrap();
//!
//! // Look for the request's path.
//! let path = headers.find(|h| h.name() == b":path").unwrap();
//!
//! if method.value() == b"GET" && path.value() == b"/" {
//! let resp = vec![
//! quiche::h3::Header::new(b":status", 200.to_string().as_bytes()),
//! quiche::h3::Header::new(b"server", b"quiche"),
//! ];
//!
//! h3_conn.send_response(&mut conn, stream_id, &resp, false)?;
//! h3_conn.send_body(&mut conn, stream_id, b"Hello World!", true)?;
//! }
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Data)) => {
//! // Request body data, handle it.
//! # return Ok(());
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Finished)) => {
//! // Peer terminated stream, handle it.
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Reset(err))) => {
//! // Peer reset the stream, handle it.
//! },
//!
//! Ok((_flow_id, quiche::h3::Event::PriorityUpdate)) => (),
//!
//! Ok((goaway_id, quiche::h3::Event::GoAway)) => {
//! // Peer signalled it is going away, handle it.
//! },
//!
//! Err(quiche::h3::Error::Done) => {
//! // Done reading.
//! break;
//! },
//!
//! Err(e) => {
//! // An error occurred, handle it.
//! break;
//! },
//! }
//! }
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! An HTTP/3 client uses [`poll()`] to read responses:
//!
//! ```no_run
//! use quiche::h3::NameValue;
//!
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
//! # let peer = "127.0.0.1:1234".parse().unwrap();
//! # let local = "127.0.0.1:1234".parse().unwrap();
//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! loop {
//! match h3_conn.poll(&mut conn) {
//! Ok((stream_id, quiche::h3::Event::Headers{list, more_frames})) => {
//! let status = list.iter().find(|h| h.name() == b":status").unwrap();
//! println!("Received {} response on stream {}",
//! std::str::from_utf8(status.value()).unwrap(),
//! stream_id);
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Data)) => {
//! let mut body = vec![0; 4096];
//!
//! // Consume all body data received on the stream.
//! while let Ok(read) =
//! h3_conn.recv_body(&mut conn, stream_id, &mut body)
//! {
//! println!("Received {} bytes of payload on stream {}",
//! read, stream_id);
//! }
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Finished)) => {
//! // Peer terminated stream, handle it.
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Reset(err))) => {
//! // Peer reset the stream, handle it.
//! },
//!
//! Ok((_prioritized_element_id, quiche::h3::Event::PriorityUpdate)) => (),
//!
//! Ok((goaway_id, quiche::h3::Event::GoAway)) => {
//! // Peer signalled it is going away, handle it.
//! },
//!
//! Err(quiche::h3::Error::Done) => {
//! // Done reading.
//! break;
//! },
//!
//! Err(e) => {
//! // An error occurred, handle it.
//! break;
//! },
//! }
//! }
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! ## Detecting end of request or response
//!
//! A single HTTP/3 request or response may consist of several HEADERS and DATA
//! frames; it is finished when the QUIC stream is closed. Calling [`poll()`]
//! repeatedly will generate an [`Event`] for each of these. The application may
//! use these event to do additional HTTP semantic validation.
//!
//! ## HTTP/3 protocol errors
//!
//! Quiche is responsible for managing the HTTP/3 connection, ensuring it is in
//! a correct state and validating all messages received by a peer. This mainly
//! takes place in the [`poll()`] method. If an HTTP/3 error occurs, quiche will
//! close the connection and send an appropriate CONNECTION_CLOSE frame to the
//! peer. An [`Error`] is returned to the application so that it can perform any
//! required tidy up such as closing sockets.
//!
//! [`application_proto()`]: ../struct.Connection.html#method.application_proto
//! [`stream_finished()`]: ../struct.Connection.html#method.stream_finished
//! [Connection setup]: ../index.html#connection-setup
//! [sending]: ../index.html#generating-outgoing-packets
//! [receiving]: ../index.html#handling-incoming-packets
//! [`with_transport()`]: struct.Connection.html#method.with_transport
//! [`poll()`]: struct.Connection.html#method.poll
//! [`Event`]: enum.Event.html
//! [`Error`]: enum.Error.html
//! [`send_request()`]: struct.Connection.html#method.send_response
//! [`send_response()`]: struct.Connection.html#method.send_response
//! [`send_body()`]: struct.Connection.html#method.send_body
use std::collections::HashSet;
use std::collections::VecDeque;
#[cfg(feature = "sfv")]
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Write;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3FrameCreated;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3FrameParsed;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3Owner;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3PriorityTargetStreamType;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3StreamType;
#[cfg(feature = "qlog")]
use qlog::events::h3::H3StreamTypeSet;
#[cfg(feature = "qlog")]
use qlog::events::h3::Http3EventType;
#[cfg(feature = "qlog")]
use qlog::events::h3::Http3Frame;
#[cfg(feature = "qlog")]
use qlog::events::EventData;
#[cfg(feature = "qlog")]
use qlog::events::EventImportance;
#[cfg(feature = "qlog")]
use qlog::events::EventType;
/// List of ALPN tokens of supported HTTP/3 versions.
///
/// This can be passed directly to the [`Config::set_application_protos()`]
/// method when implementing HTTP/3 applications.
///
/// [`Config::set_application_protos()`]:
/// ../struct.Config.html#method.set_application_protos
pub const APPLICATION_PROTOCOL: &[&[u8]] = &[b"h3"];
// The offset used when converting HTTP/3 urgency to quiche urgency.
const PRIORITY_URGENCY_OFFSET: u8 = 124;
// Parameter values as specified in [Extensible Priorities].
//
// [Extensible Priorities]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
const PRIORITY_URGENCY_LOWER_BOUND: u8 = 0;
const PRIORITY_URGENCY_UPPER_BOUND: u8 = 7;
const PRIORITY_URGENCY_DEFAULT: u8 = 3;
const PRIORITY_INCREMENTAL_DEFAULT: bool = false;
#[cfg(feature = "qlog")]
const QLOG_FRAME_CREATED: EventType =
EventType::Http3EventType(Http3EventType::FrameCreated);
#[cfg(feature = "qlog")]
const QLOG_FRAME_PARSED: EventType =
EventType::Http3EventType(Http3EventType::FrameParsed);
#[cfg(feature = "qlog")]
const QLOG_STREAM_TYPE_SET: EventType =
EventType::Http3EventType(Http3EventType::StreamTypeSet);
/// A specialized [`Result`] type for quiche HTTP/3 operations.
///
/// This type is used throughout quiche's HTTP/3 public API for any operation
/// that can produce an error.
///
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
pub type Result<T> = std::result::Result<T, Error>;
/// An HTTP/3 error.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// There is no error or no work to do
Done,
/// The provided buffer is too short.
BufferTooShort,
/// Internal error in the HTTP/3 stack.
InternalError,
/// Endpoint detected that the peer is exhibiting behavior that causes.
/// excessive load.
ExcessiveLoad,
/// Stream ID or Push ID greater that current maximum was
/// used incorrectly, such as exceeding a limit, reducing a limit,
/// or being reused.
IdError,
/// The endpoint detected that its peer created a stream that it will not
/// accept.
StreamCreationError,
/// A required critical stream was closed.
ClosedCriticalStream,
/// No SETTINGS frame at beginning of control stream.
MissingSettings,
/// A frame was received which is not permitted in the current state.
FrameUnexpected,
/// Frame violated layout or size rules.
FrameError,
/// QPACK Header block decompression failure.
QpackDecompressionFailed,
/// Error originated from the transport layer.
TransportError(crate::Error),
/// The underlying QUIC stream (or connection) doesn't have enough capacity
/// for the operation to complete. The application should retry later on.
StreamBlocked,
/// Error in the payload of a SETTINGS frame.
SettingsError,
/// Server rejected request.
RequestRejected,
/// Request or its response cancelled.
RequestCancelled,
/// Client's request stream terminated without containing a full-formed
/// request.
RequestIncomplete,
/// An HTTP message was malformed and cannot be processed.
MessageError,
/// The TCP connection established in response to a CONNECT request was
/// reset or abnormally closed.
ConnectError,
/// The requested operation cannot be served over HTTP/3. Peer should retry
/// over HTTP/1.1.
VersionFallback,
}
/// HTTP/3 error codes sent on the wire.
///
/// As defined in [RFC9114](https://www.rfc-editor.org/rfc/rfc9114.html#http-error-codes).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum WireErrorCode {
/// No error. This is used when the connection or stream needs to be closed,
/// but there is no error to signal.
NoError = 0x100,
/// Peer violated protocol requirements in a way that does not match a more
/// specific error code or endpoint declines to use the more specific
/// error code.
GeneralProtocolError = 0x101,
/// An internal error has occurred in the HTTP stack.
InternalError = 0x102,
/// The endpoint detected that its peer created a stream that it will not
/// accept.
StreamCreationError = 0x103,
/// A stream required by the HTTP/3 connection was closed or reset.
ClosedCriticalStream = 0x104,
/// A frame was received that was not permitted in the current state or on
/// the current stream.
FrameUnexpected = 0x105,
/// A frame that fails to satisfy layout requirements or with an invalid
/// size was received.
FrameError = 0x106,
/// The endpoint detected that its peer is exhibiting a behavior that might
/// be generating excessive load.
ExcessiveLoad = 0x107,
/// A stream ID or push ID was used incorrectly, such as exceeding a limit,
/// reducing a limit, or being reused.
IdError = 0x108,
/// An endpoint detected an error in the payload of a SETTINGS frame.
SettingsError = 0x109,
/// No SETTINGS frame was received at the beginning of the control stream.
MissingSettings = 0x10a,
/// A server rejected a request without performing any application
/// processing.
RequestRejected = 0x10b,
/// The request or its response (including pushed response) is cancelled.
RequestCancelled = 0x10c,
/// The client's stream terminated without containing a fully formed
/// request.
RequestIncomplete = 0x10d,
/// An HTTP message was malformed and cannot be processed.
MessageError = 0x10e,
/// The TCP connection established in response to a CONNECT request was
/// reset or abnormally closed.
ConnectError = 0x10f,
/// The requested operation cannot be served over HTTP/3. The peer should
/// retry over HTTP/1.1.
VersionFallback = 0x110,
}
impl Error {
fn to_wire(self) -> u64 {
match self {
Error::Done => WireErrorCode::NoError as u64,
Error::InternalError => WireErrorCode::InternalError as u64,
Error::StreamCreationError =>
WireErrorCode::StreamCreationError as u64,
Error::ClosedCriticalStream =>
WireErrorCode::ClosedCriticalStream as u64,
Error::FrameUnexpected => WireErrorCode::FrameUnexpected as u64,
Error::FrameError => WireErrorCode::FrameError as u64,
Error::ExcessiveLoad => WireErrorCode::ExcessiveLoad as u64,
Error::IdError => WireErrorCode::IdError as u64,
Error::MissingSettings => WireErrorCode::MissingSettings as u64,
Error::QpackDecompressionFailed => 0x200,
Error::BufferTooShort => 0x999,
Error::TransportError { .. } | Error::StreamBlocked => 0xFF,
Error::SettingsError => WireErrorCode::SettingsError as u64,
Error::RequestRejected => WireErrorCode::RequestRejected as u64,
Error::RequestCancelled => WireErrorCode::RequestCancelled as u64,
Error::RequestIncomplete => WireErrorCode::RequestIncomplete as u64,
Error::MessageError => WireErrorCode::MessageError as u64,
Error::ConnectError => WireErrorCode::ConnectError as u64,
Error::VersionFallback => WireErrorCode::VersionFallback as u64,
}
}
#[cfg(feature = "ffi")]
fn to_c(self) -> libc::ssize_t {
match self {
Error::Done => -1,
Error::BufferTooShort => -2,
Error::InternalError => -3,
Error::ExcessiveLoad => -4,
Error::IdError => -5,
Error::StreamCreationError => -6,
Error::ClosedCriticalStream => -7,
Error::MissingSettings => -8,
Error::FrameUnexpected => -9,
Error::FrameError => -10,
Error::QpackDecompressionFailed => -11,
// -12 was previously used for TransportError, skip it
Error::StreamBlocked => -13,
Error::SettingsError => -14,
Error::RequestRejected => -15,
Error::RequestCancelled => -16,
Error::RequestIncomplete => -17,
Error::MessageError => -18,
Error::ConnectError => -19,
Error::VersionFallback => -20,
Error::TransportError(quic_error) => quic_error.to_c() - 1000,
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl std::convert::From<super::Error> for Error {
fn from(err: super::Error) -> Self {
match err {
super::Error::Done => Error::Done,
_ => Error::TransportError(err),
}
}
}
impl std::convert::From<octets::BufferTooShortError> for Error {
fn from(_err: octets::BufferTooShortError) -> Self {
Error::BufferTooShort
}
}
/// An HTTP/3 configuration.
pub struct Config {
max_field_section_size: Option<u64>,
qpack_max_table_capacity: Option<u64>,
qpack_blocked_streams: Option<u64>,
connect_protocol_enabled: Option<u64>,
/// additional settings are settings that are not part of the H3
/// settings explicitly handled above
additional_settings: Option<Vec<(u64, u64)>>,
}
impl Config {
/// Creates a new configuration object with default settings.
pub const fn new() -> Result<Config> {
Ok(Config {
max_field_section_size: None,
qpack_max_table_capacity: None,
qpack_blocked_streams: None,
connect_protocol_enabled: None,
additional_settings: None,
})
}
/// Sets the `SETTINGS_MAX_FIELD_SECTION_SIZE` setting.
///
/// By default no limit is enforced. When a request whose headers exceed
/// the limit set by the application is received, the call to the [`poll()`]
/// method will return the [`Error::ExcessiveLoad`] error, and the
/// connection will be closed.
///
/// [`poll()`]: struct.Connection.html#method.poll
/// [`Error::ExcessiveLoad`]: enum.Error.html#variant.ExcessiveLoad
pub fn set_max_field_section_size(&mut self, v: u64) {
self.max_field_section_size = Some(v);
}
/// Sets the `SETTINGS_QPACK_MAX_TABLE_CAPACITY` setting.
///
/// The default value is `0`.
pub fn set_qpack_max_table_capacity(&mut self, v: u64) {
self.qpack_max_table_capacity = Some(v);
}
/// Sets the `SETTINGS_QPACK_BLOCKED_STREAMS` setting.
///
/// The default value is `0`.
pub fn set_qpack_blocked_streams(&mut self, v: u64) {
self.qpack_blocked_streams = Some(v);
}
/// Sets or omits the `SETTINGS_ENABLE_CONNECT_PROTOCOL` setting.
///
/// The default value is `false`.
pub fn enable_extended_connect(&mut self, enabled: bool) {
if enabled {
self.connect_protocol_enabled = Some(1);
} else {
self.connect_protocol_enabled = None;
}
}
/// Sets additional HTTP/3 settings.
///
/// The default value is no additional settings.
/// The `additional_settings` parameter must not the following
/// settings as they are already handled by this library:
///
/// - SETTINGS_QPACK_MAX_TABLE_CAPACITY
/// - SETTINGS_MAX_FIELD_SECTION_SIZE
/// - SETTINGS_QPACK_BLOCKED_STREAMS
/// - SETTINGS_ENABLE_CONNECT_PROTOCOL
/// - SETTINGS_H3_DATAGRAM
///
/// If such a setting is present in the `additional_settings`,
/// the method will return the [`Error::SettingsError`] error.
///
/// If a setting identifier is present twice in `additional_settings`,
/// the method will return the [`Error::SettingsError`] error.
///
/// [`Error::SettingsError`]: enum.Error.html#variant.SettingsError
pub fn set_additional_settings(
&mut self, additional_settings: Vec<(u64, u64)>,
) -> Result<()> {
let explicit_quiche_settings = HashSet::from([
frame::SETTINGS_QPACK_MAX_TABLE_CAPACITY,
frame::SETTINGS_MAX_FIELD_SECTION_SIZE,
frame::SETTINGS_QPACK_BLOCKED_STREAMS,
frame::SETTINGS_ENABLE_CONNECT_PROTOCOL,
frame::SETTINGS_H3_DATAGRAM,
frame::SETTINGS_H3_DATAGRAM_00,
]);
let dedup_settings: HashSet<u64> =
additional_settings.iter().map(|(key, _)| *key).collect();
if dedup_settings.len() != additional_settings.len() ||
!explicit_quiche_settings.is_disjoint(&dedup_settings)
{
return Err(Error::SettingsError);
}
self.additional_settings = Some(additional_settings);
Ok(())
}
}
/// A trait for types with associated string name and value.
pub trait NameValue {
/// Returns the object's name.
fn name(&self) -> &[u8];
/// Returns the object's value.
fn value(&self) -> &[u8];
}
impl<N, V> NameValue for (N, V)
where
N: AsRef<[u8]>,
V: AsRef<[u8]>,
{
fn name(&self) -> &[u8] {
self.0.as_ref()
}
fn value(&self) -> &[u8] {
self.1.as_ref()
}
}
/// An owned name-value pair representing a raw HTTP header.
#[derive(Clone, PartialEq, Eq)]
pub struct Header(Vec<u8>, Vec<u8>);
fn try_print_as_readable(hdr: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
match std::str::from_utf8(hdr) {
Ok(s) => f.write_str(&s.escape_default().to_string()),
Err(_) => write!(f, "{hdr:?}"),
}
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_char('"')?;
try_print_as_readable(&self.0, f)?;
f.write_str(": ")?;
try_print_as_readable(&self.1, f)?;
f.write_char('"')
}
}
impl Header {
/// Creates a new header.
///
/// Both `name` and `value` will be cloned.
pub fn new(name: &[u8], value: &[u8]) -> Self {
Self(name.to_vec(), value.to_vec())
}
}
impl NameValue for Header {
fn name(&self) -> &[u8] {
&self.0
}
fn value(&self) -> &[u8] {
&self.1
}
}
/// A non-owned name-value pair representing a raw HTTP header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HeaderRef<'a>(&'a [u8], &'a [u8]);
impl<'a> HeaderRef<'a> {
/// Creates a new header.
pub const fn new(name: &'a [u8], value: &'a [u8]) -> Self {
Self(name, value)
}
}
impl<'a> NameValue for HeaderRef<'a> {
fn name(&self) -> &[u8] {
self.0
}
fn value(&self) -> &[u8] {
self.1
}
}
/// An HTTP/3 connection event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
/// Request/response headers were received.
Headers {
/// The list of received header fields. The application should validate
/// pseudo-headers and headers.
list: Vec<Header>,
/// Whether more frames will follow the headers on the stream.
more_frames: bool,
},
/// Data was received.
///
/// This indicates that the application can use the [`recv_body()`] method
/// to retrieve the data from the stream.
///
/// Note that [`recv_body()`] will need to be called repeatedly until the
/// [`Done`] value is returned, as the event will not be re-armed until all
/// buffered data is read.
///
/// [`recv_body()`]: struct.Connection.html#method.recv_body
/// [`Done`]: enum.Error.html#variant.Done
Data,
/// Stream was closed,
Finished,
/// Stream was reset.
///
/// The associated data represents the error code sent by the peer.
Reset(u64),
/// PRIORITY_UPDATE was received.
///
/// This indicates that the application can use the
/// [`take_last_priority_update()`] method to take the last received
/// PRIORITY_UPDATE for a specified stream.
///
/// This event is triggered once per stream until the last PRIORITY_UPDATE
/// is taken. It is recommended that applications defer taking the
/// PRIORITY_UPDATE until after [`poll()`] returns [`Done`].
///
/// [`take_last_priority_update()`]: struct.Connection.html#method.take_last_priority_update
/// [`poll()`]: struct.Connection.html#method.poll
/// [`Done`]: enum.Error.html#variant.Done
PriorityUpdate,
/// GOAWAY was received.
GoAway,
}
/// Extensible Priorities parameters.
///
/// The `TryFrom` trait supports constructing this object from the serialized
/// Structured Fields Dictionary field value. I.e, use `TryFrom` to parse the
/// value of a Priority header field or a PRIORITY_UPDATE frame. Using this
/// trait requires the `sfv` feature to be enabled.
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Priority {
urgency: u8,
incremental: bool,
}
impl Default for Priority {
fn default() -> Self {
Priority {
urgency: PRIORITY_URGENCY_DEFAULT,
incremental: PRIORITY_INCREMENTAL_DEFAULT,
}
}
}
impl Priority {
/// Creates a new Priority.
pub const fn new(urgency: u8, incremental: bool) -> Self {
Priority {
urgency,
incremental,
}
}
}
#[cfg(feature = "sfv")]
#[cfg_attr(docsrs, doc(cfg(feature = "sfv")))]
impl TryFrom<&[u8]> for Priority {
type Error = crate::h3::Error;
/// Try to parse an Extensible Priority field value.
///
/// The field value is expected to be a Structured Fields Dictionary; see
/// [Extensible Priorities].
///
/// If the `u` or `i` fields are contained with correct types, a constructed
/// Priority object is returned. Note that urgency values outside of valid
/// range (0 through 7) are clamped to 7.
///
/// If the `u` or `i` fields are contained with the wrong types,
/// Error::Done is returned.
///
/// Omitted parameters will yield default values.
///
/// [Extensible Priorities]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
fn try_from(value: &[u8]) -> std::result::Result<Self, Self::Error> {
let dict = match sfv::Parser::parse_dictionary(value) {
Ok(v) => v,
Err(_) => return Err(Error::Done),
};
let urgency = match dict.get("u") {
// If there is a u parameter, try to read it as an Item of type
// Integer. If the value out of the spec's allowed range
// (0 through 7), that's an error so set it to the upper
// bound (lowest priority) to avoid interference with
// other streams.
Some(sfv::ListEntry::Item(item)) => match item.bare_item.as_int() {
Some(v) => {
if !(PRIORITY_URGENCY_LOWER_BOUND as i64..=
PRIORITY_URGENCY_UPPER_BOUND as i64)
.contains(&v)
{
PRIORITY_URGENCY_UPPER_BOUND
} else {
v as u8
}
},
None => return Err(Error::Done),
},
Some(sfv::ListEntry::InnerList(_)) => return Err(Error::Done),
// Omitted so use default value.
None => PRIORITY_URGENCY_DEFAULT,
};
let incremental = match dict.get("i") {
Some(sfv::ListEntry::Item(item)) =>
item.bare_item.as_bool().ok_or(Error::Done)?,
// Omitted so use default value.
_ => false,
};
Ok(Priority::new(urgency, incremental))
}
}
struct ConnectionSettings {
pub max_field_section_size: Option<u64>,
pub qpack_max_table_capacity: Option<u64>,
pub qpack_blocked_streams: Option<u64>,
pub connect_protocol_enabled: Option<u64>,
pub h3_datagram: Option<u64>,
pub additional_settings: Option<Vec<(u64, u64)>>,
pub raw: Option<Vec<(u64, u64)>>,
}
#[derive(Default)]
struct QpackStreams {
pub encoder_stream_id: Option<u64>,
pub encoder_stream_bytes: u64,
pub decoder_stream_id: Option<u64>,
pub decoder_stream_bytes: u64,
}
/// Statistics about the connection.
///
/// A connection's statistics can be collected using the [`stats()`] method.
///
/// [`stats()`]: struct.Connection.html#method.stats
#[derive(Clone, Default)]
pub struct Stats {
/// The number of bytes received on the QPACK encoder stream.
pub qpack_encoder_stream_recv_bytes: u64,
/// The number of bytes received on the QPACK decoder stream.
pub qpack_decoder_stream_recv_bytes: u64,
}
fn close_conn_critical_stream(conn: &mut super::Connection) -> Result<()> {
conn.close(
true,
Error::ClosedCriticalStream.to_wire(),
b"Critical stream closed.",
)?;
Err(Error::ClosedCriticalStream)
}
fn close_conn_if_critical_stream_finished(
conn: &mut super::Connection, stream_id: u64,
) -> Result<()> {
if conn.stream_finished(stream_id) {
close_conn_critical_stream(conn)?;
}
Ok(())
}
/// An HTTP/3 connection.
pub struct Connection {
is_server: bool,
next_request_stream_id: u64,
next_uni_stream_id: u64,
streams: crate::stream::StreamIdHashMap<stream::Stream>,
local_settings: ConnectionSettings,
peer_settings: ConnectionSettings,
control_stream_id: Option<u64>,
peer_control_stream_id: Option<u64>,
qpack_encoder: qpack::Encoder,
qpack_decoder: qpack::Decoder,
local_qpack_streams: QpackStreams,
peer_qpack_streams: QpackStreams,
max_push_id: u64,
finished_streams: VecDeque<u64>,
frames_greased: bool,
local_goaway_id: Option<u64>,
peer_goaway_id: Option<u64>,
}
impl Connection {
fn new(
config: &Config, is_server: bool, enable_dgram: bool,
) -> Result<Connection> {
let initial_uni_stream_id = if is_server { 0x3 } else { 0x2 };
let h3_datagram = if enable_dgram { Some(1) } else { None };
Ok(Connection {
is_server,
next_request_stream_id: 0,
next_uni_stream_id: initial_uni_stream_id,
streams: Default::default(),
local_settings: ConnectionSettings {
max_field_section_size: config.max_field_section_size,
qpack_max_table_capacity: config.qpack_max_table_capacity,
qpack_blocked_streams: config.qpack_blocked_streams,
connect_protocol_enabled: config.connect_protocol_enabled,
h3_datagram,
additional_settings: config.additional_settings.clone(),
raw: Default::default(),
},
peer_settings: ConnectionSettings {
max_field_section_size: None,
qpack_max_table_capacity: None,
qpack_blocked_streams: None,
h3_datagram: None,
connect_protocol_enabled: None,
additional_settings: Default::default(),
raw: Default::default(),
},
control_stream_id: None,
peer_control_stream_id: None,
qpack_encoder: qpack::Encoder::new(),
qpack_decoder: qpack::Decoder::new(),
local_qpack_streams: Default::default(),
peer_qpack_streams: Default::default(),
max_push_id: 0,
finished_streams: VecDeque::new(),
frames_greased: false,
local_goaway_id: None,
peer_goaway_id: None,
})
}
/// Creates a new HTTP/3 connection using the provided QUIC connection.
///
/// This will also initiate the HTTP/3 handshake with the peer by opening
/// all control streams (including QPACK) and sending the local settings.
///
/// On success the new connection is returned.
///
/// The [`StreamLimit`] error is returned when the HTTP/3 control stream
/// cannot be created due to stream limits.
///
/// The [`InternalError`] error is returned when either the underlying QUIC
/// connection is not in a suitable state, or the HTTP/3 control stream
/// cannot be created due to flow control limits.
///
/// [`StreamLimit`]: ../enum.Error.html#variant.StreamLimit
/// [`InternalError`]: ../enum.Error.html#variant.InternalError
pub fn with_transport(
conn: &mut super::Connection, config: &Config,
) -> Result<Connection> {
let is_client = !conn.is_server;
if is_client && !(conn.is_established() || conn.is_in_early_data()) {
trace!("{} QUIC connection must be established or in early data before creating an HTTP/3 connection", conn.trace_id());
return Err(Error::InternalError);
}
let mut http3_conn =
Connection::new(config, conn.is_server, conn.dgram_enabled())?;
match http3_conn.send_settings(conn) {
Ok(_) => (),
Err(e) => {
conn.close(true, e.to_wire(), b"Error opening control stream")?;
return Err(e);
},
};
// Try opening QPACK streams, but ignore errors if it fails since we
// don't need them right now.
http3_conn.open_qpack_encoder_stream(conn).ok();
http3_conn.open_qpack_decoder_stream(conn).ok();
if conn.grease {
// Try opening a GREASE stream, but ignore errors since it's not
// critical.
http3_conn.open_grease_stream(conn).ok();
}
Ok(http3_conn)
}
/// Sends an HTTP/3 request.
///
/// The request is encoded from the provided list of headers without a
/// body, and sent on a newly allocated stream. To include a body,
/// set `fin` as `false` and subsequently call [`send_body()`] with the
/// same `conn` and the `stream_id` returned from this method.
///
/// On success the newly allocated stream ID is returned.
///
/// The [`StreamBlocked`] error is returned when the underlying QUIC stream
/// doesn't have enough capacity for the operation to complete. When this
/// happens the application should retry the operation once the stream is
/// reported as writable again.
///
/// [`send_body()`]: struct.Connection.html#method.send_body
/// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
pub fn send_request<T: NameValue>(
&mut self, conn: &mut super::Connection, headers: &[T], fin: bool,
) -> Result<u64> {
// If we received a GOAWAY from the peer, MUST NOT initiate new
// requests.
if self.peer_goaway_id.is_some() {
return Err(Error::FrameUnexpected);
}
let stream_id = self.next_request_stream_id;
self.streams
.insert(stream_id, stream::Stream::new(stream_id, true));
// The underlying QUIC stream does not exist yet, so calls to e.g.
// stream_capacity() will fail. By writing a 0-length buffer, we force
// the creation of the QUIC stream state, without actually writing
// anything.
if let Err(e) = conn.stream_send(stream_id, b"", false) {
self.streams.remove(&stream_id);
if e == super::Error::Done {
return Err(Error::StreamBlocked);
}
return Err(e.into());
};
self.send_headers(conn, stream_id, headers, fin)?;
// To avoid skipping stream IDs, we only calculate the next available
// stream ID when a request has been successfully buffered.
self.next_request_stream_id = self
.next_request_stream_id
.checked_add(4)
.ok_or(Error::IdError)?;
Ok(stream_id)
}
/// Sends an HTTP/3 response on the specified stream with default priority.
///
/// This method sends the provided `headers` as a single initial response
/// without a body.
///
/// To send a non-final 1xx, then a final 200+ without body:
/// * send_response() with `fin` set to `false`.
/// * [`send_additional_headers()`] with fin set to `true` using the same
/// `stream_id` value.
///
/// To send a non-final 1xx, then a final 200+ with body:
/// * send_response() with `fin` set to `false`.
/// * [`send_additional_headers()`] with fin set to `false` and same
/// `stream_id` value.
/// * [`send_body()`] with same `stream_id`.
///
/// To send a final 200+ with body:
/// * send_response() with `fin` set to `false`.
/// * [`send_body()`] with same `stream_id`.
///
/// Additional headers can only be sent during certain phases of an HTTP/3
/// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
/// error is returned if this method, or [`send_response_with_priority()`],
/// are called multiple times with the same `stream_id` value.
///
/// The [`StreamBlocked`] error is returned when the underlying QUIC stream
/// doesn't have enough capacity for the operation to complete. When this
/// happens the application should retry the operation once the stream is
/// reported as writable again.
///
/// [`send_body()`]: struct.Connection.html#method.send_body
/// [`send_additional_headers()`]:
/// struct.Connection.html#method.send_additional_headers
/// [`send_response_with_priority()`]:
/// struct.Connection.html#method.send_response_with_priority
/// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
pub fn send_response<T: NameValue>(
&mut self, conn: &mut super::Connection, stream_id: u64, headers: &[T],
fin: bool,
) -> Result<()> {
let priority = Default::default();
self.send_response_with_priority(
conn, stream_id, headers, &priority, fin,
)?;
Ok(())
}
/// Sends an HTTP/3 response on the specified stream with specified
/// priority.
///
/// The `priority` parameter represents [Extensible Priority]
/// parameters. If the urgency is outside the range 0-7, it will be clamped
/// to 7.
///
/// This method sends the provided `headers` as a single initial response
/// without a body.
///
/// To send a non-final 1xx, then a final 200+ without body:
/// * send_response_with_priority() with `fin` set to `false`.
/// * [`send_additional_headers()`] with fin set to `true` using the same
/// `stream_id` value.
///
/// To send a non-final 1xx, then a final 200+ with body:
/// * send_response_with_priority() with `fin` set to `false`.
/// * [`send_additional_headers()`] with fin set to `false` and same
/// `stream_id` value.
/// * [`send_body()`] with same `stream_id`.
///
/// To send a final 200+ with body:
/// * send_response_with_priority() with `fin` set to `false`.
/// * [`send_body()`] with same `stream_id`.
///
/// Additional headers can only be sent during certain phases of an HTTP/3
/// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
/// error is returned if this method, or [`send_response()`],
/// are called multiple times with the same `stream_id` value.
///
/// The [`StreamBlocked`] error is returned when the underlying QUIC stream
/// doesn't have enough capacity for the operation to complete. When this
/// happens the application should retry the operation once the stream is
/// reported as writable again.
///
/// [`send_body()`]: struct.Connection.html#method.send_body
/// [`send_additional_headers()`]:
/// struct.Connection.html#method.send_additional_headers
/// [`send_response()`]:
/// struct.Connection.html#method.send_response
/// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
/// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
/// [Extensible Priority]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
pub fn send_response_with_priority<T: NameValue>(
&mut self, conn: &mut super::Connection, stream_id: u64, headers: &[T],
priority: &Priority, fin: bool,
) -> Result<()> {
match self.streams.get(&stream_id) {
Some(s) => {
// Only one initial HEADERS allowed.
if s.local_initialized() {
return Err(Error::FrameUnexpected);
}
s
},
None => return Err(Error::FrameUnexpected),
};
self.send_headers(conn, stream_id, headers, fin)?;
// Clamp and shift urgency into quiche-priority space
let urgency = priority
.urgency
.clamp(PRIORITY_URGENCY_LOWER_BOUND, PRIORITY_URGENCY_UPPER_BOUND) +
PRIORITY_URGENCY_OFFSET;
conn.stream_priority(stream_id, urgency, priority.incremental)?;
Ok(())
}
/// Sends additional HTTP/3 headers.
///
/// After the initial request or response headers have been sent, using
/// [`send_request()`] or [`send_response()`] respectively, this method can
/// be used send an additional HEADERS frame. For example, to send a single
/// instance of trailers after a request with a body, or to issue another
/// non-final 1xx after a preceding 1xx, or to issue a final response after
/// a preceding 1xx.
///
/// Additional headers can only be sent during certain phases of an HTTP/3
/// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
/// error is returned when this method is called during the wrong phase,
/// such as before initial headers have been sent, or if trailers have
/// already been sent.
///
/// The [`StreamBlocked`] error is returned when the underlying QUIC stream
/// doesn't have enough capacity for the operation to complete. When this
/// happens the application should retry the operation once the stream is
/// reported as writable again.
///
/// [`send_request()`]: struct.Connection.html#method.send_request
/// [`send_response()`]: struct.Connection.html#method.send_response
/// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
/// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
/// [Section 4.1 of RFC 9114]:
/// https://www.rfc-editor.org/rfc/rfc9114.html#section-4.1.
pub fn send_additional_headers<T: NameValue>(
&mut self, conn: &mut super::Connection, stream_id: u64, headers: &[T],
is_trailer_section: bool, fin: bool,
) -> Result<()> {
// Clients can only send trailer headers.
if !self.is_server && !is_trailer_section {
return Err(Error::FrameUnexpected);
}
match self.streams.get(&stream_id) {
Some(s) => {
// Initial HEADERS must have been sent.
if !s.local_initialized() {
return Err(Error::FrameUnexpected);
}
// Only one trailing HEADERS allowed.
if s.trailers_sent() {
return Err(Error::FrameUnexpected);
}
s
},
None => return Err(Error::FrameUnexpected),
};
self.send_headers(conn, stream_id, headers, fin)?;
if is_trailer_section {
// send_headers() might have tidied the stream away, so we need to
// check again.
if let Some(s) = self.streams.get_mut(&stream_id) {
s.mark_trailers_sent();
}
}
Ok(())
}
fn encode_header_block<T: NameValue>(
&mut self, headers: &[T],
) -> Result<Vec<u8>> {
let headers_len = headers
.iter()
.fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
let mut header_block = vec![0; headers_len];
let len = self
.qpack_encoder
.encode(headers, &mut header_block)
.map_err(|_| Error::InternalError)?;
header_block.truncate(len);
Ok(header_block)
}
fn send_headers<T: NameValue>(
&mut self, conn: &mut super::Connection, stream_id: u64, headers: &[T],
fin: bool,
) -> Result<()> {
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
if !self.frames_greased && conn.grease {
self.send_grease_frames(conn, stream_id)?;
self.frames_greased = true;
}
let header_block = self.encode_header_block(headers)?;
let overhead = octets::varint_len(frame::HEADERS_FRAME_TYPE_ID) +
octets::varint_len(header_block.len() as u64);
// Headers need to be sent atomically, so make sure the stream has
// enough capacity.
match conn.stream_writable(stream_id, overhead + header_block.len()) {
Ok(true) => (),
Ok(false) => return Err(Error::StreamBlocked),
Err(e) => {
if conn.stream_finished(stream_id) {
self.streams.remove(&stream_id);
}
return Err(e.into());
},
};
b.put_varint(frame::HEADERS_FRAME_TYPE_ID)?;
b.put_varint(header_block.len() as u64)?;
let off = b.off();
conn.stream_send(stream_id, &d[..off], false)?;
// Sending header block separately avoids unnecessary copy.
conn.stream_send(stream_id, &header_block, fin)?;
trace!(
"{} tx frm HEADERS stream={} len={} fin={}",
conn.trace_id(),
stream_id,
header_block.len(),
fin
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let qlog_headers = headers
.iter()
.map(|h| qlog::events::h3::HttpHeader {
name: String::from_utf8_lossy(h.name()).into_owned(),
value: String::from_utf8_lossy(h.value()).into_owned(),
})
.collect();
let frame = Http3Frame::Headers {
headers: qlog_headers,
};
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(header_block.len() as u64),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
if let Some(s) = self.streams.get_mut(&stream_id) {
s.initialize_local();
}
if fin && conn.stream_finished(stream_id) {
self.streams.remove(&stream_id);
}
Ok(())
}
/// Sends an HTTP/3 body chunk on the given stream.
///
/// On success the number of bytes written is returned, or [`Done`] if no
/// bytes could be written (e.g. because the stream is blocked).
///
/// Note that the number of written bytes returned can be lower than the
/// length of the input buffer when the underlying QUIC stream doesn't have
/// enough capacity for the operation to complete.
///
/// When a partial write happens (including when [`Done`] is returned) the
/// application should retry the operation once the stream is reported as
/// writable again.
///
/// [`Done`]: enum.Error.html#variant.Done
pub fn send_body(
&mut self, conn: &mut super::Connection, stream_id: u64, body: &[u8],
fin: bool,
) -> Result<usize> {
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
// Validate that it is sane to send data on the stream.
if stream_id % 4 != 0 {
return Err(Error::FrameUnexpected);
}
match self.streams.get_mut(&stream_id) {
Some(s) => {
if !s.local_initialized() {
return Err(Error::FrameUnexpected);
}
if s.trailers_sent() {
return Err(Error::FrameUnexpected);
}
},
None => {
return Err(Error::FrameUnexpected);
},
};
// Avoid sending 0-length DATA frames when the fin flag is false.
if body.is_empty() && !fin {
return Err(Error::Done);
}
let overhead = octets::varint_len(frame::DATA_FRAME_TYPE_ID) +
octets::varint_len(body.len() as u64);
let stream_cap = match conn.stream_capacity(stream_id) {
Ok(v) => v,
Err(e) => {
if conn.stream_finished(stream_id) {
self.streams.remove(&stream_id);
}
return Err(e.into());
},
};
// Make sure there is enough capacity to send the DATA frame header.
if stream_cap < overhead {
let _ = conn.stream_writable(stream_id, overhead + 1);
return Err(Error::Done);
}
// Cap the frame payload length to the stream's capacity.
let body_len = std::cmp::min(body.len(), stream_cap - overhead);
// If we can't send the entire body, set the fin flag to false so the
// application can try again later.
let fin = if body_len != body.len() { false } else { fin };
// Again, avoid sending 0-length DATA frames when the fin flag is false.
if body_len == 0 && !fin {
let _ = conn.stream_writable(stream_id, overhead + 1);
return Err(Error::Done);
}
b.put_varint(frame::DATA_FRAME_TYPE_ID)?;
b.put_varint(body_len as u64)?;
let off = b.off();
conn.stream_send(stream_id, &d[..off], false)?;
// Return how many bytes were written, excluding the frame header.
// Sending body separately avoids unnecessary copy.
let written = conn.stream_send(stream_id, &body[..body_len], fin)?;
trace!(
"{} tx frm DATA stream={} len={} fin={}",
conn.trace_id(),
stream_id,
written,
fin
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let frame = Http3Frame::Data { raw: None };
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(written as u64),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
if written < body.len() {
// Ensure the peer is notified that the connection or stream is
// blocked when the stream's capacity is limited by flow control.
//
// We only need enough capacity to send a few bytes, to make sure
// the stream doesn't hang due to congestion window not growing
// enough.
let _ = conn.stream_writable(stream_id, overhead + 1);
}
if fin && written == body.len() && conn.stream_finished(stream_id) {
self.streams.remove(&stream_id);
}
Ok(written)
}
/// Returns whether the peer enabled HTTP/3 DATAGRAM frame support.
///
/// Support is signalled by the peer's SETTINGS, so this method always
/// returns false until they have been processed using the [`poll()`]
/// method.
///
/// [`poll()`]: struct.Connection.html#method.poll
pub fn dgram_enabled_by_peer(&self, conn: &super::Connection) -> bool {
self.peer_settings.h3_datagram == Some(1) &&
conn.dgram_max_writable_len().is_some()
}
/// Returns whether the peer enabled extended CONNECT support.
///
/// Support is signalled by the peer's SETTINGS, so this method always
/// returns false until they have been processed using the [`poll()`]
/// method.
///
/// [`poll()`]: struct.Connection.html#method.poll
pub fn extended_connect_enabled_by_peer(&self) -> bool {
self.peer_settings.connect_protocol_enabled == Some(1)
}
/// Reads request or response body data into the provided buffer.
///
/// Applications should call this method whenever the [`poll()`] method
/// returns a [`Data`] event.
///
/// On success the amount of bytes read is returned, or [`Done`] if there
/// is no data to read.
///
/// [`poll()`]: struct.Connection.html#method.poll
/// [`Data`]: enum.Event.html#variant.Data
/// [`Done`]: enum.Error.html#variant.Done
pub fn recv_body(
&mut self, conn: &mut super::Connection, stream_id: u64, out: &mut [u8],
) -> Result<usize> {
let mut total = 0;
// Try to consume all buffered data for the stream, even across multiple
// DATA frames.
while total < out.len() {
let stream = self.streams.get_mut(&stream_id).ok_or(Error::Done)?;
if stream.state() != stream::State::Data {
break;
}
let (read, fin) =
match stream.try_consume_data(conn, &mut out[total..]) {
Ok(v) => v,
Err(Error::Done) => break,
Err(e) => return Err(e),
};
total += read;
// No more data to read, we are done.
if read == 0 || fin {
break;
}
// Process incoming data from the stream. For example, if a whole
// DATA frame was consumed, and another one is queued behind it,
// this will ensure the additional data will also be returned to
// the application.
match self.process_readable_stream(conn, stream_id, false) {
Ok(_) => unreachable!(),
Err(Error::Done) => (),
Err(e) => return Err(e),
};
if conn.stream_finished(stream_id) {
break;
}
}
// While body is being received, the stream is marked as finished only
// when all data is read by the application.
if conn.stream_finished(stream_id) {
self.process_finished_stream(stream_id);
}
if total == 0 {
return Err(Error::Done);
}
Ok(total)
}
/// Sends a PRIORITY_UPDATE frame on the control stream with specified
/// request stream ID and priority.
///
/// The `priority` parameter represents [Extensible Priority]
/// parameters. If the urgency is outside the range 0-7, it will be clamped
/// to 7.
///
/// The [`StreamBlocked`] error is returned when the underlying QUIC stream
/// doesn't have enough capacity for the operation to complete. When this
/// happens the application should retry the operation once the stream is
/// reported as writable again.
///
/// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
/// [Extensible Priority]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
pub fn send_priority_update_for_request(
&mut self, conn: &mut super::Connection, stream_id: u64,
priority: &Priority,
) -> Result<()> {
let mut d = [42; 20];
let mut b = octets::OctetsMut::with_slice(&mut d);
// Validate that it is sane to send PRIORITY_UPDATE.
if self.is_server {
return Err(Error::FrameUnexpected);
}
if stream_id % 4 != 0 {
return Err(Error::FrameUnexpected);
}
let control_stream_id =
self.control_stream_id.ok_or(Error::FrameUnexpected)?;
let urgency = priority
.urgency
.clamp(PRIORITY_URGENCY_LOWER_BOUND, PRIORITY_URGENCY_UPPER_BOUND);
let mut field_value = format!("u={urgency}");
if priority.incremental {
field_value.push_str(",i");
}
let priority_field_value = field_value.as_bytes();
let frame_payload_len =
octets::varint_len(stream_id) + priority_field_value.len();
let overhead =
octets::varint_len(frame::PRIORITY_UPDATE_FRAME_REQUEST_TYPE_ID) +
octets::varint_len(stream_id) +
octets::varint_len(frame_payload_len as u64);
// Make sure the control stream has enough capacity.
match conn.stream_writable(
control_stream_id,
overhead + priority_field_value.len(),
) {
Ok(true) => (),
Ok(false) => return Err(Error::StreamBlocked),
Err(e) => {
return Err(e.into());
},
}
b.put_varint(frame::PRIORITY_UPDATE_FRAME_REQUEST_TYPE_ID)?;
b.put_varint(frame_payload_len as u64)?;
b.put_varint(stream_id)?;
let off = b.off();
conn.stream_send(control_stream_id, &d[..off], false)?;
// Sending field value separately avoids unnecessary copy.
conn.stream_send(control_stream_id, priority_field_value, false)?;
trace!(
"{} tx frm PRIORITY_UPDATE request_stream={} priority_field_value={}",
conn.trace_id(),
stream_id,
field_value,
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let frame = Http3Frame::PriorityUpdate {
target_stream_type: H3PriorityTargetStreamType::Request,
prioritized_element_id: stream_id,
priority_field_value: field_value.clone(),
};
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(priority_field_value.len() as u64),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
Ok(())
}
/// Take the last PRIORITY_UPDATE for a prioritized element ID.
///
/// When the [`poll()`] method returns a [`PriorityUpdate`] event for a
/// prioritized element, the event has triggered and will not rearm until
/// applications call this method. It is recommended that applications defer
/// taking the PRIORITY_UPDATE until after [`poll()`] returns [`Done`].
///
/// On success the Priority Field Value is returned, or [`Done`] if there is
/// no PRIORITY_UPDATE to read (either because there is no value to take, or
/// because the prioritized element does not exist).
///
/// [`poll()`]: struct.Connection.html#method.poll
/// [`PriorityUpdate`]: enum.Event.html#variant.PriorityUpdate
/// [`Done`]: enum.Error.html#variant.Done
pub fn take_last_priority_update(
&mut self, prioritized_element_id: u64,
) -> Result<Vec<u8>> {
if let Some(stream) = self.streams.get_mut(&prioritized_element_id) {
return stream.take_last_priority_update().ok_or(Error::Done);
}
Err(Error::Done)
}
/// Processes HTTP/3 data received from the peer.
///
/// On success it returns an [`Event`] and an ID, or [`Done`] when there are
/// no events to report.
///
/// Note that all events are edge-triggered, meaning that once reported they
/// will not be reported again by calling this method again, until the event
/// is re-armed.
///
/// The events [`Headers`], [`Data`] and [`Finished`] return a stream ID,
/// which is used in methods [`recv_body()`], [`send_response()`] or
/// [`send_body()`].
///
/// The event [`GoAway`] returns an ID that depends on the connection role.
/// A client receives the largest processed stream ID. A server receives the
/// the largest permitted push ID.
///
/// The event [`PriorityUpdate`] only occurs at servers. It returns a
/// prioritized element ID that is used in the method
/// [`take_last_priority_update()`], which rearms the event for that ID.
///
/// If an error occurs while processing data, the connection is closed with
/// the appropriate error code, using the transport's [`close()`] method.
///
/// [`Event`]: enum.Event.html
/// [`Done`]: enum.Error.html#variant.Done
/// [`Headers`]: enum.Event.html#variant.Headers
/// [`Data`]: enum.Event.html#variant.Data
/// [`Finished`]: enum.Event.html#variant.Finished
/// [`GoAway`]: enum.Event.html#variant.GoAWay
/// [`PriorityUpdate`]: enum.Event.html#variant.PriorityUpdate
/// [`recv_body()`]: struct.Connection.html#method.recv_body
/// [`send_response()`]: struct.Connection.html#method.send_response
/// [`send_body()`]: struct.Connection.html#method.send_body
/// [`recv_dgram()`]: struct.Connection.html#method.recv_dgram
/// [`take_last_priority_update()`]: struct.Connection.html#method.take_last_priority_update
/// [`close()`]: ../struct.Connection.html#method.close
pub fn poll(&mut self, conn: &mut super::Connection) -> Result<(u64, Event)> {
// When connection close is initiated by the local application (e.g. due
// to a protocol error), the connection itself might be in a broken
// state, so return early.
if conn.local_error.is_some() {
return Err(Error::Done);
}
// Process control streams first.
if let Some(stream_id) = self.peer_control_stream_id {
match self.process_control_stream(conn, stream_id) {
Ok(ev) => return Ok(ev),
Err(Error::Done) => (),
Err(e) => return Err(e),
};
}
if let Some(stream_id) = self.peer_qpack_streams.encoder_stream_id {
match self.process_control_stream(conn, stream_id) {
Ok(ev) => return Ok(ev),
Err(Error::Done) => (),
Err(e) => return Err(e),
};
}
if let Some(stream_id) = self.peer_qpack_streams.decoder_stream_id {
match self.process_control_stream(conn, stream_id) {
Ok(ev) => return Ok(ev),
Err(Error::Done) => (),
Err(e) => return Err(e),
};
}
// Process finished streams list.
if let Some(finished) = self.finished_streams.pop_front() {
return Ok((finished, Event::Finished));
}
// Process HTTP/3 data from readable streams.
for s in conn.readable() {
trace!("{} stream id {} is readable", conn.trace_id(), s);
let ev = match self.process_readable_stream(conn, s, true) {
Ok(v) => Some(v),
Err(Error::Done) => None,
// Return early if the stream was reset, to avoid returning
// a Finished event later as well.
Err(Error::TransportError(crate::Error::StreamReset(e))) =>
return Ok((s, Event::Reset(e))),
Err(e) => return Err(e),
};
if conn.stream_finished(s) {
self.process_finished_stream(s);
}
// TODO: check if stream is completed so it can be freed
if let Some(ev) = ev {
return Ok(ev);
}
}
// Process finished streams list once again, to make sure `Finished`
// events are returned when receiving empty stream frames with the fin
// flag set.
if let Some(finished) = self.finished_streams.pop_front() {
if conn.stream_readable(finished) {
// The stream is finished, but is still readable, it may
// indicate that there is a pending error, such as reset.
if let Err(crate::Error::StreamReset(e)) =
conn.stream_recv(finished, &mut [])
{
return Ok((finished, Event::Reset(e)));
}
}
return Ok((finished, Event::Finished));
}
Err(Error::Done)
}
/// Sends a GOAWAY frame to initiate graceful connection closure.
///
/// When quiche is used in the server role, the `id` parameter is the stream
/// ID of the highest processed request. This can be any valid ID between 0
/// and 2^62-4. However, the ID cannot be increased. Failure to satisfy
/// these conditions will return an error.
///
/// This method does not close the QUIC connection. Applications are
/// required to call [`close()`] themselves.
///
/// [`close()`]: ../struct.Connection.html#method.close
pub fn send_goaway(
&mut self, conn: &mut super::Connection, id: u64,
) -> Result<()> {
let mut id = id;
// TODO: server push
//
// In the meantime always send 0 from client.
if !self.is_server {
id = 0;
}
if self.is_server && id % 4 != 0 {
return Err(Error::IdError);
}
if let Some(sent_id) = self.local_goaway_id {
if id > sent_id {
return Err(Error::IdError);
}
}
if let Some(stream_id) = self.control_stream_id {
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame = frame::Frame::GoAway { id };
let wire_len = frame.to_bytes(&mut b)?;
let stream_cap = conn.stream_capacity(stream_id)?;
if stream_cap < wire_len {
return Err(Error::StreamBlocked);
}
trace!("{} tx frm {:?}", conn.trace_id(), frame);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(octets::varint_len(id) as u64),
frame: frame.to_qlog(),
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
let off = b.off();
conn.stream_send(stream_id, &d[..off], false)?;
self.local_goaway_id = Some(id);
}
Ok(())
}
/// Gets the raw settings from peer including unknown and reserved types.
///
/// The order of settings is the same as received in the SETTINGS frame.
pub fn peer_settings_raw(&self) -> Option<&[(u64, u64)]> {
self.peer_settings.raw.as_deref()
}
fn open_uni_stream(
&mut self, conn: &mut super::Connection, ty: u64,
) -> Result<u64> {
let stream_id = self.next_uni_stream_id;
let mut d = [0; 8];
let mut b = octets::OctetsMut::with_slice(&mut d);
match ty {
// Control and QPACK streams are the most important to schedule.
stream::HTTP3_CONTROL_STREAM_TYPE_ID |
stream::QPACK_ENCODER_STREAM_TYPE_ID |
stream::QPACK_DECODER_STREAM_TYPE_ID => {
conn.stream_priority(stream_id, 0, false)?;
},
// TODO: Server push
stream::HTTP3_PUSH_STREAM_TYPE_ID => (),
// Anything else is a GREASE stream, so make it the least important.
_ => {
conn.stream_priority(stream_id, 255, false)?;
},
}
conn.stream_send(stream_id, b.put_varint(ty)?, false)?;
// To avoid skipping stream IDs, we only calculate the next available
// stream ID when data has been successfully buffered.
self.next_uni_stream_id = self
.next_uni_stream_id
.checked_add(4)
.ok_or(Error::IdError)?;
Ok(stream_id)
}
fn open_qpack_encoder_stream(
&mut self, conn: &mut super::Connection,
) -> Result<()> {
let stream_id =
self.open_uni_stream(conn, stream::QPACK_ENCODER_STREAM_TYPE_ID)?;
self.local_qpack_streams.encoder_stream_id = Some(stream_id);
qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
let ev_data = EventData::H3StreamTypeSet(H3StreamTypeSet {
stream_id,
owner: Some(H3Owner::Local),
stream_type: H3StreamType::QpackEncode,
stream_type_value: None,
associated_push_id: None,
});
q.add_event_data_now(ev_data).ok();
});
Ok(())
}
fn open_qpack_decoder_stream(
&mut self, conn: &mut super::Connection,
) -> Result<()> {
let stream_id =
self.open_uni_stream(conn, stream::QPACK_DECODER_STREAM_TYPE_ID)?;
self.local_qpack_streams.decoder_stream_id = Some(stream_id);
qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
let ev_data = EventData::H3StreamTypeSet(H3StreamTypeSet {
stream_id,
owner: Some(H3Owner::Local),
stream_type: H3StreamType::QpackDecode,
stream_type_value: None,
associated_push_id: None,
});
q.add_event_data_now(ev_data).ok();
});
Ok(())
}
/// Send GREASE frames on the provided stream ID.
fn send_grease_frames(
&mut self, conn: &mut super::Connection, stream_id: u64,
) -> Result<()> {
let mut d = [0; 8];
let stream_cap = match conn.stream_capacity(stream_id) {
Ok(v) => v,
Err(e) => {
if conn.stream_finished(stream_id) {
self.streams.remove(&stream_id);
}
return Err(e.into());
},
};
let grease_frame1 = grease_value();
let grease_frame2 = grease_value();
let grease_payload = b"GREASE is the word";
let overhead = octets::varint_len(grease_frame1) + // frame type
1 + // payload len
octets::varint_len(grease_frame2) + // frame type
1 + // payload len
grease_payload.len(); // payload
// Don't send GREASE if there is not enough capacity for it. Greasing
// will _not_ be attempted again later on.
if stream_cap < overhead {
return Ok(());
}
// Empty GREASE frame.
let mut b = octets::OctetsMut::with_slice(&mut d);
conn.stream_send(stream_id, b.put_varint(grease_frame1)?, false)?;
let mut b = octets::OctetsMut::with_slice(&mut d);
conn.stream_send(stream_id, b.put_varint(0)?, false)?;
trace!(
"{} tx frm GREASE stream={} len=0",
conn.trace_id(),
stream_id
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let frame = Http3Frame::Reserved { length: Some(0) };
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(0),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
// GREASE frame with payload.
let mut b = octets::OctetsMut::with_slice(&mut d);
conn.stream_send(stream_id, b.put_varint(grease_frame2)?, false)?;
let mut b = octets::OctetsMut::with_slice(&mut d);
conn.stream_send(stream_id, b.put_varint(18)?, false)?;
conn.stream_send(stream_id, grease_payload, false)?;
trace!(
"{} tx frm GREASE stream={} len={}",
conn.trace_id(),
stream_id,
grease_payload.len()
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let frame = Http3Frame::Reserved {
length: Some(grease_payload.len() as u64),
};
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id,
length: Some(grease_payload.len() as u64),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
Ok(())
}
/// Opens a new unidirectional stream with a GREASE type and sends some
/// unframed payload.
fn open_grease_stream(&mut self, conn: &mut super::Connection) -> Result<()> {
let ty = grease_value();
match self.open_uni_stream(conn, ty) {
Ok(stream_id) => {
conn.stream_send(stream_id, b"GREASE is the word", true)?;
trace!("{} open GREASE stream {}", conn.trace_id(), stream_id);
qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
let ev_data = EventData::H3StreamTypeSet(H3StreamTypeSet {
stream_id,
owner: Some(H3Owner::Local),
stream_type: H3StreamType::Unknown,
stream_type_value: Some(ty),
associated_push_id: None,
});
q.add_event_data_now(ev_data).ok();
});
},
Err(Error::IdError) => {
trace!("{} GREASE stream blocked", conn.trace_id(),);
return Ok(());
},
Err(e) => return Err(e),
};
Ok(())
}
/// Sends SETTINGS frame based on HTTP/3 configuration.
fn send_settings(&mut self, conn: &mut super::Connection) -> Result<()> {
let stream_id = match self
.open_uni_stream(conn, stream::HTTP3_CONTROL_STREAM_TYPE_ID)
{
Ok(v) => v,
Err(e) => {
trace!("{} Control stream blocked", conn.trace_id(),);
if e == Error::Done {
return Err(Error::InternalError);
}
return Err(e);
},
};
self.control_stream_id = Some(stream_id);
qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
let ev_data = EventData::H3StreamTypeSet(H3StreamTypeSet {
stream_id,
owner: Some(H3Owner::Local),
stream_type: H3StreamType::Control,
stream_type_value: None,
associated_push_id: None,
});
q.add_event_data_now(ev_data).ok();
});
let grease = if conn.grease {
Some((grease_value(), grease_value()))
} else {
None
};
let frame = frame::Frame::Settings {
max_field_section_size: self.local_settings.max_field_section_size,
qpack_max_table_capacity: self
.local_settings
.qpack_max_table_capacity,
qpack_blocked_streams: self.local_settings.qpack_blocked_streams,
connect_protocol_enabled: self
.local_settings
.connect_protocol_enabled,
h3_datagram: self.local_settings.h3_datagram,
grease,
additional_settings: self.local_settings.additional_settings.clone(),
raw: Default::default(),
};
let mut d = [42; 128];
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b)?;
let off = b.off();
if let Some(id) = self.control_stream_id {
conn.stream_send(id, &d[..off], false)?;
trace!(
"{} tx frm SETTINGS stream={} len={}",
conn.trace_id(),
id,
off
);
qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
let frame = frame.to_qlog();
let ev_data = EventData::H3FrameCreated(H3FrameCreated {
stream_id: id,
length: Some(off as u64),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
}
Ok(())
}
fn process_control_stream(
&mut self, conn: &mut super::Connection, stream_id: u64,
) -> Result<(u64, Event)> {
close_conn_if_critical_stream_finished(conn, stream_id)?;
if !conn.stream_readable(stream_id) {
return Err(Error::Done);
}
match self.process_readable_stream(conn, stream_id, true) {
Ok(ev) => return Ok(ev),
Err(Error::Done) => (),
Err(e) => return Err(e),
};
close_conn_if_critical_stream_finished(conn, stream_id)?;
Err(Error::Done)
}
fn process_readable_stream(
&mut self, conn: &mut super::Connection, stream_id: u64, polling: bool,
) -> Result<(u64, Event)> {
self.streams
.entry(stream_id)
.or_insert_with(|| stream::Stream::new(stream_id, false));
// We need to get a fresh reference to the stream for each
// iteration, to avoid borrowing `self` for the entire duration
// of the loop, because we'll need to borrow it again in the
// `State::FramePayload` case below.
while let Some(stream) = self.streams.get_mut(&stream_id) {
match stream.state() {
stream::State::StreamType => {
stream.try_fill_buffer(conn)?;
let varint = match stream.try_consume_varint() {
Ok(v) => v,
Err(_) => continue,
};
let ty = stream::Type::deserialize(varint)?;
if let Err(e) = stream.set_ty(ty) {
conn.close(true, e.to_wire(), b"")?;
return Err(e);
}
qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
let ty_val = if matches!(ty, stream::Type::Unknown) {
Some(varint)
} else {
None
};
let ev_data =
EventData::H3StreamTypeSet(H3StreamTypeSet {
stream_id,
owner: Some(H3Owner::Remote),
stream_type: ty.to_qlog(),
stream_type_value: ty_val,
associated_push_id: None,
});
q.add_event_data_now(ev_data).ok();
});
match &ty {
stream::Type::Control => {
// Only one control stream allowed.
if self.peer_control_stream_id.is_some() {
conn.close(
true,
Error::StreamCreationError.to_wire(),
b"Received multiple control streams",
)?;
return Err(Error::StreamCreationError);
}
trace!(
"{} open peer's control stream {}",
conn.trace_id(),
stream_id
);
close_conn_if_critical_stream_finished(
conn, stream_id,
)?;
self.peer_control_stream_id = Some(stream_id);
},
stream::Type::Push => {
// Only clients can receive push stream.
if self.is_server {
conn.close(
true,
Error::StreamCreationError.to_wire(),
b"Server received push stream.",
)?;
return Err(Error::StreamCreationError);
}
},
stream::Type::QpackEncoder => {
// Only one qpack encoder stream allowed.
if self.peer_qpack_streams.encoder_stream_id.is_some()
{
conn.close(
true,
Error::StreamCreationError.to_wire(),
b"Received multiple QPACK encoder streams",
)?;
return Err(Error::StreamCreationError);
}
close_conn_if_critical_stream_finished(
conn, stream_id,
)?;
self.peer_qpack_streams.encoder_stream_id =
Some(stream_id);
},
stream::Type::QpackDecoder => {
// Only one qpack decoder allowed.
if self.peer_qpack_streams.decoder_stream_id.is_some()
{
conn.close(
true,
Error::StreamCreationError.to_wire(),
b"Received multiple QPACK decoder streams",
)?;
return Err(Error::StreamCreationError);
}
close_conn_if_critical_stream_finished(
conn, stream_id,
)?;
self.peer_qpack_streams.decoder_stream_id =
Some(stream_id);
},
stream::Type::Unknown => {
// Unknown stream types are ignored.
// TODO: we MAY send STOP_SENDING
},
stream::Type::Request => unreachable!(),
}
},
stream::State::PushId => {
stream.try_fill_buffer(conn)?;
let varint = match stream.try_consume_varint() {
Ok(v) => v,
Err(_) => continue,
};
if let Err(e) = stream.set_push_id(varint) {
conn.close(true, e.to_wire(), b"")?;
return Err(e);
}
},
stream::State::FrameType => {
stream.try_fill_buffer(conn)?;
let varint = match stream.try_consume_varint() {
Ok(v) => v,
Err(_) => continue,
};
match stream.set_frame_type(varint) {
Err(Error::FrameUnexpected) => {
let msg = format!("Unexpected frame type {varint}");
conn.close(
true,
Error::FrameUnexpected.to_wire(),
msg.as_bytes(),
)?;
return Err(Error::FrameUnexpected);
},
Err(e) => {
conn.close(
true,
e.to_wire(),
b"Error handling frame.",
)?;
return Err(e);
},
_ => (),
}
},
stream::State::FramePayloadLen => {
stream.try_fill_buffer(conn)?;
let payload_len = match stream.try_consume_varint() {
Ok(v) => v,
Err(_) => continue,
};
// DATA frames are handled uniquely. After this point we lose
// visibility of DATA framing, so just log here.
if Some(frame::DATA_FRAME_TYPE_ID) == stream.frame_type() {
trace!(
"{} rx frm DATA stream={} wire_payload_len={}",
conn.trace_id(),
stream_id,
payload_len
);
qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
let frame = Http3Frame::Data { raw: None };
let ev_data =
EventData::H3FrameParsed(H3FrameParsed {
stream_id,
length: Some(payload_len),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
}
if let Err(e) = stream.set_frame_payload_len(payload_len) {
conn.close(true, e.to_wire(), b"")?;
return Err(e);
}
},
stream::State::FramePayload => {
// Do not emit events when not polling.
if !polling {
break;
}
stream.try_fill_buffer(conn)?;
let (frame, payload_len) = match stream.try_consume_frame() {
Ok(frame) => frame,
Err(Error::Done) => return Err(Error::Done),
Err(e) => {
conn.close(
true,
e.to_wire(),
b"Error handling frame.",
)?;
return Err(e);
},
};
match self.process_frame(conn, stream_id, frame, payload_len)
{
Ok(ev) => return Ok(ev),
Err(Error::Done) => {
// This might be a frame that is processed internally
// without needing to bubble up to the user as an
// event. Check whether the frame has FIN'd by QUIC
// to prevent trying to read again on a closed stream.
if conn.stream_finished(stream_id) {
break;
}
},
Err(e) => return Err(e),
};
},
stream::State::Data => {
// Do not emit events when not polling.
if !polling {
break;
}
if !stream.try_trigger_data_event() {
break;
}
return Ok((stream_id, Event::Data));
},
stream::State::QpackInstruction => {
let mut d = [0; 4096];
// Read data from the stream and discard immediately.
loop {
let (recv, fin) = conn.stream_recv(stream_id, &mut d)?;
match stream.ty() {
Some(stream::Type::QpackEncoder) =>
self.peer_qpack_streams.encoder_stream_bytes +=
recv as u64,
Some(stream::Type::QpackDecoder) =>
self.peer_qpack_streams.decoder_stream_bytes +=
recv as u64,
_ => unreachable!(),
};
if fin {
close_conn_critical_stream(conn)?;
}
}
},
stream::State::Drain => {
// Discard incoming data on the stream.
conn.stream_shutdown(
stream_id,
crate::Shutdown::Read,
0x100,
)?;
break;
},
stream::State::Finished => break,
}
}
Err(Error::Done)
}
fn process_finished_stream(&mut self, stream_id: u64) {
let stream = match self.streams.get_mut(&stream_id) {
Some(v) => v,
None => return,
};
if stream.state() == stream::State::Finished {
return;
}
match stream.ty() {
Some(stream::Type::Request) | Some(stream::Type::Push) => {
stream.finished();
self.finished_streams.push_back(stream_id);
},
_ => (),
};
}
fn process_frame(
&mut self, conn: &mut super::Connection, stream_id: u64,
frame: frame::Frame, payload_len: u64,
) -> Result<(u64, Event)> {
trace!(
"{} rx frm {:?} stream={} payload_len={}",
conn.trace_id(),
frame,
stream_id,
payload_len
);
qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
// HEADERS frames are special case and will be logged below.
if !matches!(frame, frame::Frame::Headers { .. }) {
let frame = frame.to_qlog();
let ev_data = EventData::H3FrameParsed(H3FrameParsed {
stream_id,
length: Some(payload_len),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
}
});
match frame {
frame::Frame::Settings {
max_field_section_size,
qpack_max_table_capacity,
qpack_blocked_streams,
connect_protocol_enabled,
h3_datagram,
additional_settings,
raw,
..
} => {
self.peer_settings = ConnectionSettings {
max_field_section_size,
qpack_max_table_capacity,
qpack_blocked_streams,
connect_protocol_enabled,
h3_datagram,
additional_settings,
raw,
};
if let Some(1) = h3_datagram {
// The peer MUST have also enabled DATAGRAM with a TP
if conn.dgram_max_writable_len().is_none() {
conn.close(
true,
Error::SettingsError.to_wire(),
b"H3_DATAGRAM sent with value 1 but max_datagram_frame_size TP not set.",
)?;
return Err(Error::SettingsError);
}
}
},
frame::Frame::Headers { header_block } => {
if Some(stream_id) == self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"HEADERS received on control stream",
)?;
return Err(Error::FrameUnexpected);
}
// Servers reject too many HEADERS frames.
if let Some(s) = self.streams.get_mut(&stream_id) {
if self.is_server && s.headers_received_count() == 2 {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"Too many HEADERS frames",
)?;
return Err(Error::FrameUnexpected);
}
s.increment_headers_received();
}
// Use "infinite" as default value for max_field_section_size if
// it is not configured by the application.
let max_size = self
.local_settings
.max_field_section_size
.unwrap_or(u64::MAX);
let headers = match self
.qpack_decoder
.decode(&header_block[..], max_size)
{
Ok(v) => v,
Err(e) => {
let e = match e {
qpack::Error::HeaderListTooLarge =>
Error::ExcessiveLoad,
_ => Error::QpackDecompressionFailed,
};
conn.close(true, e.to_wire(), b"Error parsing headers.")?;
return Err(e);
},
};
qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
let qlog_headers = headers
.iter()
.map(|h| qlog::events::h3::HttpHeader {
name: String::from_utf8_lossy(h.name()).into_owned(),
value: String::from_utf8_lossy(h.value())
.into_owned(),
})
.collect();
let frame = Http3Frame::Headers {
headers: qlog_headers,
};
let ev_data = EventData::H3FrameParsed(H3FrameParsed {
stream_id,
length: Some(payload_len),
frame,
raw: None,
});
q.add_event_data_now(ev_data).ok();
});
let more_frames = !conn.stream_finished(stream_id);
return Ok((stream_id, Event::Headers {
list: headers,
more_frames,
}));
},
frame::Frame::Data { .. } => {
if Some(stream_id) == self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"DATA received on control stream",
)?;
return Err(Error::FrameUnexpected);
}
// Do nothing. The Data event is returned separately.
},
frame::Frame::GoAway { id } => {
if Some(stream_id) != self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"GOAWAY received on non-control stream",
)?;
return Err(Error::FrameUnexpected);
}
if !self.is_server && id % 4 != 0 {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"GOAWAY received with ID of non-request stream",
)?;
return Err(Error::IdError);
}
if let Some(received_id) = self.peer_goaway_id {
if id > received_id {
conn.close(
true,
Error::IdError.to_wire(),
b"GOAWAY received with ID larger than previously received",
)?;
return Err(Error::IdError);
}
}
self.peer_goaway_id = Some(id);
return Ok((id, Event::GoAway));
},
frame::Frame::MaxPushId { push_id } => {
if Some(stream_id) != self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"MAX_PUSH_ID received on non-control stream",
)?;
return Err(Error::FrameUnexpected);
}
if !self.is_server {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"MAX_PUSH_ID received by client",
)?;
return Err(Error::FrameUnexpected);
}
if push_id < self.max_push_id {
conn.close(
true,
Error::IdError.to_wire(),
b"MAX_PUSH_ID reduced limit",
)?;
return Err(Error::IdError);
}
self.max_push_id = push_id;
},
frame::Frame::PushPromise { .. } => {
if self.is_server {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PUSH_PROMISE received by server",
)?;
return Err(Error::FrameUnexpected);
}
if stream_id % 4 != 0 {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PUSH_PROMISE received on non-request stream",
)?;
return Err(Error::FrameUnexpected);
}
// TODO: implement more checks and PUSH_PROMISE event
},
frame::Frame::CancelPush { .. } => {
if Some(stream_id) != self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"CANCEL_PUSH received on non-control stream",
)?;
return Err(Error::FrameUnexpected);
}
// TODO: implement CANCEL_PUSH frame
},
frame::Frame::PriorityUpdateRequest {
prioritized_element_id,
priority_field_value,
} => {
if !self.is_server {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE received by client",
)?;
return Err(Error::FrameUnexpected);
}
if Some(stream_id) != self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE received on non-control stream",
)?;
return Err(Error::FrameUnexpected);
}
if prioritized_element_id % 4 != 0 {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE for request stream type with wrong ID",
)?;
return Err(Error::FrameUnexpected);
}
if prioritized_element_id > conn.streams.max_streams_bidi() * 4 {
conn.close(
true,
Error::IdError.to_wire(),
b"PRIORITY_UPDATE for request stream beyond max streams limit",
)?;
return Err(Error::IdError);
}
// If the PRIORITY_UPDATE is valid, consider storing the latest
// contents. Due to reordering, it is possible that we might
// receive frames that reference streams that have not yet to
// been opened and that's OK because it's within our concurrency
// limit. However, we discard PRIORITY_UPDATE that refers to
// streams that we know have been collected.
if conn.streams.is_collected(prioritized_element_id) {
return Err(Error::Done);
}
// If the stream did not yet exist, create it and store.
let stream =
self.streams.entry(prioritized_element_id).or_insert_with(
|| stream::Stream::new(prioritized_element_id, false),
);
let had_priority_update = stream.has_last_priority_update();
stream.set_last_priority_update(Some(priority_field_value));
// Only trigger the event when there wasn't already a stored
// PRIORITY_UPDATE.
if !had_priority_update {
return Ok((prioritized_element_id, Event::PriorityUpdate));
} else {
return Err(Error::Done);
}
},
frame::Frame::PriorityUpdatePush {
prioritized_element_id,
..
} => {
if !self.is_server {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE received by client",
)?;
return Err(Error::FrameUnexpected);
}
if Some(stream_id) != self.peer_control_stream_id {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE received on non-control stream",
)?;
return Err(Error::FrameUnexpected);
}
if prioritized_element_id % 3 != 0 {
conn.close(
true,
Error::FrameUnexpected.to_wire(),
b"PRIORITY_UPDATE for push stream type with wrong ID",
)?;
return Err(Error::FrameUnexpected);
}
// TODO: we only implement this if we implement server push
},
frame::Frame::Unknown { .. } => (),
}
Err(Error::Done)
}
/// Collects and returns statistics about the connection.
#[inline]
pub fn stats(&self) -> Stats {
Stats {
qpack_encoder_stream_recv_bytes: self
.peer_qpack_streams
.encoder_stream_bytes,
qpack_decoder_stream_recv_bytes: self
.peer_qpack_streams
.decoder_stream_bytes,
}
}
}
/// Generates an HTTP/3 GREASE variable length integer.
pub fn grease_value() -> u64 {
let n = super::rand::rand_u64_uniform(148_764_065_110_560_899);
31 * n + 33
}
#[doc(hidden)]
pub mod testing {
use super::*;
use crate::testing;
/// Session is an HTTP/3 test helper structure. It holds a client, server
/// and pipe that allows them to communicate.
///
/// `default()` creates a session with some sensible default
/// configuration. `with_configs()` allows for providing a specific
/// configuration.
///
/// `handshake()` performs all the steps needed to establish an HTTP/3
/// connection.
///
/// Some utility functions are provided that make it less verbose to send
/// request, responses and individual headers. The full quiche API remains
/// available for any test that need to do unconventional things (such as
/// bad behaviour that triggers errors).
pub struct Session {
pub pipe: testing::Pipe,
pub client: Connection,
pub server: Connection,
}
impl Session {
pub fn new() -> Result<Session> {
fn path_relative_to_manifest_dir(path: &str) -> String {
std::fs::canonicalize(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(path),
)
.unwrap()
.to_string_lossy()
.into_owned()
}
let mut config = crate::Config::new(crate::PROTOCOL_VERSION)?;
config.load_cert_chain_from_pem_file(
&path_relative_to_manifest_dir("examples/cert.crt"),
)?;
config.load_priv_key_from_pem_file(
&path_relative_to_manifest_dir("examples/cert.key"),
)?;
config.set_application_protos(&[b"h3"])?;
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(5);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.enable_dgram(true, 3, 3);
config.set_ack_delay_exponent(8);
let h3_config = Config::new()?;
Session::with_configs(&mut config, &h3_config)
}
pub fn with_configs(
config: &mut crate::Config, h3_config: &Config,
) -> Result<Session> {
let pipe = testing::Pipe::with_config(config)?;
let client_dgram = pipe.client.dgram_enabled();
let server_dgram = pipe.server.dgram_enabled();
Ok(Session {
pipe,
client: Connection::new(h3_config, false, client_dgram)?,
server: Connection::new(h3_config, true, server_dgram)?,
})
}
/// Do the HTTP/3 handshake so both ends are in sane initial state.
pub fn handshake(&mut self) -> Result<()> {
self.pipe.handshake()?;
// Client streams.
self.client.send_settings(&mut self.pipe.client)?;
self.pipe.advance().ok();
self.client
.open_qpack_encoder_stream(&mut self.pipe.client)?;
self.pipe.advance().ok();
self.client
.open_qpack_decoder_stream(&mut self.pipe.client)?;
self.pipe.advance().ok();
if self.pipe.client.grease {
self.client.open_grease_stream(&mut self.pipe.client)?;
}
self.pipe.advance().ok();
// Server streams.
self.server.send_settings(&mut self.pipe.server)?;
self.pipe.advance().ok();
self.server
.open_qpack_encoder_stream(&mut self.pipe.server)?;
self.pipe.advance().ok();
self.server
.open_qpack_decoder_stream(&mut self.pipe.server)?;
self.pipe.advance().ok();
if self.pipe.server.grease {
self.server.open_grease_stream(&mut self.pipe.server)?;
}
self.advance().ok();
while self.client.poll(&mut self.pipe.client).is_ok() {
// Do nothing.
}
while self.server.poll(&mut self.pipe.server).is_ok() {
// Do nothing.
}
Ok(())
}
/// Advances the session pipe over the buffer.
pub fn advance(&mut self) -> crate::Result<()> {
self.pipe.advance()
}
/// Polls the client for events.
pub fn poll_client(&mut self) -> Result<(u64, Event)> {
self.client.poll(&mut self.pipe.client)
}
/// Polls the server for events.
pub fn poll_server(&mut self) -> Result<(u64, Event)> {
self.server.poll(&mut self.pipe.server)
}
/// Sends a request from client with default headers.
///
/// On success it returns the newly allocated stream and the headers.
pub fn send_request(&mut self, fin: bool) -> Result<(u64, Vec<Header>)> {
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
Header::new(b"user-agent", b"quiche-test"),
];
let stream =
self.client.send_request(&mut self.pipe.client, &req, fin)?;
self.advance().ok();
Ok((stream, req))
}
/// Sends a response from server with default headers.
///
/// On success it returns the headers.
pub fn send_response(
&mut self, stream: u64, fin: bool,
) -> Result<Vec<Header>> {
let resp = vec![
Header::new(b":status", b"200"),
Header::new(b"server", b"quiche-test"),
];
self.server.send_response(
&mut self.pipe.server,
stream,
&resp,
fin,
)?;
self.advance().ok();
Ok(resp)
}
/// Sends some default payload from client.
///
/// On success it returns the payload.
pub fn send_body_client(
&mut self, stream: u64, fin: bool,
) -> Result<Vec<u8>> {
let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
self.client
.send_body(&mut self.pipe.client, stream, &bytes, fin)?;
self.advance().ok();
Ok(bytes)
}
/// Fetches DATA payload from the server.
///
/// On success it returns the number of bytes received.
pub fn recv_body_client(
&mut self, stream: u64, buf: &mut [u8],
) -> Result<usize> {
self.client.recv_body(&mut self.pipe.client, stream, buf)
}
/// Sends some default payload from server.
///
/// On success it returns the payload.
pub fn send_body_server(
&mut self, stream: u64, fin: bool,
) -> Result<Vec<u8>> {
let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
self.server
.send_body(&mut self.pipe.server, stream, &bytes, fin)?;
self.advance().ok();
Ok(bytes)
}
/// Fetches DATA payload from the client.
///
/// On success it returns the number of bytes received.
pub fn recv_body_server(
&mut self, stream: u64, buf: &mut [u8],
) -> Result<usize> {
self.server.recv_body(&mut self.pipe.server, stream, buf)
}
/// Sends a single HTTP/3 frame from the client.
pub fn send_frame_client(
&mut self, frame: frame::Frame, stream_id: u64, fin: bool,
) -> Result<()> {
let mut d = [42; 65535];
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b)?;
let off = b.off();
self.pipe.client.stream_send(stream_id, &d[..off], fin)?;
self.advance().ok();
Ok(())
}
/// Send an HTTP/3 DATAGRAM with default data from the client.
///
/// On success it returns the data.
pub fn send_dgram_client(&mut self, flow_id: u64) -> Result<Vec<u8>> {
let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let len = octets::varint_len(flow_id) + bytes.len();
let mut d = vec![0; len];
let mut b = octets::OctetsMut::with_slice(&mut d);
b.put_varint(flow_id)?;
b.put_bytes(&bytes)?;
self.pipe.client.dgram_send(&d)?;
self.advance().ok();
Ok(bytes)
}
/// Receives an HTTP/3 DATAGRAM from the server.
///
/// On success it returns the DATAGRAM length, flow ID and flow ID
/// length.
pub fn recv_dgram_client(
&mut self, buf: &mut [u8],
) -> Result<(usize, u64, usize)> {
let len = self.pipe.client.dgram_recv(buf)?;
let mut b = octets::Octets::with_slice(buf);
let flow_id = b.get_varint()?;
Ok((len, flow_id, b.off()))
}
/// Send an HTTP/3 DATAGRAM with default data from the server
///
/// On success it returns the data.
pub fn send_dgram_server(&mut self, flow_id: u64) -> Result<Vec<u8>> {
let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let len = octets::varint_len(flow_id) + bytes.len();
let mut d = vec![0; len];
let mut b = octets::OctetsMut::with_slice(&mut d);
b.put_varint(flow_id)?;
b.put_bytes(&bytes)?;
self.pipe.server.dgram_send(&d)?;
self.advance().ok();
Ok(bytes)
}
/// Receives an HTTP/3 DATAGRAM from the client.
///
/// On success it returns the DATAGRAM length, flow ID and flow ID
/// length.
pub fn recv_dgram_server(
&mut self, buf: &mut [u8],
) -> Result<(usize, u64, usize)> {
let len = self.pipe.server.dgram_recv(buf)?;
let mut b = octets::Octets::with_slice(buf);
let flow_id = b.get_varint()?;
Ok((len, flow_id, b.off()))
}
/// Sends a single HTTP/3 frame from the server.
pub fn send_frame_server(
&mut self, frame: frame::Frame, stream_id: u64, fin: bool,
) -> Result<()> {
let mut d = [42; 65535];
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b)?;
let off = b.off();
self.pipe.server.stream_send(stream_id, &d[..off], fin)?;
self.advance().ok();
Ok(())
}
/// Sends an arbitrary buffer of HTTP/3 stream data from the client.
pub fn send_arbitrary_stream_data_client(
&mut self, data: &[u8], stream_id: u64, fin: bool,
) -> Result<()> {
self.pipe.client.stream_send(stream_id, data, fin)?;
self.advance().ok();
Ok(())
}
/// Sends an arbitrary buffer of HTTP/3 stream data from the server.
pub fn send_arbitrary_stream_data_server(
&mut self, data: &[u8], stream_id: u64, fin: bool,
) -> Result<()> {
self.pipe.server.stream_send(stream_id, data, fin)?;
self.advance().ok();
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::testing::*;
#[test]
/// Make sure that random GREASE values is within the specified limit.
fn grease_value_in_varint_limit() {
assert!(grease_value() < 2u64.pow(62) - 1);
}
#[cfg(not(feature = "openssl"))] // 0-RTT not supported when using openssl/quictls
#[test]
fn h3_handshake_0rtt() {
let mut buf = [0; 65535];
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config
.set_application_protos(&[b"proto1", b"proto2"])
.unwrap();
config.set_initial_max_data(30);
config.set_initial_max_stream_data_bidi_local(15);
config.set_initial_max_stream_data_bidi_remote(15);
config.set_initial_max_stream_data_uni(15);
config.set_initial_max_streams_bidi(3);
config.set_initial_max_streams_uni(3);
config.enable_early_data();
config.verify_peer(false);
let h3_config = Config::new().unwrap();
// Perform initial handshake.
let mut pipe = crate::testing::Pipe::with_config(&mut config).unwrap();
assert_eq!(pipe.handshake(), Ok(()));
// Extract session,
let session = pipe.client.session().unwrap();
// Configure session on new connection.
let mut pipe = crate::testing::Pipe::with_config(&mut config).unwrap();
assert_eq!(pipe.client.set_session(session), Ok(()));
// Can't create an H3 connection until the QUIC connection is determined
// to have made sufficient early data progress.
assert!(matches!(
Connection::with_transport(&mut pipe.client, &h3_config),
Err(Error::InternalError)
));
// Client sends initial flight.
let (len, _) = pipe.client.send(&mut buf).unwrap();
// Now an H3 connection can be created.
assert!(Connection::with_transport(&mut pipe.client, &h3_config).is_ok());
assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
// Client sends 0-RTT packet.
let pkt_type = crate::packet::Type::ZeroRTT;
let frames = [crate::frame::Frame::Stream {
stream_id: 6,
data: crate::stream::RangeBuf::from(b"aaaaa", 0, true),
}];
assert_eq!(
pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
Ok(1200)
);
assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
// 0-RTT stream data is readable.
let mut r = pipe.server.readable();
assert_eq!(r.next(), Some(6));
assert_eq!(r.next(), None);
let mut b = [0; 15];
assert_eq!(pipe.server.stream_recv(6, &mut b), Ok((5, true)));
assert_eq!(&b[..5], b"aaaaa");
}
#[test]
/// Send a request with no body, get a response with no body.
fn request_no_body_response_no_body() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, true).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a request with no body, get a response with one DATA frame.
fn request_no_body_response_one_chunk() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, false).unwrap();
let body = s.send_body_server(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a request with no body, get a response with multiple DATA frames.
fn request_no_body_response_many_chunks() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let total_data_frames = 4;
let resp = s.send_response(stream, false).unwrap();
for _ in 0..total_data_frames - 1 {
s.send_body_server(stream, false).unwrap();
}
let body = s.send_body_server(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.poll_client(), Err(Error::Done));
for _ in 0..total_data_frames {
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
}
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a request with one DATA frame, get a response with no body.
fn request_one_chunk_response_no_body() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, true).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
}
#[test]
/// Send a request with multiple DATA frames, get a response with no body.
fn request_many_chunks_response_no_body() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let total_data_frames = 4;
for _ in 0..total_data_frames - 1 {
s.send_body_client(stream, false).unwrap();
}
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
for _ in 0..total_data_frames {
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
}
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, true).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
}
#[test]
/// Send a request with multiple DATA frames, get a response with one DATA
/// frame.
fn many_requests_many_chunks_response_one_chunk() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let mut reqs = Vec::new();
let (stream1, req1) = s.send_request(false).unwrap();
assert_eq!(stream1, 0);
reqs.push(req1);
let (stream2, req2) = s.send_request(false).unwrap();
assert_eq!(stream2, 4);
reqs.push(req2);
let (stream3, req3) = s.send_request(false).unwrap();
assert_eq!(stream3, 8);
reqs.push(req3);
let body = s.send_body_client(stream1, false).unwrap();
s.send_body_client(stream2, false).unwrap();
s.send_body_client(stream3, false).unwrap();
let mut recv_buf = vec![0; body.len()];
// Reverse order of writes.
s.send_body_client(stream3, true).unwrap();
s.send_body_client(stream2, true).unwrap();
s.send_body_client(stream1, true).unwrap();
let (_, ev) = s.poll_server().unwrap();
let ev_headers = Event::Headers {
list: reqs[0].clone(),
more_frames: true,
};
assert_eq!(ev, ev_headers);
let (_, ev) = s.poll_server().unwrap();
let ev_headers = Event::Headers {
list: reqs[1].clone(),
more_frames: true,
};
assert_eq!(ev, ev_headers);
let (_, ev) = s.poll_server().unwrap();
let ev_headers = Event::Headers {
list: reqs[2].clone(),
more_frames: true,
};
assert_eq!(ev, ev_headers);
assert_eq!(s.poll_server(), Ok((0, Event::Data)));
assert_eq!(s.recv_body_server(0, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_body_server(0, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((0, Event::Finished)));
assert_eq!(s.poll_server(), Ok((4, Event::Data)));
assert_eq!(s.recv_body_server(4, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_body_server(4, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((4, Event::Finished)));
assert_eq!(s.poll_server(), Ok((8, Event::Data)));
assert_eq!(s.recv_body_server(8, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_body_server(8, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((8, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
let mut resps = Vec::new();
let resp1 = s.send_response(stream1, true).unwrap();
resps.push(resp1);
let resp2 = s.send_response(stream2, true).unwrap();
resps.push(resp2);
let resp3 = s.send_response(stream3, true).unwrap();
resps.push(resp3);
for _ in 0..resps.len() {
let (stream, ev) = s.poll_client().unwrap();
let ev_headers = Event::Headers {
list: resps[(stream / 4) as usize].clone(),
more_frames: false,
};
assert_eq!(ev, ev_headers);
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
}
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a request with no body, get a response with one DATA frame and an
/// empty FIN after reception from the client.
fn request_no_body_response_one_chunk_empty_fin() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, false).unwrap();
let body = s.send_body_server(stream, false).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.pipe.server.stream_send(stream, &[], true), Ok(0));
s.advance().ok();
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a request with no body, get a response with no body followed by
/// GREASE that is STREAM frame with a FIN.
fn request_no_body_response_no_body_with_grease() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let resp = s.send_response(stream, false).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
// Inject a GREASE frame
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
s.pipe.server.stream_send(0, frame_type, false).unwrap();
let frame_len = b.put_varint(10).unwrap();
s.pipe.server.stream_send(0, frame_len, false).unwrap();
s.pipe.server.stream_send(0, &d, true).unwrap();
s.advance().ok();
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Try to send DATA frames before HEADERS.
fn body_response_before_headers() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(
s.send_body_server(stream, true),
Err(Error::FrameUnexpected)
);
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Try to send DATA frames on wrong streams, ensure the API returns an
/// error before anything hits the transport layer.
fn send_body_invalid_client_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
assert_eq!(s.send_body_client(0, true), Err(Error::FrameUnexpected));
assert_eq!(
s.send_body_client(s.client.control_stream_id.unwrap(), true),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_client(
s.client.local_qpack_streams.encoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_client(
s.client.local_qpack_streams.decoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_client(s.client.peer_control_stream_id.unwrap(), true),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_client(
s.client.peer_qpack_streams.encoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_client(
s.client.peer_qpack_streams.decoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
}
#[test]
/// Try to send DATA frames on wrong streams, ensure the API returns an
/// error before anything hits the transport layer.
fn send_body_invalid_server_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
assert_eq!(s.send_body_server(0, true), Err(Error::FrameUnexpected));
assert_eq!(
s.send_body_server(s.server.control_stream_id.unwrap(), true),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_server(
s.server.local_qpack_streams.encoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_server(
s.server.local_qpack_streams.decoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_server(s.server.peer_control_stream_id.unwrap(), true),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_server(
s.server.peer_qpack_streams.encoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
assert_eq!(
s.send_body_server(
s.server.peer_qpack_streams.decoder_stream_id.unwrap(),
true
),
Err(Error::FrameUnexpected)
);
}
#[test]
/// Client sends request with body and trailers.
fn trailers() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, false).unwrap();
let mut recv_buf = vec![0; body.len()];
let req_trailers = vec![Header::new(b"foo", b"bar")];
s.client
.send_additional_headers(
&mut s.pipe.client,
stream,
&req_trailers,
true,
true,
)
.unwrap();
s.advance().ok();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
let ev_trailers = Event::Headers {
list: req_trailers,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, ev_trailers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
}
#[test]
/// Server responds with a 103, then a 200 with no body.
fn informational_response() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let info_resp = vec![
Header::new(b":status", b"103"),
Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
];
let resp = vec![
Header::new(b":status", b"200"),
Header::new(b"server", b"quiche-test"),
];
s.server
.send_response(&mut s.pipe.server, stream, &info_resp, false)
.unwrap();
s.server
.send_additional_headers(
&mut s.pipe.server,
stream,
&resp,
false,
true,
)
.unwrap();
s.advance().ok();
let ev_info_headers = Event::Headers {
list: info_resp,
more_frames: true,
};
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_info_headers)));
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Server responds with a 103, then attempts to send a 200 using
/// send_response again, which should fail.
fn no_multiple_response() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let info_resp = vec![
Header::new(b":status", b"103"),
Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
];
let resp = vec![
Header::new(b":status", b"200"),
Header::new(b"server", b"quiche-test"),
];
s.server
.send_response(&mut s.pipe.server, stream, &info_resp, false)
.unwrap();
assert_eq!(
Err(Error::FrameUnexpected),
s.server
.send_response(&mut s.pipe.server, stream, &resp, true)
);
s.advance().ok();
let ev_info_headers = Event::Headers {
list: info_resp,
more_frames: true,
};
assert_eq!(s.poll_client(), Ok((stream, ev_info_headers)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Server attempts to use send_additional_headers before initial response.
fn no_send_additional_before_initial_response() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
assert_eq!(stream, 0);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let info_resp = vec![
Header::new(b":status", b"103"),
Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
];
assert_eq!(
Err(Error::FrameUnexpected),
s.server.send_additional_headers(
&mut s.pipe.server,
stream,
&info_resp,
false,
false
)
);
s.advance().ok();
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Client sends multiple HEADERS before data.
fn additional_headers_before_data_client() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let req_trailer = vec![Header::new(b"goodbye", b"world")];
assert_eq!(
s.client.send_additional_headers(
&mut s.pipe.client,
stream,
&req_trailer,
true,
false
),
Ok(())
);
s.advance().ok();
let ev_initial_headers = Event::Headers {
list: req,
more_frames: true,
};
let ev_trailing_headers = Event::Headers {
list: req_trailer,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_initial_headers)));
assert_eq!(s.poll_server(), Ok((stream, ev_trailing_headers)));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Client sends multiple HEADERS before data.
fn data_after_trailers_client() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, false).unwrap();
let mut recv_buf = vec![0; body.len()];
let req_trailers = vec![Header::new(b"foo", b"bar")];
s.client
.send_additional_headers(
&mut s.pipe.client,
stream,
&req_trailers,
true,
false,
)
.unwrap();
s.advance().ok();
s.send_frame_client(
frame::Frame::Data {
payload: vec![1, 2, 3, 4],
},
stream,
true,
)
.unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
let ev_trailers = Event::Headers {
list: req_trailers,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, ev_trailers)));
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a MAX_PUSH_ID frame from the client on a valid stream.
fn max_push_id_from_client_good() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 1 },
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a MAX_PUSH_ID frame from the client on an invalid stream.
fn max_push_id_from_client_bad_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 2 },
stream,
false,
)
.unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a sequence of MAX_PUSH_ID frames from the client that attempt to
/// reduce the limit.
fn max_push_id_from_client_limit_reduction() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 2 },
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 1 },
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::IdError));
}
#[test]
/// Send a MAX_PUSH_ID frame from the server, which is forbidden.
fn max_push_id_from_server() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::MaxPushId { push_id: 1 },
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a PUSH_PROMISE frame from the client, which is forbidden.
fn push_promise_from_client() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let header_block = s.client.encode_header_block(&req).unwrap();
s.send_frame_client(
frame::Frame::PushPromise {
push_id: 1,
header_block,
},
stream,
false,
)
.unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a CANCEL_PUSH frame from the client.
fn cancel_push_from_client() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::CancelPush { push_id: 1 },
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a CANCEL_PUSH frame from the client on an invalid stream.
fn cancel_push_from_client_bad_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
s.send_frame_client(
frame::Frame::CancelPush { push_id: 2 },
stream,
false,
)
.unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a CANCEL_PUSH frame from the client.
fn cancel_push_from_server() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::CancelPush { push_id: 1 },
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send a GOAWAY frame from the client.
fn goaway_from_client_good() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client.send_goaway(&mut s.pipe.client, 100).unwrap();
s.advance().ok();
// TODO: server push
assert_eq!(s.poll_server(), Ok((0, Event::GoAway)));
}
#[test]
/// Send a GOAWAY frame from the server.
fn goaway_from_server_good() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.server.send_goaway(&mut s.pipe.server, 4000).unwrap();
s.advance().ok();
assert_eq!(s.poll_client(), Ok((4000, Event::GoAway)));
}
#[test]
/// A client MUST NOT send a request after it receives GOAWAY.
fn client_request_after_goaway() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.server.send_goaway(&mut s.pipe.server, 4000).unwrap();
s.advance().ok();
assert_eq!(s.poll_client(), Ok((4000, Event::GoAway)));
assert_eq!(s.send_request(true), Err(Error::FrameUnexpected));
}
#[test]
/// Send a GOAWAY frame from the server, using an invalid goaway ID.
fn goaway_from_server_invalid_id() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::GoAway { id: 1 },
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Err(Error::IdError));
}
#[test]
/// Send multiple GOAWAY frames from the server, that increase the goaway
/// ID.
fn goaway_from_server_increase_id() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::GoAway { id: 0 },
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
s.send_frame_server(
frame::Frame::GoAway { id: 4 },
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Ok((0, Event::GoAway)));
assert_eq!(s.poll_client(), Err(Error::IdError));
}
#[test]
#[cfg(feature = "sfv")]
fn parse_priority_field_value() {
// Legal dicts
assert_eq!(
Ok(Priority::new(0, false)),
Priority::try_from(b"u=0".as_slice())
);
assert_eq!(
Ok(Priority::new(3, false)),
Priority::try_from(b"u=3".as_slice())
);
assert_eq!(
Ok(Priority::new(7, false)),
Priority::try_from(b"u=7".as_slice())
);
assert_eq!(
Ok(Priority::new(0, true)),
Priority::try_from(b"u=0, i".as_slice())
);
assert_eq!(
Ok(Priority::new(3, true)),
Priority::try_from(b"u=3, i".as_slice())
);
assert_eq!(
Ok(Priority::new(7, true)),
Priority::try_from(b"u=7, i".as_slice())
);
assert_eq!(
Ok(Priority::new(0, true)),
Priority::try_from(b"u=0, i=?1".as_slice())
);
assert_eq!(
Ok(Priority::new(3, true)),
Priority::try_from(b"u=3, i=?1".as_slice())
);
assert_eq!(
Ok(Priority::new(7, true)),
Priority::try_from(b"u=7, i=?1".as_slice())
);
assert_eq!(
Ok(Priority::new(3, false)),
Priority::try_from(b"".as_slice())
);
assert_eq!(
Ok(Priority::new(0, true)),
Priority::try_from(b"u=0;foo, i;bar".as_slice())
);
assert_eq!(
Ok(Priority::new(3, true)),
Priority::try_from(b"u=3;hello, i;world".as_slice())
);
assert_eq!(
Ok(Priority::new(7, true)),
Priority::try_from(b"u=7;croeso, i;gymru".as_slice())
);
assert_eq!(
Ok(Priority::new(0, true)),
Priority::try_from(b"u=0, i, spinaltap=11".as_slice())
);
// Illegal formats
assert_eq!(Err(Error::Done), Priority::try_from(b"0".as_slice()));
assert_eq!(
Ok(Priority::new(7, false)),
Priority::try_from(b"u=-1".as_slice())
);
assert_eq!(Err(Error::Done), Priority::try_from(b"u=0.2".as_slice()));
assert_eq!(
Ok(Priority::new(7, false)),
Priority::try_from(b"u=100".as_slice())
);
assert_eq!(
Err(Error::Done),
Priority::try_from(b"u=3, i=true".as_slice())
);
// Trailing comma in dict is malformed
assert_eq!(Err(Error::Done), Priority::try_from(b"u=7, ".as_slice()));
}
#[test]
/// Send a PRIORITY_UPDATE for request stream from the client.
fn priority_update_request() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a PRIORITY_UPDATE for request stream from the client.
fn priority_update_single_stream_rearm() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 5,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Err(Error::Done));
// There is only one PRIORITY_UPDATE frame to read. Once read, the event
// will rearm ready for more.
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=5".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 7,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=7".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
}
#[test]
/// Send multiple PRIORITY_UPDATE frames for different streams from the
/// client across multiple flights of exchange.
fn priority_update_request_multiple_stream_arm_multiple_flights() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
s.client
.send_priority_update_for_request(&mut s.pipe.client, 4, &Priority {
urgency: 1,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((4, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
s.client
.send_priority_update_for_request(&mut s.pipe.client, 8, &Priority {
urgency: 2,
incremental: false,
})
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((8, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(4), Ok(b"u=1".to_vec()));
assert_eq!(s.server.take_last_priority_update(8), Ok(b"u=2".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
}
#[test]
/// Send multiple PRIORITY_UPDATE frames for different streams from the
/// client across a single flight.
fn priority_update_request_multiple_stream_arm_single_flight() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let mut d = [42; 65535];
let mut b = octets::OctetsMut::with_slice(&mut d);
let p1 = frame::Frame::PriorityUpdateRequest {
prioritized_element_id: 0,
priority_field_value: b"u=3".to_vec(),
};
let p2 = frame::Frame::PriorityUpdateRequest {
prioritized_element_id: 4,
priority_field_value: b"u=3".to_vec(),
};
let p3 = frame::Frame::PriorityUpdateRequest {
prioritized_element_id: 8,
priority_field_value: b"u=3".to_vec(),
};
p1.to_bytes(&mut b).unwrap();
p2.to_bytes(&mut b).unwrap();
p3.to_bytes(&mut b).unwrap();
let off = b.off();
s.pipe
.client
.stream_send(s.client.control_stream_id.unwrap(), &d[..off], false)
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Ok((4, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Ok((8, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(4), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(8), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
}
#[test]
/// Send a PRIORITY_UPDATE for a request stream, before and after the stream
/// has been completed.
fn priority_update_request_collected_completed() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
// Priority event is generated before request headers.
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
let resp = s.send_response(stream, true).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
// Now send a PRIORITY_UPDATE for the completed request stream.
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
// No event generated at server
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a PRIORITY_UPDATE for a request stream, before and after the stream
/// has been stopped.
fn priority_update_request_collected_stopped() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
let (stream, req) = s.send_request(false).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
// Priority event is generated before request headers.
assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
s.pipe
.client
.stream_shutdown(stream, crate::Shutdown::Write, 0x100)
.unwrap();
s.pipe
.client
.stream_shutdown(stream, crate::Shutdown::Read, 0x100)
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((0, Event::Reset(0x100))));
assert_eq!(s.poll_server(), Err(Error::Done));
// Now send a PRIORITY_UPDATE for the closed request stream.
s.client
.send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
urgency: 3,
incremental: false,
})
.unwrap();
s.advance().ok();
// No event generated at server
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a PRIORITY_UPDATE for push stream from the client.
fn priority_update_push() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::PriorityUpdatePush {
prioritized_element_id: 3,
priority_field_value: b"u=3".to_vec(),
},
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a PRIORITY_UPDATE for request stream from the client but for an
/// incorrect stream type.
fn priority_update_request_bad_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::PriorityUpdateRequest {
prioritized_element_id: 5,
priority_field_value: b"u=3".to_vec(),
},
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a PRIORITY_UPDATE for push stream from the client but for an
/// incorrect stream type.
fn priority_update_push_bad_stream() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::PriorityUpdatePush {
prioritized_element_id: 5,
priority_field_value: b"u=3".to_vec(),
},
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a PRIORITY_UPDATE for request stream from the server.
fn priority_update_request_from_server() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::PriorityUpdateRequest {
prioritized_element_id: 0,
priority_field_value: b"u=3".to_vec(),
},
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
}
#[test]
/// Send a PRIORITY_UPDATE for request stream from the server.
fn priority_update_push_from_server() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_server(
frame::Frame::PriorityUpdatePush {
prioritized_element_id: 0,
priority_field_value: b"u=3".to_vec(),
},
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
}
#[test]
/// Ensure quiche allocates streams for client and server roles as expected.
fn uni_stream_local_counting() {
let config = Config::new().unwrap();
let h3_cln = Connection::new(&config, false, false).unwrap();
assert_eq!(h3_cln.next_uni_stream_id, 2);
let h3_srv = Connection::new(&config, true, false).unwrap();
assert_eq!(h3_srv.next_uni_stream_id, 3);
}
#[test]
/// Client opens multiple control streams, which is forbidden.
fn open_multiple_control_streams() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let stream_id = s.client.next_uni_stream_id;
let mut d = [42; 8];
let mut b = octets::OctetsMut::with_slice(&mut d);
s.pipe
.client
.stream_send(
stream_id,
b.put_varint(stream::HTTP3_CONTROL_STREAM_TYPE_ID).unwrap(),
false,
)
.unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Err(Error::StreamCreationError));
}
#[test]
/// Client closes the control stream, which is forbidden.
fn close_control_stream_after_type() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.pipe
.client
.stream_send(s.client.control_stream_id.unwrap(), &[], true)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client closes the control stream after a frame is sent, which is
/// forbidden.
fn close_control_stream_after_frame() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 1 },
s.client.control_stream_id.unwrap(),
true,
)
.unwrap();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client resets the control stream, which is forbidden.
fn reset_control_stream_after_type() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.pipe
.client
.stream_shutdown(
s.client.control_stream_id.unwrap(),
crate::Shutdown::Write,
0,
)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client resets the control stream after a frame is sent, which is
/// forbidden.
fn reset_control_stream_after_frame() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.send_frame_client(
frame::Frame::MaxPushId { push_id: 1 },
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
s.pipe
.client
.stream_shutdown(
s.client.control_stream_id.unwrap(),
crate::Shutdown::Write,
0,
)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client closes QPACK stream, which is forbidden.
fn close_qpack_stream_after_type() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.pipe
.client
.stream_send(
s.client.local_qpack_streams.encoder_stream_id.unwrap(),
&[],
true,
)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client closes QPACK stream after sending some stuff, which is forbidden.
fn close_qpack_stream_after_data() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
let d = [0; 1];
s.pipe.client.stream_send(stream_id, &d, false).unwrap();
s.pipe.client.stream_send(stream_id, &d, true).unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client resets QPACK stream, which is forbidden.
fn reset_qpack_stream_after_type() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
s.pipe
.client
.stream_shutdown(
s.client.local_qpack_streams.encoder_stream_id.unwrap(),
crate::Shutdown::Write,
0,
)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client resets QPACK stream after sending some stuff, which is forbidden.
fn reset_qpack_stream_after_data() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
let d = [0; 1];
s.pipe.client.stream_send(stream_id, &d, false).unwrap();
s.pipe.client.stream_send(stream_id, &d, false).unwrap();
s.advance().ok();
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
s.pipe
.client
.stream_shutdown(stream_id, crate::Shutdown::Write, 0)
.unwrap();
s.advance().ok();
assert_eq!(
Err(Error::ClosedCriticalStream),
s.server.poll(&mut s.pipe.server)
);
assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
}
#[test]
/// Client sends QPACK data.
fn qpack_data() {
// TODO: QPACK instructions are ignored until dynamic table support is
// added so we just test that the data is safely ignored.
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let e_stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
let d_stream_id = s.client.local_qpack_streams.decoder_stream_id.unwrap();
let d = [0; 20];
s.pipe.client.stream_send(e_stream_id, &d, false).unwrap();
s.advance().ok();
s.pipe.client.stream_send(d_stream_id, &d, false).unwrap();
s.advance().ok();
match s.server.poll(&mut s.pipe.server) {
Ok(_) => panic!(),
Err(Error::Done) => {
assert_eq!(s.server.peer_qpack_streams.encoder_stream_bytes, 20);
assert_eq!(s.server.peer_qpack_streams.decoder_stream_bytes, 20);
},
Err(_) => {
panic!();
},
}
let stats = s.server.stats();
assert_eq!(stats.qpack_encoder_stream_recv_bytes, 20);
assert_eq!(stats.qpack_decoder_stream_recv_bytes, 20);
}
#[test]
/// Tests limits for the stream state buffer maximum size.
fn max_state_buf_size() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
Header::new(b"user-agent", b"quiche-test"),
];
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, false),
Ok(0)
);
s.advance().ok();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.server.poll(&mut s.pipe.server), Ok((0, ev_headers)));
// DATA frames don't consume the state buffer, so can be of any size.
let mut d = [42; 128];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame_type = b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
s.pipe.client.stream_send(0, frame_type, false).unwrap();
let frame_len = b.put_varint(1 << 24).unwrap();
s.pipe.client.stream_send(0, frame_len, false).unwrap();
s.pipe.client.stream_send(0, &d, false).unwrap();
s.advance().ok();
assert_eq!(s.server.poll(&mut s.pipe.server), Ok((0, Event::Data)));
// GREASE frames consume the state buffer, so need to be limited.
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let mut d = [42; 128];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
s.pipe.client.stream_send(0, frame_type, false).unwrap();
let frame_len = b.put_varint(1 << 24).unwrap();
s.pipe.client.stream_send(0, frame_len, false).unwrap();
s.pipe.client.stream_send(0, &d, false).unwrap();
s.advance().ok();
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::ExcessiveLoad));
}
#[test]
/// Tests that DATA frames are properly truncated depending on the request
/// stream's outgoing flow control capacity.
fn stream_backpressure() {
let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let total_data_frames = 6;
for _ in 0..total_data_frames {
assert_eq!(
s.client
.send_body(&mut s.pipe.client, stream, &bytes, false),
Ok(bytes.len())
);
s.advance().ok();
}
assert_eq!(
s.client.send_body(&mut s.pipe.client, stream, &bytes, true),
Ok(bytes.len() - 2)
);
s.advance().ok();
let mut recv_buf = vec![0; bytes.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
for _ in 0..total_data_frames {
assert_eq!(
s.recv_body_server(stream, &mut recv_buf),
Ok(bytes.len())
);
}
assert_eq!(
s.recv_body_server(stream, &mut recv_buf),
Ok(bytes.len() - 2)
);
// Fin flag from last send_body() call was not sent as the buffer was
// only partially written.
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Tests that the max header list size setting is enforced.
fn request_max_header_size_limit() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(5);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let mut h3_config = Config::new().unwrap();
h3_config.set_max_field_section_size(65);
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
Header::new(b"aaaaaaa", b"aaaaaaaa"),
];
let stream = s
.client
.send_request(&mut s.pipe.client, &req, true)
.unwrap();
s.advance().ok();
assert_eq!(stream, 0);
assert_eq!(s.poll_server(), Err(Error::ExcessiveLoad));
assert_eq!(
s.pipe.server.local_error.as_ref().unwrap().error_code,
Error::to_wire(Error::ExcessiveLoad)
);
}
#[test]
/// Tests that Error::TransportError contains a transport error.
fn transport_error() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
Header::new(b"user-agent", b"quiche-test"),
];
// We need to open all streams in the same flight, so we can't use the
// Session::send_request() method because it also calls advance(),
// otherwise the server would send a MAX_STREAMS frame and the client
// wouldn't hit the streams limit.
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(4));
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(8));
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, true),
Ok(12)
);
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, true),
Ok(16)
);
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, true),
Err(Error::TransportError(crate::Error::StreamLimit))
);
}
#[test]
/// Tests that sending DATA before HEADERS causes an error.
fn data_before_headers() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let mut d = [42; 128];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame_type = b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
s.pipe.client.stream_send(0, frame_type, false).unwrap();
let frame_len = b.put_varint(5).unwrap();
s.pipe.client.stream_send(0, frame_len, false).unwrap();
s.pipe.client.stream_send(0, b"hello", false).unwrap();
s.advance().ok();
assert_eq!(
s.server.poll(&mut s.pipe.server),
Err(Error::FrameUnexpected)
);
}
#[test]
/// Tests that calling poll() after an error occurred does nothing.
fn poll_after_error() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let mut d = [42; 128];
let mut b = octets::OctetsMut::with_slice(&mut d);
let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
s.pipe.client.stream_send(0, frame_type, false).unwrap();
let frame_len = b.put_varint(1 << 24).unwrap();
s.pipe.client.stream_send(0, frame_len, false).unwrap();
s.pipe.client.stream_send(0, &d, false).unwrap();
s.advance().ok();
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::ExcessiveLoad));
// Try to call poll() again after an error occurred.
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
}
#[test]
/// Tests that we limit sending HEADERS based on the stream capacity.
fn headers_blocked() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
];
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, true),
Err(Error::StreamBlocked)
);
// Clear the writable stream queue.
assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
assert_eq!(s.pipe.client.stream_writable_next(), Some(10));
assert_eq!(s.pipe.client.stream_writable_next(), None);
s.advance().ok();
// Once the server gives flow control credits back, we can send the
// request.
assert_eq!(s.pipe.client.stream_writable_next(), Some(4));
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(4));
}
#[test]
/// Ensure StreamBlocked when connection flow control prevents headers.
fn headers_blocked_on_conn() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
// After the HTTP handshake, some bytes of connection flow control have
// been consumed. Fill the connection with more grease data on the control
// stream.
let d = [42; 28];
assert_eq!(s.pipe.client.stream_send(2, &d, false), Ok(23));
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
];
// There is 0 connection-level flow control, so sending a request is
// blocked.
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, true),
Err(Error::StreamBlocked)
);
assert_eq!(s.pipe.client.stream_writable_next(), None);
// Emit the control stream data and drain it at the server via poll() to
// consumes it via poll() and gives back flow control.
s.advance().ok();
assert_eq!(s.poll_server(), Err(Error::Done));
s.advance().ok();
// Now we can send the request.
assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
}
#[test]
/// Ensure STREAM_DATA_BLOCKED is not emitted multiple times with the same
/// offset when trying to send large bodies.
fn send_body_truncation_stream_blocked() {
use crate::testing::decode_pkt;
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(10000); // large connection-level flow control
config.set_initial_max_stream_data_bidi_local(80);
config.set_initial_max_stream_data_bidi_remote(80);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let _ = s.send_response(stream, false).unwrap();
assert_eq!(s.pipe.server.streams.blocked().len(), 0);
// The body must be larger than the stream window would allow
let d = [42; 500];
let mut off = 0;
let sent = s
.server
.send_body(&mut s.pipe.server, stream, &d, true)
.unwrap();
assert_eq!(sent, 25);
off += sent;
// send_body wrote as much as it could (sent < size of buff).
assert_eq!(s.pipe.server.streams.blocked().len(), 1);
assert_eq!(
s.server
.send_body(&mut s.pipe.server, stream, &d[off..], true),
Err(Error::Done)
);
assert_eq!(s.pipe.server.streams.blocked().len(), 1);
// Now read raw frames to see what the QUIC layer did
let mut buf = [0; 65535];
let (len, _) = s.pipe.server.send(&mut buf).unwrap();
let frames = decode_pkt(&mut s.pipe.client, &mut buf[..len]).unwrap();
let mut iter = frames.iter();
assert_eq!(
iter.next(),
Some(&crate::frame::Frame::StreamDataBlocked {
stream_id: 0,
limit: 80,
})
);
// At the server, after sending the STREAM_DATA_BLOCKED frame, we clear
// the mark.
assert_eq!(s.pipe.server.streams.blocked().len(), 0);
// Don't read any data from the client, so stream flow control is never
// given back in the form of changing the stream's max offset.
// Subsequent body send operations will still fail but no more
// STREAM_DATA_BLOCKED frames should be submitted since the limit didn't
// change. No frames means no packet to send.
assert_eq!(
s.server
.send_body(&mut s.pipe.server, stream, &d[off..], true),
Err(Error::Done)
);
assert_eq!(s.pipe.server.streams.blocked().len(), 0);
assert_eq!(s.pipe.server.send(&mut buf), Err(crate::Error::Done));
// Now update the client's max offset manually.
let frames = [crate::frame::Frame::MaxStreamData {
stream_id: 0,
max: 100,
}];
let pkt_type = crate::packet::Type::Short;
assert_eq!(
s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
Ok(39),
);
let sent = s
.server
.send_body(&mut s.pipe.server, stream, &d[off..], true)
.unwrap();
assert_eq!(sent, 18);
// Same thing here...
assert_eq!(s.pipe.server.streams.blocked().len(), 1);
assert_eq!(
s.server
.send_body(&mut s.pipe.server, stream, &d[off..], true),
Err(Error::Done)
);
assert_eq!(s.pipe.server.streams.blocked().len(), 1);
let (len, _) = s.pipe.server.send(&mut buf).unwrap();
let frames = decode_pkt(&mut s.pipe.client, &mut buf[..len]).unwrap();
let mut iter = frames.iter();
assert_eq!(
iter.next(),
Some(&crate::frame::Frame::StreamDataBlocked {
stream_id: 0,
limit: 100,
})
);
}
#[test]
/// Ensure stream doesn't hang due to small cwnd.
fn send_body_stream_blocked_by_small_cwnd() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(100000); // large connection-level flow control
config.set_initial_max_stream_data_bidi_local(100000);
config.set_initial_max_stream_data_bidi_remote(50000);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let _ = s.send_response(stream, false).unwrap();
// Clear the writable stream queue.
assert_eq!(s.pipe.server.stream_writable_next(), Some(3));
assert_eq!(s.pipe.server.stream_writable_next(), Some(7));
assert_eq!(s.pipe.server.stream_writable_next(), Some(11));
assert_eq!(s.pipe.server.stream_writable_next(), Some(stream));
assert_eq!(s.pipe.server.stream_writable_next(), None);
// The body must be larger than the cwnd would allow.
let send_buf = [42; 80000];
let sent = s
.server
.send_body(&mut s.pipe.server, stream, &send_buf, true)
.unwrap();
// send_body wrote as much as it could (sent < size of buff).
assert_eq!(sent, 11995);
s.advance().ok();
// Client reads received headers and body.
let mut recv_buf = [42; 80000];
assert!(s.poll_client().is_ok());
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(11995));
s.advance().ok();
// Server send cap is smaller than remaining body buffer.
assert!(s.pipe.server.tx_cap < send_buf.len() - sent);
// Once the server cwnd opens up, we can send more body.
assert_eq!(s.pipe.server.stream_writable_next(), Some(0));
}
#[test]
/// Ensure stream doesn't hang due to small cwnd.
fn send_body_stream_blocked_zero_length() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(100000); // large connection-level flow control
config.set_initial_max_stream_data_bidi_local(100000);
config.set_initial_max_stream_data_bidi_remote(50000);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
let _ = s.send_response(stream, false).unwrap();
// Clear the writable stream queue.
assert_eq!(s.pipe.server.stream_writable_next(), Some(3));
assert_eq!(s.pipe.server.stream_writable_next(), Some(7));
assert_eq!(s.pipe.server.stream_writable_next(), Some(11));
assert_eq!(s.pipe.server.stream_writable_next(), Some(stream));
assert_eq!(s.pipe.server.stream_writable_next(), None);
// The body is large enough to fill the cwnd, except for enough bytes
// for another DATA frame header (but no payload).
let send_buf = [42; 11994];
let sent = s
.server
.send_body(&mut s.pipe.server, stream, &send_buf, false)
.unwrap();
assert_eq!(sent, 11994);
// There is only enough capacity left for the DATA frame header, but
// no payload.
assert_eq!(s.pipe.server.stream_capacity(stream).unwrap(), 3);
assert_eq!(
s.server
.send_body(&mut s.pipe.server, stream, &send_buf, false),
Err(Error::Done)
);
s.advance().ok();
// Client reads received headers and body.
let mut recv_buf = [42; 80000];
assert!(s.poll_client().is_ok());
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(11994));
s.advance().ok();
// Once the server cwnd opens up, we can send more body.
assert_eq!(s.pipe.server.stream_writable_next(), Some(0));
}
#[test]
/// Test handling of 0-length DATA writes with and without fin.
fn zero_length_data() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
assert_eq!(
s.client.send_body(&mut s.pipe.client, 0, b"", false),
Err(Error::Done)
);
assert_eq!(s.client.send_body(&mut s.pipe.client, 0, b"", true), Ok(0));
s.advance().ok();
let mut recv_buf = vec![0; 100];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Err(Error::Done));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
let resp = s.send_response(stream, false).unwrap();
assert_eq!(
s.server.send_body(&mut s.pipe.server, 0, b"", false),
Err(Error::Done)
);
assert_eq!(s.server.send_body(&mut s.pipe.server, 0, b"", true), Ok(0));
s.advance().ok();
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Err(Error::Done));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Tests that blocked 0-length DATA writes are reported correctly.
fn zero_length_data_blocked() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(69);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
let req = vec![
Header::new(b":method", b"GET"),
Header::new(b":scheme", b"https"),
Header::new(b":authority", b"quic.tech"),
Header::new(b":path", b"/test"),
];
assert_eq!(
s.client.send_request(&mut s.pipe.client, &req, false),
Ok(0)
);
assert_eq!(
s.client.send_body(&mut s.pipe.client, 0, b"", true),
Err(Error::Done)
);
// Clear the writable stream queue.
assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
assert_eq!(s.pipe.client.stream_writable_next(), Some(10));
assert_eq!(s.pipe.client.stream_writable_next(), None);
s.advance().ok();
// Once the server gives flow control credits back, we can send the body.
assert_eq!(s.pipe.client.stream_writable_next(), Some(0));
assert_eq!(s.client.send_body(&mut s.pipe.client, 0, b"", true), Ok(0));
}
#[test]
/// Tests that receiving an empty SETTINGS frame is handled and reported.
fn empty_settings() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(5);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.set_ack_delay_exponent(8);
config.grease(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
assert!(s.client.peer_settings_raw().is_some());
assert!(s.server.peer_settings_raw().is_some());
}
#[test]
/// Tests that receiving a H3_DATAGRAM setting is ok.
fn dgram_setting() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.enable_dgram(true, 1000, 1000);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
assert_eq!(s.pipe.handshake(), Ok(()));
s.client.send_settings(&mut s.pipe.client).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
// Before processing SETTINGS (via poll), HTTP/3 DATAGRAMS are not
// enabled.
assert!(!s.server.dgram_enabled_by_peer(&s.pipe.server));
// When everything is ok, poll returns Done and DATAGRAM is enabled.
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
assert!(s.server.dgram_enabled_by_peer(&s.pipe.server));
// Now detect things on the client
s.server.send_settings(&mut s.pipe.server).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
assert!(!s.client.dgram_enabled_by_peer(&s.pipe.client));
assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::Done));
assert!(s.client.dgram_enabled_by_peer(&s.pipe.client));
}
#[test]
/// Tests that receiving a H3_DATAGRAM setting when no TP is set generates
/// an error.
fn dgram_setting_no_tp() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
assert_eq!(s.pipe.handshake(), Ok(()));
s.client.control_stream_id = Some(
s.client
.open_uni_stream(
&mut s.pipe.client,
stream::HTTP3_CONTROL_STREAM_TYPE_ID,
)
.unwrap(),
);
let settings = frame::Frame::Settings {
max_field_section_size: None,
qpack_max_table_capacity: None,
qpack_blocked_streams: None,
connect_protocol_enabled: None,
h3_datagram: Some(1),
grease: None,
additional_settings: Default::default(),
raw: Default::default(),
};
s.send_frame_client(settings, s.client.control_stream_id.unwrap(), false)
.unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::SettingsError));
}
#[test]
/// Tests that receiving SETTINGS with prohibited values generates an error.
fn settings_h2_prohibited() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
assert_eq!(s.pipe.handshake(), Ok(()));
s.client.control_stream_id = Some(
s.client
.open_uni_stream(
&mut s.pipe.client,
stream::HTTP3_CONTROL_STREAM_TYPE_ID,
)
.unwrap(),
);
s.server.control_stream_id = Some(
s.server
.open_uni_stream(
&mut s.pipe.server,
stream::HTTP3_CONTROL_STREAM_TYPE_ID,
)
.unwrap(),
);
let frame_payload_len = 2u64;
let settings = [
frame::SETTINGS_FRAME_TYPE_ID as u8,
frame_payload_len as u8,
0x2, // 0x2 is a reserved setting type
1,
];
s.send_arbitrary_stream_data_client(
&settings,
s.client.control_stream_id.unwrap(),
false,
)
.unwrap();
s.send_arbitrary_stream_data_server(
&settings,
s.server.control_stream_id.unwrap(),
false,
)
.unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::SettingsError));
assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::SettingsError));
}
#[test]
/// Tests that setting SETTINGS with prohibited values generates an error.
fn set_prohibited_additional_settings() {
let mut h3_config = Config::new().unwrap();
assert_eq!(
h3_config.set_additional_settings(vec![(
frame::SETTINGS_QPACK_MAX_TABLE_CAPACITY,
43
)]),
Err(Error::SettingsError)
);
assert_eq!(
h3_config.set_additional_settings(vec![(
frame::SETTINGS_MAX_FIELD_SECTION_SIZE,
43
)]),
Err(Error::SettingsError)
);
assert_eq!(
h3_config.set_additional_settings(vec![(
frame::SETTINGS_QPACK_BLOCKED_STREAMS,
43
)]),
Err(Error::SettingsError)
);
assert_eq!(
h3_config.set_additional_settings(vec![(
frame::SETTINGS_ENABLE_CONNECT_PROTOCOL,
43
)]),
Err(Error::SettingsError)
);
assert_eq!(
h3_config
.set_additional_settings(vec![(frame::SETTINGS_H3_DATAGRAM, 43)]),
Err(Error::SettingsError)
);
}
#[test]
/// Tests additional settings are actually exchanged by the peers.
fn set_additional_settings() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(70);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.grease(false);
let mut h3_config = Config::new().unwrap();
h3_config
.set_additional_settings(vec![(42, 43), (44, 45)])
.unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
assert_eq!(s.pipe.handshake(), Ok(()));
assert_eq!(s.pipe.advance(), Ok(()));
s.client.send_settings(&mut s.pipe.client).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
s.server.send_settings(&mut s.pipe.server).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::Done));
assert_eq!(
s.server.peer_settings_raw(),
Some(&[(42, 43), (44, 45)][..])
);
assert_eq!(
s.client.peer_settings_raw(),
Some(&[(42, 43), (44, 45)][..])
);
}
#[test]
/// Send a single DATAGRAM.
fn single_dgram() {
let mut buf = [0; 65535];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// We'll send default data of 10 bytes on flow ID 0.
let result = (11, 0, 1);
s.send_dgram_client(0).unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
s.send_dgram_server(0).unwrap();
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
}
#[test]
/// Send multiple DATAGRAMs.
fn multiple_dgram() {
let mut buf = [0; 65535];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// We'll send default data of 10 bytes on flow ID 0.
let result = (11, 0, 1);
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Err(Error::Done));
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_client(&mut buf), Err(Error::Done));
}
#[test]
/// Send more DATAGRAMs than the send queue allows.
fn multiple_dgram_overflow() {
let mut buf = [0; 65535];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// We'll send default data of 10 bytes on flow ID 0.
let result = (11, 0, 1);
// Five DATAGRAMs
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
// Only 3 independent DATAGRAMs to read events will fire.
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.recv_dgram_server(&mut buf), Err(Error::Done));
}
#[test]
/// Send a single DATAGRAM and request.
fn poll_datagram_cycling_no_read() {
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.enable_dgram(true, 100, 100);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
// Send request followed by DATAGRAM on client side.
let (stream, req) = s.send_request(false).unwrap();
s.send_body_client(stream, true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
s.send_dgram_client(0).unwrap();
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Send a single DATAGRAM and request.
fn poll_datagram_single_read() {
let mut buf = [0; 65535];
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.enable_dgram(true, 100, 100);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
// We'll send default data of 10 bytes on flow ID 0.
let result = (11, 0, 1);
// Send request followed by DATAGRAM on client side.
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
s.send_dgram_client(0).unwrap();
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Send response followed by DATAGRAM on server side
let resp = s.send_response(stream, false).unwrap();
let body = s.send_body_server(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
s.send_dgram_server(0).unwrap();
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Send multiple DATAGRAMs and requests.
fn poll_datagram_multi_read() {
let mut buf = [0; 65535];
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.enable_dgram(true, 100, 100);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
// 10 bytes on flow ID 0 and 2.
let flow_0_result = (11, 0, 1);
let flow_2_result = (11, 2, 1);
// Send requests followed by DATAGRAMs on client side.
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(2).unwrap();
s.send_dgram_client(2).unwrap();
s.send_dgram_client(2).unwrap();
s.send_dgram_client(2).unwrap();
s.send_dgram_client(2).unwrap();
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Second cycle, start to read
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Third cycle.
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
// Send response followed by DATAGRAM on server side
let resp = s.send_response(stream, false).unwrap();
let body = s.send_body_server(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: resp,
more_frames: true,
};
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
s.send_dgram_server(0).unwrap();
s.send_dgram_server(2).unwrap();
s.send_dgram_server(2).unwrap();
s.send_dgram_server(2).unwrap();
s.send_dgram_server(2).unwrap();
s.send_dgram_server(2).unwrap();
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
assert_eq!(s.poll_client(), Err(Error::Done));
// Second cycle, start to read
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
// Third cycle.
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_client(), Err(Error::Done));
}
#[test]
/// Tests that the Finished event is not issued for streams of unknown type
/// (e.g. GREASE).
fn finished_is_for_requests() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.client.open_grease_stream(&mut s.pipe.client), Ok(()));
assert_eq!(s.pipe.advance(), Ok(()));
assert_eq!(s.poll_client(), Err(Error::Done));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Tests that streams are marked as finished only once.
fn finished_once() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Err(Error::Done));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
/// Tests that the Data event is properly re-armed.
fn data_event_rearm() {
let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
let (r1_id, r1_hdrs) = s.send_request(false).unwrap();
let mut recv_buf = vec![0; bytes.len()];
let r1_ev_headers = Event::Headers {
list: r1_hdrs,
more_frames: true,
};
// Manually send an incomplete DATA frame (i.e. the frame size is longer
// than the actual data sent).
{
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
b.put_varint(bytes.len() as u64).unwrap();
let off = b.off();
s.pipe.client.stream_send(r1_id, &d[..off], false).unwrap();
assert_eq!(
s.pipe.client.stream_send(r1_id, &bytes[..5], false),
Ok(5)
);
s.advance().ok();
}
assert_eq!(s.poll_server(), Ok((r1_id, r1_ev_headers)));
assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Read the available body data.
assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(5));
// Send the remaining DATA payload.
assert_eq!(s.pipe.client.stream_send(r1_id, &bytes[5..], false), Ok(5));
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Read the rest of the body data.
assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(5));
assert_eq!(s.poll_server(), Err(Error::Done));
// Send more data.
let r1_body = s.send_body_client(r1_id, false).unwrap();
assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(r1_body.len()));
// Send a new request to ensure cross-stream events don't break rearming.
let (r2_id, r2_hdrs) = s.send_request(false).unwrap();
let r2_ev_headers = Event::Headers {
list: r2_hdrs,
more_frames: true,
};
let r2_body = s.send_body_client(r2_id, false).unwrap();
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r2_id, r2_ev_headers)));
assert_eq!(s.poll_server(), Ok((r2_id, Event::Data)));
assert_eq!(s.recv_body_server(r2_id, &mut recv_buf), Ok(r2_body.len()));
assert_eq!(s.poll_server(), Err(Error::Done));
// Send more data on request 1, then trailing HEADERS.
let r1_body = s.send_body_client(r1_id, false).unwrap();
let trailers = vec![Header::new(b"hello", b"world")];
s.client
.send_headers(&mut s.pipe.client, r1_id, &trailers, true)
.unwrap();
let r1_ev_trailers = Event::Headers {
list: trailers.clone(),
more_frames: false,
};
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(r1_body.len()));
assert_eq!(s.poll_server(), Ok((r1_id, r1_ev_trailers)));
assert_eq!(s.poll_server(), Ok((r1_id, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Send more data on request 2, then trailing HEADERS.
let r2_body = s.send_body_client(r2_id, false).unwrap();
s.client
.send_headers(&mut s.pipe.client, r2_id, &trailers, false)
.unwrap();
let r2_ev_trailers = Event::Headers {
list: trailers,
more_frames: true,
};
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r2_id, Event::Data)));
assert_eq!(s.recv_body_server(r2_id, &mut recv_buf), Ok(r2_body.len()));
assert_eq!(s.poll_server(), Ok((r2_id, r2_ev_trailers)));
assert_eq!(s.poll_server(), Err(Error::Done));
let (r3_id, r3_hdrs) = s.send_request(false).unwrap();
let r3_ev_headers = Event::Headers {
list: r3_hdrs,
more_frames: true,
};
// Manually send an incomplete DATA frame (i.e. only the header is sent).
{
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
b.put_varint(bytes.len() as u64).unwrap();
let off = b.off();
s.pipe.client.stream_send(r3_id, &d[..off], false).unwrap();
s.advance().ok();
}
assert_eq!(s.poll_server(), Ok((r3_id, r3_ev_headers)));
assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Err(Error::Done));
assert_eq!(s.pipe.client.stream_send(r3_id, &bytes[..5], false), Ok(5));
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(5));
assert_eq!(s.pipe.client.stream_send(r3_id, &bytes[5..], false), Ok(5));
s.advance().ok();
assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(5));
// Buffer multiple data frames.
let body = s.send_body_client(r3_id, false).unwrap();
s.send_body_client(r3_id, false).unwrap();
s.send_body_client(r3_id, false).unwrap();
assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
{
let mut d = [42; 10];
let mut b = octets::OctetsMut::with_slice(&mut d);
b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
b.put_varint(0).unwrap();
let off = b.off();
s.pipe.client.stream_send(r3_id, &d[..off], true).unwrap();
s.advance().ok();
}
let mut recv_buf = vec![0; bytes.len() * 3];
assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(body.len() * 3));
}
#[test]
/// Tests that the Datagram event is properly re-armed.
fn dgram_event_rearm() {
let mut buf = [0; 65535];
let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config.set_application_protos(&[b"h3"]).unwrap();
config.set_initial_max_data(1500);
config.set_initial_max_stream_data_bidi_local(150);
config.set_initial_max_stream_data_bidi_remote(150);
config.set_initial_max_stream_data_uni(150);
config.set_initial_max_streams_bidi(100);
config.set_initial_max_streams_uni(5);
config.verify_peer(false);
config.enable_dgram(true, 100, 100);
let h3_config = Config::new().unwrap();
let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
s.handshake().unwrap();
// 10 bytes on flow ID 0 and 2.
let flow_0_result = (11, 0, 1);
let flow_2_result = (11, 2, 1);
// Send requests followed by DATAGRAMs on client side.
let (stream, req) = s.send_request(false).unwrap();
let body = s.send_body_client(stream, true).unwrap();
let mut recv_buf = vec![0; body.len()];
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
s.send_dgram_client(0).unwrap();
s.send_dgram_client(0).unwrap();
s.send_dgram_client(2).unwrap();
s.send_dgram_client(2).unwrap();
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
s.send_dgram_client(0).unwrap();
s.send_dgram_client(2).unwrap();
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
}
#[test]
fn reset_stream() {
let mut buf = [0; 65535];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// Client sends request.
let (stream, req) = s.send_request(false).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
// Server sends response and closes stream.
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::Done));
let resp = s.send_response(stream, true).unwrap();
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
// Client sends RESET_STREAM, closing stream.
let frames = [crate::frame::Frame::ResetStream {
stream_id: stream,
error_code: 42,
final_size: 68,
}];
let pkt_type = crate::packet::Type::Short;
assert_eq!(
s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
Ok(39)
);
// Server issues Reset event for the stream.
assert_eq!(s.poll_server(), Ok((stream, Event::Reset(42))));
assert_eq!(s.poll_server(), Err(Error::Done));
// Sending RESET_STREAM again shouldn't trigger another Reset event.
assert_eq!(
s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
Ok(39)
);
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
fn reset_finished_at_server() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// Client sends HEADERS and doesn't fin
let (stream, _req) = s.send_request(false).unwrap();
// ..then Client sends RESET_STREAM
assert_eq!(
s.pipe.client.stream_shutdown(0, crate::Shutdown::Write, 0),
Ok(())
);
assert_eq!(s.pipe.advance(), Ok(()));
// Server receives just a reset
assert_eq!(s.poll_server(), Ok((stream, Event::Reset(0))));
assert_eq!(s.poll_server(), Err(Error::Done));
// Client sends HEADERS and fin
let (stream, req) = s.send_request(true).unwrap();
// ..then Client sends RESET_STREAM
assert_eq!(
s.pipe.client.stream_shutdown(4, crate::Shutdown::Write, 0),
Ok(())
);
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
// Server receives headers and fin.
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
}
#[test]
fn reset_finished_at_server_with_data_pending() {
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// Client sends HEADERS and doesn't fin.
let (stream, req) = s.send_request(false).unwrap();
assert!(s.send_body_client(stream, false).is_ok());
assert_eq!(s.pipe.advance(), Ok(()));
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
// Server receives headers and data...
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
// ..then Client sends RESET_STREAM.
assert_eq!(
s.pipe
.client
.stream_shutdown(stream, crate::Shutdown::Write, 0),
Ok(())
);
assert_eq!(s.pipe.advance(), Ok(()));
// Server receives the reset and there are no more readable streams.
assert_eq!(s.poll_server(), Ok((stream, Event::Reset(0))));
assert_eq!(s.poll_server(), Err(Error::Done));
assert_eq!(s.pipe.server.readable().len(), 0);
}
#[test]
fn reset_finished_at_client() {
let mut buf = [0; 65535];
let mut s = Session::new().unwrap();
s.handshake().unwrap();
// Client sends HEADERS and doesn't fin
let (stream, req) = s.send_request(false).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: true,
};
// Server receives headers.
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Server sends response and doesn't fin
s.send_response(stream, false).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
// .. then Server sends RESET_STREAM
assert_eq!(
s.pipe
.server
.stream_shutdown(stream, crate::Shutdown::Write, 0),
Ok(())
);
assert_eq!(s.pipe.advance(), Ok(()));
// Client receives Reset only
assert_eq!(s.poll_client(), Ok((stream, Event::Reset(0))));
assert_eq!(s.poll_server(), Err(Error::Done));
// Client sends headers and fin.
let (stream, req) = s.send_request(true).unwrap();
let ev_headers = Event::Headers {
list: req,
more_frames: false,
};
// Server receives headers and fin.
assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_server(), Err(Error::Done));
// Server sends response and fin
let resp = s.send_response(stream, true).unwrap();
assert_eq!(s.pipe.advance(), Ok(()));
// ..then Server sends RESET_STREAM
let frames = [crate::frame::Frame::ResetStream {
stream_id: stream,
error_code: 42,
final_size: 68,
}];
let pkt_type = crate::packet::Type::Short;
assert_eq!(
s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
Ok(39)
);
assert_eq!(s.pipe.advance(), Ok(()));
let ev_headers = Event::Headers {
list: resp,
more_frames: false,
};
// Client receives headers and fin.
assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
assert_eq!(s.poll_client(), Err(Error::Done));
}
}
#[cfg(feature = "ffi")]
mod ffi;
#[cfg(feature = "internal")]
#[doc(hidden)]
pub mod frame;
#[cfg(not(feature = "internal"))]
mod frame;
#[doc(hidden)]
pub mod qpack;
mod stream;