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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// HttpLog.h should generally be included first
#include "HttpLog.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Preferences.h"
#include "nsHttp.h"
#include "nsHttpHandler.h"
#include "nsHttpConnection.h"
#include "nsILoadGroup.h"
#include "prprf.h"
#include "prnetdb.h"
#include "SpdyPush3.h"
#include "SpdySession3.h"
#include "SpdyStream3.h"
#include <algorithm>
#ifdef DEBUG
// defined by the socket transport service while active
extern PRThread *gSocketThread;
#endif
namespace mozilla {
namespace net {
// SpdySession3 has multiple inheritance of things that implement
// nsISupports, so this magic is taken from nsHttpPipeline that
// implements some of the same abstract classes.
NS_IMPL_THREADSAFE_ADDREF(SpdySession3)
NS_IMPL_THREADSAFE_RELEASE(SpdySession3)
NS_INTERFACE_MAP_BEGIN(SpdySession3)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsAHttpConnection)
NS_INTERFACE_MAP_END
SpdySession3::SpdySession3(nsAHttpTransaction *aHttpTransaction,
nsISocketTransport *aSocketTransport,
int32_t firstPriority)
: mSocketTransport(aSocketTransport),
mSegmentReader(nullptr),
mSegmentWriter(nullptr),
mNextStreamID(1),
mConcurrentHighWater(0),
mDownstreamState(BUFFERING_FRAME_HEADER),
mInputFrameBufferSize(kDefaultBufferSize),
mInputFrameBufferUsed(0),
mInputFrameDataLast(false),
mInputFrameDataStream(nullptr),
mNeedsCleanup(nullptr),
mShouldGoAway(false),
mClosed(false),
mCleanShutdown(false),
mDataPending(false),
mGoAwayID(0),
mMaxConcurrent(kDefaultMaxConcurrent),
mConcurrent(0),
mServerPushedResources(0),
mServerInitialWindow(kDefaultServerRwin),
mOutputQueueSize(kDefaultQueueSize),
mOutputQueueUsed(0),
mOutputQueueSent(0),
mLastReadEpoch(PR_IntervalNow()),
mPingSentEpoch(0),
mNextPingID(1)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
static uint64_t sSerial;
mSerial = ++sSerial;
LOG3(("SpdySession3::SpdySession3 %p transaction 1 = %p serial=0x%X\n",
this, aHttpTransaction, mSerial));
mStreamIDHash.Init();
mStreamTransactionHash.Init();
mConnection = aHttpTransaction->Connection();
mInputFrameBuffer = new char[mInputFrameBufferSize];
mOutputQueueBuffer = new char[mOutputQueueSize];
zlibInit();
mPushAllowance = gHttpHandler->SpdyPushAllowance();
mSendingChunkSize = gHttpHandler->SpdySendingChunkSize();
GenerateSettings();
if (!aHttpTransaction->IsNullTransaction())
AddStream(aHttpTransaction, firstPriority);
mLastDataReadEpoch = mLastReadEpoch;
mPingThreshold = gHttpHandler->SpdyPingThreshold();
}
PLDHashOperator
SpdySession3::ShutdownEnumerator(nsAHttpTransaction *key,
nsAutoPtr<SpdyStream3> &stream,
void *closure)
{
SpdySession3 *self = static_cast<SpdySession3 *>(closure);
// On a clean server hangup the server sets the GoAwayID to be the ID of
// the last transaction it processed. If the ID of stream in the
// local stream is greater than that it can safely be restarted because the
// server guarantees it was not partially processed. Streams that have not
// registered an ID haven't actually been sent yet so they can always be
// restarted.
if (self->mCleanShutdown &&
(stream->StreamID() > self->mGoAwayID || !stream->HasRegisteredID()))
self->CloseStream(stream, NS_ERROR_NET_RESET); // can be restarted
else
self->CloseStream(stream, NS_ERROR_ABORT);
return PL_DHASH_NEXT;
}
PLDHashOperator
SpdySession3::GoAwayEnumerator(nsAHttpTransaction *key,
nsAutoPtr<SpdyStream3> &stream,
void *closure)
{
SpdySession3 *self = static_cast<SpdySession3 *>(closure);
// these streams were not processed by the server and can be restarted.
// Do that after the enumerator completes to avoid the risk of
// a restart event re-entrantly modifying this hash. Be sure not to restart
// a pushed (even numbered) stream
if ((stream->StreamID() > self->mGoAwayID && (stream->StreamID() & 1)) ||
!stream->HasRegisteredID()) {
self->mGoAwayStreamsToRestart.Push(stream);
}
return PL_DHASH_NEXT;
}
SpdySession3::~SpdySession3()
{
LOG3(("SpdySession3::~SpdySession3 %p mDownstreamState=%X",
this, mDownstreamState));
inflateEnd(&mDownstreamZlib);
deflateEnd(&mUpstreamZlib);
mStreamTransactionHash.Enumerate(ShutdownEnumerator, this);
Telemetry::Accumulate(Telemetry::SPDY_PARALLEL_STREAMS, mConcurrentHighWater);
Telemetry::Accumulate(Telemetry::SPDY_REQUEST_PER_CONN, (mNextStreamID - 1) / 2);
Telemetry::Accumulate(Telemetry::SPDY_SERVER_INITIATED_STREAMS,
mServerPushedResources);
}
void
SpdySession3::LogIO(SpdySession3 *self, SpdyStream3 *stream, const char *label,
const char *data, uint32_t datalen)
{
if (!LOG4_ENABLED())
return;
LOG4(("SpdySession3::LogIO %p stream=%p id=0x%X [%s]",
self, stream, stream ? stream->StreamID() : 0, label));
// Max line is (16 * 3) + 10(prefix) + newline + null
char linebuf[128];
uint32_t index;
char *line = linebuf;
linebuf[127] = 0;
for (index = 0; index < datalen; ++index) {
if (!(index % 16)) {
if (index) {
*line = 0;
LOG4(("%s", linebuf));
}
line = linebuf;
PR_snprintf(line, 128, "%08X: ", index);
line += 10;
}
PR_snprintf(line, 128 - (line - linebuf), "%02X ",
((unsigned char *)data)[index]);
line += 3;
}
if (index) {
*line = 0;
LOG4(("%s", linebuf));
}
}
typedef nsresult (*Control_FX) (SpdySession3 *self);
static Control_FX sControlFunctions[] =
{
nullptr,
SpdySession3::HandleSynStream,
SpdySession3::HandleSynReply,
SpdySession3::HandleRstStream,
SpdySession3::HandleSettings,
SpdySession3::HandleNoop,
SpdySession3::HandlePing,
SpdySession3::HandleGoAway,
SpdySession3::HandleHeaders,
SpdySession3::HandleWindowUpdate,
SpdySession3::HandleCredential
};
bool
SpdySession3::RoomForMoreConcurrent()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
return (mConcurrent < mMaxConcurrent);
}
bool
SpdySession3::RoomForMoreStreams()
{
if (mNextStreamID + mStreamTransactionHash.Count() * 2 > kMaxStreamID)
return false;
return !mShouldGoAway;
}
PRIntervalTime
SpdySession3::IdleTime()
{
return PR_IntervalNow() - mLastDataReadEpoch;
}
void
SpdySession3::ReadTimeoutTick(PRIntervalTime now)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
MOZ_ASSERT(mNextPingID & 1, "Ping Counter Not Odd");
LOG(("SpdySession3::ReadTimeoutTick %p delta since last read %ds\n",
this, PR_IntervalToSeconds(now - mLastReadEpoch)));
if (!mPingThreshold)
return;
if ((now - mLastReadEpoch) < mPingThreshold) {
// recent activity means ping is not an issue
if (mPingSentEpoch)
mPingSentEpoch = 0;
return;
}
if (mPingSentEpoch) {
LOG(("SpdySession3::ReadTimeoutTick %p handle outstanding ping\n"));
if ((now - mPingSentEpoch) >= gHttpHandler->SpdyPingTimeout()) {
LOG(("SpdySession3::ReadTimeoutTick %p Ping Timer Exhaustion\n",
this));
mPingSentEpoch = 0;
Close(NS_ERROR_NET_TIMEOUT);
}
return;
}
LOG(("SpdySession3::ReadTimeoutTick %p generating ping 0x%X\n",
this, mNextPingID));
if (mNextPingID == 0xffffffff) {
LOG(("SpdySession3::ReadTimeoutTick %p cannot form ping - ids exhausted\n",
this));
return;
}
mPingSentEpoch = PR_IntervalNow();
if (!mPingSentEpoch)
mPingSentEpoch = 1; // avoid the 0 sentinel value
GeneratePing(mNextPingID);
mNextPingID += 2;
ResumeRecv(); // read the ping reply
// Check for orphaned push streams. This looks expensive, but generally the
// list is empty.
SpdyPushedStream3 *deleteMe;
TimeStamp timestampNow;
do {
deleteMe = nullptr;
for (uint32_t index = mPushedStreams.Length();
index > 0 ; --index) {
SpdyPushedStream3 *pushedStream = mPushedStreams[index - 1];
if (timestampNow.IsNull())
timestampNow = TimeStamp::Now(); // lazy initializer
// if spdy finished, but not connected, and its been like that for too long..
// cleanup the stream..
if (pushedStream->IsOrphaned(timestampNow))
{
LOG3(("SpdySession3 Timeout Pushed Stream %p 0x%X\n",
this, pushedStream->StreamID()));
deleteMe = pushedStream;
break; // don't CleanupStream() while iterating this vector
}
}
if (deleteMe)
CleanupStream(deleteMe, NS_ERROR_ABORT, RST_CANCEL);
} while (deleteMe);
if (mNextPingID == 0xffffffff) {
LOG(("SpdySession3::ReadTimeoutTick %p "
"ping ids exhausted marking goaway\n", this));
mShouldGoAway = true;
}
}
uint32_t
SpdySession3::RegisterStreamID(SpdyStream3 *stream, uint32_t aNewID)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
MOZ_ASSERT(mNextStreamID < 0xfffffff0,
"should have stopped admitting streams");
MOZ_ASSERT(!(aNewID & 1),
"0 for autoassign pull, otherwise explicit even push assignment");
if (!aNewID) {
// auto generate a new pull stream ID
aNewID = mNextStreamID;
MOZ_ASSERT(aNewID & 1, "pull ID must be odd.");
mNextStreamID += 2;
}
LOG3(("SpdySession3::RegisterStreamID session=%p stream=%p id=0x%X "
"concurrent=%d",this, stream, aNewID, mConcurrent));
// We've used up plenty of ID's on this session. Start
// moving to a new one before there is a crunch involving
// server push streams or concurrent non-registered submits
if (aNewID >= kMaxStreamID)
mShouldGoAway = true;
// integrity check
if (mStreamIDHash.Get(aNewID)) {
LOG3((" New ID already present\n"));
MOZ_ASSERT(false, "New ID already present in mStreamIDHash");
mShouldGoAway = true;
return kDeadStreamID;
}
mStreamIDHash.Put(aNewID, stream);
return aNewID;
}
bool
SpdySession3::AddStream(nsAHttpTransaction *aHttpTransaction,
int32_t aPriority)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
// integrity check
if (mStreamTransactionHash.Get(aHttpTransaction)) {
LOG3((" New transaction already present\n"));
MOZ_ASSERT(false, "AddStream duplicate transaction pointer");
return false;
}
aHttpTransaction->SetConnection(this);
SpdyStream3 *stream = new SpdyStream3(aHttpTransaction, this, aPriority);
LOG3(("SpdySession3::AddStream session=%p stream=%p NextID=0x%X (tentative)",
this, stream, mNextStreamID));
mStreamTransactionHash.Put(aHttpTransaction, stream);
if (RoomForMoreConcurrent()) {
LOG3(("SpdySession3::AddStream %p stream %p activated immediately.",
this, stream));
ActivateStream(stream);
}
else {
LOG3(("SpdySession3::AddStream %p stream %p queued.", this, stream));
mQueuedStreams.Push(stream);
}
return true;
}
void
SpdySession3::ActivateStream(SpdyStream3 *stream)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
MOZ_ASSERT(!stream->StreamID() || (stream->StreamID() & 1),
"Do not activate pushed streams");
++mConcurrent;
if (mConcurrent > mConcurrentHighWater)
mConcurrentHighWater = mConcurrent;
LOG3(("SpdySession3::AddStream %p activating stream %p Currently %d "
"streams in session, high water mark is %d",
this, stream, mConcurrent, mConcurrentHighWater));
mReadyForWrite.Push(stream);
SetWriteCallbacks();
// Kick off the SYN transmit without waiting for the poll loop
// This won't work for stream id=1 because there is no segment reader
// yet.
if (mSegmentReader) {
uint32_t countRead;
ReadSegments(nullptr, kDefaultBufferSize, &countRead);
}
}
void
SpdySession3::ProcessPending()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
while (RoomForMoreConcurrent()) {
SpdyStream3 *stream = static_cast<SpdyStream3 *>(mQueuedStreams.PopFront());
if (!stream)
return;
LOG3(("SpdySession3::ProcessPending %p stream %p activated from queue.",
this, stream));
ActivateStream(stream);
}
}
nsresult
SpdySession3::NetworkRead(nsAHttpSegmentWriter *writer, char *buf,
uint32_t count, uint32_t *countWritten)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
if (!count) {
*countWritten = 0;
return NS_OK;
}
nsresult rv = writer->OnWriteSegment(buf, count, countWritten);
if (NS_SUCCEEDED(rv) && *countWritten > 0)
mLastReadEpoch = PR_IntervalNow();
return rv;
}
void
SpdySession3::SetWriteCallbacks()
{
if (mConnection && (GetWriteQueueSize() || mOutputQueueUsed))
mConnection->ResumeSend();
}
void
SpdySession3::RealignOutputQueue()
{
mOutputQueueUsed -= mOutputQueueSent;
memmove(mOutputQueueBuffer.get(),
mOutputQueueBuffer.get() + mOutputQueueSent,
mOutputQueueUsed);
mOutputQueueSent = 0;
}
void
SpdySession3::FlushOutputQueue()
{
if (!mSegmentReader || !mOutputQueueUsed)
return;
nsresult rv;
uint32_t countRead;
uint32_t avail = mOutputQueueUsed - mOutputQueueSent;
rv = mSegmentReader->
OnReadSegment(mOutputQueueBuffer.get() + mOutputQueueSent, avail,
&countRead);
LOG3(("SpdySession3::FlushOutputQueue %p sz=%d rv=%x actual=%d",
this, avail, rv, countRead));
// Dont worry about errors on write, we will pick this up as a read error too
if (NS_FAILED(rv))
return;
if (countRead == avail) {
mOutputQueueUsed = 0;
mOutputQueueSent = 0;
return;
}
mOutputQueueSent += countRead;
// If the output queue is close to filling up and we have sent out a good
// chunk of data from the beginning then realign it.
if ((mOutputQueueSent >= kQueueMinimumCleanup) &&
((mOutputQueueSize - mOutputQueueUsed) < kQueueTailRoom)) {
RealignOutputQueue();
}
}
void
SpdySession3::DontReuse()
{
mShouldGoAway = true;
if (!mStreamTransactionHash.Count())
Close(NS_OK);
}
uint32_t
SpdySession3::GetWriteQueueSize()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
return mReadyForWrite.GetSize();
}
void
SpdySession3::ChangeDownstreamState(enum stateType newState)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdyStream3::ChangeDownstreamState() %p from %X to %X",
this, mDownstreamState, newState));
mDownstreamState = newState;
}
void
SpdySession3::ResetDownstreamState()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdyStream3::ResetDownstreamState() %p", this));
ChangeDownstreamState(BUFFERING_FRAME_HEADER);
if (mInputFrameDataLast && mInputFrameDataStream) {
mInputFrameDataLast = false;
if (!mInputFrameDataStream->RecvdFin()) {
LOG3((" SetRecvdFin id=0x%x\n", mInputFrameDataStream->StreamID()));
mInputFrameDataStream->SetRecvdFin(true);
DecrementConcurrent(mInputFrameDataStream);
}
}
mInputFrameBufferUsed = 0;
mInputFrameDataStream = nullptr;
}
template<typename T> void
SpdySession3::EnsureBuffer(nsAutoArrayPtr<T> &buf,
uint32_t newSize,
uint32_t preserve,
uint32_t &objSize)
{
if (objSize >= newSize)
return;
// Leave a little slop on the new allocation - add 2KB to
// what we need and then round the result up to a 4KB (page)
// boundary.
objSize = (newSize + 2048 + 4095) & ~4095;
MOZ_STATIC_ASSERT(sizeof(T) == 1, "sizeof(T) must be 1");
nsAutoArrayPtr<T> tmp(new T[objSize]);
memcpy(tmp, buf, preserve);
buf = tmp;
}
// Instantiate supported templates explicitly.
template void
SpdySession3::EnsureBuffer(nsAutoArrayPtr<char> &buf,
uint32_t newSize,
uint32_t preserve,
uint32_t &objSize);
template void
SpdySession3::EnsureBuffer(nsAutoArrayPtr<uint8_t> &buf,
uint32_t newSize,
uint32_t preserve,
uint32_t &objSize);
void
SpdySession3::DecrementConcurrent(SpdyStream3 *aStream)
{
uint32_t id = aStream->StreamID();
if (id && !(id & 0x1))
return; // pushed streams aren't counted in concurrent limit
MOZ_ASSERT(mConcurrent);
--mConcurrent;
LOG3(("DecrementConcurrent %p id=0x%X concurrent=%d\n",
this, id, mConcurrent));
ProcessPending();
}
void
SpdySession3::zlibInit()
{
mDownstreamZlib.zalloc = SpdyStream3::zlib_allocator;
mDownstreamZlib.zfree = SpdyStream3::zlib_destructor;
mDownstreamZlib.opaque = Z_NULL;
inflateInit(&mDownstreamZlib);
mUpstreamZlib.zalloc = SpdyStream3::zlib_allocator;
mUpstreamZlib.zfree = SpdyStream3::zlib_destructor;
mUpstreamZlib.opaque = Z_NULL;
// mixing carte blanche compression with tls subjects us to traffic
// analysis attacks
deflateInit(&mUpstreamZlib, Z_NO_COMPRESSION);
deflateSetDictionary(&mUpstreamZlib,
SpdyStream3::kDictionary,
sizeof(SpdyStream3::kDictionary));
}
// Need to decompress some data in order to keep the compression
// context correct, but we really don't care what the result is
nsresult
SpdySession3::UncompressAndDiscard(uint32_t offset,
uint32_t blockLen)
{
char *blockStart = mInputFrameBuffer + offset;
unsigned char trash[2048];
mDownstreamZlib.avail_in = blockLen;
mDownstreamZlib.next_in = reinterpret_cast<unsigned char *>(blockStart);
bool triedDictionary = false;
do {
mDownstreamZlib.next_out = trash;
mDownstreamZlib.avail_out = sizeof(trash);
int zlib_rv = inflate(&mDownstreamZlib, Z_NO_FLUSH);
if (zlib_rv == Z_NEED_DICT) {
if (triedDictionary) {
LOG3(("SpdySession3::UncompressAndDiscard %p Dictionary Error\n", this));
return NS_ERROR_FAILURE;
}
triedDictionary = true;
inflateSetDictionary(&mDownstreamZlib, SpdyStream3::kDictionary,
sizeof(SpdyStream3::kDictionary));
}
if (zlib_rv == Z_DATA_ERROR || zlib_rv == Z_MEM_ERROR)
return NS_ERROR_FAILURE;
}
while (mDownstreamZlib.avail_in);
return NS_OK;
}
void
SpdySession3::GeneratePing(uint32_t aID)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::GeneratePing %p 0x%X\n", this, aID));
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + 12,
mOutputQueueUsed, mOutputQueueSize);
char *packet = mOutputQueueBuffer.get() + mOutputQueueUsed;
mOutputQueueUsed += 12;
packet[0] = kFlag_Control;
packet[1] = kVersion;
packet[2] = 0;
packet[3] = CONTROL_TYPE_PING;
packet[4] = 0; /* flags */
packet[5] = 0;
packet[6] = 0;
packet[7] = 4; /* length */
aID = PR_htonl(aID);
memcpy(packet + 8, &aID, 4);
LogIO(this, nullptr, "Generate Ping", packet, 12);
FlushOutputQueue();
}
void
SpdySession3::GenerateRstStream(uint32_t aStatusCode, uint32_t aID)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::GenerateRst %p 0x%X %d\n", this, aID, aStatusCode));
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + 16,
mOutputQueueUsed, mOutputQueueSize);
char *packet = mOutputQueueBuffer.get() + mOutputQueueUsed;
mOutputQueueUsed += 16;
packet[0] = kFlag_Control;
packet[1] = kVersion;
packet[2] = 0;
packet[3] = CONTROL_TYPE_RST_STREAM;
packet[4] = 0; /* flags */
packet[5] = 0;
packet[6] = 0;
packet[7] = 8; /* length */
aID = PR_htonl(aID);
memcpy(packet + 8, &aID, 4);
aStatusCode = PR_htonl(aStatusCode);
memcpy(packet + 12, &aStatusCode, 4);
LogIO(this, nullptr, "Generate Reset", packet, 16);
FlushOutputQueue();
}
void
SpdySession3::GenerateGoAway(uint32_t aStatusCode)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::GenerateGoAway %p code=%X\n", this, aStatusCode));
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + 16,
mOutputQueueUsed, mOutputQueueSize);
char *packet = mOutputQueueBuffer.get() + mOutputQueueUsed;
mOutputQueueUsed += 16;
memset(packet, 0, 16);
packet[0] = kFlag_Control;
packet[1] = kVersion;
packet[3] = CONTROL_TYPE_GOAWAY;
packet[7] = 8; /* data length */
// last-good-stream-id are bytes 8-11, when we accept server push this will
// need to be set non zero
// bytes 12-15 are the status code.
aStatusCode = PR_htonl(aStatusCode);
memcpy(packet + 12, &aStatusCode, 4);
LogIO(this, nullptr, "Generate GoAway", packet, 16);
FlushOutputQueue();
}
void
SpdySession3::GenerateSettings()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::GenerateSettings %p\n", this));
static const uint32_t maxDataLen = 4 + 3 * 8; // sized for 3 settings
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + 8 + maxDataLen,
mOutputQueueUsed, mOutputQueueSize);
char *packet = mOutputQueueBuffer.get() + mOutputQueueUsed;
memset(packet, 0, 8 + maxDataLen);
packet[0] = kFlag_Control;
packet[1] = kVersion;
packet[3] = CONTROL_TYPE_SETTINGS;
uint8_t numberOfEntries = 0;
// entries need to be listed in order by ID
// 1st entry is bytes 12 to 19
// 2nd entry is bytes 20 to 27
// 3rd entry is bytes 28 to 35
if (!gHttpHandler->AllowSpdyPush()) {
// announcing that we accept 0 incoming streams is done to
// disable server push
packet[15 + 8 * numberOfEntries] = SETTINGS_TYPE_MAX_CONCURRENT;
// The value portion of the setting pair is already initialized to 0
numberOfEntries++;
}
nsRefPtr<nsHttpConnectionInfo> ci;
uint32_t cwnd = 0;
GetConnectionInfo(getter_AddRefs(ci));
if (ci)
cwnd = gHttpHandler->ConnMgr()->GetSpdyCWNDSetting(ci);
if (cwnd) {
packet[12 + 8 * numberOfEntries] = PERSISTED_VALUE;
packet[15 + 8 * numberOfEntries] = SETTINGS_TYPE_CWND;
LOG(("SpdySession3::GenerateSettings %p sending CWND %u\n", this, cwnd));
cwnd = PR_htonl(cwnd);
memcpy(packet + 16 + 8 * numberOfEntries, &cwnd, 4);
numberOfEntries++;
}
// Advertise the Push RWIN and on each client SYN_STREAM pipeline
// a window update with it in order to use larger initial windows with pulled
// streams.
packet[15 + 8 * numberOfEntries] = SETTINGS_TYPE_INITIAL_WINDOW;
uint32_t rwin = PR_htonl(mPushAllowance);
memcpy(packet + 16 + 8 * numberOfEntries, &rwin, 4);
numberOfEntries++;
uint32_t dataLen = 4 + 8 * numberOfEntries;
mOutputQueueUsed += 8 + dataLen;
packet[7] = dataLen;
packet[11] = numberOfEntries;
LogIO(this, nullptr, "Generate Settings", packet, 8 + dataLen);
FlushOutputQueue();
}
// perform a bunch of integrity checks on the stream.
// returns true if passed, false (plus LOG and ABORT) if failed.
bool
SpdySession3::VerifyStream(SpdyStream3 *aStream, uint32_t aOptionalID = 0)
{
// This is annoying, but at least it is O(1)
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
#ifndef DEBUG
// Only do the real verification in debug builds
return true;
#endif
if (!aStream)
return true;
uint32_t test = 0;
do {
if (aStream->StreamID() == kDeadStreamID)
break;
nsAHttpTransaction *trans = aStream->Transaction();
test++;
if (!trans)
break;
test++;
if (mStreamTransactionHash.Get(trans) != aStream)
break;
if (aStream->StreamID()) {
SpdyStream3 *idStream = mStreamIDHash.Get(aStream->StreamID());
test++;
if (idStream != aStream)
break;
if (aOptionalID) {
test++;
if (idStream->StreamID() != aOptionalID)
break;
}
}
// tests passed
return true;
} while (0);
LOG(("SpdySession3 %p VerifyStream Failure %p stream->id=0x%X "
"optionalID=0x%X trans=%p test=%d\n",
this, aStream, aStream->StreamID(),
aOptionalID, aStream->Transaction(), test));
MOZ_ASSERT(false, "VerifyStream");
return false;
}
void
SpdySession3::CleanupStream(SpdyStream3 *aStream, nsresult aResult,
rstReason aResetCode)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::CleanupStream %p %p 0x%X %X\n",
this, aStream, aStream->StreamID(), aResult));
SpdyPushedStream3 *pushSource = nullptr;
if (NS_SUCCEEDED(aResult) && aStream->DeferCleanupOnSuccess()) {
LOG(("SpdySession3::CleanupStream 0x%X deferred\n", aStream->StreamID()));
return;
}
if (!VerifyStream(aStream)) {
LOG(("SpdySession3::CleanupStream failed to verify stream\n"));
return;
}
pushSource = aStream->PushSource();
if (!aStream->RecvdFin() && aStream->StreamID()) {
LOG3(("Stream had not processed recv FIN, sending RST code %X\n",
aResetCode));
GenerateRstStream(aResetCode, aStream->StreamID());
DecrementConcurrent(aStream);
}
CloseStream(aStream, aResult);
// Remove the stream from the ID hash table and, if an even id, the pushed
// table too.
uint32_t id = aStream->StreamID();
if (id > 0) {
mStreamIDHash.Remove(id);
if (!(id & 1))
mPushedStreams.RemoveElement(aStream);
}
RemoveStreamFromQueues(aStream);
// removing from the stream transaction hash will
// delete the SpdyStream3 and drop the reference to
// its transaction
mStreamTransactionHash.Remove(aStream->Transaction());
if (mShouldGoAway && !mStreamTransactionHash.Count())
Close(NS_OK);
if (pushSource) {
pushSource->SetDeferCleanupOnSuccess(false);
CleanupStream(pushSource, aResult, aResetCode);
}
}
static void RemoveStreamFromQueue(SpdyStream3 *aStream, nsDeque &queue)
{
uint32_t size = queue.GetSize();
for (uint32_t count = 0; count < size; ++count) {
SpdyStream3 *stream = static_cast<SpdyStream3 *>(queue.PopFront());
if (stream != aStream)
queue.Push(stream);
}
}
void
SpdySession3::RemoveStreamFromQueues(SpdyStream3 *aStream)
{
RemoveStreamFromQueue(aStream, mReadyForWrite);
RemoveStreamFromQueue(aStream, mQueuedStreams);
RemoveStreamFromQueue(aStream, mReadyForRead);
}
void
SpdySession3::CloseStream(SpdyStream3 *aStream, nsresult aResult)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::CloseStream %p %p 0x%x %X\n",
this, aStream, aStream->StreamID(), aResult));
// Check if partial frame reader
if (aStream == mInputFrameDataStream) {
LOG3(("Stream had active partial read frame on close"));
ChangeDownstreamState(DISCARDING_DATA_FRAME);
mInputFrameDataStream = nullptr;
}
RemoveStreamFromQueues(aStream);
// Send the stream the close() indication
aStream->Close(aResult);
}
nsresult
SpdySession3::HandleSynStream(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_SYN_STREAM);
if (self->mInputFrameDataSize < 18) {
LOG3(("SpdySession3::HandleSynStream %p SYN_STREAM too short data=%d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
uint32_t associatedID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[3]);
uint8_t flags = reinterpret_cast<uint8_t *>(self->mInputFrameBuffer.get())[4];
LOG3(("SpdySession3::HandleSynStream %p recv SYN_STREAM (push) "
"for ID 0x%X associated with 0x%X.\n",
self, streamID, associatedID));
if (streamID & 0x01) { // test for odd stream ID
LOG3(("SpdySession3::HandleSynStream %p recvd SYN_STREAM id must be even.",
self));
return NS_ERROR_ILLEGAL_VALUE;
}
// confirm associated-to
nsresult rv = self->SetInputFrameDataStream(associatedID);
if (NS_FAILED(rv))
return rv;
SpdyStream3 *associatedStream = self->mInputFrameDataStream;
++(self->mServerPushedResources);
// Anytime we start using the high bit of stream ID (either client or server)
// begin to migrate to a new session.
if (streamID >= kMaxStreamID)
self->mShouldGoAway = true;
bool resetStream = true;
SpdyPushCache3 *cache = nullptr;
if (!(flags & kFlag_Data_UNI)) {
// pushed streams require UNIDIRECTIONAL flag
LOG3(("SpdySession3::HandleSynStream %p ID %0x%X associated ID 0x%X failed.\n",
self, streamID, associatedID));
self->GenerateRstStream(RST_PROTOCOL_ERROR, streamID);
} else if (!associatedID) {
// associated stream 0 will never find a match, but the spec requires a
// PROTOCOL_ERROR in this specific case
LOG3(("SpdySession3::HandleSynStream %p associated ID of 0 failed.\n", self));
self->GenerateRstStream(RST_PROTOCOL_ERROR, streamID);
} else if (!gHttpHandler->AllowSpdyPush()) {
// MAX_CONCURRENT_STREAMS of 0 in settings should have disabled push,
// but some servers are buggy about that.. or the config could have
// been updated after the settings frame was sent. In both cases just
// reject the pushed stream as refused
LOG3(("SpdySession3::HandleSynStream Push Recevied when Disabled\n"));
self->GenerateRstStream(RST_REFUSED_STREAM, streamID);
} else if (!associatedStream) {
LOG3(("SpdySession3::HandleSynStream %p lookup associated ID failed.\n", self));
self->GenerateRstStream(RST_INVALID_STREAM, streamID);
} else {
nsILoadGroupConnectionInfo *loadGroupCI = associatedStream->LoadGroupConnectionInfo();
if (loadGroupCI) {
loadGroupCI->GetSpdyPushCache3(&cache);
if (!cache) {
cache = new SpdyPushCache3();
if (!cache || NS_FAILED(loadGroupCI->SetSpdyPushCache3(cache))) {
delete cache;
cache = nullptr;
}
}
}
if (!cache) {
// this is unexpected, but we can handle it just be refusing the push
LOG3(("SpdySession3::HandleSynStream Push Recevied without loadgroup cache\n"));
self->GenerateRstStream(RST_REFUSED_STREAM, streamID);
}
else {
resetStream = false;
}
}
if (resetStream) {
// Need to decompress the headers even though we aren't using them yet in
// order to keep the compression context consistent for other syn_reply frames
rv = self->UncompressAndDiscard(18, self->mInputFrameDataSize - 10);
if (NS_FAILED(rv)) {
LOG(("SpdySession3::HandleSynStream uncompress failed\n"));
return rv;
}
self->ResetDownstreamState();
return NS_OK;
}
// Create the buffering transaction and push stream
nsRefPtr<SpdyPush3TransactionBuffer> transactionBuffer =
new SpdyPush3TransactionBuffer();
transactionBuffer->SetConnection(self);
SpdyPushedStream3 *pushedStream =
new SpdyPushedStream3(transactionBuffer, self,
associatedStream, streamID);
// ownership of the pushed stream is by the transaction hash, just as it
// is for a client initiated stream. Errors that aren't fatal to the
// whole session must call cleanupStream() after this point in order
// to remove the stream from that hash.
self->mStreamTransactionHash.Put(transactionBuffer, pushedStream);
self->mPushedStreams.AppendElement(pushedStream);
// The pushed stream is unidirectional so it is fully open immediately
pushedStream->SetFullyOpen();
// Uncompress the response headers into a stream specific buffer, leaving them
// in spdy format for the time being.
rv = pushedStream->Uncompress(&self->mDownstreamZlib,
self->mInputFrameBuffer + 18,
self->mInputFrameDataSize - 10);
if (NS_FAILED(rv)) {
LOG(("SpdySession3::HandleSynStream uncompress failed\n"));
return rv;
}
if (self->RegisterStreamID(pushedStream, streamID) == kDeadStreamID) {
LOG(("SpdySession3::HandleSynStream registerstreamid failed\n"));
return NS_ERROR_FAILURE;
}
// Fake the request side of the pushed HTTP transaction. Sets up hash
// key and origin
uint32_t notUsed;
pushedStream->ReadSegments(nullptr, 1, ¬Used);
nsAutoCString key;
if (!pushedStream->GetHashKey(key)) {
LOG(("SpdySession3::HandleSynStream one of :host :scheme :path missing from push\n"));
self->CleanupStream(pushedStream, NS_ERROR_FAILURE, RST_INVALID_STREAM);
self->ResetDownstreamState();
return NS_OK;
}
if (!associatedStream->Origin().Equals(pushedStream->Origin())) {
LOG(("SpdySession3::HandleSynStream pushed stream mismatched origin\n"));
self->CleanupStream(pushedStream, NS_ERROR_FAILURE, RST_INVALID_STREAM);
self->ResetDownstreamState();
return NS_OK;
}
if (!cache->RegisterPushedStream(key, pushedStream)) {
LOG(("SpdySession3::HandleSynStream registerPushedStream Failed\n"));
self->CleanupStream(pushedStream, NS_ERROR_FAILURE, RST_INVALID_STREAM);
self->ResetDownstreamState();
return NS_OK;
}
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::SetInputFrameDataStream(uint32_t streamID)
{
mInputFrameDataStream = mStreamIDHash.Get(streamID);
if (VerifyStream(mInputFrameDataStream, streamID))
return NS_OK;
LOG(("SpdySession3::SetInputFrameDataStream failed to verify 0x%X\n",
streamID));
mInputFrameDataStream = nullptr;
return NS_ERROR_UNEXPECTED;
}
nsresult
SpdySession3::HandleSynReply(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_SYN_REPLY);
if (self->mInputFrameDataSize < 4) {
LOG3(("SpdySession3::HandleSynReply %p SYN REPLY too short data=%d",
self, self->mInputFrameDataSize));
// A framing error is a session wide error that cannot be recovered
return NS_ERROR_ILLEGAL_VALUE;
}
LOG3(("SpdySession3::HandleSynReply %p lookup via streamID in syn_reply.\n",
self));
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
nsresult rv = self->SetInputFrameDataStream(streamID);
if (NS_FAILED(rv))
return rv;
if (!self->mInputFrameDataStream) {
// Cannot find stream. We can continue the SPDY session, but we need to
// uncompress the header block to maintain the correct compression context
LOG3(("SpdySession3::HandleSynReply %p lookup streamID in syn_reply "
"0x%X failed. NextStreamID = 0x%X\n",
self, streamID, self->mNextStreamID));
if (streamID >= self->mNextStreamID)
self->GenerateRstStream(RST_INVALID_STREAM, streamID);
if (NS_FAILED(self->UncompressAndDiscard(12,
self->mInputFrameDataSize - 4))) {
LOG(("SpdySession3::HandleSynReply uncompress failed\n"));
// this is fatal to the session
return NS_ERROR_FAILURE;
}
self->ResetDownstreamState();
return NS_OK;
}
// Uncompress the headers into a stream specific buffer, leaving them in
// spdy format for the time being. Make certain to do this
// step before any error handling that might abort the stream but not
// the session becuase the session compression context will become
// inconsistent if all of the compressed data is not processed.
rv = self->mInputFrameDataStream->Uncompress(&self->mDownstreamZlib,
self->mInputFrameBuffer + 12,
self->mInputFrameDataSize - 4);
if (NS_FAILED(rv)) {
LOG(("SpdySession3::HandleSynReply uncompress failed\n"));
return NS_ERROR_FAILURE;
}
if (self->mInputFrameDataStream->GetFullyOpen()) {
// "If an endpoint receives multiple SYN_REPLY frames for the same active
// stream ID, it MUST issue a stream error (Section 2.4.2) with the error
// code STREAM_IN_USE."
//
// "STREAM_ALREADY_CLOSED. The endpoint received a data or SYN_REPLY
// frame for a stream which is half closed."
//
// If the stream is open then just RST_STREAM with STREAM_IN_USE
// If the stream is half closed then RST_STREAM with STREAM_ALREADY_CLOSED
// abort the session
//
LOG3(("SpdySession3::HandleSynReply %p dup SYN_REPLY for 0x%X"
" recvdfin=%d", self, self->mInputFrameDataStream->StreamID(),
self->mInputFrameDataStream->RecvdFin()));
self->CleanupStream(self->mInputFrameDataStream, NS_ERROR_ALREADY_OPENED,
self->mInputFrameDataStream->RecvdFin() ?
RST_STREAM_ALREADY_CLOSED : RST_STREAM_IN_USE);
self->ResetDownstreamState();
return NS_OK;
}
self->mInputFrameDataStream->SetFullyOpen();
self->mInputFrameDataLast = self->mInputFrameBuffer[4] & kFlag_Data_FIN;
self->mInputFrameDataStream->UpdateTransportReadEvents(self->mInputFrameDataSize);
self->mLastDataReadEpoch = self->mLastReadEpoch;
if (self->mInputFrameBuffer[4] & ~kFlag_Data_FIN) {
LOG3(("SynReply %p had undefined flag set 0x%X\n", self, streamID));
self->CleanupStream(self->mInputFrameDataStream, NS_ERROR_ILLEGAL_VALUE,
RST_PROTOCOL_ERROR);
self->ResetDownstreamState();
return NS_OK;
}
if (!self->mInputFrameDataLast) {
// don't process the headers yet as there could be more coming from HEADERS
// frames
self->ResetDownstreamState();
return NS_OK;
}
rv = self->ResponseHeadersComplete();
if (rv == NS_ERROR_ILLEGAL_VALUE) {
LOG3(("SpdySession3::HandleSynReply %p PROTOCOL_ERROR detected 0x%X\n",
self, streamID));
self->CleanupStream(self->mInputFrameDataStream, rv, RST_PROTOCOL_ERROR);
self->ResetDownstreamState();
rv = NS_OK;
}
return rv;
}
// ResponseHeadersComplete() returns NS_ERROR_ILLEGAL_VALUE when the stream
// should be reset with a PROTOCOL_ERROR, NS_OK when the SYN_REPLY was
// fine, and any other error is fatal to the session.
nsresult
SpdySession3::ResponseHeadersComplete()
{
LOG3(("SpdySession3::ResponseHeadersComplete %p for 0x%X fin=%d",
this, mInputFrameDataStream->StreamID(), mInputFrameDataLast));
// The spdystream needs to see flattened http headers
// Uncompressed spdy format headers currently live in
// SpdyStream3::mDecompressBuffer - convert that to HTTP format in
// mFlatHTTPResponseHeaders via ConvertHeaders()
mFlatHTTPResponseHeadersOut = 0;
nsresult rv = mInputFrameDataStream->ConvertHeaders(mFlatHTTPResponseHeaders);
if (NS_FAILED(rv))
return rv;
ChangeDownstreamState(PROCESSING_COMPLETE_HEADERS);
return NS_OK;
}
nsresult
SpdySession3::HandleRstStream(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_RST_STREAM);
if (self->mInputFrameDataSize != 8) {
LOG3(("SpdySession3::HandleRstStream %p RST_STREAM wrong length data=%d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint8_t flags = reinterpret_cast<uint8_t *>(self->mInputFrameBuffer.get())[4];
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
self->mDownstreamRstReason =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[3]);
LOG3(("SpdySession3::HandleRstStream %p RST_STREAM Reason Code %u ID %x "
"flags %x", self, self->mDownstreamRstReason, streamID, flags));
if (flags != 0) {
LOG3(("SpdySession3::HandleRstStream %p RST_STREAM with flags is illegal",
self));
return NS_ERROR_ILLEGAL_VALUE;
}
if (self->mDownstreamRstReason == RST_INVALID_STREAM ||
self->mDownstreamRstReason == RST_STREAM_IN_USE ||
self->mDownstreamRstReason == RST_FLOW_CONTROL_ERROR) {
// basically just ignore this
LOG3(("SpdySession3::HandleRstStream %p No Reset Processing Needed.\n"));
self->ResetDownstreamState();
return NS_OK;
}
nsresult rv = self->SetInputFrameDataStream(streamID);
if (!self->mInputFrameDataStream) {
if (NS_FAILED(rv))
LOG(("SpdySession3::HandleRstStream %p lookup streamID for RST Frame "
"0x%X failed reason = %d :: VerifyStream Failed\n", self, streamID,
self->mDownstreamRstReason));
LOG3(("SpdySession3::HandleRstStream %p lookup streamID for RST Frame "
"0x%X failed reason = %d", self, streamID,
self->mDownstreamRstReason));
return NS_ERROR_ILLEGAL_VALUE;
}
self->ChangeDownstreamState(PROCESSING_CONTROL_RST_STREAM);
return NS_OK;
}
PLDHashOperator
SpdySession3::UpdateServerRwinEnumerator(nsAHttpTransaction *key,
nsAutoPtr<SpdyStream3> &stream,
void *closure)
{
int32_t delta = *(static_cast<int32_t *>(closure));
stream->UpdateRemoteWindow(delta);
return PL_DHASH_NEXT;
}
nsresult
SpdySession3::HandleSettings(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_SETTINGS);
if (self->mInputFrameDataSize < 4) {
LOG3(("SpdySession3::HandleSettings %p SETTINGS wrong length data=%d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint32_t numEntries =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
// Ensure frame is large enough for supplied number of entries
// Each entry is 8 bytes, frame data is reduced by 4 to account for
// the NumEntries value.
if ((self->mInputFrameDataSize - 4) < (numEntries * 8)) {
LOG3(("SpdySession3::HandleSettings %p SETTINGS wrong length data=%d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
LOG3(("SpdySession3::HandleSettings %p SETTINGS Control Frame with %d entries",
self, numEntries));
for (uint32_t index = 0; index < numEntries; ++index) {
unsigned char *setting = reinterpret_cast<unsigned char *>
(self->mInputFrameBuffer.get()) + 12 + index * 8;
uint32_t flags = setting[0];
uint32_t id = PR_ntohl(reinterpret_cast<uint32_t *>(setting)[0]) & 0xffffff;
uint32_t value = PR_ntohl(reinterpret_cast<uint32_t *>(setting)[1]);
LOG3(("Settings ID %d, Flags %X, Value %d", id, flags, value));
switch (id)
{
case SETTINGS_TYPE_UPLOAD_BW:
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_UL_BW, value);
break;
case SETTINGS_TYPE_DOWNLOAD_BW:
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_DL_BW, value);
break;
case SETTINGS_TYPE_RTT:
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_RTT, value);
break;
case SETTINGS_TYPE_MAX_CONCURRENT:
self->mMaxConcurrent = value;
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_MAX_STREAMS, value);
break;
case SETTINGS_TYPE_CWND:
if (flags & PERSIST_VALUE)
{
nsRefPtr<nsHttpConnectionInfo> ci;
self->GetConnectionInfo(getter_AddRefs(ci));
if (ci)
gHttpHandler->ConnMgr()->ReportSpdyCWNDSetting(ci, value);
}
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_CWND, value);
break;
case SETTINGS_TYPE_DOWNLOAD_RETRANS_RATE:
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_RETRANS, value);
break;
case SETTINGS_TYPE_INITIAL_WINDOW:
Telemetry::Accumulate(Telemetry::SPDY_SETTINGS_IW, value >> 10);
{
int32_t delta = value - self->mServerInitialWindow;
self->mServerInitialWindow = value;
// we need to add the delta to all open streams (delta can be negative)
self->mStreamTransactionHash.Enumerate(UpdateServerRwinEnumerator,
&delta);
}
break;
default:
break;
}
}
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::HandleNoop(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_NOOP);
// Should not be receiving noop frames in spdy/3, so we'll just
// make a log and ignore it
LOG3(("SpdySession3::HandleNoop %p NOP.", self));
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::HandlePing(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_PING);
if (self->mInputFrameDataSize != 4) {
LOG3(("SpdySession3::HandlePing %p PING had wrong amount of data %d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint32_t pingID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
LOG3(("SpdySession3::HandlePing %p PING ID 0x%X.", self, pingID));
if (pingID & 0x01) {
// presumably a reply to our timeout ping
self->mPingSentEpoch = 0;
}
else {
// Servers initiate even numbered pings, go ahead and echo it back
self->GeneratePing(pingID);
}
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::HandleGoAway(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_GOAWAY);
if (self->mInputFrameDataSize != 8) {
LOG3(("SpdySession3::HandleGoAway %p GOAWAY had wrong amount of data %d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
self->mShouldGoAway = true;
self->mGoAwayID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
self->mCleanShutdown = true;
// Find streams greater than the last-good ID and mark them for deletion
// in the mGoAwayStreamsToRestart queue with the GoAwayEnumerator. The
// underlying transaction can be restarted.
self->mStreamTransactionHash.Enumerate(GoAwayEnumerator, self);
// Process the streams marked for deletion and restart.
uint32_t size = self->mGoAwayStreamsToRestart.GetSize();
for (uint32_t count = 0; count < size; ++count) {
SpdyStream3 *stream =
static_cast<SpdyStream3 *>(self->mGoAwayStreamsToRestart.PopFront());
self->CloseStream(stream, NS_ERROR_NET_RESET);
if (stream->HasRegisteredID())
self->mStreamIDHash.Remove(stream->StreamID());
self->mStreamTransactionHash.Remove(stream->Transaction());
}
// Queued streams can also be deleted from this session and restarted
// in another one. (they were never sent on the network so they implicitly
// are not covered by the last-good id.
size = self->mQueuedStreams.GetSize();
for (uint32_t count = 0; count < size; ++count) {
SpdyStream3 *stream =
static_cast<SpdyStream3 *>(self->mQueuedStreams.PopFront());
self->CloseStream(stream, NS_ERROR_NET_RESET);
self->mStreamTransactionHash.Remove(stream->Transaction());
}
LOG3(("SpdySession3::HandleGoAway %p GOAWAY Last-Good-ID 0x%X status 0x%X "
"live streams=%d\n", self, self->mGoAwayID,
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[3]),
self->mStreamTransactionHash.Count()));
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::HandleHeaders(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_HEADERS);
if (self->mInputFrameDataSize < 4) {
LOG3(("SpdySession3::HandleHeaders %p HEADERS had wrong amount of data %d",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
LOG3(("SpdySession3::HandleHeaders %p HEADERS for Stream 0x%X.\n",
self, streamID));
nsresult rv = self->SetInputFrameDataStream(streamID);
if (NS_FAILED(rv))
return rv;
if (!self->mInputFrameDataStream) {
LOG3(("SpdySession3::HandleHeaders %p lookup streamID 0x%X failed.\n",
self, streamID));
if (streamID >= self->mNextStreamID)
self->GenerateRstStream(RST_INVALID_STREAM, streamID);
if (NS_FAILED(self->UncompressAndDiscard(12,
self->mInputFrameDataSize - 4))) {
LOG(("SpdySession3::HandleHeaders uncompress failed\n"));
// this is fatal to the session
return NS_ERROR_FAILURE;
}
self->ResetDownstreamState();
return NS_OK;
}
// Uncompress the headers into local buffers in the SpdyStream, leaving
// them in spdy format for the time being. Make certain to do this
// step before any error handling that might abort the stream but not
// the session becuase the session compression context will become
// inconsistent if all of the compressed data is not processed.
rv = self->mInputFrameDataStream->Uncompress(&self->mDownstreamZlib,
self->mInputFrameBuffer + 12,
self->mInputFrameDataSize - 4);
if (NS_FAILED(rv)) {
LOG(("SpdySession3::HandleHeaders uncompress failed\n"));
return NS_ERROR_FAILURE;
}
self->mInputFrameDataLast = self->mInputFrameBuffer[4] & kFlag_Data_FIN;
self->mInputFrameDataStream->
UpdateTransportReadEvents(self->mInputFrameDataSize);
self->mLastDataReadEpoch = self->mLastReadEpoch;
if (self->mInputFrameBuffer[4] & ~kFlag_Data_FIN) {
LOG3(("Headers %p had undefined flag set 0x%X\n", self, streamID));
self->CleanupStream(self->mInputFrameDataStream, NS_ERROR_ILLEGAL_VALUE,
RST_PROTOCOL_ERROR);
self->ResetDownstreamState();
return NS_OK;
}
if (!self->mInputFrameDataLast) {
// don't process the headers yet as there could be more HEADERS frames
self->ResetDownstreamState();
return NS_OK;
}
rv = self->ResponseHeadersComplete();
if (rv == NS_ERROR_ILLEGAL_VALUE) {
LOG3(("SpdySession3::HanndleHeaders %p PROTOCOL_ERROR detected 0x%X\n",
self, streamID));
self->CleanupStream(self->mInputFrameDataStream, rv, RST_PROTOCOL_ERROR);
self->ResetDownstreamState();
rv = NS_OK;
}
return rv;
}
nsresult
SpdySession3::HandleWindowUpdate(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_WINDOW_UPDATE);
if (self->mInputFrameDataSize < 8) {
LOG3(("SpdySession3::HandleWindowUpdate %p Window Update wrong length %d\n",
self, self->mInputFrameDataSize));
return NS_ERROR_ILLEGAL_VALUE;
}
uint32_t delta =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[3]);
delta &= 0x7fffffff;
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(self->mInputFrameBuffer.get())[2]);
streamID &= 0x7fffffff;
LOG3(("SpdySession3::HandleWindowUpdate %p len=%d for Stream 0x%X.\n",
self, delta, streamID));
nsresult rv = self->SetInputFrameDataStream(streamID);
if (NS_FAILED(rv))
return rv;
if (!self->mInputFrameDataStream) {
LOG3(("SpdySession3::HandleWindowUpdate %p lookup streamID 0x%X failed.\n",
self, streamID));
if (streamID >= self->mNextStreamID)
self->GenerateRstStream(RST_INVALID_STREAM, streamID);
self->ResetDownstreamState();
return NS_OK;
}
int64_t oldRemoteWindow = self->mInputFrameDataStream->RemoteWindow();
self->mInputFrameDataStream->UpdateRemoteWindow(delta);
LOG3(("SpdySession3::HandleWindowUpdate %p stream 0x%X window "
"%d increased by %d.\n", self, streamID, oldRemoteWindow, delta));
// If the stream had a <=0 window, that has now opened
// schedule it for writing again
if (oldRemoteWindow <= 0 &&
self->mInputFrameDataStream->RemoteWindow() > 0) {
self->mReadyForWrite.Push(self->mInputFrameDataStream);
self->SetWriteCallbacks();
}
self->ResetDownstreamState();
return NS_OK;
}
nsresult
SpdySession3::HandleCredential(SpdySession3 *self)
{
MOZ_ASSERT(self->mFrameControlType == CONTROL_TYPE_CREDENTIAL);
// These aren't used yet. Just ignore the frame.
LOG3(("SpdySession3::HandleCredential %p NOP.", self));
self->ResetDownstreamState();
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsAHttpTransaction. It is expected that nsHttpConnection is the caller
// of these methods
//-----------------------------------------------------------------------------
void
SpdySession3::OnTransportStatus(nsITransport* aTransport,
nsresult aStatus,
uint64_t aProgress)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
switch (aStatus) {
// These should appear only once, deliver to the first
// transaction on the session.
case NS_NET_STATUS_RESOLVING_HOST:
case NS_NET_STATUS_RESOLVED_HOST:
case NS_NET_STATUS_CONNECTING_TO:
case NS_NET_STATUS_CONNECTED_TO:
{
SpdyStream3 *target = mStreamIDHash.Get(1);
nsAHttpTransaction *transaction = target ? target->Transaction() : nullptr;
if (transaction)
transaction->OnTransportStatus(aTransport, aStatus, aProgress);
break;
}
default:
// The other transport events are ignored here because there is no good
// way to map them to the right transaction in spdy. Instead, the events
// are generated again from the spdy code and passed directly to the
// correct transaction.
// NS_NET_STATUS_SENDING_TO:
// This is generated by the socket transport when (part) of
// a transaction is written out
//
// There is no good way to map it to the right transaction in spdy,
// so it is ignored here and generated separately when the SYN_STREAM
// is sent from SpdyStream3::TransmitFrame
// NS_NET_STATUS_WAITING_FOR:
// Created by nsHttpConnection when the request has been totally sent.
// There is no good way to map it to the right transaction in spdy,
// so it is ignored here and generated separately when the same
// condition is complete in SpdyStream3 when there is no more
// request body left to be transmitted.
// NS_NET_STATUS_RECEIVING_FROM
// Generated in spdysession whenever we read a data frame or a syn_reply
// that can be attributed to a particular stream/transaction
break;
}
}
// ReadSegments() is used to write data to the network. Generally, HTTP
// request data is pulled from the approriate transaction and
// converted to SPDY data. Sometimes control data like window-update are
// generated instead.
nsresult
SpdySession3::ReadSegments(nsAHttpSegmentReader *reader,
uint32_t count,
uint32_t *countRead)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
MOZ_ASSERT(!mSegmentReader || !reader || (mSegmentReader == reader),
"Inconsistent Write Function Callback");
if (reader)
mSegmentReader = reader;
nsresult rv;
*countRead = 0;
LOG3(("SpdySession3::ReadSegments %p", this));
SpdyStream3 *stream = static_cast<SpdyStream3 *>(mReadyForWrite.PopFront());
if (!stream) {
LOG3(("SpdySession3 %p could not identify a stream to write; suspending.",
this));
FlushOutputQueue();
SetWriteCallbacks();
return NS_BASE_STREAM_WOULD_BLOCK;
}
LOG3(("SpdySession3 %p will write from SpdyStream3 %p 0x%X "
"block-input=%d block-output=%d\n", this, stream, stream->StreamID(),
stream->RequestBlockedOnRead(), stream->BlockedOnRwin()));
rv = stream->ReadSegments(this, count, countRead);
// Not every permutation of stream->ReadSegents produces data (and therefore
// tries to flush the output queue) - SENDING_FIN_STREAM can be an example
// of that. But we might still have old data buffered that would be good
// to flush.
FlushOutputQueue();
// Allow new server reads - that might be data or control information
// (e.g. window updates or http replies) that are responses to these writes
ResumeRecv();
if (stream->RequestBlockedOnRead()) {
// We are blocked waiting for input - either more http headers or
// any request body data. When more data from the request stream
// becomes available the httptransaction will call conn->ResumeSend().
LOG3(("SpdySession3::ReadSegments %p dealing with block on read", this));
// call readsegments again if there are other streams ready
// to run in this session
if (GetWriteQueueSize())
rv = NS_OK;
else
rv = NS_BASE_STREAM_WOULD_BLOCK;
SetWriteCallbacks();
return rv;
}
if (NS_FAILED(rv)) {
LOG3(("SpdySession3::ReadSegments %p returning FAIL code %X",
this, rv));
if (rv != NS_BASE_STREAM_WOULD_BLOCK)
CleanupStream(stream, rv, RST_CANCEL);
return rv;
}
if (*countRead > 0) {
LOG3(("SpdySession3::ReadSegments %p stream=%p countread=%d",
this, stream, *countRead));
mReadyForWrite.Push(stream);
SetWriteCallbacks();
return rv;
}
if (stream->BlockedOnRwin()) {
LOG3(("SpdySession3 %p will stream %p 0x%X suspended for flow control\n",
this, stream, stream->StreamID()));
return NS_BASE_STREAM_WOULD_BLOCK;
}
LOG3(("SpdySession3::ReadSegments %p stream=%p stream send complete",
this, stream));
// call readsegments again if there are other streams ready
// to go in this session
SetWriteCallbacks();
return rv;
}
// WriteSegments() is used to read data off the socket. Generally this is
// just the SPDY frame header and from there the appropriate SPDYStream
// is identified from the Stream-ID. The http transaction associated with
// that read then pulls in the data directly, which it will feed to
// OnWriteSegment(). That function will gateway it into http and feed
// it to the appropriate transaction.
// we call writer->OnWriteSegment via NetworkRead() to get a spdy header..
// and decide if it is data or control.. if it is control, just deal with it.
// if it is data, identify the spdy stream
// call stream->WriteSegments which can call this::OnWriteSegment to get the
// data. It always gets full frames if they are part of the stream
nsresult
SpdySession3::WriteSegments(nsAHttpSegmentWriter *writer,
uint32_t count,
uint32_t *countWritten)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
nsresult rv;
*countWritten = 0;
if (mClosed)
return NS_ERROR_FAILURE;
SetWriteCallbacks();
// If there are http transactions attached to a push stream with filled buffers
// trigger that data pump here. This only reads from buffers (not the network)
// so mDownstreamState doesn't matter.
SpdyStream3 *pushConnectedStream =
static_cast<SpdyStream3 *>(mReadyForRead.PopFront());
if (pushConnectedStream) {
LOG3(("SpdySession3::WriteSegments %p processing pushed stream 0x%X\n",
this, pushConnectedStream->StreamID()));
mSegmentWriter = writer;
rv = pushConnectedStream->WriteSegments(this, count, countWritten);
mSegmentWriter = nullptr;
// The pipe in nsHttpTransaction rewrites CLOSED error codes into OK
// so we need this check to determine the truth.
if (NS_SUCCEEDED(rv) && !*countWritten &&
pushConnectedStream->PushSource() &&
pushConnectedStream->PushSource()->GetPushComplete()) {
rv = NS_BASE_STREAM_CLOSED;
}
if (rv == NS_BASE_STREAM_CLOSED) {
CleanupStream(pushConnectedStream, NS_OK, RST_CANCEL);
rv = NS_OK;
}
// if we return OK to nsHttpConnection it will use mSocketInCondition
// to determine whether to schedule more reads, incorrectly
// assuming that nsHttpConnection::OnSocketWrite() was called.
if (NS_SUCCEEDED(rv) || rv == NS_BASE_STREAM_WOULD_BLOCK) {
rv = NS_BASE_STREAM_WOULD_BLOCK;
ResumeRecv();
}
return rv;
}
// We buffer all control frames and act on them in this layer.
// We buffer the first 8 bytes of data frames (the header) but
// the actual data is passed through unprocessed.
if (mDownstreamState == BUFFERING_FRAME_HEADER) {
// The first 8 bytes of every frame is header information that
// we are going to want to strip before passing to http. That is
// true of both control and data packets.
MOZ_ASSERT(mInputFrameBufferUsed < 8,
"Frame Buffer Used Too Large for State");
rv = NetworkRead(writer, mInputFrameBuffer + mInputFrameBufferUsed,
8 - mInputFrameBufferUsed, countWritten);
if (NS_FAILED(rv)) {
LOG3(("SpdySession3 %p buffering frame header read failure %x\n",
this, rv));
// maybe just blocked reading from network
if (rv == NS_BASE_STREAM_WOULD_BLOCK)
rv = NS_OK;
return rv;
}
LogIO(this, nullptr, "Reading Frame Header",
mInputFrameBuffer + mInputFrameBufferUsed, *countWritten);
mInputFrameBufferUsed += *countWritten;
if (mInputFrameBufferUsed < 8)
{
LOG3(("SpdySession3::WriteSegments %p "
"BUFFERING FRAME HEADER incomplete size=%d",
this, mInputFrameBufferUsed));
return rv;
}
// For both control and data frames the second 32 bit word of the header
// is 8-flags, 24-length. (network byte order)
mInputFrameDataSize =
PR_ntohl(reinterpret_cast<uint32_t *>(mInputFrameBuffer.get())[1]);
mInputFrameDataSize &= 0x00ffffff;
mInputFrameDataRead = 0;
if (mInputFrameBuffer[0] & kFlag_Control) {
EnsureBuffer(mInputFrameBuffer, mInputFrameDataSize + 8, 8,
mInputFrameBufferSize);
ChangeDownstreamState(BUFFERING_CONTROL_FRAME);
// The first 32 bit word of the header is
// 1 ctrl - 15 version - 16 type
uint16_t version =
PR_ntohs(reinterpret_cast<uint16_t *>(mInputFrameBuffer.get())[0]);
version &= 0x7fff;
mFrameControlType =
PR_ntohs(reinterpret_cast<uint16_t *>(mInputFrameBuffer.get())[1]);
LOG3(("SpdySession3::WriteSegments %p - Control Frame Identified "
"type %d version %d data len %d",
this, mFrameControlType, version, mInputFrameDataSize));
if (mFrameControlType >= CONTROL_TYPE_LAST ||
mFrameControlType <= CONTROL_TYPE_FIRST)
return NS_ERROR_ILLEGAL_VALUE;
if (version != kVersion)
return NS_ERROR_ILLEGAL_VALUE;
}
else {
ChangeDownstreamState(PROCESSING_DATA_FRAME);
Telemetry::Accumulate(Telemetry::SPDY_CHUNK_RECVD,
mInputFrameDataSize >> 10);
mLastDataReadEpoch = mLastReadEpoch;
uint32_t streamID =
PR_ntohl(reinterpret_cast<uint32_t *>(mInputFrameBuffer.get())[0]);
rv = SetInputFrameDataStream(streamID);
if (NS_FAILED(rv)) {
LOG(("SpdySession3::WriteSegments %p lookup streamID 0x%X failed. "
"probably due to verification.\n", this, streamID));
return rv;
}
if (!mInputFrameDataStream) {
LOG3(("SpdySession3::WriteSegments %p lookup streamID 0x%X failed. "
"Next = 0x%X", this, streamID, mNextStreamID));
if (streamID >= mNextStreamID)
GenerateRstStream(RST_INVALID_STREAM, streamID);
ChangeDownstreamState(DISCARDING_DATA_FRAME);
}
else if (mInputFrameDataStream->RecvdFin()) {
LOG3(("SpdySession3::WriteSegments %p streamID 0x%X "
"Data arrived for already server closed stream.\n",
this, streamID));
GenerateRstStream(RST_STREAM_ALREADY_CLOSED, streamID);
ChangeDownstreamState(DISCARDING_DATA_FRAME);
}
else if (!mInputFrameDataStream->RecvdData()) {
LOG3(("SpdySession3 %p First Data Frame Flushes Headers stream 0x%X\n",
this, streamID));
mInputFrameDataStream->SetRecvdData(true);
rv = ResponseHeadersComplete();
if (rv == NS_ERROR_ILLEGAL_VALUE) {
LOG3(("SpdySession3 %p PROTOCOL_ERROR detected 0x%X\n",
this, streamID));
CleanupStream(mInputFrameDataStream, rv, RST_PROTOCOL_ERROR);
ChangeDownstreamState(DISCARDING_DATA_FRAME);
}
else {
mDataPending = true;
}
}
mInputFrameDataLast = (mInputFrameBuffer[4] & kFlag_Data_FIN);
LOG3(("Start Processing Data Frame. "
"Session=%p Stream ID 0x%X Stream Ptr %p Fin=%d Len=%d",
this, streamID, mInputFrameDataStream, mInputFrameDataLast,
mInputFrameDataSize));
UpdateLocalRwin(mInputFrameDataStream, mInputFrameDataSize);
}
}
if (mDownstreamState == PROCESSING_CONTROL_RST_STREAM) {
if (mDownstreamRstReason == RST_REFUSED_STREAM)
rv = NS_ERROR_NET_RESET; //we can retry this 100% safely
else if (mDownstreamRstReason == RST_CANCEL ||
mDownstreamRstReason == RST_PROTOCOL_ERROR ||
mDownstreamRstReason == RST_INTERNAL_ERROR ||
mDownstreamRstReason == RST_UNSUPPORTED_VERSION)
rv = NS_ERROR_NET_INTERRUPT;
else if (mDownstreamRstReason == RST_FRAME_TOO_LARGE)
rv = NS_ERROR_FILE_TOO_BIG;
else
rv = NS_ERROR_ILLEGAL_VALUE;
if (mDownstreamRstReason != RST_REFUSED_STREAM &&
mDownstreamRstReason != RST_CANCEL)
mShouldGoAway = true;
// mInputFrameDataStream is reset by ChangeDownstreamState
SpdyStream3 *stream = mInputFrameDataStream;
ResetDownstreamState();
LOG3(("SpdySession3::WriteSegments cleanup stream on recv of rst "
"session=%p stream=%p 0x%X\n", this, stream,
stream ? stream->StreamID() : 0));
CleanupStream(stream, rv, RST_CANCEL);
return NS_OK;
}
if (mDownstreamState == PROCESSING_DATA_FRAME ||
mDownstreamState == PROCESSING_COMPLETE_HEADERS) {
// The cleanup stream should only be set while stream->WriteSegments is
// on the stack and then cleaned up in this code block afterwards.
MOZ_ASSERT(!mNeedsCleanup, "cleanup stream set unexpectedly");
mNeedsCleanup = nullptr; /* just in case */
mSegmentWriter = writer;
rv = mInputFrameDataStream->WriteSegments(this, count, countWritten);
mSegmentWriter = nullptr;
mLastDataReadEpoch = mLastReadEpoch;
if (rv == NS_BASE_STREAM_CLOSED) {
// This will happen when the transaction figures out it is EOF, generally
// due to a content-length match being made
SpdyStream3 *stream = mInputFrameDataStream;
// if we were doing PROCESSING_COMPLETE_HEADERS need to pop the state
// back to PROCESSING_DATA_FRAME where we came from
mDownstreamState = PROCESSING_DATA_FRAME;
if (mInputFrameDataRead == mInputFrameDataSize)
ResetDownstreamState();
LOG3(("SpdySession3::WriteSegments session=%p stream=%p 0x%X "
"needscleanup=%p. cleanup stream based on "
"stream->writeSegments returning BASE_STREAM_CLOSED\n",
this, stream, stream ? stream->StreamID() : 0,
mNeedsCleanup));
CleanupStream(stream, NS_OK, RST_CANCEL);
MOZ_ASSERT(!mNeedsCleanup, "double cleanup out of data frame");
mNeedsCleanup = nullptr; /* just in case */
return NS_OK;
}
if (mNeedsCleanup) {
LOG3(("SpdySession3::WriteSegments session=%p stream=%p 0x%X "
"cleanup stream based on mNeedsCleanup.\n",
this, mNeedsCleanup, mNeedsCleanup ? mNeedsCleanup->StreamID() : 0));
CleanupStream(mNeedsCleanup, NS_OK, RST_CANCEL);
mNeedsCleanup = nullptr;
}
if (NS_FAILED(rv)) {
LOG3(("SpdySession3 %p data frame read failure %x\n", this, rv));
// maybe just blocked reading from network
if (rv == NS_BASE_STREAM_WOULD_BLOCK)
rv = NS_OK;
}
return rv;
}
if (mDownstreamState == DISCARDING_DATA_FRAME) {
char trash[4096];
uint32_t count = std::min(4096U, mInputFrameDataSize - mInputFrameDataRead);
if (!count) {
ResetDownstreamState();
ResumeRecv();
return NS_BASE_STREAM_WOULD_BLOCK;
}
rv = NetworkRead(writer, trash, count, countWritten);
if (NS_FAILED(rv)) {
LOG3(("SpdySession3 %p discard frame read failure %x\n", this, rv));
// maybe just blocked reading from network
if (rv == NS_BASE_STREAM_WOULD_BLOCK)
rv = NS_OK;
return rv;
}
LogIO(this, nullptr, "Discarding Frame", trash, *countWritten);
mInputFrameDataRead += *countWritten;
if (mInputFrameDataRead == mInputFrameDataSize)
ResetDownstreamState();
return rv;
}
MOZ_ASSERT(mDownstreamState == BUFFERING_CONTROL_FRAME);
if (mDownstreamState != BUFFERING_CONTROL_FRAME) {
// this cannot happen
return NS_ERROR_UNEXPECTED;
}
MOZ_ASSERT(mInputFrameBufferUsed == 8,
"Frame Buffer Header Not Present");
rv = NetworkRead(writer, mInputFrameBuffer + 8 + mInputFrameDataRead,
mInputFrameDataSize - mInputFrameDataRead, countWritten);
if (NS_FAILED(rv)) {
LOG3(("SpdySession3 %p buffering control frame read failure %x\n",
this, rv));
// maybe just blocked reading from network
if (rv == NS_BASE_STREAM_WOULD_BLOCK)
rv = NS_OK;
return rv;
}
LogIO(this, nullptr, "Reading Control Frame",
mInputFrameBuffer + 8 + mInputFrameDataRead, *countWritten);
mInputFrameDataRead += *countWritten;
if (mInputFrameDataRead != mInputFrameDataSize)
return NS_OK;
// This check is actually redundant, the control type was previously
// checked to make sure it was in range, but we will check it again
// at time of use to make sure a regression doesn't creep in.
if (mFrameControlType >= CONTROL_TYPE_LAST ||
mFrameControlType <= CONTROL_TYPE_FIRST)
{
MOZ_ASSERT(false, "control type out of range");
return NS_ERROR_ILLEGAL_VALUE;
}
rv = sControlFunctions[mFrameControlType](this);
MOZ_ASSERT(NS_FAILED(rv) ||
mDownstreamState != BUFFERING_CONTROL_FRAME,
"Control Handler returned OK but did not change state");
if (mShouldGoAway && !mStreamTransactionHash.Count())
Close(NS_OK);
return rv;
}
void
SpdySession3::UpdateLocalRwin(SpdyStream3 *stream,
uint32_t bytes)
{
// If this data packet was not for a valid or live stream then there
// is no reason to mess with the flow control
if (!stream || stream->RecvdFin())
return;
stream->DecrementLocalWindow(bytes);
// Don't necessarily ack every data packet. Only do it
// after a significant amount of data.
uint64_t unacked = stream->LocalUnAcked();
int64_t localWindow = stream->LocalWindow();
LOG3(("SpdySession3::UpdateLocalRwin this=%p id=0x%X newbytes=%u "
"unacked=%llu localWindow=%lld\n",
this, stream->StreamID(), bytes, unacked, localWindow));
if (!unacked)
return;
if ((unacked < kMinimumToAck) && (localWindow > kEmergencyWindowThreshold))
return;
if (!stream->HasSink()) {
LOG3(("SpdySession3::UpdateLocalRwin %p 0x%X Pushed Stream Has No Sink\n",
this, stream->StreamID()));
return;
}
// Generate window updates directly out of spdysession instead of the stream
// in order to avoid queue delays in getting the 'ACK' out.
uint32_t toack = (unacked <= 0x7fffffffU) ? unacked : 0x7fffffffU;
LOG3(("SpdySession3::UpdateLocalRwin Ack this=%p id=0x%X acksize=%d\n",
this, stream->StreamID(), toack));
stream->IncrementLocalWindow(toack);
static const uint32_t dataLen = 8;
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + 8 + dataLen,
mOutputQueueUsed, mOutputQueueSize);
char *packet = mOutputQueueBuffer.get() + mOutputQueueUsed;
mOutputQueueUsed += 8 + dataLen;
memset(packet, 0, 8 + dataLen);
packet[0] = kFlag_Control;
packet[1] = kVersion;
packet[3] = CONTROL_TYPE_WINDOW_UPDATE;
packet[7] = dataLen;
uint32_t id = PR_htonl(stream->StreamID());
memcpy(packet + 8, &id, 4);
toack = PR_htonl(toack);
memcpy(packet + 12, &toack, 4);
LogIO(this, stream, "Window Update", packet, 8 + dataLen);
FlushOutputQueue();
}
void
SpdySession3::Close(nsresult aReason)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
if (mClosed)
return;
LOG3(("SpdySession3::Close %p %X", this, aReason));
mClosed = true;
mStreamTransactionHash.Enumerate(ShutdownEnumerator, this);
mStreamIDHash.Clear();
mStreamTransactionHash.Clear();
if (NS_SUCCEEDED(aReason))
GenerateGoAway(OK);
mConnection = nullptr;
mSegmentReader = nullptr;
mSegmentWriter = nullptr;
}
void
SpdySession3::CloseTransaction(nsAHttpTransaction *aTransaction,
nsresult aResult)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::CloseTransaction %p %p %x", this, aTransaction, aResult));
// Generally this arrives as a cancel event from the connection manager.
// need to find the stream and call CleanupStream() on it.
SpdyStream3 *stream = mStreamTransactionHash.Get(aTransaction);
if (!stream) {
LOG3(("SpdySession3::CloseTransaction %p %p %x - not found.",
this, aTransaction, aResult));
return;
}
LOG3(("SpdySession3::CloseTranscation probably a cancel. "
"this=%p, trans=%p, result=%x, streamID=0x%X stream=%p",
this, aTransaction, aResult, stream->StreamID(), stream));
CleanupStream(stream, aResult, RST_CANCEL);
ResumeRecv();
}
//-----------------------------------------------------------------------------
// nsAHttpSegmentReader
//-----------------------------------------------------------------------------
nsresult
SpdySession3::OnReadSegment(const char *buf,
uint32_t count,
uint32_t *countRead)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
nsresult rv;
// If we can release old queued data then we can try and write the new
// data directly to the network without using the output queue at all
if (mOutputQueueUsed)
FlushOutputQueue();
if (!mOutputQueueUsed && mSegmentReader) {
// try and write directly without output queue
rv = mSegmentReader->OnReadSegment(buf, count, countRead);
if (rv == NS_BASE_STREAM_WOULD_BLOCK)
*countRead = 0;
else if (NS_FAILED(rv))
return rv;
if (*countRead < count) {
uint32_t required = count - *countRead;
// assuming a commitment() happened, this ensurebuffer is a nop
// but just in case the queuesize is too small for the required data
// call ensurebuffer().
EnsureBuffer(mOutputQueueBuffer, required, 0, mOutputQueueSize);
memcpy(mOutputQueueBuffer.get(), buf + *countRead, required);
mOutputQueueUsed = required;
}
*countRead = count;
return NS_OK;
}
// At this point we are going to buffer the new data in the output
// queue if it fits. By coalescing multiple small submissions into one larger
// buffer we can get larger writes out to the network later on.
// This routine should not be allowed to fill up the output queue
// all on its own - at least kQueueReserved bytes are always left
// for other routines to use - but this is an all-or-nothing function,
// so if it will not all fit just return WOULD_BLOCK
if ((mOutputQueueUsed + count) > (mOutputQueueSize - kQueueReserved))
return NS_BASE_STREAM_WOULD_BLOCK;
memcpy(mOutputQueueBuffer.get() + mOutputQueueUsed, buf, count);
mOutputQueueUsed += count;
*countRead = count;
FlushOutputQueue();
return NS_OK;
}
nsresult
SpdySession3::CommitToSegmentSize(uint32_t count, bool forceCommitment)
{
if (mOutputQueueUsed)
FlushOutputQueue();
// would there be enough room to buffer this if needed?
if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved))
return NS_OK;
// if we are using part of our buffers already, try again later unless
// forceCommitment is set.
if (mOutputQueueUsed && !forceCommitment)
return NS_BASE_STREAM_WOULD_BLOCK;
if (mOutputQueueUsed) {
// normally we avoid the memmove of RealignOutputQueue, but we'll try
// it if forceCommitment is set before growing the buffer.
RealignOutputQueue();
// is there enough room now?
if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved))
return NS_OK;
}
// resize the buffers as needed
EnsureBuffer(mOutputQueueBuffer, mOutputQueueUsed + count + kQueueReserved,
mOutputQueueUsed, mOutputQueueSize);
MOZ_ASSERT((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved),
"buffer not as large as expected");
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsAHttpSegmentWriter
//-----------------------------------------------------------------------------
nsresult
SpdySession3::OnWriteSegment(char *buf,
uint32_t count,
uint32_t *countWritten)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
nsresult rv;
if (!mSegmentWriter) {
// the only way this could happen would be if Close() were called on the
// stack with WriteSegments()
return NS_ERROR_FAILURE;
}
if (mDownstreamState == PROCESSING_DATA_FRAME) {
if (mInputFrameDataLast &&
mInputFrameDataRead == mInputFrameDataSize) {
*countWritten = 0;
SetNeedsCleanup();
return NS_BASE_STREAM_CLOSED;
}
count = std::min(count, mInputFrameDataSize - mInputFrameDataRead);
rv = NetworkRead(mSegmentWriter, buf, count, countWritten);
if (NS_FAILED(rv))
return rv;
LogIO(this, mInputFrameDataStream, "Reading Data Frame",
buf, *countWritten);
mInputFrameDataRead += *countWritten;
mInputFrameDataStream->UpdateTransportReadEvents(*countWritten);
if ((mInputFrameDataRead == mInputFrameDataSize) && !mInputFrameDataLast)
ResetDownstreamState();
return rv;
}
if (mDownstreamState == PROCESSING_COMPLETE_HEADERS) {
if (mFlatHTTPResponseHeaders.Length() == mFlatHTTPResponseHeadersOut &&
mInputFrameDataLast) {
*countWritten = 0;
SetNeedsCleanup();
return NS_BASE_STREAM_CLOSED;
}
count = std::min(count,
mFlatHTTPResponseHeaders.Length() -
mFlatHTTPResponseHeadersOut);
memcpy(buf,
mFlatHTTPResponseHeaders.get() + mFlatHTTPResponseHeadersOut,
count);
mFlatHTTPResponseHeadersOut += count;
*countWritten = count;
if (mFlatHTTPResponseHeaders.Length() == mFlatHTTPResponseHeadersOut) {
if (mDataPending) {
// Now ready to process data frames - pop PROCESING_DATA_FRAME back onto
// the stack because receipt of that first data frame triggered the
// response header processing
mDataPending = false;
ChangeDownstreamState(PROCESSING_DATA_FRAME);
}
else if (!mInputFrameDataLast) {
// If more frames are expected in this stream, then reset the state so they can be
// handled. Otherwise (e.g. a 0 length response with the fin on the SYN_REPLY)
// stay in PROCESSING_COMPLETE_HEADERS state so the SetNeedsCleanup() code above can
// cleanup the stream.
ResetDownstreamState();
}
}
return NS_OK;
}
return NS_ERROR_UNEXPECTED;
}
void
SpdySession3::SetNeedsCleanup()
{
LOG3(("SpdySession3::SetNeedsCleanup %p - recorded downstream fin of "
"stream %p 0x%X", this, mInputFrameDataStream,
mInputFrameDataStream->StreamID()));
// This will result in Close() being called
MOZ_ASSERT(!mNeedsCleanup, "mNeedsCleanup unexpectedly set");
mNeedsCleanup = mInputFrameDataStream;
ResetDownstreamState();
}
void
SpdySession3::ConnectPushedStream(SpdyStream3 *stream)
{
mReadyForRead.Push(stream);
ForceRecv();
}
//-----------------------------------------------------------------------------
// Modified methods of nsAHttpConnection
//-----------------------------------------------------------------------------
void
SpdySession3::TransactionHasDataToWrite(nsAHttpTransaction *caller)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::TransactionHasDataToWrite %p trans=%p", this, caller));
// a trapped signal from the http transaction to the connection that
// it is no longer blocked on read.
SpdyStream3 *stream = mStreamTransactionHash.Get(caller);
if (!stream || !VerifyStream(stream)) {
LOG3(("SpdySession3::TransactionHasDataToWrite %p caller %p not found",
this, caller));
return;
}
LOG3(("SpdySession3::TransactionHasDataToWrite %p ID is 0x%X\n",
this, stream->StreamID()));
mReadyForWrite.Push(stream);
}
void
SpdySession3::TransactionHasDataToWrite(SpdyStream3 *stream)
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
LOG3(("SpdySession3::TransactionHasDataToWrite %p stream=%p ID=%x",
this, stream, stream->StreamID()));
mReadyForWrite.Push(stream);
SetWriteCallbacks();
}
bool
SpdySession3::IsPersistent()
{
return true;
}
nsresult
SpdySession3::TakeTransport(nsISocketTransport **,
nsIAsyncInputStream **,
nsIAsyncOutputStream **)
{
MOZ_ASSERT(false, "TakeTransport of SpdySession3");
return NS_ERROR_UNEXPECTED;
}
nsHttpConnection *
SpdySession3::TakeHttpConnection()
{
MOZ_ASSERT(false, "TakeHttpConnection of SpdySession3");
return nullptr;
}
uint32_t
SpdySession3::CancelPipeline(nsresult reason)
{
// we don't pipeline inside spdy, so this isn't an issue
return 0;
}
nsAHttpTransaction::Classifier
SpdySession3::Classification()
{
if (!mConnection)
return nsAHttpTransaction::CLASS_GENERAL;
return mConnection->Classification();
}
//-----------------------------------------------------------------------------
// unused methods of nsAHttpTransaction
// We can be sure of this because SpdySession3 is only constructed in
// nsHttpConnection and is never passed out of that object
//-----------------------------------------------------------------------------
void
SpdySession3::SetConnection(nsAHttpConnection *)
{
// This is unexpected
MOZ_ASSERT(false, "SpdySession3::SetConnection()");
}
void
SpdySession3::GetSecurityCallbacks(nsIInterfaceRequestor **)
{
// This is unexpected
MOZ_ASSERT(false, "SpdySession3::GetSecurityCallbacks()");
}
void
SpdySession3::SetProxyConnectFailed()
{
MOZ_ASSERT(false, "SpdySession3::SetProxyConnectFailed()");
}
bool
SpdySession3::IsDone()
{
return !mStreamTransactionHash.Count();
}
nsresult
SpdySession3::Status()
{
MOZ_ASSERT(false, "SpdySession3::Status()");
return NS_ERROR_UNEXPECTED;
}
uint32_t
SpdySession3::Caps()
{
MOZ_ASSERT(false, "SpdySession3::Caps()");
return 0;
}
uint64_t
SpdySession3::Available()
{
MOZ_ASSERT(false, "SpdySession3::Available()");
return 0;
}
nsHttpRequestHead *
SpdySession3::RequestHead()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
MOZ_ASSERT(false,
"SpdySession3::RequestHead() "
"should not be called after SPDY is setup");
return NULL;
}
uint32_t
SpdySession3::Http1xTransactionCount()
{
return 0;
}
// used as an enumerator by TakeSubTransactions()
static PLDHashOperator
TakeStream(nsAHttpTransaction *key,
nsAutoPtr<SpdyStream3> &stream,
void *closure)
{
nsTArray<nsRefPtr<nsAHttpTransaction> > *list =
static_cast<nsTArray<nsRefPtr<nsAHttpTransaction> > *>(closure);
list->AppendElement(key);
// removing the stream from the hash will delete the stream
// and drop the transaction reference the hash held
return PL_DHASH_REMOVE;
}
nsresult
SpdySession3::TakeSubTransactions(
nsTArray<nsRefPtr<nsAHttpTransaction> > &outTransactions)
{
// Generally this cannot be done with spdy as transactions are
// started right away.
LOG3(("SpdySession3::TakeSubTransactions %p\n", this));
if (mConcurrentHighWater > 0)
return NS_ERROR_ALREADY_OPENED;
LOG3((" taking %d\n", mStreamTransactionHash.Count()));
mStreamTransactionHash.Enumerate(TakeStream, &outTransactions);
return NS_OK;
}
nsresult
SpdySession3::AddTransaction(nsAHttpTransaction *)
{
// This API is meant for pipelining, SpdySession3's should be
// extended with AddStream()
MOZ_ASSERT(false,
"SpdySession3::AddTransaction() should not be called");
return NS_ERROR_NOT_IMPLEMENTED;
}
uint32_t
SpdySession3::PipelineDepth()
{
return IsDone() ? 0 : 1;
}
nsresult
SpdySession3::SetPipelinePosition(int32_t position)
{
// This API is meant for pipelining, SpdySession3's should be
// extended with AddStream()
MOZ_ASSERT(false,
"SpdySession3::SetPipelinePosition() should not be called");
return NS_ERROR_NOT_IMPLEMENTED;
}
int32_t
SpdySession3::PipelinePosition()
{
return 0;
}
//-----------------------------------------------------------------------------
// Pass through methods of nsAHttpConnection
//-----------------------------------------------------------------------------
nsAHttpConnection *
SpdySession3::Connection()
{
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
return mConnection;
}
nsresult
SpdySession3::OnHeadersAvailable(nsAHttpTransaction *transaction,
nsHttpRequestHead *requestHead,
nsHttpResponseHead *responseHead,
bool *reset)
{
return mConnection->OnHeadersAvailable(transaction,
requestHead,
responseHead,
reset);
}
bool
SpdySession3::IsReused()
{
return mConnection->IsReused();
}
nsresult
SpdySession3::PushBack(const char *buf, uint32_t len)
{
return mConnection->PushBack(buf, len);
}
} // namespace mozilla::net
} // namespace mozilla
|