1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659
|
/** @file
HTTP state machine
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "../ProxyTransaction.h"
#include "HttpSM.h"
#include "HttpTransact.h"
#include "HttpBodyFactory.h"
#include "HttpTransactHeaders.h"
#include "ProxyConfig.h"
#include "Http1ServerSession.h"
#include "HttpDebugNames.h"
#include "HttpSessionManager.h"
#include "P_Cache.h"
#include "P_Net.h"
#include "PreWarmConfig.h"
#include "PreWarmManager.h"
#include "StatPages.h"
#include "Log.h"
#include "LogAccess.h"
#include "PluginVC.h"
#include "ReverseProxy.h"
#include "RemapProcessor.h"
#include "Transform.h"
#include "P_SSLConfig.h"
#include "P_SSLSNI.h"
#include "HttpPages.h"
#include "IPAllow.h"
#include "ProxyProtocol.h"
#include "tscore/I_Layout.h"
#include "tscore/bwf_std_format.h"
#include "ts/sdt.h"
#include <openssl/ossl_typ.h>
#include <openssl/ssl.h>
#include <algorithm>
#include <atomic>
#include <logging/Log.h>
#define DEFAULT_RESPONSE_BUFFER_SIZE_INDEX 6 // 8K
#define DEFAULT_REQUEST_BUFFER_SIZE_INDEX 6 // 8K
#define MIN_CONFIG_BUFFER_SIZE_INDEX 5 // 4K
#define hsm_release_assert(EX) \
{ \
if (!(EX)) { \
this->dump_state_on_assert(); \
_ink_assert(#EX, __FILE__, __LINE__); \
} \
}
/*
* Comment this off if you don't
* want httpSM to use new_empty_MIOBuffer(..) call
*/
#define USE_NEW_EMPTY_MIOBUFFER
extern int cache_config_read_while_writer;
extern HttpBodyFactory *body_factory;
// We have a debugging list that can use to find stuck
// state machines
DList(HttpSM, debug_link) debug_sm_list;
ink_mutex debug_sm_list_mutex;
static const int sub_header_size = sizeof("Content-type: ") - 1 + 2 + sizeof("Content-range: bytes ") - 1 + 4;
static const int boundary_size = 2 + sizeof("RANGE_SEPARATOR") - 1 + 2;
static const char *str_100_continue_response = "HTTP/1.1 100 Continue\r\n\r\n";
static const int len_100_continue_response = strlen(str_100_continue_response);
// Handy typedef for short (single line) message generation.
using lbw = ts::LocalBufferWriter<256>;
namespace
{
// Unique state machine identifier
std::atomic<int64_t> next_sm_id(0);
/// Buffer for some error logs.
thread_local std::string error_bw_buffer;
/**
Outbound PROXY Protocol
Write PROXY Protocol to the first block of given MIOBuffer
FIXME: make @vc_in const
*/
int64_t
do_outbound_proxy_protocol(MIOBuffer *miob, NetVConnection *vc_out, NetVConnection *vc_in, int conf)
{
ink_release_assert(conf >= 0);
ProxyProtocol info = vc_in->get_proxy_protocol_info();
ProxyProtocolVersion pp_version = proxy_protocol_version_cast(conf);
if (info.version == ProxyProtocolVersion::UNDEFINED) {
if (conf == 0) {
// nothing to forward
return 0;
} else {
// set info from incoming NetVConnection
IpEndpoint local = vc_in->get_local_endpoint();
info = ProxyProtocol{pp_version, local.family(), local, vc_in->get_remote_endpoint()};
}
}
vc_out->set_proxy_protocol_info(info);
IOBufferBlock *block = miob->first_write_block();
size_t len = proxy_protocol_build(reinterpret_cast<uint8_t *>(block->buf()), block->write_avail(), info, pp_version);
if (len > 0) {
miob->fill(len);
}
return len;
}
} // namespace
ClassAllocator<HttpSM> httpSMAllocator("httpSMAllocator");
HttpVCTable::HttpVCTable(HttpSM *mysm)
{
memset(&vc_table, 0, sizeof(vc_table));
sm = mysm;
}
HttpVCTableEntry *
HttpVCTable::new_entry()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == nullptr) {
vc_table[i].sm = sm;
return vc_table + i;
}
}
ink_release_assert(0);
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VConnection *vc)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == vc) {
return vc_table + i;
}
}
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VIO *vio)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].read_vio == vio || vc_table[i].write_vio == vio) {
ink_assert(vc_table[i].vc != nullptr);
return vc_table + i;
}
}
return nullptr;
}
// bool HttpVCTable::remove_entry(HttpVCEntry* e)
//
// Deallocates all buffers from the associated
// entry and re-initializes it's other fields
// for reuse
//
void
HttpVCTable::remove_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc == nullptr || e->in_tunnel);
e->vc = nullptr;
e->eos = false;
if (e->read_buffer) {
free_MIOBuffer(e->read_buffer);
e->read_buffer = nullptr;
}
if (e->write_buffer) {
free_MIOBuffer(e->write_buffer);
e->write_buffer = nullptr;
}
// Cannot reach in to checkout the netvc
// for remaining I/O operations because the netvc
// may have been deleted at this point and the pointer
// could be stale.
e->read_vio = nullptr;
e->write_vio = nullptr;
e->vc_handler = nullptr;
e->vc_type = HTTP_UNKNOWN;
e->in_tunnel = false;
}
// bool HttpVCTable::cleanup_entry(HttpVCEntry* e)
//
// Closes the associate vc for the entry,
// and the call remove_entry
//
void
HttpVCTable::cleanup_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc);
if (e->in_tunnel == false) {
// Update stats
switch (e->vc_type) {
case HTTP_UA_VC:
// proxy.process.http.current_client_transactions is decremented in HttpSM::destroy
break;
default:
// This covers:
// HTTP_UNKNOWN, HTTP_SERVER_VC, HTTP_TRANSFORM_VC, HTTP_CACHE_READ_VC,
// HTTP_CACHE_WRITE_VC, HTTP_RAW_SERVER_VC
break;
}
if (e->vc_type == HTTP_SERVER_VC) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_cleanup_entry);
}
e->vc->do_io_close();
e->vc = nullptr;
}
remove_entry(e);
}
void
HttpVCTable::cleanup_all()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc != nullptr) {
cleanup_entry(vc_table + i);
}
}
}
#define SMDebug(tag, fmt, ...) SpecificDebug(debug_on, tag, "[%" PRId64 "] " fmt, sm_id, ##__VA_ARGS__)
#define REMEMBER(e, r) \
{ \
history.push_back(MakeSourceLocation(), e, r); \
}
#ifdef STATE_ENTER
#undef STATE_ENTER
#endif
#define STATE_ENTER(state_name, event) \
{ \
/*ink_assert (magic == HTTP_SM_MAGIC_ALIVE); */ REMEMBER(event, reentrancy_count); \
SMDebug("http", "[%s, %s]", #state_name, HttpDebugNames::get_event_name(event)); \
}
#define HTTP_SM_SET_DEFAULT_HANDLER(_h) \
{ \
REMEMBER(NO_EVENT, reentrancy_count); \
default_handler = _h; \
}
/*
* Helper functions to ensure that the parallel
* API set timeouts are set consistently with the records.config settings
*/
ink_hrtime
HttpSM::get_server_inactivity_timeout()
{
ink_hrtime retval = 0;
if (t_state.api_txn_no_activity_timeout_value != -1) {
retval = HRTIME_MSECONDS(t_state.api_txn_no_activity_timeout_value);
} else {
retval = HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out);
}
return retval;
}
ink_hrtime
HttpSM::get_server_active_timeout()
{
ink_hrtime retval = 0;
if (t_state.api_txn_active_timeout_value != -1) {
retval = HRTIME_MSECONDS(t_state.api_txn_active_timeout_value);
} else {
retval = HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out);
}
return retval;
}
ink_hrtime
HttpSM::get_server_connect_timeout()
{
ink_hrtime retval = 0;
if (t_state.api_txn_connect_timeout_value != -1) {
retval = HRTIME_MSECONDS(t_state.api_txn_connect_timeout_value);
} else {
int connect_timeout;
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
connect_timeout = t_state.txn_conf->post_connect_attempts_timeout;
} else if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.txn_conf->parent_connect_timeout;
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
retval = HRTIME_SECONDS(connect_timeout);
}
return retval;
}
HttpSM::HttpSM() : Continuation(nullptr), vc_table(this) {}
void
HttpSM::cleanup()
{
t_state.destroy();
api_hooks.clear();
http_parser_clear(&http_parser);
HttpConfig::release(t_state.http_config_param);
m_remap->release();
mutex.clear();
tunnel.mutex.clear();
cache_sm.mutex.clear();
transform_cache_sm.mutex.clear();
magic = HTTP_SM_MAGIC_DEAD;
debug_on = false;
if (_prewarm_sm) {
_prewarm_sm->destroy();
THREAD_FREE(_prewarm_sm, preWarmSMAllocator, this_ethread());
_prewarm_sm = nullptr;
}
}
void
HttpSM::destroy()
{
cleanup();
THREAD_FREE(this, httpSMAllocator, this_thread());
}
void
HttpSM::init(bool from_early_data)
{
milestones[TS_MILESTONE_SM_START] = ink_get_hrtime();
_from_early_data = from_early_data;
magic = HTTP_SM_MAGIC_ALIVE;
// Unique state machine identifier
sm_id = next_sm_id++;
t_state.state_machine_id = sm_id;
t_state.state_machine = this;
t_state.http_config_param = HttpConfig::acquire();
// Acquire a lease on the global remap / rewrite table (stupid global name ...)
m_remap = rewrite_table->acquire();
// Simply point to the global config for the time being, no need to copy this
// entire struct if nothing is going to change it.
t_state.txn_conf = &t_state.http_config_param->oride;
t_state.init();
http_parser_init(&http_parser);
// Added to skip dns if the document is in cache. DNS will be forced if there is a ip based ACL in
// cache control or parent.config or if the doc_in_cache_skip_dns is disabled or if http caching is disabled
// TODO: This probably doesn't honor this as a per-transaction overridable config.
t_state.force_dns = (ip_rule_in_CacheControlTable() || t_state.parent_params->parent_table->ipMatch ||
!(t_state.txn_conf->doc_in_cache_skip_dns) || !(t_state.txn_conf->cache_http));
SET_HANDLER(&HttpSM::main_handler);
// Remember where this SM is running so it gets returned correctly
this->setThreadAffinity(this_ethread());
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.push(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
}
void
HttpSM::set_ua_half_close_flag()
{
ua_txn->set_half_close_flag(true);
}
inline int
HttpSM::do_api_callout()
{
if (hooks_set) {
return do_api_callout_internal();
} else {
handle_api_return();
return 0;
}
}
int
HttpSM::state_add_to_list(int event, void * /* data ATS_UNUSED */)
{
// The list if for stat pages and general debugging
// The config variable exists mostly to allow us to
// measure an performance drop during benchmark runs
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_add_to_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = (static_cast<unsigned int>(sm_id) % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
// the client_vc`s timeout events can be triggered, so we should not
// reschedule the http_sm when the lock is not acquired.
// FIXME: the sm_list may miss some http_sms when the lock contention
if (lock.is_locked()) {
HttpSMList[bucket].sm_list.push(this);
}
}
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_START;
if (do_api_callout() < 0) {
// Didn't get the hook continuation lock. Clear the read and wait for next event
if (ua_entry->read_vio) {
// Seems like ua_entry->read_vio->disable(); should work, but that was
// not sufficient to stop the state machine from processing IO events until the
// TXN_START hooks had completed. Just set the number of bytes to read to 0
ua_entry->read_vio = ua_entry->vc->do_io_read(this, 0, nullptr);
}
return EVENT_CONT;
}
return EVENT_DONE;
}
int
HttpSM::state_remove_from_list(int event, void * /* data ATS_UNUSED */)
{
// The config parameters are guaranteed not change
// across the life of a transaction so it safe to
// check the config here and use it determine
// whether we need to strip ourselves off of the
// state page list
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_remove_from_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = (static_cast<unsigned int>(sm_id) % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
if (!lock.is_locked()) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remove_from_list);
mutex->thread_holding->schedule_in(this, HTTP_LIST_RETRY);
return EVENT_DONE;
}
HttpSMList[bucket].sm_list.remove(this);
}
// We're now ready to finish off the state machine
terminate_sm = true;
kill_this_async_done = true;
return EVENT_DONE;
}
void
HttpSM::start_sub_sm()
{
tunnel.init(this, mutex);
cache_sm.init(this, mutex);
transform_cache_sm.init(this, mutex);
}
void
HttpSM::attach_client_session(ProxyTransaction *client_vc)
{
milestones[TS_MILESTONE_UA_BEGIN] = ink_get_hrtime();
ink_assert(client_vc != nullptr);
NetVConnection *netvc = client_vc->get_netvc();
if (!netvc) {
return;
}
ua_txn = client_vc;
// It seems to be possible that the ua_txn pointer will go stale before log entries for this HTTP transaction are
// generated. Therefore, collect information that may be needed for logging from the ua_txn object at this point.
//
_client_transaction_id = ua_txn->get_transaction_id();
_client_transaction_priority_weight = ua_txn->get_transaction_priority_weight();
_client_transaction_priority_dependence = ua_txn->get_transaction_priority_dependence();
{
auto p = ua_txn->get_proxy_ssn();
if (p) {
_client_connection_id = p->connection_id();
}
}
// Collect log & stats information. We've already verified that the netvc is !nullptr above,
// and netvc == ua_txn->get_netvc().
is_internal = netvc->get_is_internal_request();
mptcp_state = netvc->get_mptcp_state();
client_tcp_reused = !(ua_txn->is_first_transaction());
if (auto tbs = dynamic_cast<TLSBasicSupport *>(netvc)) {
client_connection_is_ssl = true;
const char *protocol = tbs->get_tls_protocol_name();
client_sec_protocol = protocol ? protocol : "-";
const char *cipher = tbs->get_tls_cipher_suite();
client_cipher_suite = cipher ? cipher : "-";
const char *curve = tbs->get_tls_curve();
client_curve = curve ? curve : "-";
if (!client_tcp_reused) {
// Copy along the TLS handshake timings
milestones[TS_MILESTONE_TLS_HANDSHAKE_START] = tbs->get_tls_handshake_begin_time();
milestones[TS_MILESTONE_TLS_HANDSHAKE_END] = tbs->get_tls_handshake_end_time();
}
}
if (auto as = dynamic_cast<ALPNSupport *>(netvc)) {
client_alpn_id = as->get_negotiated_protocol_id();
}
if (auto tsrs = dynamic_cast<TLSSessionResumptionSupport *>(netvc)) {
client_ssl_reused = tsrs->getSSLSessionCacheHit();
}
const char *protocol_str = client_vc->get_protocol_string();
client_protocol = protocol_str ? protocol_str : "-";
ink_release_assert(ua_txn->get_half_close_flag() == false);
mutex = client_vc->mutex;
if (ua_txn->debug()) {
debug_on = true;
}
t_state.setup_per_txn_configs();
ink_assert(ua_txn->get_proxy_ssn());
ink_assert(ua_txn->get_proxy_ssn()->accept_options);
// default the upstream IP style host resolution order from inbound
t_state.my_txn_conf().host_res_data.order = ua_txn->get_proxy_ssn()->accept_options->host_res_preference;
start_sub_sm();
// Allocate a user agent entry in the state machine's
// vc table
ua_entry = vc_table.new_entry();
ua_entry->vc = client_vc;
ua_entry->vc_type = HTTP_UA_VC;
ats_ip_copy(&t_state.client_info.src_addr, netvc->get_remote_addr());
ats_ip_copy(&t_state.client_info.dst_addr, netvc->get_local_addr());
t_state.client_info.is_transparent = netvc->get_is_transparent();
t_state.client_info.port_attribute = static_cast<HttpProxyPort::TransportType>(netvc->attributes);
// Record api hook set state
hooks_set = client_vc->has_hooks();
// Setup for parsing the header
ua_entry->vc_handler = &HttpSM::state_read_client_request_header;
t_state.hdr_info.client_request.destroy();
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
// Prepare raw reader which will live until we are sure this is HTTP indeed
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
if (is_transparent_passthrough_allowed() || (ssl_vc && ssl_vc->decrypt_tunnel())) {
ua_raw_buffer_reader = ua_txn->get_remote_reader()->clone();
}
// We first need to run the transaction start hook. Since
// this hook maybe asynchronous, we need to disable IO on
// client but set the continuation to be the state machine
// so if we get an timeout events the sm handles them
// hold onto enabling read until setup_client_read_request_header
ua_entry->read_vio = client_vc->do_io_read(this, 0, nullptr);
ua_entry->write_vio = client_vc->do_io_write(this, 0, nullptr);
/////////////////////////
// set up timeouts //
/////////////////////////
client_vc->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
client_vc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_in));
++reentrancy_count;
// Add our state sm to the sm list
state_add_to_list(EVENT_NONE, nullptr);
// This is another external entry point and it is possible for the state machine to get terminated
// while down the call chain from @c state_add_to_list. So we need to use the reentrancy_count to
// prevent cleanup there and do it here as we return to the external caller.
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
--reentrancy_count;
ink_assert(reentrancy_count >= 0);
}
}
void
HttpSM::setup_client_read_request_header()
{
ink_assert(ua_entry->vc_handler == &HttpSM::state_read_client_request_header);
ua_entry->read_vio = ua_txn->do_io_read(this, INT64_MAX, ua_txn->get_remote_reader()->mbuf);
// The header may already be in the buffer if this
// a request from a keep-alive connection
handleEvent(VC_EVENT_READ_READY, ua_entry->read_vio);
}
void
HttpSM::setup_blind_tunnel_port()
{
NetVConnection *netvc = ua_txn->get_netvc();
ink_release_assert(netvc);
int host_len;
if (SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc)) {
if (!t_state.hdr_info.client_request.url_get()->host_get(&host_len)) {
// the URL object has not been created in the start of the transaction. Hence, we need to create the URL here
URL u;
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
t_state.hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
t_state.hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
t_state.hdr_info.client_request.url_set(&u);
if (ssl_vc->has_tunnel_destination()) {
const char *tunnel_host = ssl_vc->get_tunnel_host();
t_state.hdr_info.client_request.url_get()->host_set(tunnel_host, strlen(tunnel_host));
if (ssl_vc->get_tunnel_port() > 0) {
t_state.hdr_info.client_request.url_get()->port_set(ssl_vc->get_tunnel_port());
} else {
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
} else {
t_state.hdr_info.client_request.url_get()->host_set(ssl_vc->get_server_name(), strlen(ssl_vc->get_server_name()));
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
}
} else {
char new_host[INET6_ADDRSTRLEN];
ats_ip_ntop(netvc->get_local_addr(), new_host, sizeof(new_host));
t_state.hdr_info.client_request.url_get()->host_set(new_host, strlen(new_host));
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
call_transact_and_set_next_state(HttpTransact::HandleBlindTunnel);
}
int
HttpSM::state_read_client_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_client_request_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(server_entry == nullptr);
ink_assert(server_txn == nullptr);
int bytes_used = 0;
ink_assert(ua_entry->eos == false);
NetVConnection *netvc = ua_txn->get_netvc();
if (!netvc && event != VC_EVENT_EOS) {
return 0;
}
switch (event) {
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_EOS:
ua_entry->eos = true;
if ((client_request_hdr_bytes > 0) && is_transparent_passthrough_allowed() && (ua_raw_buffer_reader != nullptr)) {
break;
}
// Fall through
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Close it &
// bail on the state machine
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the accept timeout by the ProxyTransaction
//
if ((ua_txn->get_remote_reader()->read_avail() > 0) && (client_request_hdr_bytes == 0)) {
milestones[TS_MILESTONE_UA_FIRST_READ] = ink_get_hrtime();
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state = t_state.hdr_info.client_request.parse_req(
&http_parser, ua_txn->get_remote_reader(), &bytes_used, ua_entry->eos, t_state.http_config_param->strict_uri_parsing,
t_state.http_config_param->http_request_line_max_size, t_state.http_config_param->http_hdr_field_max_size);
client_request_hdr_bytes += bytes_used;
// Check to see if we are over the hdr size limit
if (client_request_hdr_bytes > t_state.txn_conf->request_hdr_max_size) {
SMDebug("http", "client header bytes were over max header size; treating as a bad request");
state = PARSE_RESULT_ERROR;
}
// We need to handle EOS as well as READ_READY because the client
// may have sent all of the data already followed by a FIN and that
// should be OK.
if (ua_raw_buffer_reader != nullptr) {
bool do_blind_tunnel = false;
// If we had a parse error and we're done reading data
// blind tunnel
if ((event == VC_EVENT_READ_READY || event == VC_EVENT_EOS) && state == PARSE_RESULT_ERROR) {
do_blind_tunnel = true;
// If we had a GET request that has data after the
// get request, do blind tunnel
} else if (state == PARSE_RESULT_DONE && t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET &&
ua_txn->get_remote_reader()->read_avail() > 0 && !t_state.hdr_info.client_request.is_keep_alive_set()) {
do_blind_tunnel = true;
}
if (do_blind_tunnel) {
SMDebug("http", "first request on connection failed parsing, switching to passthrough.");
t_state.transparent_passthrough = true;
http_parser_clear(&http_parser);
// Turn off read eventing until we get the
// blind tunnel infrastructure set up
if (netvc) {
netvc->do_io_read(nullptr, 0, nullptr);
}
/* establish blind tunnel */
setup_blind_tunnel_port();
// Setting half close means we will send the FIN when we've written all of the data.
if (event == VC_EVENT_EOS) {
this->set_ua_half_close_flag();
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
return 0;
}
}
// Check to see if we are done parsing the header
if (state != PARSE_RESULT_CONT || ua_entry->eos || (state == PARSE_RESULT_CONT && event == VC_EVENT_READ_COMPLETE)) {
if (ua_raw_buffer_reader != nullptr) {
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
http_parser_clear(&http_parser);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
milestones[TS_MILESTONE_UA_READ_HEADER_DONE] = ink_get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
SMDebug("http", "error parsing client request header");
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
(bytes_used > t_state.http_config_param->http_request_line_max_size) ?
t_state.http_return_code = HTTP_STATUS_REQUEST_URI_TOO_LONG :
t_state.http_return_code = HTTP_STATUS_NONE;
if (!is_http1_hdr_version_supported(t_state.hdr_info.client_request.version_get())) {
t_state.http_return_code = HTTP_STATUS_HTTPVER_NOT_SUPPORTED;
}
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
case PARSE_RESULT_CONT:
if (ua_entry->eos) {
SMDebug("http_seq", "EOS before client request parsing finished");
set_ua_abort(HttpTransact::ABORTED, event);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
} else if (event == VC_EVENT_READ_COMPLETE) {
SMDebug("http_parse", "VC_EVENT_READ_COMPLETE and PARSE CONT state");
break;
} else {
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr &&
ua_raw_buffer_reader->get_current_block()->write_avail() <= 0) {
// Disable passthrough regardless of eventual parsing failure or success -- otherwise
// we either have to consume some data or risk blocking the writer.
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
}
case PARSE_RESULT_DONE:
SMDebug("http", "done parsing client request header");
if (!t_state.hdr_info.client_request.check_hdr_implements()) {
t_state.http_return_code = HTTP_STATUS_NOT_IMPLEMENTED;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
}
if (!is_internal && t_state.http_config_param->scheme_proto_mismatch_policy != 0) {
auto scheme = t_state.hdr_info.client_request.url_get()->scheme_get_wksidx();
if ((client_connection_is_ssl && (scheme == URL_WKSIDX_HTTP || scheme == URL_WKSIDX_WS)) ||
(!client_connection_is_ssl && (scheme == URL_WKSIDX_HTTPS || scheme == URL_WKSIDX_WSS))) {
Warning("scheme [%s] vs. protocol [%s] mismatch", hdrtoken_index_to_wks(scheme),
client_connection_is_ssl ? "tls" : "plaintext");
if (t_state.http_config_param->scheme_proto_mismatch_policy == 2) {
t_state.http_return_code = HTTP_STATUS_BAD_REQUEST;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
}
}
}
if (_from_early_data) {
// Only allow early data for safe methods defined in RFC7231 Section 4.2.1.
// https://tools.ietf.org/html/rfc7231#section-4.2.1
SMDebug("ssl_early_data", "%d", t_state.hdr_info.client_request.method_get_wksidx());
if (!HttpTransactHeaders::is_method_safe(t_state.hdr_info.client_request.method_get_wksidx())) {
SMDebug("http", "client request was from early data but is NOT safe");
call_transact_and_set_next_state(HttpTransact::TooEarly);
return 0;
} else if (!SSLConfigParams::server_allow_early_data_params &&
(t_state.hdr_info.client_request.m_http->u.req.m_url_impl->m_len_params > 0 ||
t_state.hdr_info.client_request.m_http->u.req.m_url_impl->m_len_query > 0)) {
SMDebug("http", "client request was from early data but HAS parameters");
call_transact_and_set_next_state(HttpTransact::TooEarly);
return 0;
}
t_state.hdr_info.client_request.mark_early_data();
}
ua_txn->set_session_active();
if (t_state.hdr_info.client_request.version_get() == HTTP_1_1 &&
(t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_POST ||
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_PUT)) {
int len = 0;
const char *expect = t_state.hdr_info.client_request.value_get(MIME_FIELD_EXPECT, MIME_LEN_EXPECT, &len);
if ((len == HTTP_LEN_100_CONTINUE) && (strncasecmp(expect, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0)) {
// When receive an "Expect: 100-continue" request from client, ATS sends a "100 Continue" response to client
// immediately, before receive the real response from original server.
if (t_state.http_config_param->send_100_continue_response) {
int64_t alloc_index = buffer_size_to_index(len_100_continue_response, t_state.http_config_param->max_payload_iobuf_index);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = ua_entry->write_buffer->alloc_reader();
SMDebug("http_seq", "send 100 Continue response to client");
int64_t nbytes = ua_entry->write_buffer->write(str_100_continue_response, len_100_continue_response);
ua_entry->write_vio = ua_txn->do_io_write(this, nbytes, buf_start);
} else {
t_state.hdr_info.client_request.m_100_continue_required = true;
}
}
}
if (t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_PUSH &&
t_state.http_config_param->push_method_enabled == 0) {
SMDebug("http", "Rejecting PUSH request because push_method_enabled is 0.");
call_transact_and_set_next_state(HttpTransact::Forbidden);
return 0;
}
// Call to ensure the content-length and transfer_encoding elements in client_request are filled in
HttpTransact::set_client_request_state(&t_state, &t_state.hdr_info.client_request);
if (t_state.hdr_info.client_request.get_content_length() == 0 &&
t_state.client_info.transfer_encoding != HttpTransact::CHUNKED_ENCODING) {
// Enable further IO to watch for client aborts
ua_entry->read_vio->reenable();
} else if (t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_TRACE) {
// Trace with request body is not allowed
call_transact_and_set_next_state(HttpTransact::BadRequest);
return 0;
} else {
// Disable further I/O on the client since there could
// be body that we are tunneling POST/PUT/CONNECT or
// extension methods and we can't issue another
// another IO later for the body with a different buffer
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
call_transact_and_set_next_state(HttpTransact::ModifyRequest);
break;
default:
ink_assert(!"not reached");
}
return 0;
}
void
HttpSM::wait_for_full_body()
{
is_waiting_for_full_body = true;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
bool chunked = (t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING);
int64_t alloc_index;
HttpTunnelProducer *p = nullptr;
// content length is undefined, use default buffer size
if (t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL) {
alloc_index = static_cast<int>(t_state.txn_conf->default_buffer_size_index);
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > MAX_BUFFER_SIZE_INDEX) {
alloc_index = DEFAULT_REQUEST_BUFFER_SIZE_INDEX;
}
} else {
alloc_index = buffer_size_to_index(t_state.hdr_info.request_content_length, t_state.http_config_param->max_payload_iobuf_index);
}
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
this->_postbuf.init(post_buffer->clone_reader(buf_start));
// Note: Many browsers, Netscape and IE included send two extra
// bytes (CRLF) at the end of the post. We just ignore those
// bytes since the sending them is not spec
// Next order of business if copy the remaining data from the
// header buffer into new buffer
int64_t post_bytes = chunked ? INT64_MAX : t_state.hdr_info.request_content_length;
client_request_body_bytes =
post_buffer->write(ua_txn->get_remote_reader(), chunked ? ua_txn->get_remote_reader()->read_avail() : post_bytes);
ua_txn->get_remote_reader()->consume(client_request_body_bytes);
p = tunnel.add_producer(ua_entry->vc, post_bytes, buf_start, &HttpSM::tunnel_handler_post_ua, HT_BUFFER_READ, "ua post buffer");
if (chunked) {
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
tunnel.set_producer_chunking_action(p, 0, TCA_PASSTHRU_CHUNKED_CONTENT, drop_chunked_trailers);
}
ua_entry->in_tunnel = true;
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
tunnel.tunnel_run(p);
}
int
HttpSM::state_watch_for_client_abort(int event, void *data)
{
STATE_ENTER(&HttpSM::state_watch_for_client_abort, event);
ink_assert(ua_entry->read_vio == (VIO *)data || ua_entry->write_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_txn);
switch (event) {
/* EOS means that the client has initiated the connection shut down.
* Only half close the client connection so ATS can read additional
* data that may still be sent from the server and send it to the
* client.
*/
case VC_EVENT_EOS: {
// We got an early EOS. If the tunnal has cache writer, don't kill it for background fill.
NetVConnection *netvc = ua_txn->get_netvc();
if (ua_txn->allow_half_open() || tunnel.has_consumer_besides_client()) {
if (netvc) {
netvc->do_io_shutdown(IO_SHUTDOWN_READ);
}
ua_entry->eos = true;
} else {
ua_txn->do_io_close();
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
tunnel.kill_tunnel();
terminate_sm = true; // Just die already, the requester is gone
set_ua_abort(HttpTransact::ABORTED, event);
}
break;
}
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
if (tunnel.is_tunnel_active()) {
// Check to see if the user agent is part of the tunnel.
// If so forward the event to the tunnel. Otherwise,
// kill the tunnel and fallthrough to the case
// where the tunnel is not active
HttpTunnelConsumer *c = tunnel.get_consumer(ua_txn);
if (c && c->alive) {
SMDebug("http", "forwarding event %s to tunnel", HttpDebugNames::get_event_name(event));
tunnel.handleEvent(event, c->write_vio);
return 0;
} else {
tunnel.kill_tunnel();
}
}
// Disable further I/O on the client
if (ua_entry->read_vio) {
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
milestones[TS_MILESTONE_UA_CLOSE] = ink_get_hrtime();
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
break;
}
case VC_EVENT_READ_COMPLETE:
// XXX Work around for TS-1233.
case VC_EVENT_READ_READY:
// Ignore. Could be a pipelined request. We'll get to it
// when we finish the current transaction
break;
case VC_EVENT_WRITE_READY:
// 100-continue handler
ink_assert(t_state.hdr_info.client_request.m_100_continue_required || t_state.http_config_param->send_100_continue_response);
ua_entry->write_vio->reenable();
break;
case VC_EVENT_WRITE_COMPLETE:
// 100-continue handler
ink_assert(t_state.hdr_info.client_request.m_100_continue_required || t_state.http_config_param->send_100_continue_response);
if (ua_entry->write_buffer) {
ink_assert(ua_entry->write_vio && !ua_entry->write_vio->ntodo());
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::setup_push_read_response_header()
{
ink_assert(server_txn == nullptr);
ink_assert(server_entry == nullptr);
ink_assert(ua_txn != nullptr);
ink_assert(t_state.method == HTTP_WKSIDX_PUSH);
// Set the handler to read the pushed response hdr
ua_entry->vc_handler = &HttpSM::state_read_push_response_header;
// We record both the total payload size as
// client_request_body_bytes and the bytes for the individual
// pushed hdr and body components
pushed_response_hdr_bytes = 0;
client_request_body_bytes = 0;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
// We already done the READ when we read the client
// request header
ink_assert(ua_entry->read_vio);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
int resp_hdr_state = VC_EVENT_CONT;
if (ua_txn->get_remote_reader()->read_avail() > 0) {
if (ua_entry->eos) {
resp_hdr_state = state_read_push_response_header(VC_EVENT_EOS, ua_entry->read_vio);
} else {
resp_hdr_state = state_read_push_response_header(VC_EVENT_READ_READY, ua_entry->read_vio);
}
}
// It is possible that the entire PUSHed response header was already
// in the buffer. In this case we don't want to fire off any more
// IO since we are going to switch buffers when we go to tunnel to
// the cache
if (resp_hdr_state == VC_EVENT_CONT) {
ink_assert(ua_entry->eos == false);
ua_entry->read_vio = ua_txn->do_io_read(this, INT64_MAX, ua_txn->get_remote_reader()->mbuf);
}
}
int
HttpSM::state_read_push_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_push_response_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server == nullptr);
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Send an error
set_ua_abort(HttpTransact::ABORTED, event);
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
return 0;
}
int state = PARSE_RESULT_CONT;
while (ua_txn->get_remote_reader()->read_avail() && state == PARSE_RESULT_CONT) {
const char *start = ua_txn->get_remote_reader()->start();
const char *tmp = start;
int64_t data_size = ua_txn->get_remote_reader()->block_read_avail();
ink_assert(data_size >= 0);
/////////////////////
// tokenize header //
/////////////////////
state = t_state.hdr_info.server_response.parse_resp(&http_parser, &tmp, tmp + data_size,
false); // Only call w/ eof when data exhausted
int64_t bytes_used = tmp - start;
ink_release_assert(bytes_used <= data_size);
ua_txn->get_remote_reader()->consume(bytes_used);
pushed_response_hdr_bytes += bytes_used;
client_request_body_bytes += bytes_used;
}
// We are out of data. If we've received an EOS we need to
// call the parser with (eof == true) so it can determine
// whether to use the response as is or declare a parse error
if (ua_entry->eos) {
const char *end = ua_txn->get_remote_reader()->start();
state = t_state.hdr_info.server_response.parse_resp(&http_parser, &end, end, true // We are out of data after server eos
);
ink_release_assert(state == PARSE_RESULT_DONE || state == PARSE_RESULT_ERROR);
}
// Don't allow 0.9 (unparsable headers) since TS doesn't
// cache 0.9 responses
if (state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTP_0_9) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = ink_get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
SMDebug("http", "error parsing push response header");
call_transact_and_set_next_state(HttpTransact::HandleBadPushRespHdr);
break;
case PARSE_RESULT_CONT:
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
case PARSE_RESULT_DONE:
SMDebug("http", "done parsing push response header");
call_transact_and_set_next_state(HttpTransact::HandlePushResponseHdr);
break;
default:
ink_assert(!"not reached");
}
return VC_EVENT_DONE;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_raw_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_raw_http_server_open(int event, void *data)
{
STATE_ENTER(&HttpSM::state_raw_http_server_open, event);
ink_assert(server_entry == nullptr);
milestones[TS_MILESTONE_SERVER_CONNECT_END] = ink_get_hrtime();
NetVConnection *netvc = nullptr;
pending_action = nullptr;
switch (event) {
case EVENT_INTERVAL:
// If we get EVENT_INTERNAL it means that we moved the transaction
// to a different thread in do_http_server_open. Since we didn't
// do any of the actual work in do_http_server_open, we have to
// go back and do it now.
do_http_server_open(true);
return 0;
case NET_EVENT_OPEN: {
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = netvc = static_cast<NetVConnection *>(data);
server_entry->vc_type = HTTP_RAW_SERVER_VC;
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
ats_ip_copy(&t_state.server_info.src_addr, netvc->get_local_addr());
netvc->set_inactivity_timeout(get_server_inactivity_timeout());
netvc->set_active_timeout(get_server_active_timeout());
t_state.current.server->clear_connect_fail();
if (get_tunnel_type() != SNIRoutingType::NONE) {
tunnel.mark_tls_tunnel_active();
}
break;
}
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED:
t_state.current.state = HttpTransact::OPEN_RAW_ERROR;
// use this value just to get around other values
t_state.hdr_info.response_error = HttpTransact::STATUS_CODE_SERVER_ERROR;
break;
default:
ink_release_assert(0);
break;
}
call_transact_and_set_next_state(HttpTransact::OriginServerRawOpen);
return 0;
}
// int HttpSM::state_request_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// server request header
//
int
HttpSM::state_request_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_request_wait_for_transform_read, event);
int64_t size;
switch (event) {
case TRANSFORM_READ_READY:
size = *(static_cast<int64_t *>(data));
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal
// data as well as fix up the request header
t_state.hdr_info.transform_request_cl = size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
setup_server_send_request_api();
break;
} else {
// No content length from the post. This is a no go
// since http spec requires content length when
// sending a request message body. Change the event
// to an error and fall through
event = VC_EVENT_ERROR;
Log::error("Request transformation failed to set content length");
}
// FALLTHROUGH
default:
state_common_wait_for_transform_read(&post_transform_info, &HttpSM::tunnel_handler_post, event, data);
break;
}
return 0;
}
// int HttpSM::state_response_wait_for_transform_read(int event, void* data)
//
// We've done a successful transform open and issued a do_io_write
// to the transform. We are now ready for the transform to tell
// us it is now ready to be read from and it done modifying the
// user agent response header
//
int
HttpSM::state_response_wait_for_transform_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_response_wait_for_transform_read, event);
int64_t size = *(static_cast<int64_t *>(data));
switch (event) {
case TRANSFORM_READ_READY:
if (size != INT64_MAX && size >= 0) {
// We got a content length so update our internal state
t_state.hdr_info.transform_response_cl = size;
t_state.hdr_info.transform_response.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, size);
} else {
t_state.hdr_info.transform_response_cl = HTTP_UNDEFINED_CL;
}
call_transact_and_set_next_state(HttpTransact::handle_transform_ready);
break;
default:
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
break;
}
return 0;
}
// int HttpSM::state_common_wait_for_transform_read(...)
//
// This function handles the overlapping cases between request and response
// transforms which prevents code duplication
//
int
HttpSM::state_common_wait_for_transform_read(HttpTransformInfo *t_info, HttpSMHandler tunnel_handler, int event, void *data)
{
STATE_ENTER(&HttpSM::state_common_wait_for_transform_read, event);
HttpTunnelConsumer *c = nullptr;
switch (event) {
case HTTP_TUNNEL_EVENT_DONE:
// There are three reasons why the tunnel could signal completed
// 1) there was error from the transform write
// 2) there was an error from the data source
// 3) the transform write completed before it sent
// TRANSFORM_READ_READY which is legal and in which
// case we should just wait for the transform read ready
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
ink_assert(c->vc == t_info->entry->vc);
if (c->handler_state == HTTP_SM_TRANSFORM_FAIL) {
// Case 1 we failed to complete the write to the
// transform fall through to vc event error case
ink_assert(c->write_success == false);
} else if (c->producer->read_success == false) {
// Case 2 - error from data source
if (c->producer->vc_type == HT_HTTP_CLIENT) {
// Our source is the client. POST can't
// be truncated so forward to the tunnel
// handler to clean this mess up
ink_assert(t_info == &post_transform_info);
return (this->*tunnel_handler)(event, data);
} else {
// On the response side, we just forward as much
// as we can of truncated documents so
// just don't cache the result
ink_assert(t_info == &transform_info);
t_state.api_info.cache_transformed = false;
return 0;
}
} else {
// Case 3 - wait for transform read ready
return 0;
}
// FALLTHROUGH
case VC_EVENT_ERROR:
// Transform VC sends NULL on error conditions
if (!c) {
c = tunnel.get_consumer(t_info->vc);
ink_assert(c != nullptr);
}
vc_table.cleanup_entry(t_info->entry);
t_info->entry = nullptr;
// In Case 1: error due to transform write,
// we need to keep the original t_info->vc for transform_cleanup()
// to skip do_io_close(); otherwise, set it to NULL.
if (c->handler_state != HTTP_SM_TRANSFORM_FAIL) {
t_info->vc = nullptr;
}
if (c->producer->vc_type == HT_HTTP_CLIENT) {
/* Producer was the user agent and there was a failure transforming the POST.
Handling this is challenging and this isn't the best way but it at least
avoids a crash due to trying to send a response to a NULL'd out user agent.
The problem with not closing the user agent is handling draining of the
rest of the POST - the user agent may well not check for a response until that's
done in which case we can get a deadlock where the user agent never reads the
error response because the POST wasn't drained and the buffers filled up.
Draining has a potential bad impact on any pipelining which must be considered.
If we're not going to drain properly the next best choice is to shut down the
entire state machine since (1) there's no point in finishing the POST to the
origin and (2) there's no user agent connection to which to send the error response.
*/
terminate_sm = true;
} else {
tunnel.kill_tunnel();
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
break;
default:
ink_release_assert(0);
}
return 0;
}
// int HttpSM::state_api_callback(int event, void *data)
// InkAPI.cc calls us directly here to avoid problems
// with setting and changing the default_handler
// function. As such, this is an entry point
// and needs to handle the reentrancy counter and
// deallocation of the state machine if necessary
//
int
HttpSM::state_api_callback(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
this->milestone_update_api_time();
STATE_ENTER(&HttpSM::state_api_callback, event);
state_api_callout(event, data);
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return VC_EVENT_CONT;
}
int
HttpSM::state_api_callout(int event, void *data)
{
// enum and variable for figuring out what the next action is after
// after we've finished the api state
enum AfterApiReturn_t {
API_RETURN_UNKNOWN = 0,
API_RETURN_CONTINUE,
API_RETURN_DEFERED_CLOSE,
API_RETURN_DEFERED_SERVER_ERROR,
API_RETURN_ERROR_JUMP,
API_RETURN_SHUTDOWN,
API_RETURN_INVALIDATE_ERROR
};
AfterApiReturn_t api_next = API_RETURN_UNKNOWN;
if (event != EVENT_NONE) {
STATE_ENTER(&HttpSM::state_api_callout, event);
}
if (api_timer < 0) {
// This happens when either the plugin lock was missed and the hook rescheduled or
// the transaction got an event without the plugin calling TsHttpTxnReenable().
// The call chain does not recurse here if @a api_timer < 0 which means this call
// is the first from an event dispatch in this case.
this->milestone_update_api_time();
}
switch (event) {
case HTTP_TUNNEL_EVENT_DONE:
// This is a reschedule via the tunnel. Just fall through
//
case EVENT_INTERVAL:
if (data != pending_action) {
pending_action->cancel();
}
pending_action = nullptr;
// FALLTHROUGH
case EVENT_NONE:
if (cur_hook_id == TS_HTTP_TXN_START_HOOK && t_state.client_info.port_attribute == HttpProxyPort::TRANSPORT_BLIND_TUNNEL) {
/* Creating the request object early to set the host header and port for blind tunneling here for the
plugins required to work with sni_routing.
*/
// Plugins triggered on txn_start_hook will get the host and port at that point
// We've received a request on a port which we blind forward
URL u;
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
t_state.hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
t_state.hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
t_state.hdr_info.client_request.url_set(&u);
NetVConnection *netvc = ua_txn->get_netvc();
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
if (ssl_vc && ssl_vc->has_tunnel_destination()) {
const char *tunnel_host = ssl_vc->get_tunnel_host();
t_state.hdr_info.client_request.url_get()->host_set(tunnel_host, strlen(tunnel_host));
ushort tunnel_port = ssl_vc->get_tunnel_port();
if (tunnel_port > 0) {
t_state.hdr_info.client_request.url_get()->port_set(tunnel_port);
} else {
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
} else if (ssl_vc) {
t_state.hdr_info.client_request.url_get()->host_set(ssl_vc->get_server_name(), strlen(ssl_vc->get_server_name()));
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
}
// FALLTHROUGH
case HTTP_API_CONTINUE:
if (nullptr == cur_hook) {
cur_hook = hook_state.getNext();
}
if (cur_hook) {
if (callout_state == HTTP_API_NO_CALLOUT) {
callout_state = HTTP_API_IN_CALLOUT;
}
WEAK_MUTEX_TRY_LOCK(lock, cur_hook->m_cont->mutex, mutex->thread_holding);
// Have a mutex but didn't get the lock, reschedule
if (!lock.is_locked()) {
api_timer = -ink_get_hrtime();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_api_callout);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
return -1;
}
SMDebug("http", "calling plugin on hook %s at hook %p", HttpDebugNames::get_api_hook_name(cur_hook_id), cur_hook);
APIHook const *hook = cur_hook;
// Need to delay the next hook update until after this hook is called to handle dynamic
// callback manipulation. cur_hook isn't needed to track state (in hook_state).
cur_hook = nullptr;
if (!api_timer) {
api_timer = ink_get_hrtime();
}
hook->invoke(TS_EVENT_HTTP_READ_REQUEST_HDR + cur_hook_id, this);
if (api_timer > 0) { // true if the hook did not call TxnReenable()
this->milestone_update_api_time();
api_timer = -ink_get_hrtime(); // set in order to track non-active callout duration
// which means that if we get back from the invoke with api_timer < 0 we're already
// tracking a non-complete callout from a chain so just let it ride. It will get cleaned
// up in state_api_callback when the plugin re-enables this transaction.
}
return 0;
}
// Map the callout state into api_next
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
case HTTP_API_IN_CALLOUT:
if (t_state.api_modifiable_cached_resp && t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE;
}
api_next = API_RETURN_CONTINUE;
break;
case HTTP_API_DEFERED_CLOSE:
api_next = API_RETURN_DEFERED_CLOSE;
break;
case HTTP_API_DEFERED_SERVER_ERROR:
api_next = API_RETURN_DEFERED_SERVER_ERROR;
break;
case HTTP_API_REWIND_STATE_MACHINE:
SMDebug("http", "REWIND");
callout_state = HTTP_API_NO_CALLOUT;
set_next_state();
return 0;
default:
ink_release_assert(0);
}
break;
case HTTP_API_ERROR:
if (callout_state == HTTP_API_DEFERED_CLOSE) {
api_next = API_RETURN_DEFERED_CLOSE;
} else if (cur_hook_id == TS_HTTP_TXN_CLOSE_HOOK) {
// If we are closing the state machine, we can't
// jump to an error state so just continue
api_next = API_RETURN_CONTINUE;
} else if (t_state.api_http_sm_shutdown) {
t_state.api_http_sm_shutdown = false;
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
transform_cache_sm.close_read();
release_server_session();
terminate_sm = true;
api_next = API_RETURN_SHUTDOWN;
t_state.squid_codes.log_code = SQUID_LOG_TCP_DENIED;
} else if (t_state.api_modifiable_cached_resp &&
t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_ERROR;
api_next = API_RETURN_INVALIDATE_ERROR;
} else {
api_next = API_RETURN_ERROR_JUMP;
}
break;
default:
ink_assert(false);
terminate_sm = true;
return 0;
}
// Now that we're completed with the api state and figured out what
// to do next, do it
callout_state = HTTP_API_NO_CALLOUT;
api_timer = 0;
switch (api_next) {
case API_RETURN_CONTINUE:
handle_api_return();
break;
case API_RETURN_DEFERED_CLOSE:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SM_SHUTDOWN);
do_api_callout();
break;
case API_RETURN_DEFERED_SERVER_ERROR:
ink_assert(t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR);
ink_assert(t_state.current.state != HttpTransact::CONNECTION_ALIVE);
call_transact_and_set_next_state(HttpTransact::HandleResponse);
break;
case API_RETURN_ERROR_JUMP:
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
break;
case API_RETURN_SHUTDOWN:
break;
case API_RETURN_INVALIDATE_ERROR:
do_cache_prepare_update();
break;
default:
case API_RETURN_UNKNOWN:
ink_release_assert(0);
}
return 0;
}
// void HttpSM::handle_api_return()
//
// Figures out what to do after calling api callouts
// have finished. This messy and I would like
// to come up with a cleaner way to handle the api
// return. The way we are doing things also makes a
// mess of set_next_state()
//
void
HttpSM::handle_api_return()
{
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START: {
NetVConnection *netvc = ua_txn->get_netvc();
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
bool forward_dest = ssl_vc != nullptr && ssl_vc->decrypt_tunnel();
if (t_state.client_info.port_attribute == HttpProxyPort::TRANSPORT_BLIND_TUNNEL || forward_dest) {
setup_blind_tunnel_port();
} else {
setup_client_read_request_header();
}
return;
}
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
if (t_state.api_cleanup_cache_read && t_state.api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_PREPARE) {
t_state.api_cleanup_cache_read = false;
t_state.cache_info.object_read = nullptr;
t_state.request_sent_time = UNDEFINED_TIME;
t_state.response_received_time = UNDEFINED_TIME;
cache_sm.close_read();
transform_cache_sm.close_read();
}
// fallthrough
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_REQUEST_BUFFER_READ_COMPLETE:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
call_transact_and_set_next_state(nullptr);
return;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
setup_server_send_request();
return;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
// Set back the inactivity timeout
if (ua_txn) {
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
// We only follow 3xx when redirect_in_process == false. Otherwise the redirection has already been launched (in
// SM_ACTION_SERVER_READ).redirect_in_process is set before this logic if we need more direction.
// This redirection is only used with the build_error_response. Then, the redirection_tries will be increased by
// state_read_server_response_header and never get into this logic again.
if (enable_redirection && !t_state.redirect_info.redirect_in_process && is_redirect_required()) {
do_redirect();
}
// we have further processing to do
// based on what t_state.next_action is
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
state_remove_from_list(EVENT_NONE, nullptr);
return;
default:
ink_release_assert(!"Not reached");
break;
}
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
HttpTunnelProducer *p = setup_transfer_from_transform();
perform_transform_cache_write_action();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
if (unlikely(t_state.did_upgrade_succeed)) {
// We've successfully handled the upgrade, let's now setup
// a blind tunnel.
IOBufferReader *initial_data = nullptr;
if (t_state.is_websocket) {
HTTP_INCREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
if (server_txn) {
initial_data = server_txn->get_remote_reader();
}
if (ua_txn) {
SMDebug("http_websocket",
"(client session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
ua_txn->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
if (server_txn) {
SMDebug("http_websocket",
"(server session) Setting websocket active timeout=%" PRId64 "s and inactive timeout=%" PRId64 "s",
t_state.txn_conf->websocket_active_timeout, t_state.txn_conf->websocket_inactive_timeout);
server_txn->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_active_timeout));
server_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->websocket_inactive_timeout));
}
}
setup_blind_tunnel(true, initial_data);
} else {
HttpTunnelProducer *p = setup_server_transfer();
perform_cache_write_action();
tunnel.tunnel_run(p);
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
HttpTunnelProducer *p = setup_cache_read_transfer();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
if (cache_sm.cache_write_vc) {
setup_internal_transfer(&HttpSM::tunnel_handler_cache_fill);
} else {
setup_internal_transfer(&HttpSM::tunnel_handler);
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE:
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS:
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_internal_transfer(&HttpSM::tunnel_handler);
break;
}
case HttpTransact::SM_ACTION_REDIRECT_READ: {
// Clean up from any communication with previous servers
release_server_session();
call_transact_and_set_next_state(HttpTransact::HandleRequest);
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
setup_blind_tunnel(true);
break;
}
default: {
ink_release_assert(!"Should not get here");
}
}
}
PoolableSession *
HttpSM::create_server_session(NetVConnection *netvc)
{
HttpTransact::State &s = this->t_state;
PoolableSession *retval = httpServerSessionAllocator.alloc();
retval->sharing_pool = static_cast<TSServerSessionSharingPoolType>(s.http_config_param->server_session_sharing_pool);
retval->sharing_match = static_cast<TSServerSessionSharingMatchMask>(s.txn_conf->server_session_sharing_match);
MIOBuffer *netvc_read_buffer = new_MIOBuffer(HTTP_SERVER_RESP_HDR_BUFFER_INDEX);
IOBufferReader *netvc_reader = netvc_read_buffer->alloc_reader();
retval->new_connection(netvc, netvc_read_buffer, netvc_reader);
retval->attach_hostname(s.current.server->name);
ATS_PROBE1(new_origin_server_connection, s.current.server->name);
retval->set_active();
if (netvc) {
ats_ip_copy(&s.server_info.src_addr, netvc->get_local_addr());
}
// If origin_max_connections or origin_min_keep_alive_connections is set then we are metering
// the max and or min number of connections per host. Transfer responsibility for this to the
// session object.
if (s.outbound_conn_track_state.is_active()) {
SMDebug("http_connect", "max number of outbound connections: %d", s.txn_conf->outbound_conntrack.max);
retval->enable_outbound_connection_tracking(s.outbound_conn_track_state.drop());
}
return retval;
}
bool
HttpSM::create_server_txn(PoolableSession *new_session)
{
bool retval = false;
server_txn = new_session->new_transaction();
if (server_txn != nullptr) {
server_txn->attach_transaction(this);
server_txn->do_io_write(this, 0, nullptr);
attach_server_session();
retval = true;
}
return retval;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_http_server_open()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_http_server_open(int event, void *data)
{
SMDebug("http_track", "entered inside state_http_server_open: %s", HttpDebugNames::get_event_name(event));
STATE_ENTER(&HttpSM::state_http_server_open, event);
ink_release_assert(event == EVENT_INTERVAL || event == NET_EVENT_OPEN || event == NET_EVENT_OPEN_FAILED ||
pending_action == nullptr);
if (event != NET_EVENT_OPEN) {
pending_action = nullptr;
}
milestones[TS_MILESTONE_SERVER_CONNECT_END] = ink_get_hrtime();
switch (event) {
case NET_EVENT_OPEN: {
NetVConnection *netvc = static_cast<NetVConnection *>(data);
UnixNetVConnection *vc = static_cast<UnixNetVConnection *>(data);
PoolableSession *new_session = this->create_server_session(netvc);
if (t_state.current.request_to == HttpTransact::PARENT_PROXY) {
new_session->to_parent_proxy = true;
HTTP_INCREMENT_DYN_STAT(http_current_parent_proxy_connections_stat);
HTTP_INCREMENT_DYN_STAT(http_total_parent_proxy_connections_stat);
} else {
new_session->to_parent_proxy = false;
}
this->create_server_txn(new_session);
// Since the UnixNetVConnection::action_ or SocksEntry::action_ may be returned from netProcessor.connect_re, and the
// SocksEntry::action_ will be copied into UnixNetVConnection::action_ before call back NET_EVENT_OPEN from SocksEntry::free(),
// so we just compare the Continuation between pending_action and VC's action_.
ink_release_assert(pending_action == nullptr || pending_action->continuation == vc->get_action()->continuation);
pending_action = nullptr;
if (this->plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
SMDebug("http", "setting handler for TCP handshake");
// Just want to get a write-ready event so we know that the TCP handshake is complete.
server_entry->vc_handler = &HttpSM::state_http_server_open;
int64_t nbytes = 1;
if (t_state.txn_conf->proxy_protocol_out >= 0) {
nbytes = do_outbound_proxy_protocol(server_txn->get_remote_reader()->mbuf, vc, ua_txn->get_netvc(),
t_state.txn_conf->proxy_protocol_out);
}
server_entry->write_vio = server_txn->do_io_write(this, nbytes, server_txn->get_remote_reader());
} else { // in the case of an intercept plugin don't to the connect timeout change
SMDebug("http", "not setting handler for TCP handshake");
handle_http_server_open();
}
return 0;
}
case VC_EVENT_READ_COMPLETE:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
// Update the time out to the regular connection timeout.
SMDebug("http_ss", "TCP Handshake complete");
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
// Reset the timeout to the non-connect timeout
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
t_state.current.server->clear_connect_fail();
handle_http_server_open();
return 0;
case EVENT_INTERVAL: // Delayed call from another thread
if (server_txn == nullptr) {
do_http_server_open();
}
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.set_connect_fail(ETIMEDOUT);
/* fallthrough */
case VC_EVENT_ERROR:
case NET_EVENT_OPEN_FAILED: {
if (server_txn) {
NetVConnection *vc = server_txn->get_netvc();
if (vc) {
t_state.set_connect_fail(vc->lerrno);
server_connection_provided_cert = vc->provided_cert();
}
}
t_state.current.state = HttpTransact::CONNECTION_ERROR;
t_state.outbound_conn_track_state.clear();
/* If we get this error in transparent mode, then we simply can't bind to the 4-tuple to make the connection. There's no hope
of retries succeeding in the near future. The best option is to just shut down the connection without further comment. The
only known cause for this is outbound transparency combined with use client target address / source port, as noted in
TS-1424. If the keep alives desync the current connection can be attempting to rebind the 4 tuple simultaneously with the
shut down of an existing connection. Dropping the client side will cause it to pick a new source port and recover from this
issue.
*/
if (EADDRNOTAVAIL == t_state.current.server->connect_result && t_state.client_info.is_transparent) {
if (is_debug_tag_set("http_tproxy")) {
ip_port_text_buffer ip_c, ip_s;
SMDebug("http_tproxy", "Force close of client connect (%s->%s) due to EADDRNOTAVAIL",
ats_ip_nptop(&t_state.client_info.src_addr.sa, ip_c, sizeof ip_c),
ats_ip_nptop(&t_state.server_info.dst_addr.sa, ip_s, sizeof ip_s));
}
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE; // part of the problem, clear it.
terminate_sm = true;
} else if (ENET_THROTTLING == t_state.current.server->connect_result) {
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
} else {
// Go ahead and release the failed server session. Since it didn't receive a response, the release logic will
// see that it didn't get a valid response and it will close it rather than returning it to the server session pool
release_server_session();
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
return 0;
}
default:
Error("[HttpSM::state_http_server_open] Unknown event: %d", event);
ink_release_assert(0);
return 0;
}
return 0;
}
int
HttpSM::state_read_server_response_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_server_response_header, event);
// If we had already received EOS, just go away. We would sometimes see
// a WRITE event appear after receiving EOS from the server connection
if (server_entry->eos) {
return 0;
} else if (data == server_entry->write_vio) {
return this->state_send_server_request_header(event, data);
}
ink_assert(server_entry->eos != true);
ink_assert(server_entry->read_vio == (VIO *)data);
ink_assert(t_state.current.server->state == HttpTransact::STATE_UNDEFINED);
ink_assert(t_state.current.state == HttpTransact::STATE_UNDEFINED);
int bytes_used = 0;
switch (event) {
case VC_EVENT_EOS:
server_entry->eos = true;
// Fall through
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// Error handling function
handle_server_setup_error(event, data);
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the connect timeout when we set up to read the header
//
if (server_response_hdr_bytes == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_READ] = ink_get_hrtime();
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
// For requests that contain a body, we can cancel the ua inactivity timeout.
if (ua_txn && ua_txn->has_request_body(t_state.hdr_info.request_content_length,
t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
ua_txn->cancel_inactivity_timeout();
}
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state =
t_state.hdr_info.server_response.parse_resp(&http_parser, server_txn->get_remote_reader(), &bytes_used, server_entry->eos);
server_response_hdr_bytes += bytes_used;
// Don't allow HTTP 0.9 (unparsable headers) on resued connections.
// And don't allow empty headers from closed connections
if ((state == PARSE_RESULT_DONE && t_state.hdr_info.server_response.version_get() == HTTP_0_9 &&
server_txn->get_transaction_id() > 1) ||
(server_entry->eos && state == PARSE_RESULT_CONT)) { // No more data will be coming
state = PARSE_RESULT_ERROR;
}
// Check to see if we are over the hdr size limit
if (server_response_hdr_bytes > t_state.txn_conf->response_hdr_max_size) {
state = PARSE_RESULT_ERROR;
}
if (state != PARSE_RESULT_CONT) {
// Disable further IO
server_entry->read_vio->nbytes = server_entry->read_vio->ndone;
http_parser_clear(&http_parser);
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = ink_get_hrtime();
// If there is a post body in transit, give up on it
if (tunnel.is_tunnel_alive()) {
tunnel.abort_tunnel();
// Make sure client connection is closed when we are done in case there is cruft left over
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
// Similarly the server connection should also be closed
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
}
switch (state) {
case PARSE_RESULT_ERROR: {
// Many broken servers send really badly formed 302 redirects.
// Even if the parser doesn't like the redirect forward
// if it's got a Location header. We check the type of the
// response to make sure that the parser was able to parse
// something and didn't just throw up it's hands (INKqa05339)
bool allow_error = false;
if (t_state.hdr_info.server_response.type_get() == HTTP_TYPE_RESPONSE &&
t_state.hdr_info.server_response.status_get() == HTTP_STATUS_MOVED_TEMPORARILY) {
if (t_state.hdr_info.server_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
allow_error = true;
}
}
if (allow_error == false) {
SMDebug("http_seq", "Error parsing server response header");
t_state.current.state = HttpTransact::PARSE_ERROR;
// If the server closed prematurely on us, use the
// server setup error routine since it will forward
// error to a POST tunnel if any
if (event == VC_EVENT_EOS) {
handle_server_setup_error(VC_EVENT_EOS, data);
} else {
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
break;
}
// FALLTHROUGH (since we are allowing the parse error)
}
// fallthrough
case PARSE_RESULT_DONE:
if (!t_state.hdr_info.server_response.check_hdr_implements()) {
t_state.http_return_code = HTTP_STATUS_BAD_GATEWAY;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
}
SMDebug("http_seq", "Done parsing server response header");
// Now that we know that we have all of the origin server
// response headers, we can reset the client inactivity
// timeout.
// we now reset the client inactivity timeout only
// when we are ready to send the response headers. In the
// case of transform plugin, this is after the transform
// outputs the 1st byte, which can take a long time if the
// plugin buffers the whole response.
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
t_state.transact_return_point = HttpTransact::HandleResponse;
t_state.api_next_action = HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR;
// if exceeded limit deallocate postdata buffers and disable redirection
if (!(enable_redirection && (redirection_tries < t_state.txn_conf->number_of_redirections))) {
this->disable_redirect();
}
// Go ahead and process the hooks assuming any body tunnel has already completed
if (!tunnel.is_tunnel_alive()) {
SMDebug("http_seq", "Continue processing response");
do_api_callout();
} else {
SMDebug("http_seq", "Defer processing response until post body is processed");
server_entry->read_vio->disable(); // Disable the read until we finish the tunnel
}
break;
case PARSE_RESULT_CONT:
ink_assert(server_entry->eos == false);
server_entry->read_vio->reenable();
return VC_EVENT_CONT;
default:
ink_assert(!"not reached");
}
return 0;
}
int
HttpSM::state_send_server_request_header(int event, void *data)
{
ink_assert(server_entry != nullptr);
if (server_entry->read_vio == data) {
return this->state_read_server_response_header(event, data);
}
ink_assert(server_entry->eos == false);
ink_assert(server_entry->write_vio == (VIO *)data);
STATE_ENTER(&HttpSM::state_send_server_request_header, event);
int method;
switch (event) {
case VC_EVENT_WRITE_READY:
server_entry->write_vio->reenable();
break;
case VC_EVENT_WRITE_COMPLETE:
// We are done sending the request header, deallocate
// our buffer and then decide what to do next
free_MIOBuffer(server_entry->write_buffer);
server_entry->write_buffer = nullptr;
method = t_state.hdr_info.server_request.method_get_wksidx();
if (!t_state.api_server_request_body_set && method != HTTP_WKSIDX_TRACE &&
ua_txn->has_request_body(t_state.hdr_info.request_content_length,
t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
if (post_transform_info.vc) {
setup_transform_to_server_transfer();
} else {
// Go ahead and set up the post tunnel if we are not waiting for a 100 response
if (!t_state.hdr_info.client_request.m_100_continue_required) {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
}
}
break;
case VC_EVENT_EOS:
// EOS of stream comes from the read side. Treat it as
// as error if there is nothing in the read buffer. If
// there is something the server may have blasted back
// the response before receiving the request. Happens
// often with redirects
//
// If we are in the middle of an api callout, it
// means we haven't actually sent the request yet
// so the stuff in the buffer is garbage and we
// want to ignore it
//
server_entry->eos = true;
// I'm not sure about the above comment, but if EOS is received on read and we are
// still in this state, we must have not gotten WRITE_COMPLETE. With epoll we might not receive EOS
// from both read and write sides of a connection so it should be handled correctly (close tunnels,
// deallocate, etc) here with handle_server_setup_error(). Otherwise we might hang due to not shutting
// down and never receiving another event again.
/*if (server_txn->get_remote_reader()->read_avail() > 0 && callout_state == HTTP_API_NO_CALLOUT) {
break;
} */
// Nothing in the buffer
// proceed to error
// fallthrough
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
handle_server_setup_error(event, data);
break;
case VC_EVENT_READ_COMPLETE:
// new event expected due to TS-3189
SMDebug("http_ss", "read complete due to 0 byte do_io_read");
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
void
HttpSM::process_srv_info(HostDBInfo *r)
{
SMDebug("dns_srv", "beginning process_srv_info");
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
/* we didn't get any SRV records, continue w normal lookup */
if (!r || !r->is_srv || !r->round_robin) {
t_state.dns_info.srv_hostname[0] = '\0';
t_state.dns_info.srv_lookup_success = false;
t_state.my_txn_conf().srv_enabled = false;
SMDebug("dns_srv", "No SRV records were available, continuing to lookup %s", t_state.dns_info.lookup_name);
} else {
HostDBRoundRobin *rr = r->rr();
HostDBInfo *srv = nullptr;
if (rr) {
srv = rr->select_best_srv(t_state.dns_info.srv_hostname, &mutex->thread_holding->generator, ink_local_time(),
static_cast<int>(t_state.txn_conf->down_server_timeout));
}
if (!srv) {
t_state.dns_info.srv_lookup_success = false;
t_state.dns_info.srv_hostname[0] = '\0';
t_state.my_txn_conf().srv_enabled = false;
SMDebug("dns_srv", "SRV records empty for %s", t_state.dns_info.lookup_name);
} else {
t_state.dns_info.srv_lookup_success = true;
t_state.dns_info.srv_port = srv->data.srv.srv_port;
t_state.dns_info.srv_app = srv->app;
// t_state.dns_info.single_srv = (rr->good == 1);
ink_assert(srv->data.srv.key == makeHostHash(t_state.dns_info.srv_hostname));
SMDebug("dns_srv", "select SRV records %s", t_state.dns_info.srv_hostname);
}
}
return;
}
void
HttpSM::process_hostdb_info(HostDBInfo *r)
{
// Increment the refcount to our item, since we are pointing at it
t_state.hostdb_entry = Ptr<HostDBInfo>(r);
sockaddr const *client_addr = nullptr;
bool use_client_addr = t_state.http_config_param->use_client_target_addr == 1 && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_Addr::OS_ADDR_TRY_DEFAULT;
if (use_client_addr) {
NetVConnection *vc = ua_txn ? ua_txn->get_netvc() : nullptr;
if (vc) {
client_addr = vc->get_local_addr();
// Regardless of whether the client address matches the DNS record or not,
// we want to use that address. Therefore, we copy over the client address
// info and skip the assignment from the DNS cache
ats_ip_copy(t_state.host_db_info.ip(), client_addr);
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_Addr::OS_ADDR_TRY_CLIENT;
t_state.dns_info.lookup_success = true;
// Leave ret unassigned, so we don't overwrite the host_db_info
} else {
use_client_addr = false;
}
}
if (r && !r->is_failed()) {
ink_time_t now = ink_local_time();
HostDBInfo *ret = nullptr;
t_state.dns_info.lookup_success = true;
t_state.dns_info.lookup_validated = true;
HostDBRoundRobin *rr = r->round_robin ? r->rr() : nullptr;
if (rr) {
// if use_client_target_addr is set, make sure the client addr is in the results pool
if (use_client_addr && rr->find_ip(client_addr) == nullptr) {
SMDebug("http", "use_client_target_addr == 1. Client specified address is not in the pool, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
// Since the time elapsed between current time and client_request_time
// may be very large, we cannot use client_request_time to approximate
// current time when calling select_best_http().
ret = rr->select_best_http(&t_state.client_info.src_addr.sa, now, static_cast<int>(t_state.txn_conf->down_server_timeout));
// set the srv target`s last_failure
if (t_state.dns_info.srv_lookup_success) {
uint32_t last_failure = 0xFFFFFFFF;
for (int i = 0; i < rr->rrcount && last_failure != 0; ++i) {
if (last_failure > rr->info(i).app.http_data.last_failure) {
last_failure = rr->info(i).app.http_data.last_failure;
}
}
if (last_failure != 0 && static_cast<uint32_t>(now - t_state.txn_conf->down_server_timeout) < last_failure) {
HostDBApplicationInfo app;
app.allotment.application1 = 0;
app.allotment.application2 = 0;
app.http_data.last_failure = last_failure;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &app);
}
}
}
} else {
if (use_client_addr && !ats_ip_addr_eq(client_addr, &r->data.ip.sa)) {
SMDebug("http", "use_client_target_addr == 1. Comparing single addresses failed, not validated.");
t_state.dns_info.lookup_validated = false;
} else {
ret = r;
}
}
if (ret) {
t_state.host_db_info = *ret;
ink_release_assert(!t_state.host_db_info.reverse_dns);
ink_release_assert(ats_is_ip(t_state.host_db_info.ip()));
}
} else {
SMDebug("http", "DNS lookup failed for '%s'", t_state.dns_info.lookup_name);
if (!use_client_addr) {
t_state.dns_info.lookup_success = false;
}
t_state.host_db_info.app.allotment.application1 = 0;
t_state.host_db_info.app.allotment.application2 = 0;
ink_assert(!t_state.host_db_info.round_robin);
}
milestones[TS_MILESTONE_DNS_LOOKUP_END] = ink_get_hrtime();
if (is_debug_tag_set("http_timeout")) {
if (t_state.api_txn_dns_timeout_value != -1) {
int foo = static_cast<int>(milestones.difference_msec(TS_MILESTONE_DNS_LOOKUP_BEGIN, TS_MILESTONE_DNS_LOOKUP_END));
SMDebug("http_timeout", "DNS took: %d msec", foo);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_hostdb_lookup()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_hostdb_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_lookup, event);
// ink_assert (m_origin_server_vc == 0);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
process_hostdb_info(static_cast<HostDBInfo *>(data));
call_transact_and_set_next_state(nullptr);
break;
case EVENT_SRV_LOOKUP: {
pending_action = nullptr;
process_srv_info(static_cast<HostDBInfo *>(data));
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
HostDBProcessor::Options opt;
opt.port = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_port : t_state.server_info.dst_addr.host_order_port();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ats_host_res_from(ua_txn->get_netvc()->get_local_addr()->sa_family, t_state.txn_conf->host_res_data.order);
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (cb_process_result_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
} break;
case EVENT_HOST_DB_IP_REMOVED:
ink_assert(!"Unexpected event from HostDB");
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
int
HttpSM::state_hostdb_reverse_lookup(int event, void *data)
{
STATE_ENTER(&HttpSM::state_hostdb_reverse_lookup, event);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed into
// REQ_FLAVOR_REVPROXY
ink_assert(t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY || ua_entry->vc != nullptr);
switch (event) {
case EVENT_HOST_DB_LOOKUP:
pending_action = nullptr;
if (data) {
t_state.request_data.hostname_str = (static_cast<HostDBInfo *>(data))->hostname();
} else {
SMDebug("http", "reverse DNS lookup failed for '%s'", t_state.dns_info.lookup_name);
}
call_transact_and_set_next_state(nullptr);
break;
default:
ink_assert(!"Unexpected event");
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM:state_mark_os_down()
//
//////////////////////////////////////////////////////////////////////////////
int
HttpSM::state_mark_os_down(int event, void *data)
{
STATE_ENTER(&HttpSM::state_mark_os_down, event);
HostDBInfo *mark_down = nullptr;
if (event == EVENT_HOST_DB_LOOKUP && data) {
HostDBInfo *r = static_cast<HostDBInfo *>(data);
if (r->round_robin) {
// Look for the entry we need mark down in the round robin
ink_assert(t_state.current.server != nullptr);
ink_assert(t_state.current.request_to == HttpTransact::ORIGIN_SERVER);
if (t_state.current.server) {
mark_down = r->rr()->find_ip(&t_state.current.server->dst_addr.sa);
}
} else {
// No longer a round robin, check to see if our address is the same
if (ats_ip_addr_eq(t_state.host_db_info.ip(), r->ip())) {
mark_down = r;
}
}
if (mark_down) {
mark_host_failure(mark_down, t_state.request_sent_time);
}
}
// We either found our entry or we did not. Either way find
// the entry we should use now
return state_hostdb_lookup(event, data);
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_handle_stat_page()
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_handle_stat_page(int event, void *data)
{
STATE_ENTER(&HttpSM::state_handle_stat_page, event);
switch (event) {
case STAT_PAGE_SUCCESS:
pending_action = nullptr;
if (data) {
StatPageData *spd = static_cast<StatPageData *>(data);
t_state.internal_msg_buffer = spd->data;
if (spd->type) {
t_state.internal_msg_buffer_type = spd->type;
} else {
t_state.internal_msg_buffer_type = nullptr; // Defaults to text/html
}
t_state.internal_msg_buffer_size = spd->length;
t_state.internal_msg_buffer_fast_allocator_size = -1;
}
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
case STAT_PAGE_FAILURE:
pending_action = nullptr;
call_transact_and_set_next_state(HttpTransact::HandleStatPage);
break;
default:
ink_release_assert(0);
break;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////
// HttpSM::state_cache_open_write()
//
// This state is set by set_next_state() for a cache open write
// (SERVER_READ_CACHE_WRITE)
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_write(int event, void *data)
{
STATE_ENTER(&HttpSM : state_cache_open_write, event);
// Make sure we are on the "right" thread
if (ua_txn) {
if (pending_action) {
pending_action->cancel();
}
if ((pending_action = ua_txn->adjust_thread(this, event, data))) {
HTTP_INCREMENT_DYN_STAT(http_cache_open_write_adjust_thread_stat);
return 0; // Go away if we reschedule
}
}
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_END] = ink_get_hrtime();
pending_action = nullptr;
switch (event) {
case CACHE_EVENT_OPEN_WRITE:
//////////////////////////////
// OPEN WRITE is successful //
//////////////////////////////
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
break;
case CACHE_EVENT_OPEN_WRITE_FAILED:
// Failed on the write lock and retrying the vector
// for reading
if (t_state.redirect_info.redirect_in_process) {
SMDebug("http_redirect", "CACHE_EVENT_OPEN_WRITE_FAILED during redirect follow");
t_state.cache_open_write_fail_action = CACHE_WL_FAIL_ACTION_DEFAULT;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
if (t_state.txn_conf->cache_open_write_fail_action == CACHE_WL_FAIL_ACTION_DEFAULT) {
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
} else {
t_state.cache_open_write_fail_action = t_state.txn_conf->cache_open_write_fail_action;
if (!t_state.cache_info.object_read ||
(t_state.cache_open_write_fail_action == CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE)) {
// cache miss, set wl_state to fail
SMDebug("http", "cache object read %p, cache_wl_fail_action %d", t_state.cache_info.object_read,
t_state.cache_open_write_fail_action);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_FAIL;
break;
}
}
// INTENTIONAL FALL THROUGH
// Allow for stale object to be served
case CACHE_EVENT_OPEN_READ:
if (!t_state.cache_info.object_read) {
t_state.cache_open_write_fail_action = t_state.txn_conf->cache_open_write_fail_action;
// Note that CACHE_LOOKUP_COMPLETE may be invoked more than once
// if CACHE_WL_FAIL_ACTION_READ_RETRY is configured
ink_assert(t_state.cache_open_write_fail_action == CACHE_WL_FAIL_ACTION_READ_RETRY);
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_READ_RETRY;
break;
}
// The write vector was locked and the cache_sm retried
// and got the read vector again.
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
// clear up CACHE_LOOKUP_MISS, let Freshness function decide
// hit status
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_READ_RETRY;
break;
case HTTP_TUNNEL_EVENT_DONE:
// In the case where we have issued a cache write for the
// transformed copy, the tunnel from the origin server to
// the transform may complete while we are waiting for
// the cache write. If this is the case, forward the event
// to the transform read state as it will know how to
// handle it
if (t_state.next_action == HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM) {
state_common_wait_for_transform_read(&transform_info, &HttpSM::tunnel_handler, event, data);
return 0;
}
// Fallthrough
default:
ink_release_assert(0);
}
// The write either succeeded or failed, notify transact
call_transact_and_set_next_state(nullptr);
return 0;
}
inline void
HttpSM::setup_cache_lookup_complete_api()
{
t_state.api_next_action = HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE;
do_api_callout();
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::state_cache_open_read()
//
// This state handles the result of CacheProcessor::open_read()
// that attempts to do cache lookup and open a particular cached
// object for reading.
//
//////////////////////////////////////////////////////////////////////////
int
HttpSM::state_cache_open_read(int event, void *data)
{
STATE_ENTER(&HttpSM::state_cache_open_read, event);
ink_assert(server_entry == nullptr);
ink_assert(t_state.cache_info.object_read == nullptr);
switch (event) {
case CACHE_EVENT_OPEN_READ: {
pending_action = nullptr;
SMDebug("http", "cache_open_read - CACHE_EVENT_OPEN_READ");
/////////////////////////////////
// lookup/open is successful. //
/////////////////////////////////
ink_assert(cache_sm.cache_read_vc != nullptr);
t_state.source = HttpTransact::SOURCE_CACHE;
cache_sm.cache_read_vc->get_http_info(&t_state.cache_info.object_read);
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (cache_sm.cache_read_vc->is_ram_cache_hit()) {
t_state.cache_info.hit_miss_code = SQUID_HIT_RAM;
} else {
t_state.cache_info.hit_miss_code = SQUID_HIT_DISK;
}
ink_assert(t_state.cache_info.object_read != nullptr);
call_transact_and_set_next_state(HttpTransact::HandleCacheOpenRead);
break;
}
case CACHE_EVENT_OPEN_READ_FAILED:
pending_action = nullptr;
SMDebug("http", "[%" PRId64 "] cache_open_read - CACHE_EVENT_OPEN_READ_FAILED with %s (%d)", sm_id,
InkStrerror(-(intptr_t)data), (int)(intptr_t)data);
SMDebug("http", "open read failed.");
// Inform HttpTransact somebody else is updating the document
// HttpCacheSM already waited so transact should go ahead.
if ((intptr_t)data == -ECACHE_DOC_BUSY) {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_DOC_BUSY;
} else {
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
}
ink_assert(t_state.transact_return_point == nullptr);
t_state.transact_return_point = HttpTransact::HandleCacheOpenRead;
setup_cache_lookup_complete_api();
break;
default:
ink_release_assert(!"Unknown event");
break;
}
milestones[TS_MILESTONE_CACHE_OPEN_READ_END] = ink_get_hrtime();
return 0;
}
int
HttpSM::main_handler(int event, void *data)
{
ink_release_assert(magic == HTTP_SM_MAGIC_ALIVE);
HttpSMHandler jump_point = nullptr;
ink_assert(reentrancy_count >= 0);
reentrancy_count++;
// Don't use the state enter macro since it uses history
// space that we don't care about
SMDebug("http", "%s, %d", HttpDebugNames::get_event_name(event), event);
HttpVCTableEntry *vc_entry = nullptr;
if (data != nullptr) {
// Only search the VC table if the event could have to
// do with a VIO to save a few cycles
if (event < VC_EVENT_EVENTS_START + 100) {
vc_entry = vc_table.find_entry(static_cast<VIO *>(data));
}
}
if (vc_entry) {
jump_point = vc_entry->vc_handler;
ink_assert(jump_point != (HttpSMHandler) nullptr);
ink_assert(vc_entry->vc != (VConnection *)nullptr);
(this->*jump_point)(event, data);
} else {
ink_assert(default_handler != (HttpSMHandler) nullptr);
(this->*default_handler)(event, data);
}
// The sub-handler signals when it is time for the state
// machine to exit. We can only exit if we are not reentrantly
// called otherwise when the our call unwinds, we will be
// running on a dead state machine
//
// Because of the need for an api shutdown hook, kill_this()
// is also reentrant. As such, we don't want to decrement
// the reentrancy count until after we run kill_this()
//
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
reentrancy_count--;
ink_assert(reentrancy_count >= 0);
}
return (VC_EVENT_CONT);
}
// void HttpSM::tunnel_handler_post_or_put()
//
// Handles the common cleanup tasks for Http post/put
// to prevent code duplication
//
void
HttpSM::tunnel_handler_post_or_put(HttpTunnelProducer *p)
{
ink_assert(p->vc_type == HT_HTTP_CLIENT || (p->handler_state == HTTP_SM_POST_UA_FAIL && p->vc_type == HT_BUFFER_READ));
HttpTunnelConsumer *c;
// If there is a post transform, remove it's entry from the State
// Machine's VC table
//
// MUST NOT clear the vc pointer from post_transform_info
// as this causes a double close of the transform vc in transform_cleanup
//
if (post_transform_info.vc != nullptr) {
ink_assert(post_transform_info.entry->in_tunnel == true);
ink_assert(post_transform_info.vc == post_transform_info.entry->vc);
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
}
switch (p->handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
c = tunnel.get_consumer(server_entry->vc);
ink_assert(c->write_success == false);
break;
case HTTP_SM_POST_UA_FAIL:
// UA quit - shutdown the SM
ink_assert(p->read_success == false);
terminate_sm = true;
break;
case HTTP_SM_POST_SUCCESS:
// The post succeeded
ink_assert(p->read_success == true);
ink_assert(p->consumer_list.head->write_success == true);
tunnel.deallocate_buffers();
tunnel.reset();
// When the ua completed sending it's data we must have
// removed it from the tunnel
ua_entry->in_tunnel = false;
server_entry->in_tunnel = false;
break;
default:
ink_release_assert(0);
}
}
// int HttpSM::tunnel_handler_post(int event, void* data)
//
// Handles completion of any http request body tunnel
// Having 'post' in its name is a misnomer
//
int
HttpSM::tunnel_handler_post(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_post, event);
HttpTunnelProducer *p = ua_txn != nullptr ? tunnel.get_producer(ua_txn) : tunnel.get_producer(HT_HTTP_CLIENT);
if (!p) {
return 0; // Cannot do anything if there is no producer
}
switch (event) {
case HTTP_TUNNEL_EVENT_DONE: // Tunnel done.
if (p->handler_state == HTTP_SM_POST_UA_FAIL) {
// post failed
switch (t_state.client_info.state) {
case HttpTransact::ACTIVE_TIMEOUT:
call_transact_and_set_next_state(HttpTransact::PostActiveTimeoutResponse);
return 0;
case HttpTransact::INACTIVE_TIMEOUT:
call_transact_and_set_next_state(HttpTransact::PostInactiveTimeoutResponse);
return 0;
default:
break;
}
}
break;
case VC_EVENT_WRITE_READY: // iocore may callback first before send.
return 0;
case VC_EVENT_EOS: // SSLNetVC may callback EOS during write error (6.0.x or early)
case VC_EVENT_ERROR: // Send HTTP 408 error
case VC_EVENT_WRITE_COMPLETE: // tunnel_handler_post_ua has sent HTTP 408 response
case VC_EVENT_INACTIVITY_TIMEOUT: // ua_txn timeout during sending the HTTP 408 response
case VC_EVENT_ACTIVE_TIMEOUT: // ua_txn timeout
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
if (!p->handler_state) {
p->handler_state = HTTP_SM_POST_UA_FAIL;
}
break;
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
default:
ink_assert(!"not reached");
return 0;
}
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// The tunnel calls this when it is done
int p_handler_state = p->handler_state;
if (is_waiting_for_full_body && !this->is_postbuf_valid()) {
p_handler_state = HTTP_SM_POST_SERVER_FAIL;
}
if (p->vc_type != HT_BUFFER_READ) {
tunnel_handler_post_or_put(p);
}
switch (p_handler_state) {
case HTTP_SM_POST_SERVER_FAIL:
handle_post_failure();
break;
case HTTP_SM_POST_UA_FAIL:
// Client side failed. Shutdown and go home. No need to communicate back to UA
terminate_sm = true;
break;
case HTTP_SM_POST_SUCCESS:
// It's time to start reading the response
if (is_waiting_for_full_body) {
is_waiting_for_full_body = false;
is_using_post_buffer = true;
client_request_body_bytes = this->postbuf_buffer_avail();
call_transact_and_set_next_state(HttpTransact::HandleRequestBufferDone);
break;
}
// Is the response header ready and waiting?
// If so, go ahead and do the hook processing
if (milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] != 0) {
Warning("Process waiting response id=[%" PRId64, sm_id);
t_state.current.state = HttpTransact::CONNECTION_ALIVE;
t_state.transact_return_point = HttpTransact::HandleResponse;
t_state.api_next_action = HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR;
do_api_callout();
}
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_cache_fill(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_fill, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
ink_release_assert(cache_sm.cache_write_vc);
tunnel.deallocate_buffers();
this->postbuf_clear();
tunnel.reset();
setup_server_transfer_to_cache_only();
tunnel.tunnel_run();
return 0;
}
int
HttpSM::tunnel_handler_100_continue(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// We're done sending the 100 continue. If we succeeded,
// we set up to parse the next server response. If we
// failed, shutdown the state machine
HttpTunnelConsumer *c = tunnel.get_consumer(ua_txn);
if (c->write_success) {
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.client_response.destroy();
tunnel.deallocate_buffers();
this->postbuf_clear();
tunnel.reset();
if (server_entry->eos) {
// if the server closed while sending the
// 100 continue header, handle it here so we
// don't assert later
SMDebug("http", "server already closed, terminating connection");
// Since 100 isn't a final (loggable) response header
// kill the 100 continue header and create an empty one
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
handle_server_setup_error(VC_EVENT_EOS, server_entry->read_vio);
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
} else {
terminate_sm = true;
}
return 0;
}
int
HttpSM::tunnel_handler_push(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler_push, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
ink_assert(data == &tunnel);
// Check to see if the client is still around
HttpTunnelProducer *ua = (ua_txn) ? tunnel.get_producer(ua_txn) : tunnel.get_producer(HT_HTTP_CLIENT);
if (ua && !ua->read_success) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return 0;
}
HttpTunnelConsumer *cache = ua->consumer_list.head;
ink_release_assert(cache->vc_type == HT_CACHE_WRITE);
bool cache_write_success = cache->write_success;
// Reset tunneling state since we need to send a response
// to client as whether we succeeded
tunnel.deallocate_buffers();
this->postbuf_clear();
tunnel.reset();
if (cache_write_success) {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelSuccess);
} else {
call_transact_and_set_next_state(HttpTransact::HandlePushTunnelFailure);
}
return 0;
}
int
HttpSM::tunnel_handler(int event, void *data)
{
STATE_ENTER(&HttpSM::tunnel_handler, event);
ink_assert(event == HTTP_TUNNEL_EVENT_DONE);
// The tunnel calls this when it is done
terminate_sm = true;
if (unlikely(t_state.is_websocket)) {
HTTP_DECREMENT_DYN_STAT(http_websocket_current_active_client_connections_stat);
}
return 0;
}
/****************************************************
TUNNELING HANDLERS
******************************************************/
bool
HttpSM::is_http_server_eos_truncation(HttpTunnelProducer *p)
{
if ((p->do_dechunking || p->do_chunked_passthru) && p->chunked_handler.truncation) {
return true;
}
//////////////////////////////////////////////////////////////
// If we did not get or did not trust the origin server's //
// content-length, read_content_length is unset. The //
// only way the end of the document is signaled is the //
// origin server closing the connection. However, we //
// need to protect against the document getting truncated //
// because the origin server crashed. The following //
// tabled outlines when we mark the server read as failed //
// //
// No C-L : read success //
// Received byts < C-L : read failed (=> Cache Abort) //
// Received byts == C-L : read success //
// Received byts > C-L : read success //
//////////////////////////////////////////////////////////////
int64_t cl = t_state.hdr_info.server_response.get_content_length();
if (cl != UNDEFINED_COUNT && cl > server_response_body_bytes) {
SMDebug("http", "server EOS after %" PRId64 " bytes, expected %" PRId64, server_response_body_bytes, cl);
return true;
} else {
return false;
}
}
int
HttpSM::tunnel_handler_server(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_server, event);
// An intercept handler may not set TS_MILESTONE_SERVER_CONNECT
// by default. Therefore we only set TS_MILESTONE_SERVER_CLOSE if
// TS_MILESTONE_SERVER_CONNECT is set (non-zero), lest certain time
// statistics are calculated from epoch time.
if (0 != milestones[TS_MILESTONE_SERVER_CONNECT]) {
milestones[TS_MILESTONE_SERVER_CLOSE] = ink_get_hrtime();
}
bool close_connection = false;
if (t_state.current.server->keep_alive == HTTP_KEEPALIVE && server_entry->eos == false &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL && t_state.txn_conf->keep_alive_enabled_out == 1) {
close_connection = false;
} else {
if (t_state.current.server->keep_alive != HTTP_KEEPALIVE) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_server_no_keep_alive);
} else if (server_entry->eos == true) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_server_eos);
} else {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_server_plugin_tunnel);
}
close_connection = true;
}
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_TIMEOUT;
t_state.squid_codes.hier_code = SQUID_HIER_TIMEOUT_DIRECT;
/* fallthru */
case VC_EVENT_EOS:
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.current.server->state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.server->state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.current.server->state = HttpTransact::CONNECTION_ERROR;
break;
case VC_EVENT_EOS:
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
break;
}
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_server);
close_connection = true;
ink_assert(p->vc_type == HT_HTTP_SERVER);
if (is_http_server_eos_truncation(p)) {
SMDebug("http", "aborting HTTP tunnel due to server truncation");
tunnel.chain_abort_all(p);
// UA session may not be in the tunnel yet, don't NULL out the pointer in that case.
// Note: This is a hack. The correct solution is for the UA session to signal back to the SM
// when the UA is about to be destroyed and clean up the pointer there. That should be done once
// the TS-3612 changes are in place (and similarly for the server session).
/*if (ua_entry->in_tunnel)
ua_txn = NULL; */
t_state.current.server->abort = HttpTransact::ABORTED;
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (event == VC_EVENT_EOS) {
t_state.squid_codes.log_code = SQUID_LOG_ERR_READ_ERROR;
}
} else {
SMDebug("http", "finishing HTTP tunnel");
p->read_success = true;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
// Appending reason to a response without Content-Length will result in
// the reason string being written to the client and a bad CL when reading from cache.
// I didn't find anywhere this appended reason is being used, so commenting it out.
/*
if (t_state.is_cacheable_due_to_negative_caching_configuration && p->bytes_read == 0) {
int reason_len;
const char *reason = t_state.hdr_info.server_response.reason_get(&reason_len);
if (reason == NULL)
tunnel.append_message_to_producer_buffer(p, "Negative Response", sizeof("Negative Response") - 1);
else
tunnel.append_message_to_producer_buffer(p, reason, reason_len);
}
*/
tunnel.local_finish_all(p);
}
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
// If there is still data in the buffer, the server
// sent too much indicating a failed transfer
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
// We couldn't read all chunks successfully:
// Disable keep-alive.
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
} else {
tunnel.local_finish_all(p);
}
}
break;
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
// All consumers are prematurely gone. Shutdown
// the server connection
p->read_success = true;
t_state.current.server->state = HttpTransact::TRANSACTION_COMPLETE;
t_state.current.server->abort = HttpTransact::DIDNOT_ABORT;
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_server_detach);
close_connection = true;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
// turn off negative caching in case there are multiple server contacts
if (t_state.is_cacheable_due_to_negative_caching_configuration) {
t_state.is_cacheable_due_to_negative_caching_configuration = false;
}
// If we had a ground fill, check update our status
if (background_fill == BACKGROUND_FILL_STARTED) {
background_fill = p->read_success ? BACKGROUND_FILL_COMPLETED : BACKGROUND_FILL_ABORTED;
HTTP_DECREMENT_DYN_STAT(http_background_fill_current_count_stat);
}
// We handled the event. Now either shutdown the connection or
// setup it up for keep-alive
ink_assert(p->vc_type == HT_HTTP_SERVER);
ink_assert(p->vc == server_txn);
// The server session has been released. Clean all pointer
// Calling remove_entry instead of server_entry because we don't
// want to close the server VC at this point
vc_table.remove_entry(server_entry);
if (close_connection) {
p->vc->do_io_close();
p->read_vio = nullptr;
/* TS-1424: if we're outbound transparent and using the client
source port for the outbound connection we must effectively
propagate server closes back to the client. Part of that is
disabling KeepAlive if the server closes.
*/
if (ua_txn && ua_txn->is_outbound_transparent() && t_state.http_config_param->use_client_source_port) {
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
} else {
// If the option to attach the server session to the client session is set
// and if the client is still around and the client is keep-alive, attach the
// server session to so the next ka request can use it. Server sessions will
// be placed into the shared pool if the next incoming request is for a different
// origin server
bool release_origin_connection = true;
if (t_state.txn_conf->attach_server_session_to_client == 1 && ua_txn && t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
SMDebug("http", "attaching server session to the client");
if (ua_txn->attach_server_session(static_cast<PoolableSession *>(server_txn->get_proxy_ssn()))) {
release_origin_connection = false;
}
}
if (release_origin_connection) {
// Release the session back into the shared session pool
server_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_txn->release();
}
}
return 0;
}
// int HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer* c)
//
// Used for tunneling the 100 continue response. The tunnel
// should not close or release the user agent unless there is
// an error since the real response is yet to come
//
int
HttpSM::tunnel_handler_100_continue_ua(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_100_continue_ua, event);
ink_assert(c->vc == ua_txn);
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
set_ua_abort(HttpTransact::ABORTED, event);
c->vc->do_io_close();
break;
case VC_EVENT_WRITE_COMPLETE:
// mark the vc as no longer in tunnel
// so we don't get hosed if the ua abort before
// real response header is received
ua_entry->in_tunnel = false;
c->write_success = true;
}
return 0;
}
bool
HttpSM::is_bg_fill_necessary(HttpTunnelConsumer *c)
{
ink_assert(c->vc_type == HT_HTTP_CLIENT);
if (c->producer->alive && // something there to read
// server_entry && server_entry->vc && // from an origin server
// server_txn && server_txn->get_netvc() && // which is still open and valid
c->producer->num_consumers > 1 // with someone else reading it
) {
HttpTunnelProducer *p = nullptr;
if (!server_txn || !server_txn->get_netvc()) {
// return true if we have finished the reading from OS when client aborted
p = c->producer->self_consumer ? c->producer->self_consumer->producer : c->producer;
if (p->vc_type == HT_HTTP_SERVER && p->read_success) {
return true;
} else {
return false;
}
}
// If threshold is 0.0 or negative then do background
// fill regardless of the content length. Since this
// is floating point just make sure the number is near zero
if (t_state.txn_conf->background_fill_threshold <= 0.001) {
return true;
}
int64_t ua_cl = t_state.hdr_info.client_response.get_content_length();
if (ua_cl > 0) {
int64_t ua_body_done = c->bytes_written - client_response_hdr_bytes;
float pDone = static_cast<float>(ua_body_done) / ua_cl;
// If we got a good content length. Check to make sure that we haven't already
// done more the content length since that would indicate the content-length
// is bogus. If we've done more than the threshold, continue the background fill
if (pDone <= 1.0 && pDone > t_state.txn_conf->background_fill_threshold) {
return true;
} else {
SMDebug("http", "no background. Only %%%f of %%%f done [%" PRId64 " / %" PRId64 " ]", pDone,
t_state.txn_conf->background_fill_threshold, ua_body_done, ua_cl);
}
}
}
return false;
}
int
HttpSM::tunnel_handler_ua(int event, HttpTunnelConsumer *c)
{
bool close_connection = true;
HttpTunnelProducer *p = nullptr;
HttpTunnelConsumer *selfc = nullptr;
STATE_ENTER(&HttpSM::tunnel_handler_ua, event);
ink_assert(c->vc == ua_txn);
milestones[TS_MILESTONE_UA_CLOSE] = ink_get_hrtime();
switch (event) {
case VC_EVENT_EOS:
ua_entry->eos = true;
// FALL-THROUGH
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
// The user agent died or aborted. Check to
// see if we should setup a background fill
set_ua_abort(HttpTransact::ABORTED, event);
if (is_bg_fill_necessary(c)) {
p = c->producer->self_consumer ? c->producer->self_consumer->producer : c->producer;
SMDebug("http", "Initiating background fill");
// check whether to finish the reading.
background_fill = p->read_success ? BACKGROUND_FILL_COMPLETED : BACKGROUND_FILL_STARTED;
// There is another consumer (cache write) so
// detach the user agent
if (background_fill == BACKGROUND_FILL_STARTED) {
HTTP_INCREMENT_DYN_STAT(http_background_fill_current_count_stat);
HTTP_INCREMENT_DYN_STAT(http_background_fill_total_count_stat);
ink_assert(server_entry->vc == server_txn);
ink_assert(c->is_downstream_from(server_txn));
server_txn->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->background_fill_active_timeout));
}
// Even with the background fill, the client side should go down
c->write_vio = nullptr;
c->vc->do_io_close(EHTTP_ERROR);
c->alive = false;
} else {
// No background fill
p = c->producer;
tunnel.chain_abort_all(c->producer);
selfc = p->self_consumer;
if (selfc) {
// This is the case where there is a transformation between ua and os
p = selfc->producer;
// if producer is the cache or OS, close the producer.
// Otherwise in case of large docs, producer iobuffer gets filled up,
// waiting for a consumer to consume data and the connection is never closed.
if (p->alive && ((p->vc_type == HT_CACHE_READ) || (p->vc_type == HT_HTTP_SERVER))) {
tunnel.chain_abort_all(p);
}
}
}
break;
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
t_state.client_info.abort = HttpTransact::DIDNOT_ABORT;
if (t_state.client_info.keep_alive == HTTP_KEEPALIVE) {
if (t_state.www_auth_content != HttpTransact::CACHE_AUTH_SERVE || ua_txn->get_server_session()) {
// successful keep-alive
close_connection = false;
}
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
client_response_body_bytes = c->bytes_written - client_response_hdr_bytes;
if (client_response_body_bytes < 0) {
client_response_body_bytes = 0;
}
// attribute the size written to the client from various sources
// NOTE: responses that go through a range transform are attributed
// to their original sources
// all other transforms attribute the total number of input bytes
// to a source in HttpSM::tunnel_handler_transform_write
//
HttpTransact::Source_t original_source = t_state.source;
if (HttpTransact::SOURCE_TRANSFORM == original_source && t_state.range_setup != HttpTransact::RANGE_NONE) {
original_source = t_state.pre_transform_source;
}
switch (original_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
ink_assert(ua_entry->vc == c->vc);
if (close_connection) {
// If the client could be pipelining or is doing a POST, we need to
// set the ua_txn into half close mode
// only external POSTs should be subject to this logic; ruling out internal POSTs here
bool is_eligible_post_request = ((t_state.method == HTTP_WKSIDX_POST) && !is_internal);
if (is_eligible_post_request && c->producer->vc_type != HT_STATIC && event == VC_EVENT_WRITE_COMPLETE) {
ua_txn->set_half_close_flag(true);
}
vc_table.remove_entry(this->ua_entry);
ua_txn->do_io_close();
} else {
ink_assert(ua_txn->get_remote_reader() != nullptr);
vc_table.remove_entry(this->ua_entry);
ua_txn->release();
}
return 0;
}
int
HttpSM::tunnel_handler_ua_push(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ua_push, event);
pushed_response_body_bytes += p->bytes_read;
client_request_body_bytes += p->bytes_read;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Transfer terminated. Bail on the cache write.
set_ua_abort(HttpTransact::ABORTED, event);
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
break;
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case VC_EVENT_READ_COMPLETE:
//
// The transfer completed successfully
p->read_success = true;
ua_entry->in_tunnel = false;
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
default:
// None of these events should ever come our way
ink_assert(0);
break;
}
return 0;
}
int
HttpSM::tunnel_handler_cache_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_read, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
ink_assert(t_state.cache_info.object_read->valid());
if (t_state.cache_info.object_read->object_size_get() != INT64_MAX || event == VC_EVENT_ERROR) {
// Abnormal termination
t_state.squid_codes.log_code = SQUID_LOG_TCP_SWAPFAIL;
p->vc->do_io_close(EHTTP_ERROR);
p->read_vio = nullptr;
tunnel.chain_abort_all(p);
HTTP_INCREMENT_DYN_STAT(http_cache_read_errors);
break;
} else {
tunnel.local_finish_all(p);
// fall through for the case INT64_MAX read with VC_EVENT_EOS
// callback (read successful)
}
// fallthrough
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
case HTTP_TUNNEL_EVENT_CONSUMER_DETACH:
p->read_success = true;
p->vc->do_io_close();
p->read_vio = nullptr;
break;
default:
ink_release_assert(0);
break;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_cache_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_cache_write, event);
SMDebug("http", "handling cache event: %s", HttpDebugNames::get_event_name(event));
HttpTransact::CacheWriteStatus_t *status_ptr =
(c->producer->vc_type == HT_TRANSFORM) ? &t_state.cache_info.transform_write_status : &t_state.cache_info.write_status;
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
// Abnormal termination
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_vio = nullptr;
c->vc->do_io_close(EHTTP_ERROR);
HTTP_INCREMENT_DYN_STAT(http_cache_write_errors);
SMDebug("http", "aborting cache write due %s event from cache", HttpDebugNames::get_event_name(event));
// abort the producer if the cache_writevc is the only consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.chain_abort_all(c->producer);
}
break;
case VC_EVENT_WRITE_COMPLETE:
// if we've never initiated a cache write
// abort the cache since it's finicky about a close
// in this case. This case can only occur
// we got a truncated header from the origin server
// but decided to accept it anyways
if (c->write_vio == nullptr) {
*status_ptr = HttpTransact::CACHE_WRITE_ERROR;
c->write_success = false;
c->vc->do_io_close(EHTTP_ERROR);
} else {
*status_ptr = HttpTransact::CACHE_WRITE_COMPLETE;
c->write_success = true;
c->vc->do_io_close();
c->write_vio = nullptr;
}
break;
default:
// All other events indicate problems
ink_assert(0);
break;
}
if (background_fill != BACKGROUND_FILL_NONE) {
server_response_body_bytes = c->bytes_written;
}
HTTP_DECREMENT_DYN_STAT(http_current_cache_connections_stat);
return 0;
}
int
HttpSM::tunnel_handler_post_ua(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_ua, event);
client_request_body_bytes = p->init_bytes_done + p->bytes_read;
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
if (client_response_hdr_bytes == 0) {
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
SMDebug("http_tunnel", "send 408 response to client to vc %p, tunnel vc %p", ua_txn->get_netvc(), p->vc);
tunnel.chain_abort_all(p);
// Reset the inactivity timeout, otherwise the InactivityCop will callback again in the next second.
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
// if it is active timeout case, we need to give another chance to send 408 response;
ua_txn->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_in));
return 0;
}
// fall through
case VC_EVENT_EOS:
// My reading of spec says that user agents can not terminate
// posts with a half close so this is an error
case VC_EVENT_ERROR:
// Did not complete post tunneling. Abort the
// server and close the ua
p->handler_state = HTTP_SM_POST_UA_FAIL;
set_ua_abort(HttpTransact::ABORTED, event);
tunnel.chain_abort_all(p);
// the in_tunnel status on both the ua & and
// it's consumer must already be set to true. Previously
// we were setting it again to true but incorrectly in
// the case of a transform
hsm_release_assert(ua_entry->in_tunnel == true);
if (p->consumer_list.head && p->consumer_list.head->vc_type == HT_TRANSFORM) {
hsm_release_assert(post_transform_info.entry->in_tunnel == true);
} // server side may have completed before the user agent side, so it may no longer be in tunnel
// In the error case, start to take down the client session. There should
// be no reuse here
vc_table.remove_entry(this->ua_entry);
ua_txn->do_io_close();
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
p->handler_state = HTTP_SM_POST_SUCCESS;
p->read_success = true;
ua_entry->in_tunnel = false;
if (p->do_dechunking || p->do_chunked_passthru) {
if (p->chunked_handler.truncation) {
tunnel.abort_cache_write_finish_others(p);
} else {
tunnel.local_finish_all(p);
}
}
// Now that we have communicated the post body, turn off the inactivity timeout
// until the server starts sending data back
if (ua_txn) {
ua_txn->cancel_inactivity_timeout();
// Initiate another read to catch aborts
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = p->vc->do_io_read(this, INT64_MAX, ua_txn->get_remote_reader()->mbuf);
}
break;
default:
ink_release_assert(0);
}
return 0;
}
// YTS Team, yamsat Plugin
// Tunnel handler to deallocate the tunnel buffers and
// set redirect_in_process=false
// Copy partial POST data to buffers. Check for the various parameters including
// the maximum configured post data size
int
HttpSM::tunnel_handler_for_partial_post(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::tunnel_handler_for_partial_post, event);
tunnel.deallocate_buffers();
tunnel.reset();
t_state.redirect_info.redirect_in_process = false;
is_using_post_buffer = false;
if (post_failed) {
post_failed = false;
handle_post_failure();
} else {
do_setup_post_tunnel(HTTP_SERVER_VC);
}
return 0;
}
int
HttpSM::tunnel_handler_post_server(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_post_server, event);
server_request_body_bytes = c->bytes_written;
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
switch (event) {
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.current.state = HttpTransact::INACTIVE_TIMEOUT;
t_state.set_connect_fail(ETIMEDOUT);
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.current.state = HttpTransact::ACTIVE_TIMEOUT;
t_state.set_connect_fail(ETIMEDOUT);
break;
case VC_EVENT_EOS:
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
t_state.set_connect_fail(EPIPE);
break;
case VC_EVENT_ERROR:
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
t_state.set_connect_fail(server_txn->get_netvc()->lerrno);
break;
default:
break;
}
// Did not complete post tunneling
//
// In the http case, we don't want to close
// the connection because the
// destroys the header buffer which may
// a response even though the tunnel failed.
// Shutdown both sides of the connection. This prevents us
// from getting any further events and signals to client
// that POST data will not be forwarded to the server. Doing
// shutdown on the write side will likely generate a TCP
// reset to the client but if the proxy wasn't here this is
// exactly what would happen.
// we should wait to shutdown read side of the
// client to prevent sending a reset
server_entry->eos = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// We may be reading from a transform. In that case, we
// want to close the transform
HttpTunnelProducer *ua_producer;
if (c->producer->vc_type == HT_TRANSFORM) {
if (c->producer->handler_state == HTTP_SM_TRANSFORM_OPEN) {
ink_assert(c->producer->vc == post_transform_info.vc);
c->producer->vc->do_io_close();
c->producer->alive = false;
c->producer->self_consumer->alive = false;
}
ua_producer = c->producer->self_consumer->producer;
} else {
ua_producer = c->producer;
}
ink_assert(ua_producer->vc_type == HT_HTTP_CLIENT);
ink_assert(ua_producer->vc == ua_txn);
ink_assert(ua_producer->vc == ua_entry->vc);
// Before shutting down, initiate another read
// on the user agent in order to get timeouts
// coming to the state machine and not the tunnel
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
// YTS Team, yamsat Plugin
// When event is VC_EVENT_ERROR,and when redirection is enabled
// do not shut down the client read
if (enable_redirection) {
if (ua_producer->vc_type == HT_STATIC && event != VC_EVENT_ERROR && event != VC_EVENT_EOS) {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, ua_txn->get_remote_reader()->mbuf);
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
if (ua_producer->vc_type == HT_STATIC && t_state.redirect_info.redirect_in_process) {
post_failed = true;
}
}
} else {
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, ua_txn->get_remote_reader()->mbuf);
// we should not shutdown read side of the client here to prevent sending a reset
// ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} // end of added logic
// We want to shutdown the tunnel here and see if there
// is a response on from the server. Mark the user
// agent as down so that tunnel concludes.
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
ink_assert(tunnel.is_tunnel_alive() == false);
break;
case VC_EVENT_WRITE_COMPLETE:
// Completed successfully
c->write_success = true;
server_entry->in_tunnel = false;
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_producer(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_producer, event);
switch (event) {
case VC_EVENT_EOS:
// The write side of this connection is still alive
// so half-close the read
if (p->self_consumer->alive) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
tunnel.local_finish_all(p);
break;
}
// FALL THROUGH - both sides of the tunnel are dea
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The other side of the connection is either already dead
// or rendered inoperative by the error on the connection
// Note: use tunnel close vc so the tunnel knows we are
// nuking the of the connection as well
tunnel.close_vc(p);
tunnel.local_finish_all(p);
// Because we've closed the net vc this error came in, it's write
// direction is now dead as well. If that side still being fed data,
// we need to kill that pipe as well
if (p->self_consumer->producer->alive) {
p->self_consumer->producer->alive = false;
if (p->self_consumer->producer->self_consumer->alive) {
p->self_consumer->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(p->self_consumer->producer);
}
}
break;
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// We should never get these event since we don't know
// how long the stream is
default:
ink_release_assert(0);
}
// Update stats
switch (p->vc_type) {
case HT_HTTP_SERVER:
server_response_body_bytes += p->bytes_read;
break;
case HT_HTTP_CLIENT:
client_request_body_bytes += p->bytes_read;
break;
default:
// Covered here:
// HT_CACHE_READ, HT_CACHE_WRITE,
// HT_TRANSFORM, HT_STATIC.
break;
}
return 0;
}
int
HttpSM::tunnel_handler_ssl_consumer(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_ssl_consumer, event);
switch (event) {
case VC_EVENT_ERROR:
case VC_EVENT_EOS:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// we need to mark the producer dead
// otherwise it can stay alive forever.
if (c->producer->alive) {
c->producer->alive = false;
if (c->producer->self_consumer->alive) {
c->producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else {
tunnel.close_vc(c->producer);
}
}
// Since we are changing the state of the self_producer
// we must have the tunnel shutdown the vc
tunnel.close_vc(c);
tunnel.local_finish_all(c->self_producer);
break;
case VC_EVENT_WRITE_COMPLETE:
// If we get this event, it means that the producer
// has finished and we wrote the remaining data
// to the consumer
//
// If the read side of this connection has not yet
// closed, do a write half-close and then wait for
// read side to close so that we don't cut off
// pipelined responses with TCP resets
//
// ink_assert(c->producer->alive == false);
c->write_success = true;
if (c->self_producer->alive == true) {
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
} else {
c->vc->do_io_close();
}
break;
default:
ink_release_assert(0);
}
// Update stats
switch (c->vc_type) {
case HT_HTTP_SERVER:
server_request_body_bytes += c->bytes_written;
break;
case HT_HTTP_CLIENT:
client_response_body_bytes += c->bytes_written;
break;
default:
// Handled here:
// HT_CACHE_READ, HT_CACHE_WRITE, HT_TRANSFORM,
// HT_STATIC
break;
}
return 0;
}
int
HttpSM::tunnel_handler_transform_write(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_write, event);
HttpTransformInfo *i;
// Figure out if this the request or response transform
// : use post_transform_info.entry because post_transform_info.vc
// is not set to NULL after the post transform is done.
if (post_transform_info.entry) {
i = &post_transform_info;
ink_assert(c->vc == i->entry->vc);
} else {
i = &transform_info;
ink_assert(c->vc == i->vc);
ink_assert(c->vc == i->entry->vc);
}
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(c->producer);
c->handler_state = HTTP_SM_TRANSFORM_FAIL;
c->vc->do_io_close(EHTTP_ERROR);
break;
case VC_EVENT_EOS:
// It possible the transform quit
// before the producer finished. If this is true
// we need shut down the producer if it doesn't
// have other consumers to serve or else it will
// fill up buffer and get hung
if (c->producer->alive && c->producer->num_consumers == 1) {
// Send a tunnel detach event to the producer
// to shut it down but indicates it should not abort
// downstream (on the other side of the transform)
// cache writes
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
// write to transform complete - shutdown the write side
c->write_success = true;
c->vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
// If the read side has not started up yet, then the
// this transform_vc is no longer owned by the tunnel
if (c->self_producer == nullptr) {
i->entry->in_tunnel = false;
} else if (c->self_producer->alive == false) {
// The read side of the Transform
// has already completed (possible when the
// transform intentionally truncates the response).
// So close it
c->vc->do_io_close();
}
break;
default:
ink_release_assert(0);
}
// attribute the size written to the transform from various sources
// NOTE: the range transform is excluded from this accounting and
// is instead handled in HttpSM::tunnel_handler_ua
//
// the reasoning is that the range transform is internal functionality
// in support of HTTP 1.1 compliance, therefore part of "normal" operation
// all other transforms are plugin driven and the difference between
// source data and final data should represent the transformation delta
//
if (t_state.range_setup == HttpTransact::RANGE_NONE) {
switch (t_state.pre_transform_source) {
case HttpTransact::SOURCE_HTTP_ORIGIN_SERVER:
server_response_body_bytes = client_response_body_bytes;
break;
case HttpTransact::SOURCE_CACHE:
cache_response_body_bytes = client_response_body_bytes;
break;
default:
break;
}
}
return 0;
}
int
HttpSM::tunnel_handler_transform_read(int event, HttpTunnelProducer *p)
{
STATE_ENTER(&HttpSM::tunnel_handler_transform_read, event);
ink_assert(p->vc == transform_info.vc || p->vc == post_transform_info.vc);
switch (event) {
case VC_EVENT_ERROR:
// Transform error
tunnel.chain_abort_all(p->self_consumer->producer);
break;
case VC_EVENT_EOS:
// If we did not get enough data from the transform abort the
// cache write otherwise fallthrough to the transform
// completing successfully
if (t_state.hdr_info.transform_response_cl != HTTP_UNDEFINED_CL &&
p->read_vio->nbytes < t_state.hdr_info.transform_response_cl) {
tunnel.abort_cache_write_finish_others(p);
break;
}
// FALL-THROUGH
case VC_EVENT_READ_COMPLETE:
case HTTP_TUNNEL_EVENT_PRECOMPLETE:
// Transform complete
p->read_success = true;
tunnel.local_finish_all(p);
break;
default:
ink_release_assert(0);
}
// it's possible that the write side of the
// transform hasn't detached yet. If it is still alive,
// don't close the transform vc
if (p->self_consumer->alive == false) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_tunnel_transform_read);
p->vc->do_io_close();
}
p->handler_state = HTTP_SM_TRANSFORM_CLOSED;
return 0;
}
int
HttpSM::tunnel_handler_plugin_agent(int event, HttpTunnelConsumer *c)
{
STATE_ENTER(&HttpSM::tunnel_handler_plugin_client, event);
switch (event) {
case VC_EVENT_ERROR:
c->vc->do_io_close(EHTTP_ERROR); // close up
// Signal producer if we're the last consumer.
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
break;
case VC_EVENT_EOS:
if (c->producer->alive && c->producer->num_consumers == 1) {
tunnel.producer_handler(HTTP_TUNNEL_EVENT_CONSUMER_DETACH, c->producer);
}
// FALLTHROUGH
case VC_EVENT_WRITE_COMPLETE:
c->write_success = true;
c->vc->do_io_close();
break;
default:
ink_release_assert(0);
}
return 0;
}
int
HttpSM::state_remap_request(int event, void * /* data ATS_UNUSED */)
{
STATE_ENTER(&HttpSM::state_remap_request, event);
switch (event) {
case EVENT_REMAP_ERROR: {
ink_assert(!"this doesn't happen");
pending_action = nullptr;
Error("error remapping request [see previous errors]");
call_transact_and_set_next_state(HttpTransact::HandleRequest); // HandleRequest skips EndRemapRequest
break;
}
case EVENT_REMAP_COMPLETE: {
pending_action = nullptr;
SMDebug("url_rewrite", "completed processor-based remapping request");
t_state.url_remap_success = remapProcessor.finish_remap(&t_state, m_remap);
call_transact_and_set_next_state(nullptr);
break;
}
default:
ink_assert(!"Unexpected event inside state_remap_request");
break;
}
return 0;
}
// This check must be called before remap. Otherwise, the client_request host
// name may be changed.
void
HttpSM::check_sni_host()
{
// Check that the SNI and host name fields match, if it matters
// Issue warning or mark the transaction to be terminated as necessary
int host_len;
const char *host_name = t_state.hdr_info.client_request.host_get(&host_len);
if (host_name && host_len) {
if (ua_txn->support_sni()) {
int host_sni_policy = t_state.http_config_param->http_host_sni_policy;
NetVConnection *netvc = ua_txn->get_netvc();
if (netvc) {
IpEndpoint ip = netvc->get_remote_endpoint();
if (SNIConfig::test_client_action(std::string{host_name, static_cast<size_t>(host_len)}.c_str(), ip, host_sni_policy) &&
host_sni_policy > 0) {
// In a SNI/Host mismatch where the Host would have triggered SNI policy, mark the transaction
// to be considered for rejection after the remap phase passes. Gives the opportunity to conf_remap
// override the policy.:w
//
//
// to be rejected
// in the end_remap logic
const char *sni_value = netvc->get_server_name();
const char *action_value = host_sni_policy == 2 ? "terminate" : "continue";
if (!sni_value || sni_value[0] == '\0') { // No SNI
Warning("No SNI for TLS request with hostname %.*s action=%s", host_len, host_name, action_value);
SMDebug("ssl_sni", "No SNI for TLS request with hostname %.*s action=%s", host_len, host_name, action_value);
if (host_sni_policy == 2) {
ts::bwprint(error_bw_buffer, "No SNI for TLS request: connecting to {} for host='{}', returning a 403",
t_state.client_info.dst_addr, std::string_view{host_name, static_cast<size_t>(host_len)});
Log::error("%s", error_bw_buffer.c_str());
this->t_state.client_connection_enabled = false;
}
} else if (strncasecmp(host_name, sni_value, host_len) != 0) { // Name mismatch
Warning("SNI/hostname mismatch sni=%s host=%.*s action=%s", sni_value, host_len, host_name, action_value);
SMDebug("ssl_sni", "SNI/hostname mismatch sni=%s host=%.*s action=%s", sni_value, host_len, host_name, action_value);
if (host_sni_policy == 2) {
ts::bwprint(error_bw_buffer, "SNI/hostname mismatch: connecting to {} for host='{}' sni='{}', returning a 403",
t_state.client_info.dst_addr, std::string_view{host_name, static_cast<size_t>(host_len)}, sni_value);
Log::error("%s", error_bw_buffer.c_str());
this->t_state.client_connection_enabled = false;
}
} else {
SMDebug("ssl_sni", "SNI/hostname sucessfully match sni=%s host=%.*s", sni_value, host_len, host_name);
}
} else {
SMDebug("ssl_sni", "No SNI/hostname check configured for host=%.*s", host_len, host_name);
}
}
}
}
}
void
HttpSM::do_remap_request(bool run_inline)
{
SMDebug("http_seq", "Remapping request");
SMDebug("url_rewrite", "Starting a possible remapping for request");
bool ret = remapProcessor.setup_for_remap(&t_state, m_remap);
check_sni_host();
// Depending on a variety of factors the HOST field may or may not have been promoted to the
// client request URL. The unmapped URL should always have that promotion done. If the HOST field
// is not already there, promote it only in the unmapped_url. This avoids breaking any logic that
// depends on the lack of promotion in the client request URL.
if (!t_state.unmapped_url.m_url_impl->m_ptr_host) {
MIMEField *host_field = t_state.hdr_info.client_request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
if (host_field) {
int host_len = 0;
const char *host_name = host_field->value_get(&host_len);
if (host_name && host_len) {
int port = -1;
// Host header can contain port number, and if it does we need to set host and port separately to unmapped_url.
// If header value starts with '[', the value must contain an IPv6 address, and it may contain a port number as well.
if (host_name[0] == '[') { // IPv6
host_name = host_name + 1; // Skip '['
host_len--;
// If header value ends with ']', the value must only contain an IPv6 address (no port number).
if (host_name[host_len - 1] == ']') { // Without port number
host_len--; // Exclude ']'
} else { // With port number
for (int idx = host_len - 1; idx > 0; idx--) {
if (host_name[idx] == ':') {
port = ink_atoi(host_name + idx + 1, host_len - (idx + 1));
host_len = idx;
break;
}
}
}
} else { // Anything else (Hostname or IPv4 address)
// If the value contains ':' where it does not have IPv6 address, there must be port number
if (const char *colon = static_cast<const char *>(memchr(host_name, ':', host_len));
colon == nullptr) { // Without port number
// Nothing to adjust. Entire value should be used as hostname.
} else { // With port number
port = ink_atoi(colon + 1, host_len - ((colon + 1) - host_name));
host_len = colon - host_name;
}
}
// Set values
t_state.unmapped_url.host_set(host_name, host_len);
if (port >= 0) {
t_state.unmapped_url.port_set(port);
}
}
}
}
if (!ret) {
SMDebug("url_rewrite", "Could not find a valid remapping entry for this request");
if (!run_inline) {
handleEvent(EVENT_REMAP_COMPLETE, nullptr);
}
return;
}
SMDebug("url_rewrite", "Found a remap map entry, attempting to remap request and call any plugins");
Action *remap_action_handle = remapProcessor.perform_remap(this, &t_state);
if (remap_action_handle != ACTION_RESULT_DONE) {
SMDebug("url_rewrite", "Still more remapping needed for [%" PRId64 "]", sm_id);
ink_assert(!pending_action);
pending_action = remap_action_handle;
}
return;
}
void
HttpSM::do_hostdb_lookup()
{
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
milestones[TS_MILESTONE_DNS_LOOKUP_BEGIN] = ink_get_hrtime();
// If directed to not look up fqdns then mark as resolved
if (t_state.http_config_param->no_dns_forward_to_parent && t_state.parent_result.result == PARENT_UNDEFINED) {
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
return;
} else if (t_state.txn_conf->srv_enabled) {
char d[MAXDNAME];
// Look at the next_hop_scheme to determine what scheme to put in the SRV lookup
unsigned int scheme_len = sprintf(d, "_%s._tcp.", hdrtoken_index_to_wks(t_state.next_hop_scheme));
ink_strlcpy(d + scheme_len, t_state.server_info.name, sizeof(d) - scheme_len);
SMDebug("dns_srv", "Beginning lookup of SRV records for origin %s", d);
HostDBProcessor::Options opt;
if (t_state.api_txn_dns_timeout_value != -1) {
opt.timeout = t_state.api_txn_dns_timeout_value;
}
Action *srv_lookup_action_handle =
hostDBProcessor.getSRVbyname_imm(this, (cb_process_result_pfn)&HttpSM::process_srv_info, d, 0, opt);
if (srv_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = srv_lookup_action_handle;
} else {
char *host_name = t_state.dns_info.srv_lookup_success ? t_state.dns_info.srv_hostname : t_state.dns_info.lookup_name;
opt.port = t_state.dns_info.srv_lookup_success ?
t_state.dns_info.srv_port :
t_state.server_info.dst_addr.isValid() ? t_state.server_info.dst_addr.host_order_port() :
t_state.hdr_info.client_request.port_get();
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style =
ats_host_res_from(ua_txn->get_netvc()->get_local_addr()->sa_family, t_state.txn_conf->host_res_data.order);
Action *dns_lookup_action_handle =
hostDBProcessor.getbyname_imm(this, (cb_process_result_pfn)&HttpSM::process_hostdb_info, host_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
}
return;
} else { /* we aren't using SRV stuff... */
SMDebug("http_seq", "Doing DNS Lookup");
// If there is not a current server, we must be looking up the origin
// server at the beginning of the transaction
int server_port = 0;
if (t_state.current.server && t_state.current.server->dst_addr.isValid()) {
server_port = t_state.current.server->dst_addr.host_order_port();
} else if (t_state.server_info.dst_addr.isValid()) {
server_port = t_state.server_info.dst_addr.host_order_port();
} else {
server_port = t_state.hdr_info.client_request.port_get();
}
if (t_state.api_txn_dns_timeout_value != -1) {
SMDebug("http_timeout", "beginning DNS lookup. allowing %d mseconds for DNS lookup", t_state.api_txn_dns_timeout_value);
}
HostDBProcessor::Options opt;
opt.port = server_port;
opt.flags = (t_state.cache_info.directives.does_client_permit_dns_storing) ? HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS :
HostDBProcessor::HOSTDB_FORCE_DNS_RELOAD;
opt.timeout = (t_state.api_txn_dns_timeout_value != -1) ? t_state.api_txn_dns_timeout_value : 0;
opt.host_res_style = ats_host_res_from(ua_txn->get_netvc()->get_local_addr()->sa_family, t_state.txn_conf->host_res_data.order);
Action *dns_lookup_action_handle = hostDBProcessor.getbyname_imm(this, (cb_process_result_pfn)&HttpSM::process_hostdb_info,
t_state.dns_info.lookup_name, 0, opt);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
} else {
call_transact_and_set_next_state(nullptr);
}
return;
}
ink_assert(!"not reached");
return;
}
void
HttpSM::do_hostdb_reverse_lookup()
{
ink_assert(t_state.dns_info.lookup_name != nullptr);
ink_assert(pending_action == nullptr);
SMDebug("http_seq", "Doing reverse DNS Lookup");
IpEndpoint addr;
ats_ip_pton(t_state.dns_info.lookup_name, &addr.sa);
Action *dns_lookup_action_handle = hostDBProcessor.getbyaddr_re(this, &addr.sa);
if (dns_lookup_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = dns_lookup_action_handle;
}
return;
}
bool
HttpSM::track_connect_fail() const
{
bool retval = false;
if (t_state.current.server->had_connect_fail()) {
// What does our policy say?
if (t_state.txn_conf->connect_dead_policy == 2) { // Any connection error through TLS handshake
retval = true;
} else if (t_state.txn_conf->connect_dead_policy == 1) { // Any connection error through TCP
retval = t_state.current.server->connect_result != -ENET_SSL_CONNECT_FAILED;
}
}
return retval;
}
void
HttpSM::do_hostdb_update_if_necessary()
{
int issue_update = 0;
if (t_state.current.server == nullptr || plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// No server, so update is not necessary
return;
}
// If we failed back over to the origin server, we don't have our
// hostdb information anymore which means we shouldn't update the hostdb
if (!ats_ip_addr_eq(&t_state.current.server->dst_addr.sa, t_state.host_db_info.ip())) {
SMDebug("http", "skipping hostdb update due to server failover");
return;
}
if (t_state.updated_server_version != HTTP_INVALID) {
// we may have incorrectly assumed that the hostdb had the wrong version of
// http for the server because our first few connect attempts to the server
// failed, causing us to downgrade our requests to a lower version and changing
// our information about the server version.
//
// This test therefore just issues the update only if the hostdb version is
// in fact different from the version we want the value to be updated to.
if (t_state.host_db_info.app.http_data.http_version != t_state.updated_server_version) {
t_state.host_db_info.app.http_data.http_version = t_state.updated_server_version;
issue_update |= 1;
}
t_state.updated_server_version = HTTP_INVALID;
}
// Check to see if we need to report or clear a connection failure
if (track_connect_fail()) {
issue_update |= 1;
mark_host_failure(&t_state.host_db_info, t_state.client_request_time);
} else {
if (t_state.host_db_info.app.http_data.last_failure != 0) {
t_state.host_db_info.app.http_data.last_failure = 0;
t_state.host_db_info.app.http_data.fail_count = 0;
issue_update |= 1;
char addrbuf[INET6_ADDRPORTSTRLEN];
SMDebug("http", "hostdb update marking IP: %s as up",
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
if (t_state.dns_info.srv_lookup_success && t_state.dns_info.srv_app.http_data.last_failure != 0) {
t_state.dns_info.srv_app.http_data.last_failure = 0;
hostDBProcessor.setby_srv(t_state.dns_info.lookup_name, 0, t_state.dns_info.srv_hostname, &t_state.dns_info.srv_app);
SMDebug("http", "hostdb update marking SRV: %s as up", t_state.dns_info.srv_hostname);
}
}
if (issue_update) {
hostDBProcessor.setby(t_state.current.server->name, strlen(t_state.current.server->name), &t_state.current.server->dst_addr.sa,
&t_state.host_db_info.app);
}
char addrbuf[INET6_ADDRPORTSTRLEN];
SMDebug("http", "server info = %s", ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
return;
}
/*
* range entry valid [a,b] (a >= 0 and b >= 0 and a <= b)
* HttpTransact::RANGE_NONE if the content length of cached copy is zero or
* no range entry
* HttpTransact::RANGE_NOT_SATISFIABLE iff all range entries are valid but
* none overlap the current extent of the cached copy
* HttpTransact::RANGE_NOT_HANDLED if out-of-order Range entries or
* the cached copy`s content_length is INT64_MAX (e.g. read_from_writer and trunked)
* HttpTransact::RANGE_REQUESTED if all sub range entries are valid and
* in order (remove the entries that not overlap the extent of cache copy)
*/
void
HttpSM::parse_range_and_compare(MIMEField *field, int64_t content_length)
{
int prev_good_range = -1;
const char *value;
int value_len;
int n_values;
int nr = 0; // number of valid ranges, also index to range array.
int not_satisfy = 0;
HdrCsvIter csv;
const char *s, *e, *tmp;
RangeRecord *ranges = nullptr;
int64_t start, end;
ink_assert(field != nullptr && t_state.range_setup == HttpTransact::RANGE_NONE && t_state.ranges == nullptr);
if (content_length <= 0) {
return;
}
// ToDo: Can this really happen?
if (content_length == INT64_MAX) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
return;
}
if (parse_range_done) {
SMDebug("http_range", "parse_range already done, t_state.range_setup %d", t_state.range_setup);
return;
}
parse_range_done = true;
n_values = 0;
value = csv.get_first(field, &value_len);
while (value) {
++n_values;
value = csv.get_next(&value_len);
}
value = csv.get_first(field, &value_len);
if (n_values <= 0 || ptr_len_ncmp(value, value_len, "bytes=", 6)) {
return;
}
ranges = new RangeRecord[n_values];
value += 6; // skip leading 'bytes='
value_len -= 6;
// assume range_in_cache
t_state.range_in_cache = true;
for (; value; value = csv.get_next(&value_len)) {
if (!(tmp = static_cast<const char *>(memchr(value, '-', value_len)))) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
// process start value
s = value;
e = tmp;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
start = -1;
} else {
for (start = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
// check the int64 overflow in case of high gcc with O3 option
// thinking the start is always positive
int64_t new_start = start * 10 + (*s - '0');
if (new_start < start) { // Overflow
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
start = new_start;
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
}
// process end value
s = tmp + 1;
e = value + value_len;
// skip leading white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s >= e) {
if (start < 0) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
} else if (start >= content_length) {
not_satisfy++;
continue;
}
end = content_length - 1;
} else {
for (end = 0; s < e && *s >= '0' && *s <= '9'; ++s) {
// check the int64 overflow in case of high gcc with O3 option
// thinking the start is always positive
int64_t new_end = end * 10 + (*s - '0');
if (new_end < end) { // Overflow
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
end = new_end;
}
// skip last white spaces
for (; s < e && ParseRules::is_ws(*s); ++s) {
;
}
if (s < e) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (start < 0) {
if (end >= content_length) {
end = content_length;
}
start = content_length - end;
end = content_length - 1;
} else if (start >= content_length && start <= end) {
not_satisfy++;
continue;
}
if (end >= content_length) {
end = content_length - 1;
}
}
if (start > end) {
t_state.range_setup = HttpTransact::RANGE_NONE;
goto Lfaild;
}
if (prev_good_range >= 0 && start <= ranges[prev_good_range]._end) {
t_state.range_setup = HttpTransact::RANGE_NOT_HANDLED;
goto Lfaild;
}
ink_assert(start >= 0 && end >= 0 && start < content_length && end < content_length);
prev_good_range = nr;
ranges[nr]._start = start;
ranges[nr]._end = end;
++nr;
if (cache_sm.cache_read_vc && t_state.cache_info.object_read) {
if (!cache_sm.cache_read_vc->is_pread_capable() && cache_config_read_while_writer == 2) {
// write in progress, check if request range not in cache yet
HTTPInfo::FragOffset *frag_offset_tbl = t_state.cache_info.object_read->get_frag_table();
int frag_offset_cnt = t_state.cache_info.object_read->get_frag_offset_count();
if (!frag_offset_tbl || !frag_offset_cnt || (frag_offset_tbl[frag_offset_cnt - 1] < static_cast<uint64_t>(end))) {
SMDebug("http_range", "request range in cache, end %" PRId64 ", frg_offset_cnt %d" PRId64, end, frag_offset_cnt);
t_state.range_in_cache = false;
}
}
} else {
t_state.range_in_cache = false;
}
}
if (nr > 0) {
t_state.range_setup = HttpTransact::RANGE_REQUESTED;
t_state.ranges = ranges;
t_state.num_range_fields = nr;
return;
}
if (not_satisfy) {
t_state.range_setup = HttpTransact::RANGE_NOT_SATISFIABLE;
}
Lfaild:
t_state.range_in_cache = false;
t_state.num_range_fields = -1;
delete[] ranges;
return;
}
void
HttpSM::calculate_output_cl(int64_t num_chars_for_ct, int64_t num_chars_for_cl)
{
if (t_state.range_setup != HttpTransact::RANGE_REQUESTED && t_state.range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
return;
}
ink_assert(t_state.ranges);
if (t_state.num_range_fields == 1) {
t_state.range_output_cl = t_state.ranges[0]._end - t_state.ranges[0]._start + 1;
} else {
for (int i = 0; i < t_state.num_range_fields; i++) {
if (t_state.ranges[i]._start >= 0) {
t_state.range_output_cl += boundary_size;
t_state.range_output_cl += sub_header_size + num_chars_for_ct;
t_state.range_output_cl +=
num_chars_for_int(t_state.ranges[i]._start) + num_chars_for_int(t_state.ranges[i]._end) + num_chars_for_cl + 2;
t_state.range_output_cl += t_state.ranges[i]._end - t_state.ranges[i]._start + 1;
t_state.range_output_cl += 2;
}
}
t_state.range_output_cl += boundary_size + 2;
}
SMDebug("http_range", "Pre-calculated Content-Length for Range response is %" PRId64, t_state.range_output_cl);
}
void
HttpSM::do_range_parse(MIMEField *range_field)
{
int num_chars_for_ct = 0;
int64_t content_length = 0;
if (t_state.cache_info.object_read != nullptr) {
t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &num_chars_for_ct);
content_length = t_state.cache_info.object_read->object_size_get();
} else {
content_length = t_state.hdr_info.server_response.get_content_length();
t_state.hdr_info.server_response.value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &num_chars_for_ct);
}
int64_t num_chars_for_cl = num_chars_for_int(content_length);
parse_range_and_compare(range_field, content_length);
calculate_output_cl(num_chars_for_ct, num_chars_for_cl);
}
// this function looks for any Range: headers, parses them and either
// sets up a transform processor to handle the request OR defers to the
// HttpTunnel
void
HttpSM::do_range_setup_if_necessary()
{
MIMEField *field;
field = t_state.hdr_info.client_request.field_find(MIME_FIELD_RANGE, MIME_LEN_RANGE);
ink_assert(field != nullptr);
t_state.range_setup = HttpTransact::RANGE_NONE;
if (t_state.method == HTTP_WKSIDX_GET && t_state.hdr_info.client_request.version_get() == HTTP_1_1) {
do_range_parse(field);
if (t_state.range_setup == HttpTransact::RANGE_REQUESTED) {
bool do_transform = false;
if (!t_state.range_in_cache && t_state.cache_info.object_read) {
SMDebug("http_range", "range can't be satisfied from cache, force origin request");
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_MISS;
return;
}
if (t_state.num_range_fields > 1) {
if (0 == t_state.txn_conf->allow_multi_range) {
t_state.range_setup = HttpTransact::RANGE_NONE; // No Range required (not allowed)
t_state.hdr_info.client_request.field_delete(MIME_FIELD_RANGE, MIME_LEN_RANGE); // ... and nuke the Range header too
t_state.num_range_fields = 0;
} else if (1 == t_state.txn_conf->allow_multi_range) {
do_transform = true;
} else {
t_state.num_range_fields = 0;
t_state.range_setup = HttpTransact::RANGE_NOT_SATISFIABLE;
}
} else {
// if revalidating and cache is stale we want to transform
if (t_state.cache_info.action == HttpTransact::CACHE_DO_REPLACE) {
if (t_state.hdr_info.server_response.status_get() == HTTP_STATUS_OK) {
Debug("http_range", "Serving transform after stale cache re-serve");
do_transform = true;
} else {
Debug("http_range", "Not transforming after revalidate");
}
} else if (cache_sm.cache_read_vc && cache_sm.cache_read_vc->is_pread_capable()) {
// If only one range entry and pread is capable, no need transform range
t_state.range_setup = HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED;
} else {
do_transform = true;
}
}
// We have to do the transform on (allowed) multi-range request, *or* if the VC is not pread capable
if (do_transform) {
if (api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK) == nullptr) {
int field_content_type_len = -1;
const char *content_type = nullptr;
int64_t content_length = 0;
if (t_state.cache_info.object_read && t_state.cache_info.action != HttpTransact::CACHE_DO_REPLACE) {
content_type = t_state.cache_info.object_read->response_get()->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE,
&field_content_type_len);
content_length = t_state.cache_info.object_read->object_size_get();
} else {
// We don't want to transform a range request if the server response has a content encoding.
if (t_state.hdr_info.server_response.presence(MIME_PRESENCE_CONTENT_ENCODING)) {
Debug("http_trans", "Cannot setup range transform for server response with content encoding");
t_state.range_setup = HttpTransact::RANGE_NONE;
return;
}
// Since we are transforming the range from the server, we want to cache the original response
t_state.api_info.cache_untransformed = true;
content_type =
t_state.hdr_info.server_response.value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &field_content_type_len);
content_length = t_state.hdr_info.server_response.get_content_length();
}
SMDebug("http_trans", "Unable to accelerate range request, fallback to transform");
// create a Range: transform processor for requests of type Range: bytes=1-2,4-5,10-100 (eg. multiple ranges)
INKVConnInternal *range_trans = transformProcessor.range_transform(mutex.get(), t_state.ranges, t_state.num_range_fields,
&t_state.hdr_info.transform_response, content_type,
field_content_type_len, content_length);
api_hooks.append(TS_HTTP_RESPONSE_TRANSFORM_HOOK, range_trans);
} else {
// ToDo: Do we do something here? The theory is that multiple transforms do not behave well with
// the range transform needed here.
}
}
}
}
}
void
HttpSM::do_cache_lookup_and_read()
{
// TODO decide whether to uncomment after finish testing redirect
// ink_assert(server_txn == NULL);
ink_assert(pending_action == nullptr);
t_state.request_sent_time = UNDEFINED_TIME;
t_state.response_received_time = UNDEFINED_TIME;
HTTP_INCREMENT_DYN_STAT(http_cache_lookups_stat);
milestones[TS_MILESTONE_CACHE_OPEN_READ_BEGIN] = ink_get_hrtime();
t_state.cache_lookup_result = HttpTransact::CACHE_LOOKUP_NONE;
t_state.cache_info.lookup_count++;
// YTS Team, yamsat Plugin
// Changed the lookup_url to c_url which enables even
// the new redirect url to perform a CACHE_LOOKUP
URL *c_url;
if (t_state.redirect_info.redirect_in_process && !t_state.txn_conf->redirect_use_orig_cache_key) {
c_url = t_state.hdr_info.client_request.url_get();
} else {
c_url = t_state.cache_info.lookup_url;
}
SMDebug("http_seq", "Issuing cache lookup for URL %s", c_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, c_url, t_state.txn_conf->cache_generation_number);
t_state.hdr_info.cache_request.copy(&t_state.hdr_info.client_request);
HttpTransactHeaders::normalize_accept_encoding(t_state.txn_conf, &t_state.hdr_info.cache_request);
Action *cache_action_handle = cache_sm.open_read(
&key, c_url, &t_state.hdr_info.cache_request, t_state.txn_conf,
static_cast<time_t>((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for));
//
// pin_in_cache value is an open_write parameter.
// It is passed in open_read to allow the cluster to
// optimize the typical open_read/open_read failed/open_write
// sequence.
//
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
REMEMBER((long)pending_action, reentrancy_count);
return;
}
void
HttpSM::do_cache_delete_all_alts(Continuation *cont)
{
// Do not delete a non-existent object.
ink_assert(t_state.cache_info.object_read);
SMDebug("http_seq", "Issuing cache delete for %s", t_state.cache_info.lookup_url->string_get_ref());
Action *cache_action_handle = nullptr;
HttpCacheKey key;
Cache::generate_key(&key, t_state.cache_info.lookup_url, t_state.txn_conf->cache_generation_number);
cache_action_handle = cacheProcessor.remove(cont, &key);
if (cont != nullptr) {
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
return;
}
inline void
HttpSM::do_cache_prepare_write()
{
milestones[TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN] = ink_get_hrtime();
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, true);
}
inline void
HttpSM::do_cache_prepare_write_transform()
{
if (cache_sm.cache_write_vc != nullptr || tunnel.has_cache_writer()) {
do_cache_prepare_action(&transform_cache_sm, nullptr, false, true);
} else {
do_cache_prepare_action(&transform_cache_sm, nullptr, false);
}
}
void
HttpSM::do_cache_prepare_update()
{
if (t_state.cache_info.object_read != nullptr && t_state.cache_info.object_read->valid() &&
t_state.cache_info.object_store.valid() && t_state.cache_info.object_store.response_get() != nullptr &&
t_state.cache_info.object_store.response_get()->valid() &&
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET) {
t_state.cache_info.object_store.request_set(t_state.cache_info.object_read->request_get());
// t_state.cache_info.object_read = NULL;
// cache_sm.close_read();
t_state.transact_return_point = HttpTransact::HandleUpdateCachedObject;
ink_assert(cache_sm.cache_write_vc == nullptr);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
// don't retry read for update
do_cache_prepare_action(&cache_sm, t_state.cache_info.object_read, false);
} else {
t_state.api_modifiable_cached_resp = false;
call_transact_and_set_next_state(HttpTransact::HandleApiErrorJump);
}
}
void
HttpSM::do_cache_prepare_action(HttpCacheSM *c_sm, CacheHTTPInfo *object_read_info, bool retry, bool allow_multiple)
{
URL *o_url, *s_url;
bool restore_client_request = false;
ink_assert(!pending_action);
if (t_state.redirect_info.redirect_in_process) {
o_url = &(t_state.redirect_info.original_url);
ink_assert(o_url->valid());
restore_client_request = true;
s_url = o_url;
} else {
o_url = &(t_state.cache_info.original_url);
if (o_url->valid()) {
s_url = o_url;
} else {
s_url = t_state.cache_info.lookup_url;
}
}
// modify client request to make it have the url we are going to
// store into the cache
if (restore_client_request) {
URL *c_url = t_state.hdr_info.client_request.url_get();
s_url->copy(c_url);
}
ink_assert(s_url != nullptr && s_url->valid());
SMDebug("http_cache_write", "writing to cache with URL %s", s_url->string_get(&t_state.arena));
HttpCacheKey key;
Cache::generate_key(&key, s_url, t_state.txn_conf->cache_generation_number);
Action *cache_action_handle =
c_sm->open_write(&key, s_url, &t_state.hdr_info.cache_request, object_read_info,
static_cast<time_t>((t_state.cache_control.pin_in_cache_for < 0) ? 0 : t_state.cache_control.pin_in_cache_for),
retry, allow_multiple);
if (cache_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = cache_action_handle;
}
}
void
HttpSM::send_origin_throttled_response()
{
// if the request is to a parent proxy, do not reset
// t_state.current.attempts so that another parent or
// NextHop may be tried.
if (t_state.current.request_to != HttpTransact::PARENT_PROXY) {
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries;
}
t_state.current.state = HttpTransact::OUTBOUND_CONGESTION;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
static void
set_tls_options(NetVCOptions &opt, const OverridableHttpConfigParams *txn_conf)
{
char *verify_server = nullptr;
if (txn_conf->ssl_client_verify_server_policy == nullptr) {
opt.verifyServerPolicy = YamlSNIConfig::Policy::UNSET;
} else {
verify_server = txn_conf->ssl_client_verify_server_policy;
if (strcmp(verify_server, "DISABLED") == 0) {
opt.verifyServerPolicy = YamlSNIConfig::Policy::DISABLED;
} else if (strcmp(verify_server, "PERMISSIVE") == 0) {
opt.verifyServerPolicy = YamlSNIConfig::Policy::PERMISSIVE;
} else if (strcmp(verify_server, "ENFORCED") == 0) {
opt.verifyServerPolicy = YamlSNIConfig::Policy::ENFORCED;
} else {
Warning("%s is invalid for proxy.config.ssl.client.verify.server.policy. Should be one of DISABLED, PERMISSIVE, or ENFORCED",
verify_server);
opt.verifyServerPolicy = YamlSNIConfig::Policy::UNSET;
}
}
if (txn_conf->ssl_client_verify_server_properties == nullptr) {
opt.verifyServerProperties = YamlSNIConfig::Property::UNSET;
} else {
verify_server = txn_conf->ssl_client_verify_server_properties;
if (strcmp(verify_server, "SIGNATURE") == 0) {
opt.verifyServerProperties = YamlSNIConfig::Property::SIGNATURE_MASK;
} else if (strcmp(verify_server, "NAME") == 0) {
opt.verifyServerProperties = YamlSNIConfig::Property::NAME_MASK;
} else if (strcmp(verify_server, "ALL") == 0) {
opt.verifyServerProperties = YamlSNIConfig::Property::ALL_MASK;
} else if (strcmp(verify_server, "NONE") == 0) {
opt.verifyServerProperties = YamlSNIConfig::Property::NONE;
} else {
Warning("%s is invalid for proxy.config.ssl.client.verify.server.properties. Should be one of SIGNATURE, NAME, or ALL",
verify_server);
opt.verifyServerProperties = YamlSNIConfig::Property::NONE;
}
}
}
std::string_view
HttpSM::get_outbound_cert() const
{
const char *cert_name = t_state.txn_conf->ssl_client_cert_filename;
if (cert_name == nullptr) {
cert_name = "";
}
return std::string_view(cert_name);
}
std::string_view
HttpSM::get_outbound_sni() const
{
using namespace ts::literals;
ts::TextView zret;
ts::TextView policy{t_state.txn_conf->ssl_client_sni_policy, ts::TextView::npos};
if (ua_txn) {
if (const NetVConnection *netvc = ua_txn->get_netvc(); netvc->options.outbound_sni_policy) {
policy.assign(netvc->options.outbound_sni_policy.get(), ts::TextView::npos);
}
}
if (policy.empty() || !strcmp(policy, "host"_tv)) {
// By default the host header field value is used for the SNI.
int len;
char const *ptr = t_state.hdr_info.server_request.host_get(&len);
zret.assign(ptr, len);
} else if (ua_txn && !strcmp(policy, "server_name"_tv)) {
zret.assign(ua_txn->get_netvc()->get_server_name(), ts::TextView::npos);
} else if (policy.front() == '@') { // guaranteed non-empty from previous clause
zret = policy.remove_prefix(1);
} else {
// If other is specified, like "remap" and "verify_with_name_source", the remapped origin name is used for the SNI value
zret.assign(t_state.server_info.name, ts::TextView::npos);
}
return zret;
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::do_http_server_open()
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::do_http_server_open(bool raw)
{
int ip_family = t_state.current.server->dst_addr.sa.sa_family;
auto fam_name = ats_ip_family_name(ip_family);
SMDebug("http_track", "entered inside do_http_server_open ][%.*s]", static_cast<int>(fam_name.size()), fam_name.data());
// Make sure we are on the "right" thread
if (ua_txn) {
if ((pending_action = ua_txn->adjust_thread(this, EVENT_INTERVAL, nullptr))) {
HTTP_INCREMENT_DYN_STAT(http_origin_connect_adjust_thread_stat);
return; // Go away if we reschedule
}
}
pending_action = nullptr;
ink_assert(server_entry == nullptr);
// Clean up connection tracking info if any. Need to do it now so the selected group
// is consistent with the actual upstream in case of retry.
t_state.outbound_conn_track_state.clear();
// Make sure any previous attempts are cleaned out
if (server_txn) {
tunnel.reset();
server_txn->transaction_done();
server_txn = nullptr;
}
// ua_entry can be null if a scheduled update is also a reverse proxy
// request. Added REVPROXY to the assert below, and then changed checks
// to be based on ua_txn != NULL instead of req_flavor value.
ink_assert(ua_entry != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
ink_assert(pending_action == nullptr);
ink_assert(t_state.current.server->dst_addr.network_order_port() != 0);
char addrbuf[INET6_ADDRPORTSTRLEN];
SMDebug("http", "open connection to %s: %s", t_state.current.server->name,
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
SMDebug("http_seq", "Sending request to server");
// set the server first connect milestone here in case we return in the plugin_tunnel case that follows
milestones[TS_MILESTONE_SERVER_CONNECT] = ink_get_hrtime();
if (milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] == 0) {
milestones[TS_MILESTONE_SERVER_FIRST_CONNECT] = milestones[TS_MILESTONE_SERVER_CONNECT];
}
if (plugin_tunnel) {
PluginVCCore *t = plugin_tunnel;
plugin_tunnel = nullptr;
Action *pvc_action_handle = t->connect_re(this);
// This connect call is always reentrant
ink_release_assert(pvc_action_handle == ACTION_RESULT_DONE);
return;
}
// Check for remap rule. If so, only apply ip_allow filter if it is activated (ip_allow_check_enabled_p set).
// Otherwise, if no remap rule is defined, apply the ip_allow filter.
if (!t_state.url_remap_success || t_state.url_map.getMapping()->ip_allow_check_enabled_p) {
// Method allowed on dest IP address check
sockaddr *server_ip = &t_state.current.server->dst_addr.sa;
IpAllow::ACL acl = IpAllow::match(server_ip, IpAllow::DST_ADDR);
bool deny_request = false; // default is fail open.
int method = t_state.hdr_info.server_request.method_get_wksidx();
int method_str_len = 0;
const char *method_str = nullptr;
if (acl.isValid()) {
if (acl.isDenyAll()) {
deny_request = true;
} else if (!acl.isAllowAll()) {
if (method != -1) {
deny_request = !acl.isMethodAllowed(method);
} else {
method_str = t_state.hdr_info.server_request.method_get(&method_str_len);
deny_request = !acl.isNonstandardMethodAllowed(std::string_view(method_str, method_str_len));
}
}
}
if (deny_request) {
if (is_debug_tag_set("ip-allow")) {
ip_text_buffer ipb;
if (method != -1) {
method_str = hdrtoken_index_to_wks(method);
method_str_len = strlen(method_str);
} else if (!method_str) {
method_str = t_state.hdr_info.client_request.method_get(&method_str_len);
}
Warning("server '%s' prohibited by ip-allow policy at line %d", ats_ip_ntop(server_ip, ipb, sizeof(ipb)),
acl.source_line());
SMDebug("ip-allow", "Line %d denial for '%.*s' from %s", acl.source_line(), method_str_len, method_str,
ats_ip_ntop(server_ip, ipb, sizeof(ipb)));
}
t_state.current.attempts = t_state.txn_conf->connect_attempts_max_retries; // prevent any more retries with this IP
call_transact_and_set_next_state(HttpTransact::Forbidden);
return;
}
if (HttpTransact::is_server_negative_cached(&t_state) == true &&
t_state.txn_conf->connect_attempts_max_retries_dead_server <= 0) {
call_transact_and_set_next_state(HttpTransact::OriginDead);
return;
}
}
// Check for self loop.
if (!ua_txn->is_outbound_transparent() && HttpTransact::will_this_request_self_loop(&t_state)) {
call_transact_and_set_next_state(HttpTransact::SelfLoop);
return;
}
// If this is not a raw connection, we try to get a session from the
// shared session pool. Raw connections are for SSLs tunnel and
// require a new connection
//
// This problem with POST requests is a bug. Because of the issue of the
// race with us sending a request after server has closed but before the FIN
// gets to us, we should open a new connection for POST. I believe TS used
// to do this but as far I can tell the code that prevented keep-alive if
// there is a request body has been removed.
// If we are sending authorizations headers, mark the connection private
//
// We do this here because it means that we will not waste a connection from the pool if we already
// know that the session will be private. This is overridable meaning that if a plugin later decides
// it shouldn't be private it can still be returned to a shared pool.
//
if (t_state.txn_conf->auth_server_session_private == 1 &&
t_state.hdr_info.server_request.presence(MIME_PRESENCE_AUTHORIZATION | MIME_PRESENCE_PROXY_AUTHORIZATION |
MIME_PRESENCE_WWW_AUTHENTICATE)) {
SMDebug("http_ss_auth", "Setting server session to private for authorization header");
will_be_private_ss = true;
}
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
// don't share the session if keep-alive for post is not on
if (t_state.txn_conf->keep_alive_post_out == 0) {
SMDebug("http_ss", "Setting server session to private because of keep-alive post out");
will_be_private_ss = true;
}
}
bool try_reuse = false;
if ((raw == false) && TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match &&
(t_state.txn_conf->keep_alive_post_out == 1 || t_state.hdr_info.request_content_length <= 0) && !is_private() &&
ua_txn != nullptr) {
HSMresult_t shared_result;
shared_result = httpSessionManager.acquire_session(this, // state machine
&t_state.current.server->dst_addr.sa, // ip + port
t_state.current.server->name, // hostname
ua_txn // has ptr to bound ua sessions
);
try_reuse = true;
switch (shared_result) {
case HSM_DONE:
HTTP_INCREMENT_DYN_STAT(http_origin_reuse);
hsm_release_assert(server_txn != nullptr);
handle_http_server_open();
return;
case HSM_NOT_FOUND:
HTTP_INCREMENT_DYN_STAT(http_origin_not_found);
hsm_release_assert(server_txn == nullptr);
break;
case HSM_RETRY:
HTTP_INCREMENT_DYN_STAT(http_origin_reuse_fail);
// Could not get shared pool lock
// FIX: should retry lock
break;
default:
hsm_release_assert(0);
}
}
// Avoid a problem where server session sharing is disabled and we have keep-alive, we are trying to open a new server
// session when we already have an attached server session.
else if ((TS_SERVER_SESSION_SHARING_MATCH_NONE == t_state.txn_conf->server_session_sharing_match || is_private()) &&
(ua_txn != nullptr)) {
PoolableSession *existing_ss = ua_txn->get_server_session();
if (existing_ss) {
// [amc] Not sure if this is the best option, but we don't get here unless session sharing is disabled
// so there's no point in further checking on the match or pool values. But why check anything? The
// client has already exchanged a request with this specific origin server and has sent another one
// shouldn't we just automatically keep the association?
if (ats_ip_addr_port_eq(existing_ss->get_remote_addr(), &t_state.current.server->dst_addr.sa)) {
ua_txn->attach_server_session(nullptr);
existing_ss->set_active();
this->create_server_txn(existing_ss);
hsm_release_assert(server_txn != nullptr);
handle_http_server_open();
return;
} else {
// As this is in the non-sharing configuration, we want to close
// the existing connection and call connect_re to get a new one
existing_ss->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release(server_txn);
ua_txn->attach_server_session(nullptr);
}
}
}
// Otherwise, we release the existing connection and call connect_re
// to get a new one.
// ua_txn is null when t_state.req_flavor == REQ_FLAVOR_SCHEDULED_UPDATE
else if (ua_txn != nullptr) {
PoolableSession *existing_ss = ua_txn->get_server_session();
if (existing_ss) {
existing_ss->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
existing_ss->release(server_txn);
ua_txn->attach_server_session(nullptr);
}
}
if (!try_reuse) {
HTTP_INCREMENT_DYN_STAT(http_origin_make_new);
if (TS_SERVER_SESSION_SHARING_MATCH_NONE == t_state.txn_conf->server_session_sharing_match) {
HTTP_INCREMENT_DYN_STAT(http_origin_no_sharing);
} else if ((t_state.txn_conf->keep_alive_post_out != 1 && t_state.hdr_info.request_content_length > 0)) {
HTTP_INCREMENT_DYN_STAT(http_origin_body);
} else if (is_private()) {
HTTP_INCREMENT_DYN_STAT(http_origin_private);
} else if (raw) {
HTTP_INCREMENT_DYN_STAT(http_origin_raw);
} else {
ink_release_assert(ua_txn == nullptr);
}
}
// Check to see if we have reached the max number of connections.
// Atomically read the current number of connections and check to see
// if we have gone above the max allowed.
if (t_state.http_config_param->server_max_connections > 0) {
int64_t sum;
HTTP_READ_GLOBAL_DYN_SUM(http_current_server_connections_stat, sum);
// Note that there is a potential race condition here where
// the value of the http_current_server_connections_stat gets changed
// between the statement above and the check below.
// If this happens, we might go over the max by 1 but this is ok.
if (sum >= t_state.http_config_param->server_max_connections) {
httpSessionManager.purge_keepalives();
// Eventually may want to have a queue as the origin_max_connection does to allow for a combination
// of retries and errors. But at this point, we are just going to allow the error case.
t_state.current.state = HttpTransact::CONNECTION_ERROR;
call_transact_and_set_next_state(HttpTransact::HandleResponse);
return;
}
}
// See if the outbound connection tracker data is needed. If so, get it here for consistency.
if (t_state.txn_conf->outbound_conntrack.max > 0 || t_state.txn_conf->outbound_conntrack.min > 0) {
t_state.outbound_conn_track_state = OutboundConnTrack::obtain(
t_state.txn_conf->outbound_conntrack, std::string_view{t_state.current.server->name}, t_state.current.server->dst_addr);
}
// Check to see if we have reached the max number of connections on this upstream host.
if (t_state.txn_conf->outbound_conntrack.max > 0) {
auto &ct_state = t_state.outbound_conn_track_state;
auto ccount = ct_state.reserve();
if (ccount > t_state.txn_conf->outbound_conntrack.max) {
ct_state.release();
ink_assert(pending_action == nullptr); // in case of reschedule must not have already pending.
// If the queue is disabled, reschedule.
if (t_state.http_config_param->global_outbound_conntrack.queue_size < 0) {
ct_state.enqueue();
ct_state.rescheduled();
pending_action = eventProcessor.schedule_in(
this, HRTIME_MSECONDS(t_state.http_config_param->global_outbound_conntrack.queue_delay.count()));
} else if (t_state.http_config_param->global_outbound_conntrack.queue_size > 0) { // queue enabled, check for a slot
auto wcount = ct_state.enqueue();
if (wcount < t_state.http_config_param->global_outbound_conntrack.queue_size) {
ct_state.rescheduled();
SMDebug("http", "%s", lbw().print("queued for {}\0", t_state.current.server->dst_addr).data());
pending_action = eventProcessor.schedule_in(
this, HRTIME_MSECONDS(t_state.http_config_param->global_outbound_conntrack.queue_delay.count()));
} else { // the queue is full
ct_state.dequeue(); // release the queue slot
ct_state.blocked(); // note the blockage.
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
send_origin_throttled_response();
}
} else { // queue size is 0, always block.
ct_state.blocked();
HTTP_INCREMENT_DYN_STAT(http_origin_connections_throttled_stat);
ct_state.Warn_Blocked(&t_state.txn_conf->outbound_conntrack, sm_id, ccount - 1, &t_state.current.server->dst_addr.sa,
debug_on && is_debug_tag_set("http") ? "http" : nullptr);
send_origin_throttled_response();
}
return;
} else {
ct_state.Note_Unblocked(&t_state.txn_conf->outbound_conntrack, ccount, &t_state.current.server->dst_addr.sa);
}
ct_state.update_max_count(ccount);
}
// We did not manage to get an existing session and need to open a new connection
Action *connect_action_handle;
NetVCOptions opt;
opt.f_blocking_connect = false;
opt.set_sock_param(t_state.txn_conf->sock_recv_buffer_size_out, t_state.txn_conf->sock_send_buffer_size_out,
t_state.txn_conf->sock_option_flag_out, t_state.txn_conf->sock_packet_mark_out,
t_state.txn_conf->sock_packet_tos_out, t_state.txn_conf->sock_packet_notsent_lowat);
set_tls_options(opt, t_state.txn_conf);
opt.ip_family = ip_family;
int scheme_to_use = t_state.scheme; // get initial scheme
bool tls_upstream = scheme_to_use == URL_WKSIDX_HTTPS;
if (ua_txn) {
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(ua_txn->get_netvc());
if (ssl_vc && raw) {
tls_upstream = ssl_vc->upstream_tls();
_tunnel_type = ssl_vc->tunnel_type();
// ALPN on TLS Partial Blind Tunnel - set negotiated ALPN id
int pid = SessionProtocolNameRegistry::INVALID;
if (ssl_vc->tunnel_type() == SNIRoutingType::PARTIAL_BLIND) {
pid = ssl_vc->get_negotiated_protocol_id();
if (pid != SessionProtocolNameRegistry::INVALID) {
opt.alpn_protos = SessionProtocolNameRegistry::convert_openssl_alpn_wire_format(pid);
}
}
//
// Grab pre-warmed NetVConnection if possible
//
PreWarmConfig::scoped_config prewarm_conf;
bool use_prewarm = prewarm_conf->enabled;
// override "proxy.config.tunnel.prewarm" by "tunnel_prewarm" in sni.yaml
if (YamlSNIConfig::TunnelPreWarm sni_use_prewarm = ssl_vc->tunnel_prewarm();
sni_use_prewarm != YamlSNIConfig::TunnelPreWarm::UNSET) {
use_prewarm = static_cast<bool>(sni_use_prewarm);
}
if (use_prewarm) {
// TODO: avoid copy of string -> make map key std::variant
PreWarm::SPtrConstDst dst =
std::make_shared<const PreWarm::Dst>(ssl_vc->get_tunnel_host(), ssl_vc->get_tunnel_port(),
tls_upstream ? SNIRoutingType::PARTIAL_BLIND : SNIRoutingType::FORWARD, pid);
EThread *ethread = this_ethread();
_prewarm_sm = ethread->prewarm_queue->dequeue(dst);
if (_prewarm_sm != nullptr) {
NetVConnection *netvc = _prewarm_sm->move_netvc();
ink_release_assert(_prewarm_sm->handler == &PreWarmSM::state_closed);
SMDebug("http_ss", "using pre-warmed tunnel netvc=%p", netvc);
t_state.current.attempts = 0;
ink_release_assert(default_handler == HttpSM::default_handler);
handleEvent(NET_EVENT_OPEN, netvc);
return;
}
SMDebug("http_ss", "no pre-warmed tunnel");
}
}
opt.local_port = ua_txn->get_outbound_port();
const IpAddr &outbound_ip = AF_INET6 == opt.ip_family ? ua_txn->get_outbound_ip6() : ua_txn->get_outbound_ip4();
if (outbound_ip.isValid()) {
opt.addr_binding = NetVCOptions::INTF_ADDR;
opt.local_ip = outbound_ip;
} else if (ua_txn->is_outbound_transparent()) {
opt.addr_binding = NetVCOptions::FOREIGN_ADDR;
opt.local_ip = t_state.client_info.src_addr;
/* If the connection is server side transparent, we can bind to the
port that the client chose instead of randomly assigning one at
the proxy. This is controlled by the 'use_client_source_port'
configuration parameter.
*/
NetVConnection *client_vc = ua_txn->get_netvc();
if (t_state.http_config_param->use_client_source_port && nullptr != client_vc) {
opt.local_port = client_vc->get_remote_port();
}
}
}
if (!t_state.is_websocket) { // if not websocket, then get scheme from server request
int new_scheme_to_use = t_state.hdr_info.server_request.url_get()->scheme_get_wksidx();
// if the server_request url scheme was never set, try the client_request
if (new_scheme_to_use < 0) {
new_scheme_to_use = t_state.hdr_info.client_request.url_get()->scheme_get_wksidx();
}
if (new_scheme_to_use >= 0) { // found a new scheme, use it
scheme_to_use = new_scheme_to_use;
}
if (!raw || !tls_upstream) {
tls_upstream = scheme_to_use == URL_WKSIDX_HTTPS;
}
}
// draft-stenberg-httpbis-tcp recommends only enabling TFO on idempotent methods or
// those with intervening protocol layers (eg. TLS).
if (tls_upstream || HttpTransactHeaders::is_method_idempotent(t_state.method)) {
opt.f_tcp_fastopen = (t_state.txn_conf->sock_option_flag_out & NetVCOptions::SOCK_OPT_TCP_FAST_OPEN);
}
opt.set_ssl_client_cert_name(t_state.txn_conf->ssl_client_cert_filename);
opt.ssl_client_private_key_name = t_state.txn_conf->ssl_client_private_key_filename;
opt.ssl_client_ca_cert_name = t_state.txn_conf->ssl_client_ca_cert_filename;
if (tls_upstream) {
SMDebug("http", "calling sslNetProcessor.connect_re");
std::string_view sni_name = this->get_outbound_sni();
if (sni_name.length() > 0) {
opt.set_sni_servername(sni_name.data(), sni_name.length());
}
int len = 0;
if (t_state.txn_conf->ssl_client_sni_policy != nullptr &&
!strcmp(t_state.txn_conf->ssl_client_sni_policy, "verify_with_name_source")) {
// also set sni_hostname with host header from server request in this policy
const char *host = t_state.hdr_info.server_request.host_get(&len);
if (host && len > 0) {
opt.set_sni_hostname(host, len);
}
}
if (t_state.server_info.name) {
opt.set_ssl_servername(t_state.server_info.name);
}
connect_action_handle = sslNetProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
} else {
SMDebug("http", "calling netProcessor.connect_re");
connect_action_handle = netProcessor.connect_re(this, // state machine
&t_state.current.server->dst_addr.sa, // addr + port
&opt);
}
if (connect_action_handle != ACTION_RESULT_DONE) {
ink_assert(!pending_action);
pending_action = connect_action_handle;
}
return;
}
int
HttpSM::do_api_callout_internal()
{
switch (t_state.api_next_action) {
case HttpTransact::SM_ACTION_API_SM_START:
cur_hook_id = TS_HTTP_TXN_START_HOOK;
break;
case HttpTransact::SM_ACTION_API_PRE_REMAP:
cur_hook_id = TS_HTTP_PRE_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_POST_REMAP:
cur_hook_id = TS_HTTP_POST_REMAP_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
cur_hook_id = TS_HTTP_READ_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_REQUEST_BUFFER_READ_COMPLETE:
cur_hook_id = TS_HTTP_REQUEST_BUFFER_READ_COMPLETE_HOOK;
break;
case HttpTransact::SM_ACTION_API_OS_DNS:
cur_hook_id = TS_HTTP_OS_DNS_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
cur_hook_id = TS_HTTP_SEND_REQUEST_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
cur_hook_id = TS_HTTP_READ_CACHE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE:
cur_hook_id = TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK;
break;
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
cur_hook_id = TS_HTTP_READ_RESPONSE_HDR_HOOK;
break;
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
cur_hook_id = TS_HTTP_SEND_RESPONSE_HDR_HOOK;
milestones[TS_MILESTONE_UA_BEGIN_WRITE] = ink_get_hrtime();
break;
case HttpTransact::SM_ACTION_API_SM_SHUTDOWN:
if (callout_state == HTTP_API_IN_CALLOUT || callout_state == HTTP_API_DEFERED_SERVER_ERROR) {
callout_state = HTTP_API_DEFERED_CLOSE;
return 0;
} else {
cur_hook_id = TS_HTTP_TXN_CLOSE_HOOK;
}
break;
default:
cur_hook_id = static_cast<TSHttpHookID>(-1);
ink_assert(!"not reached");
}
hook_state.init(cur_hook_id, http_global_hooks, ua_txn ? ua_txn->feature_hooks() : nullptr, &api_hooks);
cur_hook = nullptr;
cur_hooks = 0;
return state_api_callout(0, nullptr);
}
VConnection *
HttpSM::do_post_transform_open()
{
ink_assert(post_transform_info.vc == nullptr);
if (is_action_tag_set("http_post_nullt")) {
txn_hook_add(TS_HTTP_REQUEST_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
post_transform_info.vc = transformProcessor.open(this, api_hooks.get(TS_HTTP_REQUEST_TRANSFORM_HOOK));
if (post_transform_info.vc) {
// Record the transform VC in our table
post_transform_info.entry = vc_table.new_entry();
post_transform_info.entry->vc = post_transform_info.vc;
post_transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
}
return post_transform_info.vc;
}
VConnection *
HttpSM::do_transform_open()
{
ink_assert(transform_info.vc == nullptr);
APIHook *hooks;
if (is_action_tag_set("http_nullt")) {
txn_hook_add(TS_HTTP_RESPONSE_TRANSFORM_HOOK, transformProcessor.null_transform(mutex.get()));
}
hooks = api_hooks.get(TS_HTTP_RESPONSE_TRANSFORM_HOOK);
if (hooks) {
transform_info.vc = transformProcessor.open(this, hooks);
// Record the transform VC in our table
transform_info.entry = vc_table.new_entry();
transform_info.entry->vc = transform_info.vc;
transform_info.entry->vc_type = HTTP_TRANSFORM_VC;
} else {
transform_info.vc = nullptr;
}
return transform_info.vc;
}
void
HttpSM::mark_host_failure(HostDBInfo *info, time_t time_down)
{
char addrbuf[INET6_ADDRPORTSTRLEN];
if (time_down) {
// Increment the fail_count
++info->app.http_data.fail_count;
if (info->app.http_data.fail_count >= t_state.txn_conf->connect_attempts_rr_retries) {
if (info->app.http_data.last_failure == 0) {
char *url_str = t_state.hdr_info.client_request.url_string_get(&t_state.arena, nullptr);
int host_len;
const char *host_name_ptr = t_state.unmapped_url.host_get(&host_len);
std::string_view host_name{host_name_ptr, size_t(host_len)};
ts::bwprint(error_bw_buffer, "CONNECT: {::s} connecting to {} for host='{}' url='{}' marking down",
ts::bwf::Errno(t_state.current.server->connect_result), t_state.current.server->dst_addr, host_name,
ts::bwf::FirstOf(url_str, "<none>"));
Log::error("%s", error_bw_buffer.c_str());
if (url_str) {
t_state.arena.str_free(url_str);
}
}
info->app.http_data.last_failure = time_down;
SMDebug("http", "hostdb update marking IP: %s as down",
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
} else {
SMDebug("http", "hostdb increment IP failcount %s to %d",
ats_ip_nptop(&t_state.current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)), info->app.http_data.fail_count);
}
} else { // Clear the failure
info->app.http_data.fail_count = 0;
info->app.http_data.last_failure = time_down;
}
#ifdef DEBUG
ink_assert(ink_local_time() + t_state.txn_conf->down_server_timeout > time_down);
#endif
}
void
HttpSM::set_ua_abort(HttpTransact::AbortState_t ua_abort, int event)
{
t_state.client_info.abort = ua_abort;
switch (ua_abort) {
case HttpTransact::ABORTED:
// More detailed client side abort logging based on event
switch (event) {
case VC_EVENT_ERROR:
t_state.squid_codes.log_code = SQUID_LOG_ERR_CLIENT_READ_ERROR;
break;
case VC_EVENT_EOS:
case VC_EVENT_ACTIVE_TIMEOUT: // Won't matter. Server will hangup
case VC_EVENT_INACTIVITY_TIMEOUT: // Won't matter. Send back 408
// Fall-through
default:
t_state.squid_codes.log_code = SQUID_LOG_ERR_CLIENT_ABORT;
break;
}
break;
default:
// Handled here:
// HttpTransact::ABORT_UNDEFINED, HttpTransact::DIDNOT_ABORT
break;
}
// Set the connection attribute code for the client so that
// we log the client finish code correctly
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.client_info.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
t_state.client_info.state = HttpTransact::INACTIVE_TIMEOUT;
break;
case VC_EVENT_ERROR:
t_state.client_info.state = HttpTransact::CONNECTION_ERROR;
break;
}
}
// void HttpSM::release_server_session()
//
// Called when we are not tunneling a response from the
// server. If the session is keep alive, release it back to the
// shared pool, otherwise close it
//
void
HttpSM::release_server_session(bool serve_from_cache)
{
if (server_txn == nullptr) {
return;
}
if (TS_SERVER_SESSION_SHARING_MATCH_NONE != t_state.txn_conf->server_session_sharing_match && t_state.current.server != nullptr &&
t_state.current.server->keep_alive == HTTP_KEEPALIVE && t_state.hdr_info.server_response.valid() &&
t_state.hdr_info.server_request.valid() &&
(t_state.hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED ||
(t_state.hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD &&
t_state.www_auth_content != HttpTransact::CACHE_AUTH_NONE)) &&
plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL && (!server_entry || !server_entry->eos)) {
if (t_state.www_auth_content == HttpTransact::CACHE_AUTH_NONE || serve_from_cache == false) {
// Must explicitly set the keep_alive_no_activity time before doing the release
server_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->keep_alive_no_activity_timeout_out));
server_txn->release();
} else {
// an authenticated server connection - attach to the local client
// we are serving from cache for the current transaction
t_state.www_auth_content = HttpTransact::CACHE_AUTH_SERVE;
ua_txn->attach_server_session(static_cast<PoolableSession *>(server_txn->get_proxy_ssn()), false);
}
} else {
server_txn->do_io_close();
if (TS_SERVER_SESSION_SHARING_MATCH_NONE == t_state.txn_conf->server_session_sharing_match) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_no_sharing);
} else if (t_state.current.server == nullptr) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_no_server);
} else if (t_state.current.server->keep_alive != HTTP_KEEPALIVE) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_no_keep_alive);
} else if (!t_state.hdr_info.server_response.valid()) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_invalid_response);
} else if (!t_state.hdr_info.server_request.valid()) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_invalid_request);
} else if (t_state.hdr_info.server_response.status_get() != HTTP_STATUS_NOT_MODIFIED &&
(t_state.hdr_info.server_request.method_get_wksidx() != HTTP_WKSIDX_HEAD ||
t_state.www_auth_content == HttpTransact::CACHE_AUTH_NONE)) {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_modified);
} else {
HTTP_INCREMENT_DYN_STAT(http_origin_shutdown_release_misc);
}
}
if (server_entry) {
server_entry->vc = nullptr;
server_entry->read_vio = nullptr;
server_entry->write_vio = nullptr;
server_entry = nullptr;
}
}
// void HttpSM::handle_post_failure()
//
// We failed in our attempt post (or put) a document
// to the server. Two cases happen here. The normal
// one is the server died, in which case we ought to
// return an error to the client. The second one is
// stupid. The server returned a response without reading
// all the post data. In order to be as transparent as
// possible process the server's response
void
HttpSM::handle_post_failure()
{
STATE_ENTER(&HttpSM::handle_post_failure, VC_EVENT_NONE);
ink_assert(ua_entry->vc == ua_txn);
ink_assert(is_waiting_for_full_body || server_entry->eos == true);
if (is_waiting_for_full_body) {
call_transact_and_set_next_state(HttpTransact::Forbidden);
return;
}
// First order of business is to clean up from
// the tunnel
// note: since the tunnel is providing the buffer for a lingering
// client read (for abort watching purposes), we need to stop
// the read
if (false == t_state.redirect_info.redirect_in_process) {
ua_entry->read_vio = ua_txn->do_io_read(this, 0, nullptr);
}
ua_entry->in_tunnel = false;
server_entry->in_tunnel = false;
// disable redirection in case we got a partial response and then EOS, because the buffer might not
// have the full post and it's deallocating the post buffers here
this->disable_redirect();
// Don't even think about doing keep-alive after this debacle
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
ink_assert(server_txn->get_remote_reader()->read_avail() == 0);
tunnel.deallocate_buffers();
tunnel.reset();
// Server died
if (t_state.current.state == HttpTransact::STATE_UNDEFINED || t_state.current.state == HttpTransact::CONNECTION_ALIVE) {
t_state.set_connect_fail(server_txn->get_netvc()->lerrno);
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
}
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
// void HttpSM::handle_http_server_open()
//
// The server connection is now open. If there is a POST or PUT,
// we need setup a transform is there is one otherwise we need
// to send the request header
//
void
HttpSM::handle_http_server_open()
{
// The request is now not queued. This is important because server retries reuse the t_state.
t_state.outbound_conn_track_state.dequeue();
// [bwyatt] applying per-transaction OS netVC options here
// IFF they differ from the netVC's current options.
// This should keep this from being redundant on a
// server session's first transaction.
if (nullptr != server_txn) {
NetVConnection *vc = server_txn->get_netvc();
if (vc) {
server_connection_provided_cert = vc->provided_cert();
if (vc->options.sockopt_flags != t_state.txn_conf->sock_option_flag_out ||
vc->options.packet_mark != t_state.txn_conf->sock_packet_mark_out ||
vc->options.packet_tos != t_state.txn_conf->sock_packet_tos_out ||
vc->options.packet_notsent_lowat != t_state.txn_conf->sock_packet_notsent_lowat) {
vc->options.sockopt_flags = t_state.txn_conf->sock_option_flag_out;
vc->options.packet_mark = t_state.txn_conf->sock_packet_mark_out;
vc->options.packet_tos = t_state.txn_conf->sock_packet_tos_out;
vc->options.packet_notsent_lowat = t_state.txn_conf->sock_packet_notsent_lowat;
vc->apply_options();
}
}
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
}
int method = t_state.hdr_info.server_request.method_get_wksidx();
if (method != HTTP_WKSIDX_TRACE &&
(t_state.hdr_info.request_content_length > 0 || t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) &&
do_post_transform_open()) {
do_setup_post_tunnel(HTTP_TRANSFORM_VC); // Seems like we should be sending the request along this way too
} else if (server_txn != nullptr) {
setup_server_send_request_api();
}
}
// void HttpSM::handle_server_setup_error(int event, void* data)
//
// Handles setting t_state.current.state and calling
// Transact in between opening an origin server connection
// and receiving the response header (in the case of the
// POST, a post tunnel happens in between the sending
// request header and reading the response header
//
void
HttpSM::handle_server_setup_error(int event, void *data)
{
VIO *vio = static_cast<VIO *>(data);
ink_assert(vio != nullptr);
STATE_ENTER(&HttpSM::handle_server_setup_error, event);
// If there is POST or PUT tunnel wait for the tunnel
// to figure out that things have gone to hell
if (tunnel.is_tunnel_active()) {
ink_assert(server_entry->read_vio == data || server_entry->write_vio == data);
SMDebug("http", "forwarding event %s to post tunnel", HttpDebugNames::get_event_name(event));
HttpTunnelConsumer *c = tunnel.get_consumer(server_entry->vc);
// it is possible only user agent post->post transform is set up
// this happened for Linux iocore where NET_EVENT_OPEN was returned
// for a non-existing listening port. the hack is to pass the error
// event for server connection to post_transform_info
if (c == nullptr && post_transform_info.vc) {
c = tunnel.get_consumer(post_transform_info.vc);
// c->handler_state = HTTP_SM_TRANSFORM_FAIL;
// No point in proceeding if there is no consumer
// Do we need to do additional clean up in the c == NULL case?
if (c != nullptr) {
HttpTunnelProducer *ua_producer = c->producer;
ink_assert(ua_entry->vc == ua_producer->vc);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
ua_entry->read_vio = ua_producer->vc->do_io_read(this, INT64_MAX, c->producer->read_buffer);
ua_producer->vc->do_io_shutdown(IO_SHUTDOWN_READ);
ua_producer->alive = false;
ua_producer->handler_state = HTTP_SM_POST_SERVER_FAIL;
tunnel.handleEvent(VC_EVENT_ERROR, c->write_vio);
return;
}
} else {
// c could be null here as well
if (c != nullptr) {
tunnel.handleEvent(event, c->write_vio);
return;
}
}
// If there is no consumer, let the event pass through to shutdown
} else {
if (post_transform_info.vc) {
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
if (c && c->handler_state == HTTP_SM_TRANSFORM_OPEN) {
vc_table.cleanup_entry(post_transform_info.entry);
post_transform_info.entry = nullptr;
tunnel.deallocate_buffers();
tunnel.reset();
}
}
}
switch (event) {
case VC_EVENT_EOS:
t_state.current.state = HttpTransact::CONNECTION_CLOSED;
t_state.set_connect_fail(EPIPE);
break;
case VC_EVENT_ERROR:
t_state.current.state = HttpTransact::CONNECTION_ERROR;
t_state.set_connect_fail(server_txn->get_netvc()->lerrno);
break;
case VC_EVENT_ACTIVE_TIMEOUT:
t_state.set_connect_fail(ETIMEDOUT);
t_state.current.state = HttpTransact::ACTIVE_TIMEOUT;
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
// If we're writing the request and get an inactivity timeout
// before any bytes are written, the connection to the
// server failed
// In case of TIMEOUT, the iocore sends back
// server_entry->read_vio instead of the write_vio
t_state.set_connect_fail(ETIMEDOUT);
if (server_entry->write_vio && server_entry->write_vio->nbytes > 0 && server_entry->write_vio->ndone == 0) {
t_state.current.state = HttpTransact::CONNECTION_ERROR;
} else {
t_state.current.state = HttpTransact::INACTIVE_TIMEOUT;
}
break;
default:
ink_release_assert(0);
}
if (event == VC_EVENT_INACTIVITY_TIMEOUT || event == VC_EVENT_ERROR || event == VC_EVENT_EOS) {
// Clean up the vc_table entry so any events in play to the timed out server vio
// don't get handled. The connection isn't there.
if (server_entry) {
ink_assert(server_entry->vc_type == HTTP_SERVER_VC);
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
}
}
// Closedown server connection and deallocate buffers
ink_assert(!server_entry || server_entry->in_tunnel == false);
// if we are waiting on a plugin callout for
// HTTP_API_SEND_REQUEST_HDR defer calling transact until
// after we've finished processing the plugin callout
switch (callout_state) {
case HTTP_API_NO_CALLOUT:
// Normal fast path case, no api callouts in progress
break;
case HTTP_API_IN_CALLOUT:
case HTTP_API_DEFERED_SERVER_ERROR:
// Callout in progress note that we are in deferring
// the server error
callout_state = HTTP_API_DEFERED_SERVER_ERROR;
return;
case HTTP_API_DEFERED_CLOSE:
// The user agent has shutdown killing the sm
// but we are stuck waiting for the server callout
// to finish so do nothing here. We don't care
// about the server connection at this and are
// just waiting till we can execute the close hook
return;
default:
ink_release_assert(0);
}
call_transact_and_set_next_state(HttpTransact::HandleResponse);
}
void
HttpSM::setup_transform_to_server_transfer()
{
ink_assert(post_transform_info.vc != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
int64_t nbytes = t_state.hdr_info.transform_request_cl;
int64_t alloc_index = buffer_size_to_index(nbytes, t_state.http_config_param->max_payload_iobuf_index);
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
HttpTunnelConsumer *c = tunnel.get_consumer(post_transform_info.vc);
HttpTunnelProducer *p = tunnel.add_producer(post_transform_info.vc, nbytes, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "post transform");
tunnel.chain(c, p);
post_transform_info.entry->in_tunnel = true;
tunnel.add_consumer(server_entry->vc, post_transform_info.vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"http server post");
server_entry->in_tunnel = true;
tunnel.tunnel_run(p);
}
void
HttpSM::do_drain_request_body(HTTPHdr &response)
{
int64_t content_length = t_state.hdr_info.client_request.get_content_length();
int64_t avail = ua_txn->get_remote_reader()->read_avail();
if (t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
SMDebug("http", "Chunked body, setting the response to non-keepalive");
goto close_connection;
}
if (content_length > 0) {
if (avail >= content_length) {
SMDebug("http", "entire body is in the buffer, consuming");
int64_t act_on = (avail < content_length) ? avail : content_length;
client_request_body_bytes = act_on;
ua_txn->get_remote_reader()->consume(act_on);
} else {
SMDebug("http", "entire body is not in the buffer, setting the response to non-keepalive");
goto close_connection;
}
}
return;
close_connection:
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
ua_txn->set_close_connection(response);
}
void
HttpSM::do_setup_post_tunnel(HttpVC_t to_vc_type)
{
bool chunked = t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING ||
t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL;
bool post_redirect = false;
HttpTunnelProducer *p = nullptr;
// YTS Team, yamsat Plugin
// if redirect_in_process and redirection is enabled add static producer
if (is_using_post_buffer ||
(t_state.redirect_info.redirect_in_process && enable_redirection && this->_postbuf.postdata_copy_buffer_start != nullptr)) {
post_redirect = true;
// copy the post data into a new producer buffer for static producer
MIOBuffer *postdata_producer_buffer = new_empty_MIOBuffer(t_state.http_config_param->max_payload_iobuf_index);
IOBufferReader *postdata_producer_reader = postdata_producer_buffer->alloc_reader();
postdata_producer_buffer->write(this->_postbuf.postdata_copy_buffer_start);
int64_t post_bytes = postdata_producer_reader->read_avail();
transfered_bytes = post_bytes;
p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, post_bytes, postdata_producer_reader, (HttpProducerHandler) nullptr,
HT_STATIC, "redirect static agent post");
} else {
int64_t alloc_index;
// content length is undefined, use default buffer size
if (t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL) {
alloc_index = static_cast<int>(t_state.txn_conf->default_buffer_size_index);
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > MAX_BUFFER_SIZE_INDEX) {
alloc_index = DEFAULT_REQUEST_BUFFER_SIZE_INDEX;
}
} else {
alloc_index =
buffer_size_to_index(t_state.hdr_info.request_content_length, t_state.http_config_param->max_payload_iobuf_index);
}
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
int64_t post_bytes = chunked ? INT64_MAX : t_state.hdr_info.request_content_length;
if (enable_redirection) {
this->_postbuf.init(post_buffer->clone_reader(buf_start));
}
// Note: Many browsers, Netscape and IE included send two extra
// bytes (CRLF) at the end of the post. We just ignore those
// bytes since the sending them is not spec
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes =
post_buffer->write(ua_txn->get_remote_reader(), chunked ? ua_txn->get_remote_reader()->read_avail() : post_bytes);
ua_txn->get_remote_reader()->consume(client_request_body_bytes);
p = tunnel.add_producer(ua_entry->vc, post_bytes - transfered_bytes, buf_start, &HttpSM::tunnel_handler_post_ua, HT_HTTP_CLIENT,
"user agent post");
}
ua_entry->in_tunnel = true;
switch (to_vc_type) {
case HTTP_TRANSFORM_VC:
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_request_wait_for_transform_read);
ink_assert(post_transform_info.entry != nullptr);
ink_assert(post_transform_info.entry->vc == post_transform_info.vc);
tunnel.add_consumer(post_transform_info.entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"post transform");
post_transform_info.entry->in_tunnel = true;
break;
case HTTP_SERVER_VC:
// YTS Team, yamsat Plugin
// When redirect in process is true and redirection is enabled
// add http server as the consumer
if (post_redirect) {
chunked = false;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_for_partial_post);
tunnel.add_consumer(server_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER,
"redirect http server post");
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_post_server, HT_HTTP_SERVER, "http server post");
}
server_entry->in_tunnel = true;
break;
default:
ink_release_assert(0);
break;
}
// The user agent may support chunked (HTTP/1.1) or not (HTTP/2)
// In either case, the server will support chunked (HTTP/1.1)
if (chunked) {
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
if (ua_txn->is_chunked_encoding_supported()) {
tunnel.set_producer_chunking_action(p, 0, TCA_PASSTHRU_CHUNKED_CONTENT, drop_chunked_trailers);
} else {
tunnel.set_producer_chunking_action(p, 0, TCA_CHUNK_CONTENT, drop_chunked_trailers);
tunnel.set_producer_chunking_size(p, 0);
}
}
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
tunnel.tunnel_run(p);
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
// HttpTunnel could broken due to bad chunked data and close all vc by chain_abort_all().
if (p->handler_state != HTTP_SM_POST_UA_FAIL && ua_txn->get_half_close_flag()) {
p->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
// void HttpSM::perform_transform_cache_write_action()
//
// Called to do cache write from the transform
//
void
HttpSM::perform_transform_cache_write_action()
{
SMDebug("http", "%s", HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
if (t_state.range_setup) {
SMDebug("http", "perform_transform_cache_write_action %s (with range setup)",
HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
}
switch (t_state.cache_info.transform_action) {
case HttpTransact::CACHE_DO_NO_ACTION: {
// Nothing to do
transform_cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_WRITE: {
if (t_state.api_info.cache_untransformed == false) {
transform_cache_sm.close_read();
t_state.cache_info.transform_write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&transform_cache_sm, transform_info.entry->vc, &t_state.cache_info.transform_store,
client_response_hdr_bytes, "cache write t");
}
break;
}
default:
ink_release_assert(0);
break;
}
}
// void HttpSM::perform_cache_write_action()
//
// Called to do cache write, delete and updates based
// on s->cache_info.action. Does not setup cache
// read tunnels
//
void
HttpSM::perform_cache_write_action()
{
SMDebug("http", "%s", HttpDebugNames::get_cache_action_name(t_state.cache_info.action));
switch (t_state.cache_info.action) {
case HttpTransact::CACHE_DO_NO_ACTION:
{
// Nothing to do
cache_sm.end_both();
break;
}
case HttpTransact::CACHE_DO_SERVE: {
cache_sm.abort_write();
break;
}
case HttpTransact::CACHE_DO_DELETE: {
// Write close deletes the old alternate
cache_sm.close_write();
cache_sm.close_read();
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_DELETE: {
// FIX ME: need to set up delete for after cache write has
// completed
break;
}
case HttpTransact::CACHE_DO_SERVE_AND_UPDATE: {
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_UPDATE: {
cache_sm.close_read();
issue_cache_update();
break;
}
case HttpTransact::CACHE_DO_WRITE:
case HttpTransact::CACHE_DO_REPLACE:
// Fix need to set up delete for after cache write has
// completed
if (transform_info.entry == nullptr || t_state.api_info.cache_untransformed == true) {
cache_sm.close_read();
t_state.cache_info.write_status = HttpTransact::CACHE_WRITE_IN_PROGRESS;
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, client_response_hdr_bytes,
"cache write");
} else {
// We are not caching the untransformed. We might want to
// use the cache writevc to cache the transformed copy
ink_assert(transform_cache_sm.cache_write_vc == nullptr);
transform_cache_sm.cache_write_vc = cache_sm.cache_write_vc;
cache_sm.cache_write_vc = nullptr;
}
break;
default:
ink_release_assert(0);
break;
}
}
void
HttpSM::issue_cache_update()
{
ink_assert(cache_sm.cache_write_vc != nullptr);
if (cache_sm.cache_write_vc) {
t_state.cache_info.object_store.request_sent_time_set(t_state.request_sent_time);
t_state.cache_info.object_store.response_received_time_set(t_state.response_received_time);
ink_assert(t_state.cache_info.object_store.request_sent_time_get() > 0);
ink_assert(t_state.cache_info.object_store.response_received_time_get() > 0);
cache_sm.cache_write_vc->set_http_info(&t_state.cache_info.object_store);
t_state.cache_info.object_store.clear();
}
// Now close the write which commits the update
cache_sm.close_write();
}
int
HttpSM::write_header_into_buffer(HTTPHdr *h, MIOBuffer *b)
{
int dumpoffset;
int done;
dumpoffset = 0;
do {
IOBufferBlock *block = b->get_current_block();
int bufindex = 0;
int tmp = dumpoffset;
ink_assert(block->write_avail() > 0);
done = h->print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
ink_assert(bufindex > 0);
b->fill(bufindex);
if (!done) {
b->add_block();
}
} while (!done);
return dumpoffset;
}
void
HttpSM::attach_server_session()
{
hsm_release_assert(server_entry == nullptr);
// In the h1 only origin version, the transact_count was updated after making this assignment.
// The SSN-TXN-COUNT option in header rewrite relies on this fact, so we decrement here so the
// plugin API interface is consistent as we move to more protocols to origin
server_transact_count = server_txn->get_proxy_ssn()->get_transact_count() - 1;
// update the dst_addr when using an existing session
// for e.g using Host based session pools may ignore the DNS IP
IpEndpoint addr;
addr.assign(server_txn->get_remote_addr());
if (!ats_ip_addr_eq(&t_state.current.server->dst_addr, &addr)) {
ip_port_text_buffer ipb1, ipb2;
SMDebug("http_ss", "updating ip when attaching server session from %s to %s",
ats_ip_ntop(&t_state.current.server->dst_addr.sa, ipb1, sizeof(ipb1)),
ats_ip_ntop(server_txn->get_remote_addr(), ipb2, sizeof(ipb2)));
ats_ip_copy(&t_state.current.server->dst_addr, server_txn->get_remote_addr());
}
// Propagate the per client IP debugging
if (ua_txn) {
server_txn->get_netvc()->control_flags.set_flags(get_cont_flags().get_flags());
} else { // If there is no ua_txn no sense in continuing to attach the server session
return;
}
// Set the mutex so that we have something to update
// stats with
server_txn->mutex = this->mutex;
server_txn->increment_transactions_stat();
// Record the VC in our table
server_entry = vc_table.new_entry();
server_entry->vc = server_txn;
server_entry->vc_type = HTTP_SERVER_VC;
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
UnixNetVConnection *server_vc = static_cast<UnixNetVConnection *>(server_txn->get_netvc());
// set flag for server session is SSL
SSLNetVConnection *server_ssl_vc = dynamic_cast<SSLNetVConnection *>(server_vc);
if (server_ssl_vc) {
server_connection_is_ssl = true;
}
if (auto tsrs = dynamic_cast<TLSSessionResumptionSupport *>(server_vc)) {
server_ssl_reused = tsrs->getSSLOriginSessionCacheHit();
}
server_protocol = server_txn->get_protocol_string();
// Initiate a read on the session so that the SM and not
// session manager will get called back if the timeout occurs
// or the server closes on us. The IO Core now requires us to
// do the read with a buffer and a size so preallocate the
// buffer
// ts-3189 We are only setting up an empty read at this point. This
// is sufficient to have the timeout errors directed to the appropriate
// SM handler, but we don't want to read any data until the tunnel has
// been set up. This isn't such a big deal with GET results, since
// if no tunnels are set up, there is no danger of data being delivered
// to the wrong tunnel's consumer handler. But for post and other
// methods that send data after the request, two tunnels are created in
// series, and with a full read set up at this point, the EOS from the
// first tunnel was sometimes behind handled by the consumer of the
// first tunnel instead of the producer of the second tunnel.
// The real read is setup in setup_server_read_response_header()
server_entry->read_vio = server_txn->do_io_read(this, 0, server_txn->get_remote_reader()->mbuf);
// Transfer control of the write side as well
server_entry->write_vio = server_txn->do_io_write(this, 0, nullptr);
// Setup the timeouts
// Set the inactivity timeout to the connect timeout so that we
// we fail this server if it doesn't start sending the response
// header
server_txn->set_inactivity_timeout(get_server_connect_timeout());
server_txn->set_active_timeout(get_server_active_timeout());
// Do we need Transfer_Encoding?
if (ua_txn->has_request_body(t_state.hdr_info.request_content_length,
t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
// See if we need to insert a chunked header
if (!t_state.hdr_info.server_request.presence(MIME_PRESENCE_CONTENT_LENGTH) &&
!t_state.hdr_info.server_request.presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
// Stuff in a TE setting so we treat this as chunked, sort of.
t_state.server_info.transfer_encoding = HttpTransact::CHUNKED_ENCODING;
t_state.hdr_info.server_request.value_append(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING, HTTP_VALUE_CHUNKED,
HTTP_LEN_CHUNKED, true);
}
}
if (plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL || is_private()) {
this->set_server_session_private(true);
}
}
void
HttpSM::setup_server_send_request_api()
{
// Make sure the VC is on the correct timeout
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR;
do_api_callout();
}
void
HttpSM::setup_server_send_request()
{
int hdr_length;
int64_t msg_len = 0; /* lv: just make gcc happy */
hsm_release_assert(server_entry != nullptr);
hsm_release_assert(server_txn != nullptr);
hsm_release_assert(server_entry->vc == server_txn);
// Send the request header
server_entry->vc_handler = &HttpSM::state_send_server_request_header;
server_entry->write_buffer = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
if (t_state.api_server_request_body_set) {
msg_len = t_state.internal_msg_buffer_size;
t_state.hdr_info.server_request.value_set_int64(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH, msg_len);
}
DUMP_HEADER("http_hdrs", &(t_state.hdr_info.server_request), t_state.state_machine_id, "Proxy's Request after hooks");
// We need a reader so bytes don't fall off the end of
// the buffer
IOBufferReader *buf_start = server_entry->write_buffer->alloc_reader();
server_request_hdr_bytes = hdr_length = write_header_into_buffer(&t_state.hdr_info.server_request, server_entry->write_buffer);
// the plugin decided to append a message to the request
if (t_state.api_server_request_body_set) {
SMDebug("http", "appending msg of %" PRId64 " bytes to request %s", msg_len, t_state.internal_msg_buffer);
hdr_length += server_entry->write_buffer->write(t_state.internal_msg_buffer, msg_len);
server_request_body_bytes = msg_len;
}
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = ink_get_hrtime();
server_entry->write_vio = server_entry->vc->do_io_write(this, hdr_length, buf_start);
// Make sure the VC is using correct timeouts. We may be reusing a previously used server session
server_txn->set_inactivity_timeout(get_server_inactivity_timeout());
// Go on and set up the read response header too
setup_server_read_response_header();
}
void
HttpSM::setup_server_read_response_header()
{
ink_assert(server_txn != nullptr);
ink_assert(server_entry != nullptr);
// REQ_FLAVOR_SCHEDULED_UPDATE can be transformed in REQ_FLAVOR_REVPROXY
ink_assert(ua_txn != nullptr || t_state.req_flavor == HttpTransact::REQ_FLAVOR_SCHEDULED_UPDATE ||
t_state.req_flavor == HttpTransact::REQ_FLAVOR_REVPROXY);
ink_assert(server_txn != nullptr && server_txn->get_remote_reader() != nullptr);
SMDebug("http", "Setting up the header read");
// Now that we've got the ability to read from the
// server, setup to read the response header
server_entry->vc_handler = &HttpSM::state_read_server_response_header;
server_entry->vc = server_txn;
t_state.current.state = HttpTransact::STATE_UNDEFINED;
t_state.current.server->state = HttpTransact::STATE_UNDEFINED;
// Note: we must use destroy() here since clear()
// does not free the memory from the header
t_state.hdr_info.server_response.destroy();
t_state.hdr_info.server_response.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
server_response_hdr_bytes = 0;
milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] = 0;
// We already done the READ when we setup the connection to
// read the request header
ink_assert(server_entry->read_vio);
// The tunnel from OS to UA is now setup. Ready to read the response
server_entry->read_vio = server_txn->do_io_read(this, INT64_MAX, server_txn->get_remote_reader()->mbuf);
// If there is anything in the buffer call the parsing routines
// since if the response is finished, we won't get any
// additional callbacks
if (server_txn->get_remote_reader()->read_avail() > 0) {
state_read_server_response_header((server_entry->eos) ? VC_EVENT_EOS : VC_EVENT_READ_READY, server_entry->read_vio);
}
}
HttpTunnelProducer *
HttpSM::setup_cache_read_transfer()
{
int64_t alloc_index, hdr_size;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size + index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX),
t_state.http_config_param->max_payload_iobuf_index);
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = static_cast<int>(t_state.txn_conf->default_buffer_water_mark);
IOBufferReader *buf_start = buf->alloc_reader();
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
cache_response_hdr_bytes = client_response_hdr_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
if (doc_size != INT64_MAX) {
doc_size += hdr_size;
}
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(ua_entry->vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
// if size of a cached item is not known, we'll do chunking for keep-alive HTTP/1.1 clients
// this only applies to read-while-write cases where origin server sends a dynamically generated chunked content
// w/o providing a Content-Length header
if (t_state.client_info.receive_chunked_response) {
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT, drop_chunked_trailers);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
ua_entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
HttpTunnelProducer *
HttpSM::setup_cache_transfer_to_transform()
{
int64_t alloc_index;
int64_t doc_size;
ink_assert(cache_sm.cache_read_vc != nullptr);
ink_assert(transform_info.vc != nullptr);
ink_assert(transform_info.entry->vc == transform_info.vc);
// grab this here
cache_response_hdr_bytes = t_state.hdr_info.cache_response.length_get();
doc_size = t_state.cache_info.object_read->object_size_get();
alloc_index = buffer_size_to_index(doc_size, t_state.http_config_param->max_payload_iobuf_index);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p = tunnel.add_producer(cache_sm.cache_read_vc, doc_size, buf_start, &HttpSM::tunnel_handler_cache_read,
HT_CACHE_READ, "cache read");
tunnel.add_consumer(transform_info.vc, cache_sm.cache_read_vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
transform_info.entry->in_tunnel = true;
cache_sm.cache_read_vc = nullptr;
return p;
}
void
HttpSM::setup_cache_write_transfer(HttpCacheSM *c_sm, VConnection *source_vc, HTTPInfo *store_info, int64_t skip_bytes,
const char *name)
{
ink_assert(c_sm->cache_write_vc != nullptr);
ink_assert(t_state.request_sent_time > 0);
ink_assert(t_state.response_received_time > 0);
store_info->request_sent_time_set(t_state.request_sent_time);
store_info->response_received_time_set(t_state.response_received_time);
c_sm->cache_write_vc->set_http_info(store_info);
store_info->clear();
tunnel.add_consumer(c_sm->cache_write_vc, source_vc, &HttpSM::tunnel_handler_cache_write, HT_CACHE_WRITE, name, skip_bytes);
c_sm->cache_write_vc = nullptr;
}
void
HttpSM::setup_100_continue_transfer()
{
MIOBuffer *buf = new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
ink_assert(t_state.client_info.http_version != HTTP_0_9);
client_response_hdr_bytes = write_header_into_buffer(&t_state.hdr_info.client_response, buf);
ink_assert(client_response_hdr_bytes > 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_100_continue);
// Clear the decks before we set up new producers. As things stand, we cannot have two static operators
// at once
tunnel.reset();
// Setup the tunnel to the client
HttpTunnelProducer *p = tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, client_response_hdr_bytes, buf_start,
(HttpProducerHandler) nullptr, HT_STATIC, "internal msg - 100 continue");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_100_continue_ua, HT_HTTP_CLIENT,
"user agent");
// Make sure the half_close is not set.
ua_txn->set_half_close_flag(false);
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
// Set up the header response read again. Already processed the 100 response
setup_server_read_response_header();
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::setup_error_transfer()
//
// The proxy has generated an error message which it
// is sending to the client. For some cases, however,
// such as when the proxy is transparent, returning
// a proxy-generated error message exposes the proxy,
// destroying transparency. The HttpBodyFactory code,
// therefore, does not generate an error message body
// in such cases. This function checks for the presence
// of an error body. If its not present, it closes the
// connection to the user, else it simply calls
// setup_write_proxy_internal, which is the standard
// routine for setting up proxy-generated responses.
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::setup_error_transfer()
{
if (body_factory->is_response_suppressed(&t_state) || t_state.internal_msg_buffer ||
is_response_body_precluded(t_state.http_return_code)) {
// Since we need to send the error message, call the API
// function
ink_assert(t_state.internal_msg_buffer_size > 0 || is_response_body_precluded(t_state.http_return_code));
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
} else {
SMDebug("http", "Now closing connection ...");
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
// ua_txn = NULL;
terminate_sm = true;
t_state.source = HttpTransact::SOURCE_INTERNAL;
}
}
void
HttpSM::setup_internal_transfer(HttpSMHandler handler_arg)
{
bool is_msg_buf_present;
if (t_state.internal_msg_buffer) {
is_msg_buf_present = true;
ink_assert(t_state.internal_msg_buffer_size > 0);
// Set the content length here since a plugin
// may have changed the error body
t_state.hdr_info.client_response.set_content_length(t_state.internal_msg_buffer_size);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
// set internal_msg_buffer_type if available
if (t_state.internal_msg_buffer_type) {
int len = strlen(t_state.internal_msg_buffer_type);
if (len > 0) {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, t_state.internal_msg_buffer_type,
len);
}
ats_free(t_state.internal_msg_buffer_type);
t_state.internal_msg_buffer_type = nullptr;
} else {
t_state.hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
}
} else {
is_msg_buf_present = false;
// If we are sending a response that can have a body
// but doesn't have a body add a content-length of zero.
// Needed for keep-alive on PURGE requests
if (!is_response_body_precluded(t_state.hdr_info.client_response.status_get(), t_state.method)) {
t_state.hdr_info.client_response.set_content_length(0);
t_state.hdr_info.client_response.field_delete(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
}
}
t_state.source = HttpTransact::SOURCE_INTERNAL;
int64_t buf_size =
index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + (is_msg_buf_present ? t_state.internal_msg_buffer_size : 0);
MIOBuffer *buf = new_MIOBuffer(buffer_size_to_index(buf_size, t_state.http_config_param->max_payload_iobuf_index));
IOBufferReader *buf_start = buf->alloc_reader();
// First write the client response header into the buffer
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
int64_t nbytes = client_response_hdr_bytes;
// Next append the message onto the MIOBuffer
// From HTTP/1.1 RFC:
// "The HEAD method is identical to GET except that the server
// MUST NOT return a message-body in the response. The metainformation
// in the HTTP headers in response to a HEAD request SHOULD be
// identical to the information sent in response to a GET request."
// --> do not append the message onto the MIOBuffer and keep our pointer
// to it so that it can be freed.
if (is_msg_buf_present && t_state.method != HTTP_WKSIDX_HEAD) {
nbytes += t_state.internal_msg_buffer_size;
if (t_state.internal_msg_buffer_fast_allocator_size < 0) {
buf->append_xmalloced(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size);
} else {
buf->append_fast_allocated(t_state.internal_msg_buffer, t_state.internal_msg_buffer_size,
t_state.internal_msg_buffer_fast_allocator_size);
}
// The IOBufferBlock will free the msg buffer when necessary so
// eliminate our pointer to it
t_state.internal_msg_buffer = nullptr;
t_state.internal_msg_buffer_size = 0;
}
HTTP_SM_SET_DEFAULT_HANDLER(handler_arg);
if (ua_entry && ua_entry->vc) {
// Clear the decks before we setup the new producers
// As things stand, we cannot have two static producers operating at
// once
tunnel.reset();
// Setup the tunnel to the client
HttpTunnelProducer *p =
tunnel.add_producer(HTTP_TUNNEL_STATIC_PRODUCER, nbytes, buf_start, (HttpProducerHandler) nullptr, HT_STATIC, "internal msg");
tunnel.add_consumer(ua_entry->vc, HTTP_TUNNEL_STATIC_PRODUCER, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
tunnel.tunnel_run(p);
} else {
(this->*default_handler)(HTTP_TUNNEL_EVENT_DONE, &tunnel);
}
}
// int HttpSM::find_http_resp_buffer_size(int cl)
//
// Returns the allocation index for the buffer for
// a response based on the content length
//
int
HttpSM::find_http_resp_buffer_size(int64_t content_length)
{
int64_t alloc_index;
if (content_length == HTTP_UNDEFINED_CL) {
// Try use our configured default size. Otherwise pick
// the default size
alloc_index = static_cast<int>(t_state.txn_conf->default_buffer_size_index);
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > DEFAULT_MAX_BUFFER_SIZE) {
alloc_index = DEFAULT_RESPONSE_BUFFER_SIZE_INDEX;
}
} else {
int64_t buf_size = index_to_buffer_size(HTTP_HEADER_BUFFER_SIZE_INDEX) + content_length;
alloc_index = buffer_size_to_index(buf_size, t_state.http_config_param->max_payload_iobuf_index);
}
return alloc_index;
}
// int HttpSM::server_transfer_init()
//
// Moves data from the header buffer into the reply buffer
// and return the number of bytes we should use for initiating the
// tunnel
//
int64_t
HttpSM::server_transfer_init(MIOBuffer *buf, int hdr_size)
{
int64_t nbytes;
int64_t to_copy = INT64_MAX;
ink_assert(t_state.current.server != nullptr); // should have been set up if we're doing a transfer.
if (server_entry->eos == true) {
// The server has shutdown on us already so the only data
// we'll get is already in the buffer
nbytes = server_txn->get_remote_reader()->read_avail() + hdr_size;
} else if (t_state.hdr_info.response_content_length == HTTP_UNDEFINED_CL) {
nbytes = -1;
} else {
// Set to copy to the number of bytes we want to write as
// if the server is sending us a bogus response we have to
// truncate it as we've already decided to trust the content
// length
to_copy = t_state.hdr_info.response_content_length;
nbytes = t_state.hdr_info.response_content_length + hdr_size;
}
// Next order of business if copy the remaining data from the header buffer into new buffer.
int64_t server_response_pre_read_bytes = buf->write(server_txn->get_remote_reader(), to_copy);
server_txn->get_remote_reader()->consume(server_response_pre_read_bytes);
// If we know the length & copied the entire body
// of the document out of the header buffer make
// sure the server isn't screwing us by having sent too
// much. If it did, we want to close the server connection
if (server_response_pre_read_bytes == to_copy && server_txn->get_remote_reader()->read_avail() > 0) {
t_state.current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
return nbytes;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer_to_transform()
{
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_response_wait_for_transform_read);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(transform_info.vc, server_entry->vc, &HttpSM::tunnel_handler_transform_write, HT_TRANSFORM,
"transform write");
server_entry->in_tunnel = true;
transform_info.entry->in_tunnel = true;
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
client_response_hdr_bytes = 0; // fixed by YTS Team, yamsat
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_DECHUNK_CONTENT, HttpTunnel::DROP_CHUNKED_TRAILERS);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform()
{
int64_t alloc_index = find_server_buffer_size();
// TODO change this call to new_empty_MIOBuffer()
MIOBuffer *buf = new_MIOBuffer(alloc_index);
buf->water_mark = static_cast<int>(t_state.txn_conf->default_buffer_water_mark);
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
tunnel.add_consumer(ua_entry->vc, transform_info.vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
transform_info.entry->in_tunnel = true;
ua_entry->in_tunnel = true;
this->setup_plugin_agents(p, client_response_hdr_bytes);
if (t_state.client_info.receive_chunked_response) {
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, TCA_CHUNK_CONTENT, drop_chunked_trailers);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
}
return p;
}
HttpTunnelProducer *
HttpSM::setup_transfer_from_transform_to_cache_only()
{
int64_t alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
HttpTunnelConsumer *c = tunnel.get_consumer(transform_info.vc);
ink_assert(c != nullptr);
ink_assert(c->vc == transform_info.vc);
ink_assert(c->vc_type == HT_TRANSFORM);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p = tunnel.add_producer(transform_info.vc, INT64_MAX, buf_start, &HttpSM::tunnel_handler_transform_read,
HT_TRANSFORM, "transform read");
tunnel.chain(c, p);
transform_info.entry->in_tunnel = true;
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_DO_WRITE);
perform_transform_cache_write_action();
return p;
}
void
HttpSM::setup_server_transfer_to_cache_only()
{
TunnelChunkingAction_t action;
int64_t alloc_index;
int64_t nbytes;
alloc_index = find_server_buffer_size();
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
action = (t_state.current.server && t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) ?
TCA_DECHUNK_CONTENT :
TCA_PASSTHRU_DECHUNKED_CONTENT;
nbytes = server_transfer_init(buf, 0);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
tunnel.set_producer_chunking_action(p, 0, action, drop_chunked_trailers);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
setup_cache_write_transfer(&cache_sm, server_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
server_entry->in_tunnel = true;
}
HttpTunnelProducer *
HttpSM::setup_server_transfer()
{
SMDebug("http", "Setup Server Transfer");
int64_t alloc_index, hdr_size;
int64_t nbytes;
alloc_index = find_server_buffer_size();
#ifndef USE_NEW_EMPTY_MIOBUFFER
MIOBuffer *buf = new_MIOBuffer(alloc_index);
#else
MIOBuffer *buf = new_empty_MIOBuffer(alloc_index);
buf->append_block(HTTP_HEADER_BUFFER_SIZE_INDEX);
#endif
buf->water_mark = static_cast<int>(t_state.txn_conf->default_buffer_water_mark);
IOBufferReader *buf_start = buf->alloc_reader();
// we need to know if we are going to chunk the response or not
// before we write the response header into buffer
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
action = TCA_DECHUNK_CONTENT;
} else {
action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
} else {
if (t_state.current.server->transfer_encoding != HttpTransact::CHUNKED_ENCODING) {
if (t_state.client_info.http_version == HTTP_0_9) {
action = TCA_PASSTHRU_DECHUNKED_CONTENT; // send as-is
} else {
action = TCA_CHUNK_CONTENT;
}
} else {
action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
}
if (action == TCA_CHUNK_CONTENT || action == TCA_PASSTHRU_CHUNKED_CONTENT) { // remove Content-Length
t_state.hdr_info.client_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Now dump the header into the buffer
ink_assert(t_state.hdr_info.client_response.status_get() != HTTP_STATUS_NOT_MODIFIED);
client_response_hdr_bytes = hdr_size = write_response_header_into_buffer(&t_state.hdr_info.client_response, buf);
nbytes = server_transfer_init(buf, hdr_size);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
HttpTunnelProducer *p =
tunnel.add_producer(server_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_server, HT_HTTP_SERVER, "http server");
tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ua, HT_HTTP_CLIENT, "user agent");
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
this->setup_plugin_agents(p, client_response_hdr_bytes);
// If the incoming server response is chunked and the client does not
// expect a chunked response, then dechunk it. Otherwise, if the
// incoming response is not chunked and the client expects a chunked
// response, then chunk it.
/*
// this block is moved up so that we know if we need to remove
// Content-Length field from response header before writing the
// response header into buffer bz50730
TunnelChunkingAction_t action;
if (t_state.client_info.receive_chunked_response == false) {
if (t_state.current.server->transfer_encoding ==
HttpTransact::CHUNKED_ENCODING)
action = TCA_DECHUNK_CONTENT;
else action = TCA_PASSTHRU_DECHUNKED_CONTENT;
}
else {
if (t_state.current.server->transfer_encoding !=
HttpTransact::CHUNKED_ENCODING)
action = TCA_CHUNK_CONTENT;
else action = TCA_PASSTHRU_CHUNKED_CONTENT;
}
*/
bool const drop_chunked_trailers = t_state.http_config_param->oride.http_drop_chunked_trailers == 1;
tunnel.set_producer_chunking_action(p, client_response_hdr_bytes, action, drop_chunked_trailers);
tunnel.set_producer_chunking_size(p, t_state.txn_conf->http_chunking_size);
return p;
}
HttpTunnelProducer *
HttpSM::setup_push_transfer_to_cache()
{
int64_t nbytes, alloc_index;
alloc_index = find_http_resp_buffer_size(t_state.hdr_info.request_content_length);
MIOBuffer *buf = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = buf->alloc_reader();
ink_release_assert(t_state.hdr_info.request_content_length != HTTP_UNDEFINED_CL);
nbytes = t_state.hdr_info.request_content_length - pushed_response_hdr_bytes;
ink_release_assert(nbytes >= 0);
if (ua_entry->eos == true) {
// The ua has shutdown on us already so the only data
// we'll get is already in the buffer. Make sure it
// fulfills the stated length
int64_t avail = ua_txn->get_remote_reader()->read_avail();
if (avail < nbytes) {
// Client failed to send the body, it's gone. Kill the
// state machine
terminate_sm = true;
return nullptr;
}
}
// Next order of business is copy the remaining data from the
// header buffer into new buffer.
pushed_response_body_bytes = buf->write(ua_txn->get_remote_reader(), nbytes);
ua_txn->get_remote_reader()->consume(pushed_response_body_bytes);
client_request_body_bytes += pushed_response_body_bytes;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_push);
HttpTunnelProducer *p =
tunnel.add_producer(ua_entry->vc, nbytes, buf_start, &HttpSM::tunnel_handler_ua_push, HT_HTTP_CLIENT, "user_agent");
setup_cache_write_transfer(&cache_sm, ua_entry->vc, &t_state.cache_info.object_store, 0, "cache write");
ua_entry->in_tunnel = true;
return p;
}
void
HttpSM::setup_blind_tunnel(bool send_response_hdr, IOBufferReader *initial)
{
HttpTunnelConsumer *c_ua;
HttpTunnelConsumer *c_os;
HttpTunnelProducer *p_ua;
HttpTunnelProducer *p_os;
MIOBuffer *from_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
MIOBuffer *to_ua_buf = new_MIOBuffer(BUFFER_SIZE_INDEX_32K);
IOBufferReader *r_from = from_ua_buf->alloc_reader();
IOBufferReader *r_to = to_ua_buf->alloc_reader();
milestones[TS_MILESTONE_SERVER_BEGIN_WRITE] = ink_get_hrtime();
if (send_response_hdr) {
client_response_hdr_bytes = write_response_header_into_buffer(&t_state.hdr_info.client_response, to_ua_buf);
if (initial && initial->read_avail()) {
int64_t avail = initial->read_avail();
to_ua_buf->write(initial, avail);
initial->consume(avail);
}
} else {
client_response_hdr_bytes = 0;
}
client_request_body_bytes = 0;
if (ua_raw_buffer_reader != nullptr) {
client_request_body_bytes += from_ua_buf->write(ua_raw_buffer_reader, client_request_hdr_bytes);
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
// if pre-warmed connection is used and it has data from origin server, foward it to ua
if (_prewarm_sm && _prewarm_sm->has_data_from_origin_server()) {
ink_release_assert(_prewarm_sm->handler == &PreWarmSM::state_closed);
client_response_hdr_bytes += to_ua_buf->write(_prewarm_sm->server_buf_reader());
}
// Next order of business if copy the remaining data from the
// header buffer into new buffer
client_request_body_bytes += from_ua_buf->write(ua_txn->get_remote_reader());
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler);
p_os =
tunnel.add_producer(server_entry->vc, -1, r_to, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_SERVER, "http server - tunnel");
c_ua = tunnel.add_consumer(ua_entry->vc, server_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_CLIENT,
"user agent - tunnel");
p_ua = tunnel.add_producer(ua_entry->vc, -1, r_from, &HttpSM::tunnel_handler_ssl_producer, HT_HTTP_CLIENT, "user agent - tunnel");
c_os = tunnel.add_consumer(server_entry->vc, ua_entry->vc, &HttpSM::tunnel_handler_ssl_consumer, HT_HTTP_SERVER,
"http server - tunnel");
// Make the tunnel aware that the entries are bi-directional
tunnel.chain(c_os, p_os);
tunnel.chain(c_ua, p_ua);
ua_entry->in_tunnel = true;
server_entry->in_tunnel = true;
tunnel.tunnel_run();
// If we're half closed, we got a FIN from the client. Forward it on to the origin server
// now that we have the tunnel operational.
if (ua_txn && ua_txn->get_half_close_flag()) {
p_ua->vc->do_io_shutdown(IO_SHUTDOWN_READ);
}
}
void
HttpSM::setup_plugin_agents(HttpTunnelProducer *p, int num_header_bytes)
{
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
has_active_plugin_agents = agent != nullptr;
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
tunnel.add_consumer(contp, p->vc, &HttpSM::tunnel_handler_plugin_agent, HT_HTTP_CLIENT, "plugin agent", num_header_bytes);
// We don't put these in the SM VC table because the tunnel
// will clean them up in do_io_close().
agent = agent->next();
}
}
inline void
HttpSM::transform_cleanup(TSHttpHookID hook, HttpTransformInfo *info)
{
APIHook *t_hook = api_hooks.get(hook);
if (t_hook && info->vc == nullptr) {
do {
VConnection *t_vcon = t_hook->m_cont;
t_vcon->do_io_close();
t_hook = t_hook->m_link.next;
} while (t_hook != nullptr);
}
}
void
HttpSM::plugin_agents_cleanup()
{
// If this is set then all of the plugin agent VCs were put in
// the VC table and cleaned up there. This handles the case where
// something went wrong early.
if (!has_active_plugin_agents) {
APIHook *agent = txn_hook_get(TS_HTTP_RESPONSE_CLIENT_HOOK);
while (agent) {
INKVConnInternal *contp = static_cast<INKVConnInternal *>(agent->m_cont);
contp->do_io_close();
agent = agent->next();
}
}
}
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::kill_this()
//
// This function has two phases. One before we call the asynchronous
// clean up routines (api and list removal) and one after.
// The state about which phase we are in is kept in
// HttpSM::kill_this_async_done
//
//////////////////////////////////////////////////////////////////////////
void
HttpSM::kill_this()
{
ink_release_assert(reentrancy_count == 1);
this->postbuf_clear();
enable_redirection = false;
if (kill_this_async_done == false) {
////////////////////////////////
// cancel uncompleted actions //
////////////////////////////////
// The action should be cancelled only if
// the state machine is in HTTP_API_NO_CALLOUT
// state. This is because we are depending on the
// callout to complete for the state machine to
// get killed.
if (callout_state == HTTP_API_NO_CALLOUT && pending_action) {
pending_action->cancel();
pending_action = nullptr;
} else if (pending_action) {
ink_assert(pending_action == nullptr);
}
cache_sm.end_both();
transform_cache_sm.end_both();
vc_table.cleanup_all();
// tunnel.deallocate_buffers();
// Why don't we just kill the tunnel? Might still be
// active if the state machine is going down hard,
// and we should clean it up.
tunnel.kill_tunnel();
// It possible that a plugin added transform hook
// but the hook never executed due to a client abort
// In that case, we need to manually close all the
// transforms to prevent memory leaks (INKqa06147)
if (hooks_set) {
transform_cleanup(TS_HTTP_RESPONSE_TRANSFORM_HOOK, &transform_info);
transform_cleanup(TS_HTTP_REQUEST_TRANSFORM_HOOK, &post_transform_info);
plugin_agents_cleanup();
}
// It's also possible that the plugin_tunnel vc was never
// executed due to not contacting the server
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
// So we don't try to nuke the state machine
// if the plugin receives event we must reset
// the terminate_flag
terminate_sm = false;
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_SHUTDOWN;
if (do_api_callout() < 0) { // Failed to get a continuation lock
// Need to hang out until we can complete the TXN_CLOSE hook
terminate_sm = false;
reentrancy_count--;
return;
}
}
// The reentrancy_count is still valid up to this point since
// the api shutdown hook is asynchronous and double frees can
// happen if the reentrancy count is not still valid until
// after all asynch callouts have completed
//
// Once we get to this point, we could be waiting for async
// completion in which case we need to decrement the reentrancy
// count since the entry points can't do it for us since they
// don't know if the state machine has been destroyed. In the
// case we really are done with asynch callouts, decrement the
// reentrancy count since it seems tacky to destruct a state
// machine with non-zero count
reentrancy_count--;
ink_release_assert(reentrancy_count == 0);
// If the api shutdown & list removal was synchronous
// then the value of kill_this_async_done has changed so
// we must check it again
if (kill_this_async_done == true) {
if (pending_action) {
pending_action->cancel();
pending_action = nullptr;
}
if (t_state.http_config_param->enable_http_stats) {
update_stats();
}
//////////////
// Log Data //
//////////////
SMDebug("http_seq", "Logging transaction");
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccess accessor(this);
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
SMDebug("http", "Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
if (server_txn) {
server_txn->transaction_done();
server_txn = nullptr;
}
if (ua_txn) {
if (ua_txn->get_server_session() != nullptr) {
ua_txn->attach_server_session(nullptr);
}
ua_txn->transaction_done();
}
// In the async state, the plugin could have been
// called resulting in the creation of a plugin_tunnel.
// So it needs to be deleted now.
if (plugin_tunnel) {
plugin_tunnel->kill_no_connect();
plugin_tunnel = nullptr;
}
ink_assert(pending_action == nullptr);
ink_release_assert(vc_table.is_table_clear() == true);
ink_release_assert(tunnel.is_tunnel_active() == false);
HTTP_SM_SET_DEFAULT_HANDLER(nullptr);
ats_free(redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.remove(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
SMDebug("http", "deallocating sm");
destroy();
}
}
void
HttpSM::update_stats()
{
milestones[TS_MILESTONE_SM_FINISH] = ink_get_hrtime();
if (is_action_tag_set("bad_length_state_dump")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
if (!((p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0))) {
Error("[%" PRId64 "] Truncated content detected", sm_id);
dump_state_on_assert();
}
} else if (client_request_hdr_bytes == 0) {
Error("[%" PRId64 "] Zero length request header received", sm_id);
dump_state_on_assert();
}
}
if (is_action_tag_set("assert_jtest_length")) {
if (t_state.hdr_info.client_response.valid() && t_state.hdr_info.client_response.status_get() == HTTP_STATUS_OK) {
int64_t p_resp_cl = t_state.hdr_info.client_response.get_content_length();
int64_t resp_size = client_response_body_bytes;
ink_release_assert(p_resp_cl == -1 || p_resp_cl == resp_size || resp_size == 0);
}
}
ink_hrtime total_time = milestones.elapsed(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH);
// ua_close will not be assigned properly in some exceptional situation.
// TODO: Assign ua_close with suitable value when HttpTunnel terminates abnormally.
if (milestones[TS_MILESTONE_UA_CLOSE] == 0 && milestones[TS_MILESTONE_UA_READ_HEADER_DONE] > 0) {
milestones[TS_MILESTONE_UA_CLOSE] = ink_get_hrtime();
}
// request_process_time = The time after the header is parsed to the completion of the transaction
ink_hrtime request_process_time = milestones[TS_MILESTONE_UA_CLOSE] - milestones[TS_MILESTONE_UA_READ_HEADER_DONE];
HttpTransact::client_result_stat(&t_state, total_time, request_process_time);
ink_hrtime ua_write_time;
if (milestones[TS_MILESTONE_UA_BEGIN_WRITE] != 0 && milestones[TS_MILESTONE_UA_CLOSE] != 0) {
ua_write_time = milestones.elapsed(TS_MILESTONE_UA_BEGIN_WRITE, TS_MILESTONE_UA_CLOSE);
} else {
ua_write_time = -1;
}
ink_hrtime os_read_time;
if (milestones[TS_MILESTONE_SERVER_READ_HEADER_DONE] != 0 && milestones[TS_MILESTONE_SERVER_CLOSE] != 0) {
os_read_time = milestones.elapsed(TS_MILESTONE_SERVER_READ_HEADER_DONE, TS_MILESTONE_SERVER_CLOSE);
} else {
os_read_time = -1;
}
HttpTransact::update_size_and_time_stats(
&t_state, total_time, ua_write_time, os_read_time, client_request_hdr_bytes, client_request_body_bytes,
client_response_hdr_bytes, client_response_body_bytes, server_request_hdr_bytes, server_request_body_bytes,
server_response_hdr_bytes, server_response_body_bytes, pushed_response_hdr_bytes, pushed_response_body_bytes, milestones);
/*
if (is_action_tag_set("http_handler_times")) {
print_all_http_handler_times();
}
*/
// print slow requests if the threshold is set (> 0) and if we are over the time threshold
if (t_state.txn_conf->slow_log_threshold != 0 && ink_hrtime_from_msec(t_state.txn_conf->slow_log_threshold) < total_time) {
char url_string[256] = "";
int offset = 0;
int skip = 0;
t_state.hdr_info.client_request.url_print(url_string, sizeof(url_string) - 1, &offset, &skip);
url_string[offset] = 0; // NULL terminate the string
// unique id
char unique_id_string[128] = "";
int length = 0;
const char *field = t_state.hdr_info.client_request.value_get(MIME_FIELD_X_ID, MIME_LEN_X_ID, &length);
if (field != nullptr && length > 0) {
length = std::min(length, static_cast<int>(sizeof(unique_id_string)) - 1);
memcpy(unique_id_string, field, length);
unique_id_string[length] = 0; // NULL terminate the string
}
// set the fd for the request
int fd = 0;
NetVConnection *vc = nullptr;
if (ua_txn != nullptr) {
vc = ua_txn->get_netvc();
if (vc != nullptr) {
fd = vc->get_socket();
} else {
fd = -1;
}
}
// get the status code, lame that we have to check to see if it is valid or we will assert in the method call
int status = 0;
if (t_state.hdr_info.client_response.valid()) {
status = t_state.hdr_info.client_response.status_get();
}
char client_ip[INET6_ADDRSTRLEN];
ats_ip_ntop(&t_state.client_info.src_addr, client_ip, sizeof(client_ip));
Error("[%" PRId64 "] Slow Request: "
"client_ip: %s:%u "
"protocol: %s "
"url: %s "
"status: %d "
"unique id: %s "
"redirection_tries: %d "
"bytes: %" PRId64 " "
"fd: %d "
"client state: %d "
"server state: %d "
"tls_handshake: %.3f "
"ua_begin: %.3f "
"ua_first_read: %.3f "
"ua_read_header_done: %.3f "
"cache_open_read_begin: %.3f "
"cache_open_read_end: %.3f "
"cache_open_write_begin: %.3f "
"cache_open_write_end: %.3f "
"dns_lookup_begin: %.3f "
"dns_lookup_end: %.3f "
"server_connect: %.3f "
"server_connect_end: %.3f "
"server_first_read: %.3f "
"server_read_header_done: %.3f "
"server_close: %.3f "
"ua_write: %.3f "
"ua_close: %.3f "
"sm_finish: %.3f "
"plugin_active: %.3f "
"plugin_total: %.3f",
sm_id, client_ip, t_state.client_info.src_addr.host_order_port(), ua_txn ? ua_txn->get_protocol_string() : "-1",
url_string, status, unique_id_string, redirection_tries, client_response_body_bytes, fd, t_state.client_info.state,
t_state.server_info.state, milestones.difference_sec(TS_MILESTONE_TLS_HANDSHAKE_START, TS_MILESTONE_TLS_HANDSHAKE_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_ACTIVE),
milestones.difference_sec(TS_MILESTONE_SM_START, TS_MILESTONE_PLUGIN_TOTAL));
}
}
//
// void HttpSM::dump_state_on_assert
// Debugging routine to dump the state machine's history
// and other state on an assertion failure
// We use Diags::Status instead of stderr since
// Diags works both on UNIX & NT
//
void
HttpSM::dump_state_on_assert()
{
Error("[%" PRId64 "] ------- begin http state dump -------", sm_id);
if (history.overflowed()) {
Error(" History Wrap around. history size: %d", history.size());
}
// Loop through the history and dump it
for (unsigned int i = 0; i < history.size(); i++) {
char buf[256];
int r = history[i].reentrancy;
int e = history[i].event;
Error("%d %d %s", e, r, history[i].location.str(buf, sizeof(buf)));
}
// Dump the via string
Error("Via String: [%s]\n", t_state.via_string);
// Dump header info
dump_state_hdr(&t_state.hdr_info.client_request, "Client Request");
dump_state_hdr(&t_state.hdr_info.server_request, "Server Request");
dump_state_hdr(&t_state.hdr_info.server_response, "Server Response");
dump_state_hdr(&t_state.hdr_info.transform_response, "Transform Response");
dump_state_hdr(&t_state.hdr_info.client_response, "Client Response");
Error("[%" PRId64 "] ------- end http state dump ---------", sm_id);
}
void
HttpSM::dump_state_hdr(HTTPHdr *h, const char *s)
{
// Dump the client request if available
if (h->valid()) {
int l = h->length_get();
char *hdr_buf = static_cast<char *>(ats_malloc(l + 1));
int index = 0;
int offset = 0;
h->print(hdr_buf, l, &index, &offset);
hdr_buf[l] = '\0';
Error(" ---- %s [%" PRId64 "] ----\n%s\n", s, sm_id, hdr_buf);
ats_free(hdr_buf);
}
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact Interface ****
**** ****
*****************************************************************************
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// HttpSM::call_transact_and_set_next_state(f)
//
// This routine takes an HttpTransact function <f>, calls the function
// to perform some actions on the current HttpTransact::State, and
// then uses the HttpTransact return action code to set the next
// handler (state) for the state machine. HttpTransact could have
// returned the handler directly, but returns action codes in hopes of
// making a cleaner separation between the state machine and the
// HttpTransact logic.
//
//////////////////////////////////////////////////////////////////////////
// Where is the goatherd?
void
HttpSM::call_transact_and_set_next_state(TransactEntryFunc_t f)
{
last_action = t_state.next_action; // remember where we were
// The callee can either specify a method to call in to Transact,
// or call with NULL which indicates that Transact should use
// its stored entry point.
if (f == nullptr) {
ink_release_assert(t_state.transact_return_point != nullptr);
t_state.transact_return_point(&t_state);
} else {
f(&t_state);
}
SMDebug("http", "State Transition: %s -> %s", HttpDebugNames::get_action_name(last_action),
HttpDebugNames::get_action_name(t_state.next_action));
set_next_state();
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpSM::set_next_state()
//
// call_transact_and_set_next_state() was broken into two parts, one
// which calls the HttpTransact method and the second which sets the
// next state. In a case which set_next_state() was not completed,
// the state function calls set_next_state() to retry setting the
// state.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpSM::set_next_state()
{
///////////////////////////////////////////////////////////////////////
// Use the returned "next action" code to set the next state handler //
///////////////////////////////////////////////////////////////////////
switch (t_state.next_action) {
case HttpTransact::SM_ACTION_API_PRE_REMAP:
case HttpTransact::SM_ACTION_API_POST_REMAP:
case HttpTransact::SM_ACTION_API_READ_REQUEST_HDR:
case HttpTransact::SM_ACTION_REQUEST_BUFFER_READ_COMPLETE:
case HttpTransact::SM_ACTION_API_OS_DNS:
case HttpTransact::SM_ACTION_API_SEND_REQUEST_HDR:
case HttpTransact::SM_ACTION_API_READ_CACHE_HDR:
case HttpTransact::SM_ACTION_API_READ_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR:
case HttpTransact::SM_ACTION_API_CACHE_LOOKUP_COMPLETE: {
t_state.api_next_action = t_state.next_action;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_POST_REMAP_SKIP: {
call_transact_and_set_next_state(nullptr);
break;
}
case HttpTransact::SM_ACTION_REMAP_REQUEST: {
do_remap_request(true); /* run inline */
SMDebug("url_rewrite", "completed inline remapping request");
t_state.url_remap_success = remapProcessor.finish_remap(&t_state, m_remap);
if (t_state.next_action == HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP && t_state.transact_return_point == nullptr) {
// It appears that we can now set the next_action to error and transact_return_point to nullptr when
// going through do_remap_request presumably due to a plugin setting an error. In that case, it seems
// that the error message has already been setup, so we can just return and avoid the further
// call_transact_and_set_next_state
} else {
call_transact_and_set_next_state(nullptr);
}
break;
}
case HttpTransact::SM_ACTION_DNS_LOOKUP: {
sockaddr const *addr;
if (t_state.api_server_addr_set) {
/* If the API has set the server address before the OS DNS lookup
* then we can skip the lookup
*/
ip_text_buffer ipb;
SMDebug("dns", "Skipping DNS lookup for API supplied target %s.",
ats_ip_ntop(&t_state.server_info.dst_addr, ipb, sizeof(ipb)));
// this seems wasteful as we will just copy it right back
ats_ip_copy(t_state.host_db_info.ip(), &t_state.server_info.dst_addr);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
} else if (0 == ats_ip_pton(t_state.dns_info.lookup_name, t_state.host_db_info.ip()) &&
ats_is_ip_loopback(t_state.host_db_info.ip())) {
// If it's 127.0.0.1 or ::1 don't bother with hostdb
SMDebug("dns", "Skipping DNS lookup for %s because it's loopback", t_state.dns_info.lookup_name);
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.http_config_param->use_client_target_addr == 2 && !t_state.url_remap_success &&
t_state.parent_result.result != PARENT_SPECIFIED && t_state.client_info.is_transparent &&
t_state.dns_info.os_addr_style == HttpTransact::DNSLookupInfo::OS_Addr::OS_ADDR_TRY_DEFAULT &&
ats_is_ip(addr = ua_txn->get_netvc()->get_local_addr())) {
/* If the connection is client side transparent and the URL
* was not remapped/directed to parent proxy, we can use the
* client destination IP address instead of doing a DNS
* lookup. This is controlled by the 'use_client_target_addr'
* configuration parameter.
*/
if (is_debug_tag_set("dns")) {
ip_text_buffer ipb;
SMDebug("dns", "Skipping DNS lookup for client supplied target %s.", ats_ip_ntop(addr, ipb, sizeof(ipb)));
}
ats_ip_copy(t_state.host_db_info.ip(), addr);
t_state.host_db_info.app.http_data.http_version = t_state.hdr_info.client_request.version_get();
t_state.dns_info.lookup_success = true;
// cache this result so we don't have to unreliably duplicate the
// logic later if the connect fails.
t_state.dns_info.os_addr_style = HttpTransact::DNSLookupInfo::OS_Addr::OS_ADDR_TRY_CLIENT;
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.parent_result.result == PARENT_UNDEFINED && t_state.dns_info.lookup_success) {
// Already set, and we don't have a parent proxy to lookup
ink_assert(ats_is_ip(t_state.host_db_info.ip()));
SMDebug("dns", "Skipping DNS lookup, provided by plugin");
call_transact_and_set_next_state(nullptr);
break;
} else if (t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER && t_state.http_config_param->no_dns_forward_to_parent &&
t_state.parent_result.result != PARENT_UNDEFINED) {
t_state.dns_info.lookup_success = true;
call_transact_and_set_next_state(nullptr);
break;
}
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_lookup);
// We need to close the previous attempt
// Because it could be a server side retry by DNS rr
if (server_entry) {
ink_assert(server_entry->vc_type == HTTP_SERVER_VC);
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
} else {
// Now that we have gotten the user agent request, we can cancel
// the inactivity timeout associated with it. Note, however, that
// we must not cancel the inactivity timeout if the message
// contains a body. This indicates that a POST operation is taking place and
// that the client is still sending data to the origin server. The
// origin server cannot reply until the entire request is received. In
// light of this dependency, TS must ensure that the client finishes
// sending its request and for this reason, the inactivity timeout
// cannot be cancelled.
if (ua_txn && !ua_txn->has_request_body(t_state.hdr_info.request_content_length,
t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
ua_txn->cancel_inactivity_timeout();
} else if (!ua_txn) {
terminate_sm = true;
return; // Give up if there is no session
}
}
ink_assert(t_state.dns_info.looking_up != HttpTransact::UNDEFINED_LOOKUP);
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_DNS_REVERSE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_hostdb_reverse_lookup);
do_hostdb_reverse_lookup();
break;
}
case HttpTransact::SM_ACTION_CACHE_LOOKUP: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_read);
do_cache_lookup_and_read();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN: {
// Pre-emptively set a server connect failure that will be cleared once a WRITE_READY is received from origin or
// bytes are received back
t_state.set_connect_fail(EIO);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_http_server_open);
// We need to close the previous attempt
if (server_entry) {
ink_assert(server_entry->vc_type == HTTP_SERVER_VC);
vc_table.cleanup_entry(server_entry);
server_entry = nullptr;
} else {
// Now that we have gotten the user agent request, we can cancel
// the inactivity timeout associated with it. Note, however, that
// we must not cancel the inactivity timeout if the message
// contains a body. This indicates that a POST operation is taking place and
// that the client is still sending data to the origin server. The
// origin server cannot reply until the entire request is received. In
// light of this dependency, TS must ensure that the client finishes
// sending its request and for this reason, the inactivity timeout
// cannot be cancelled.
if (ua_txn && !ua_txn->has_request_body(t_state.hdr_info.request_content_length,
t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING)) {
ua_txn->cancel_inactivity_timeout();
} else if (!ua_txn) {
terminate_sm = true;
return; // Give up if there is no session
}
}
do_http_server_open();
break;
}
// This is called in some case if the 100 continue header is from a HTTP/1.0 server
// Likely an obsolete case now and should probably return an error
case HttpTransact::SM_ACTION_SERVER_PARSE_NEXT_HDR: {
setup_server_read_response_header();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_100_RESPONSE: {
setup_100_continue_transfer();
break;
}
case HttpTransact::SM_ACTION_SERVER_READ: {
t_state.source = HttpTransact::SOURCE_HTTP_ORIGIN_SERVER;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
HttpTunnelProducer *p = setup_server_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if we are going to handle the redirection from server response and if there is a plugin hook set
if (hooks_set && is_redirect_required() == false) {
do_api_callout_internal();
} else {
do_redirect();
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_SERVE_FROM_CACHE: {
ink_assert(t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_DELETE ||
t_state.cache_info.action == HttpTransact::CACHE_DO_SERVE_AND_UPDATE);
release_server_session(true);
t_state.source = HttpTransact::SOURCE_CACHE;
if (transform_info.vc) {
ink_assert(t_state.hdr_info.client_response.valid() == 0);
ink_assert((t_state.hdr_info.transform_response.valid() ? true : false) == true);
do_drain_request_body(t_state.hdr_info.transform_response);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.transform_response);
HttpTunnelProducer *p = setup_cache_transfer_to_transform();
perform_cache_write_action();
tunnel.tunnel_run(p);
} else {
ink_assert((t_state.hdr_info.client_response.valid() ? true : false) == true);
do_drain_request_body(t_state.hdr_info.client_response);
t_state.hdr_info.cache_response.create(HTTP_TYPE_RESPONSE);
t_state.hdr_info.cache_response.copy(&t_state.hdr_info.client_response);
perform_cache_write_action();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
// check to see if there is a plugin hook set
if (hooks_set) {
do_api_callout_internal();
} else {
handle_api_return();
}
}
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE: {
ink_assert((cache_sm.cache_write_vc == nullptr) || t_state.redirect_info.redirect_in_process);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_WRITE: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_NOOP: {
if (server_entry != nullptr && server_entry->in_tunnel == false) {
release_server_session();
}
do_drain_request_body(t_state.hdr_info.client_response);
// If we're in state SEND_API_RESPONSE_HDR, it means functions
// registered to hook SEND_RESPONSE_HDR have already been called. So we do not
// need to call do_api_callout. Otherwise TS loops infinitely in this state !
if (t_state.api_next_action == HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR) {
handle_api_return();
} else {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
}
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE: {
// Nuke all the alternates since this is mostly likely
// the result of a delete method
cache_sm.end_both();
do_cache_delete_all_alts(nullptr);
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS: {
issue_cache_update();
cache_sm.close_read();
release_server_session();
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_SEND_ERROR_CACHE_NOOP: {
setup_error_transfer();
break;
}
case HttpTransact::SM_ACTION_INTERNAL_REQUEST: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_handle_stat_page);
Action *action_handle = statPagesManager.handle_http(this, &t_state.hdr_info.client_request);
if (action_handle != ACTION_RESULT_DONE) {
ink_assert(pending_action == nullptr);
pending_action = action_handle;
}
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN: {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_mark_os_down);
ink_assert(t_state.dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
// TODO: This might not be optimal (or perhaps even correct), but it will
// effectively mark the host as down. What's odd is that state_mark_os_down
// above isn't triggering.
HttpSM::do_hostdb_update_if_necessary();
do_hostdb_lookup();
break;
}
case HttpTransact::SM_ACTION_SSL_TUNNEL: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN: {
// Pre-emptively set a server connect failure that will be cleared once a WRITE_READY is received from origin or
// bytes are received back
t_state.set_connect_fail(EIO);
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_raw_http_server_open);
ink_assert(server_entry == nullptr);
do_http_server_open(true);
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM: {
ink_assert(t_state.cache_info.transform_action == HttpTransact::CACHE_PREPARE_TO_WRITE);
if (transform_cache_sm.cache_write_vc) {
// We've already got the write_vc that
// didn't use for the untransformed copy
ink_assert(cache_sm.cache_write_vc == nullptr);
ink_assert(t_state.api_info.cache_untransformed == false);
t_state.cache_info.write_lock_state = HttpTransact::CACHE_WL_SUCCESS;
call_transact_and_set_next_state(nullptr);
} else {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_cache_open_write);
do_cache_prepare_write_transform();
}
break;
}
case HttpTransact::SM_ACTION_TRANSFORM_READ: {
t_state.api_next_action = HttpTransact::SM_ACTION_API_SEND_RESPONSE_HDR;
do_api_callout();
break;
}
case HttpTransact::SM_ACTION_READ_PUSH_HDR: {
setup_push_read_response_header();
break;
}
case HttpTransact::SM_ACTION_STORE_PUSH_BODY: {
// This can return NULL - do we really want to run the tunnel in that case?
// But that's how it was before this change.
HttpTunnelProducer *p = setup_push_transfer_to_cache();
tunnel.tunnel_run(p);
break;
}
case HttpTransact::SM_ACTION_CACHE_PREPARE_UPDATE: {
ink_assert(t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE);
do_cache_prepare_update();
break;
}
case HttpTransact::SM_ACTION_CACHE_ISSUE_UPDATE: {
if (t_state.api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_ERROR) {
t_state.cache_info.object_read = nullptr;
cache_sm.close_read();
}
issue_cache_update();
call_transact_and_set_next_state(nullptr);
break;
}
case HttpTransact::SM_ACTION_WAIT_FOR_FULL_BODY: {
wait_for_full_body();
break;
}
case HttpTransact::SM_ACTION_CONTINUE: {
ink_release_assert(!"Not implemented");
break;
}
default: {
ink_release_assert(!"Unknown next action");
}
}
}
void
HttpSM::do_redirect()
{
SMDebug("http_redirect", "enable_redirection %u", enable_redirection);
if (!enable_redirection || redirection_tries >= t_state.txn_conf->number_of_redirections) {
this->postbuf_clear();
if (enable_redirection && redirection_tries >= t_state.txn_conf->number_of_redirections) {
t_state.squid_codes.subcode = SQUID_SUBCODE_NUM_REDIRECTIONS_EXCEEDED;
}
return;
}
// if redirect_url is set by an user's plugin, yts will redirect to this url anyway.
if (is_redirect_required()) {
if (redirect_url != nullptr || t_state.hdr_info.client_response.field_find(MIME_FIELD_LOCATION, MIME_LEN_LOCATION)) {
if (Log::transaction_logging_enabled() && t_state.api_info.logging_enabled) {
LogAccess accessor(this);
if (redirect_url == nullptr) {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_REDIRECT;
}
} else {
if (t_state.squid_codes.log_code == SQUID_LOG_TCP_HIT) {
t_state.squid_codes.log_code = SQUID_LOG_TCP_HIT_X_REDIRECT;
} else {
t_state.squid_codes.log_code = SQUID_LOG_TCP_MISS_X_REDIRECT;
}
}
int ret = Log::access(&accessor);
if (ret & Log::FULL) {
SMDebug("http", "Logging system indicates FULL.");
}
if (ret & Log::FAIL) {
Log::error("failed to log transaction for at least one log object");
}
}
++redirection_tries;
if (redirect_url != nullptr) {
redirect_request(redirect_url, redirect_url_len);
ats_free((void *)redirect_url);
redirect_url = nullptr;
redirect_url_len = 0;
HTTP_INCREMENT_DYN_STAT(http_total_x_redirect_stat);
} else {
// get the location header and setup the redirect
int redir_len = 0;
char *redir_url =
const_cast<char *>(t_state.hdr_info.client_response.value_get(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, &redir_len));
redirect_request(redir_url, redir_len);
}
} else {
enable_redirection = false;
}
} else {
enable_redirection = false;
}
}
void
HttpSM::redirect_request(const char *arg_redirect_url, const int arg_redirect_len)
{
SMDebug("http_redirect", "redirect url: %.*s", arg_redirect_len, arg_redirect_url);
// get a reference to the client request header and client url and check to see if the url is valid
HTTPHdr &clientRequestHeader = t_state.hdr_info.client_request;
URL &clientUrl = *clientRequestHeader.url_get();
if (!clientUrl.valid()) {
return;
}
bool valid_origHost = true;
int origHost_len, origMethod_len;
char origHost[MAXDNAME];
char origMethod[255];
int origPort = 80;
if (t_state.hdr_info.server_request.valid()) {
char *tmpOrigHost;
origPort = t_state.hdr_info.server_request.port_get();
tmpOrigHost = const_cast<char *>(t_state.hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &origHost_len));
if (tmpOrigHost) {
memcpy(origHost, tmpOrigHost, origHost_len);
origHost[std::min(origHost_len, MAXDNAME - 1)] = '\0';
} else {
valid_origHost = false;
}
char *tmpOrigMethod = const_cast<char *>(t_state.hdr_info.server_request.method_get(&origMethod_len));
if (tmpOrigMethod) {
memcpy(origMethod, tmpOrigMethod, std::min(origMethod_len, static_cast<int>(sizeof(origMethod))));
} else {
valid_origHost = false;
}
} else {
SMDebug("http_redir_error", "t_state.hdr_info.server_request not valid");
valid_origHost = false;
}
t_state.redirect_info.redirect_in_process = true;
// set the passed in location url and parse it
URL redirectUrl;
redirectUrl.create(nullptr);
redirectUrl.parse(arg_redirect_url, arg_redirect_len);
{
int _scheme_len = -1;
int _host_len = -1;
if (redirectUrl.scheme_get(&_scheme_len) == nullptr && redirectUrl.host_get(&_host_len) != nullptr &&
arg_redirect_url[0] != '/') {
// RFC7230 ยง 5.5
// The redirect URL lacked a scheme and so it is a relative URL.
// The redirect URL did not begin with a slash, so we parsed some or all
// of the relative URI path as the host.
// Prepend a slash and parse again.
std::string redirect_url_leading_slash(arg_redirect_len + 1, '\0');
redirect_url_leading_slash[0] = '/';
if (arg_redirect_len > 0) {
memcpy(redirect_url_leading_slash.data() + 1, arg_redirect_url, arg_redirect_len);
}
url_nuke_proxy_stuff(redirectUrl.m_url_impl);
redirectUrl.parse(redirect_url_leading_slash.c_str(), arg_redirect_len + 1);
}
}
// copy the client url to the original url
URL &origUrl = t_state.redirect_info.original_url;
if (!origUrl.valid()) {
origUrl.create(nullptr);
origUrl.copy(&clientUrl);
}
// copy the redirect url to the client url
clientUrl.copy(&redirectUrl);
redirectUrl.destroy();
//(bug 2540703) Clear the previous response if we will attempt the redirect
if (t_state.hdr_info.client_response.valid()) {
// XXX - doing a destroy() for now, we can do a fileds_clear() if we have performance issue
t_state.hdr_info.client_response.destroy();
}
int scheme = t_state.next_hop_scheme;
int scheme_len = hdrtoken_index_to_length(scheme);
const char *next_hop_scheme = hdrtoken_index_to_wks(scheme);
char scheme_str[scheme_len + 1];
if (next_hop_scheme) {
memcpy(scheme_str, next_hop_scheme, scheme_len);
} else {
valid_origHost = false;
}
t_state.hdr_info.server_request.destroy();
// we want to close the server session
// will do that in handle_api_return under the
// HttpTransact::SM_ACTION_REDIRECT_READ state
t_state.parent_result.reset();
t_state.request_sent_time = 0;
t_state.response_received_time = 0;
t_state.next_action = HttpTransact::SM_ACTION_REDIRECT_READ;
// we have a new OS and need to have DNS lookup the new OS
t_state.dns_info.lookup_success = false;
t_state.force_dns = false;
t_state.server_info.clear();
t_state.parent_info.clear();
// Must reset whether the InkAPI has set the destination address
t_state.api_server_addr_set = false;
if (t_state.txn_conf->cache_http) {
t_state.cache_info.object_read = nullptr;
}
bool noPortInHost = HttpConfig::m_master.redirection_host_no_port;
bool isRedirectUrlOriginForm = !clientUrl.m_url_impl->m_len_scheme && !clientUrl.m_url_impl->m_len_user &&
!clientUrl.m_url_impl->m_len_password && !clientUrl.m_url_impl->m_len_host &&
!clientUrl.m_url_impl->m_len_port;
// check to see if the client request passed a host header, if so copy the host and port from the redirect url and
// make a new host header
if (t_state.hdr_info.client_request.presence(MIME_PRESENCE_HOST)) {
int host_len;
const char *host = clientUrl.host_get(&host_len);
if (host != nullptr) {
int port = clientUrl.port_get();
int redirectSchemeLen;
const char *redirectScheme = clientUrl.scheme_get(&redirectSchemeLen);
if (redirectScheme == nullptr) {
clientUrl.scheme_set(scheme_str, scheme_len);
SMDebug("http_redirect", "URL without scheme");
}
if (noPortInHost) {
int redirectSchemeIdx = clientUrl.scheme_get_wksidx();
bool defaultPort =
(((redirectSchemeIdx == URL_WKSIDX_HTTP) && (port == 80)) || ((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (port == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%.*s:%d", host_len, host, port);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
} else {
// the client request didn't have a host, so use the current origin host
if (valid_origHost) {
char *saveptr = nullptr;
// the client request didn't have a host, so use the current origin host
SMDebug("http_redirect", "keeping client request host %s://%s", next_hop_scheme, origHost);
char *origHostNoPort = strtok_r(origHost, ":", &saveptr);
if (origHostNoPort == nullptr) {
goto LhostError;
}
host_len = strlen(origHostNoPort);
if (noPortInHost) {
int redirectSchemeIdx = t_state.next_hop_scheme;
bool defaultPort = (((redirectSchemeIdx == URL_WKSIDX_HTTP) && (origPort == 80)) ||
((redirectSchemeIdx == URL_WKSIDX_HTTPS) && (origPort == 443)));
if (!defaultPort) {
noPortInHost = false;
}
}
if (!noPortInHost) {
char buf[host_len + 7]; // 5 + 1 + 1 ("12345" + ':' + '\0')
host_len = snprintf(buf, host_len + 7, "%s:%d", origHostNoPort, origPort);
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
t_state.hdr_info.client_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, origHostNoPort, host_len);
}
// Cleanup of state etc.
url_nuke_proxy_stuff(clientUrl.m_url_impl);
url_nuke_proxy_stuff(t_state.hdr_info.client_request.m_url_cached.m_url_impl);
t_state.hdr_info.client_request.method_set(origMethod, std::min(origMethod_len, static_cast<int>(sizeof(origMethod))));
t_state.hdr_info.client_request.m_target_cached = false;
t_state.hdr_info.server_request.m_target_cached = false;
clientUrl.scheme_set(scheme_str, scheme_len);
if (isRedirectUrlOriginForm) {
// build the rest of the effictive URL: the authority part
clientUrl.user_set(origUrl.m_url_impl->m_ptr_user, origUrl.m_url_impl->m_len_user);
clientUrl.password_set(origUrl.m_url_impl->m_ptr_password, origUrl.m_url_impl->m_len_password);
clientUrl.host_set(origUrl.m_url_impl->m_ptr_host, origUrl.m_url_impl->m_len_host);
clientUrl.port_set(origUrl.port_get());
}
} else {
LhostError:
// the server request didn't have a host, so remove it from the headers
t_state.hdr_info.client_request.field_delete(MIME_FIELD_HOST, MIME_LEN_HOST);
}
}
}
DUMP_HEADER("http_hdrs", &t_state.hdr_info.client_request, sm_id, "Framed Client Request..checking");
}
void
HttpSM::set_http_schedule(Continuation *contp)
{
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
schedule_cont = contp;
}
int
HttpSM::get_http_schedule(int event, void * /* data ATS_UNUSED */)
{
bool plugin_lock;
Ptr<ProxyMutex> plugin_mutex;
if (schedule_cont->mutex) {
plugin_mutex = schedule_cont->mutex;
plugin_lock = MUTEX_TAKE_TRY_LOCK(schedule_cont->mutex, mutex->thread_holding);
if (!plugin_lock) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::get_http_schedule);
ink_assert(pending_action == nullptr);
pending_action = mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
return 0;
} else {
pending_action = nullptr; // if there was a pending action, it'll get freed after this returns so clear it.
}
} else {
plugin_lock = false;
}
// handle Mutex;
schedule_cont->handleEvent(event, this);
if (plugin_lock) {
Mutex_unlock(plugin_mutex, mutex->thread_holding);
}
return 0;
}
bool
HttpSM::set_server_session_private(bool private_session)
{
if (server_txn != nullptr) {
static_cast<PoolableSession *>(server_txn->get_proxy_ssn())->set_private(private_session);
return true;
}
return false;
}
inline bool
HttpSM::is_private()
{
bool res = false;
if (will_be_private_ss) {
res = will_be_private_ss;
}
return res;
}
// check to see if redirection is enabled and less than max redirections tries or if a plugin enabled redirection
inline bool
HttpSM::is_redirect_required()
{
bool redirect_required = (enable_redirection && (redirection_tries < t_state.txn_conf->number_of_redirections) &&
!HttpTransact::is_fresh_cache_hit(t_state.cache_lookup_result));
SMDebug("http_redirect", "redirect_required: %u", redirect_required);
if (redirect_required == true) {
HTTPStatus status = t_state.hdr_info.client_response.status_get();
// check to see if the response from the origin was a 301, 302, or 303
switch (status) {
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
case HTTP_STATUS_MOVED_TEMPORARILY: // 302
case HTTP_STATUS_SEE_OTHER: // 303
case HTTP_STATUS_USE_PROXY: // 305
case HTTP_STATUS_TEMPORARY_REDIRECT: // 307
case HTTP_STATUS_PERMANENT_REDIRECT: // 308
redirect_required = true;
break;
default:
redirect_required = false;
break;
}
// if redirect_url is set by an user's plugin, ats will redirect to this url anyway.
if (redirect_url != nullptr) {
redirect_required = true;
}
}
return redirect_required;
}
SNIRoutingType
HttpSM::get_tunnel_type() const
{
return _tunnel_type;
}
// Fill in the client protocols used. Return the number of entries populated.
int
HttpSM::populate_client_protocol(std::string_view *result, int n) const
{
int retval = 0;
if (n > 0) {
std::string_view proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (!proto.empty()) {
result[retval++] = proto;
if (n > retval && ua_txn) {
retval += ua_txn->populate_protocol(result + retval, n - retval);
}
}
}
return retval;
}
// Look for a specific client protocol
const char *
HttpSM::client_protocol_contains(std::string_view tag_prefix) const
{
const char *retval = nullptr;
std::string_view proto = HttpSM::find_proto_string(t_state.hdr_info.client_request.version_get());
if (!proto.empty()) {
std::string_view prefix(tag_prefix);
if (prefix.size() <= proto.size() && 0 == strncmp(proto.data(), prefix.data(), prefix.size())) {
retval = proto.data();
} else if (ua_txn) {
retval = ua_txn->protocol_contains(prefix);
}
}
return retval;
}
// Fill in the server protocols used. Return the number of entries populated.
int
HttpSM::populate_server_protocol(std::string_view *result, int n) const
{
int retval = 0;
if (!t_state.hdr_info.server_request.valid()) {
return retval;
}
if (n > 0) {
std::string_view proto = HttpSM::find_proto_string(t_state.hdr_info.server_request.version_get());
if (!proto.empty()) {
result[retval++] = proto;
if (n > retval && server_txn) {
retval += server_txn->populate_protocol(result + retval, n - retval);
}
}
}
return retval;
}
// Look for a specific server protocol
const char *
HttpSM::server_protocol_contains(std::string_view tag_prefix) const
{
const char *retval = nullptr;
std::string_view proto = HttpSM::find_proto_string(t_state.hdr_info.server_request.version_get());
if (!proto.empty()) {
std::string_view prefix(tag_prefix);
if (prefix.size() <= proto.size() && 0 == strncmp(proto.data(), prefix.data(), prefix.size())) {
retval = proto.data();
} else {
if (server_txn) {
retval = server_txn->protocol_contains(prefix);
}
}
}
return retval;
}
std::string_view
HttpSM::find_proto_string(HTTPVersion version) const
{
if (version == HTTP_2_0) {
return IP_PROTO_TAG_HTTP_2_0;
} else if (version == HTTP_1_1) {
return IP_PROTO_TAG_HTTP_1_1;
} else if (version == HTTP_1_0) {
return IP_PROTO_TAG_HTTP_1_0;
} else if (version == HTTP_0_9) {
return IP_PROTO_TAG_HTTP_0_9;
}
return {};
}
void
HttpSM::rewind_state_machine()
{
callout_state = HTTP_API_REWIND_STATE_MACHINE;
}
// YTS Team, yamsat Plugin
// Function to copy the partial Post data while tunnelling
void
PostDataBuffers::copy_partial_post_data()
{
if (post_data_buffer_done) {
return;
}
Debug("http_redirect", "[PostDataBuffers::copy_partial_post_data] wrote %" PRId64 " bytes to buffers %" PRId64 "",
this->ua_buffer_reader->read_avail(), this->postdata_copy_buffer_start->read_avail());
this->postdata_copy_buffer->write(this->ua_buffer_reader);
this->ua_buffer_reader->consume(this->ua_buffer_reader->read_avail());
}
IOBufferReader *
PostDataBuffers::get_post_data_buffer_clone_reader()
{
return this->postdata_copy_buffer->clone_reader(this->postdata_copy_buffer_start);
}
// YTS Team, yamsat Plugin
// Allocating the post data buffers
void
PostDataBuffers::init(IOBufferReader *ua_reader)
{
Debug("http_redirect", "[PostDataBuffers::init]");
this->ua_buffer_reader = ua_reader;
if (this->postdata_copy_buffer == nullptr) {
this->post_data_buffer_done = false;
ink_assert(this->postdata_copy_buffer_start == nullptr);
this->postdata_copy_buffer = new_empty_MIOBuffer(BUFFER_SIZE_INDEX_4K);
this->postdata_copy_buffer_start = this->postdata_copy_buffer->alloc_reader();
}
ink_assert(this->ua_buffer_reader != nullptr);
}
// YTS Team, yamsat Plugin
// Deallocating the post data buffers
void
PostDataBuffers::clear()
{
Debug("http_redirect", "[PostDataBuffers::clear]");
if (this->postdata_copy_buffer != nullptr) {
free_MIOBuffer(this->postdata_copy_buffer);
this->postdata_copy_buffer = nullptr;
this->postdata_copy_buffer_start = nullptr; // deallocated by the buffer
}
this->post_data_buffer_done = false;
}
PostDataBuffers::~PostDataBuffers()
{
this->clear();
}
HTTPVersion
HttpSM::get_server_version(HTTPHdr &hdr) const
{
return this->server_txn->get_proxy_ssn()->get_version(hdr);
}
/// Update the milestone state given the milestones and timer.
void
HttpSM::milestone_update_api_time()
{
// Bit of funkiness - we set @a api_timer to be the negative value when we're tracking
// non-active API time. In that case we need to make a note of it and flip the value back
// to positive.
if (api_timer) {
ink_hrtime delta;
bool active = api_timer >= 0;
if (!active) {
api_timer = -api_timer;
}
delta = ink_get_hrtime() - api_timer;
api_timer = 0;
// Zero or negative time is a problem because we want to signal *something* happened
// vs. no API activity at all. This can happen due to graininess or real time
// clock adjustment.
if (delta <= 0) {
delta = 1;
}
if (0 == milestones[TS_MILESTONE_PLUGIN_TOTAL]) {
milestones[TS_MILESTONE_PLUGIN_TOTAL] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_TOTAL] += delta;
if (active) {
if (0 == milestones[TS_MILESTONE_PLUGIN_ACTIVE]) {
milestones[TS_MILESTONE_PLUGIN_ACTIVE] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_ACTIVE] += delta;
}
}
}
|