File size: 142,882 Bytes
d3de7c1 | 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 | import binascii
import logging
import os
from collections import deque
from dataclasses import dataclass
from enum import Enum
from functools import partial
from typing import (
Any,
Callable,
Deque,
Dict,
FrozenSet,
List,
Optional,
Sequence,
Set,
Tuple,
)
from .. import tls
from ..buffer import (
UINT_VAR_MAX,
UINT_VAR_MAX_SIZE,
Buffer,
BufferReadError,
size_uint_var,
)
from . import events
from .configuration import SMALLEST_MAX_DATAGRAM_SIZE, QuicConfiguration
from .congestion.base import K_GRANULARITY
from .crypto import CryptoError, CryptoPair, KeyUnavailableError, NoCallback
from .logger import QuicLoggerTrace
from .packet import (
CONNECTION_ID_MAX_SIZE,
NON_ACK_ELICITING_FRAME_TYPES,
PROBING_FRAME_TYPES,
RETRY_INTEGRITY_TAG_SIZE,
STATELESS_RESET_TOKEN_SIZE,
QuicErrorCode,
QuicFrameType,
QuicHeader,
QuicPacketType,
QuicProtocolVersion,
QuicStreamFrame,
QuicTransportParameters,
QuicVersionInformation,
get_retry_integrity_tag,
get_spin_bit,
pretty_protocol_version,
pull_ack_frame,
pull_quic_header,
pull_quic_transport_parameters,
push_ack_frame,
push_quic_transport_parameters,
)
from .packet_builder import QuicDeliveryState, QuicPacketBuilder, QuicPacketBuilderStop
from .recovery import QuicPacketRecovery, QuicPacketSpace
from .stream import FinalSizeError, QuicStream, StreamFinishedError
logger = logging.getLogger("quic")
CRYPTO_BUFFER_SIZE = 16384
EPOCH_SHORTCUTS = {
"I": tls.Epoch.INITIAL,
"H": tls.Epoch.HANDSHAKE,
"0": tls.Epoch.ZERO_RTT,
"1": tls.Epoch.ONE_RTT,
}
MAX_EARLY_DATA = 0xFFFFFFFF
MAX_REMOTE_CHALLENGES = 5
MAX_LOCAL_CHALLENGES = 5
SECRETS_LABELS = [
[
None,
"CLIENT_EARLY_TRAFFIC_SECRET",
"CLIENT_HANDSHAKE_TRAFFIC_SECRET",
"CLIENT_TRAFFIC_SECRET_0",
],
[
None,
None,
"SERVER_HANDSHAKE_TRAFFIC_SECRET",
"SERVER_TRAFFIC_SECRET_0",
],
]
STREAM_FLAGS = 0x07
STREAM_COUNT_MAX = 0x1000000000000000
UDP_HEADER_SIZE = 8
MAX_PENDING_RETIRES = 100
MAX_PENDING_CRYPTO = 524288 # in bytes
NetworkAddress = Any
# frame sizes
ACK_FRAME_CAPACITY = 64 # FIXME: this is arbitrary!
APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE # + reason length
CONNECTION_LIMIT_FRAME_CAPACITY = 1 + UINT_VAR_MAX_SIZE
HANDSHAKE_DONE_FRAME_CAPACITY = 1
MAX_STREAM_DATA_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE
NEW_CONNECTION_ID_FRAME_CAPACITY = (
1 + 2 * UINT_VAR_MAX_SIZE + 1 + CONNECTION_ID_MAX_SIZE + STATELESS_RESET_TOKEN_SIZE
)
PATH_CHALLENGE_FRAME_CAPACITY = 1 + 8
PATH_RESPONSE_FRAME_CAPACITY = 1 + 8
PING_FRAME_CAPACITY = 1
RESET_STREAM_FRAME_CAPACITY = 1 + 3 * UINT_VAR_MAX_SIZE
RETIRE_CONNECTION_ID_CAPACITY = 1 + UINT_VAR_MAX_SIZE
STOP_SENDING_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE
STREAMS_BLOCKED_CAPACITY = 1 + UINT_VAR_MAX_SIZE
TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 3 * UINT_VAR_MAX_SIZE # + reason length
def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]:
return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut)
def is_version_compatible(from_version: int, to_version: int) -> bool:
"""
Return whether it is possible to perform compatible version negotiation
from `from_version` to `to_version`.
"""
# Version 1 is compatible with version 2 and vice versa. These are the
# only compatible versions so far.
return set([from_version, to_version]) == set(
[QuicProtocolVersion.VERSION_1, QuicProtocolVersion.VERSION_2]
)
def dump_cid(cid: bytes) -> str:
return binascii.hexlify(cid).decode("ascii")
def get_epoch(packet_type: QuicPacketType) -> tls.Epoch:
if packet_type == QuicPacketType.INITIAL:
return tls.Epoch.INITIAL
elif packet_type == QuicPacketType.ZERO_RTT:
return tls.Epoch.ZERO_RTT
elif packet_type == QuicPacketType.HANDSHAKE:
return tls.Epoch.HANDSHAKE
else:
return tls.Epoch.ONE_RTT
def stream_is_client_initiated(stream_id: int) -> bool:
"""
Returns True if the stream is client initiated.
"""
return not (stream_id & 1)
def stream_is_unidirectional(stream_id: int) -> bool:
"""
Returns True if the stream is unidirectional.
"""
return bool(stream_id & 2)
class Limit:
def __init__(self, frame_type: int, name: str, value: int):
self.frame_type = frame_type
self.name = name
self.sent = value
self.used = 0
self.value = value
class QuicConnectionError(Exception):
def __init__(self, error_code: int, frame_type: int, reason_phrase: str):
self.error_code = error_code
self.frame_type = frame_type
self.reason_phrase = reason_phrase
def __str__(self) -> str:
s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase)
if self.frame_type is not None:
s += ", frame_type: %s" % self.frame_type
return s
class QuicConnectionAdapter(logging.LoggerAdapter):
def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:
return "[%s] %s" % (self.extra["id"], msg), kwargs
@dataclass
class QuicConnectionId:
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
was_sent: bool = False
class QuicConnectionState(Enum):
FIRSTFLIGHT = 0
CONNECTED = 1
CLOSING = 2
DRAINING = 3
TERMINATED = 4
class QuicNetworkPath:
def __init__(self, addr: NetworkAddress, is_validated: bool = False):
self.addr: NetworkAddress = addr
self.bytes_received: int = 0
self.bytes_sent: int = 0
self.is_validated: bool = is_validated
self.local_challenge_sent: bool = False
self.remote_challenges: Deque[bytes] = deque()
def can_send(self, size: int) -> bool:
return self.is_validated or (self.bytes_sent + size) <= 3 * self.bytes_received
@dataclass
class QuicReceiveContext:
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
time: float
version: Optional[int]
QuicTokenHandler = Callable[[bytes], None]
END_STATES = frozenset(
[
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
QuicConnectionState.TERMINATED,
]
)
class QuicConnection:
"""
A QUIC connection.
The state machine is driven by three kinds of sources:
- the API user requesting data to be send out (see :meth:`connect`,
:meth:`reset_stream`, :meth:`send_ping`, :meth:`send_datagram_frame`
and :meth:`send_stream_data`)
- data being received from the network (see :meth:`receive_datagram`)
- a timer firing (see :meth:`handle_timer`)
:param configuration: The QUIC configuration to use.
"""
def __init__(
self,
*,
configuration: QuicConfiguration,
original_destination_connection_id: Optional[bytes] = None,
retry_source_connection_id: Optional[bytes] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
token_handler: Optional[QuicTokenHandler] = None,
) -> None:
assert configuration.max_datagram_size >= SMALLEST_MAX_DATAGRAM_SIZE, (
"The smallest allowed maximum datagram size is "
f"{SMALLEST_MAX_DATAGRAM_SIZE} bytes"
)
if configuration.is_client:
assert (
original_destination_connection_id is None
), "Cannot set original_destination_connection_id for a client"
assert (
retry_source_connection_id is None
), "Cannot set retry_source_connection_id for a client"
else:
assert token_handler is None, "Cannot set `token_handler` for a server"
assert (
configuration.token == b""
), "Cannot set `configuration.token` for a server"
assert (
configuration.certificate is not None
), "SSL certificate is required for a server"
assert (
configuration.private_key is not None
), "SSL private key is required for a server"
assert (
original_destination_connection_id is not None
), "original_destination_connection_id is required for a server"
# configuration
self._configuration = configuration
self._is_client = configuration.is_client
self._ack_delay = K_GRANULARITY
self._close_at: Optional[float] = None
self._close_event: Optional[events.ConnectionTerminated] = None
self._connect_called = False
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._cryptos_initial: Dict[int, CryptoPair] = {}
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_frame_type: Optional[int] = None
self._crypto_packet_version: Optional[int] = None
self._crypto_retransmitted = False
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._events: Deque[events.QuicEvent] = deque()
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(configuration.connection_id_length),
sequence_number=0,
stateless_reset_token=os.urandom(16) if not self._is_client else None,
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
self._local_ack_delay_exponent = 3
self._local_active_connection_id_limit = 8
self._local_challenges: Dict[bytes, QuicNetworkPath] = {}
self._local_initial_source_connection_id = self._host_cids[0].cid
self._local_max_data = Limit(
frame_type=QuicFrameType.MAX_DATA,
name="max_data",
value=configuration.max_data,
)
self._local_max_stream_data_bidi_local = configuration.max_stream_data
self._local_max_stream_data_bidi_remote = configuration.max_stream_data
self._local_max_stream_data_uni = configuration.max_stream_data
self._local_max_streams_bidi = Limit(
frame_type=QuicFrameType.MAX_STREAMS_BIDI,
name="max_streams_bidi",
value=128,
)
self._local_max_streams_uni = Limit(
frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128
)
self._local_next_stream_id_bidi = 0 if self._is_client else 1
self._local_next_stream_id_uni = 2 if self._is_client else 3
self._loss_at: Optional[float] = None
self._max_datagram_size = configuration.max_datagram_size
self._network_paths: List[QuicNetworkPath] = []
self._pacing_at: Optional[float] = None
self._packet_number = 0
self._peer_cid = QuicConnectionId(
cid=os.urandom(configuration.connection_id_length), sequence_number=None
)
self._peer_cid_available: List[QuicConnectionId] = []
self._peer_cid_sequence_numbers: Set[int] = set([0])
self._peer_retire_prior_to = 0
self._peer_token = configuration.token
self._quic_logger: Optional[QuicLoggerTrace] = None
self._remote_ack_delay_exponent = 3
self._remote_active_connection_id_limit = 2
self._remote_initial_source_connection_id: Optional[bytes] = None
self._remote_max_idle_timeout: Optional[float] = None # seconds
self._remote_max_data = 0
self._remote_max_data_used = 0
self._remote_max_datagram_frame_size: Optional[int] = None
self._remote_max_stream_data_bidi_local = 0
self._remote_max_stream_data_bidi_remote = 0
self._remote_max_stream_data_uni = 0
self._remote_max_streams_bidi = 0
self._remote_max_streams_uni = 0
self._remote_version_information: Optional[QuicVersionInformation] = None
self._retry_count = 0
self._retry_source_connection_id = retry_source_connection_id
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._spin_bit = False
self._spin_highest_pn = 0
self._state = QuicConnectionState.FIRSTFLIGHT
self._streams: Dict[int, QuicStream] = {}
self._streams_queue: List[QuicStream] = []
self._streams_blocked_bidi: List[QuicStream] = []
self._streams_blocked_uni: List[QuicStream] = []
self._streams_finished: Set[int] = set()
self._version: Optional[int] = None
self._version_negotiated_compatible = False
self._version_negotiated_incompatible = False
if self._is_client:
self._original_destination_connection_id = self._peer_cid.cid
else:
self._original_destination_connection_id = (
original_destination_connection_id
)
# logging
self._logger = QuicConnectionAdapter(
logger, {"id": dump_cid(self._original_destination_connection_id)}
)
if configuration.quic_logger:
self._quic_logger = configuration.quic_logger.start_trace(
is_client=configuration.is_client,
odcid=self._original_destination_connection_id,
)
# loss recovery
self._loss = QuicPacketRecovery(
congestion_control_algorithm=configuration.congestion_control_algorithm,
initial_rtt=configuration.initial_rtt,
max_datagram_size=self._max_datagram_size,
peer_completed_address_validation=not self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
logger=self._logger,
)
# things to send
self._close_pending = False
self._datagrams_pending: Deque[bytes] = deque()
self._handshake_done_pending = False
self._ping_pending: List[int] = []
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._streams_blocked_pending = False
# callbacks
self._session_ticket_fetcher = session_ticket_fetcher
self._session_ticket_handler = session_ticket_handler
self._token_handler = token_handler
# frame handlers
self.__frame_handlers = {
0x00: (self._handle_padding_frame, EPOCHS("IH01")),
0x01: (self._handle_ping_frame, EPOCHS("IH01")),
0x02: (self._handle_ack_frame, EPOCHS("IH1")),
0x03: (self._handle_ack_frame, EPOCHS("IH1")),
0x04: (self._handle_reset_stream_frame, EPOCHS("01")),
0x05: (self._handle_stop_sending_frame, EPOCHS("01")),
0x06: (self._handle_crypto_frame, EPOCHS("IH1")),
0x07: (self._handle_new_token_frame, EPOCHS("1")),
0x08: (self._handle_stream_frame, EPOCHS("01")),
0x09: (self._handle_stream_frame, EPOCHS("01")),
0x0A: (self._handle_stream_frame, EPOCHS("01")),
0x0B: (self._handle_stream_frame, EPOCHS("01")),
0x0C: (self._handle_stream_frame, EPOCHS("01")),
0x0D: (self._handle_stream_frame, EPOCHS("01")),
0x0E: (self._handle_stream_frame, EPOCHS("01")),
0x0F: (self._handle_stream_frame, EPOCHS("01")),
0x10: (self._handle_max_data_frame, EPOCHS("01")),
0x11: (self._handle_max_stream_data_frame, EPOCHS("01")),
0x12: (self._handle_max_streams_bidi_frame, EPOCHS("01")),
0x13: (self._handle_max_streams_uni_frame, EPOCHS("01")),
0x14: (self._handle_data_blocked_frame, EPOCHS("01")),
0x15: (self._handle_stream_data_blocked_frame, EPOCHS("01")),
0x16: (self._handle_streams_blocked_frame, EPOCHS("01")),
0x17: (self._handle_streams_blocked_frame, EPOCHS("01")),
0x18: (self._handle_new_connection_id_frame, EPOCHS("01")),
0x19: (self._handle_retire_connection_id_frame, EPOCHS("01")),
0x1A: (self._handle_path_challenge_frame, EPOCHS("01")),
0x1B: (self._handle_path_response_frame, EPOCHS("01")),
0x1C: (self._handle_connection_close_frame, EPOCHS("IH01")),
0x1D: (self._handle_connection_close_frame, EPOCHS("01")),
0x1E: (self._handle_handshake_done_frame, EPOCHS("1")),
0x30: (self._handle_datagram_frame, EPOCHS("01")),
0x31: (self._handle_datagram_frame, EPOCHS("01")),
}
@property
def configuration(self) -> QuicConfiguration:
return self._configuration
@property
def original_destination_connection_id(self) -> bytes:
return self._original_destination_connection_id
def change_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
.. aioquic_transmit::
"""
if self._peer_cid_available:
# retire previous CID
self._retire_peer_cid(self._peer_cid)
# assign new CID
self._consume_peer_cid()
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
.. aioquic_transmit::
:param error_code: An error code indicating why the connection is
being closed.
:param reason_phrase: A human-readable explanation of why the
connection is being closed.
"""
if self._close_event is None and self._state not in END_STATES:
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_pending = True
def connect(self, addr: NetworkAddress, now: float) -> None:
"""
Initiate the TLS handshake.
This method can only be called for clients and a single time.
.. aioquic_transmit::
:param addr: The network address of the remote peer.
:param now: The current time.
"""
assert (
self._is_client and not self._connect_called
), "connect() can only be called for clients and a single time"
self._connect_called = True
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
if self._configuration.original_version is not None:
self._version = self._configuration.original_version
else:
self._version = self._configuration.supported_versions[0]
self._connect(now=now)
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
"""
Return a list of `(data, addr)` tuples of datagrams which need to be
sent, and the network address to which they need to be sent.
After calling this method call :meth:`get_timer` to know when the next
timer needs to be set.
:param now: The current time.
"""
network_path = self._network_paths[0]
if self._state in END_STATES:
return []
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
is_client=self._is_client,
max_datagram_size=self._max_datagram_size,
packet_number=self._packet_number,
peer_cid=self._peer_cid.cid,
peer_token=self._peer_token,
quic_logger=self._quic_logger,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
epoch_packet_types = []
if not self._handshake_confirmed:
epoch_packet_types += [
(tls.Epoch.INITIAL, QuicPacketType.INITIAL),
(tls.Epoch.HANDSHAKE, QuicPacketType.HANDSHAKE),
]
epoch_packet_types.append((tls.Epoch.ONE_RTT, QuicPacketType.ONE_RTT))
for epoch, packet_type in epoch_packet_types:
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
self._write_connection_close_frame(
builder=builder,
epoch=epoch,
error_code=self._close_event.error_code,
frame_type=self._close_event.frame_type,
reason_phrase=self._close_event.reason_phrase,
)
self._logger.info(
"Connection close sent (code 0x%X, reason %s)",
self._close_event.error_code,
self._close_event.reason_phrase,
)
self._close_pending = False
self._close_begin(is_initiator=True, now=now)
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes_in_flight
)
if (
self._probe_pending
and builder.max_flight_bytes < self._max_datagram_size
):
builder.max_flight_bytes = self._max_datagram_size
# limit data on un-validated network paths
if not network_path.is_validated:
builder.max_total_bytes = (
network_path.bytes_received * 3 - network_path.bytes_sent
)
try:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch, now)
self._write_application(builder, network_path, now)
except QuicPacketBuilderStop:
pass
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# register packets
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# log packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_sent",
data={
"frames": packet.quic_logger_frames,
"header": {
"packet_number": packet.packet_number,
"packet_type": self._quic_logger.packet_type(
packet.packet_type
),
"scid": (
""
if packet.packet_type == QuicPacketType.ONE_RTT
else dump_cid(self.host_cid)
),
"dcid": dump_cid(self._peer_cid.cid),
},
"raw": {"length": packet.sent_bytes},
},
)
# check if we can discard initial keys
if sent_handshake and self._is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# return datagrams to send and the destination network address
ret = []
for datagram in datagrams:
payload_length = len(datagram)
network_path.bytes_sent += payload_length
ret.append((datagram, network_path.addr))
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="datagrams_sent",
data={
"count": 1,
"raw": [
{
"length": UDP_HEADER_SIZE + payload_length,
"payload_length": payload_length,
}
],
},
)
return ret
def get_next_available_stream_id(self, is_unidirectional=False) -> int:
"""
Return the stream ID for the next stream created by this endpoint.
"""
if is_unidirectional:
return self._local_next_stream_id_uni
else:
return self._local_next_stream_id_bidi
def get_timer(self) -> Optional[float]:
"""
Return the time at which the timer should fire or None if no timer is needed.
"""
timer_at = self._close_at
if self._state not in END_STATES:
# ack timer
for space in self._loss.spaces:
if space.ack_at is not None and space.ack_at < timer_at:
timer_at = space.ack_at
# loss detection timer
self._loss_at = self._loss.get_loss_detection_time()
if self._loss_at is not None and self._loss_at < timer_at:
timer_at = self._loss_at
# pacing timer
if self._pacing_at is not None and self._pacing_at < timer_at:
timer_at = self._pacing_at
return timer_at
def handle_timer(self, now: float) -> None:
"""
Handle the timer.
.. aioquic_transmit::
:param now: The current time.
"""
# end of closing period or idle timeout
if now >= self._close_at:
if self._close_event is None:
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=QuicFrameType.PADDING,
reason_phrase="Idle timeout",
)
self._close_end()
return
# loss detection timeout
if self._loss_at is not None and now >= self._loss_at:
self._logger.debug("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=now)
def next_event(self) -> Optional[events.QuicEvent]:
"""
Retrieve the next event from the event buffer.
Returns `None` if there are no buffered events.
"""
try:
return self._events.popleft()
except IndexError:
return None
def _idle_timeout(self) -> float:
# RFC 9000 section 10.1
# Start with our local timeout.
idle_timeout = self._configuration.idle_timeout
if self._remote_max_idle_timeout is not None:
# Our peer has a preference too, so pick the smaller timeout.
idle_timeout = min(idle_timeout, self._remote_max_idle_timeout)
# But not too small!
return max(idle_timeout, 3 * self._loss.get_probe_timeout())
def receive_datagram(self, data: bytes, addr: NetworkAddress, now: float) -> None:
"""
Handle an incoming datagram.
.. aioquic_transmit::
:param data: The datagram which was received.
:param addr: The network address from which the datagram was received.
:param now: The current time.
"""
payload_length = len(data)
# stop handling packets when closing
if self._state in END_STATES:
return
# log datagram
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="datagrams_received",
data={
"count": 1,
"raw": [
{
"length": UDP_HEADER_SIZE + payload_length,
"payload_length": payload_length,
}
],
},
)
# For anti-amplification purposes, servers need to keep track of the
# amount of data received on unvalidated network paths. We must count the
# entire datagram size regardless of whether packets are processed or
# dropped.
#
# This is particularly important when talking to clients who pad
# datagrams containing INITIAL packets by appending bytes after the
# long-header packets, which is legitimate behaviour.
#
# https://datatracker.ietf.org/doc/html/rfc9000#section-8.1
network_path = self._find_network_path(addr)
if not network_path.is_validated:
network_path.bytes_received += payload_length
# for servers, arm the idle timeout on the first datagram
if self._close_at is None:
self._close_at = now + self._idle_timeout()
buf = Buffer(data=data)
while not buf.eof():
start_off = buf.tell()
try:
header = pull_quic_header(
buf, host_cid_length=self._configuration.connection_id_length
)
except ValueError:
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "header_parse_error",
"raw": {"length": buf.capacity - start_off},
},
)
return
# RFC 9000 section 14.1 requires servers to drop all initial packets
# contained in a datagram smaller than 1200 bytes.
if (
not self._is_client
and header.packet_type == QuicPacketType.INITIAL
and payload_length < SMALLEST_MAX_DATAGRAM_SIZE
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "initial_packet_datagram_too_small",
"raw": {"length": header.packet_length},
},
)
return
# Check destination CID matches.
destination_cid_seq: Optional[int] = None
for connection_id in self._host_cids:
if header.destination_cid == connection_id.cid:
destination_cid_seq = connection_id.sequence_number
break
if (
self._is_client or header.packet_type == QuicPacketType.HANDSHAKE
) and destination_cid_seq is None:
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "unknown_connection_id",
"raw": {"length": header.packet_length},
},
)
return
# Handle version negotiation packet.
if header.packet_type == QuicPacketType.VERSION_NEGOTIATION:
self._receive_version_negotiation_packet(header=header, now=now)
return
# Check long header packet protocol version.
if (
header.version is not None
and header.version not in self._configuration.supported_versions
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "unsupported_version",
"raw": {"length": header.packet_length},
},
)
return
# Handle retry packet.
if header.packet_type == QuicPacketType.RETRY:
self._receive_retry_packet(
header=header,
packet_without_tag=buf.data_slice(
start_off, buf.tell() - RETRY_INTEGRITY_TAG_SIZE
),
now=now,
)
return
crypto_frame_required = False
# Server initialization.
if not self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT:
assert (
header.packet_type == QuicPacketType.INITIAL
), "first packet must be INITIAL"
crypto_frame_required = True
self._network_paths = [network_path]
self._version = header.version
self._initialize(header.destination_cid)
# Determine crypto and packet space.
epoch = get_epoch(header.packet_type)
if epoch == tls.Epoch.INITIAL:
crypto = self._cryptos_initial[header.version]
else:
crypto = self._cryptos[epoch]
if epoch == tls.Epoch.ZERO_RTT:
space = self._spaces[tls.Epoch.ONE_RTT]
else:
space = self._spaces[epoch]
# decrypt packet
encrypted_off = buf.tell() - start_off
end_off = start_off + header.packet_length
buf.seek(end_off)
try:
plain_header, plain_payload, packet_number = crypto.decrypt_packet(
data[start_off:end_off], encrypted_off, space.expected_packet_number
)
except KeyUnavailableError as exc:
self._logger.debug(exc)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "key_unavailable",
"raw": {"length": header.packet_length},
},
)
# If a client receives HANDSHAKE or 1-RTT packets before it has
# handshake keys, it can assume that the server's INITIAL was lost.
if (
self._is_client
and epoch in (tls.Epoch.HANDSHAKE, tls.Epoch.ONE_RTT)
and not self._crypto_retransmitted
):
self._loss.reschedule_data(now=now)
self._crypto_retransmitted = True
continue
except CryptoError as exc:
self._logger.debug(exc)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "payload_decrypt_error",
"raw": {"length": header.packet_length},
},
)
continue
# check reserved bits
if header.packet_type == QuicPacketType.ONE_RTT:
reserved_mask = 0x18
else:
reserved_mask = 0x0C
if plain_header[0] & reserved_mask:
self.close(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=QuicFrameType.PADDING,
reason_phrase="Reserved bits must be zero",
)
return
# log packet
quic_logger_frames: Optional[List[Dict]] = None
if self._quic_logger is not None:
quic_logger_frames = []
self._quic_logger.log_event(
category="transport",
event="packet_received",
data={
"frames": quic_logger_frames,
"header": {
"packet_number": packet_number,
"packet_type": self._quic_logger.packet_type(
header.packet_type
),
"dcid": dump_cid(header.destination_cid),
"scid": dump_cid(header.source_cid),
},
"raw": {"length": header.packet_length},
},
)
# raise expected packet number
if packet_number > space.expected_packet_number:
space.expected_packet_number = packet_number + 1
# discard initial keys and packet space
if not self._is_client and epoch == tls.Epoch.HANDSHAKE:
self._discard_epoch(tls.Epoch.INITIAL)
# update state
if self._peer_cid.sequence_number is None:
self._peer_cid.cid = header.source_cid
self._peer_cid.sequence_number = 0
if self._state == QuicConnectionState.FIRSTFLIGHT:
self._remote_initial_source_connection_id = header.source_cid
self._set_state(QuicConnectionState.CONNECTED)
# update spin bit
if (
header.packet_type == QuicPacketType.ONE_RTT
and packet_number > self._spin_highest_pn
):
spin_bit = get_spin_bit(plain_header[0])
if self._is_client:
self._spin_bit = not spin_bit
else:
self._spin_bit = spin_bit
self._spin_highest_pn = packet_number
if self._quic_logger is not None:
self._quic_logger.log_event(
category="connectivity",
event="spin_bit_updated",
data={"state": self._spin_bit},
)
# handle payload
context = QuicReceiveContext(
epoch=epoch,
host_cid=header.destination_cid,
network_path=network_path,
quic_logger_frames=quic_logger_frames,
time=now,
version=header.version,
)
try:
is_ack_eliciting, is_probing = self._payload_received(
context, plain_payload, crypto_frame_required=crypto_frame_required
)
except QuicConnectionError as exc:
self._logger.warning(exc)
self.close(
error_code=exc.error_code,
frame_type=exc.frame_type,
reason_phrase=exc.reason_phrase,
)
if self._state in END_STATES or self._close_pending:
return
# update idle timeout
self._close_at = now + self._idle_timeout()
# handle migration
if (
not self._is_client
and context.host_cid != self.host_cid
and epoch == tls.Epoch.ONE_RTT
):
self._logger.debug(
"Peer switching to CID %s (%d)",
dump_cid(context.host_cid),
destination_cid_seq,
)
self.host_cid = context.host_cid
self.change_connection_id()
# update network path
if not network_path.is_validated and epoch == tls.Epoch.HANDSHAKE:
self._logger.debug(
"Network path %s validated by handshake", network_path.addr
)
network_path.is_validated = True
if network_path not in self._network_paths:
self._network_paths.append(network_path)
idx = self._network_paths.index(network_path)
if idx and not is_probing and packet_number > space.largest_received_packet:
self._logger.debug("Network path %s promoted", network_path.addr)
self._network_paths.pop(idx)
self._network_paths.insert(0, network_path)
# record packet as received
if not space.discarded:
if packet_number > space.largest_received_packet:
space.largest_received_packet = packet_number
space.largest_received_time = now
space.ack_queue.add(packet_number)
if is_ack_eliciting and space.ack_at is None:
space.ack_at = now + self._ack_delay
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
.. aioquic_transmit::
"""
assert self._handshake_complete, "cannot change key before handshake completes"
self._cryptos[tls.Epoch.ONE_RTT].update_key()
def reset_stream(self, stream_id: int, error_code: int) -> None:
"""
Abruptly terminate the sending part of a stream.
.. aioquic_transmit::
:param stream_id: The stream's ID.
:param error_code: An error code indicating why the stream is being reset.
"""
stream = self._get_or_create_stream_for_send(stream_id)
stream.sender.reset(error_code)
def send_ping(self, uid: int) -> None:
"""
Send a PING frame to the peer.
.. aioquic_transmit::
:param uid: A unique ID for this PING.
"""
self._ping_pending.append(uid)
def send_datagram_frame(self, data: bytes) -> None:
"""
Send a DATAGRAM frame.
.. aioquic_transmit::
:param data: The data to be sent.
"""
self._datagrams_pending.append(data)
def send_stream_data(
self, stream_id: int, data: bytes, end_stream: bool = False
) -> None:
"""
Send data on the specific stream.
.. aioquic_transmit::
:param stream_id: The stream's ID.
:param data: The data to be sent.
:param end_stream: If set to `True`, the FIN bit will be set.
"""
stream = self._get_or_create_stream_for_send(stream_id)
stream.sender.write(data, end_stream=end_stream)
def stop_stream(self, stream_id: int, error_code: int) -> None:
"""
Request termination of the receiving part of a stream.
.. aioquic_transmit::
:param stream_id: The stream's ID.
:param error_code: An error code indicating why the stream is being stopped.
"""
if not self._stream_can_receive(stream_id):
raise ValueError(
"Cannot stop receiving on a local-initiated unidirectional stream"
)
stream = self._streams.get(stream_id, None)
if stream is None:
raise ValueError("Cannot stop receiving on an unknown stream")
stream.receiver.stop(error_code)
# Private
def _alpn_handler(self, alpn_protocol: str) -> None:
"""
Callback which is invoked by the TLS engine at most once, when the
ALPN negotiation completes.
At this point, TLS extensions have been received so we can parse the
transport parameters.
"""
# Parse the remote transport parameters.
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
break
else:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR
+ tls.AlertDescription.missing_extension,
frame_type=self._crypto_frame_type,
reason_phrase="No QUIC transport parameters received",
)
# For servers, determine the Negotiated Version.
if not self._is_client and not self._version_negotiated_compatible:
if self._remote_version_information is not None:
# Pick the first version we support in the client's available versions,
# which is compatible with the current version.
for version in self._remote_version_information.available_versions:
if version == self._version:
# Stay with the current version.
break
elif (
version in self._configuration.supported_versions
and is_version_compatible(self._version, version)
):
# Change version.
self._version = version
self._cryptos[tls.Epoch.INITIAL] = self._cryptos_initial[
version
]
# Update our transport parameters to reflect the chosen version.
self.tls.handshake_extensions = [
(
tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
self._serialize_transport_parameters(),
)
]
break
self._version_negotiated_compatible = True
self._logger.info(
"Negotiated protocol version %s", pretty_protocol_version(self._version)
)
# Notify the application.
self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol))
def _assert_stream_can_receive(self, frame_type: int, stream_id: int) -> None:
"""
Check the specified stream can receive data or raises a QuicConnectionError.
"""
if not self._stream_can_receive(stream_id):
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_STATE_ERROR,
frame_type=frame_type,
reason_phrase="Stream is send-only",
)
def _assert_stream_can_send(self, frame_type: int, stream_id: int) -> None:
"""
Check the specified stream can send data or raises a QuicConnectionError.
"""
if not self._stream_can_send(stream_id):
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_STATE_ERROR,
frame_type=frame_type,
reason_phrase="Stream is receive-only",
)
def _consume_peer_cid(self) -> None:
"""
Update the destination connection ID by taking the next
available connection ID provided by the peer.
"""
self._peer_cid = self._peer_cid_available.pop(0)
self._logger.debug(
"Switching to CID %s (%d)",
dump_cid(self._peer_cid.cid),
self._peer_cid.sequence_number,
)
def _close_begin(self, is_initiator: bool, now: float) -> None:
"""
Begin the close procedure.
"""
self._close_at = now + 3 * self._loss.get_probe_timeout()
if is_initiator:
self._set_state(QuicConnectionState.CLOSING)
else:
self._set_state(QuicConnectionState.DRAINING)
def _close_end(self) -> None:
"""
End the close procedure.
"""
self._close_at = None
for epoch in self._spaces.keys():
self._discard_epoch(epoch)
self._events.append(self._close_event)
self._set_state(QuicConnectionState.TERMINATED)
# signal log end
if self._quic_logger is not None:
self._configuration.quic_logger.end_trace(self._quic_logger)
self._quic_logger = None
def _connect(self, now: float) -> None:
"""
Start the client handshake.
"""
assert self._is_client
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="version_information",
data={
"client_versions": self._configuration.supported_versions,
"chosen_version": self._version,
},
)
self._quic_logger.log_event(
category="transport",
event="alpn_information",
data={"client_alpns": self._configuration.alpn_protocols},
)
self._close_at = now + self._idle_timeout()
self._initialize(self._peer_cid.cid)
self.tls.handle_message(b"", self._crypto_buffers)
self._push_crypto_data()
def _discard_epoch(self, epoch: tls.Epoch) -> None:
if not self._spaces[epoch].discarded:
self._logger.debug("Discarding epoch %s", epoch)
self._cryptos[epoch].teardown()
if epoch == tls.Epoch.INITIAL:
# Tear the crypto pairs, but do not log the event,
# to avoid duplicate log entries.
for crypto in self._cryptos_initial.values():
crypto.recv._teardown_cb = NoCallback
crypto.send._teardown_cb = NoCallback
crypto.teardown()
self._loss.discard_space(self._spaces[epoch])
self._spaces[epoch].discarded = True
def _find_network_path(self, addr: NetworkAddress) -> QuicNetworkPath:
# check existing network paths
for idx, network_path in enumerate(self._network_paths):
if network_path.addr == addr:
return network_path
# new network path
network_path = QuicNetworkPath(addr)
self._logger.debug("Network path %s discovered", network_path.addr)
return network_path
def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream:
"""
Get or create a stream in response to a received frame.
"""
if stream_id in self._streams_finished:
# the stream was created, but its state was since discarded
raise StreamFinishedError
stream = self._streams.get(stream_id, None)
if stream is None:
# check initiator
if stream_is_client_initiated(stream_id) == self._is_client:
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_STATE_ERROR,
frame_type=frame_type,
reason_phrase="Wrong stream initiator",
)
# determine limits
if stream_is_unidirectional(stream_id):
max_stream_data_local = self._local_max_stream_data_uni
max_stream_data_remote = 0
max_streams = self._local_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_remote
max_stream_data_remote = self._remote_max_stream_data_bidi_local
max_streams = self._local_max_streams_bidi
# check max streams
stream_count = (stream_id // 4) + 1
if stream_count > max_streams.value:
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_LIMIT_ERROR,
frame_type=frame_type,
reason_phrase="Too many streams open",
)
elif stream_count > max_streams.used:
max_streams.used = stream_count
# create stream
self._logger.debug("Stream %d created by peer" % stream_id)
stream = self._streams[stream_id] = QuicStream(
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
writable=not stream_is_unidirectional(stream_id),
)
self._streams_queue.append(stream)
return stream
def _get_or_create_stream_for_send(self, stream_id: int) -> QuicStream:
"""
Get or create a QUIC stream in order to send data to the peer.
This always occurs as a result of an API call.
"""
if not self._stream_can_send(stream_id):
raise ValueError("Cannot send data on peer-initiated unidirectional stream")
stream = self._streams.get(stream_id, None)
if stream is None:
# check initiator
if stream_is_client_initiated(stream_id) != self._is_client:
raise ValueError("Cannot send data on unknown peer-initiated stream")
# determine limits
if stream_is_unidirectional(stream_id):
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
streams_blocked = self._streams_blocked_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
streams_blocked = self._streams_blocked_bidi
# create stream
is_unidirectional = stream_is_unidirectional(stream_id)
stream = self._streams[stream_id] = QuicStream(
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
readable=not is_unidirectional,
)
self._streams_queue.append(stream)
if is_unidirectional:
self._local_next_stream_id_uni = stream_id + 4
else:
self._local_next_stream_id_bidi = stream_id + 4
# mark stream as blocked if needed
if stream_id // 4 >= max_streams:
stream.is_blocked = True
streams_blocked.append(stream)
self._streams_blocked_pending = True
return stream
def _handle_session_ticket(self, session_ticket: tls.SessionTicket) -> None:
if (
session_ticket.max_early_data_size is not None
and session_ticket.max_early_data_size != MAX_EARLY_DATA
):
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="Invalid max_early_data value %s"
% session_ticket.max_early_data_size,
)
self._session_ticket_handler(session_ticket)
def _initialize(self, peer_cid: bytes) -> None:
# TLS
self.tls = tls.Context(
alpn_protocols=self._configuration.alpn_protocols,
cadata=self._configuration.cadata,
cafile=self._configuration.cafile,
capath=self._configuration.capath,
cipher_suites=self.configuration.cipher_suites,
is_client=self._is_client,
logger=self._logger,
max_early_data=None if self._is_client else MAX_EARLY_DATA,
server_name=self._configuration.server_name,
verify_mode=self._configuration.verify_mode,
)
self.tls.certificate = self._configuration.certificate
self.tls.certificate_chain = self._configuration.certificate_chain
self.tls.certificate_private_key = self._configuration.private_key
self.tls.handshake_extensions = [
(
tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
self._serialize_transport_parameters(),
)
]
# TLS session resumption
session_ticket = self._configuration.session_ticket
if (
self._is_client
and session_ticket is not None
and session_ticket.is_valid
and session_ticket.server_name == self._configuration.server_name
):
self.tls.session_ticket = self._configuration.session_ticket
# parse saved QUIC transport parameters - for 0-RTT
if session_ticket.max_early_data_size == MAX_EARLY_DATA:
for ext_type, ext_data in session_ticket.other_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(
ext_data, from_session_ticket=True
)
break
# TLS callbacks
self.tls.alpn_cb = self._alpn_handler
if self._session_ticket_fetcher is not None:
self.tls.get_session_ticket_cb = self._session_ticket_fetcher
if self._session_ticket_handler is not None:
self.tls.new_session_ticket_cb = self._handle_session_ticket
self.tls.update_traffic_key_cb = self._update_traffic_key
# packet spaces
def create_crypto_pair(epoch: tls.Epoch) -> CryptoPair:
epoch_name = ["initial", "0rtt", "handshake", "1rtt"][epoch.value]
secret_names = [
"server_%s_secret" % epoch_name,
"client_%s_secret" % epoch_name,
]
recv_secret_name = secret_names[not self._is_client]
send_secret_name = secret_names[self._is_client]
return CryptoPair(
recv_setup_cb=partial(self._log_key_updated, recv_secret_name),
recv_teardown_cb=partial(self._log_key_retired, recv_secret_name),
send_setup_cb=partial(self._log_key_updated, send_secret_name),
send_teardown_cb=partial(self._log_key_retired, send_secret_name),
)
# To enable version negotiation, setup encryption keys for all
# our supported versions.
self._cryptos_initial = {}
for version in self._configuration.supported_versions:
pair = CryptoPair()
pair.setup_initial(cid=peer_cid, is_client=self._is_client, version=version)
self._cryptos_initial[version] = pair
self._cryptos = dict(
(epoch, create_crypto_pair(epoch))
for epoch in (
tls.Epoch.ZERO_RTT,
tls.Epoch.HANDSHAKE,
tls.Epoch.ONE_RTT,
)
)
self._cryptos[tls.Epoch.INITIAL] = self._cryptos_initial[self._version]
self._crypto_buffers = {
tls.Epoch.INITIAL: Buffer(capacity=CRYPTO_BUFFER_SIZE),
tls.Epoch.HANDSHAKE: Buffer(capacity=CRYPTO_BUFFER_SIZE),
tls.Epoch.ONE_RTT: Buffer(capacity=CRYPTO_BUFFER_SIZE),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
self._loss.spaces = list(self._spaces.values())
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
buf.pull_uint_var()
buf.pull_uint_var()
buf.pull_uint_var()
ack_delay = (ack_delay_encoded << self._remote_ack_delay_exponent) / 1000000
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_ack_frame(ack_rangeset, ack_delay)
)
# check whether peer completed address validation
if not self._loss.peer_completed_address_validation and context.epoch in (
tls.Epoch.HANDSHAKE,
tls.Epoch.ONE_RTT,
):
self._loss.peer_completed_address_validation = True
self._loss.on_ack_received(
ack_rangeset=ack_rangeset,
ack_delay=ack_delay,
now=context.time,
space=self._spaces[context.epoch],
)
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
error_code = buf.pull_uint_var()
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
frame_type = buf.pull_uint_var()
else:
frame_type = None
reason_length = buf.pull_uint_var()
try:
reason_phrase = buf.pull_bytes(reason_length).decode("utf8")
except UnicodeDecodeError:
reason_phrase = ""
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_connection_close_frame(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._logger.info(
"Connection close received (code 0x%X, reason %s)",
error_code,
reason_phrase,
)
if self._close_event is None:
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_begin(is_initiator=False, now=context.time)
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
offset = buf.pull_uint_var()
length = buf.pull_uint_var()
if offset + length > UINT_VAR_MAX:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="offset + length cannot exceed 2^62 - 1",
)
frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
# Log the frame.
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_crypto_frame(frame)
)
stream = self._crypto_streams[context.epoch]
pending = offset + length - stream.receiver.starting_offset()
if pending > MAX_PENDING_CRYPTO:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_BUFFER_EXCEEDED,
frame_type=frame_type,
reason_phrase="too much crypto buffering",
)
event = stream.receiver.handle_frame(frame)
if event is not None:
# Pass data to TLS layer, which may cause calls to:
# - _alpn_handler
# - _update_traffic_key
self._crypto_frame_type = frame_type
self._crypto_packet_version = context.version
try:
self.tls.handle_message(event.data, self._crypto_buffers)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=frame_type,
reason_phrase=str(exc),
)
# Update the current epoch.
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
# for servers, the handshake is now confirmed
if not self._is_client:
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
self._handshake_done_pending = True
self._replenish_connection_ids()
self._events.append(
events.HandshakeCompleted(
alpn_protocol=self.tls.alpn_negotiated,
early_data_accepted=self.tls.early_data_accepted,
session_resumed=self.tls.session_resumed,
)
)
self._unblock_streams(is_unidirectional=False)
self._unblock_streams(is_unidirectional=True)
self._logger.info(
"ALPN negotiated protocol %s", self.tls.alpn_negotiated
)
else:
self._logger.info(
"Duplicate CRYPTO data received for epoch %s", context.epoch
)
# If a server receives duplicate CRYPTO in an INITIAL packet,
# it can assume the client did not receive the server's CRYPTO.
if (
not self._is_client
and context.epoch == tls.Epoch.INITIAL
and not self._crypto_retransmitted
):
self._loss.reschedule_data(now=context.time)
self._crypto_retransmitted = True
def _handle_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a DATA_BLOCKED frame.
"""
limit = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_data_blocked_frame(limit=limit)
)
def _handle_datagram_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a DATAGRAM frame.
"""
start = buf.tell()
if frame_type == QuicFrameType.DATAGRAM_WITH_LENGTH:
length = buf.pull_uint_var()
else:
length = buf.capacity - start
data = buf.pull_bytes(length)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_datagram_frame(length=length)
)
# check frame is allowed
if (
self._configuration.max_datagram_frame_size is None
or buf.tell() - start >= self._configuration.max_datagram_frame_size
):
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Unexpected DATAGRAM frame",
)
self._events.append(events.DatagramFrameReceived(data=data))
def _handle_handshake_done_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a HANDSHAKE_DONE frame.
"""
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_handshake_done_frame()
)
if not self._is_client:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Clients must not send HANDSHAKE_DONE frames",
)
# for clients, the handshake is now confirmed
if not self._handshake_confirmed:
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
self._loss.peer_completed_address_validation = True
def _handle_max_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_DATA frame.
This adjusts the total amount of we can send to the peer.
"""
max_data = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_connection_limit_frame(
frame_type=frame_type, maximum=max_data
)
)
if max_data > self._remote_max_data:
self._logger.debug("Remote max_data raised to %d", max_data)
self._remote_max_data = max_data
def _handle_max_stream_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_STREAM_DATA frame.
This adjusts the amount of data we can send on a specific stream.
"""
stream_id = buf.pull_uint_var()
max_stream_data = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_max_stream_data_frame(
maximum=max_stream_data, stream_id=stream_id
)
)
# check stream direction
self._assert_stream_can_send(frame_type, stream_id)
stream = self._get_or_create_stream(frame_type, stream_id)
if max_stream_data > stream.max_stream_data_remote:
self._logger.debug(
"Stream %d remote max_stream_data raised to %d",
stream_id,
max_stream_data,
)
stream.max_stream_data_remote = max_stream_data
def _handle_max_streams_bidi_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_STREAMS_BIDI frame.
This raises number of bidirectional streams we can initiate to the peer.
"""
max_streams = buf.pull_uint_var()
if max_streams > STREAM_COUNT_MAX:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Maximum Streams cannot exceed 2^60",
)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_connection_limit_frame(
frame_type=frame_type, maximum=max_streams
)
)
if max_streams > self._remote_max_streams_bidi:
self._logger.debug("Remote max_streams_bidi raised to %d", max_streams)
self._remote_max_streams_bidi = max_streams
self._unblock_streams(is_unidirectional=False)
def _handle_max_streams_uni_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_STREAMS_UNI frame.
This raises number of unidirectional streams we can initiate to the peer.
"""
max_streams = buf.pull_uint_var()
if max_streams > STREAM_COUNT_MAX:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Maximum Streams cannot exceed 2^60",
)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_connection_limit_frame(
frame_type=frame_type, maximum=max_streams
)
)
if max_streams > self._remote_max_streams_uni:
self._logger.debug("Remote max_streams_uni raised to %d", max_streams)
self._remote_max_streams_uni = max_streams
self._unblock_streams(is_unidirectional=True)
def _handle_new_connection_id_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a NEW_CONNECTION_ID frame.
"""
sequence_number = buf.pull_uint_var()
retire_prior_to = buf.pull_uint_var()
length = buf.pull_uint8()
connection_id = buf.pull_bytes(length)
stateless_reset_token = buf.pull_bytes(STATELESS_RESET_TOKEN_SIZE)
if not connection_id or len(connection_id) > CONNECTION_ID_MAX_SIZE:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Length must be greater than 0 and less than 20",
)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_new_connection_id_frame(
connection_id=connection_id,
retire_prior_to=retire_prior_to,
sequence_number=sequence_number,
stateless_reset_token=stateless_reset_token,
)
)
# sanity check
if retire_prior_to > sequence_number:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Retire Prior To is greater than Sequence Number",
)
# only accept retire_prior_to if it is bigger than the one we know
self._peer_retire_prior_to = max(retire_prior_to, self._peer_retire_prior_to)
# determine which CIDs to retire
change_cid = False
retire = [
cid
for cid in self._peer_cid_available
if cid.sequence_number < self._peer_retire_prior_to
]
if self._peer_cid.sequence_number < self._peer_retire_prior_to:
change_cid = True
retire.insert(0, self._peer_cid)
# update available CIDs
self._peer_cid_available = [
cid
for cid in self._peer_cid_available
if cid.sequence_number >= self._peer_retire_prior_to
]
if (
sequence_number >= self._peer_retire_prior_to
and sequence_number not in self._peer_cid_sequence_numbers
):
self._peer_cid_available.append(
QuicConnectionId(
cid=connection_id,
sequence_number=sequence_number,
stateless_reset_token=stateless_reset_token,
)
)
self._peer_cid_sequence_numbers.add(sequence_number)
# retire previous CIDs
for quic_connection_id in retire:
self._retire_peer_cid(quic_connection_id)
# assign new CID if we retired the active one
if change_cid:
self._consume_peer_cid()
# check number of active connection IDs, including the selected one
if 1 + len(self._peer_cid_available) > self._local_active_connection_id_limit:
raise QuicConnectionError(
error_code=QuicErrorCode.CONNECTION_ID_LIMIT_ERROR,
frame_type=frame_type,
reason_phrase="Too many active connection IDs",
)
# Check the number of retired connection IDs pending, though with a safer limit
# than the 2x recommended in section 5.1.2 of the RFC. Note that we are doing
# the check here and not in _retire_peer_cid() because we know the frame type to
# use here, and because it is the new connection id path that is potentially
# dangerous. We may transiently go a bit over the limit due to unacked frames
# getting added back to the list, but that's ok as it is bounded.
if len(self._retire_connection_ids) > min(
self._local_active_connection_id_limit * 4, MAX_PENDING_RETIRES
):
raise QuicConnectionError(
error_code=QuicErrorCode.CONNECTION_ID_LIMIT_ERROR,
frame_type=frame_type,
reason_phrase="Too many pending retired connection IDs",
)
def _handle_new_token_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a NEW_TOKEN frame.
"""
length = buf.pull_uint_var()
token = buf.pull_bytes(length)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_new_token_frame(token=token)
)
if not self._is_client:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Clients must not send NEW_TOKEN frames",
)
if self._token_handler is not None:
self._token_handler(token)
def _handle_padding_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a PADDING frame.
"""
# consume padding
pos = buf.tell()
for byte in buf.data_slice(pos, buf.capacity):
if byte:
break
pos += 1
buf.seek(pos)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(self._quic_logger.encode_padding_frame())
def _handle_path_challenge_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a PATH_CHALLENGE frame.
"""
data = buf.pull_bytes(8)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_path_challenge_frame(data=data)
)
context.network_path.remote_challenges.append(data)
def _handle_path_response_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a PATH_RESPONSE frame.
"""
data = buf.pull_bytes(8)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_path_response_frame(data=data)
)
try:
network_path = self._local_challenges.pop(data)
except KeyError:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Response does not match challenge",
)
self._logger.debug("Network path %s validated by challenge", network_path.addr)
network_path.is_validated = True
def _handle_ping_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a PING frame.
"""
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
def _handle_reset_stream_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a RESET_STREAM frame.
"""
stream_id = buf.pull_uint_var()
error_code = buf.pull_uint_var()
final_size = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_reset_stream_frame(
error_code=error_code, final_size=final_size, stream_id=stream_id
)
)
# check stream direction
self._assert_stream_can_receive(frame_type, stream_id)
# check flow-control limits
stream = self._get_or_create_stream(frame_type, stream_id)
if final_size > stream.max_stream_data_local:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over stream data limit",
)
newly_received = max(0, final_size - stream.receiver.highest_offset)
if self._local_max_data.used + newly_received > self._local_max_data.value:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over connection data limit",
)
# process reset
self._logger.info(
"Stream %d reset by peer (error code %d, final size %d)",
stream_id,
error_code,
final_size,
)
try:
event = stream.receiver.handle_reset(
error_code=error_code, final_size=final_size
)
except FinalSizeError as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.FINAL_SIZE_ERROR,
frame_type=frame_type,
reason_phrase=str(exc),
)
if event is not None:
self._events.append(event)
self._local_max_data.used += newly_received
def _handle_retire_connection_id_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a RETIRE_CONNECTION_ID frame.
"""
sequence_number = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_retire_connection_id_frame(sequence_number)
)
if sequence_number >= self._host_cid_seq:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Cannot retire unknown connection ID",
)
# find the connection ID by sequence number
for index, connection_id in enumerate(self._host_cids):
if connection_id.sequence_number == sequence_number:
if connection_id.cid == context.host_cid:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Cannot retire current connection ID",
)
self._logger.debug(
"Peer retiring CID %s (%d)",
dump_cid(connection_id.cid),
connection_id.sequence_number,
)
del self._host_cids[index]
self._events.append(
events.ConnectionIdRetired(connection_id=connection_id.cid)
)
break
# issue a new connection ID
self._replenish_connection_ids()
def _handle_stop_sending_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a STOP_SENDING frame.
"""
stream_id = buf.pull_uint_var()
error_code = buf.pull_uint_var() # application error code
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_stop_sending_frame(
error_code=error_code, stream_id=stream_id
)
)
# check stream direction
self._assert_stream_can_send(frame_type, stream_id)
# reset the stream
stream = self._get_or_create_stream(frame_type, stream_id)
stream.sender.reset(error_code=QuicErrorCode.NO_ERROR)
self._events.append(
events.StopSendingReceived(error_code=error_code, stream_id=stream_id)
)
def _handle_stream_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a STREAM frame.
"""
stream_id = buf.pull_uint_var()
if frame_type & 4:
offset = buf.pull_uint_var()
else:
offset = 0
if frame_type & 2:
length = buf.pull_uint_var()
else:
length = buf.capacity - buf.tell()
if offset + length > UINT_VAR_MAX:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="offset + length cannot exceed 2^62 - 1",
)
frame = QuicStreamFrame(
offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1)
)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_stream_frame(frame, stream_id=stream_id)
)
# check stream direction
self._assert_stream_can_receive(frame_type, stream_id)
# check flow-control limits
stream = self._get_or_create_stream(frame_type, stream_id)
if offset + length > stream.max_stream_data_local:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over stream data limit",
)
newly_received = max(0, offset + length - stream.receiver.highest_offset)
if self._local_max_data.used + newly_received > self._local_max_data.value:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over connection data limit",
)
# process data
try:
event = stream.receiver.handle_frame(frame)
except FinalSizeError as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.FINAL_SIZE_ERROR,
frame_type=frame_type,
reason_phrase=str(exc),
)
if event is not None:
self._events.append(event)
self._local_max_data.used += newly_received
def _handle_stream_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a STREAM_DATA_BLOCKED frame.
"""
stream_id = buf.pull_uint_var()
limit = buf.pull_uint_var()
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_stream_data_blocked_frame(
limit=limit, stream_id=stream_id
)
)
# check stream direction
self._assert_stream_can_receive(frame_type, stream_id)
self._get_or_create_stream(frame_type, stream_id)
def _handle_streams_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a STREAMS_BLOCKED frame.
"""
limit = buf.pull_uint_var()
if limit > STREAM_COUNT_MAX:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Maximum Streams cannot exceed 2^60",
)
# log frame
if self._quic_logger is not None:
context.quic_logger_frames.append(
self._quic_logger.encode_streams_blocked_frame(
is_unidirectional=frame_type == QuicFrameType.STREAMS_BLOCKED_UNI,
limit=limit,
)
)
def _log_key_retired(self, key_type: str, trigger: str) -> None:
"""
Log a key retirement.
"""
if self._quic_logger is not None:
self._quic_logger.log_event(
category="security",
event="key_retired",
data={"key_type": key_type, "trigger": trigger},
)
def _log_key_updated(self, key_type: str, trigger: str) -> None:
"""
Log a key update.
"""
if self._quic_logger is not None:
self._quic_logger.log_event(
category="security",
event="key_updated",
data={"key_type": key_type, "trigger": trigger},
)
def _on_ack_delivery(
self, delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int
) -> None:
"""
Callback when an ACK frame is acknowledged or lost.
"""
if delivery == QuicDeliveryState.ACKED:
space.ack_queue.subtract(0, highest_acked + 1)
def _on_connection_limit_delivery(
self, delivery: QuicDeliveryState, limit: Limit
) -> None:
"""
Callback when a MAX_DATA or MAX_STREAMS frame is acknowledged or lost.
"""
if delivery != QuicDeliveryState.ACKED:
limit.sent = 0
def _on_handshake_done_delivery(self, delivery: QuicDeliveryState) -> None:
"""
Callback when a HANDSHAKE_DONE frame is acknowledged or lost.
"""
if delivery != QuicDeliveryState.ACKED:
self._handshake_done_pending = True
def _on_max_stream_data_delivery(
self, delivery: QuicDeliveryState, stream: QuicStream
) -> None:
"""
Callback when a MAX_STREAM_DATA frame is acknowledged or lost.
"""
if delivery != QuicDeliveryState.ACKED:
stream.max_stream_data_local_sent = 0
def _on_new_connection_id_delivery(
self, delivery: QuicDeliveryState, connection_id: QuicConnectionId
) -> None:
"""
Callback when a NEW_CONNECTION_ID frame is acknowledged or lost.
"""
if delivery != QuicDeliveryState.ACKED:
connection_id.was_sent = False
def _on_ping_delivery(
self, delivery: QuicDeliveryState, uids: Sequence[int]
) -> None:
"""
Callback when a PING frame is acknowledged or lost.
"""
if delivery == QuicDeliveryState.ACKED:
self._logger.debug("Received PING%s response", "" if uids else " (probe)")
for uid in uids:
self._events.append(events.PingAcknowledged(uid=uid))
else:
self._ping_pending.extend(uids)
def _on_retire_connection_id_delivery(
self, delivery: QuicDeliveryState, sequence_number: int
) -> None:
"""
Callback when a RETIRE_CONNECTION_ID frame is acknowledged or lost.
"""
if delivery != QuicDeliveryState.ACKED:
self._retire_connection_ids.append(sequence_number)
def _payload_received(
self,
context: QuicReceiveContext,
plain: bytes,
crypto_frame_required: bool = False,
) -> Tuple[bool, bool]:
"""
Handle a QUIC packet payload.
"""
buf = Buffer(data=plain)
crypto_frame_found = False
frame_found = False
is_ack_eliciting = False
is_probing = None
while not buf.eof():
# get frame type
try:
frame_type = buf.pull_uint_var()
except BufferReadError:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=None,
reason_phrase="Malformed frame type",
)
# check frame type is known
try:
frame_handler, frame_epochs = self.__frame_handlers[frame_type]
except KeyError:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Unknown frame type",
)
# check frame type is allowed for the epoch
if context.epoch not in frame_epochs:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=frame_type,
reason_phrase="Unexpected frame type",
)
# handle the frame
try:
frame_handler(context, frame_type, buf)
except BufferReadError:
raise QuicConnectionError(
error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
frame_type=frame_type,
reason_phrase="Failed to parse frame",
)
except StreamFinishedError:
# we lack the state for the stream, ignore the frame
pass
# update ACK only / probing flags
frame_found = True
if frame_type == QuicFrameType.CRYPTO:
crypto_frame_found = True
if frame_type not in NON_ACK_ELICITING_FRAME_TYPES:
is_ack_eliciting = True
if frame_type not in PROBING_FRAME_TYPES:
is_probing = False
elif is_probing is None:
is_probing = True
if not frame_found:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=QuicFrameType.PADDING,
reason_phrase="Packet contains no frames",
)
# RFC 9000 - 17.2.2. Initial Packet
# The first packet sent by a client always includes a CRYPTO frame.
if crypto_frame_required and not crypto_frame_found:
raise QuicConnectionError(
error_code=QuicErrorCode.PROTOCOL_VIOLATION,
frame_type=QuicFrameType.PADDING,
reason_phrase="Packet contains no CRYPTO frame",
)
return is_ack_eliciting, bool(is_probing)
def _receive_retry_packet(
self, header: QuicHeader, packet_without_tag: bytes, now: float
) -> None:
"""
Handle a retry packet.
"""
if (
self._is_client
and not self._retry_count
and header.destination_cid == self.host_cid
and header.integrity_tag
== get_retry_integrity_tag(
packet_without_tag,
self._peer_cid.cid,
version=header.version,
)
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_received",
data={
"frames": [],
"header": {
"packet_type": "retry",
"scid": dump_cid(header.source_cid),
"dcid": dump_cid(header.destination_cid),
},
"raw": {"length": header.packet_length},
},
)
self._peer_cid.cid = header.source_cid
self._peer_token = header.token
self._retry_count += 1
self._retry_source_connection_id = header.source_cid
self._logger.info("Retrying with token (%d bytes)" % len(header.token))
self._connect(now=now)
else:
# Unexpected or invalid retry packet.
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "unexpected_packet",
"raw": {"length": header.packet_length},
},
)
def _receive_version_negotiation_packet(
self, header: QuicHeader, now: float
) -> None:
"""
Handle a version negotiation packet.
This is used in "Incompatible Version Negotiation", see:
https://datatracker.ietf.org/doc/html/rfc9368#section-2.2
"""
# Only clients process Version Negotiation, and once a Version
# Negotiation packet has been acted upon, any further
# such packets must be ignored.
#
# https://datatracker.ietf.org/doc/html/rfc9368#section-4
if (
self._is_client
and self._state == QuicConnectionState.FIRSTFLIGHT
and not self._version_negotiated_incompatible
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_received",
data={
"frames": [],
"header": {
"packet_type": self._quic_logger.packet_type(
header.packet_type
),
"scid": dump_cid(header.source_cid),
"dcid": dump_cid(header.destination_cid),
},
"raw": {"length": header.packet_length},
},
)
# Ignore any Version Negotiation packets that contain the
# original version.
#
# https://datatracker.ietf.org/doc/html/rfc9368#section-4
if self._version in header.supported_versions:
self._logger.warning(
"Version negotiation packet contains protocol version %s",
pretty_protocol_version(self._version),
)
return
# Look for a common protocol version.
common = [
x
for x in self._configuration.supported_versions
if x in header.supported_versions
]
# Look for a common protocol version.
chosen_version = common[0] if common else None
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="version_information",
data={
"server_versions": header.supported_versions,
"client_versions": self._configuration.supported_versions,
"chosen_version": chosen_version,
},
)
if chosen_version is None:
self._logger.error("Could not find a common protocol version")
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=QuicFrameType.PADDING,
reason_phrase="Could not find a common protocol version",
)
self._close_end()
return
self._packet_number = 0
self._version = chosen_version
self._version_negotiated_incompatible = True
self._logger.info(
"Retrying with protocol version %s",
pretty_protocol_version(self._version),
)
self._connect(now=now)
else:
# Unexpected version negotiation packet.
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "unexpected_packet",
"raw": {"length": header.packet_length},
},
)
def _replenish_connection_ids(self) -> None:
"""
Generate new connection IDs.
"""
while len(self._host_cids) < min(8, self._remote_active_connection_id_limit):
self._host_cids.append(
QuicConnectionId(
cid=os.urandom(self._configuration.connection_id_length),
sequence_number=self._host_cid_seq,
stateless_reset_token=os.urandom(16),
)
)
self._host_cid_seq += 1
def _retire_peer_cid(self, connection_id: QuicConnectionId) -> None:
"""
Retire a destination connection ID.
"""
self._logger.debug(
"Retiring CID %s (%d) [%d]",
dump_cid(connection_id.cid),
connection_id.sequence_number,
len(self._retire_connection_ids) + 1,
)
self._retire_connection_ids.append(connection_id.sequence_number)
def _push_crypto_data(self) -> None:
for epoch, buf in self._crypto_buffers.items():
self._crypto_streams[epoch].sender.write(buf.data)
buf.seek(0)
def _send_probe(self) -> None:
self._probe_pending = True
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
"""
Parse and apply remote transport parameters.
`from_session_ticket` is `True` when restoring saved transport parameters,
and `False` when handling received transport parameters.
"""
try:
quic_transport_parameters = pull_quic_transport_parameters(
Buffer(data=data)
)
except ValueError:
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="Could not parse QUIC transport parameters",
)
# log event
if self._quic_logger is not None and not from_session_ticket:
self._quic_logger.log_event(
category="transport",
event="parameters_set",
data=self._quic_logger.encode_transport_parameters(
owner="remote", parameters=quic_transport_parameters
),
)
# Validate remote parameters.
if not self._is_client:
for attr in [
"original_destination_connection_id",
"preferred_address",
"retry_source_connection_id",
"stateless_reset_token",
]:
if getattr(quic_transport_parameters, attr) is not None:
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="%s is not allowed for clients" % attr,
)
if not from_session_ticket:
if (
quic_transport_parameters.initial_source_connection_id
!= self._remote_initial_source_connection_id
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="initial_source_connection_id does not match",
)
if self._is_client and (
quic_transport_parameters.original_destination_connection_id
!= self._original_destination_connection_id
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="original_destination_connection_id does not match",
)
if self._is_client and (
quic_transport_parameters.retry_source_connection_id
!= self._retry_source_connection_id
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="retry_source_connection_id does not match",
)
if (
quic_transport_parameters.active_connection_id_limit is not None
and quic_transport_parameters.active_connection_id_limit < 2
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="active_connection_id_limit must be no less than 2",
)
if (
quic_transport_parameters.ack_delay_exponent is not None
and quic_transport_parameters.ack_delay_exponent > 20
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="ack_delay_exponent must be <= 20",
)
if (
quic_transport_parameters.max_ack_delay is not None
and quic_transport_parameters.max_ack_delay >= 2**14
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="max_ack_delay must be < 2^14",
)
if quic_transport_parameters.max_udp_payload_size is not None and (
quic_transport_parameters.max_udp_payload_size
< SMALLEST_MAX_DATAGRAM_SIZE
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase=(
f"max_udp_payload_size must be >= {SMALLEST_MAX_DATAGRAM_SIZE}"
),
)
# Validate Version Information extension.
#
# https://datatracker.ietf.org/doc/html/rfc9368#section-4
if quic_transport_parameters.version_information is not None:
version_information = quic_transport_parameters.version_information
# If a server receives Version Information where the Chosen Version
# is not included in Available Versions, it MUST treat is as a
# parsing failure.
if (
not self._is_client
and version_information.chosen_version
not in version_information.available_versions
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase=(
"version_information's chosen_version is not included "
"in available_versions"
),
)
# Validate that the Chosen Version matches the version in use for the
# connection.
if version_information.chosen_version != self._crypto_packet_version:
raise QuicConnectionError(
error_code=QuicErrorCode.VERSION_NEGOTIATION_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase=(
"version_information's chosen_version does not match "
"the version in use"
),
)
# Store remote parameters.
if not from_session_ticket:
if quic_transport_parameters.ack_delay_exponent is not None:
self._remote_ack_delay_exponent = self._remote_ack_delay_exponent
if quic_transport_parameters.max_ack_delay is not None:
self._loss.max_ack_delay = (
quic_transport_parameters.max_ack_delay / 1000.0
)
if (
self._is_client
and self._peer_cid.sequence_number == 0
and quic_transport_parameters.stateless_reset_token is not None
):
self._peer_cid.stateless_reset_token = (
quic_transport_parameters.stateless_reset_token
)
self._remote_version_information = (
quic_transport_parameters.version_information
)
if quic_transport_parameters.active_connection_id_limit is not None:
self._remote_active_connection_id_limit = (
quic_transport_parameters.active_connection_id_limit
)
if quic_transport_parameters.max_idle_timeout is not None:
self._remote_max_idle_timeout = (
quic_transport_parameters.max_idle_timeout / 1000.0
)
self._remote_max_datagram_frame_size = (
quic_transport_parameters.max_datagram_frame_size
)
for param in [
"max_data",
"max_stream_data_bidi_local",
"max_stream_data_bidi_remote",
"max_stream_data_uni",
"max_streams_bidi",
"max_streams_uni",
]:
value = getattr(quic_transport_parameters, "initial_" + param)
if value is not None:
setattr(self, "_remote_" + param, value)
def _serialize_transport_parameters(self) -> bytes:
quic_transport_parameters = QuicTransportParameters(
ack_delay_exponent=self._local_ack_delay_exponent,
active_connection_id_limit=self._local_active_connection_id_limit,
max_idle_timeout=int(self._configuration.idle_timeout * 1000),
initial_max_data=self._local_max_data.value,
initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,
initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,
initial_max_stream_data_uni=self._local_max_stream_data_uni,
initial_max_streams_bidi=self._local_max_streams_bidi.value,
initial_max_streams_uni=self._local_max_streams_uni.value,
initial_source_connection_id=self._local_initial_source_connection_id,
max_ack_delay=25,
max_datagram_frame_size=self._configuration.max_datagram_frame_size,
quantum_readiness=(
b"Q" * SMALLEST_MAX_DATAGRAM_SIZE
if self._configuration.quantum_readiness_test
else None
),
stateless_reset_token=self._host_cids[0].stateless_reset_token,
version_information=QuicVersionInformation(
chosen_version=self._version,
available_versions=self._configuration.supported_versions,
),
)
if not self._is_client:
quic_transport_parameters.original_destination_connection_id = (
self._original_destination_connection_id
)
quic_transport_parameters.retry_source_connection_id = (
self._retry_source_connection_id
)
# log event
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="parameters_set",
data=self._quic_logger.encode_transport_parameters(
owner="local", parameters=quic_transport_parameters
),
)
buf = Buffer(capacity=3 * self._max_datagram_size)
push_quic_transport_parameters(buf, quic_transport_parameters)
return buf.data
def _set_state(self, state: QuicConnectionState) -> None:
self._logger.debug("%s -> %s", self._state, state)
self._state = state
def _stream_can_receive(self, stream_id: int) -> bool:
return stream_is_client_initiated(
stream_id
) != self._is_client or not stream_is_unidirectional(stream_id)
def _stream_can_send(self, stream_id: int) -> bool:
return stream_is_client_initiated(
stream_id
) == self._is_client or not stream_is_unidirectional(stream_id)
def _unblock_streams(self, is_unidirectional: bool) -> None:
if is_unidirectional:
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
streams_blocked = self._streams_blocked_uni
else:
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
streams_blocked = self._streams_blocked_bidi
while streams_blocked and streams_blocked[0].stream_id // 4 < max_streams:
stream = streams_blocked.pop(0)
stream.is_blocked = False
stream.max_stream_data_remote = max_stream_data_remote
if not self._streams_blocked_bidi and not self._streams_blocked_uni:
self._streams_blocked_pending = False
def _update_traffic_key(
self,
direction: tls.Direction,
epoch: tls.Epoch,
cipher_suite: tls.CipherSuite,
secret: bytes,
) -> None:
"""
Callback which is invoked by the TLS engine when new traffic keys are
available.
"""
# For clients, determine the negotiated protocol version.
if (
self._is_client
and self._crypto_packet_version is not None
and not self._version_negotiated_compatible
):
self._version = self._crypto_packet_version
self._version_negotiated_compatible = True
self._logger.info(
"Negotiated protocol version %s", pretty_protocol_version(self._version)
)
secrets_log_file = self._configuration.secrets_log_file
if secrets_log_file is not None:
label_row = self._is_client == (direction == tls.Direction.DECRYPT)
label = SECRETS_LABELS[label_row][epoch.value]
secrets_log_file.write(
"%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex())
)
secrets_log_file.flush()
crypto = self._cryptos[epoch]
if direction == tls.Direction.ENCRYPT:
crypto.send.setup(
cipher_suite=cipher_suite, secret=secret, version=self._version
)
else:
crypto.recv.setup(
cipher_suite=cipher_suite, secret=secret, version=self._version
)
def _add_local_challenge(self, challenge: bytes, network_path: QuicNetworkPath):
self._local_challenges[challenge] = network_path
while len(self._local_challenges) > MAX_LOCAL_CHALLENGES:
# Dictionaries are ordered, so pop the first key until we are below the
# limit.
key = next(iter(self._local_challenges.keys()))
del self._local_challenges[key]
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
crypto_stream: Optional[QuicStream] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
packet_type = QuicPacketType.ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = QuicPacketType.ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
while True:
# apply pacing, except if we have ACKs to send
if space.ack_at is None or space.ack_at >= now:
self._pacing_at = self._loss._pacer.next_send_time(now=now)
if self._pacing_at is not None:
break
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
if space.ack_at is not None and space.ack_at <= now:
self._write_ack_frame(builder=builder, space=space, now=now)
# HANDSHAKE_DONE
if self._handshake_done_pending:
self._write_handshake_done_frame(builder=builder)
self._handshake_done_pending = False
# PATH CHALLENGE
if not (network_path.is_validated or network_path.local_challenge_sent):
challenge = os.urandom(8)
self._add_local_challenge(
challenge=challenge, network_path=network_path
)
self._write_path_challenge_frame(
builder=builder, challenge=challenge
)
network_path.local_challenge_sent = True
# PATH RESPONSE
while len(network_path.remote_challenges) > 0:
challenge = network_path.remote_challenges.popleft()
self._write_path_response_frame(
builder=builder, challenge=challenge
)
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
self._write_new_connection_id_frame(
builder=builder, connection_id=connection_id
)
# RETIRE_CONNECTION_ID
for sequence_number in self._retire_connection_ids[:]:
self._write_retire_connection_id_frame(
builder=builder, sequence_number=sequence_number
)
self._retire_connection_ids.pop(0)
# STREAMS_BLOCKED
if self._streams_blocked_pending:
if self._streams_blocked_bidi:
self._write_streams_blocked_frame(
builder=builder,
frame_type=QuicFrameType.STREAMS_BLOCKED_BIDI,
limit=self._remote_max_streams_bidi,
)
if self._streams_blocked_uni:
self._write_streams_blocked_frame(
builder=builder,
frame_type=QuicFrameType.STREAMS_BLOCKED_UNI,
limit=self._remote_max_streams_uni,
)
self._streams_blocked_pending = False
# MAX_DATA and MAX_STREAMS
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._ping_pending:
self._write_ping_frame(builder, self._ping_pending)
self._ping_pending.clear()
# PING (probe)
if self._probe_pending:
self._write_ping_frame(builder, comment="probe")
self._probe_pending = False
# CRYPTO
if crypto_stream is not None and not crypto_stream.sender.buffer_is_empty:
self._write_crypto_frame(
builder=builder, space=space, stream=crypto_stream
)
# DATAGRAM
while self._datagrams_pending:
try:
self._write_datagram_frame(
builder=builder,
data=self._datagrams_pending[0],
frame_type=QuicFrameType.DATAGRAM_WITH_LENGTH,
)
self._datagrams_pending.popleft()
except QuicPacketBuilderStop:
break
sent: Set[QuicStream] = set()
discarded: Set[QuicStream] = set()
try:
for stream in self._streams_queue:
# if the stream is finished, discard it
if stream.is_finished:
self._logger.debug("Stream %d discarded", stream.stream_id)
self._streams.pop(stream.stream_id)
self._streams_finished.add(stream.stream_id)
discarded.add(stream)
continue
if stream.receiver.stop_pending:
# STOP_SENDING
self._write_stop_sending_frame(builder=builder, stream=stream)
if stream.sender.reset_pending:
# RESET_STREAM
self._write_reset_stream_frame(builder=builder, stream=stream)
elif not stream.is_blocked and not stream.sender.buffer_is_empty:
# STREAM
used = self._write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream.sender.highest_offset
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
self._remote_max_data_used += used
if used > 0:
sent.add(stream)
finally:
# Make a new stream service order, putting served ones at the end.
#
# This method of updating the streams queue ensures that discarded
# streams are removed and ones which sent are moved to the end even
# if an exception occurs in the loop.
self._streams_queue = [
stream
for stream in self._streams_queue
if not (stream in discarded or stream in sent)
]
self._streams_queue.extend(sent)
if builder.packet_is_empty:
break
else:
self._loss._pacer.update_after_send(now=now)
def _write_handshake(
self, builder: QuicPacketBuilder, epoch: tls.Epoch, now: float
) -> None:
crypto = self._cryptos[epoch]
if not crypto.send.is_valid():
return
crypto_stream = self._crypto_streams[epoch]
space = self._spaces[epoch]
while True:
if epoch == tls.Epoch.INITIAL:
packet_type = QuicPacketType.INITIAL
else:
packet_type = QuicPacketType.HANDSHAKE
builder.start_packet(packet_type, crypto)
# ACK
if space.ack_at is not None:
self._write_ack_frame(builder=builder, space=space, now=now)
# CRYPTO
if not crypto_stream.sender.buffer_is_empty:
if self._write_crypto_frame(
builder=builder, space=space, stream=crypto_stream
):
self._probe_pending = False
# PING (probe)
if (
self._probe_pending
and not self._handshake_complete
and (
epoch == tls.Epoch.HANDSHAKE
or not self._cryptos[tls.Epoch.HANDSHAKE].send.is_valid()
)
):
self._write_ping_frame(builder, comment="probe")
self._probe_pending = False
if builder.packet_is_empty:
break
def _write_ack_frame(
self, builder: QuicPacketBuilder, space: QuicPacketSpace, now: float
) -> None:
# calculate ACK delay
ack_delay = now - space.largest_received_time
ack_delay_encoded = int(ack_delay * 1000000) >> self._local_ack_delay_exponent
buf = builder.start_frame(
QuicFrameType.ACK,
capacity=ACK_FRAME_CAPACITY,
handler=self._on_ack_delivery,
handler_args=(space, space.largest_received_packet),
)
ranges = push_ack_frame(buf, space.ack_queue, ack_delay_encoded)
space.ack_at = None
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_ack_frame(
ranges=space.ack_queue, delay=ack_delay
)
)
# check if we need to trigger an ACK-of-ACK
if ranges > 1 and builder.packet_number % 8 == 0:
self._write_ping_frame(builder, comment="ACK-of-ACK trigger")
def _write_connection_close_frame(
self,
builder: QuicPacketBuilder,
epoch: tls.Epoch,
error_code: int,
frame_type: Optional[int],
reason_phrase: str,
) -> None:
# convert application-level close to transport-level close in early stages
if frame_type is None and epoch in (tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE):
error_code = QuicErrorCode.APPLICATION_ERROR
frame_type = QuicFrameType.PADDING
reason_phrase = ""
reason_bytes = reason_phrase.encode("utf8")
reason_length = len(reason_bytes)
if frame_type is None:
buf = builder.start_frame(
QuicFrameType.APPLICATION_CLOSE,
capacity=APPLICATION_CLOSE_FRAME_CAPACITY + reason_length,
)
buf.push_uint_var(error_code)
buf.push_uint_var(reason_length)
buf.push_bytes(reason_bytes)
else:
buf = builder.start_frame(
QuicFrameType.TRANSPORT_CLOSE,
capacity=TRANSPORT_CLOSE_FRAME_CAPACITY + reason_length,
)
buf.push_uint_var(error_code)
buf.push_uint_var(frame_type)
buf.push_uint_var(reason_length)
buf.push_bytes(reason_bytes)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_connection_close_frame(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
def _write_connection_limits(
self, builder: QuicPacketBuilder, space: QuicPacketSpace
) -> None:
"""
Raise MAX_DATA or MAX_STREAMS if needed.
"""
for limit in (
self._local_max_data,
self._local_max_streams_bidi,
self._local_max_streams_uni,
):
if limit.used * 2 > limit.value:
limit.value *= 2
self._logger.debug("Local %s raised to %d", limit.name, limit.value)
if limit.value != limit.sent:
buf = builder.start_frame(
limit.frame_type,
capacity=CONNECTION_LIMIT_FRAME_CAPACITY,
handler=self._on_connection_limit_delivery,
handler_args=(limit,),
)
buf.push_uint_var(limit.value)
limit.sent = limit.value
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_connection_limit_frame(
frame_type=limit.frame_type,
maximum=limit.value,
)
)
def _write_crypto_frame(
self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream
) -> bool:
frame_overhead = 3 + size_uint_var(stream.sender.next_offset)
frame = stream.sender.get_frame(builder.remaining_flight_space - frame_overhead)
if frame is not None:
buf = builder.start_frame(
QuicFrameType.CRYPTO,
capacity=frame_overhead,
handler=stream.sender.on_data_delivery,
handler_args=(frame.offset, frame.offset + len(frame.data), False),
)
buf.push_uint_var(frame.offset)
buf.push_uint16(len(frame.data) | 0x4000)
buf.push_bytes(frame.data)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_crypto_frame(frame)
)
return True
return False
def _write_datagram_frame(
self, builder: QuicPacketBuilder, data: bytes, frame_type: QuicFrameType
) -> bool:
"""
Write a DATAGRAM frame.
Returns True if the frame was processed, False otherwise.
"""
assert frame_type == QuicFrameType.DATAGRAM_WITH_LENGTH
length = len(data)
frame_size = 1 + size_uint_var(length) + length
buf = builder.start_frame(frame_type, capacity=frame_size)
buf.push_uint_var(length)
buf.push_bytes(data)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_datagram_frame(length=length)
)
return True
def _write_handshake_done_frame(self, builder: QuicPacketBuilder) -> None:
builder.start_frame(
QuicFrameType.HANDSHAKE_DONE,
capacity=HANDSHAKE_DONE_FRAME_CAPACITY,
handler=self._on_handshake_done_delivery,
)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_handshake_done_frame()
)
def _write_new_connection_id_frame(
self, builder: QuicPacketBuilder, connection_id: QuicConnectionId
) -> None:
retire_prior_to = 0 # FIXME
buf = builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
capacity=NEW_CONNECTION_ID_FRAME_CAPACITY,
handler=self._on_new_connection_id_delivery,
handler_args=(connection_id,),
)
buf.push_uint_var(connection_id.sequence_number)
buf.push_uint_var(retire_prior_to)
buf.push_uint8(len(connection_id.cid))
buf.push_bytes(connection_id.cid)
buf.push_bytes(connection_id.stateless_reset_token)
connection_id.was_sent = True
self._events.append(events.ConnectionIdIssued(connection_id=connection_id.cid))
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_new_connection_id_frame(
connection_id=connection_id.cid,
retire_prior_to=retire_prior_to,
sequence_number=connection_id.sequence_number,
stateless_reset_token=connection_id.stateless_reset_token,
)
)
def _write_path_challenge_frame(
self, builder: QuicPacketBuilder, challenge: bytes
) -> None:
buf = builder.start_frame(
QuicFrameType.PATH_CHALLENGE, capacity=PATH_CHALLENGE_FRAME_CAPACITY
)
buf.push_bytes(challenge)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_path_challenge_frame(data=challenge)
)
def _write_path_response_frame(
self, builder: QuicPacketBuilder, challenge: bytes
) -> None:
buf = builder.start_frame(
QuicFrameType.PATH_RESPONSE, capacity=PATH_RESPONSE_FRAME_CAPACITY
)
buf.push_bytes(challenge)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_path_response_frame(data=challenge)
)
def _write_ping_frame(
self, builder: QuicPacketBuilder, uids: List[int] = [], comment=""
):
builder.start_frame(
QuicFrameType.PING,
capacity=PING_FRAME_CAPACITY,
handler=self._on_ping_delivery,
handler_args=(tuple(uids),),
)
self._logger.debug(
"Sending PING%s in packet %d",
" (%s)" % comment if comment else "",
builder.packet_number,
)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
def _write_reset_stream_frame(
self,
builder: QuicPacketBuilder,
stream: QuicStream,
) -> None:
buf = builder.start_frame(
frame_type=QuicFrameType.RESET_STREAM,
capacity=RESET_STREAM_FRAME_CAPACITY,
handler=stream.sender.on_reset_delivery,
)
frame = stream.sender.get_reset_frame()
buf.push_uint_var(frame.stream_id)
buf.push_uint_var(frame.error_code)
buf.push_uint_var(frame.final_size)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_reset_stream_frame(
error_code=frame.error_code,
final_size=frame.final_size,
stream_id=frame.stream_id,
)
)
def _write_retire_connection_id_frame(
self, builder: QuicPacketBuilder, sequence_number: int
) -> None:
buf = builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
capacity=RETIRE_CONNECTION_ID_CAPACITY,
handler=self._on_retire_connection_id_delivery,
handler_args=(sequence_number,),
)
buf.push_uint_var(sequence_number)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_retire_connection_id_frame(sequence_number)
)
def _write_stop_sending_frame(
self,
builder: QuicPacketBuilder,
stream: QuicStream,
) -> None:
buf = builder.start_frame(
frame_type=QuicFrameType.STOP_SENDING,
capacity=STOP_SENDING_FRAME_CAPACITY,
handler=stream.receiver.on_stop_sending_delivery,
)
frame = stream.receiver.get_stop_frame()
buf.push_uint_var(frame.stream_id)
buf.push_uint_var(frame.error_code)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_stop_sending_frame(
error_code=frame.error_code, stream_id=frame.stream_id
)
)
def _write_stream_frame(
self,
builder: QuicPacketBuilder,
space: QuicPacketSpace,
stream: QuicStream,
max_offset: int,
) -> int:
# the frame data size is constrained by our peer's MAX_DATA and
# the space available in the current packet
frame_overhead = (
3
+ size_uint_var(stream.stream_id)
+ (
size_uint_var(stream.sender.next_offset)
if stream.sender.next_offset
else 0
)
)
previous_send_highest = stream.sender.highest_offset
frame = stream.sender.get_frame(
builder.remaining_flight_space - frame_overhead, max_offset
)
if frame is not None:
frame_type = QuicFrameType.STREAM_BASE | 2 # length
if frame.offset:
frame_type |= 4
if frame.fin:
frame_type |= 1
buf = builder.start_frame(
frame_type,
capacity=frame_overhead,
handler=stream.sender.on_data_delivery,
handler_args=(frame.offset, frame.offset + len(frame.data), frame.fin),
)
buf.push_uint_var(stream.stream_id)
if frame.offset:
buf.push_uint_var(frame.offset)
buf.push_uint16(len(frame.data) | 0x4000)
buf.push_bytes(frame.data)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_stream_frame(
frame, stream_id=stream.stream_id
)
)
return stream.sender.highest_offset - previous_send_highest
else:
return 0
def _write_stream_limits(
self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream
) -> None:
"""
Raise MAX_STREAM_DATA if needed.
The only case where `stream.max_stream_data_local` is zero is for
locally created unidirectional streams. We skip such streams to avoid
spurious logging.
"""
if (
stream.max_stream_data_local
and stream.receiver.highest_offset * 2 > stream.max_stream_data_local
):
stream.max_stream_data_local *= 2
self._logger.debug(
"Stream %d local max_stream_data raised to %d",
stream.stream_id,
stream.max_stream_data_local,
)
if stream.max_stream_data_local_sent != stream.max_stream_data_local:
buf = builder.start_frame(
QuicFrameType.MAX_STREAM_DATA,
capacity=MAX_STREAM_DATA_FRAME_CAPACITY,
handler=self._on_max_stream_data_delivery,
handler_args=(stream,),
)
buf.push_uint_var(stream.stream_id)
buf.push_uint_var(stream.max_stream_data_local)
stream.max_stream_data_local_sent = stream.max_stream_data_local
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_max_stream_data_frame(
maximum=stream.max_stream_data_local, stream_id=stream.stream_id
)
)
def _write_streams_blocked_frame(
self, builder: QuicPacketBuilder, frame_type: QuicFrameType, limit: int
) -> None:
buf = builder.start_frame(frame_type, capacity=STREAMS_BLOCKED_CAPACITY)
buf.push_uint_var(limit)
# log frame
if self._quic_logger is not None:
builder.quic_logger_frames.append(
self._quic_logger.encode_streams_blocked_frame(
is_unidirectional=frame_type == QuicFrameType.STREAMS_BLOCKED_UNI,
limit=limit,
)
)
|