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 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041
|
/** @file
A brief file description
@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 "ts/parentselectdefs.h"
#include "tscore/ink_platform.h"
#include <strings.h>
#include <cmath>
#include "HttpTransact.h"
#include "HttpTransactHeaders.h"
#include "HttpSM.h"
#include "HttpCacheSM.h" //Added to get the scope of HttpCacheSM object - YTS Team, yamsat
#include "HttpDebugNames.h"
#include <ctime>
#include "tscore/ParseRules.h"
#include "tscore/Filenames.h"
#include "tscore/bwf_std_format.h"
#include "HTTP.h"
#include "HdrUtils.h"
#include "logging/Log.h"
#include "logging/LogUtils.h"
#include "CacheControl.h"
#include "ControlMatcher.h"
#include "ReverseProxy.h"
#include "HttpBodyFactory.h"
#include "StatPages.h"
#include "../IPAllow.h"
#include "I_Machine.h"
namespace
{
char const Dns_error_body[] = "connect#dns_failed";
/// Buffer for some error logs.
thread_local std::string error_bw_buffer;
} // namespace
// Support ip_resolve override.
const MgmtConverter HttpTransact::HOST_RES_CONV{[](const void *data) -> std::string_view {
const HostResData *host_res_data = static_cast<const HostResData *>(data);
return host_res_data->conf_value;
},
[](void *data, std::string_view src) -> void {
HostResData *res_data = static_cast<HostResData *>(data);
parse_host_res_preference(src.data(), res_data->order);
}};
static char range_type[] = "multipart/byteranges; boundary=RANGE_SEPARATOR";
#define RANGE_NUMBERS_LENGTH 60
#define TRANSACT_SETUP_RETURN(n, r) \
s->next_action = n; \
s->transact_return_point = r; \
SpecificDebug((s->state_machine && s->state_machine->debug_on), "http_trans", "Next action %s; %s", #n, #r);
#define TRANSACT_RETURN(n, r) \
TRANSACT_SETUP_RETURN(n, r) \
return;
#define TRANSACT_RETURN_VAL(n, r, v) \
TRANSACT_SETUP_RETURN(n, r) \
return v;
#define SET_UNPREPARE_CACHE_ACTION(C) \
{ \
if (C.action == HttpTransact::CACHE_PREPARE_TO_DELETE) { \
C.action = HttpTransact::CACHE_DO_DELETE; \
} else if (C.action == HttpTransact::CACHE_PREPARE_TO_UPDATE) { \
C.action = HttpTransact::CACHE_DO_UPDATE; \
} else { \
C.action = HttpTransact::CACHE_DO_WRITE; \
} \
}
#define TxnDebug(tag, fmt, ...) \
SpecificDebug((s->state_machine->debug_on), tag, "[%" PRId64 "] " fmt, s->state_machine->sm_id, ##__VA_ARGS__)
extern HttpBodyFactory *body_factory;
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static bool
bypass_ok(HttpTransact::State *s)
{
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
return s->response_action.action.goDirect;
} else if (mp && mp->strategy) {
// remap strategies do not support the TSHttpTxnParentProxySet API.
return mp->strategy->go_direct;
} else if (s->parent_params) {
return s->parent_result.bypass_ok();
}
return false;
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static bool
is_api_result(HttpTransact::State *s)
{
bool r = false;
url_mapping *mp = s->url_map.getMapping();
if (mp && mp->strategy) {
// remap strategies do not support the TSHttpTxnParentProxySet API.
r = false;
} else if (s->parent_params) {
r = s->parent_result.is_api_result();
}
return r;
}
// wrapper to get the max_retries.
// Does NOT check the strategy; if strategy exists, strategy->responseIsRetryable should be called instead.
inline static unsigned
max_retries(HttpTransact::State *s, ParentRetry_t method)
{
if (s->parent_params) {
return s->parent_result.max_retries(method);
}
return 0;
}
// wrapper to get the numParents.
// Does NOT check the strategy; if strategy exists, strategy->responseIsRetryable should be called instead.
inline static uint32_t
numParents(HttpTransact::State *s)
{
if (s->parent_params) {
return s->parent_params->numParents(&s->parent_result);
}
return 0;
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static bool
parent_is_proxy(HttpTransact::State *s)
{
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
return s->response_action.action.parentIsProxy;
} else if (mp && mp->strategy) {
return mp->strategy->parent_is_proxy;
} else if (s->parent_params) {
return s->parent_result.parent_is_proxy();
}
return false;
}
// wrapper to get the parent.config retry type.
// Does NOT check the strategy; if strategy exists, strategy->responseIsRetryable should be called instead.
inline static unsigned
retry_type(HttpTransact::State *s)
{
if (s->parent_params) {
return s->parent_result.retry_type();
}
return PARENT_RETRY_NONE;
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static void
findParent(HttpTransact::State *s)
{
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
s->parent_result.hostname = s->response_action.action.hostname;
s->parent_result.port = s->response_action.action.port;
s->parent_result.retry = s->response_action.action.is_retry;
if (!s->response_action.action.fail) {
s->parent_result.result = PARENT_SPECIFIED;
} else if (s->response_action.action.goDirect) {
s->parent_result.result = PARENT_DIRECT;
} else {
s->parent_result.result = PARENT_FAIL;
}
} else if (mp && mp->strategy) {
mp->strategy->findNextHop(reinterpret_cast<TSHttpTxn>(s->state_machine));
} else if (s->parent_params) {
s->parent_params->findParent(&s->request_data, &s->parent_result, s->txn_conf->parent_fail_threshold,
s->txn_conf->parent_retry_time);
}
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static void
markParentDown(HttpTransact::State *s)
{
HTTP_INCREMENT_DYN_STAT(http_total_parent_marked_down_count);
url_mapping *mp = s->url_map.getMapping();
TxnDebug("http_trans", "enable_parent_timeout_markdowns: %d, disable_parent_markdowns: %d",
s->txn_conf->enable_parent_timeout_markdowns, s->txn_conf->disable_parent_markdowns);
if (s->txn_conf->disable_parent_markdowns == 1) {
TxnDebug("http_trans", "parent markdowns are disabled for this request");
return;
}
if (s->current.state == HttpTransact::INACTIVE_TIMEOUT && s->txn_conf->enable_parent_timeout_markdowns == 0) {
return;
}
if (s->response_action.handled) {
// Do nothing. If a plugin handled the response, let it handle markdown.
} else if (mp && mp->strategy) {
mp->strategy->markNextHop(reinterpret_cast<TSHttpTxn>(s->state_machine), s->parent_result.hostname, s->parent_result.port,
NH_MARK_DOWN);
} else if (s->parent_params) {
s->parent_params->markParentDown(&s->parent_result, s->txn_conf->parent_fail_threshold, s->txn_conf->parent_retry_time);
}
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static void
markParentUp(HttpTransact::State *s)
{
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
// Do nothing. If a plugin handled the response, let it handle markdown
} else if (mp && mp->strategy) {
mp->strategy->markNextHop(reinterpret_cast<TSHttpTxn>(s->state_machine), s->parent_result.hostname, s->parent_result.port,
NH_MARK_UP);
} else if (s->parent_params) {
s->parent_params->markParentUp(&s->parent_result);
}
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static bool
parentExists(HttpTransact::State *s)
{
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
return s->response_action.action.nextHopExists;
} else if (mp && mp->strategy) {
return mp->strategy->nextHopExists(reinterpret_cast<TSHttpTxn>(s->state_machine));
} else if (s->parent_params) {
return s->parent_params->parentExists(&s->request_data);
} else {
return false;
}
}
// wrapper to choose between a remap next hop strategy or use parent.config
// remap next hop strategy is preferred
inline static void
nextParent(HttpTransact::State *s)
{
TxnDebug("parent_down", "connection to parent %s failed, conn_state: %s, request to origin: %s", s->parent_result.hostname,
HttpDebugNames::get_server_state_name(s->current.state), s->request_data.get_host());
url_mapping *mp = s->url_map.getMapping();
if (s->response_action.handled) {
s->parent_result.hostname = s->response_action.action.hostname;
s->parent_result.port = s->response_action.action.port;
s->parent_result.retry = s->response_action.action.is_retry;
if (!s->response_action.action.fail) {
s->parent_result.result = PARENT_SPECIFIED;
} else if (s->response_action.action.goDirect) {
s->parent_result.result = PARENT_DIRECT;
} else {
s->parent_result.result = PARENT_FAIL;
}
} else if (mp && mp->strategy) {
// NextHop only has a findNextHop() function.
mp->strategy->findNextHop(reinterpret_cast<TSHttpTxn>(s->state_machine));
} else if (s->parent_params) {
s->parent_params->nextParent(&s->request_data, &s->parent_result, s->txn_conf->parent_fail_threshold,
s->txn_conf->parent_retry_time);
}
}
inline static bool
is_localhost(const char *name, int len)
{
static const char local[] = "127.0.0.1";
return (len == (sizeof(local) - 1)) && (memcmp(name, local, len) == 0);
}
bool
HttpTransact::is_response_valid(State *s, HTTPHdr *incoming_response)
{
if (s->current.state != CONNECTION_ALIVE) {
ink_assert((s->current.state == CONNECTION_ERROR) || (s->current.state == OPEN_RAW_ERROR) ||
(s->current.state == PARSE_ERROR) || (s->current.state == CONNECTION_CLOSED) ||
(s->current.state == INACTIVE_TIMEOUT) || (s->current.state == ACTIVE_TIMEOUT) ||
s->current.state == OUTBOUND_CONGESTION || s->current.state == BAD_INCOMING_RESPONSE);
s->hdr_info.response_error = CONNECTION_OPEN_FAILED;
return false;
}
s->hdr_info.response_error = check_response_validity(s, incoming_response);
switch (s->hdr_info.response_error) {
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
// We could modify the response to add the date, if need be.
// incoming_response->set_date(s->request_sent_time);
return true;
#endif
case NO_RESPONSE_HEADER_ERROR:
TxnDebug("http_trans", "No errors in response");
return true;
case MISSING_REASON_PHRASE:
TxnDebug("http_trans", "Response Error: Missing reason phrase - allowing");
return true;
case STATUS_CODE_SERVER_ERROR:
TxnDebug("http_trans", "Response Error: Origin Server returned 500 - allowing");
return true;
case CONNECTION_OPEN_FAILED:
TxnDebug("http_trans", "Response Error: connection open failed");
s->current.state = CONNECTION_ERROR;
return false;
case NON_EXISTANT_RESPONSE_HEADER:
TxnDebug("http_trans", "Response Error: No response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case NOT_A_RESPONSE_HEADER:
TxnDebug("http_trans", "Response Error: Not a response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case MISSING_STATUS_CODE:
TxnDebug("http_trans", "Response Error: Missing status code");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
default:
TxnDebug("http_trans", "Errors in response");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
}
}
inline static ParentRetry_t
response_is_retryable(HttpTransact::State *s, HTTPStatus response_code)
{
if (!HttpTransact::is_response_valid(s, &s->hdr_info.server_response) || s->current.request_to != HttpTransact::PARENT_PROXY) {
return PARENT_RETRY_NONE;
}
if (s->response_action.handled) {
return s->response_action.action.responseIsRetryable ? PARENT_RETRY_SIMPLE : PARENT_RETRY_NONE;
}
const url_mapping *mp = s->url_map.getMapping();
if (mp && mp->strategy) {
return mp->strategy->responseIsRetryable(s->state_machine->sm_id, s->current, response_code);
}
if (s->parent_params && !s->parent_result.response_is_retryable((ParentRetry_t)(s->parent_result.retry_type()), response_code)) {
return PARENT_RETRY_NONE;
}
const unsigned int s_retry_type = retry_type(s);
// If simple or both, check if code is simple-retryable and for retry attempts
if ((s_retry_type & PARENT_RETRY_SIMPLE) && s->parent_result.response_is_retryable(PARENT_RETRY_SIMPLE, response_code) &&
s->current.simple_retry_attempts < max_retries(s, PARENT_RETRY_SIMPLE)) {
TxnDebug("http_trans", "saw parent retry simple first in trans");
if (s->current.simple_retry_attempts < numParents(s)) {
return PARENT_RETRY_SIMPLE;
}
return PARENT_RETRY_NONE;
}
// If unavailable or both, check if code is unavailable-retryable AND also not simple-retryable, then unavailable retry attempts
if ((s_retry_type & PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->parent_result.response_is_retryable(PARENT_RETRY_UNAVAILABLE_SERVER, response_code) &&
!s->parent_result.response_is_retryable(PARENT_RETRY_SIMPLE, response_code) &&
s->current.unavailable_server_retry_attempts < max_retries(s, PARENT_RETRY_UNAVAILABLE_SERVER)) {
TxnDebug("http_trans", "saw parent retry unavailable first in trans");
if (s->current.unavailable_server_retry_attempts < numParents(s)) {
return PARENT_RETRY_UNAVAILABLE_SERVER;
}
return PARENT_RETRY_NONE;
}
return PARENT_RETRY_NONE;
}
inline static void
simple_or_unavailable_server_retry(HttpTransact::State *s)
{
if (!HttpTransact::is_response_valid(s, &s->hdr_info.server_response)) {
return; // must return now if the response isn't valid, before calling http_hdr_status_get on uninitialized data
}
HTTPStatus server_response = http_hdr_status_get(s->hdr_info.server_response.m_http);
switch (response_is_retryable(s, server_response)) {
case PARENT_RETRY_SIMPLE:
s->current.state = HttpTransact::PARENT_RETRY;
s->current.retry_type = PARENT_RETRY_SIMPLE;
break;
case PARENT_RETRY_UNAVAILABLE_SERVER:
s->current.state = HttpTransact::PARENT_RETRY;
s->current.retry_type = PARENT_RETRY_UNAVAILABLE_SERVER;
break;
case PARENT_RETRY_BOTH:
ink_assert(!"response_is_retryable should return an exact retry type, never both");
break;
case PARENT_RETRY_NONE:
break; // no retry
}
}
inline static bool
is_request_conditional(HTTPHdr *header)
{
uint64_t mask = (MIME_PRESENCE_IF_UNMODIFIED_SINCE | MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_RANGE |
MIME_PRESENCE_IF_MATCH | MIME_PRESENCE_IF_NONE_MATCH);
return (header->presence(mask) &&
(header->method_get_wksidx() == HTTP_WKSIDX_GET || header->method_get_wksidx() == HTTP_WKSIDX_HEAD));
}
static inline bool
is_port_in_range(int port, HttpConfigPortRange *pr)
{
while (pr) {
if (pr->low == -1) {
return true;
} else if ((pr->low <= port) && (pr->high >= port)) {
return true;
}
pr = pr->next;
}
return false;
}
inline static void
update_cache_control_information_from_config(HttpTransact::State *s)
{
getCacheControl(&s->cache_control, &s->request_data, s->txn_conf);
s->cache_info.directives.does_config_permit_lookup &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_config_permit_storing &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_client_permit_storing =
HttpTransact::does_client_request_permit_storing(&s->cache_control, &s->hdr_info.client_request);
s->cache_info.directives.does_client_permit_lookup = HttpTransact::does_client_request_permit_cached_response(
s->txn_conf, &s->cache_control, &s->hdr_info.client_request, s->via_string);
s->cache_info.directives.does_client_permit_dns_storing =
HttpTransact::does_client_request_permit_dns_caching(&s->cache_control, &s->hdr_info.client_request);
if (s->client_info.http_version == HTTP_0_9) {
s->cache_info.directives.does_client_permit_lookup = false;
s->cache_info.directives.does_client_permit_storing = false;
}
// Less than 0 means it wasn't overridden, so leave it alone.
if (s->cache_control.cache_responses_to_cookies >= 0) {
s->my_txn_conf().cache_responses_to_cookies = s->cache_control.cache_responses_to_cookies;
}
}
bool
HttpTransact::is_server_negative_cached(State *s)
{
if (s->host_db_info.app.http_data.last_failure != 0 &&
s->host_db_info.app.http_data.last_failure + s->txn_conf->down_server_timeout > s->client_request_time) {
return true;
} else {
// Make sure some nasty clock skew has not happened
// Use the server timeout to set an upperbound as to how far in the
// future we should tolerate bogus last failure times. This sets
// the upper bound to the time that we would ever consider a server
// down to 2*down_server_timeout
if (s->client_request_time + s->txn_conf->down_server_timeout < s->host_db_info.app.http_data.last_failure) {
s->host_db_info.app.http_data.last_failure = 0;
s->host_db_info.app.http_data.fail_count = 0;
ink_assert(!"extreme clock skew");
return true;
}
return false;
}
}
inline static void
update_current_info(HttpTransact::CurrentInfo *into, HttpTransact::ConnectionAttributes *from, HttpTransact::LookingUp_t who,
int attempts)
{
into->request_to = who;
into->server = from;
into->attempts = attempts;
}
inline static void
update_dns_info(HttpTransact::DNSLookupInfo *dns, HttpTransact::CurrentInfo *from)
{
dns->looking_up = from->request_to;
dns->lookup_name = from->server->name;
}
inline static HTTPHdr *
find_appropriate_cached_resp(HttpTransact::State *s)
{
HTTPHdr *c_resp = nullptr;
if (s->cache_info.object_store.valid()) {
c_resp = s->cache_info.object_store.response_get();
if (c_resp != nullptr && c_resp->valid()) {
return c_resp;
}
}
ink_assert(s->cache_info.object_read != nullptr);
return s->cache_info.object_read->response_get();
}
int response_cacheable_indicated_by_cc(HTTPHdr *response);
inline static bool
is_negative_caching_appropriate(HttpTransact::State *s)
{
if (!s->txn_conf->negative_caching_enabled || !s->hdr_info.server_response.valid()) {
return false;
}
int status = s->hdr_info.server_response.status_get();
auto params = s->http_config_param;
if (params->negative_caching_list[status]) {
TxnDebug("http_trans", "%d is eligible for negative caching", status);
return true;
} else {
TxnDebug("http_trans", "%d is NOT eligible for negative caching", status);
return false;
}
}
inline static HttpTransact::LookingUp_t
find_server_and_update_current_info(HttpTransact::State *s)
{
int host_len;
const char *host = s->hdr_info.client_request.host_get(&host_len);
if (is_localhost(host, host_len)) {
// Do not forward requests to local_host onto a parent.
// I just wanted to do this for cop heartbeats, someone else
// wanted it for all requests to local_host.
TxnDebug("http_trans", "request is from localhost, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
} else if (s->method == HTTP_WKSIDX_CONNECT && s->http_config_param->disable_ssl_parenting) {
if (s->parent_result.result == PARENT_SPECIFIED) {
nextParent(s);
} else {
findParent(s);
}
if (!s->parent_result.is_some() || is_api_result(s) || parent_is_proxy(s)) {
TxnDebug("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else if (s->txn_conf->uncacheable_requests_bypass_parent && s->http_config_param->no_dns_forward_to_parent == 0 &&
!HttpTransact::is_request_cache_lookupable(s)) {
// request not lookupable and cacheable, so bypass parent if the parent is not an origin server.
// Note that the configuration of the proxy as well as the request
// itself affects the result of is_request_cache_lookupable();
// we are assuming both child and parent have similar configuration
// with respect to whether a request is cacheable or not.
// For example, the cache_urls_that_look_dynamic variable.
if (s->parent_result.result == PARENT_SPECIFIED) {
nextParent(s);
} else {
findParent(s);
}
if (!s->parent_result.is_some() || is_api_result(s) || parent_is_proxy(s)) {
TxnDebug("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else {
switch (s->parent_result.result) {
case PARENT_UNDEFINED:
findParent(s);
break;
case PARENT_SPECIFIED:
nextParent(s);
// Hack!
// We already have a parent that failed, if we are now told
// to go the origin server, we can only obey this if we
// dns'ed the origin server
if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 0) {
ink_assert(!s->server_info.dst_addr.isValid());
s->parent_result.result = PARENT_FAIL;
}
break;
case PARENT_FAIL:
// Check to see if should bypass the parent and go direct
// We can only do this if
// 1) the config permitted us to dns the origin server
// 2) the config permits us
// 3) the parent was not set from API
if (s->http_config_param->no_dns_forward_to_parent == 0 && bypass_ok(s) && parent_is_proxy(s) &&
!s->parent_params->apiParentExists(&s->request_data)) {
s->parent_result.result = PARENT_DIRECT;
}
break;
default:
ink_assert(0);
// FALL THROUGH
case PARENT_DIRECT:
// // if we have already decided to go direct
// // dont bother calling nextParent.
// // do nothing here, guy.
break;
}
}
switch (s->parent_result.result) {
case PARENT_SPECIFIED:
s->parent_info.name = s->arena.str_store(s->parent_result.hostname, strlen(s->parent_result.hostname));
update_current_info(&s->current, &s->parent_info, HttpTransact::PARENT_PROXY, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current);
ink_assert(s->dns_info.looking_up == HttpTransact::PARENT_PROXY);
s->next_hop_scheme = URL_WKSIDX_HTTP;
return HttpTransact::PARENT_PROXY;
case PARENT_FAIL:
// No more parents - need to return an error message
s->current.request_to = HttpTransact::HOST_NONE;
return HttpTransact::HOST_NONE;
case PARENT_DIRECT:
// if the configuration does not allow the origin to be dns'd
// we're unable to go direct to the origin.
if (s->http_config_param->no_dns_forward_to_parent) {
Warning("no available parents and the config proxy.config.http.no_dns_just_forward_to_parent, prevents origin lookups.");
s->parent_result.result = PARENT_FAIL;
return HttpTransact::HOST_NONE;
}
/* fall through */
default:
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current);
ink_assert(s->dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
s->next_hop_scheme = s->scheme;
return HttpTransact::ORIGIN_SERVER;
}
}
inline static bool
do_cookies_prevent_caching(int cookies_conf, HTTPHdr *request, HTTPHdr *response, HTTPHdr *cached_request = nullptr)
{
enum CookiesConfig {
COOKIES_CACHE_NONE = 0, // do not cache any responses to cookies
COOKIES_CACHE_ALL = 1, // cache for any content-type (ignore cookies)
COOKIES_CACHE_IMAGES = 2, // cache only for image types
COOKIES_CACHE_ALL_BUT_TEXT = 3, // cache for all but text content-types
COOKIES_CACHE_ALL_BUT_TEXT_EXT = 4 // cache for all but text content-types except with OS response
// without "Set-Cookie" or with "Cache-Control: public"
};
const char *content_type = nullptr;
int str_len;
#ifdef DEBUG
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (cached_request) {
ink_assert(cached_request->type_get() == HTTP_TYPE_REQUEST);
}
#endif
// Can cache all regardless of cookie header - just ignore all cookie headers
if (static_cast<CookiesConfig>(cookies_conf) == COOKIES_CACHE_ALL) {
return false;
}
// It is considered that Set-Cookie headers can be safely ignored
// for non text content types if Cache-Control private is not set.
// This enables a bigger hit rate, which currently outweighs the risk of
// breaking origin servers that truly intend to set a cookie with other
// objects such as images.
// At this time, it is believed that only advertisers do this, and that
// customers won't care about it.
// If the response does not have a Set-Cookie header and
// the response does not have a Cookie header and
// the object is not cached or the request does not have a Cookie header
// then cookies do not prevent caching.
if (!response->presence(MIME_PRESENCE_SET_COOKIE) && !request->presence(MIME_PRESENCE_COOKIE) &&
(cached_request == nullptr || !cached_request->presence(MIME_PRESENCE_COOKIE))) {
return false;
}
// Do not cache if cookies option is COOKIES_CACHE_NONE
// and a Cookie is detected
if (static_cast<CookiesConfig>(cookies_conf) == COOKIES_CACHE_NONE) {
return true;
}
// All other options depend on the Content-Type
content_type = response->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &str_len);
if (static_cast<CookiesConfig>(cookies_conf) == COOKIES_CACHE_IMAGES) {
if (content_type && str_len >= 5 && memcmp(content_type, "image", 5) == 0) {
// Images can be cached
return false;
}
return true; // do not cache if COOKIES_CACHE_IMAGES && content_type != "image"
}
// COOKIES_CACHE_ALL_BUT_TEXT || COOKIES_CACHE_ALL_BUT_TEXT_EXT
// Note: if the configuration is bad, we consider
// COOKIES_CACHE_ALL_BUT_TEXT to be the default
if (content_type && str_len >= 4 && memcmp(content_type, "text", 4) == 0) { // content type - "text"
// Text objects cannot be cached unless the option is
// COOKIES_CACHE_ALL_BUT_TEXT_EXT.
// Furthermore, if there is a Set-Cookie header, then
// Cache-Control must be set.
if (static_cast<CookiesConfig>(cookies_conf) == COOKIES_CACHE_ALL_BUT_TEXT_EXT &&
((!response->presence(MIME_PRESENCE_SET_COOKIE)) || response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
return false;
}
return true;
}
return false; // Non text objects can be cached
}
inline static bool
does_method_require_cache_copy_deletion(const HttpConfigParams *http_config_param, const int method)
{
return ((method != HTTP_WKSIDX_GET) &&
(method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
(http_config_param->cache_post_method != 1 && method == HTTP_WKSIDX_POST)));
}
inline static bool
does_method_effect_cache(int method)
{
return ((method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
method == HTTP_WKSIDX_POST));
}
inline static HttpTransact::StateMachineAction_t
how_to_open_connection(HttpTransact::State *s)
{
ink_assert((s->pending_work == nullptr) || (s->current.request_to == HttpTransact::PARENT_PROXY));
// Originally we returned which type of server to open
// Now, however, we may want to issue a cache
// operation first in order to lock the cache
// entry to prevent multiple origin server requests
// for the same document.
// The cache operation that we actually issue, of
// course, depends on the specified "cache_action".
// If there is no cache-action to be issued, just
// connect to the server.
switch (s->cache_info.action) {
case HttpTransact::CACHE_PREPARE_TO_DELETE:
case HttpTransact::CACHE_PREPARE_TO_UPDATE:
case HttpTransact::CACHE_PREPARE_TO_WRITE:
s->transact_return_point = HttpTransact::handle_cache_write_lock;
return HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE;
default:
// This covers:
// CACHE_DO_UNDEFINED, CACHE_DO_NO_ACTION, CACHE_DO_DELETE,
// CACHE_DO_LOOKUP, CACHE_DO_REPLACE, CACHE_DO_SERVE,
// CACHE_DO_SERVE_AND_DELETE, CACHE_DO_SERVE_AND_UPDATE,
// CACHE_DO_UPDATE, CACHE_DO_WRITE, TOTAL_CACHE_ACTION_TYPES
break;
}
HttpTransact::StateMachineAction_t connect_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
// Setting up a direct CONNECT tunnel enters OriginServerRawOpen. We always do that if we
// are not forwarding CONNECT and are not going to a parent proxy.
if (s->method == HTTP_WKSIDX_CONNECT) {
if (s->txn_conf->forward_connect_method != 1 && s->parent_result.result != PARENT_SPECIFIED) {
connect_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
}
}
if (!s->already_downgraded) { // false unless downgraded previously (possibly due to HTTP 505)
(&s->hdr_info.server_request)->version_set(HTTP_1_1);
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
}
return connect_next_action;
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact State Machine Handlers ****
**** ****
**** What follow from here on are the state machine handlers - the code ****
**** which is called from HttpSM::set_next_state to specify ****
**** what action the state machine needs to execute next. These ftns ****
**** take as input just the state and set the next_action variable. ****
*****************************************************************************
*****************************************************************************/
void
HttpTransact::BadRequest(State *s)
{
TxnDebug("http_trans", "parser marked request bad");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
const char *body_factory_template = "request#syntax_error";
HTTPStatus status = HTTP_STATUS_BAD_REQUEST;
const char *reason = "Invalid HTTP Request";
switch (s->http_return_code) {
case HTTP_STATUS_REQUEST_URI_TOO_LONG:
body_factory_template = "request#uri_len_too_long";
status = s->http_return_code;
reason = "URI Too Long";
break;
case HTTP_STATUS_NOT_IMPLEMENTED:
status = s->http_return_code;
reason = "Field not implemented";
body_factory_template = "transcoding#unsupported";
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
status = s->http_return_code;
reason = "Unsupported HTTP Version";
default:
break;
}
build_error_response(s, status, reason, body_factory_template);
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::PostActiveTimeoutResponse(State *s)
{
TxnDebug("http_trans", "post active timeout");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_REQUEST_TIMEOUT, "Active Timeout", "timeout#activity");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::PostInactiveTimeoutResponse(State *s)
{
TxnDebug("http_trans", "post inactive timeout");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_REQUEST_TIMEOUT, "Inactive Timeout", "timeout#inactivity");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::Forbidden(State *s)
{
TxnDebug("http_trans", "IpAllow marked request forbidden");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::SelfLoop(State *s)
{
TxnDebug("http_trans", "Request will selfloop.");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Direct self loop detected", "request#cycle_detected");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::TooEarly(State *s)
{
TxnDebug("http_trans", "Early Data method is not safe");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_TOO_EARLY, "Too Early", "too#early");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::OriginDead(State *s)
{
TxnDebug("http_trans", "origin server is marked down");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Origin Server Marked Down", "connect#failed_connect");
HTTP_INCREMENT_DYN_STAT(http_dead_server_no_requests);
char *url_str = s->hdr_info.client_request.url_string_get(&s->arena);
int host_len;
const char *host_name_ptr = s->unmapped_url.host_get(&host_len);
std::string_view host_name{host_name_ptr, size_t(host_len)};
ts::bwprint(error_bw_buffer, "CONNECT: dead server no request to {} for host='{}' url='{}'", s->current.server->dst_addr,
host_name, ts::bwf::FirstOf(url_str, "<none>"));
Log::error("%s", error_bw_buffer.c_str());
s->arena.str_free(url_str);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::HandleBlindTunnel(State *s)
{
URL u;
// IpEndpoint dest_addr;
// ip_text_buffer new_host;
TxnDebug("http_trans", "Entering HttpTransact::HandleBlindTunnel");
// We set the version to 0.9 because once we know where we are going
// this blind ssl tunnel is indistinguishable from a "CONNECT 0.9"
// except for the need to suppression error messages
HTTPVersion ver(0, 9);
s->hdr_info.client_request.version_set(ver);
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
if (is_debug_tag_set("http_trans")) {
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
TxnDebug("http_trans", "destination set to %.*s:%d", host_len, host, s->hdr_info.client_request.url_get()->port_get());
}
// Set the mode to tunnel so that we don't lookup the cache
s->current.mode = TUNNELLING_PROXY;
// Let the request work it's way through the code and
// we grab it again after the raw connection has been opened
HandleRequest(s);
}
void
HttpTransact::StartRemapRequest(State *s)
{
// Preserve effective url before remap, regardless of actual need for remap
s->unmapped_url.create(s->hdr_info.client_request.url_get()->m_heap);
s->unmapped_url.copy(s->hdr_info.client_request.url_get());
if (s->api_skip_all_remapping) {
TxnDebug("http_trans", "API request to skip remapping");
s->hdr_info.client_request.set_url_target_from_host_field();
// Since we're not doing remap, we still have to allow for these overridable
// configurations to modify follow-redirect behavior. Someone could for example
// have set them in a plugin other than conf_remap running in a prior hook.
s->state_machine->enable_redirection = (s->txn_conf->number_of_redirections > 0);
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, HttpTransact::HandleRequest);
}
TxnDebug("http_trans", "START HttpTransact::StartRemapRequest");
//////////////////////////////////////////////////////////////////
// FIX: this logic seems awfully convoluted and hard to follow; //
// seems like we could come up with a more elegant and //
// comprehensible design that generalized things //
//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// run the remap url-rewriting engine: //
// //
// * the variable <url_remap_success> is set true if //
// the url was rewritten //
// //
// * the variable <remap_redirect> is set to non-NULL if there //
// is a URL provided that the proxy is supposed to redirect //
// requesters of a particular URL to. //
/////////////////////////////////////////////////////////////////
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans")) {
TxnDebug("http_trans", "Before Remapping:");
obj_describe(s->hdr_info.client_request.m_http, true);
}
DUMP_HEADER("http_hdrs", &s->hdr_info.client_request, s->state_machine_id, "Incoming Request");
if (s->http_config_param->referer_filter_enabled) {
s->filter_mask = URL_REMAP_FILTER_REFERER;
if (s->http_config_param->referer_format_redirect) {
s->filter_mask |= URL_REMAP_FILTER_REDIRECT_FMT;
}
}
TxnDebug("http_trans", "END HttpTransact::StartRemapRequest");
TxnDebug("http_trans", "Checking if transaction wants to upgrade");
if (handle_upgrade_request(s)) {
// everything should be handled by the upgrade handler.
TxnDebug("http_trans", "Transaction will be upgraded by the appropriate upgrade handler.");
return;
}
TRANSACT_RETURN(SM_ACTION_API_PRE_REMAP, HttpTransact::PerformRemap);
}
void
HttpTransact::PerformRemap(State *s)
{
TxnDebug("http_trans", "Inside PerformRemap");
TRANSACT_RETURN(SM_ACTION_REMAP_REQUEST, HttpTransact::EndRemapRequest);
}
void
HttpTransact::EndRemapRequest(State *s)
{
TxnDebug("http_trans", "START HttpTransact::EndRemapRequest");
HTTPHdr *incoming_request = &s->hdr_info.client_request;
int method = incoming_request->method_get_wksidx();
int host_len;
const char *host = incoming_request->host_get(&host_len);
TxnDebug("http_trans", "EndRemapRequest host is %.*s", host_len, host);
// Setting enable_redirection according to HttpConfig (master or overridable). We
// defer this as late as possible, to allow plugins to modify the overridable
// configurations (e.g. conf_remap.so). We intentionally only modify this if
// the configuration says so.
s->state_machine->enable_redirection = (s->txn_conf->number_of_redirections > 0);
////////////////////////////////////////////////////////////////
// if we got back a URL to redirect to, vector the user there //
////////////////////////////////////////////////////////////////
if (s->remap_redirect != nullptr) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
const char *error_body_type;
switch (s->http_return_code) {
case HTTP_STATUS_MOVED_PERMANENTLY:
case HTTP_STATUS_PERMANENT_REDIRECT:
case HTTP_STATUS_SEE_OTHER:
case HTTP_STATUS_USE_PROXY:
error_body_type = "redirect#moved_permanently";
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
case HTTP_STATUS_TEMPORARY_REDIRECT:
error_body_type = "redirect#moved_temporarily";
break;
default:
if (HTTP_STATUS_NONE == s->http_return_code) {
s->http_return_code = HTTP_STATUS_MOVED_TEMPORARILY;
Warning("Changed status code from '0' to '%d'.", s->http_return_code);
} else {
Warning("Using invalid status code for redirect '%d'. Building a response for a temporary redirect.", s->http_return_code);
}
error_body_type = "redirect#moved_temporarily";
}
build_error_response(s, s->http_return_code, "Redirect", error_body_type);
ats_free(s->remap_redirect);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////
// Quick HTTP filtering (primary key: http method) //
/////////////////////////////////////////////////////
process_quick_http_filter(s, method);
/////////////////////////////////////////////////////////////////////////
// We must close this connection if client_connection_enabled == false //
/////////////////////////////////////////////////////////////////////////
if (!s->client_connection_enabled) {
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied");
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////////////////
// Check if remap plugin set HTTP return code and return body //
/////////////////////////////////////////////////////////////////
if (s->http_return_code != HTTP_STATUS_NONE) {
build_error_response(s, s->http_return_code, nullptr, nullptr);
s->reverse_proxy = false;
goto done;
}
///////////////////////////////////////////////////////////////
// if no mapping was found, handle the cases where: //
// //
// (1) reverse proxy is on, and no URL host (server request) //
// (2) no mappings are found, but mappings strictly required //
///////////////////////////////////////////////////////////////
if (!s->url_remap_success) {
/**
* It's better to test redirect rules just after url_remap failed
* Or those successfully remapped rules might be redirected
**/
if (handleIfRedirect(s)) {
TxnDebug("http_trans", "END HttpTransact::RemapRequest");
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, nullptr);
}
if (!s->http_config_param->url_remap_required && !incoming_request->is_target_in_url()) {
s->hdr_info.client_request.set_url_target_from_host_field();
}
/////////////////////////////////////////////////////////
// check for: (1) reverse proxy is on, and no URL host //
/////////////////////////////////////////////////////////
if (s->http_config_param->reverse_proxy_enabled && !s->client_info.is_transparent && !incoming_request->is_target_in_url()) {
/////////////////////////////////////////////////////////
// the url mapping failed, reverse proxy was enabled,
// and the request contains no host:
//
// * if there is an explanatory redirect, send there.
// * if there was no host, send "no host" error.
// * if there was a host, say "not found".
/////////////////////////////////////////////////////////
char *redirect_url = s->http_config_param->reverse_proxy_no_host_redirect;
int redirect_url_len = s->http_config_param->reverse_proxy_no_host_redirect_len;
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (redirect_url) { /* there is a redirect url */
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect For Explanation", "request#no_host");
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, redirect_url, redirect_url_len);
// socket when there is no host. Need to handle DNS failure elsewhere.
} else if (host == nullptr) { /* no host */
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host");
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
} else {
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found on Accelerator", "urlrouting#no_mapping");
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
}
s->reverse_proxy = false;
goto done;
} else if (s->http_config_param->url_remap_required) {
///////////////////////////////////////////////////////
// the url mapping failed, but mappings are strictly //
// required so return an error message. //
///////////////////////////////////////////////////////
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found", "urlrouting#no_mapping");
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
s->reverse_proxy = false;
goto done;
}
} else {
if (s->http_config_param->reverse_proxy_enabled) {
s->req_flavor = REQ_FLAVOR_REVPROXY;
}
}
s->reverse_proxy = true;
s->server_info.is_transparent = s->state_machine->ua_txn ? s->state_machine->ua_txn->is_outbound_transparent() : false;
done:
// We now set the active-timeout again, since it might have been changed as part of the remap rules.
if (s->state_machine->ua_txn) {
s->state_machine->ua_txn->set_active_timeout(HRTIME_SECONDS(s->txn_conf->transaction_active_timeout_in));
}
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans") || is_debug_tag_set("url_rewrite")) {
TxnDebug("http_trans", "After Remapping:");
obj_describe(s->hdr_info.client_request.m_http, true);
}
// If the client failed ACLs, send error response
// This extra condition was added to separate it from the logic below that might allow
// requests that use some types of plugins as that code was allowing requests that didn't
// pass ACL checks. ACL mismatches are also not counted as invalid client requests
if (!s->client_connection_enabled) {
TxnDebug("http_trans", "END HttpTransact::EndRemapRequest: connection not allowed");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
/*
if s->reverse_proxy == false, we can assume remapping failed in some way
-however-
If an API setup a tunnel to fake the origin or proxy's response we will
continue to handle the request (as this was likely the plugin author's intent)
otherwise, 502/404 the request right now. /eric
*/
if (!s->reverse_proxy && s->state_machine->plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
TxnDebug("http_trans", "END HttpTransact::EndRemapRequest");
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
} else {
s->hdr_info.client_response.destroy(); // release the underlying memory.
s->hdr_info.client_response.clear(); // clear the pointers.
TxnDebug("http_trans", "END HttpTransact::EndRemapRequest");
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::HandleRequest);
}
ink_assert(!"not reached");
}
bool
HttpTransact::handle_upgrade_request(State *s)
{
HTTPHdr &request = s->hdr_info.client_request;
s->method = request.method_get_wksidx();
// Quickest way to determine that this is defintely not an upgrade.
/* RFC 6455 The method of the request MUST be GET, and the HTTP version MUST
be at least 1.1. */
if (!s->hdr_info.client_request.presence(MIME_PRESENCE_UPGRADE) ||
!s->hdr_info.client_request.presence(MIME_PRESENCE_CONNECTION) || s->method != HTTP_WKSIDX_GET ||
s->hdr_info.client_request.version_get() < HTTP_1_1) {
return false;
}
MIMEField *upgrade_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
MIMEField *connection_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
StrList connection_hdr_vals;
const char *upgrade_hdr_val = nullptr;
int upgrade_hdr_val_len = 0;
if (!upgrade_hdr || !connection_hdr || connection_hdr->value_get_comma_list(&connection_hdr_vals) == 0 ||
(upgrade_hdr_val = upgrade_hdr->value_get(&upgrade_hdr_val_len)) == nullptr) {
TxnDebug("http_trans_upgrade", "Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request.");
return false;
}
/*
* In order for this request to be treated as a normal upgrade request we must have a Connection: Upgrade header
* and a Upgrade: header, with a non-empty value, otherwise we just assume it's not an Upgrade Request, after
* we've verified that, we will try to match this upgrade to a known upgrade type such as Websockets.
*/
bool connection_contains_upgrade = false;
// Next, let's validate that the Connection header contains an Upgrade key
for (int i = 0; i < connection_hdr_vals.count; ++i) {
Str *val = connection_hdr_vals.get_idx(i);
if (ptr_len_casecmp(val->str, val->len, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE) == 0) {
connection_contains_upgrade = true;
break;
}
}
if (!connection_contains_upgrade) {
TxnDebug("http_trans_upgrade",
"Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request, missing Connection upgrade header.");
return false;
}
// Mark this request as an upgrade request.
s->is_upgrade_request = true;
/*
RFC 6455
The request MUST contain an |Upgrade| header field whose value
MUST include the "websocket" keyword.
The request MUST contain a |Connection| header field whose value
MUST include the "Upgrade" token. // Checked Above
The request MUST include a header field with the name
|Sec-WebSocket-Key|.
The request MUST include a header field with the name
|Sec-WebSocket-Version|. The value of this header field MUST be
13.
*/
if (hdrtoken_tokenize(upgrade_hdr_val, upgrade_hdr_val_len, &s->upgrade_token_wks) >= 0) {
if (s->upgrade_token_wks == MIME_VALUE_WEBSOCKET) {
MIMEField *sec_websocket_key =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_KEY, MIME_LEN_SEC_WEBSOCKET_KEY);
MIMEField *sec_websocket_ver =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_VERSION, MIME_LEN_SEC_WEBSOCKET_VERSION);
if (sec_websocket_key && sec_websocket_ver && sec_websocket_ver->value_get_int() == 13) {
TxnDebug("http_trans_upgrade", "Transaction wants upgrade to websockets");
handle_websocket_upgrade_pre_remap(s);
return true;
} else {
TxnDebug("http_trans_upgrade", "Unable to upgrade connection to websockets, invalid headers (RFC 6455).");
}
} else if (s->upgrade_token_wks == MIME_VALUE_H2C) {
// We need to recognize h2c to not handle it as an error.
// We just ignore the Upgrade header and respond to the request as though the Upgrade header field were absent.
s->is_upgrade_request = false;
return false;
}
} else {
TxnDebug("http_trans_upgrade", "Transaction requested upgrade for unknown protocol: %s", upgrade_hdr_val);
}
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error");
// we want our modify_request method to just return while we fail out from here.
// this seems like the preferred option because the user wanted to do an upgrade but sent a bad protocol.
TRANSACT_RETURN_VAL(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr, true);
}
void
HttpTransact::handle_websocket_upgrade_pre_remap(State *s)
{
TxnDebug("http_trans_websocket_upgrade_pre_remap", "Prepping transaction before remap.");
/*
* We will use this opportunity to set everything up so that during the remap stage we can deal with
* ws:// and wss:// remap rules, and then we will take over again post remap.
*/
s->is_websocket = true;
s->post_remap_upgrade_return_point = HttpTransact::handle_websocket_upgrade_post_remap;
/* let's modify the url scheme to be wss or ws, so remapping will happen as expected */
URL *url = s->hdr_info.client_request.url_get();
if (url->scheme_get_wksidx() == URL_WKSIDX_HTTP) {
TxnDebug("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WS for remapping.");
url->scheme_set(URL_SCHEME_WS, URL_LEN_WS);
} else if (url->scheme_get_wksidx() == URL_WKSIDX_HTTPS) {
TxnDebug("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WSS for remapping.");
url->scheme_set(URL_SCHEME_WSS, URL_LEN_WSS);
} else {
TxnDebug("http_trans_websocket_upgrade_pre_remap", "Invalid scheme for websocket upgrade");
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
TRANSACT_RETURN(SM_ACTION_API_PRE_REMAP, HttpTransact::PerformRemap);
}
void
HttpTransact::handle_websocket_upgrade_post_remap(State *s)
{
TxnDebug("http_trans_websocket_upgrade_post_remap", "Remap is complete, start websocket upgrade");
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::handle_websocket_connection);
}
void
HttpTransact::handle_websocket_connection(State *s)
{
TxnDebug("http_trans_websocket", "START handle_websocket_connection");
HandleRequest(s);
}
static bool
mimefield_value_equal(MIMEField *field, const char *value, const int value_len)
{
int field_value_len = 0;
const char *field_value = field->value_get(&field_value_len);
if (field_value != nullptr && field_value_len == value_len) {
return !strncasecmp(field_value, value, value_len);
}
return false;
}
void
HttpTransact::ModifyRequest(State *s)
{
int scheme, hostname_len;
HTTPHdr &request = s->hdr_info.client_request;
static const int PORT_PADDING = 8;
TxnDebug("http_trans", "START HttpTransact::ModifyRequest");
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &request);
////////////////////////////////////////////////
// If there is no scheme, default to http //
////////////////////////////////////////////////
URL *url = request.url_get();
s->orig_scheme = (scheme = url->scheme_get_wksidx());
s->method = request.method_get_wksidx();
if (scheme < 0 && s->method != HTTP_WKSIDX_CONNECT) {
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
url->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
s->orig_scheme = URL_WKSIDX_HTTPS;
} else {
url->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
s->orig_scheme = URL_WKSIDX_HTTP;
}
}
if (s->method == HTTP_WKSIDX_CONNECT && !request.is_port_in_header()) {
url->port_set(80);
}
// Ugly - this must come after the call to url->scheme_set or
// it can't get the scheme properly and the wrong data is cached.
// The solution should be to move the scheme detecting logic in to
// the header class, rather than doing it in a random bit of
// external code.
const char *buf = request.host_get(&hostname_len);
if (!request.is_target_in_url()) {
s->hdr_info.client_req_is_server_style = true;
}
// Copy out buf to a hostname just in case its heap header memory is freed during coalescing
// due to later HdrHeap operations
char *hostname = static_cast<char *>(alloca(hostname_len + PORT_PADDING));
memcpy(hostname, buf, hostname_len);
// Make clang analyzer happy. hostname is non-null iff request.is_target_in_url().
ink_assert(hostname || s->hdr_info.client_req_is_server_style);
// If the incoming request is proxy-style make sure the Host: header
// matches the incoming request URL. The exception is if we have
// Max-Forwards set to 0 in the request
int max_forwards = -1; // -1 is a valid value meaning that it didn't find the header
if (request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
max_forwards = request.get_max_forwards();
}
if ((max_forwards != 0) && !s->hdr_info.client_req_is_server_style && s->method != HTTP_WKSIDX_CONNECT) {
MIMEField *host_field = request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
in_port_t port = url->port_get_raw();
// Form the host:port string if not a default port (e.g. 80)
// We allocated extra space for the port above
if (port > 0) {
hostname_len += snprintf(hostname + hostname_len, PORT_PADDING, ":%u", port);
}
// No host_field means not equal to host and will need to be set, so create it now.
if (!host_field) {
host_field = request.field_create(MIME_FIELD_HOST, MIME_LEN_HOST);
request.field_attach(host_field);
}
if (mimefield_value_equal(host_field, hostname, hostname_len) == false) {
request.field_value_set(host_field, hostname, hostname_len);
request.mark_target_dirty();
}
}
TxnDebug("http_trans", "END HttpTransact::ModifyRequest");
TRANSACT_RETURN(SM_ACTION_API_READ_REQUEST_HDR, HttpTransact::StartRemapRequest);
}
// This function is supposed to figure out if this transaction is
// susceptible to a redirection as specified by remap.config
bool
HttpTransact::handleIfRedirect(State *s)
{
int answer;
URL redirect_url;
answer = request_url_remap_redirect(&s->hdr_info.client_request, &redirect_url, s->state_machine->m_remap);
if ((answer == PERMANENT_REDIRECT) || (answer == TEMPORARY_REDIRECT)) {
int remap_redirect_len;
s->remap_redirect = redirect_url.string_get(&s->arena, &remap_redirect_len);
redirect_url.destroy();
if (answer == TEMPORARY_REDIRECT) {
if ((s->client_info).http_version == HTTP_1_1) {
build_error_response(s, HTTP_STATUS_TEMPORARY_REDIRECT, "Redirect", "redirect#moved_temporarily");
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily");
}
} else {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently");
}
s->arena.str_free(s->remap_redirect);
s->remap_redirect = nullptr;
return true;
}
return false;
}
void
HttpTransact::HandleRequest(State *s)
{
TxnDebug("http_trans", "START HttpTransact::HandleRequest");
if (!s->state_machine->is_waiting_for_full_body && !s->state_machine->is_using_post_buffer) {
ink_assert(!s->hdr_info.server_request.valid());
HTTP_INCREMENT_DYN_STAT(http_incoming_requests_stat);
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
HTTP_INCREMENT_DYN_STAT(https_incoming_requests_stat);
}
///////////////////////////////////////////////
// if request is bad, return error response //
///////////////////////////////////////////////
if (!(is_request_valid(s, &s->hdr_info.client_request))) {
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
TxnDebug("http_seq", "request invalid.");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
return;
}
TxnDebug("http_seq", "request valid.");
if (is_debug_tag_set("http_chdr_describe")) {
obj_describe(s->hdr_info.client_request.m_http, true);
}
// at this point we are guaranteed that the request is good and acceptable.
// initialize some state variables from the request (client version,
// client keep-alive, cache action, etc.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
// The following chunk of code will limit the maximum number of websocket connections (TS-3659)
if (s->is_upgrade_request && s->is_websocket && s->http_config_param->max_websocket_connections >= 0) {
int64_t val = 0;
HTTP_READ_DYN_SUM(http_websocket_current_active_client_connections_stat, val);
if (val >= s->http_config_param->max_websocket_connections) {
s->is_websocket = false; // unset to avoid screwing up stats.
TxnDebug("http_trans", "Rejecting websocket connection because the limit has been exceeded");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_SERVICE_UNAVAILABLE, "WebSocket Connection Limit Exceeded", nullptr);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
}
// The following code is configurable to allow a user to control the max post size (TS-3631)
if (s->http_config_param->max_post_size > 0 && s->hdr_info.request_content_length > 0 &&
s->hdr_info.request_content_length > s->http_config_param->max_post_size) {
TxnDebug("http_trans", "Max post size %" PRId64 " Client tried to post a body that was too large.",
s->http_config_param->max_post_size);
HTTP_INCREMENT_DYN_STAT(http_post_body_too_large);
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large", "request#entity_too_large");
s->squid_codes.log_code = SQUID_LOG_ERR_POST_ENTITY_TOO_LARGE;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
// The following chunk of code allows you to disallow post w/ expect 100-continue (TS-3459)
if (s->hdr_info.request_content_length && s->http_config_param->disallow_post_100_continue) {
MIMEField *expect = s->hdr_info.client_request.field_find(MIME_FIELD_EXPECT, MIME_LEN_EXPECT);
if (expect != nullptr) {
const char *expect_hdr_val = nullptr;
int expect_hdr_val_len = 0;
expect_hdr_val = expect->value_get(&expect_hdr_val_len);
if (ptr_len_casecmp(expect_hdr_val, expect_hdr_val_len, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0) {
// Let's error out this request.
TxnDebug("http_trans", "Client sent a post expect: 100-continue, sending 405.");
HTTP_INCREMENT_DYN_STAT(disallowed_post_100_continue);
build_error_response(s, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method Not Allowed", "request#method_unsupported");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
}
}
if (s->txn_conf->request_buffer_enabled &&
s->state_machine->ua_txn->has_request_body(s->hdr_info.request_content_length,
s->client_info.transfer_encoding == CHUNKED_ENCODING)) {
TRANSACT_RETURN(SM_ACTION_WAIT_FOR_FULL_BODY, nullptr);
}
}
// Cache lookup or not will be decided later at DecideCacheLookup().
// Before it's decided to do a cache lookup,
// assume no cache lookup and using proxy (not tunneling)
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
// initialize the cache_control structure read from cache.config
update_cache_control_information_from_config(s);
// We still need to decide whether or not to do a cache lookup since
// the scheduled update code depends on this info.
if (is_request_cache_lookupable(s)) {
s->cache_info.action = CACHE_DO_LOOKUP;
}
// If the hostname is "$internal$" then this is a request for
// internal proxy information.
if (handle_internal_request(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_REQUEST, nullptr);
}
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_INTERCEPT) {
setup_plugin_request_intercept(s);
return;
}
// if ip in url or cop test page, not do srv lookup.
if (s->txn_conf->srv_enabled) {
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
s->my_txn_conf().srv_enabled = !ats_is_ip(&addr);
}
// if the request is a trace or options request, decrement the
// max-forwards value. if the incoming max-forwards value was 0,
// then we have to return a response to the client with the
// appropriate action for trace/option. in this case this routine
// is responsible for building the response.
if (handle_trace_and_options_requests(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, nullptr);
}
if (s->http_config_param->no_dns_forward_to_parent && s->scheme != URL_WKSIDX_HTTPS &&
strcmp(s->server_info.name, "127.0.0.1") != 0) {
// for HTTPS requests, we must go directly to the
// origin server. Ignore the no_dns_just_forward_to_parent setting.
// we need to see if the hostname is an
// ip address since the parent selection code result
// could change as a result of this ip address
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
if (ats_is_ip(&addr)) {
ats_ip_copy(&s->request_data.dest_ip, &addr);
}
if (parentExists(s)) {
// If the proxy is behind and firewall and there is no
// DNS service available, we just want to forward the request
// the parent proxy. In this case, we never find out the
// origin server's ip. So just skip past OSDNS
ats_ip_invalidate(&s->server_info.dst_addr);
StartAccessControl(s);
return;
} else if (s->http_config_param->no_origin_server_dns) {
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect#failed_connect");
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
}
// Added to skip the dns if the document is in the cache.
// DNS is requested before cache lookup only if there are rules in cache.config , parent.config or
// if the newly added variable doc_in_cache_skip_dns is not enabled
if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' &&
(!s->state_machine->enable_redirection || !s->redirect_info.redirect_in_process) &&
s->parent_params->parent_table->hostMatch) {
s->force_dns = true;
}
/* A redirect means we need to check some things again.
If the cache is enabled then we need to check the new (redirected) request against the cache.
If not, then we need to at least do DNS again to guarantee we are using the correct IP address
(if the host changed). Note DNS comes after cache lookup so in both cases we do the DNS.
*/
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->txn_conf->cache_http) {
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, nullptr);
} else {
return CallOSDNSLookup(s);
}
}
if (s->force_dns) {
return CallOSDNSLookup(s);
} else {
// After the requested is properly handled No need of requesting the DNS directly check the ACLs
// if the request is authorized
StartAccessControl(s);
}
}
void
HttpTransact::HandleRequestBufferDone(State *s)
{
TRANSACT_RETURN(SM_ACTION_REQUEST_BUFFER_READ_COMPLETE, HttpTransact::HandleRequest);
}
void
HttpTransact::setup_plugin_request_intercept(State *s)
{
ink_assert(s->state_machine->plugin_tunnel != nullptr);
// Plugin is intercepting the request which means
// that we don't do dns, cache read or cache write
//
// We just want to write the request straight to the plugin
if (s->cache_info.action != HttpTransact::CACHE_DO_NO_ACTION) {
s->cache_info.action = HttpTransact::CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
// Regardless of the protocol we're gatewaying to
// we see the scheme as http
s->scheme = s->next_hop_scheme = URL_WKSIDX_HTTP;
// Set up a "fake" server entry
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, 0);
// Also "fake" the info we'd normally get from
// hostDB
s->server_info.http_version = HTTP_1_0;
s->server_info.keep_alive = HTTP_NO_KEEPALIVE;
s->host_db_info.app.http_data.http_version = HTTP_1_0;
s->server_info.dst_addr.setToAnyAddr(AF_INET); // must set an address or we can't set the port.
s->server_info.dst_addr.network_order_port() = htons(s->hdr_info.client_request.port_get()); // this is the info that matters.
// Build the request to the server
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->client_info.http_version);
// We don't do keep alive over these impersonated
// NetVCs so nuke the connection header
s->hdr_info.server_request.field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_OPEN, nullptr);
}
////////////////////////////////////////////////////////////////////////
// void HttpTransact::HandleApiErrorJump(State* s)
//
// Called after an API function indicates it wished to send an
// error to the user agent
////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleApiErrorJump(State *s)
{
TxnDebug("http_trans", "Entering HttpTransact::HandleApiErrorJump");
// since the READ_REQUEST_HDR_HOOK is processed before
// we examine the request, returning TS_EVENT_ERROR will cause
// the protocol in the via string to be "?" Set it here
// since we know it has to be http
// For CONNECT method, next_hop_scheme is NULL
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// The client response may not be empty in the
// case the txn was reenabled in error by a plugin from hook SEND_RESPONSE_HDR.
// build_response doesn't clean the header. So clean it up before.
// Do fields_clear() instead of clear() to prevent memory leak
if (s->hdr_info.client_response.valid()) {
s->hdr_info.client_response.fields_clear();
}
// Set the source to internal so chunking is handled correctly
s->source = SOURCE_INTERNAL;
/**
The API indicated an error. Lets use a >=400 error from the state (if one's set) or fallback to a
generic HTTP/1.X 500 INKApi Error
**/
if (s->http_return_code && s->http_return_code >= HTTP_STATUS_BAD_REQUEST) {
const char *reason = http_hdr_reason_lookup(s->http_return_code);
;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, s->http_return_code, reason ? reason : "Error");
} else {
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_INTERNAL_SERVER_ERROR, "INKApi Error");
}
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, nullptr);
return;
}
// PPDNSLookupAPICall does an API callout if a plugin set the response_action,
// then calls PPDNSLookup.
// This is to preserve plugin hook calling behavior pre-9, which didn't call
// the TS_HTTP_OS_DNS_HOOK on PPDNSLookup.
// Since response_action is new in 9, only new plugins intentionally setting
// it will have the new behavior of TS_HTTP_OS_DNS_HOOK firing on PPDNSLookup.
void
HttpTransact::PPDNSLookupAPICall(State *s)
{
TxnDebug("http_trans", "response_action.handled %d", s->response_action.handled);
if (!s->response_action.handled) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, PPDNSLookup);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : PPDNSLookup
// Description: called after DNS lookup of parent proxy name
//
// Details :
//
// the configuration information gave us the name of the parent proxy
// to send the request to. this function is called after the dns lookup
// for that name. it may fail, in which case we look for the next parent
// proxy to try and if none exist, then go to the origin server.
// if the lookup succeeds, we open a connection to the parent proxy.
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::PPDNSLookup(State *s)
{
TxnDebug("http_trans", "Entering HttpTransact::PPDNSLookup");
ink_assert(s->dns_info.looking_up == PARENT_PROXY);
if (!s->dns_info.lookup_success) {
// Mark parent as down due to resolving failure
markParentDown(s);
// DNS lookup of parent failed, find next parent or o.s.
if (find_server_and_update_current_info(s) == HttpTransact::HOST_NONE) {
ink_assert(s->current.request_to == HOST_NONE);
handle_parent_died(s);
return;
}
if (!s->current.server->dst_addr.isValid()) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookupAPICall);
} else if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 1) {
// We ran out of parents but parent configuration allows us to go to Origin Server directly
CallOSDNSLookup(s);
return;
} else {
// We could be out of parents here if all the parents failed DNS lookup
ink_assert(s->current.request_to == HOST_NONE);
handle_parent_died(s);
}
return;
}
} else {
// lookup succeeded, open connection to p.p.
ats_ip_copy(&s->parent_info.dst_addr, s->host_db_info.ip());
s->parent_info.dst_addr.network_order_port() = htons(s->parent_result.port);
get_ka_info_from_host_db(s, &s->parent_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "DNS lookup for successful IP: %s", ats_ip_ntop(&s->parent_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
// Since this function can be called several times while retrying
// parents, check to see if we've already built our request
if (!s->hdr_info.server_request.valid()) {
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
// Take care of deferred (issue revalidate) work in building
// the request
if (s->pending_work != nullptr) {
ink_assert(s->pending_work == issue_revalidate);
(*s->pending_work)(s);
s->pending_work = nullptr;
}
}
// what kind of a connection (raw, simple)
s->next_action = how_to_open_connection(s);
}
///////////////////////////////////////////////////////////////////////////////
//
// Name : ReDNSRoundRobin
// Description: Called after we fail to contact part of a round-robin
// robin server set and we found a another ip address.
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::ReDNSRoundRobin(State *s)
{
ink_assert(s->current.server == &s->server_info);
ink_assert(s->current.server->had_connect_fail());
if (s->dns_info.lookup_success) {
// We using a new server now so clear the connection
// failure mark
s->current.server->clear_connect_fail();
// Our ReDNS of the server succeeded so update the necessary
// information and try again. Need to preserve the current port value if possible.
in_port_t server_port = s->current.server->dst_addr.host_order_port();
// Temporary check to make sure the port preservation can be depended upon. That should be the case
// because we get here only after trying a connection. Remove for 6.2.
ink_assert(s->current.server->dst_addr.isValid() && 0 != server_port);
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
s->server_info.dst_addr.network_order_port() = htons(server_port);
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "DNS lookup for O.S. successful IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
s->next_action = how_to_open_connection(s);
} else {
// Our ReDNS failed so output the DNS failure error message
// Set to internal server error so later logging will pick up SQUID_LOG_ERR_DNS_FAIL
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Cannot find server.", Dns_error_body);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = PROXY_INTERNAL_CACHE_NOOP;
char *url_str = s->hdr_info.client_request.url_string_get(&s->arena, nullptr);
ts::bwprint(error_bw_buffer, "DNS Error: looking up {}", ts::bwf::FirstOf(url_str, "<none>"));
Log::error("%s", error_bw_buffer.c_str());
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OSDNSLookup
// Description: called after the DNS lookup of origin server name
//
// Details :
//
// normally called after Start. may be called more than once, however,
// if the dns lookup fails. this may be because
// it was not possible to resolve the name after several attempts.
//
// the next action depends. since this function is normally called after
// a request has come in, which is valid and does not require an immediate
// response, the next action may just be to open a connection to the
// origin server, or a parent proxy, or the next action may be to do a
// cache lookup, or in the event of an error, the next action may be to
// send a response back to the client.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::CACHE_LOOKUP;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OSDNSLookup(State *s)
{
ink_assert(s->dns_info.looking_up == ORIGIN_SERVER);
TxnDebug("http_trans", "Entering HttpTransact::OSDNSLookup");
// It's never valid to connect *to* INADDR_ANY, so let's reject the request now.
if (ats_is_ip_any(s->host_db_info.ip())) {
TxnDebug("http_trans", "Invalid request IP: INADDR_ANY");
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Bad Destination Address", "request#syntax_error");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
if (!s->dns_info.lookup_success) {
if (DNSLookupInfo::OS_Addr::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
/*
* Transparent case: We tried to connect to client target address, failed and tried to use a different addr
* No HostDB data, just keep on with the CTA.
*/
s->dns_info.lookup_success = true;
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_CLIENT;
TxnDebug("http_seq", "DNS lookup unsuccessful, using client target address");
} else {
TxnDebug("http_seq", "DNS Lookup unsuccessful");
// Even with unsuccessful DNS lookup, return stale object from cache if applicable
if (is_cache_hit(s->cache_lookup_result) && is_stale_cache_response_returnable(s)) {
s->source = SOURCE_CACHE;
TxnDebug("http_trans", "[hscno] serving stale doc to client");
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
return;
}
// output the DNS failure error message
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// Set to internal server error so later logging will pick up SQUID_LOG_ERR_DNS_FAIL
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Cannot find server.", "connect#dns_failed");
char *url_str = s->hdr_info.client_request.url_string_get(&s->arena, nullptr);
ts::bwprint(error_bw_buffer, "DNS Error: looking up {}", ts::bwf::FirstOf(url_str, "<none>"));
Log::error("%s", error_bw_buffer.c_str());
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
return;
}
// The dns lookup succeeded
ink_assert(s->dns_info.lookup_success);
TxnDebug("http_seq", "DNS Lookup successful");
// For the transparent case, nail down the kind of address we are really using
if (DNSLookupInfo::OS_Addr::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
// We've backed off from a client supplied address and found some
// HostDB addresses. We use those if they're different from the CTA.
// In all cases we now commit to client or HostDB for our source.
if (s->host_db_info.round_robin) {
HostDBInfo *cta = s->host_db_info.rr()->select_next(&s->current.server->dst_addr.sa);
if (cta) {
// found another addr, lock in host DB.
s->host_db_info = *cta;
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_HOSTDB;
} else {
// nothing else there, continue with CTA.
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_CLIENT;
}
} else if (ats_ip_addr_eq(s->host_db_info.ip(), &s->server_info.dst_addr.sa)) {
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_CLIENT;
} else {
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_HOSTDB;
}
}
// Check to see if can fullfill expect requests based on the cached
// update some state variables with hostdb information that has
// been provided.
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
// If the SRV response has a port number, we should honor it. Otherwise we do the port defined in remap
if (s->dns_info.srv_lookup_success) {
s->server_info.dst_addr.network_order_port() = htons(s->dns_info.srv_port);
} else if (!s->api_server_addr_set) {
s->server_info.dst_addr.network_order_port() = htons(s->hdr_info.client_request.port_get()); // now we can set the port.
}
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "DNS lookup for O.S. successful IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
if (s->redirect_info.redirect_in_process) {
// If dns lookup was not successful, the code below will handle the error.
RedirectEnabled::Action action = RedirectEnabled::Action::INVALID;
if (true == Machine::instance()->is_self(s->host_db_info.ip())) {
action = s->http_config_param->redirect_actions_self_action;
} else {
// Make sure the return value from contains is big enough for a void*.
intptr_t x{intptr_t(RedirectEnabled::Action::INVALID)};
ink_release_assert(s->http_config_param->redirect_actions_map != nullptr);
ink_release_assert(s->http_config_param->redirect_actions_map->contains(s->host_db_info.ip(), reinterpret_cast<void **>(&x)));
action = static_cast<RedirectEnabled::Action>(x);
}
if (action == RedirectEnabled::Action::FOLLOW) {
TxnDebug("http_trans", "Invalid redirect address. Following");
} else if (action == RedirectEnabled::Action::REJECT || s->hdr_info.server_response.valid() == false) {
if (action == RedirectEnabled::Action::REJECT) {
TxnDebug("http_trans", "Invalid redirect address. Rejecting.");
} else {
// Invalid server response, since we can't copy it we are going to reject
TxnDebug("http_trans", "Invalid server response. Rejecting.");
Error("Invalid server response. Rejecting. IP: %s", ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
build_error_response(s, HTTP_STATUS_FORBIDDEN, nullptr, "request#syntax_error");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
} else {
// Return this 3xx to the client as-is
if (action == RedirectEnabled::Action::RETURN) {
TxnDebug("http_trans", "Configured to return on invalid redirect address.");
} else {
TxnDebug("http_trans", "Invalid redirect address. Returning.");
}
build_response_copy(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, nullptr);
}
}
// everything succeeded with the DNS lookup so do an API callout
// that allows for filtering. We'll do traffic_server internal
// filtering after API filtering
// After SM_ACTION_DNS_LOOKUP, goto the saved action/state ORIGIN_SERVER_(RAW_)OPEN.
// Should we skip the StartAccessControl()? why?
if (DNSLookupInfo::OS_Addr::OS_ADDR_USE_CLIENT == s->dns_info.os_addr_style ||
DNSLookupInfo::OS_Addr::OS_ADDR_USE_HOSTDB == s->dns_info.os_addr_style) {
// we've come back after already trying the server to get a better address
// and finished with all backtracking - return to trying the server.
TRANSACT_RETURN(how_to_open_connection(s), HttpTransact::HandleResponse);
} else if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' && s->parent_params->parent_table->hostMatch &&
!s->http_config_param->no_dns_forward_to_parent) {
// note, broken logic: ACC fudges the OR stmt to always be true,
// 'AuthHttpAdapter' should do the rev-dns if needed, not here .
TRANSACT_RETURN(SM_ACTION_DNS_REVERSE_LOOKUP, HttpTransact::StartAccessControl);
} else {
if (s->force_dns) {
StartAccessControl(s); // If skip_dns is enabled and no ip based rules in cache.config and parent.config
// Access Control is called after DNS response
} else {
if ((s->cache_info.action == CACHE_DO_NO_ACTION) &&
(((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
s->range_setup == RANGE_NOT_SATISFIABLE || s->range_setup == RANGE_NOT_HANDLED))) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
} else if (!s->txn_conf->cache_http || s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_SKIPPED) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, LookupSkipOpenServer);
// DNS Lookup is done after LOOKUP Skipped and after we get response
// from the DNS we need to call LookupSkipOpenServer
} else if (is_cache_hit(s->cache_lookup_result)) {
// DNS lookup is done if the content is state need to call handle cache open read hit
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadHit);
} else if (s->cache_lookup_result == CACHE_LOOKUP_MISS || s->cache_info.action == CACHE_DO_NO_ACTION) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
// DNS lookup is done if the lookup failed and need to call Handle Cache Open Read Miss
} else if (s->cache_info.action == CACHE_PREPARE_TO_WRITE && s->http_config_param->cache_post_method == 1 &&
s->method == HTTP_WKSIDX_POST) {
// By virtue of being here, we are intending to forward the request on
// to the server. If we marked this as CACHE_PREPARE_TO_WRITE and this
// is a POST request whose response we intend to write, then we have to
// proceed from here by calling the function that handles this as a
// miss.
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
} else {
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Invalid Cache Lookup result", "default");
Log::error("HTTP: Invalid CACHE LOOKUP RESULT : %d", s->cache_lookup_result);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
}
}
}
void
HttpTransact::StartAccessControl(State *s)
{
HandleRequestAuthorized(s);
}
void
HttpTransact::HandleRequestAuthorized(State *s)
{
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HttpTransact::DecideCacheLookup);
} else {
HttpTransact::DecideCacheLookup(s);
}
}
void
HttpTransact::DecideCacheLookup(State *s)
{
// Check if a client request is lookupable.
if (s->redirect_info.redirect_in_process) {
// for redirect, we want to skip cache lookup and write into
// the cache directly with the URL before the redirect
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
} else {
if (is_request_cache_lookupable(s) && !s->is_upgrade_request) {
s->cache_info.action = CACHE_DO_LOOKUP;
s->current.mode = GENERIC_PROXY;
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
}
// at this point the request is ready to continue down the
// traffic server path.
// now decide whether the cache can even be looked up.
if (s->cache_info.action == CACHE_DO_LOOKUP) {
TxnDebug("http_trans", "Will do cache lookup.");
TxnDebug("http_seq", "Will do cache lookup");
ink_assert(s->current.mode != TUNNELLING_PROXY);
if (s->cache_info.lookup_url == nullptr) {
HTTPHdr *incoming_request = &s->hdr_info.client_request;
if (s->txn_conf->maintain_pristine_host_hdr) {
s->cache_info.lookup_url_storage.create(nullptr);
s->cache_info.lookup_url_storage.copy(incoming_request->url_get());
s->cache_info.lookup_url = &s->cache_info.lookup_url_storage;
// if the target isn't in the URL, put it in the copy for
// cache lookup.
incoming_request->set_url_target_from_host_field(s->cache_info.lookup_url);
} else {
// make sure the target is in the URL.
incoming_request->set_url_target_from_host_field();
s->cache_info.lookup_url = incoming_request->url_get();
}
// *somebody* wants us to not hack the host header in a reverse proxy setup.
// In addition, they want us to reverse proxy for 6000 servers, which vary
// the stupid content on the Host header!!!!
// We could a) have 6000 alts (barf, puke, vomit) or b) use the original
// host header in the url before doing all cache actions (lookups, writes, etc.)
if (s->txn_conf->maintain_pristine_host_hdr) {
const char *host_hdr;
const char *port_hdr;
int host_len, port_len;
// So, the host header will have the original host header.
if (incoming_request->get_host_port_values(&host_hdr, &host_len, &port_hdr, &port_len)) {
int port = 0;
if (port_hdr) {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
port = ink_atoi(port_hdr, port_len);
} else {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
}
s->cache_info.lookup_url->port_set(port);
}
}
ink_assert(s->cache_info.lookup_url->valid() == true);
}
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, nullptr);
} else {
ink_assert(s->cache_info.action != CACHE_DO_LOOKUP && s->cache_info.action != CACHE_DO_SERVE);
TxnDebug("http_trans", "Will NOT do cache lookup.");
TxnDebug("http_seq", "Will NOT do cache lookup");
// If this is a push request, we need send an error because
// since what ever was sent is not cacheable
if (s->method == HTTP_WKSIDX_PUSH) {
HandlePushError(s, "Request Not Cacheable");
return;
}
// for redirect, we skipped cache lookup to do the automatic redirection
if (s->redirect_info.redirect_in_process) {
// without calling out the CACHE_LOOKUP_COMPLETE_HOOK
if (s->txn_conf->cache_http) {
if (s->cache_info.write_lock_state == CACHE_WL_FAIL) {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
s->cache_info.write_lock_state = HttpTransact::CACHE_WL_INIT;
} else if (s->cache_info.write_lock_state == CACHE_WL_SUCCESS) {
s->cache_info.action = CACHE_DO_WRITE;
}
}
LookupSkipOpenServer(s);
} else {
// calling out CACHE_LOOKUP_COMPLETE_HOOK even when the cache
// lookup is skipped
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_SKIPPED;
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, LookupSkipOpenServer);
} else {
// Returning to dns lookup as cache lookup is skipped
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, CallOSDNSLookup);
}
}
}
return;
}
void
HttpTransact::LookupSkipOpenServer(State *s)
{
// cache will not be looked up. open a connection
// to a parent proxy or to the origin server.
find_server_and_update_current_info(s);
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookupAPICall);
} else if (s->parent_result.result == PARENT_FAIL) {
handle_parent_died(s);
return;
}
ink_assert(s->current.request_to == ORIGIN_SERVER);
// ink_assert(s->current.server->ip != 0);
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
StateMachineAction_t next = how_to_open_connection(s);
s->next_action = next;
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
TRANSACT_RETURN(next, HttpTransact::HandleResponse);
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadPush
// Description:
//
// Details :
//
// Called on PUSH requests from HandleCacheOpenRead
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadPush(State *s, bool read_successful)
{
if (read_successful) {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
TRANSACT_RETURN(SM_ACTION_READ_PUSH_HDR, HandlePushResponseHdr);
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushResponseHdr
// Description:
//
// Details :
//
// Called after reading the response header on PUSH request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushResponseHdr(State *s)
{
// Verify the pushed header wasn't longer than the content length
int64_t body_bytes = s->hdr_info.request_content_length - s->state_machine->pushed_response_hdr_bytes;
if (body_bytes < 0) {
HandlePushError(s, "Bad Content Length");
return;
}
// We need to create the request header storing in the cache
s->hdr_info.server_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.server_request.copy(&s->hdr_info.client_request);
s->hdr_info.server_request.method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
s->hdr_info.server_request.value_set("X-Inktomi-Source", 16, "http PUSH", 9);
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Pushed Response Header");
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Generated Request Header");
s->response_received_time = s->request_sent_time = ink_local_time();
if (is_response_cacheable(s, &s->hdr_info.server_request, &s->hdr_info.server_response)) {
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_WRITE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE);
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE, HandlePushCacheWrite);
} else {
HandlePushError(s, "Response Not Cacheable");
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushCacheWrite
// Description:
//
// Details :
//
// Called after performing the cache write on a push request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushCacheWrite(State *s)
{
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
if (s->cache_info.action == CACHE_PREPARE_TO_WRITE) {
s->cache_info.action = CACHE_DO_WRITE;
} else if (s->cache_info.action == CACHE_PREPARE_TO_UPDATE) {
s->cache_info.action = CACHE_DO_REPLACE;
} else {
ink_release_assert(0);
}
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
TRANSACT_RETURN(SM_ACTION_STORE_PUSH_BODY, nullptr);
break;
case CACHE_WL_FAIL:
case CACHE_WL_READ_RETRY:
// No write lock, can not complete request so bail
HandlePushError(s, "Cache Write Failed");
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
}
}
void
HttpTransact::HandlePushTunnelSuccess(State *s)
{
ink_assert(s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_REPLACE);
// FIX ME: check PUSH spec for status codes
HTTPStatus resp_status = (s->cache_info.action == CACHE_DO_WRITE) ? HTTP_STATUS_CREATED : HTTP_STATUS_OK;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, resp_status);
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, nullptr);
}
void
HttpTransact::HandlePushTunnelFailure(State *s)
{
HandlePushError(s, "Cache Error");
}
void
HttpTransact::HandleBadPushRespHdr(State *s)
{
HandlePushError(s, "Malformed Pushed Response Header");
}
void
HttpTransact::HandlePushError(State *s, const char *reason)
{
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
// Set half close flag to prevent TCP
// reset from the body still being transferred
s->state_machine->set_ua_half_close_flag();
build_error_response(s, HTTP_STATUS_BAD_REQUEST, reason, "default");
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenRead
// Description: the cache lookup succeeded - may have been a hit or a miss
//
// Details :
//
// the cache lookup succeeded. first check if the lookup resulted in
// a hit or a miss, if the lookup was for an http request.
// This function just funnels the result into the appropriate
// functions which handle these different cases.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenRead(State *s)
{
TxnDebug("http_trans", "[HttpTransact::HandleCacheOpenRead]");
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
bool read_successful = true;
if (s->cache_info.object_read == nullptr) {
read_successful = false;
//
// If somebody else was writing the document, proceed just like it was
// a normal cache miss, except don't try to write to the cache
//
if (s->cache_lookup_result == CACHE_LOOKUP_DOC_BUSY) {
s->cache_lookup_result = CACHE_LOOKUP_MISS;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
} else {
CacheHTTPInfo *obj = s->cache_info.object_read;
if (obj->response_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
if (obj->request_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
}
if (s->method == HTTP_WKSIDX_PUSH) {
HandleCacheOpenReadPush(s, read_successful);
} else if (read_successful == false) {
// cache miss
TxnDebug("http_trans", "CacheOpenRead -- miss");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
// Perform DNS for the origin when it is required.
// 1. If parent configuration does not allow to go to origin there is no need of performing DNS
// 2. If parent satisfies the request there is no need to go to origin to perform DNS
HandleCacheOpenReadMiss(s);
} else {
// cache hit
TxnDebug("http_trans", "CacheOpenRead -- hit");
TRANSACT_RETURN(SM_ACTION_API_READ_CACHE_HDR, HandleCacheOpenReadHitFreshness);
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : issue_revalidate
// Description: Sets cache action and does various bookkeeping
//
// Details :
//
// The Cache Lookup was hit but the document was stale so after
// calling build_request, we need setup up the cache action,
// set the via code, and possibly conditionalize the request
// The paths that we take to get this code are:
// Directly from HandleOpenReadHit if we are going to the origin server
// After PPDNS if we are going to a parent proxy
//
//
// Possible Next States From Here:
// -
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::issue_revalidate(State *s)
{
HTTPHdr *c_resp = find_appropriate_cached_resp(s);
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_STALE);
ink_assert(GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) != ' ');
if (s->www_auth_content == CACHE_AUTH_FRESH) {
s->hdr_info.server_request.method_set(HTTP_METHOD_HEAD, HTTP_LEN_HEAD);
// The document is fresh in cache and we just want to see if the
// the client has the right credentials
// this cache action is just to get us into the hcoofsr function
s->cache_info.action = CACHE_DO_UPDATE;
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
return;
}
if (s->cache_info.write_lock_state == CACHE_WL_INIT) {
// We do a cache lookup for DELETE, PUT and POST requests as well.
// We must, however, delete the cached copy after forwarding the
// request to the server. is_cache_response_returnable will ensure
// that we forward the request. We now specify what the cache
// action should be when the response is received.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method)) {
s->cache_info.action = CACHE_PREPARE_TO_DELETE;
TxnDebug("http_seq", "cache action: DELETE");
} else {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
TxnDebug("http_seq", "cache action: UPDATE");
}
} else {
// We've looped back around due to missing the write lock
// for the cache. At this point we want to forget about the cache
ink_assert(s->cache_info.write_lock_state == CACHE_WL_READ_RETRY);
s->cache_info.action = CACHE_DO_NO_ACTION;
return;
}
// if the document is cached, just send a conditional request to the server
// So the request does not have preconditions. It can, however
// be a simple GET request with a Pragma:no-cache. As on 8/28/98
// we have fixed the whole Reload/Shift-Reload cached copy
// corruption problem. This means that we can issue a conditional
// request to the server only if the incoming request has a conditional
// or the incoming request does NOT have a no-cache header.
// In other words, if the incoming request is not conditional
// but has a no-cache header we can not issue an IMS. check for
// that case here.
bool no_cache_in_request = false;
if (s->hdr_info.client_request.is_pragma_no_cache_set() || s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
TxnDebug("http_trans", "no-cache header directive in request, folks");
no_cache_in_request = true;
}
if ((!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_MODIFIED_SINCE))) &&
(!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_NONE_MATCH))) && (no_cache_in_request == true) &&
(!s->txn_conf->cache_ims_on_client_no_cache) && (s->www_auth_content == CACHE_AUTH_NONE)) {
TxnDebug("http_trans", "Can not make this a conditional request. This is the force update of the cached copy case");
// set cache action to update. response will be a 200 or error,
// causing cached copy to be replaced (if 200).
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
return;
}
// do not conditionalize if the cached response is not a 200
switch (c_resp->status_get()) {
case HTTP_STATUS_OK: // 200
// don't conditionalize if we are configured to repeat the clients
// conditionals
if (s->txn_conf->cache_when_to_revalidate == 4) {
break;
}
// ok, request is either a conditional or does not have a no-cache.
// (or is method that we don't conditionalize but lookup the
// cache on like DELETE)
if (c_resp->get_last_modified() > 0 &&
(s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD) &&
s->range_setup == RANGE_NONE) {
// make this a conditional request
int length;
const char *str = c_resp->value_get(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED, &length);
if (str) {
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, str, length);
}
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
// if Etag exists, also add if-non-match header
if (c_resp->presence(MIME_PRESENCE_ETAG) && (s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD)) {
int length = 0;
const char *etag = c_resp->value_get(MIME_FIELD_ETAG, MIME_LEN_ETAG, &length);
if (nullptr != etag) {
if ((length >= 2) && (etag[0] == 'W') && (etag[1] == '/')) {
etag += 2;
length -= 2;
}
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, etag, length);
}
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
break;
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: // 203
/* fall through */
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
/* fall through */
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
/* fall through */
case HTTP_STATUS_GONE: // 410
/* fall through */
default:
TxnDebug("http_trans", "cached response is not a 200 response so no conditionalization.");
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
break;
case HTTP_STATUS_PARTIAL_CONTENT:
ink_assert(!"unexpected status code");
break;
}
}
void
HttpTransact::HandleCacheOpenReadHitFreshness(State *s)
{
CacheHTTPInfo *&obj = s->cache_info.object_read;
ink_release_assert((s->request_sent_time == UNDEFINED_TIME) && (s->response_received_time == UNDEFINED_TIME));
TxnDebug("http_seq", "Hit in cache");
if (delete_all_document_alternates_and_return(s, true)) {
TxnDebug("http_trans", "Delete and return");
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE;
return;
}
s->request_sent_time = obj->request_sent_time_get();
s->response_received_time = obj->response_received_time_get();
// There may be clock skew if one of the machines
// went down and we do not have the correct delta
// for it. this is just to deal with the effects
// of the skew by setting minimum and maximum times
// so that ages are not negative, etc.
s->request_sent_time = std::min(s->client_request_time, s->request_sent_time);
s->response_received_time = std::min(s->client_request_time, s->response_received_time);
ink_assert(s->request_sent_time <= s->response_received_time);
TxnDebug("http_trans", "request_sent_time : %" PRId64, (int64_t)s->request_sent_time);
TxnDebug("http_trans", "response_received_time : %" PRId64, (int64_t)s->response_received_time);
// if the plugin has already decided the freshness, we don't need to
// do it again
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_NONE) {
// is the document still fresh enough to be served back to
// the client without revalidation?
Freshness_t freshness = what_is_document_freshness(s, &s->hdr_info.client_request, obj->response_get());
switch (freshness) {
case FRESHNESS_FRESH:
TxnDebug("http_seq", "Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_FRESH;
break;
case FRESHNESS_WARNING:
TxnDebug("http_seq", "Heuristic-based Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_WARNING;
break;
case FRESHNESS_STALE:
TxnDebug("http_seq", "Stale in cache");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_STALE;
break;
default:
ink_assert(!("what_is_document_freshness has returned unsupported code."));
break;
}
}
ink_assert(s->cache_lookup_result != HttpTransact::CACHE_LOOKUP_MISS);
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_HIT_STALE) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_STALE);
}
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);
}
///////////////////////////////////////////////////////////////////////////////
// Name : CallOSDNSLookup
// Description: Moves in SM_ACTION_DNS_LOOKUP state and sets the transact return to OSDNSLookup
//
// Details :
/////////////////////////////////////////////////////////////////////////////
void
HttpTransact::CallOSDNSLookup(State *s)
{
TxnDebug("http", "%s ", s->server_info.name);
HostStatus &pstatus = HostStatus::instance();
HostStatRec *hst = pstatus.getHostStatus(s->server_info.name);
if (hst && hst->status == TSHostStatus::TS_HOST_STATUS_DOWN) {
TxnDebug("http", "%d ", s->cache_lookup_result);
s->current.state = OUTBOUND_CONGESTION;
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH) {
s->cache_info.action = CACHE_DO_SERVE;
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
}
handle_server_connection_not_open(s);
} else {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : need_to_revalidate
// Description: Checks if a document which is in the cache needs to be revalidates
//
// Details : Function calls AuthenticationNeeded and is_cache_response_returnable to determine
// if the cached document can be served
/////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::need_to_revalidate(State *s)
{
bool needs_revalidate, needs_authenticate = false;
bool needs_cache_auth = false;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
if (!obj->valid()) {
return true;
}
} else {
obj = s->cache_info.object_read;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
TxnDebug("http_seq", "Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
TxnDebug("http_seq", "Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
TxnDebug("http_seq", "Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_CACHE_AUTH:
TxnDebug("http_seq", "Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
return true;
break;
}
ink_assert(is_cache_hit(s->cache_lookup_result));
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE &&
s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
needs_revalidate = true;
} else {
needs_revalidate = false;
}
bool send_revalidate = ((needs_authenticate == true) || (needs_revalidate == true) || (is_cache_response_returnable(s) == false));
if (needs_cache_auth == true) {
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
return send_revalidate;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadHit
// Description: handle result of a cache hit
//
// Details :
//
// Cache lookup succeeded and resulted in a cache hit. This means
// that the Accept* and Etags fields also matched. The cache lookup
// may have resulted in a vector of alternates (since lookup may
// be based on a url). A different function (SelectFromAlternates)
// goes through the alternates and finds the best match. That is
// then returned to this function. The result may not be sent back
// to the client, still, if the document is not fresh enough, or
// does not have enough authorization, or if the client wants a
// reload, etc. that decision will be made in this routine.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_DELETE;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SERVE_FROM_CACHE;
// - result of how_to_open_connection()
//
//
// For Range requests, we will decide to do simple tunneling if one of the
// following conditions hold:
// - document stale
// - cached response doesn't have Accept-Ranges and Content-Length
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadHit(State *s)
{
bool needs_revalidate = false;
bool needs_authenticate = false;
bool needs_cache_auth = false;
bool server_up = true;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
if (obj == nullptr || !obj->valid()) {
HandleCacheOpenReadMiss(s);
return;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
TxnDebug("http_seq", "Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
TxnDebug("http_seq", "Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
TxnDebug("http_seq", "Authentication needed");
HandleCacheOpenReadMiss(s);
return;
case AUTHENTICATION_CACHE_AUTH:
TxnDebug("http_seq", "Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
break;
}
ink_assert(is_cache_hit(s->cache_lookup_result));
// We'll request a revalidation under one of these conditions:
//
// 1. Cache lookup is a hit, but the response is stale
// 2. The cached object has a "Cache-Control: no-cache" header
// *and*
// proxy.config.http.cache.ignore_server_no_cache is set to 0 (i.e don't ignore no cache -- the default setting)
//
// But, we only do this if we're not in an API updating the cached object (see TSHttpTxnUpdateCachedObject)
if ((((s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) ||
((obj->response_get()->get_cooked_cc_mask() & MIME_COOKED_MASK_CC_NO_CACHE) && !s->cache_control.ignore_server_no_cache)) &&
(s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE))) {
needs_revalidate = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
}
// the response may not be directly returnable to the client. there
// are several reasons for this: config may force revalidation or
// client may have forced a refresh by sending a Pragma:no-cache
// or a Cache-Control:no-cache, or the client may have sent a
// non-GET/HEAD request for a document that is cached. an example
// of a situation for this is when a client sends a DELETE, PUT
// or POST request for a url that is cached. except for DELETE,
// we may actually want to update the cached copy with the contents
// of the PUT/POST, but the easiest, safest and most robust solution
// is to simply delete the cached copy (in order to maintain cache
// consistency). this is particularly true if the server does not
// accept or conditionally accepts the PUT/POST requests.
// anyhow, this is an overloaded function and will return false
// if the origin server still has to be looked up.
bool response_returnable = is_cache_response_returnable(s);
// do we need to revalidate. in other words if the response
// has to be authorized, is stale or can not be returned, do
// a revalidate.
bool send_revalidate = (needs_authenticate || needs_revalidate || !response_returnable);
if (needs_cache_auth == true) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
TxnDebug("http_trans", "CacheOpenRead --- needs_auth = %d", needs_authenticate);
TxnDebug("http_trans", "CacheOpenRead --- needs_revalidate = %d", needs_revalidate);
TxnDebug("http_trans", "CacheOpenRead --- response_returnable = %d", response_returnable);
TxnDebug("http_trans", "CacheOpenRead --- needs_cache_auth = %d", needs_cache_auth);
TxnDebug("http_trans", "CacheOpenRead --- send_revalidate = %d", send_revalidate);
if (send_revalidate) {
TxnDebug("http_trans", "CacheOpenRead --- HIT-STALE");
TxnDebug("http_seq", "Revalidate document with server");
find_server_and_update_current_info(s);
// We do not want to try to revalidate documents if we think
// the server is down due to the something report problem
//
// Note: we only want to skip origin servers because 1)
// parent proxies have their own negative caching
// scheme & 2) If we skip down parents, every page
// we serve is potentially stale
//
if (s->current.request_to == ORIGIN_SERVER && is_server_negative_cached(s) && response_returnable == true &&
is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, nullptr, UNDEFINED_LOOKUP, 0);
TxnDebug("http_trans", "CacheOpenReadHit - server_down, returning stale document");
}
// a parent lookup could come back as PARENT_FAIL if in parent.config, go_direct == false and
// there are no available parents (all down).
else if (s->current.request_to == HOST_NONE && s->parent_result.result == PARENT_FAIL) {
if (response_returnable == true && is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, nullptr, UNDEFINED_LOOKUP, 0);
TxnDebug("http_trans", "CacheOpenReadHit - server_down, returning stale document");
} else {
handle_parent_died(s);
return;
}
}
if (server_up) {
// set a default version for the outgoing request
HTTPVersion http_version;
if (s->current.server != nullptr) {
bool check_hostdb = get_ka_info_from_config(s, s->current.server);
TxnDebug("http_trans", "CacheOpenReadHit - check_hostdb %d", check_hostdb);
if (check_hostdb || !s->current.server->dst_addr.isValid()) {
// We must be going a PARENT PROXY since so did
// origin server DNS lookup right after state Start
//
// If we end up here in the release case just fall
// through. The request will fail because of the
// missing ip but we won't take down the system
//
if (s->current.request_to == PARENT_PROXY) {
// Set ourselves up to handle pending revalidate issues
// after the PP DNS lookup
ink_assert(s->pending_work == nullptr);
s->pending_work = issue_revalidate;
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookupAPICall);
} else if (s->current.request_to == ORIGIN_SERVER) {
return CallOSDNSLookup(s);
} else {
handle_parent_died(s);
return;
}
}
// override the default version with what the server has
http_version = s->current.server->http_version;
}
TxnDebug("http_trans", "CacheOpenReadHit - version %d.%d", http_version.get_major(), http_version.get_minor());
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, http_version);
issue_revalidate(s);
// this can not be anything but a simple origin server connection.
// in other words, we would not have looked up the cache for a
// connect request, so the next action can not be origin_server_raw_open.
s->next_action = how_to_open_connection(s);
ink_release_assert(s->next_action != SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return;
} else { // server is down but stale response is returnable
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
}
}
// cache hit, document is fresh, does not authorization,
// is valid, etc. etc. send it back to the client.
//
// the important thing to keep in mind is that if we are
// here then we found a match in the cache and the document
// is fresh and we have enough authorization for it to send
// it back to the client without revalidating first with the
// origin server. we are, therefore, allowed to behave as the
// origin server. we can, therefore, make the claim that the
// document has not been modified since or has not been unmodified
// since the time requested by the client. this may not be
// the case in reality, but since the document is fresh in
// the cache, we can make the claim that this is the truth.
//
// so, any decision we make at this point can be made with authority.
// realistically, if we can not make this claim, then there
// is no reason to cache anything.
//
ink_assert((send_revalidate == true && server_up == false) || (send_revalidate == false && server_up == true));
TxnDebug("http_trans", "CacheOpenRead --- HIT-FRESH");
TxnDebug("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Serve from cache");
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
HttpCacheSM &cache_sm = s->state_machine->get_cache_sm();
TxnDebug("http_trans", "CacheOpenRead --- HIT-FRESH read while write %d", cache_sm.is_readwhilewrite_inprogress());
if (cache_sm.is_readwhilewrite_inprogress())
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_RWW_HIT);
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING) {
build_response_from_cache(s, HTTP_WARNING_CODE_HERUISTIC_EXPIRATION);
} else if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) {
ink_assert(server_up == false);
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
build_response_from_cache(s, HTTP_WARNING_CODE_NONE);
}
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
s->saved_update_next_action = s->next_action;
s->saved_update_cache_action = s->cache_info.action;
s->next_action = SM_ACTION_CACHE_PREPARE_UPDATE;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : build_response_from_cache()
// Description: build a client response from cached response and client request
//
// Input : State, warning code to be inserted into the response header
// Output :
//
// Details : This function is called if we decided to serve a client request
// using a cached response.
// It is called by handle_server_connection_not_open()
// and HandleCacheOpenReadHit().
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_response_from_cache(State *s, HTTPWarningCode warning_code)
{
HTTPHdr *client_request = &s->hdr_info.client_request;
HTTPHdr *cached_response = nullptr;
HTTPHdr *to_warn = &s->hdr_info.client_response;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
cached_response = obj->response_get();
// If the client request is conditional, and the cached copy meets
// the conditions, do not need to send back the full document,
// just a NOT_MODIFIED response.
// If the request is not conditional,
// the function match_response_to_request_conditionals() returns
// the code of the cached response, which means that we should send
// back the full document.
HTTPStatus client_response_code =
HttpTransactCache::match_response_to_request_conditionals(client_request, cached_response, s->response_received_time);
switch (client_response_code) {
case HTTP_STATUS_NOT_MODIFIED:
// A IMS or INM GET client request with conditions being met
// by the cached response. Send back a NOT MODIFIED response.
TxnDebug("http_trans", "Not modified");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_CONDITIONAL);
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// A conditional request with conditions not being met by the cached
// response. Send back a PRECONDITION FAILED response.
TxnDebug("http_trans", "Precondition Failed");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONDITIONAL);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// A little misnomer. HTTP_STATUS_RANGE_NOT_SATISFIABLE
// actually means If-Range match fails here.
// fall through
default:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_SERVED);
if (s->method == HTTP_WKSIDX_GET || (s->http_config_param->cache_post_method == 1 && s->method == HTTP_WKSIDX_POST) ||
s->api_resp_cacheable == true) {
// send back the full document to the client.
TxnDebug("http_trans", "Match! Serving full document.");
s->cache_info.action = CACHE_DO_SERVE;
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// only if the cached response is a 200 OK
if (client_response_code == HTTP_STATUS_OK && client_request->presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
if (s->range_setup == RANGE_NOT_SATISFIABLE) {
build_error_response(s, HTTP_STATUS_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable", "default");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
} else if ((s->range_setup == RANGE_NOT_HANDLED) || !s->range_in_cache) {
// we switch to tunneling for Range requests if it is out of order.
// or if the range can't be satisfied from the cache
// In that case we fetch the entire source so it's OK to switch
// this late.
TxnDebug("http_seq", "Out-of-order Range request - tunneling");
s->cache_info.action = CACHE_DO_NO_ACTION;
if (s->force_dns || s->dns_info.lookup_success) {
HandleCacheOpenReadMiss(s); // DNS is already completed no need of doing DNS
} else {
CallOSDNSLookup(s);
}
return;
}
}
if (s->state_machine->do_transform_open()) {
set_header_for_transform(s, cached_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
}
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
// If the client request is a HEAD, then serve the header from cache.
else if (s->method == HTTP_WKSIDX_HEAD) {
TxnDebug("http_trans", "Match! Serving header only.");
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
// We handled the request but it's not GET or HEAD (eg. DELETE),
// and server is not reachable: 502
//
TxnDebug("http_trans", "No match! Connection failed.");
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
warning_code = HTTP_WARNING_CODE_NONE;
}
break;
}
// After building the client response, add the given warning if provided.
if (warning_code != HTTP_WARNING_CODE_NONE) {
delete_warning_value(to_warn, warning_code);
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, warning_code);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_write_lock
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
// - result of how_to_open_connection
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_write_lock(State *s)
{
bool remove_ims = false;
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_DELETE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE ||
s->cache_info.action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
SET_UNPREPARE_CACHE_ACTION(s->cache_info);
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache and proxy only;
// FIX: Should just serve from cache if this is a revalidate
s->cache_info.action = CACHE_DO_NO_ACTION;
switch (s->cache_open_write_fail_action) {
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_STALE_ON_REVALIDATE:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE:
TxnDebug("http_error", "cache_open_write_fail_action %d, cache miss, return error", s->cache_open_write_fail_action);
s->cache_info.write_status = CACHE_WRITE_ERROR;
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect");
MIMEField *ats_field;
HTTPHdr *header;
header = &(s->hdr_info.client_response);
if ((ats_field = header->field_find(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) == nullptr) {
if (likely((ats_field = header->field_create(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) != nullptr)) {
header->field_attach(ats_field);
}
}
if (likely(ats_field)) {
int value = (s->cache_info.object_read) ? 1 : 0;
TxnDebug("http_error", "Adding Ats-Internal-Messages: %d", value);
header->field_value_set_int(ats_field, value);
} else {
TxnDebug("http_error", "failed to add Ats-Internal-Messages");
}
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
default:
s->cache_info.write_status = CACHE_WRITE_LOCK_MISS;
remove_ims = true;
break;
}
break;
case CACHE_WL_READ_RETRY:
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
s->cache_info.action = CACHE_DO_LOOKUP;
if (!s->cache_info.object_read) {
// Write failed and read retry triggered
// Clean up server_request and re-initiate
// Cache Lookup
ink_assert(s->cache_open_write_fail_action == CACHE_WL_FAIL_ACTION_READ_RETRY);
s->cache_info.write_status = CACHE_WRITE_LOCK_MISS;
StateMachineAction_t next;
next = SM_ACTION_CACHE_LOOKUP;
s->next_action = next;
s->hdr_info.server_request.destroy();
TRANSACT_RETURN(next, nullptr);
}
// Write failed but retried and got a vector to read
// We need to clean up our state so that transact does
// not assert later on. Then handle the open read hit
remove_ims = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
break;
}
// Since we've already built the server request and we can't get the write
// lock we need to remove the ims field from the request since we're
// ignoring the cache. If their is a client ims field, copy that since
// we're tunneling response anyway
if (remove_ims) {
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
MIMEField *c_ims = s->hdr_info.client_request.field_find(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
MIMEField *c_inm = s->hdr_info.client_request.field_find(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
if (c_ims) {
int len;
const char *value = c_ims->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, value, len);
}
if (c_inm) {
int len;
const char *value = c_inm->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, value, len);
}
}
if (s->cache_info.write_lock_state == CACHE_WL_READ_RETRY) {
TxnDebug("http_error", "calling hdr_info.server_request.destroy");
s->hdr_info.server_request.destroy();
HandleCacheOpenReadHitFreshness(s);
} else {
StateMachineAction_t next;
next = how_to_open_connection(s);
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
s->next_action = next;
TRANSACT_RETURN(next, nullptr);
} else {
// hehe!
s->next_action = next;
ink_assert(s->next_action == SM_ACTION_DNS_LOOKUP);
return;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadMiss
// Description: cache looked up, miss or hit, but needs authorization
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - result of how_to_open_connection()
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadMiss(State *s)
{
TxnDebug("http_trans", "--- MISS");
TxnDebug("http_seq", "Miss in cache");
if (delete_all_document_alternates_and_return(s, false)) {
TxnDebug("http_trans", "Delete and return");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
return;
}
// reinitialize some variables to reflect cache miss state.
s->cache_info.object_read = nullptr;
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_CACHE_MISS);
if (GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) == ' ') {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
// We do a cache lookup for some non-GET requests as well.
// We must, however, not cache the responses to these requests.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method) && s->api_req_cacheable == false) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if ((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
does_method_effect_cache(s->method) == false || s->range_setup == RANGE_NOT_SATISFIABLE ||
s->range_setup == RANGE_NOT_HANDLED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->api_server_response_no_store) { // plugin may have decided not to cache the response
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
///////////////////////////////////////////////////////////////
// a normal miss would try to fetch the document from the //
// origin server, unless the origin server isn't resolvable, //
// but if "CacheControl: only-if-cached" is set, then we are //
// supposed to send a 504 (GATEWAY TIMEOUT) response. //
///////////////////////////////////////////////////////////////
HTTPHdr *h = &s->hdr_info.client_request;
if (!h->is_cache_control_set(HTTP_VALUE_ONLY_IF_CACHED)) {
// Initialize the server_info structure if we haven't been through DNS
// Otherwise, the http_version will not be initialized
if (!s->current.server || !s->current.server->dst_addr.isValid()) {
// Short term hack. get_ka_info_from_config assumes if http_version is > 0,9 it has already been
// set and skips the rest of the function. The default functor sets it to 1,0
s->server_info.http_version = HTTP_0_9;
get_ka_info_from_config(s, &s->server_info);
}
find_server_and_update_current_info(s);
// a parent lookup could come back as PARENT_FAIL if in parent.config go_direct == false and
// there are no available parents (all down).
if (s->parent_result.result == PARENT_FAIL) {
handle_parent_died(s);
return;
}
if (!s->current.server->dst_addr.isValid()) {
ink_release_assert(s->parent_result.result == PARENT_DIRECT || s->current.request_to == PARENT_PROXY ||
s->http_config_param->no_dns_forward_to_parent != 0);
if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 1) {
return CallOSDNSLookup(s);
}
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, HttpTransact::PPDNSLookupAPICall);
} else {
handle_parent_died(s);
return;
}
}
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
s->current.attempts = 0;
s->next_action = how_to_open_connection(s);
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
} else { // miss, but only-if-cached is set
build_error_response(s, HTTP_STATUS_GATEWAY_TIMEOUT, "Not Cached", "cache#not_in_cache");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OriginServerRawOpen
// Description: called for ssl tunneling
//
// Details :
//
// when the method is CONNECT, we open a raw connection to the origin
// server. if the open succeeds, then do ssl tunneling from the client
// to the host.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SSL_TUNNEL;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OriginServerRawOpen(State *s)
{
TxnDebug("http_trans", "Entering HttpTransact::OriginServerRawOpen");
switch (s->current.state) {
case STATE_UNDEFINED:
/* fall through */
case OPEN_RAW_ERROR:
/* fall through */
case CONNECTION_ERROR:
/* fall through */
case CONNECTION_CLOSED:
/* fall through */
case OUTBOUND_CONGESTION:
/* fall through */
handle_server_died(s);
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case CONNECTION_ALIVE:
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
TxnDebug("http_trans", "connection alive. next action is ssl_tunnel");
s->next_action = SM_ACTION_SSL_TUNNEL;
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleResponse
// Description: called from the state machine when a response is received
//
// Details :
//
// This is the entry into a coin-sorting machine. There are many different
// bins that the response can fall into. First, the response can be invalid
// if for example it is not a response, or not complete, or the connection
// was closed, etc. Then, the response can be from parent proxy or from
// the origin server. The next action to take differs for all three of these
// cases. Finally, good responses can either require a cache action,
// be it deletion, update, or writing or may just need to be tunnelled
// to the client. This latter case should be handled with as little processing
// as possible, since it should represent a fast path.
//
//
// Possible Next States From Here:
//
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleResponse(State *s)
{
TxnDebug("http_trans", "Entering HttpTransact::HandleResponse");
TxnDebug("http_seq", "Response received");
s->source = SOURCE_HTTP_ORIGIN_SERVER;
s->response_received_time = ink_local_time();
ink_assert(s->response_received_time >= s->request_sent_time);
s->current.now = s->response_received_time;
TxnDebug("http_trans", "response_received_time: %" PRId64, (int64_t)s->response_received_time);
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Incoming O.S. Response");
HTTP_INCREMENT_DYN_STAT(http_incoming_responses_stat);
ink_release_assert(s->current.request_to != UNDEFINED_LOOKUP);
if (s->cache_info.action != CACHE_DO_WRITE) {
ink_release_assert(s->cache_info.action != CACHE_DO_LOOKUP);
ink_release_assert(s->cache_info.action != CACHE_DO_SERVE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_DELETE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_UPDATE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_WRITE);
}
if (!HttpTransact::is_response_valid(s, &s->hdr_info.server_response)) {
TxnDebug("http_seq", "Response not valid");
} else {
TxnDebug("http_seq", "Response valid");
initialize_state_variables_from_response(s, &s->hdr_info.server_response);
}
switch (s->current.request_to) {
case PARENT_PROXY:
handle_response_from_parent(s);
break;
case ORIGIN_SERVER:
handle_response_from_server(s);
break;
default:
ink_assert(!("s->current.request_to is not P.P. or O.S. - hmmm."));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleUpdateCachedObject
// Description: called from the state machine when we are going to modify
// headers without any server contact.
//
// Details : this function does very little. mainly to satisfy
// the call_transact_and_set_next format and not affect
// the performance of the non-invalidate operations, which
// are the majority
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleUpdateCachedObject(State *s)
{
if (s->cache_info.write_lock_state == HttpTransact::CACHE_WL_SUCCESS) {
ink_assert(s->cache_info.object_store.valid());
ink_assert(s->cache_info.object_store.response_get() != nullptr);
ink_assert(s->cache_info.object_read != nullptr);
ink_assert(s->cache_info.object_read->valid());
if (!s->cache_info.object_store.request_get()) {
s->cache_info.object_store.request_set(s->cache_info.object_read->request_get());
}
s->request_sent_time = s->cache_info.object_read->request_sent_time_get();
s->response_received_time = s->cache_info.object_read->response_received_time_get();
if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleUpdateCachedObjectContinue);
} else {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleApiErrorJump);
}
} else if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
// even failed to update, continue to serve from cache
HandleUpdateCachedObjectContinue(s);
} else {
s->api_update_cached_object = UPDATE_CACHED_OBJECT_FAIL;
HandleApiErrorJump(s);
}
}
void
HttpTransact::HandleUpdateCachedObjectContinue(State *s)
{
ink_assert(s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE);
s->cache_info.action = s->saved_update_cache_action;
s->next_action = s->saved_update_next_action;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleStatPage
// Description: called from the state machine when a response is received
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleStatPage(State *s)
{
HTTPStatus status;
if (s->internal_msg_buffer) {
status = HTTP_STATUS_OK;
} else {
status = HTTP_STATUS_NOT_FOUND;
}
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status);
///////////////////////////
// insert content-length //
///////////////////////////
s->hdr_info.client_response.set_content_length(s->internal_msg_buffer_size);
if (s->internal_msg_buffer_type) {
int len = strlen(s->internal_msg_buffer_type);
if (len > 0) {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, s->internal_msg_buffer_type, len);
}
} else {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/plain", 10);
}
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_parent
// Description: response came from a parent proxy
//
// Details :
//
// The configuration file can be used to specify more than one parent
// proxy. If a connection to one fails, another can be looked up. This
// function handles responses from parent proxies. If the response is
// bad the next parent proxy (if any) is looked up. If there are no more
// parent proxies that can be looked up, the response is sent to the
// origin server. If the response is good handle_forward_server_connection_open
// is called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_parent(State *s)
{
LookingUp_t next_lookup = UNDEFINED_LOOKUP;
TxnDebug("http_trans", "(hrfp)");
HTTP_RELEASE_ASSERT(s->current.server == &s->parent_info);
// if this parent was retried from a markdown, then
// notify that the retry has completed.
if (s->parent_result.retry) {
markParentUp(s);
}
simple_or_unavailable_server_retry(s);
s->parent_info.state = s->current.state;
switch (s->current.state) {
case CONNECTION_ALIVE:
TxnDebug("http_trans", "[hrfp] connection alive");
s->current.server->connect_result = 0;
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_SUCCESS);
if (s->parent_result.retry) {
markParentUp(s);
}
// the next hop strategy is configured not
// to cache a response from a next hop peer.
if (s->response_action.handled) {
if (s->response_action.action.no_cache) {
TxnDebug("http_trans", "plugin set response_action.no_cache, do not cache.");
s->cache_info.action = CACHE_DO_NO_ACTION;
}
} else {
if (s->parent_result.do_not_cache_response) {
TxnDebug("http_trans", "response is from a next hop peer, do not cache.");
s->cache_info.action = CACHE_DO_NO_ACTION;
}
}
handle_forward_server_connection_open(s);
break;
case PARENT_RETRY:
if (s->current.retry_type == PARENT_RETRY_SIMPLE) {
s->current.simple_retry_attempts++;
} else {
markParentDown(s);
s->current.unavailable_server_retry_attempts++;
}
next_lookup = find_server_and_update_current_info(s);
s->current.retry_type = PARENT_RETRY_NONE;
break;
default:
TxnDebug("http_trans", "[hrfp] connection not alive");
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_FAILURE);
ink_assert(s->hdr_info.server_request.valid());
s->current.server->connect_result = ENOTCONN;
// only mark the parent down in hostdb if the configuration allows it and the parent,
// is not congested, see proxy.config.http.parent_proxy.mark_down_hostdb in records.config.
if (s->txn_conf->parent_failures_update_hostdb && s->current.state != OUTBOUND_CONGESTION) {
s->state_machine->do_hostdb_update_if_necessary();
}
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "[%d] failed to connect to parent %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
// If the request is not retryable, just give up!
if (!is_request_retryable(s)) {
if (s->current.state != OUTBOUND_CONGESTION) {
markParentDown(s);
}
s->parent_result.result = PARENT_FAIL;
handle_parent_died(s);
return;
}
if (s->current.attempts < s->txn_conf->parent_connect_attempts) {
HTTP_INCREMENT_DYN_STAT(http_total_parent_retries_stat);
s->current.attempts++;
// Are we done with this particular parent?
if (s->current.attempts % s->txn_conf->per_parent_connect_attempts != 0) {
// No we are not done with this parent so retry
HTTP_INCREMENT_DYN_STAT(http_total_parent_switches_stat);
s->next_action = how_to_open_connection(s);
TxnDebug("http_trans", "%s Retrying parent for attempt %d, max %" PRId64, "[handle_response_from_parent]",
s->current.attempts, s->txn_conf->per_parent_connect_attempts);
return;
} else {
TxnDebug("http_trans", "%s %d per parent attempts exhausted", "[handle_response_from_parent]", s->current.attempts);
HTTP_INCREMENT_DYN_STAT(http_total_parent_retries_exhausted_stat);
// Only mark the parent down if we failed to connect
// to the parent otherwise slow origin servers cause
// us to mark the parent down
if (s->current.state == CONNECTION_ERROR || s->current.state == INACTIVE_TIMEOUT) {
markParentDown(s);
}
// We are done so look for another parent if any
next_lookup = find_server_and_update_current_info(s);
}
} else {
// Done trying parents... fail over to origin server if that is
// appropriate
HTTP_INCREMENT_DYN_STAT(http_total_parent_retries_exhausted_stat);
TxnDebug("http_trans", "Error. No more retries.");
if (s->current.state == CONNECTION_ERROR || s->current.state == INACTIVE_TIMEOUT) {
markParentDown(s);
}
s->parent_result.result = PARENT_FAIL;
next_lookup = HOST_NONE;
}
break;
}
// We have either tried to find a new parent or failed over to the
// origin server
switch (next_lookup) {
case PARENT_PROXY:
ink_assert(s->current.request_to == PARENT_PROXY);
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookupAPICall);
break;
case ORIGIN_SERVER:
// Next lookup is Origin Server, try DNS for Origin Server
return CallOSDNSLookup(s);
break;
case HOST_NONE:
// Check if content can be served from cache
s->current.request_to = PARENT_PROXY;
handle_server_connection_not_open(s);
break;
default:
// This handles:
// UNDEFINED_LOOKUP
// INCOMING_ROUTER
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_server
// Description: response is from the origin server
//
// Details :
//
// response from the origin server. one of three things can happen now.
// if the response is bad, then we can either retry (by first downgrading
// the request, maybe making it non-keepalive, etc.), or we can give up.
// the latter case is handled by handle_server_connection_not_open and
// sends an error response back to the client. if the response is good
// handle_forward_server_connection_open is called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_server(State *s)
{
TxnDebug("http_trans", "(hrfs)");
HTTP_RELEASE_ASSERT(s->current.server == &s->server_info);
unsigned max_connect_retries = 0;
// plugin call
s->server_info.state = s->current.state;
if (s->os_response_plugin_inst) {
s->os_response_plugin_inst->osResponse(reinterpret_cast<TSHttpTxn>(s->state_machine), s->current.state);
}
switch (s->current.state) {
case CONNECTION_ALIVE:
TxnDebug("http_trans", "[hrfs] connection alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_SUCCESS);
s->current.server->clear_connect_fail();
handle_forward_server_connection_open(s);
break;
case OUTBOUND_CONGESTION:
TxnDebug("http_trans", "Error. congestion control -- congested.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->set_connect_fail(EUSERS); // too many users
handle_server_connection_not_open(s);
break;
case OPEN_RAW_ERROR:
case CONNECTION_ERROR:
case STATE_UNDEFINED:
case INACTIVE_TIMEOUT:
case PARSE_ERROR:
case CONNECTION_CLOSED:
case BAD_INCOMING_RESPONSE:
if (is_server_negative_cached(s)) {
max_connect_retries = s->txn_conf->connect_attempts_max_retries_dead_server - 1;
} else {
// server not yet negative cached - use default number of retries
max_connect_retries = s->txn_conf->connect_attempts_max_retries;
}
TxnDebug("http_trans", "max_connect_retries: %d s->current.attempts: %d", max_connect_retries, s->current.attempts);
if (is_request_retryable(s) && s->current.attempts < max_connect_retries) {
// If this is a round robin DNS entry & we're tried configured
// number of times, we should try another node
if (DNSLookupInfo::OS_Addr::OS_ADDR_TRY_CLIENT == s->dns_info.os_addr_style) {
// attempt was based on client supplied server address. Try again
// using HostDB.
// Allow DNS attempt
s->dns_info.lookup_success = false;
// See if we can get data from HostDB for this.
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_TRY_HOSTDB;
// Force host resolution to have the same family as the client.
// Because this is a transparent connection, we can't switch address
// families - that is locked in by the client source address.
ats_force_order_by_family(&s->current.server->dst_addr.sa, s->my_txn_conf().host_res_data.order);
return CallOSDNSLookup(s);
} else if ((s->dns_info.srv_lookup_success || s->host_db_info.is_rr_elt()) &&
(s->txn_conf->connect_attempts_rr_retries > 0) &&
((s->current.attempts + 1) % s->txn_conf->connect_attempts_rr_retries == 0)) {
delete_server_rr_entry(s, max_connect_retries);
return;
} else {
retry_server_connection_not_open(s, s->current.state, max_connect_retries);
TxnDebug("http_trans", "Error. Retrying...");
s->next_action = how_to_open_connection(s);
if (s->api_server_addr_set) {
// If the plugin set a server address, back up to the OS_DNS hook
// to let it try another one. Force OS_ADDR_USE_CLIENT so that
// in OSDNSLoopkup, we back up to how_to_open_connections which
// will tell HttpSM to connect the origin server.
s->dns_info.os_addr_style = DNSLookupInfo::OS_Addr::OS_ADDR_USE_CLIENT;
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, OSDNSLookup);
}
return;
}
} else {
error_log_connection_failure(s, s->current.state);
TxnDebug("http_trans", "Error. No more retries.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
handle_server_connection_not_open(s);
}
break;
case ACTIVE_TIMEOUT:
TxnDebug("http_trans", "[hrfs] connection not alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->set_connect_fail(ETIMEDOUT);
handle_server_connection_not_open(s);
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : delete_server_rr_entry
// Description:
//
// Details :
//
// connection to server failed mark down the server round robin entry
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::delete_server_rr_entry(State *s, int max_retries)
{
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "[%d] failed to connect to %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
TxnDebug("http_trans", "marking rr entry down and finding next one");
ink_assert(s->current.server->had_connect_fail());
ink_assert(s->current.request_to == ORIGIN_SERVER);
ink_assert(s->current.server == &s->server_info);
update_dns_info(&s->dns_info, &s->current);
s->current.attempts++;
TxnDebug("http_trans", "attempts now: %d, max: %d", s->current.attempts, max_retries);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN, ReDNSRoundRobin);
}
void
HttpTransact::error_log_connection_failure(State *s, ServerState_t conn_state)
{
char addrbuf[INET6_ADDRSTRLEN];
TxnDebug("http_trans", "[%d] failed to connect [%d] to %s", s->current.attempts, conn_state,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
if (s->current.server->had_connect_fail()) {
char *url_str = s->hdr_info.client_request.url_string_get(&s->arena);
int host_len = 0;
const char *host_name_ptr = "";
if (s->unmapped_url.valid()) {
host_name_ptr = s->unmapped_url.host_get(&host_len);
}
std::string_view host_name{host_name_ptr, size_t(host_len)};
ts::bwprint(error_bw_buffer,
"CONNECT: attempt fail [{}] to {} for host='{}' "
"connection_result={::s} error={::s} attempts={} url='{}'",
HttpDebugNames::get_server_state_name(conn_state), s->current.server->dst_addr, host_name,
ts::bwf::Errno(s->current.server->connect_result), ts::bwf::Errno(s->cause_of_death_errno), s->current.attempts,
ts::bwf::FirstOf(url_str, "<none>"));
Log::error("%s", error_bw_buffer.c_str());
s->arena.str_free(url_str);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : retry_server_connection_not_open
// Description:
//
// Details :
//
// connection to server failed. retry.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::retry_server_connection_not_open(State *s, ServerState_t conn_state, unsigned max_retries)
{
ink_assert(s->current.state != CONNECTION_ALIVE);
ink_assert(s->current.state != ACTIVE_TIMEOUT);
ink_assert(s->current.attempts <= max_retries);
ink_assert(s->cause_of_death_errno != -UNKNOWN_INTERNAL_ERROR);
error_log_connection_failure(s, conn_state);
//////////////////////////////////////////////
// disable keep-alive for request and retry //
//////////////////////////////////////////////
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->current.attempts++;
TxnDebug("http_trans", "attempts now: %d, max: %d", s->current.attempts, max_retries);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_server_connection_not_open
// Description:
//
// Details :
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_server_connection_not_open(State *s)
{
bool serve_from_cache = false;
TxnDebug("http_trans", "(hscno)");
TxnDebug("http_seq", "Entering HttpTransact::handle_server_connection_not_open");
ink_assert(s->current.state != CONNECTION_ALIVE);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_ERROR);
HTTP_INCREMENT_DYN_STAT(http_broken_server_connections_stat);
// Fire off a hostdb update to mark the server as down
s->state_machine->do_hostdb_update_if_necessary();
switch (s->cache_info.action) {
case CACHE_DO_UPDATE:
case CACHE_DO_SERVE:
serve_from_cache = is_stale_cache_response_returnable(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - "
"we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_DELETE:
// decisions, decisions. what should we do here?
// we could theoretically still delete the cached
// copy or serve it back with a warning, or easier
// just punt and biff the user. i say: biff the user.
/* fall through */
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
case CACHE_DO_WRITE:
/* fall through */
default:
serve_from_cache = false;
break;
}
if (serve_from_cache) {
ink_assert(s->cache_info.object_read != nullptr);
ink_assert(s->cache_info.action == CACHE_DO_UPDATE || s->cache_info.action == CACHE_DO_SERVE);
ink_assert(s->internal_msg_buffer == nullptr);
s->source = SOURCE_CACHE;
TxnDebug("http_trans", "[hscno] serving stale doc to client");
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
switch (s->current.request_to) {
case PARENT_PROXY:
handle_parent_died(s);
break;
case ORIGIN_SERVER:
handle_server_died(s);
break;
default:
ink_assert(!("s->current.request_to is not P.P. or O.S. - hmmm."));
break;
}
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_forward_server_connection_open
// Description: connection to a forward server is open and good
//
// Details :
//
// "Forward server" includes the parent proxy
// or the origin server. This function first determines if the forward
// server uses HTTP 0.9, in which case it simply tunnels the response
// to the client. Else, it updates
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_forward_server_connection_open(State *s)
{
TxnDebug("http_trans", "(hfsco)");
TxnDebug("http_seq", "Entering HttpTransact::handle_server_connection_open");
ink_release_assert(s->current.state == CONNECTION_ALIVE);
HTTPVersion real_version = s->state_machine->get_server_version(s->hdr_info.server_response);
if (real_version != s->host_db_info.app.http_data.http_version) {
// Need to update the hostdb
s->updated_server_version = real_version;
TxnDebug("http_trans", "Update hostdb history of server HTTP version 0x%x", s->updated_server_version.get_flat_version());
}
s->state_machine->do_hostdb_update_if_necessary();
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_CONTINUE ||
s->hdr_info.server_response.status_get() == HTTP_STATUS_EARLY_HINTS) {
handle_100_continue_response(s);
return;
}
if (s->www_auth_content == CACHE_AUTH_FRESH) {
// no update is needed - either to serve from cache if authorized,
// or tunnnel the server response
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_OK) {
// borrow a state variable used by the API function
// this enable us to serve from cache without doing any updating
s->api_server_response_ignore = true;
}
// s->cache_info.action = CACHE_PREPARE_TO_SERVE;
// xing in the tunneling case, need to check when the cache_read_vc is closed, make sure the cache_read_vc is closed
// right away
}
CacheVConnection *cw_vc = s->state_machine->get_cache_sm().cache_write_vc;
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->cache_info.action == CACHE_DO_NO_ACTION) {
switch (s->hdr_info.server_response.status_get()) {
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
break;
default:
TxnDebug("http_trans", "[hfsco] redirect in progress, non-3xx response, setting cache_do_write");
if (cw_vc && s->txn_conf->cache_http) {
s->cache_info.action = CACHE_DO_WRITE;
}
break;
}
}
}
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
/* fall through */
case CACHE_DO_UPDATE:
/* fall through */
case CACHE_DO_DELETE:
TxnDebug("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_cache_operation_on_forward_server_response(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
/* fall through */
case CACHE_DO_SERVE:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
default:
// Just tunnel?
TxnDebug("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_no_cache_operation_on_forward_server_response(s);
break;
}
return;
}
// void HttpTransact::handle_100_continue_response(State* s)
//
// We've received a 100 continue response. Determine if
// we should just swallow the response 100 or forward it
// the client. http-1.1-spec-rev-06 section 8.2.3
//
void
HttpTransact::handle_100_continue_response(State *s)
{
bool forward_100 = false;
HTTPVersion ver = s->hdr_info.client_request.version_get();
if (ver == HTTP_1_1) {
forward_100 = true;
} else if (ver == HTTP_1_0) {
if (s->hdr_info.client_request.value_get_int(MIME_FIELD_EXPECT, MIME_LEN_EXPECT) == 100) {
forward_100 = true;
}
}
if (forward_100) {
// We just want to copy the server's response. All
// the other build response functions insist on
// adding stuff
build_response_copy(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
TRANSACT_RETURN(SM_ACTION_INTERNAL_100_RESPONSE, HandleResponse);
} else {
TRANSACT_RETURN(SM_ACTION_SERVER_PARSE_NEXT_HDR, HandleResponse);
}
}
// void HttpTransact::build_response_copy
//
// Build a response with minimal changes from the base response
//
void
HttpTransact::build_response_copy(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent, s->current.now);
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response); // http version conversion
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response");
}
//////////////////////////////////////////////////////////////////////////
// IMS handling table //
// OS = Origin Server //
// IMS = A GET request w/ an If-Modified-Since header //
// LMs = Last modified state returned by server //
// D, D' are Last modified dates returned by the origin server //
// and are later used for IMS //
// D < D' //
// //
// +----------+-----------+----------+-----------+--------------+ //
// | Client's | Cached | Proxy's | Response to client | //
// | Request | State | Request +-----------+--------------+ //
// | | | | OS 200 | OS 304 | //
// +==========+===========+==========+===========+==============+ //
// | GET | Fresh | N/A | N/A | N/A | //
// +----------+-----------+----------+-----------+--------------+ //
// | GET | Stale, D' | IMS D' | 200, new | 200, cached | //
// +----------+-----------+----------+-----------+--------------+ //
// | GET | Stale, E | INM E | 200, new | 200, cached | //
// +----------+-----------+----------+-----------+--------------+ //
// | INM E | Stale, E | INM E | 304 | 304 | //
// +----------+-----------+----------+-----------+--------------+ //
// | INM E + | Stale, | INM E | 200, new *| 304 | //
// | IMS D' | E + D' | IMS D' | | | //
// +----------+-----------+----------+-----------+--------------+ //
// | IMS D | None | GET | 200, new *| N/A | //
// +----------+-----------+----------+-----------+--------------+ //
// | INM E | None | GET | 200, new *| N/A | //
// +----------+-----------+----------+-----------+--------------+ //
// | IMS D | Stale, D' | IMS D' | 200, new | Compare | //
// |---------------------------------------------| LMs & D' | //
// | IMS D' | Stale, D' | IMS D' | 200, new | If match, 304| //
// |---------------------------------------------| If no match, | //
// | IMS D' | Stale D | IMS D | 200, new *| 200, cached | //
// +------------------------------------------------------------+ //
// //
// Note: * indicates a case that could be optimized to return //
// 304 to the client but currently is not //
// //
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_operation_on_forward_server_response(State *s)
{
TxnDebug("http_trans", "(hcoofsr)");
TxnDebug("http_seq", "Entering handle_cache_operation_on_forward_server_response");
HTTPHdr *base_response = nullptr;
HTTPStatus server_response_code = HTTP_STATUS_NONE;
HTTPStatus client_response_code = HTTP_STATUS_NONE;
const char *warn_text = nullptr;
bool cacheable = false;
cacheable = is_response_cacheable(s, &s->hdr_info.client_request, &s->hdr_info.server_response);
TxnDebug("http_trans", "[hcoofsr] response %s cacheable", cacheable ? "is" : "is not");
// set the correct next action, cache action, response code, and base response
server_response_code = s->hdr_info.server_response.status_get();
switch (server_response_code) {
case HTTP_STATUS_NOT_MODIFIED: // 304
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
// determine the correct cache action, next state, and response
// precondition: s->cache_info.action should be one of the following
// CACHE_DO_DELETE, or CACHE_DO_UPDATE; otherwise, it's an error.
if (s->api_server_response_ignore && s->cache_info.action == CACHE_DO_UPDATE) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
TxnDebug("http_trans", "[hcoofsr] not merging, cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if ((s->cache_info.action == CACHE_DO_DELETE) || ((s->cache_info.action == CACHE_DO_UPDATE) && !cacheable)) {
if (is_request_conditional(&s->hdr_info.client_request)) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// we can just forward the not modified response
// from the server and delete the cached copy
base_response = &s->hdr_info.server_response;
client_response_code = base_response->status_get();
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
} else {
// We got screwed. The client did not send a conditional request,
// but we had a cached copy which we revalidated. The server has
// now told us to delete the cached copy and sent back a 304.
// We need to send the cached copy to the client, then delete it.
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
// Check client request range header if we cached a stealed content with cacheable=false
}
s->cache_info.action = CACHE_DO_SERVE_AND_DELETE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
base_response = s->cache_info.object_read->response_get();
client_response_code = base_response->status_get();
}
} else if (s->cache_info.action == CACHE_DO_UPDATE && is_request_conditional(&s->hdr_info.server_request)) {
// CACHE_DO_UPDATE and server response is cacheable
if (is_request_conditional(&s->hdr_info.client_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = server_response_code;
}
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// delete the cached copy unless configured to always verify IMS
if (s->txn_conf->cache_when_to_revalidate != 4) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
/* base_response will be set after updating headers below */
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
base_response = &s->hdr_info.server_response;
}
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
// Note that even if the Range request is not satisfiable, we
// update and serve this cache. This will give a 200 response to
// a bad client, but allows us to avoid pegging the origin (e.g. abuse).
}
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
/* base_response will be set after updating headers below */
}
} else { // cache action != CACHE_DO_DELETE and != CACHE_DO_UPDATE
// bogus response from server. deal by tunnelling to client.
// server should not have sent back a 304 because our request
// should not have been an conditional.
TxnDebug("http_trans", "[hcoofsr] 304 for non-conditional request");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
client_response_code = s->hdr_info.server_response.status_get();
base_response = &s->hdr_info.server_response;
// since this is bad, insert warning header into client response
// The only exception case is conditional client request,
// cache miss, and client request being unlikely cacheable.
// In this case, the server request is given the same
// conditional headers as client request (see build_request()).
// So an unexpected 304 might be received.
// FIXME: check this case
if (is_request_likely_cacheable(s, &s->hdr_info.client_request)) {
warn_text = "Proxy received unexpected 304 response; "
"content may be stale";
}
}
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED: // 505
{
bool keep_alive = (s->current.server->keep_alive == HTTP_KEEPALIVE);
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
s->already_downgraded = true;
} else {
if (!keep_alive) {
/* START Hack */
(s->hdr_info.server_request).field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
/* END Hack */
}
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
}
return;
default:
TxnDebug("http_trans", "[hcoofsr] response code: %d", server_response_code);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
/* if we receive a 500, 502, 503 or 504 while revalidating
a document, treat the response as a 304 and in effect revalidate the document for
negative_revalidating_lifetime. (negative revalidating)
*/
if ((server_response_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || server_response_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
server_response_code == HTTP_STATUS_BAD_GATEWAY || server_response_code == HTTP_STATUS_SERVICE_UNAVAILABLE) &&
s->cache_info.action == CACHE_DO_UPDATE && s->txn_conf->negative_revalidating_enabled &&
is_stale_cache_response_returnable(s)) {
HTTPStatus cached_response_code = s->cache_info.object_read->response_get()->status_get();
if (!(cached_response_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || cached_response_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
cached_response_code == HTTP_STATUS_BAD_GATEWAY || cached_response_code == HTTP_STATUS_SERVICE_UNAVAILABLE)) {
TxnDebug("http_trans", "[hcoofsr] negative revalidating: revalidate stale object and serve from cache");
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
base_response = s->cache_info.object_store.response_get();
time_t exp_time = s->txn_conf->negative_revalidating_lifetime + ink_local_time();
base_response->set_expires(exp_time);
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate
// documents so that an invalidated document needs to be
// revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
if (is_request_conditional(&s->hdr_info.client_request) &&
HttpTransactCache::match_response_to_request_conditionals(&s->hdr_info.client_request,
s->cache_info.object_read->response_get(),
s->response_received_time) == HTTP_STATUS_NOT_MODIFIED) {
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
client_response_code = HTTP_STATUS_NOT_MODIFIED;
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
client_response_code = s->cache_info.object_read->response_get()->status_get();
}
ink_assert(base_response->valid());
if (client_response_code == HTTP_STATUS_NOT_MODIFIED) {
ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST) != VIA_CLIENT_SIMPLE);
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
if (s->next_action == SM_ACTION_SERVE_FROM_CACHE && s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
return;
}
}
s->next_action = SM_ACTION_SERVER_READ;
client_response_code = server_response_code;
base_response = &s->hdr_info.server_response;
s->is_cacheable_due_to_negative_caching_configuration = cacheable && is_negative_caching_appropriate(s);
// determine the correct cache action given the original cache action,
// cacheability of server response, and request method
// precondition: s->cache_info.action is one of the following
// CACHE_DO_UPDATE, CACHE_DO_WRITE, or CACHE_DO_DELETE
int const server_request_method = s->hdr_info.server_request.method_get_wksidx();
if (s->api_server_response_no_store) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->api_server_response_ignore && server_response_code == HTTP_STATUS_OK &&
server_request_method == HTTP_WKSIDX_HEAD) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
TxnDebug("http_trans",
"[hcoofsr] ignoring server response, "
"cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if (s->cache_info.action == CACHE_DO_UPDATE) {
if (s->www_auth_content == CACHE_AUTH_FRESH || s->api_server_response_ignore) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->www_auth_content == CACHE_AUTH_STALE && server_response_code == HTTP_STATUS_UNAUTHORIZED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (!cacheable) {
if (HttpTransactHeaders::is_status_an_error_response(server_response_code) &&
!HttpTransactHeaders::is_method_safe(server_request_method)) {
// Only delete the cache entry if the response is successful. For
// unsuccessful responses, the transaction doesn't invalidate our
// entry. This behavior complies with RFC 7234, section 4.4 which
// stipulates that the entry only need be invalidated for non-error
// responses:
//
// A cache MUST invalidate the effective request URI (Section 5.5 of
// [RFC7230]) when it receives a non-error response to a request
// with a method whose safety is unknown.
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_DO_DELETE;
}
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
} else {
ink_assert(s->cache_info.object_read != nullptr);
s->cache_info.action = CACHE_DO_REPLACE;
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
}
}
} else if (s->cache_info.action == CACHE_DO_WRITE) {
if (!cacheable) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_DO_WRITE;
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
}
}
} else if (s->cache_info.action == CACHE_DO_DELETE) {
if (!cacheable && HttpTransactHeaders::is_status_an_error_response(server_response_code) &&
!HttpTransactHeaders::is_method_safe(server_request_method)) {
// Only delete the cache entry if the response is successful. For
// unsuccessful responses, the transaction doesn't invalidate our
// entry. This behavior complies with RFC 7234, section 4.4 which
// stipulates that the entry only need be invalidated for non-error
// responses:
//
// A cache MUST invalidate the effective request URI (Section 5.5 of
// [RFC7230]) when it receives a non-error response to a request
// with a method whose safety is unknown.
s->cache_info.action = CACHE_DO_NO_ACTION;
}
} else {
ink_assert(!("cache action inconsistent with current state"));
}
// postcondition: s->cache_info.action is one of the following
// CACHE_DO_REPLACE, CACHE_DO_WRITE, CACHE_DO_DELETE, or
// CACHE_DO_NO_ACTION
// Check see if we ought to serve the client a 304 based on
// it's IMS date. We may gotten a 200 back from the origin
// server if our (the proxies's) cached copy was out of date
// but the client's wasn't. However, if the response is
// not cacheable we ought not issue a 304 to the client so
// make sure we are writing the document to the cache if
// before issuing a 304
if (s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_NO_ACTION ||
s->cache_info.action == CACHE_DO_REPLACE) {
if (s->is_cacheable_due_to_negative_caching_configuration) {
HTTPHdr *resp;
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(&s->hdr_info.server_response);
resp = s->cache_info.object_store.response_get();
if (!resp->presence(MIME_PRESENCE_EXPIRES)) {
time_t exp_time = s->txn_conf->negative_caching_lifetime + ink_local_time();
resp->set_expires(exp_time);
}
} else if (is_request_conditional(&s->hdr_info.client_request) && server_response_code == HTTP_STATUS_OK) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, &s->hdr_info.server_response, s->response_received_time);
TxnDebug("http_trans",
"[hcoofsr] conditional request, 200 "
"response, send back 304 if possible [crc=%d]",
client_response_code);
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
case CACHE_DO_REPLACE:
s->next_action = SM_ACTION_INTERNAL_CACHE_WRITE;
break;
case CACHE_DO_DELETE:
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
break;
default:
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
}
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVER_REVALIDATED);
}
}
} else if (s->is_cacheable_due_to_negative_caching_configuration) {
s->is_cacheable_due_to_negative_caching_configuration = false;
}
break;
}
// update stat, set via string, etc
switch (s->cache_info.action) {
case CACHE_DO_SERVE_AND_DELETE:
// fall through
case CACHE_DO_DELETE:
TxnDebug("http_trans", "[hcoofsr] delete cached copy");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_DELETED);
HTTP_INCREMENT_DYN_STAT(http_cache_deletes_stat);
break;
case CACHE_DO_WRITE:
TxnDebug("http_trans", "[hcoofsr] cache write");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_WRITTEN);
HTTP_INCREMENT_DYN_STAT(http_cache_writes_stat);
break;
case CACHE_DO_SERVE_AND_UPDATE:
// fall through
case CACHE_DO_UPDATE:
// fall through
case CACHE_DO_REPLACE:
TxnDebug("http_trans", "[hcoofsr] cache update/replace");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
break;
default:
break;
}
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) && (s->cache_info.action != CACHE_DO_NO_ACTION)) {
/* ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST)
!= VIA_CLIENT_SIMPLE); */
TxnDebug("http_trans", "[hcoofsr] Client request was conditional");
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
// The correct cache action, next action, and response code are set.
// Do the real work below.
// first update the cached object
if ((s->cache_info.action == CACHE_DO_UPDATE) || (s->cache_info.action == CACHE_DO_SERVE_AND_UPDATE)) {
TxnDebug("http_trans", "[hcoofsr] merge and update cached copy");
merge_and_update_headers_for_cache_update(s);
base_response = s->cache_info.object_store.response_get();
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate documents
// so that an invalidated document needs to be revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
// unset warning revalidation failed header if it set
// (potentially added by negative revalidating)
delete_warning_value(base_response, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
ink_assert(base_response->valid());
if ((s->cache_info.action == CACHE_DO_WRITE) || (s->cache_info.action == CACHE_DO_REPLACE)) {
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
}
// 304, 412, and 416 responses are handled here
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
// Because we are decoupling User-Agent validation from
// Traffic Server validation just build a regular 304
// if the exception of adding prepending the VIA
// header to show the revalidation path
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
// Copy over the response via field (if any) preserving
// the order of the fields
MIMEField *resp_via = s->hdr_info.server_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (resp_via) {
MIMEField *our_via;
our_via = s->hdr_info.client_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (our_via == nullptr) {
our_via = s->hdr_info.client_response.field_create(MIME_FIELD_VIA, MIME_LEN_VIA);
s->hdr_info.client_response.field_attach(our_via);
}
// HDR FIX ME - Multiple appends are VERY slow
while (resp_via) {
int clen;
const char *cfield = resp_via->value_get(&clen);
s->hdr_info.client_response.field_value_append(our_via, cfield, clen, true);
resp_via = resp_via->m_next_dup;
}
}
// a warning text is added only in the case of a NOT MODIFIED response
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, &s->hdr_info.client_response, HTTP_WARNING_CODE_MISC_WARNING,
warn_text, strlen(warn_text));
}
DUMP_HEADER("http_hdrs", &s->hdr_info.client_response, s->state_machine_id, "Proxy's Response (Client Conditionals)");
return;
}
// all other responses (not 304, 412, 416) are handled here
else {
if (((s->next_action == SM_ACTION_SERVE_FROM_CACHE) || (s->next_action == SM_ACTION_SERVER_READ)) &&
s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_no_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_no_cache_operation_on_forward_server_response(State *s)
{
TxnDebug("http_trans", "(hncoofsr)");
TxnDebug("http_seq", "Entering handle_no_cache_operation_on_forward_server_response");
bool keep_alive = s->current.server->keep_alive == HTTP_KEEPALIVE;
const char *warn_text = nullptr;
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_OK:
TxnDebug("http_trans", "[hncoofsr] server sent back 200");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
if (s->method == HTTP_WKSIDX_CONNECT) {
TxnDebug("http_trans", "[hncoofsr] next action is SSL_TUNNEL");
s->next_action = SM_ACTION_SSL_TUNNEL;
} else {
TxnDebug("http_trans", "[hncoofsr] next action will be OS_READ_CACHE_NOOP");
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
}
if (s->state_machine->redirect_url == nullptr) {
s->state_machine->enable_redirection = false;
}
break;
case HTTP_STATUS_NOT_MODIFIED:
TxnDebug("http_trans", "[hncoofsr] server sent back 304. IMS from client?");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
if (!is_request_conditional(&s->hdr_info.client_request)) {
// bogus server response. not a conditional request
// from the client and probably not a conditional
// request from the proxy.
// since this is bad, insert warning header into client response
warn_text = "Proxy received unexpected 304 response; content may be stale";
}
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
s->already_downgraded = true;
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
} else {
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
return;
case HTTP_STATUS_PARTIAL_CONTENT:
// If we get this back we should be just passing it through.
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
default:
TxnDebug("http_trans", "[hncoofsr] server sent back something other than 100,304,200");
/* Default behavior is to pass-through response to the client */
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
}
HTTPHdr *to_warn;
if (s->next_action == SM_ACTION_SERVER_READ && s->state_machine->do_transform_open()) {
set_header_for_transform(s, &s->hdr_info.server_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
to_warn = &s->hdr_info.server_response;
}
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, HTTP_WARNING_CODE_MISC_WARNING, warn_text,
strlen(warn_text));
}
return;
}
void
HttpTransact::merge_and_update_headers_for_cache_update(State *s)
{
URL *s_url = nullptr;
HTTPHdr *cached_hdr = nullptr;
if (!s->cache_info.object_store.valid()) {
s->cache_info.object_store.create();
}
s->cache_info.object_store.request_set(&s->hdr_info.server_request);
cached_hdr = s->cache_info.object_store.response_get();
if (s->redirect_info.redirect_in_process) {
s_url = &s->redirect_info.original_url;
} else {
s_url = &s->cache_info.original_url;
}
ink_assert(s_url != nullptr);
s->cache_info.object_store.request_get()->url_set(s_url->valid() ? s_url : s->hdr_info.client_request.url_get());
if (s->cache_info.object_store.request_get()->method_get_wksidx() == HTTP_WKSIDX_HEAD) {
s->cache_info.object_store.request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
if (s->api_modifiable_cached_resp) {
ink_assert(cached_hdr != nullptr && cached_hdr->valid());
s->api_modifiable_cached_resp = false;
} else {
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
}
// Delete caching headers from the cached response. If these are
// still being served by the origin we will copy new versions in
// from the server response. RFC 2616 says that a 304 response may
// omit some headers if they were sent in a 200 response (see section
// 10.3.5), but RFC 7232) is clear that the 304 and 200 responses
// must be identical (see section 4.1). This code attempts to strike
// a balance between the two.
cached_hdr->field_delete(MIME_FIELD_AGE, MIME_LEN_AGE);
cached_hdr->field_delete(MIME_FIELD_ETAG, MIME_LEN_ETAG);
cached_hdr->field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
merge_response_header_with_cached_header(cached_hdr, &s->hdr_info.server_response);
// Some special processing for 304
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED) {
// Hack fix. If the server sends back
// a 304 without a Date Header, use the current time
// as the new Date value in the header to be cached.
time_t date_value = s->hdr_info.server_response.get_date();
if (date_value <= 0) {
cached_hdr->set_date(s->request_sent_time);
date_value = s->request_sent_time;
}
// If the cached response has an Age: we should update it
// We could use calculate_document_age but my guess is it's overkill
// Just use 'now' - 304's Date: + Age: (response's Age: if there)
date_value = std::max(s->current.now - date_value, static_cast<ink_time_t>(0));
if (s->hdr_info.server_response.presence(MIME_PRESENCE_AGE)) {
time_t new_age = s->hdr_info.server_response.get_age();
if (new_age >= 0) {
cached_hdr->set_age(date_value + new_age);
} else {
cached_hdr->set_age(-1); // Overflow
}
}
delete_warning_value(cached_hdr, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
s->cache_info.object_store.request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
}
void
HttpTransact::handle_transform_cache_write(State *s)
{
ink_assert(s->cache_info.transform_action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
s->cache_info.transform_action = CACHE_DO_WRITE;
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
s->cache_info.transform_write_status = CACHE_WRITE_LOCK_MISS;
break;
default:
ink_release_assert(0);
}
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, nullptr);
}
void
HttpTransact::handle_transform_ready(State *s)
{
ink_assert(s->hdr_info.transform_response.valid() == true);
s->pre_transform_source = s->source;
s->source = SOURCE_TRANSFORM;
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header From Transform");
build_response(s, &s->hdr_info.transform_response, &s->hdr_info.client_response, s->client_info.http_version);
if (s->cache_info.action != CACHE_DO_NO_ACTION && s->cache_info.action != CACHE_DO_DELETE && s->api_info.cache_transformed &&
!s->range_setup) {
HTTPHdr *transform_store_request = nullptr;
switch (s->pre_transform_source) {
case SOURCE_CACHE:
// If we are transforming from the cache, treat
// the transform as if it were virtual server
// use in the incoming request
transform_store_request = &s->hdr_info.client_request;
break;
case SOURCE_HTTP_ORIGIN_SERVER:
transform_store_request = &s->hdr_info.server_request;
break;
default:
ink_release_assert(0);
}
ink_assert(transform_store_request->valid() == true);
set_headers_for_cache_write(s, &s->cache_info.transform_store, transform_store_request, &s->hdr_info.transform_response);
// For debugging
if (is_action_tag_set("http_nullt")) {
s->cache_info.transform_store.request_get()->value_set("InkXform", 8, "nullt", 5);
s->cache_info.transform_store.response_get()->value_set("InkXform", 8, "nullt", 5);
}
s->cache_info.transform_action = CACHE_PREPARE_TO_WRITE;
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM, handle_transform_cache_write);
} else {
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, nullptr);
}
}
void
HttpTransact::set_header_for_transform(State *s, HTTPHdr *base_header)
{
s->hdr_info.transform_response.create(HTTP_TYPE_RESPONSE);
s->hdr_info.transform_response.copy(base_header);
// Nuke the content length since 1) the transform will probably
// change it. 2) it would only be valid for the first transform
// in the chain
s->hdr_info.transform_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header To Transform");
}
void
HttpTransact::set_headers_for_cache_write(State *s, HTTPInfo *cache_info, HTTPHdr *request, HTTPHdr *response)
{
URL *temp_url;
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (!cache_info->valid()) {
cache_info->create();
}
/* Store the requested URI */
// Nasty hack. The set calls for
// marshalled types current do handle something being
// set to itself. Make the check here for that case.
// Why the request url is set before a copy made is
// quite beyond me. Seems like a unsafe practice so
// FIX ME!
// Logic added to restore the original URL for multiple cache lookup
// and automatic redirection
if (s->redirect_info.redirect_in_process) {
temp_url = &s->redirect_info.original_url;
ink_assert(temp_url->valid());
request->url_set(temp_url);
} else if ((temp_url = &(s->cache_info.original_url))->valid()) {
request->url_set(temp_url);
} else if (request != &s->hdr_info.client_request) {
request->url_set(s->hdr_info.client_request.url_get());
}
cache_info->request_set(request);
/* Why do we check the negative caching case? No one knows. This used to assert if the cache_info
response wasn't already valid, which broke negative caching when a transform is active. Why it
wasn't OK to pull in the @a response explicitly passed in isn't clear and looking at the call
sites yields no insight. So the assert is removed and we keep the behavior that if the response
in @a cache_info is already set, we don't override it.
*/
if (!s->is_cacheable_due_to_negative_caching_configuration || !cache_info->response_get()->valid()) {
cache_info->response_set(response);
}
if (s->api_server_request_body_set) {
cache_info->request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
// Set-Cookie should not be put in the cache to prevent
// sending person A's cookie to person B
cache_info->response_get()->field_delete(MIME_FIELD_SET_COOKIE, MIME_LEN_SET_COOKIE);
cache_info->request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
// server 200 Ok for Range request
cache_info->request_get()->field_delete(MIME_FIELD_RANGE, MIME_LEN_RANGE);
// If we're ignoring auth, then we don't want to cache WWW-Auth headers
if (s->txn_conf->cache_ignore_auth) {
cache_info->response_get()->field_delete(MIME_FIELD_WWW_AUTHENTICATE, MIME_LEN_WWW_AUTHENTICATE);
}
DUMP_HEADER("http_hdrs", cache_info->request_get(), s->state_machine_id, "Cached Request Hdr");
}
void
HttpTransact::merge_response_header_with_cached_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
MIMEField *new_field;
const char *name;
bool dups_seen = false;
for (auto spot = response_header->begin(), limit = response_header->end(); spot != limit; ++spot) {
MIMEField &field{*spot};
int name_len;
name = field.name_get(&name_len);
///////////////////////////
// is hop-by-hop header? //
///////////////////////////
if (HttpTransactHeaders::is_this_a_hop_by_hop_header(name)) {
continue;
}
/////////////////////////////////////
// dont cache content-length field and transfer encoding //
/////////////////////////////////////
if (name == MIME_FIELD_CONTENT_LENGTH || name == MIME_FIELD_TRANSFER_ENCODING) {
continue;
}
/////////////////////////////////////
// dont cache Set-Cookie headers //
/////////////////////////////////////
if (name == MIME_FIELD_SET_COOKIE) {
continue;
}
/////////////////////////////////////////
// dont overwrite the cached content //
// type as this wreaks havoc with //
// transformed content //
/////////////////////////////////////////
if (name == MIME_FIELD_CONTENT_TYPE) {
continue;
}
/////////////////////////////////////
// dont delete warning. a separate//
// functions merges the two in a //
// complex manner //
/////////////////////////////////////
if (name == MIME_FIELD_WARNING) {
continue;
}
// Copy all remaining headers with replacement
// Duplicate header fields cause a bug problem
// since we need to duplicate with replacement.
// Without dups, we can just nuke what is already
// there in the cached header. With dups, we
// can't do this because what is already there
// may be a dup we've already copied in. If
// dups show up we look through the remaining
// header fields in the new response, nuke
// them in the cached response and then add in
// the remaining fields one by one from the
// response header
//
if (field.m_next_dup) {
if (dups_seen == false) {
const char *name2;
int name_len2;
// use a second iterator to delete the
// remaining response headers in the cached response,
// so that they will be added in the next iterations.
for (auto spot2 = spot; spot2 != limit; ++spot2) {
MIMEField &field2{*spot2};
name2 = field2.name_get(&name_len2);
// It is specified above that content type should not
// be altered here however when a duplicate header
// is present, all headers following are delete and
// re-added back. This includes content type if it follows
// any duplicate header. This leads to the loss of
// content type in the client response.
// This ensures that it is not altered when duplicate
// headers are present.
if (name2 == MIME_FIELD_CONTENT_TYPE) {
continue;
}
cached_header->field_delete(name2, name_len2);
}
dups_seen = true;
}
}
int value_len;
const char *value = field.value_get(&value_len);
if (dups_seen == false) {
cached_header->value_set(name, name_len, value, value_len);
} else {
new_field = cached_header->field_create(name, name_len);
cached_header->field_attach(new_field);
cached_header->field_value_set(new_field, value, value_len);
}
}
merge_warning_header(cached_header, response_header);
Debug("http_hdr_space", "Merged response header with %d dead bytes", cached_header->m_heap->m_lost_string_space);
}
void
HttpTransact::merge_warning_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
// The plan:
//
// 1) The cached header has it's warning codes untouched
// since merge_response_header_with_cached_header()
// doesn't deal with warning headers.
// 2) If there are 1xx warning codes in the cached
// header, they need to be removed. Removal
// is difficult since the hdrs don't comma
// separate values, so build up a new header
// piecemeal. Very slow but shouldn't happen
// very often
// 3) Since we keep the all the warning codes from
// the response header, append if to
// the cached header
//
MIMEField *c_warn = cached_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *r_warn = response_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *new_cwarn = nullptr;
int move_warn_len;
const char *move_warn;
// Loop over the cached warning header and transfer all non 1xx
// warning values to a new header
if (c_warn) {
HdrCsvIter csv;
move_warn = csv.get_first(c_warn, &move_warn_len);
while (move_warn) {
int code = ink_atoi(move_warn, move_warn_len);
if (code < 100 || code > 199) {
bool first_move;
if (!new_cwarn) {
new_cwarn = cached_header->field_create();
first_move = true;
} else {
first_move = false;
}
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, !first_move);
}
move_warn = csv.get_next(&move_warn_len);
}
// At this point we can nuke the old warning headers
cached_header->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
// Add in the new header if it has anything in it
if (new_cwarn) {
new_cwarn->name_set(cached_header->m_heap, cached_header->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
}
}
// Loop over all the dups in the response warning header and append
// them one by one on to the cached warning header
while (r_warn) {
move_warn = r_warn->value_get(&move_warn_len);
if (new_cwarn) {
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, true);
} else {
new_cwarn = cached_header->field_create(MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
cached_header->field_value_set(new_cwarn, move_warn, move_warn_len);
}
r_warn = r_warn->m_next_dup;
}
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
bool
HttpTransact::get_ka_info_from_config(State *s, ConnectionAttributes *server_info)
{
bool check_hostdb = false;
if (server_info->http_version > HTTP_0_9) {
TxnDebug("http_trans", "version already set server_info->http_version %d.%d", server_info->http_version.get_major(),
server_info->http_version.get_minor());
return false;
}
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
server_info->http_version = HTTP_1_0;
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
server_info->http_version = HTTP_1_0;
check_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
server_info->http_version = HTTP_1_0;
if (s->hdr_info.client_request.version_get() == HTTP_1_1) {
// check hostdb only if client req is http/1.1
check_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// fallthrough
case HttpConfigParams::SEND_HTTP11_ALWAYS:
server_info->http_version = HTTP_1_1;
break;
}
TxnDebug("http_trans", "server_info->http_version %d.%d, check_hostdb %d", server_info->http_version.get_major(),
server_info->http_version.get_minor(), check_hostdb);
// Set keep_alive info based on the records.config setting
server_info->keep_alive = s->txn_conf->keep_alive_enabled_out ? HTTP_KEEPALIVE : HTTP_NO_KEEPALIVE;
return check_hostdb;
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
void
HttpTransact::get_ka_info_from_host_db(State *s, ConnectionAttributes *server_info,
ConnectionAttributes * /* client_info ATS_UNUSED */, HostDBInfo *host_db_info)
{
bool force_http11 = false;
bool http11_if_hostdb = false;
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
// No need to do anything since above vars
// are defaulted false
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
http11_if_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
if (s->hdr_info.client_request.version_get() == HTTP_1_1) {
http11_if_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// fallthrough
case HttpConfigParams::SEND_HTTP11_ALWAYS:
force_http11 = true;
break;
}
if (force_http11 == true || (http11_if_hostdb == true && host_db_info->app.http_data.http_version == HTTP_1_1)) {
server_info->http_version = HTTP_1_1;
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HTTP_1_0) {
server_info->http_version = HTTP_1_0;
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HTTP_0_9) {
server_info->http_version = HTTP_0_9;
server_info->keep_alive = HTTP_NO_KEEPALIVE;
} else {
//////////////////////////////////////////////
// not set yet for this host. set defaults. //
//////////////////////////////////////////////
server_info->http_version = HTTP_1_0;
server_info->keep_alive = HTTP_KEEPALIVE;
host_db_info->app.http_data.http_version = HTTP_1_0;
}
/////////////////////////////
// origin server keep_alive //
/////////////////////////////
if (!s->txn_conf->keep_alive_enabled_out) {
server_info->keep_alive = HTTP_NO_KEEPALIVE;
}
return;
}
void
HttpTransact::add_client_ip_to_outgoing_request(State *s, HTTPHdr *request)
{
char ip_string[INET6_ADDRSTRLEN + 1] = {'\0'};
size_t ip_string_size = 0;
if (!ats_is_ip(&s->client_info.src_addr.sa)) {
return;
}
// Always prepare the IP string.
if (ats_ip_ntop(&s->client_info.src_addr.sa, ip_string, sizeof(ip_string)) != nullptr) {
ip_string_size += strlen(ip_string);
} else {
// Failure, omg
ip_string_size = 0;
ip_string[0] = 0;
}
// Check to see if the ip_string has been set
if (ip_string_size == 0) {
return;
}
// if we want client-ip headers, and there isn't one, add one
if (!s->txn_conf->anonymize_remove_client_ip) {
switch (s->txn_conf->anonymize_insert_client_ip) {
case 1: { // Insert the client-ip, but only if the UA did not send one
bool client_ip_set = request->presence(MIME_PRESENCE_CLIENT_IP);
TxnDebug("http_trans", "client_ip_set = %d", client_ip_set);
if (client_ip_set == true) {
break;
}
}
// FALL-THROUGH
case 2: // Always insert the client-ip
request->value_set(MIME_FIELD_CLIENT_IP, MIME_LEN_CLIENT_IP, ip_string, ip_string_size);
TxnDebug("http_trans", "inserted request header 'Client-ip: %s'", ip_string);
break;
default: // don't insert client-ip
break;
}
}
// Add or append to the X-Forwarded-For header
if (s->txn_conf->insert_squid_x_forwarded_for) {
request->value_append_or_set(MIME_FIELD_X_FORWARDED_FOR, MIME_LEN_X_FORWARDED_FOR, ip_string, ip_string_size);
TxnDebug("http_trans", "Appended connecting client's (%s) to the X-Forwards header", ip_string);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : check_request_validity()
// Description: checks to see if incoming request has necessary fields
//
// Input : State, header (can we do this without the state?)
// Output : enum RequestError_t of the error type, if any
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
HttpTransact::RequestError_t
HttpTransact::check_request_validity(State *s, HTTPHdr *incoming_hdr)
{
// Called also on receiving request. Not sure if we need to call this again in case
// the transfer-encoding and content-length headers changed
set_client_request_state(s, incoming_hdr);
if (incoming_hdr == nullptr) {
return NON_EXISTANT_REQUEST_HEADER;
}
if (!(HttpTransactHeaders::is_request_proxy_authorized(incoming_hdr))) {
return FAILED_PROXY_AUTHORIZATION;
}
URL *incoming_url = incoming_hdr->url_get();
int hostname_len;
const char *hostname = incoming_hdr->host_get(&hostname_len);
if (hostname == nullptr) {
return MISSING_HOST_FIELD;
}
if (hostname_len >= MAXDNAME || hostname_len <= 0 || memchr(hostname, '\0', hostname_len)) {
return BAD_HTTP_HEADER_SYNTAX;
}
int scheme = incoming_url->scheme_get_wksidx();
int method = incoming_hdr->method_get_wksidx();
if (!((scheme == URL_WKSIDX_HTTP) && (method == HTTP_WKSIDX_GET))) {
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS && method != HTTP_WKSIDX_CONNECT &&
!((scheme == URL_WKSIDX_WS || scheme == URL_WKSIDX_WSS) && s->is_websocket)) {
if (scheme < 0) {
return NO_REQUEST_SCHEME;
} else {
return SCHEME_NOT_SUPPORTED;
}
}
if (!HttpTransactHeaders::is_this_method_supported(scheme, method)) {
return METHOD_NOT_SUPPORTED;
}
if ((method == HTTP_WKSIDX_CONNECT) && !s->transparent_passthrough &&
(!is_port_in_range(incoming_hdr->url_get()->port_get(), s->http_config_param->connect_ports))) {
return BAD_CONNECT_PORT;
}
if (s->client_info.transfer_encoding == CHUNKED_ENCODING && incoming_hdr->version_get() < HTTP_1_1) {
// Per spec, Transfer-Encoding is only supported in HTTP/1.1. For earlier
// versions, we must reject Transfer-Encoding rather than interpret it
// since downstream proxies may ignore the chunk header and rely upon the
// Content-Length, or interpret the body some other way. These
// differences in interpretation may open up the door to compatibility
// issues. To protect against this, we reply with a 4xx if the client
// uses Transfer-Encoding with HTTP versions that do not support it.
return UNACCEPTABLE_TE_REQUIRED;
}
// Require Content-Length/Transfer-Encoding for POST/PUSH/PUT
if ((scheme == URL_WKSIDX_HTTP || scheme == URL_WKSIDX_HTTPS) &&
(method == HTTP_WKSIDX_POST || method == HTTP_WKSIDX_PUSH || method == HTTP_WKSIDX_PUT) &&
s->client_info.transfer_encoding != CHUNKED_ENCODING) {
// In normal operation there will always be a ua_txn at this point, but in one of the -R1 regression tests a request is
// createdindependent of a transaction and this method is called, so we must null check
if (!s->state_machine->ua_txn || s->state_machine->ua_txn->is_chunked_encoding_supported()) {
// See if we need to insert a chunked header
if (!incoming_hdr->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
if (s->txn_conf->post_check_content_length_enabled) {
return NO_POST_CONTENT_LENGTH;
} else {
// Stuff in a TE setting so we treat this as chunked, sort of.
s->client_info.transfer_encoding = HttpTransact::CHUNKED_ENCODING;
incoming_hdr->value_append(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING, HTTP_VALUE_CHUNKED,
HTTP_LEN_CHUNKED, true);
}
}
if (HTTP_UNDEFINED_CL == s->hdr_info.request_content_length) {
return INVALID_POST_CONTENT_LENGTH;
}
}
}
}
// Check whether a Host header field is missing in the request.
if (!incoming_hdr->presence(MIME_PRESENCE_HOST) && incoming_hdr->version_get() != HTTP_0_9) {
// Update the number of incoming 1.0 or 1.1 requests that do
// not contain Host header fields.
HTTP_INCREMENT_DYN_STAT(http_missing_host_hdr_stat);
}
// Did the client send a "TE: identity;q=0"? We have to respond
// with an error message because we only support identity
// Transfer Encoding.
if (incoming_hdr->presence(MIME_PRESENCE_TE)) {
MIMEField *te_field = incoming_hdr->field_find(MIME_FIELD_TE, MIME_LEN_TE);
HTTPValTE *te_val;
if (te_field) {
HdrCsvIter csv_iter;
int te_raw_len;
const char *te_raw = csv_iter.get_first(te_field, &te_raw_len);
while (te_raw) {
te_val = http_parse_te(te_raw, te_raw_len, &s->arena);
if (te_val->encoding == HTTP_VALUE_IDENTITY) {
if (te_val->qvalue <= 0.0) {
s->arena.free(te_val, sizeof(HTTPValTE));
return UNACCEPTABLE_TE_REQUIRED;
}
}
s->arena.free(te_val, sizeof(HTTPValTE));
te_raw = csv_iter.get_next(&te_raw_len);
}
}
}
return NO_REQUEST_HEADER_ERROR;
}
void
HttpTransact::set_client_request_state(State *s, HTTPHdr *incoming_hdr)
{
if (incoming_hdr == nullptr) {
return;
}
// Set transfer_encoding value
if (incoming_hdr->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_hdr->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
if (field) {
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED) {
s->client_info.transfer_encoding = CHUNKED_ENCODING;
break;
}
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
}
/////////////////////////////////////////////////////
// get request content length //
// To avoid parsing content-length twice, we set //
// s->hdr_info.request_content_length here rather //
// than in initialize_state_variables_from_request //
/////////////////////////////////////////////////////
if (incoming_hdr->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
s->hdr_info.request_content_length = incoming_hdr->get_content_length();
} else {
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL; // content length less than zero is invalid
}
TxnDebug("http_trans", "set req cont length to %" PRId64, s->hdr_info.request_content_length);
}
HttpTransact::ResponseError_t
HttpTransact::check_response_validity(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS ||
s->next_hop_scheme == URL_WKSIDX_TUNNEL);
if (incoming_hdr == nullptr) {
return NON_EXISTANT_RESPONSE_HEADER;
}
if (incoming_hdr->type_get() != HTTP_TYPE_RESPONSE) {
return NOT_A_RESPONSE_HEADER;
}
HTTPStatus incoming_status = incoming_hdr->status_get();
if (!incoming_status) {
return MISSING_STATUS_CODE;
}
if (incoming_status == HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return STATUS_CODE_SERVER_ERROR;
}
if (!incoming_hdr->presence(MIME_PRESENCE_DATE)) {
incoming_hdr->set_date(s->current.now);
}
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
if (incoming_hdr->presence(MIME_PRESENCE_DATE)) {
time_t date_value = incoming_hdr->get_date();
if (date_value <= 0) {
TxnDebug("http_trans", "Bogus date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
} else {
TxnDebug("http_trans", "No date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
#endif
return NO_RESPONSE_HEADER_ERROR;
}
bool
HttpTransact::handle_internal_request(State * /* s ATS_UNUSED */, HTTPHdr *incoming_hdr)
{
URL *url;
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
if (incoming_hdr->method_get_wksidx() != HTTP_WKSIDX_GET) {
return false;
}
url = incoming_hdr->url_get();
int scheme = url->scheme_get_wksidx();
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS) {
return false;
}
if (!statPagesManager.is_stat_page(url)) {
return false;
}
return true;
}
bool
HttpTransact::handle_trace_and_options_requests(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
// This only applies to TRACE and OPTIONS
if ((s->method != HTTP_WKSIDX_TRACE) && (s->method != HTTP_WKSIDX_OPTIONS)) {
return false;
}
// If there is no Max-Forwards request header, just return false.
if (!incoming_hdr->presence(MIME_PRESENCE_MAX_FORWARDS)) {
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
return false;
}
int max_forwards = incoming_hdr->get_max_forwards();
if (max_forwards <= 0) {
//////////////////////////////////////////////
// if max-forward is 0 the request must not //
// be forwarded to the origin server. //
//////////////////////////////////////////////
TxnDebug("http_trans", "[handle_trace] max-forwards: 0, building response...");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
////////////////////////////////////////
// if method is trace we should write //
// the request header as the body. //
////////////////////////////////////////
if (s->method == HTTP_WKSIDX_TRACE) {
TxnDebug("http_trans", "[handle_trace] inserting request in body.");
int req_length = incoming_hdr->length_get();
HTTP_RELEASE_ASSERT(req_length > 0);
s->free_internal_msg_buffer();
s->internal_msg_buffer_size = req_length * 2;
if (s->internal_msg_buffer_size <= BUFFER_SIZE_FOR_INDEX(s->http_config_param->max_msg_iobuf_index)) {
s->internal_msg_buffer_fast_allocator_size =
buffer_size_to_index(s->internal_msg_buffer_size, s->http_config_param->max_msg_iobuf_index);
s->internal_msg_buffer = static_cast<char *>(ioBufAllocator[s->internal_msg_buffer_fast_allocator_size].alloc_void());
} else {
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer = static_cast<char *>(ats_malloc(s->internal_msg_buffer_size));
}
// clear the stupid buffer
memset(s->internal_msg_buffer, '\0', s->internal_msg_buffer_size);
int offset = 0;
int used = 0;
int done;
done = incoming_hdr->print(s->internal_msg_buffer, s->internal_msg_buffer_size, &used, &offset);
HTTP_RELEASE_ASSERT(done);
s->internal_msg_buffer_size = used;
s->internal_msg_buffer_type = ats_strdup("message/http");
s->hdr_info.client_response.set_content_length(used);
} else {
// For OPTIONS request insert supported methods in ALLOW field
TxnDebug("http_trans", "[handle_options] inserting methods in Allow.");
HttpTransactHeaders::insert_supported_methods_in_response(&s->hdr_info.client_response, s->scheme);
}
return true;
} else { /* max-forwards != 0 */
// Logically want to make sure max_forwards is a legitimate non-zero non-negative integer
// Since max_forwards is a signed integer, no sense making sure it is less than INT_MAX.
// Would be negative in that case. Already checked negative in the other case. Noted by coverity
--max_forwards;
TxnDebug("http_trans", "[handle_trace_options] Decrementing max_forwards to %d", max_forwards);
incoming_hdr->set_max_forwards(max_forwards);
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
return false;
}
void
HttpTransact::bootstrap_state_variables_from_request(State *s, HTTPHdr *incoming_request)
{
s->current.now = s->client_request_time = ink_local_time();
s->client_info.http_version = incoming_request->version_get();
}
void
HttpTransact::initialize_state_variables_from_request(State *s, HTTPHdr *obsolete_incoming_request)
{
HTTPHdr *incoming_request = &s->hdr_info.client_request;
// Temporary, until we're confident that the second argument is redundant.
ink_assert(incoming_request == obsolete_incoming_request);
int host_len;
const char *host_name = incoming_request->host_get(&host_len);
// check if the request is conditional (IMS or INM)
if (incoming_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_NONE_MATCH)) {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
} else {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_SIMPLE);
}
// Is the user agent Keep-Alive?
// If we are transparent or if the user-agent is following
// the 1.1 spec, we will see a "Connection" header to
// indicate a keep-alive. However most user-agents including
// MSIE3.0, Netscape4.04 and Netscape3.01 send Proxy-Connection
// when they are configured to use a proxy. Proxy-Connection
// is not in the spec but was added to prevent problems
// with a dumb proxy forwarding all headers (including "Connection")
// to the origin server and confusing it. In cases of transparent
// deployments we use the Proxy-Connect hdr (to be as transparent
// as possible).
MIMEField *pc = incoming_request->field_find(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// If we need to send a close header later check to see if it should be "Proxy-Connection"
if (pc != nullptr) {
s->client_info.proxy_connect_hdr = true;
}
NetVConnection *vc = nullptr;
if (s->state_machine->ua_txn) {
vc = s->state_machine->ua_txn->get_netvc();
}
if (vc) {
s->request_data.incoming_port = vc->get_local_port();
s->request_data.internal_txn = vc->get_is_internal_request();
}
// If this is an internal request, never keep alive
if (!s->txn_conf->keep_alive_enabled_in) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else if (vc && vc->get_is_internal_request()) {
// Following the trail of JIRAs back from TS-4960, there can be issues with
// EOS event delivery when using keepalive on internal PluginVC session. As
// an interim measure, if proxy.config.http.keepalive_internal_vc is set,
// we will obey the incoming transaction's keepalive request.
s->client_info.keep_alive =
s->http_config_param->keepalive_internal_vc ? incoming_request->keep_alive_get() : HTTP_NO_KEEPALIVE;
} else {
s->client_info.keep_alive = incoming_request->keep_alive_get();
}
if (!s->server_info.name || s->redirect_info.redirect_in_process) {
s->server_info.name = s->arena.str_store(host_name, host_len);
}
s->next_hop_scheme = s->scheme = incoming_request->url_get()->scheme_get_wksidx();
// With websockets we need to make an outgoing request
// as http or https.
// We switch back to HTTP or HTTPS for the next hop
// I think this is required to properly establish outbound WSS connections,
// you'll need to force the next hop to be https.
if (s->is_websocket) {
if (s->next_hop_scheme == URL_WKSIDX_WS) {
TxnDebug("http_trans", "Switching WS next hop scheme to http.");
s->next_hop_scheme = URL_WKSIDX_HTTP;
s->scheme = URL_WKSIDX_HTTP;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
} else if (s->next_hop_scheme == URL_WKSIDX_WSS) {
TxnDebug("http_trans", "Switching WSS next hop scheme to https.");
s->next_hop_scheme = URL_WKSIDX_HTTPS;
s->scheme = URL_WKSIDX_HTTPS;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
} else {
Error("Scheme doesn't match websocket...!");
}
s->current.mode = GENERIC_PROXY;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
s->method = incoming_request->method_get_wksidx();
if (s->method == HTTP_WKSIDX_GET) {
HTTP_INCREMENT_DYN_STAT(http_get_requests_stat);
} else if (s->method == HTTP_WKSIDX_HEAD) {
HTTP_INCREMENT_DYN_STAT(http_head_requests_stat);
} else if (s->method == HTTP_WKSIDX_POST) {
HTTP_INCREMENT_DYN_STAT(http_post_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUT) {
HTTP_INCREMENT_DYN_STAT(http_put_requests_stat);
} else if (s->method == HTTP_WKSIDX_CONNECT) {
HTTP_INCREMENT_DYN_STAT(http_connect_requests_stat);
} else if (s->method == HTTP_WKSIDX_DELETE) {
HTTP_INCREMENT_DYN_STAT(http_delete_requests_stat);
} else if (s->method == HTTP_WKSIDX_PURGE) {
HTTP_INCREMENT_DYN_STAT(http_purge_requests_stat);
} else if (s->method == HTTP_WKSIDX_TRACE) {
HTTP_INCREMENT_DYN_STAT(http_trace_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_INCREMENT_DYN_STAT(http_push_requests_stat);
} else if (s->method == HTTP_WKSIDX_OPTIONS) {
HTTP_INCREMENT_DYN_STAT(http_options_requests_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_extension_method_requests_stat);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
s->squid_codes.log_code = SQUID_LOG_TCP_MISS;
s->hdr_info.extension_method = true;
}
// if transfer encoding is chunked content length is undefined
if (s->client_info.transfer_encoding == CHUNKED_ENCODING) {
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
}
s->request_data.hdr = &s->hdr_info.client_request;
s->request_data.hostname_str = s->arena.str_store(host_name, host_len);
ats_ip_copy(&s->request_data.src_ip, &s->client_info.src_addr);
memset(&s->request_data.dest_ip, 0, sizeof(s->request_data.dest_ip));
if (vc) {
s->request_data.incoming_port = vc->get_local_port();
s->pp_info.version = vc->get_proxy_protocol_version();
if (s->pp_info.version != ProxyProtocolVersion::UNDEFINED) {
ats_ip_copy(s->pp_info.src_addr, vc->get_proxy_protocol_src_addr());
ats_ip_copy(s->pp_info.dst_addr, vc->get_proxy_protocol_dst_addr());
}
}
s->request_data.xact_start = s->client_request_time;
s->request_data.api_info = &s->api_info;
s->request_data.cache_info_lookup_url = &s->cache_info.lookup_url;
s->request_data.cache_info_parent_selection_url = &s->cache_info.parent_selection_url;
/////////////////////////////////////////////
// Do dns lookup for the host. We need //
// the expanded host for cache lookup, and //
// the host ip for reverse proxy. //
/////////////////////////////////////////////
s->dns_info.looking_up = ORIGIN_SERVER;
s->dns_info.lookup_name = s->server_info.name;
}
void
HttpTransact::initialize_state_variables_from_response(State *s, HTTPHdr *incoming_response)
{
/* check if the server permits caching */
s->cache_info.directives.does_server_permit_storing =
HttpTransactHeaders::does_server_allow_response_to_be_stored(&s->hdr_info.server_response);
/*
* A stupid moronic broken pathetic excuse
* for a server may send us a keep alive response even
* if we sent "Connection: close" We need check the response
* header regardless of what we sent to the server
*/
s->current.server->keep_alive = s->hdr_info.server_response.keep_alive_get();
// Don't allow an upgrade request to Keep Alive
if (s->is_upgrade_request) {
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
if (s->current.server->keep_alive == HTTP_KEEPALIVE) {
TxnDebug("http_hdrs", "Server is keep-alive.");
} else if (s->state_machine->ua_txn && s->state_machine->ua_txn->is_outbound_transparent() &&
s->state_machine->t_state.http_config_param->use_client_source_port) {
/* If we are reusing the client<->ATS 4-tuple for ATS<->server then if the server side is closed, we can't
re-open it because the 4-tuple may still be in the processing of shutting down. So if the server isn't
keep alive we must turn that off for the client as well.
*/
s->state_machine->t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
HTTPStatus status_code = incoming_response->status_get();
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.response_content_length = 0;
s->hdr_info.trust_response_cl = true;
} else {
// This code used to discriminate CL: headers when the origin disabled keep-alive.
if (incoming_response->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
int64_t cl = incoming_response->get_content_length();
s->hdr_info.response_content_length = (cl >= 0) ? cl : HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
}
}
if (incoming_response->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_response->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
ink_assert(field != nullptr);
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED && !is_response_body_precluded(status_code, s->method)) {
TxnDebug("http_hdrs", "transfer encoding: chunked!");
s->current.server->transfer_encoding = CHUNKED_ENCODING;
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
// OBJECTIVE: Since we are dechunking the request remove the
// chunked value If this is the only value, we need to remove
// the whole field.
MIMEField *new_enc_field = nullptr;
HdrCsvIter new_enc_iter;
int new_enc_len;
const char *new_enc_val = new_enc_iter.get_first(field, &new_enc_len);
// Loop over the all the values in existing Trans-enc header and
// copy the ones that aren't our chunked value to a new field
while (new_enc_val) {
const char *new_wks_value = hdrtoken_string_to_wks(new_enc_val, new_enc_len);
if (new_wks_value != wks_value) {
if (new_enc_field) {
new_enc_field->value_append(incoming_response->m_heap, incoming_response->m_mime, new_enc_val, new_enc_len, true);
} else {
new_enc_field = incoming_response->field_create();
incoming_response->field_value_set(new_enc_field, new_enc_val, new_enc_len);
}
}
new_enc_val = new_enc_iter.get_next(&new_enc_len);
}
// We're done with the old field since we copied out everything
// we needed
incoming_response->field_delete(field);
// If there is a new field (ie: there was more than one
// transfer-encoding), insert it to the list
if (new_enc_field) {
new_enc_field->name_set(incoming_response->m_heap, incoming_response->m_mime, MIME_FIELD_TRANSFER_ENCODING,
MIME_LEN_TRANSFER_ENCODING);
incoming_response->field_attach(new_enc_field);
}
return;
} // if (enc_value == CHUNKED)
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
s->current.server->transfer_encoding = NO_TRANSFER_ENCODING;
}
bool
HttpTransact::is_cache_response_returnable(State *s)
{
if (s->cache_control.never_cache) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONFIG);
return false;
}
if (!s->cache_info.directives.does_client_permit_lookup) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CLIENT);
return false;
}
if (!HttpTransactHeaders::is_method_cacheable(s->http_config_param, s->method) && s->api_resp_cacheable == false) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
return false;
}
// We may be caching responses to methods other than GET, such as POST. Make
// sure that our cached resource has a method that matches the incoming
// requests's method. If not, then we cannot reply with the cached resource.
// That is, we cannot reply to an incoming GET request with a response to a
// previous POST request. The only exception is replying a HEAD request with
// a cached GET request as neither are destructive
int const client_request_method = s->hdr_info.client_request.method_get_wksidx();
int const cached_request_method = s->cache_info.object_read->request_get()->method_get_wksidx();
if (client_request_method != cached_request_method &&
(client_request_method != HTTP_WKSIDX_HEAD || cached_request_method != HTTP_WKSIDX_GET)) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
return false;
}
// If cookies in response and no TTL set, we do not cache the doc
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching(static_cast<int>(s->txn_conf->cache_responses_to_cookies), &s->hdr_info.client_request,
s->cache_info.object_read->response_get(), s->cache_info.object_read->request_get())) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_COOKIE);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_stale_cache_response_returnable()
// Description: check if a stale cached response is returnable to a client
//
// Input : State
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_stale_cache_response_returnable(State *s)
{
HTTPHdr *cached_response = s->cache_info.object_read->response_get();
// First check if client allows cached response
// Note does_client_permit_lookup was set to
// does_client_Request_permit_cached_response()
// in update_cache_control_information_from_config().
if (!s->cache_info.directives.does_client_permit_lookup) {
return false;
}
// Spec says that we can not serve a stale document with a
// "must-revalidate header"
// How about "s-maxage" and "no-cache" directives?
uint32_t cc_mask;
cc_mask = (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE | MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE |
MIME_COOKED_MASK_CC_NO_CACHE | MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_S_MAXAGE);
if ((cached_response->get_cooked_cc_mask() & cc_mask) || cached_response->is_pragma_no_cache_set()) {
TxnDebug("http_trans", "document headers prevent serving stale");
return false;
}
// See how old the document really is. We don't want create a
// stale content museum of documents that are no longer available
time_t current_age = HttpTransactHeaders::calculate_document_age(s->cache_info.object_read->request_sent_time_get(),
s->cache_info.object_read->response_received_time_get(),
cached_response, cached_response->get_date(), s->current.now);
// Negative age is overflow
if ((current_age < 0) || (current_age > s->txn_conf->cache_max_stale_age)) {
TxnDebug("http_trans", "document age is too large %" PRId64, (int64_t)current_age);
return false;
}
// If the stale document requires authorization, we can't return it either.
Authentication_t auth_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, cached_response);
if (auth_needed != AUTHENTICATION_SUCCESS) {
TxnDebug("http_trans", "authorization prevent serving stale");
return false;
}
TxnDebug("http_trans", "can serve stale");
return true;
}
bool
HttpTransact::url_looks_dynamic(URL *url)
{
const char *p_start, *p, *t;
static const char *asp = ".asp";
const char *part;
int part_length;
if (url->scheme_get_wksidx() != URL_WKSIDX_HTTP && url->scheme_get_wksidx() != URL_WKSIDX_HTTPS) {
return false;
}
////////////////////////////////////////////////////////////
// (1) If URL contains query stuff in it, call it dynamic //
////////////////////////////////////////////////////////////
part = url->params_get(&part_length);
if (part != nullptr) {
return true;
}
part = url->query_get(&part_length);
if (part != nullptr) {
return true;
}
///////////////////////////////////////////////
// (2) If path ends in "asp" call it dynamic //
///////////////////////////////////////////////
part = url->path_get(&part_length);
if (part) {
p = &part[part_length - 1];
t = &asp[3];
while (p != part) {
if (ParseRules::ink_tolower(*p) == ParseRules::ink_tolower(*t)) {
p -= 1;
t -= 1;
if (t == asp) {
return true;
}
} else {
break;
}
}
}
/////////////////////////////////////////////////////////////////
// (3) If the path of the url contains "cgi", call it dynamic. //
/////////////////////////////////////////////////////////////////
if (part && part_length >= 3) {
for (p_start = part; p_start <= &part[part_length - 3]; p_start++) {
if (((p_start[0] == 'c') || (p_start[0] == 'C')) && ((p_start[1] == 'g') || (p_start[1] == 'G')) &&
((p_start[2] == 'i') || (p_start[2] == 'I'))) {
return (true);
}
}
}
return (false);
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_request_cache_lookupable()
// Description: check if a request should be looked up in cache
//
// Input : State, request header
// Output : true or false
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_request_cache_lookupable(State *s)
{
// ummm, someone has already decided that proxy should tunnel
if (s->current.mode == TUNNELLING_PROXY) {
return false;
}
// don't bother with remaining checks if we already did a cache lookup
if (s->cache_info.lookup_count > 0) {
return true;
}
// is cache turned on?
if (!s->txn_conf->cache_http) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_CACHE_OFF);
return false;
}
// GET, HEAD, POST, DELETE, and PUT are all cache lookupable
if (!HttpTransactHeaders::is_method_cache_lookupable(s->method) && s->api_req_cacheable == false) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
return false;
}
// don't cache page if URL "looks dynamic" and this filter is enabled
// We can do the check in is_response_cacheable() or here.
// It may be more efficient if we are not going to cache dynamic looking urls
// (the default config?) since we don't even need to do cache lookup.
// So for the time being, it'll be left here.
// If url looks dynamic but a ttl is set, request is cache lookupable
if ((!s->txn_conf->cache_urls_that_look_dynamic) && url_looks_dynamic(s->hdr_info.client_request.url_get()) &&
(s->cache_control.ttl_in_cache <= 0)) {
// We do not want to forward the request for a dynamic URL onto the
// origin server if the value of the Max-Forwards header is zero.
int max_forwards = -1;
if (s->hdr_info.client_request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
if (max_forwards_f) {
max_forwards = max_forwards_f->value_get_int();
}
}
if (max_forwards != 0) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_URL);
return false;
}
}
// Don't look in cache if it's a RANGE request but the cache is not enabled for RANGE.
if (!s->txn_conf->cache_range_lookup && s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_HEADER_FIELD);
return false;
}
// Even with "no-cache" directive, we want to do a cache lookup
// because we need to update our cached copy.
// Client request "no-cache" directive is handle elsewhere:
// update_cache_control_information_from_config()
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : response_cacheable_indicated_by_cc()
// Description: check if a response is cacheable as indicated by Cache-Control
//
// Input : Response header
// Output : -1, 0, or +1
//
// Details :
// (1) return -1 if cache control indicates response not cacheable,
// ie, with no-store, or private directives;
// (2) return +1 if cache control indicates response cacheable
// ie, with public, max-age, s-maxage, must-revalidate, or proxy-revalidate;
// (3) otherwise, return 0 if cache control does not indicate.
//
///////////////////////////////////////////////////////////////////////////////
int
response_cacheable_indicated_by_cc(HTTPHdr *response)
{
uint32_t cc_mask;
// the following directives imply not cacheable
cc_mask = (MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_PRIVATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return -1;
}
// the following directives imply cacheable
cc_mask = (MIME_COOKED_MASK_CC_PUBLIC | MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE |
MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return 1;
}
// otherwise, no indication
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_response_cacheable()
// Description: check if a response is cacheable
//
// Input : State, request header, response header
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_response_cacheable(State *s, HTTPHdr *request, HTTPHdr *response)
{
// If the use_client_target_addr is specified but the client
// specified OS addr does not match any of trafficserver's looked up
// host addresses, do not allow cache. This may cause DNS cache poisoning
// of other trafficserver clients. The flag is set in the
// process_host_db_info method
if (!s->dns_info.lookup_validated && s->client_info.is_transparent) {
TxnDebug("http_trans", "Lookup not validated. Possible DNS cache poison. Don't cache");
return false;
}
// the plugin may decide we don't want to cache the response
if (s->api_server_response_no_store) {
return false;
}
// if method is not GET or HEAD, do not cache.
// Note: POST is also cacheable with Expires or Cache-control.
// but due to INKqa11567, we are not caching POST responses.
// Basically, the problem is the resp for POST url1 req should not
// be served to a GET url1 request, but we just match URL not method.
int req_method = request->method_get_wksidx();
if (!(HttpTransactHeaders::is_method_cacheable(s->http_config_param, req_method)) && s->api_req_cacheable == false) {
TxnDebug("http_trans", "only GET, and some HEAD and POST are cacheable");
return false;
}
// TxnDebug("http_trans", "[is_response_cacheable] method is cacheable");
// If the request was not looked up in the cache, the response
// should not be cached (same subsequent requests will not be
// looked up, either, so why cache this).
if (!(is_request_cache_lookupable(s))) {
TxnDebug("http_trans", "request is not cache lookupable, response is not cacheable");
return false;
}
// already has a fresh copy in the cache
if (s->range_setup == RANGE_NOT_HANDLED) {
return false;
}
// Check whether the response is cacheable based on its cookie
// If there are cookies in response but a ttl is set, allow caching
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching(static_cast<int>(s->txn_conf->cache_responses_to_cookies), request, response)) {
TxnDebug("http_trans", "response has uncachable cookies, response is not cacheable");
return false;
}
// if server spits back a WWW-Authenticate
if ((s->txn_conf->cache_ignore_auth) == 0 && response->presence(MIME_PRESENCE_WWW_AUTHENTICATE)) {
TxnDebug("http_trans", "response has WWW-Authenticate, response is not cacheable");
return false;
}
// does server explicitly forbid storing?
// If OS forbids storing but a ttl is set, allow caching
if (!s->cache_info.directives.does_server_permit_storing && (s->cache_control.ttl_in_cache <= 0)) {
TxnDebug("http_trans", "server does not permit storing and config file does not "
"indicate that server directive should be ignored");
return false;
}
// TxnDebug("http_trans", "[is_response_cacheable] server permits storing");
// does config explicitly forbid storing?
// ttl overrides other config parameters
if ((!s->cache_info.directives.does_config_permit_storing && (s->cache_control.ttl_in_cache <= 0)) ||
(s->cache_control.never_cache)) {
TxnDebug("http_trans", "config doesn't allow storing, and cache control does not "
"say to ignore no-cache and does not specify never-cache or a ttl");
return false;
}
// TxnDebug("http_trans", "[is_response_cacheable] config permits storing");
// does client explicitly forbid storing?
if (!s->cache_info.directives.does_client_permit_storing && !s->cache_control.ignore_client_no_cache) {
TxnDebug("http_trans", "client does not permit storing, "
"and cache control does not say to ignore client no-cache");
return false;
}
TxnDebug("http_trans", "client permits storing");
HTTPStatus response_code = response->status_get();
// caching/not-caching based on required headers
// only makes sense when the server sends back a
// 200 and a document.
if (response_code == HTTP_STATUS_OK) {
// If a ttl is set: no header required for caching
// otherwise: follow parameter http.cache.required_headers
if (s->cache_control.ttl_in_cache <= 0) {
uint32_t cc_mask = (MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE);
// server did not send expires header or last modified
// and we are configured to not cache without them.
switch (s->txn_conf->cache_required_headers) {
case HttpConfigParams::CACHE_REQUIRED_HEADERS_NONE:
TxnDebug("http_trans", "no response headers required");
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_AT_LEAST_LAST_MODIFIED:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask) &&
!response->get_last_modified()) {
TxnDebug("http_trans", "last_modified, expires, or max-age is required");
s->squid_codes.hit_miss_code = ((response->get_date() == 0) ? (SQUID_MISS_HTTP_NO_DLE) : (SQUID_MISS_HTTP_NO_LE));
return false;
}
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_CACHE_CONTROL:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask)) {
TxnDebug("http_trans", "expires header or max-age is required");
return false;
}
break;
default:
break;
}
}
}
// do not cache partial content - Range response
if (response_code == HTTP_STATUS_PARTIAL_CONTENT || response_code == HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
TxnDebug("http_trans", "response code %d - don't cache", response_code);
return false;
}
// check if cache control overrides default cacheability
int indicator;
indicator = response_cacheable_indicated_by_cc(response);
if (indicator > 0) { // cacheable indicated by cache control header
TxnDebug("http_trans", "YES by response cache control");
// even if it is authenticated, this is cacheable based on regular rules
s->www_auth_content = CACHE_AUTH_NONE;
return true;
} else if (indicator < 0) { // not cacheable indicated by cache control header
// If a ttl is set, allow caching even if response contains
// Cache-Control headers to prevent caching
if (s->cache_control.ttl_in_cache > 0) {
TxnDebug("http_trans", "Cache-control header directives in response overridden by ttl in %s", ts::filename::CACHE);
} else {
TxnDebug("http_trans", "NO by response cache control");
return false;
}
}
// else no indication by cache control header
// continue to determine cacheability
if (response->presence(MIME_PRESENCE_EXPIRES)) {
TxnDebug("http_trans", "YES response w/ Expires");
return true;
}
// if it's a 302 or 307 and no positive indicator from cache-control, reject
if (response_code == HTTP_STATUS_MOVED_TEMPORARILY || response_code == HTTP_STATUS_TEMPORARY_REDIRECT) {
TxnDebug("http_trans", "cache-control or expires header is required for 302");
return false;
}
// if it's a POST request and no positive indicator from cache-control
if (req_method == HTTP_WKSIDX_POST) {
// allow caching for a POST requests w/o Expires but with a ttl
if (s->cache_control.ttl_in_cache > 0) {
TxnDebug("http_trans", "POST method with a TTL");
} else {
TxnDebug("http_trans", "NO POST w/o Expires or CC");
return false;
}
}
if ((response_code == HTTP_STATUS_OK) || (response_code == HTTP_STATUS_NOT_MODIFIED) ||
(response_code == HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION) || (response_code == HTTP_STATUS_MOVED_PERMANENTLY) ||
(response_code == HTTP_STATUS_MULTIPLE_CHOICES) || (response_code == HTTP_STATUS_GONE)) {
TxnDebug("http_trans", "YES response code seems fine");
return true;
}
// Notice that the following are not overridable by negative caching.
if (response_code == HTTP_STATUS_SEE_OTHER || response_code == HTTP_STATUS_UNAUTHORIZED ||
response_code == HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
return false;
}
// The response code does not look appropriate for caching. Check, however,
// whether the user has specified it should be cached via negative response
// caching configuration.
if (is_negative_caching_appropriate(s)) {
return true;
}
return false;
/* Since we weren't caching response obtained with
Authorization (the cache control stuff was commented out previously)
I've moved this check to is_request_cache_lookupable().
We should consider this matter further. It is unclear
how many sites actually add Cache-Control headers for Authorized content.
*/
}
bool
HttpTransact::is_request_valid(State *s, HTTPHdr *incoming_request)
{
RequestError_t incoming_error;
URL *url = nullptr;
if (incoming_request) {
url = incoming_request->url_get();
}
incoming_error = check_request_validity(s, incoming_request);
switch (incoming_error) {
case NO_REQUEST_HEADER_ERROR:
TxnDebug("http_trans", "no request header errors");
break;
case FAILED_PROXY_AUTHORIZATION:
TxnDebug("http_trans", "failed proxy authorization");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required",
"access#proxy_auth_required");
return false;
case NON_EXISTANT_REQUEST_HEADER:
/* fall through */
case BAD_HTTP_HEADER_SYNTAX: {
TxnDebug("http_trans", "non-existent/bad header");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error");
return false;
}
case MISSING_HOST_FIELD:
////////////////////////////////////////////////////////////////////
// FIX: are we sure the following logic is right? it seems that //
// we shouldn't complain about the missing host header until //
// we know we really need one --- are we sure we need a host //
// header at this point? //
// //
// FIX: also, let's clean up the transparency code to remove the //
// SunOS conditionals --- we will be transparent on all //
// platforms soon! in fact, I really want a method that i //
// can call for each transaction to say if the transaction //
// is a forward proxy request, a transparent request, a //
// reverse proxy request, etc --- the detail of how we //
// determine the cases should be hidden behind the method. //
////////////////////////////////////////////////////////////////////
TxnDebug("http_trans", "missing host field");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_config_param->reverse_proxy_enabled) { // host header missing and reverse proxy on
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host");
} else {
// host header missing and reverse proxy off
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Required In Request", "request#no_host");
}
return false;
case SCHEME_NOT_SUPPORTED:
case NO_REQUEST_SCHEME: {
TxnDebug("http_trans", "unsupported or missing request scheme");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Unsupported URL Scheme", "request#scheme_unsupported");
return false;
}
/* fall through */
case METHOD_NOT_SUPPORTED:
TxnDebug("http_trans", "unsupported method");
s->current.mode = TUNNELLING_PROXY;
return true;
case BAD_CONNECT_PORT:
int port;
port = url ? url->port_get() : 0;
TxnDebug("http_trans", "%d is an invalid connect port", port);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Tunnel Forbidden", "access#connect_forbidden");
return false;
case NO_POST_CONTENT_LENGTH: {
TxnDebug("http_trans", "post request without content length");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_LENGTH_REQUIRED, "Content Length Required", "request#no_content_length");
return false;
}
case UNACCEPTABLE_TE_REQUIRED: {
TxnDebug("http_trans", "TE required is unacceptable.");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_ACCEPTABLE, "Transcoding Not Available", "transcoding#unsupported");
return false;
}
case INVALID_POST_CONTENT_LENGTH: {
TxnDebug("http_trans", "post request with negative content length value");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Content Length", "request#invalid_content_length");
return false;
}
default:
return true;
}
return true;
}
// bool HttpTransact::is_request_retryable
//
// In the general case once bytes have been sent on the wire the request cannot be retried.
// The reason we cannot retry is that the rfc2616 does not make any guarantees about the
// retry-ability of a request. In fact in the reverse proxy case it is quite common for GET
// requests on the origin to fire tracking events etc. So, as a proxy, once bytes have been ACKd
// by the server we cannot guarantee that the request is safe to retry or redispatch to another server.
// This is distinction of "ACKd" vs "sent" is intended, and has reason. In the case of a
// new origin connection there is little difference, as the chance of a RST between setup
// and the first set of bytes is relatively small. This distinction is more apparent in the
// case where the origin connection is a KA session. In this case, the session may not have
// been used for a long time. In that case, we'll immediately queue up session to send to the
// origin, without any idea of the state of the connection. If the origin is dead (or the connection
// is broken for some other reason) we'll immediately get a RST back. In that case-- since no
// bytes where ACKd by the remote end, we can retry/redispatch the request.
//
bool
HttpTransact::is_request_retryable(State *s)
{
// If safe requests are retryable, it should be safe to retry safe requests irrespective of bytes sent or connection state
// according to RFC the following methods are safe (https://tools.ietf.org/html/rfc7231#section-4.2.1)
// Otherwise, if there was no error establishing the connection (and we sent bytes)-- we cannot retry
if (!HttpTransactHeaders::is_method_safe(s->method) && s->current.state != CONNECTION_ERROR &&
s->state_machine->server_request_hdr_bytes > 0) {
return false;
}
// FIXME: disable the post transform retry currently.
if (s->state_machine->is_post_transform_request()) {
return false;
}
if (s->state_machine->plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// API can override
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_SERVER && s->api_info.retry_intercept_failures == true) {
// This used to be an == comparison, which made no sense. Changed
// to be an assignment, hoping the state is correct.
s->state_machine->plugin_tunnel_type = HTTP_NO_PLUGIN_TUNNEL;
} else {
return false;
}
}
return true;
}
void
HttpTransact::process_quick_http_filter(State *s, int method)
{
// connection already disabled by previous ACL filtering, don't modify it.
if (!s->client_connection_enabled) {
return;
}
// if ipallow rules are disabled by remap then don't modify anything
url_mapping *mp = s->url_map.getMapping();
if (mp && !mp->ip_allow_check_enabled_p) {
return;
}
if (s->state_machine->ua_txn) {
auto &acl = s->state_machine->ua_txn->get_acl();
bool deny_request = !acl.isValid();
int method_str_len = 0;
const char *method_str = nullptr;
if (acl.isValid() && !acl.isAllowAll()) {
if (method != -1) {
deny_request = !acl.isMethodAllowed(method);
} else {
method_str = s->hdr_info.client_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 = s->hdr_info.client_request.method_get(&method_str_len);
}
TxnDebug("ip-allow", "Line %d denial for '%.*s' from %s", acl.source_line(), method_str_len, method_str,
ats_ip_ntop(&s->client_info.src_addr.sa, ipb, sizeof(ipb)));
}
s->client_connection_enabled = false;
}
}
}
bool
HttpTransact::will_this_request_self_loop(State *s)
{
// The self-loop detection for this ATS node will allow up to max_proxy_cycles
// (each time it sees it returns to itself it is one cycle) before declaring a self-looping condition detected.
// If max_proxy_cycles is > 0 then next-hop is disabled since --
// * if first cycle then it is alright okay
// * if not first cycle then will be detected by via string checking the next time that
// it enters the node
int max_proxy_cycles = s->txn_conf->max_proxy_cycles;
////////////////////////////////////////
// check if we are about to self loop //
////////////////////////////////////////
if (s->dns_info.lookup_success) {
TxnDebug("http_transact", "max_proxy_cycles = %d", max_proxy_cycles);
if (max_proxy_cycles == 0) {
in_port_t dst_port = s->hdr_info.client_request.url_get()->port_get(); // going to this port.
in_port_t local_port = s->client_info.dst_addr.host_order_port(); // already connected proxy port.
// It's a loop if connecting to the same port as it already connected to the proxy and
// it's a proxy address or the same address it already connected to.
TxnDebug("http_transact", "dst_port = %d local_port = %d", dst_port, local_port);
if (dst_port == local_port && (ats_ip_addr_eq(s->host_db_info.ip(), &Machine::instance()->ip.sa) ||
ats_ip_addr_eq(s->host_db_info.ip(), s->client_info.dst_addr))) {
switch (s->dns_info.looking_up) {
case ORIGIN_SERVER:
TxnDebug("http_transact", "host ip and port same as local ip and port - bailing");
break;
case PARENT_PROXY:
TxnDebug("http_transact", "parent proxy ip and port same as local ip and port - bailing");
break;
default:
TxnDebug("http_transact", "unknown's ip and port same as local ip and port - bailing");
break;
}
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_LOOP_DETECTED);
HTTP_INCREMENT_DYN_STAT(http_proxy_loop_detected_stat);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Cycle Detected", "request#cycle_detected");
return true;
}
}
// Now check for a loop using the Via string.
int count = 0;
MIMEField *via_field = s->hdr_info.client_request.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
std::string_view uuid{Machine::instance()->uuid.getString()};
while (via_field) {
// No need to waste cycles comma separating the via values since we want to do a match anywhere in the
// in the string. We can just loop over the dup hdr fields
int via_len;
const char *via_string = via_field->value_get(&via_len);
if ((count <= max_proxy_cycles) && via_string) {
std::string_view current{via_field->value_get()};
std::string_view::size_type offset;
TxnDebug("http_transact", "Incoming via: \"%.*s\" --has-- (%s[%s] (%s))", via_len, via_string,
s->http_config_param->proxy_hostname, uuid.data(), s->http_config_param->proxy_request_via_string);
while ((count <= max_proxy_cycles) && (std::string_view::npos != (offset = current.find(uuid)))) {
current.remove_prefix(offset + TS_UUID_STRING_LEN);
count++;
TxnDebug("http_transact", "count = %d current = %.*s", count, static_cast<int>(current.length()), current.data());
}
}
via_field = via_field->m_next_dup;
}
if (count > max_proxy_cycles) {
TxnDebug("http_transact", "count = %d > max_proxy_cycles = %d : detected loop", count, max_proxy_cycles);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_LOOP_DETECTED);
HTTP_INCREMENT_DYN_STAT(http_proxy_mh_loop_detected_stat);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Multi-Hop Cycle Detected", "request#cycle_detected");
return true;
} else {
TxnDebug("http_transact", "count = %d <= max_proxy_cycles = %d : allowing loop", count, max_proxy_cycles);
}
}
return false;
}
/*
* handle_content_length_header(...)
* Function handles the insertion of content length headers into
* header. header CAN equal base.
*/
void
HttpTransact::handle_content_length_header(State *s, HTTPHdr *header, HTTPHdr *base)
{
int64_t cl = HTTP_UNDEFINED_CL;
ink_assert(header->type_get() == HTTP_TYPE_RESPONSE);
if (base->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
cl = base->get_content_length();
if (cl >= 0) {
// header->set_content_length(cl);
ink_assert(header->get_content_length() == cl);
switch (s->source) {
case SOURCE_HTTP_ORIGIN_SERVER:
// We made our decision about whether to trust the
// response content length in init_state_vars_from_response()
if (s->range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
break;
}
// fallthrough
case SOURCE_CACHE:
// if we are doing a single Range: request, calculate the new
// C-L: header
if (s->range_setup == HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
}
////////////////////////////////////////////////
// Make sure that the cache's object size //
// agrees with the Content-Length //
// Otherwise, set the state's machine view //
// of c-l to undefined to turn off K-A //
////////////////////////////////////////////////
else if (s->cache_info.object_read->object_size_get() == cl) {
s->hdr_info.trust_response_cl = true;
} else {
TxnDebug("http_trans", "Content Length header and cache object size mismatch."
"Disabling keep-alive");
s->hdr_info.trust_response_cl = false;
}
break;
case SOURCE_TRANSFORM:
if (s->range_setup == HttpTransact::RANGE_REQUESTED) {
header->set_content_length(s->range_output_cl);
s->hdr_info.trust_response_cl = true;
} else if (s->hdr_info.transform_response_cl == HTTP_UNDEFINED_CL) {
s->hdr_info.trust_response_cl = false;
} else {
s->hdr_info.trust_response_cl = true;
}
break;
default:
ink_release_assert(0);
break;
}
} else {
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
}
TxnDebug("http_trans", "RESPONSE cont len in hdr is %" PRId64, header->get_content_length());
} else {
// No content length header.
// If the source is cache or server returned 304 response,
// we can try to get the content length based on object size.
// Also, we should check the scenario of server sending't a unexpected 304 response for a non conditional request( no cached
// object )
if (s->source == SOURCE_CACHE ||
(s->source == SOURCE_HTTP_ORIGIN_SERVER && s->hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED &&
s->cache_info.object_read != nullptr)) {
// If there is no content-length header, we can
// insert one since the cache knows definitely
// how long the object is unless we're in a
// read-while-write mode and object hasn't been
// written into a cache completely.
cl = s->cache_info.object_read->object_size_get();
if (cl == INT64_MAX) { // INT64_MAX cl in cache indicates rww in progress
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
ink_assert(s->range_setup == RANGE_NONE);
} else if (s->range_setup == RANGE_NOT_TRANSFORM_REQUESTED) {
// if we are doing a single Range: request, calculate the new
// C-L: header
// either the object is in cache or origin returned a 304 Not Modified response. We can still turn this into a proper Range
// response from the cached object.
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
} else {
if (header->status_get() != HTTP_STATUS_NO_CONTENT) {
header->set_content_length(cl);
}
s->hdr_info.trust_response_cl = true;
}
} else {
// Check to see if there is no content length
// header because the response precludes a
// body
if (is_response_body_precluded(header->status_get(), s->method)) {
// We want to be able to do keep-alive here since
// there can't be body so we don't have any
// issues about trusting the body length
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.trust_response_cl = false;
}
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
ink_assert(s->range_setup != RANGE_NOT_TRANSFORM_REQUESTED);
}
}
return;
} /* End HttpTransact::handle_content_length_header */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_request_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from user-agent from <heads>
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_request_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
bool upstream_ka = (s->current.server->keep_alive == HTTP_KEEPALIVE);
ink_assert(heads->type_get() == HTTP_TYPE_REQUEST);
// Check preconditions for Keep-Alive
if (!upstream_ka) {
ka_action = KA_DISABLED;
} else if (ver.get_major() == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
}
// If preconditions are met, figure out what action to take
if (ka_action == KA_UNKNOWN) {
int method = heads->method_get_wksidx();
if (method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_HEAD || method == HTTP_WKSIDX_OPTIONS || method == HTTP_WKSIDX_PURGE ||
method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_TRACE) {
// These methods do not need a content-length header
ka_action = KA_CONNECTION;
} else {
// All remaining methods require a content length header
if (heads->get_content_length() == -1) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
}
ink_assert(ka_action != KA_UNKNOWN);
// Since connection headers are hop-to-hop, strip the
// the ones we received from the user-agent
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (!s->is_upgrade_request) {
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->current.server->keep_alive != HTTP_NO_KEEPALIVE);
if (ver == HTTP_1_0) {
if (s->current.request_to == PARENT_PROXY && parent_is_proxy(s)) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "keep-alive", 10);
} else {
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "keep-alive", 10);
}
}
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_DISABLED:
case KA_CLOSE:
if (s->current.server->keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTP_1_1)) {
/* Had keep-alive */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (s->current.request_to == PARENT_PROXY && parent_is_proxy(s)) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "close", 5);
} else {
ProxyTransaction *svr = s->state_machine->get_server_txn();
if (svr) {
svr->set_close_connection(*heads);
}
}
}
// Note: if we are 1.1, we always need to send the close
// header since persistent connections are the default
break;
default:
ink_assert(0);
break;
}
} else { /* websocket connection */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
if (s->is_websocket) {
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
}
} /* End HttpTransact::handle_request_keep_alive_headers */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_response_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from origin server from <heads>
//
// Adds the appropriate Transfer-Encoding: chunked header.
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
ink_assert(heads->type_get() == HTTP_TYPE_RESPONSE);
// Since connection headers are hop-to-hop, strip the
// the ones we received from upstream
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// Handle the upgrade cases
if (s->is_upgrade_request && heads->status_get() == HTTP_STATUS_SWITCHING_PROTOCOL && s->source == SOURCE_HTTP_ORIGIN_SERVER) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
if (s->is_websocket) {
TxnDebug("http_trans", "transaction successfully upgraded to websockets.");
// s->transparent_passthrough = true;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
// We set this state so that we can jump to our blind forwarding state once
// the response is sent to the client.
s->did_upgrade_succeed = true;
return;
}
int c_hdr_field_len;
const char *c_hdr_field_str;
if (s->client_info.proxy_connect_hdr) {
c_hdr_field_str = MIME_FIELD_PROXY_CONNECTION;
c_hdr_field_len = MIME_LEN_PROXY_CONNECTION;
} else {
c_hdr_field_str = MIME_FIELD_CONNECTION;
c_hdr_field_len = MIME_LEN_CONNECTION;
}
// Check pre-conditions for keep-alive
if (ver.get_major() == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
} else if (heads->status_get() == HTTP_STATUS_NO_CONTENT &&
((s->source == SOURCE_HTTP_ORIGIN_SERVER && s->current.server->transfer_encoding != NO_TRANSFER_ENCODING) ||
heads->get_content_length() != 0)) {
// some systems hang until the connection closes when receiving a 204 regardless of the K-A headers
// close if there is any body response from the origin
ka_action = KA_CLOSE;
} else {
// Determine if we are going to send either a server-generated or
// proxy-generated chunked response to the client. If we cannot
// trust the content-length, we may be able to chunk the response
// to the client to keep the connection alive.
// Insert a Transfer-Encoding header in the response if necessary.
// check that the client protocol is HTTP/1.1 and the conf allows chunking or
// the client protocol doesn't support chunked transfer coding (i.e. HTTP/1.0, HTTP/2, and HTTP/3)
if (s->state_machine->ua_txn && s->state_machine->ua_txn->is_chunked_encoding_supported() &&
s->client_info.http_version == HTTP_1_1 && s->txn_conf->chunking_enabled == 1 &&
s->state_machine->ua_txn->is_chunked_encoding_supported() &&
// if we're not sending a body, don't set a chunked header regardless of server response
!is_response_body_precluded(s->hdr_info.client_response.status_get(), s->method) &&
// we do not need chunked encoding for internal error messages
// that are sent to the client if the server response is not valid.
(((s->source == SOURCE_HTTP_ORIGIN_SERVER || s->source == SOURCE_TRANSFORM) && s->hdr_info.server_response.valid() &&
// if we receive a 304, we will serve the client from the
// cache and thus do not need chunked encoding.
s->hdr_info.server_response.status_get() != HTTP_STATUS_NOT_MODIFIED &&
(s->current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING ||
// we can use chunked encoding if we cannot trust the content
// length (e.g. no Content-Length and Connection:close in HTTP/1.1 responses)
s->hdr_info.trust_response_cl == false)) ||
// handle serve from cache (read-while-write) case
(s->source == SOURCE_CACHE && s->hdr_info.trust_response_cl == false) ||
// any transform will potentially alter the content length. try chunking if possible
(s->source == SOURCE_TRANSFORM && s->hdr_info.trust_response_cl == false))) {
s->client_info.receive_chunked_response = true;
heads->value_append(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING, HTTP_VALUE_CHUNKED, HTTP_LEN_CHUNKED, true);
} else {
s->client_info.receive_chunked_response = false;
}
// make sure no content length header is send when transfer encoding is chunked
if (s->client_info.receive_chunked_response) {
s->hdr_info.trust_response_cl = false;
// And delete the header if it's already been added...
heads->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Close the connection if client_info is not keep-alive.
// Otherwise, if we cannot trust the content length, we will close the connection
// unless we are going to use chunked encoding on HTTP/1.1 or the client issued a PUSH request
if (s->client_info.keep_alive != HTTP_KEEPALIVE) {
ka_action = KA_DISABLED;
} else if (s->hdr_info.trust_response_cl == false && s->state_machine->ua_txn &&
s->state_machine->ua_txn->is_chunked_encoding_supported() &&
!(s->client_info.receive_chunked_response == true ||
(s->method == HTTP_WKSIDX_PUSH && s->client_info.keep_alive == HTTP_KEEPALIVE))) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
ink_assert(ka_action != KA_UNKNOWN);
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->client_info.keep_alive != HTTP_NO_KEEPALIVE);
// This is a hack, we send the keep-alive header for both 1.0
// and 1.1, to be "compatible" with Akamai.
heads->value_set(c_hdr_field_str, c_hdr_field_len, "keep-alive", 10);
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_CLOSE:
case KA_DISABLED:
if (s->client_info.keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTP_1_1)) {
if (s->client_info.proxy_connect_hdr) {
heads->value_set(c_hdr_field_str, c_hdr_field_len, "close", 5);
} else if (s->state_machine->ua_txn != nullptr) {
s->state_machine->ua_txn->set_close_connection(*heads);
}
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
// Note: if we are 1.1, we always need to send the close
// header since persistent connections are the default
break;
default:
ink_assert(0);
break;
}
} /* End HttpTransact::handle_response_keep_alive_headers */
bool
HttpTransact::delete_all_document_alternates_and_return(State *s, bool cache_hit)
{
if (cache_hit == true) {
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
} else {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
if ((s->method != HTTP_WKSIDX_GET) && (s->method == HTTP_WKSIDX_DELETE || s->method == HTTP_WKSIDX_PURGE)) {
bool valid_max_forwards;
int max_forwards = -1;
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
// Check the max forwards value for DELETE
if (max_forwards_f) {
valid_max_forwards = true;
max_forwards = max_forwards_f->value_get_int();
} else {
valid_max_forwards = false;
}
if (s->method == HTTP_WKSIDX_PURGE || (valid_max_forwards && max_forwards <= 0)) {
TxnDebug("http_trans", "DELETE with Max-Forwards: %d", max_forwards);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// allow deletes to be pipelined
// We want to allow keep-alive so trust the response content
// length. There really isn't one and the SM will add the
// zero content length when setting up the transfer
s->hdr_info.trust_response_cl = true;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version,
(cache_hit == true) ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
return true;
} else {
if (valid_max_forwards) {
--max_forwards;
TxnDebug("http_trans", "Decrementing max_forwards to %d", max_forwards);
s->hdr_info.client_request.value_set_int(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS, max_forwards);
}
}
}
return false;
}
bool
HttpTransact::does_client_request_permit_cached_response(const OverridableHttpConfigParams *p, CacheControlResult *c, HTTPHdr *h,
char *via_string)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
return (false);
}
if (h->is_pragma_no_cache_set()) {
// if we are going to send out an ims anyway,
// no need to flag this as a no-cache.
if (!p->cache_ims_on_client_no_cache) {
via_string[VIA_CLIENT_REQUEST] = VIA_CLIENT_NO_CACHE;
}
return (false);
}
}
return (true);
}
bool
HttpTransact::does_client_request_permit_dns_caching(CacheControlResult *c, HTTPHdr *h)
{
if (h->is_pragma_no_cache_set() && h->is_cache_control_set(HTTP_VALUE_NO_CACHE) && (!c->ignore_client_no_cache)) {
return (false);
}
return (true);
}
bool
HttpTransact::does_client_request_permit_storing(CacheControlResult *c, HTTPHdr *h)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_STORE)) {
return (false);
}
}
return (true);
}
int
HttpTransact::get_max_age(HTTPHdr *response)
{
int max_age = -1;
uint32_t cc_mask = response->get_cooked_cc_mask();
bool max_age_is_present = false;
if (cc_mask & MIME_COOKED_MASK_CC_S_MAXAGE) {
// Precedence to s-maxage
max_age = static_cast<int>(response->get_cooked_cc_s_maxage());
max_age_is_present = true;
} else if (cc_mask & MIME_COOKED_MASK_CC_MAX_AGE) {
// If s-maxage isn't set, try max-age
max_age = static_cast<int>(response->get_cooked_cc_max_age());
max_age_is_present = true;
}
// Negative max-age values:
//
// Per RFC 7234, section-1.2.1, max-age values should be a non-negative
// value. If it is negative, therefore, the value is invalid. Per RFC 7234,
// section-4.2.1, invalid freshness specifications should be considered
// stale.
//
// Negative return values from this function are used to indicate that the
// max-age value was not present, resulting in a default value likely being
// used. If the max-age is negative, therefore, we return 0 to indicate to
// the caller that the max-age directive was present and indicates that the
// object should be considered stale.
if (max_age_is_present && max_age < 0) {
max_age = 0;
}
return max_age;
}
int
HttpTransact::calculate_document_freshness_limit(State *s, HTTPHdr *response, time_t response_date, bool *heuristic)
{
bool expires_set, date_set, last_modified_set;
time_t date_value, expires_value, last_modified_value;
MgmtInt min_freshness_bounds, max_freshness_bounds;
int freshness_limit = 0;
int max_age = get_max_age(response);
*heuristic = false;
if (max_age >= 0) {
freshness_limit = std::min(std::max(0, max_age), static_cast<int>(s->txn_conf->cache_guaranteed_max_lifetime));
TxnDebug("http_match", "freshness_limit = %d", freshness_limit);
} else {
date_set = last_modified_set = false;
if (s->plugin_set_expire_time != UNDEFINED_TIME) {
expires_set = true;
expires_value = s->plugin_set_expire_time;
} else {
expires_set = (response->presence(MIME_PRESENCE_EXPIRES) != 0);
expires_value = response->get_expires();
}
date_value = response_date;
if (date_value > 0) {
date_set = true;
} else {
date_value = s->request_sent_time;
TxnDebug("http_match", "Expires header = %" PRId64 " no date, using sent time %" PRId64, (int64_t)expires_value,
(int64_t)date_value);
}
ink_assert(date_value > 0);
// Getting the cache_sm object
HttpCacheSM &cache_sm = s->state_machine->get_cache_sm();
// Bypassing if loop to set freshness_limit to heuristic value
if (expires_set && !cache_sm.is_readwhilewrite_inprogress()) {
if (expires_value == UNDEFINED_TIME || expires_value <= date_value) {
expires_value = date_value;
TxnDebug("http_match", "no expires, using date %" PRId64, (int64_t)expires_value);
}
freshness_limit = static_cast<int>(expires_value - date_value);
TxnDebug("http_match", "Expires: %" PRId64 ", Date: %" PRId64 ", freshness_limit = %d", (int64_t)expires_value,
(int64_t)date_value, freshness_limit);
freshness_limit = std::min(std::max(0, freshness_limit), static_cast<int>(s->txn_conf->cache_guaranteed_max_lifetime));
} else {
last_modified_value = 0;
if (response->presence(MIME_PRESENCE_LAST_MODIFIED)) {
last_modified_set = true;
last_modified_value = response->get_last_modified();
TxnDebug("http_match", "Last Modified header = %" PRId64, (int64_t)last_modified_value);
if (last_modified_value == UNDEFINED_TIME) {
last_modified_set = false;
} else if (last_modified_value > date_value) {
last_modified_value = date_value;
TxnDebug("http_match", "no last-modified, using sent time %" PRId64, (int64_t)last_modified_value);
}
}
*heuristic = true;
if (date_set && last_modified_set) {
MgmtFloat f = s->txn_conf->cache_heuristic_lm_factor;
ink_assert((f >= 0.0) && (f <= 1.0));
ink_time_t time_since_last_modify = date_value - last_modified_value;
int h_freshness = static_cast<int>(time_since_last_modify * f);
freshness_limit = std::max(h_freshness, 0);
TxnDebug("http_match",
"heuristic: date=%" PRId64 ", lm=%" PRId64 ", time_since_last_modify=%" PRId64 ", f=%g, freshness_limit = %d",
(int64_t)date_value, (int64_t)last_modified_value, (int64_t)time_since_last_modify, f, freshness_limit);
} else {
freshness_limit = s->txn_conf->cache_heuristic_min_lifetime;
TxnDebug("http_match", "heuristic: freshness_limit = %d", freshness_limit);
}
}
}
// The freshness limit must always fall within the min and max guaranteed bounds.
min_freshness_bounds = std::max(static_cast<MgmtInt>(0), s->txn_conf->cache_guaranteed_min_lifetime);
max_freshness_bounds = s->txn_conf->cache_guaranteed_max_lifetime;
// Heuristic freshness can be more strict.
if (*heuristic) {
min_freshness_bounds = std::max(min_freshness_bounds, s->txn_conf->cache_heuristic_min_lifetime);
max_freshness_bounds = std::min(max_freshness_bounds, s->txn_conf->cache_heuristic_max_lifetime);
}
// Now clip the freshness limit.
if (freshness_limit > max_freshness_bounds) {
freshness_limit = max_freshness_bounds;
}
if (freshness_limit < min_freshness_bounds) {
freshness_limit = min_freshness_bounds;
}
TxnDebug("http_match", "final freshness_limit = %d", freshness_limit);
return (freshness_limit);
}
//////////////////////////////////////////////////////////////////////////////
//
//
// This function takes the request and response headers for a cached
// object, and the current HTTP parameters, and decides if the object
// is still "fresh enough" to serve. One of the following values
// is returned:
//
// FRESHNESS_FRESH Fresh enough, serve it
// FRESHNESS_WARNING Stale but client says it's okay
// FRESHNESS_STALE Too stale, don't use
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Freshness_t
HttpTransact::what_is_document_freshness(State *s, HTTPHdr *client_request, HTTPHdr *cached_obj_response)
{
bool heuristic, do_revalidate = false;
int age_limit;
int fresh_limit;
ink_time_t current_age, response_date;
uint32_t cc_mask, cooked_cc_mask;
uint32_t os_specifies_revalidate;
if (s->cache_open_write_fail_action & CACHE_WL_FAIL_ACTION_STALE_ON_REVALIDATE) {
if (is_stale_cache_response_returnable(s)) {
TxnDebug("http_match", "cache_serve_stale_on_write_lock_fail, return FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////
// If config file has a ttl-in-cache field set, //
// it has priority over any other http headers and //
// other configuration parameters. //
//////////////////////////////////////////////////////
if (s->cache_control.ttl_in_cache > 0) {
// what matters if ttl is set is not the age of the document
// but for how long it has been stored in the cache (resident time)
int resident_time = s->current.now - s->response_received_time;
TxnDebug("http_match", "ttl-in-cache = %d, resident time = %d", s->cache_control.ttl_in_cache, resident_time);
if (resident_time > s->cache_control.ttl_in_cache) {
return (FRESHNESS_STALE);
} else {
return (FRESHNESS_FRESH);
}
}
cooked_cc_mask = cached_obj_response->get_cooked_cc_mask();
os_specifies_revalidate = cooked_cc_mask & (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
cc_mask = MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE;
// Check to see if the server forces revalidation
if ((cooked_cc_mask & cc_mask) && s->cache_control.revalidate_after <= 0) {
TxnDebug("http_match", "document stale due to server must-revalidate");
return FRESHNESS_STALE;
}
response_date = cached_obj_response->get_date();
fresh_limit = calculate_document_freshness_limit(s, cached_obj_response, response_date, &heuristic);
ink_assert(fresh_limit >= 0);
current_age = HttpTransactHeaders::calculate_document_age(s->request_sent_time, s->response_received_time, cached_obj_response,
response_date, s->current.now);
// First check overflow status
// Second if current_age is under the max, use the smaller value
// Finally we take the max of current age or guaranteed max, this ensures it will
// age out properly, otherwise a doc will never expire if guaranteed < document max-age
if (current_age < 0) {
current_age = s->txn_conf->cache_guaranteed_max_lifetime;
} else if (current_age < s->txn_conf->cache_guaranteed_max_lifetime) {
current_age = std::min(static_cast<time_t>(s->txn_conf->cache_guaranteed_max_lifetime), current_age);
} else {
current_age = std::max(static_cast<time_t>(s->txn_conf->cache_guaranteed_max_lifetime), current_age);
}
TxnDebug("http_match", "fresh_limit: %d current_age: %" PRId64, fresh_limit, (int64_t)current_age);
ink_assert(client_request == &s->hdr_info.client_request);
if (auto scheme = client_request->url_get()->scheme_get_wksidx(); scheme == URL_WKSIDX_HTTP || scheme == URL_WKSIDX_HTTPS) {
switch (s->txn_conf->cache_when_to_revalidate) {
case 0: // Use cache directives or heuristic (the default value)
// Nothing to do here
break;
case 1: // Stale if heuristic
if (heuristic) {
TxnDebug("http_match", "config requires FRESHNESS_STALE because heuristic calculation");
return (FRESHNESS_STALE);
}
break;
case 2: // Always stale
TxnDebug("http_match", "config specifies always FRESHNESS_STALE");
return (FRESHNESS_STALE);
case 3: // Never stale
TxnDebug("http_match", "config specifies always FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
case 4: // Stale if IMS
if (client_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE)) {
TxnDebug("http_match", "config specifies FRESHNESS_STALE if IMS present");
return (FRESHNESS_STALE);
}
default: // Bad config, ignore
break;
}
}
//////////////////////////////////////////////////////////////////////
// the normal expiration policy allows serving a doc from cache if: //
// basic: (current_age <= fresh_limit) //
// //
// this can be modified by client Cache-Control headers: //
// max-age: (current_age <= max_age) //
// min-fresh: (current_age <= fresh_limit - min_fresh) //
// max-stale: (current_age <= fresh_limit + max_stale) //
//////////////////////////////////////////////////////////////////////
age_limit = fresh_limit; // basic constraint
TxnDebug("http_match", "initial age limit: %d", age_limit);
cooked_cc_mask = client_request->get_cooked_cc_mask();
cc_mask = (MIME_COOKED_MASK_CC_MAX_STALE | MIME_COOKED_MASK_CC_MIN_FRESH | MIME_COOKED_MASK_CC_MAX_AGE);
if (cooked_cc_mask & cc_mask) {
/////////////////////////////////////////////////
// if max-stale set, relax the freshness limit //
/////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_STALE) {
if (os_specifies_revalidate) {
TxnDebug("http_match", "OS specifies revalidation; ignoring client's max-stale request...");
} else {
int max_stale_val = client_request->get_cooked_cc_max_stale();
if (max_stale_val != INT_MAX) {
age_limit += max_stale_val;
} else {
age_limit = max_stale_val;
}
TxnDebug("http_match", "max-stale set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////
// if min-fresh set, constrain the freshness limit //
/////////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MIN_FRESH) {
age_limit = std::min(age_limit, fresh_limit - client_request->get_cooked_cc_min_fresh());
TxnDebug("http_match", "min_fresh set, age limit: %d", age_limit);
}
///////////////////////////////////////////////////
// if max-age set, constrain the freshness limit //
///////////////////////////////////////////////////
if (!s->cache_control.ignore_client_cc_max_age && (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_AGE)) {
int age_val = client_request->get_cooked_cc_max_age();
if (age_val == 0) {
do_revalidate = true;
}
age_limit = std::min(age_limit, age_val);
TxnDebug("http_match", "min_fresh set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////////
// config file may have a "revalidate_after" field set //
/////////////////////////////////////////////////////////
// bug fix changed ">0" to ">=0"
if (s->cache_control.revalidate_after >= 0) {
// if we want the minimum of the already-computed age_limit and revalidate_after
// age_limit = mine(age_limit, s->cache_control.revalidate_after);
// if instead the revalidate_after overrides all other variables
age_limit = s->cache_control.revalidate_after;
TxnDebug("http_match", "revalidate_after set, age limit: %d", age_limit);
}
TxnDebug("http_match", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
TxnDebug("http_match", "document_freshness --- age_limit = %d", age_limit);
TxnDebug("http_match", "document_freshness --- fresh_limit = %d", fresh_limit);
TxnDebug("http_seq", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
TxnDebug("http_seq", "document_freshness --- age_limit = %d", age_limit);
TxnDebug("http_seq", "document_freshness --- fresh_limit = %d", fresh_limit);
///////////////////////////////////////////
// now, see if the age is "fresh enough" //
///////////////////////////////////////////
if (do_revalidate || !age_limit || current_age > age_limit) { // client-modified limit
TxnDebug("http_match", "document needs revalidate/too old; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
} else if (current_age > fresh_limit) { // original limit
if (os_specifies_revalidate) {
TxnDebug("http_match", "document is stale and OS specifies revalidation; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
}
TxnDebug("http_match", "document is stale but no revalidation explicitly required; "
"returning FRESHNESS_WARNING");
return (FRESHNESS_WARNING);
} else {
TxnDebug("http_match", "document is fresh; returning FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpTransact::Authentication_t HttpTransact::AuthenticationNeeded(
// const OverridableHttpConfigParams *p,
// HTTPHdr *client_request,
// HTTPHdr *obj_response)
//
// This function takes the current client request, and the headers
// from a potential response (e.g. from cache or proxy), and decides
// if the object needs to be authenticated with the origin server,
// before it can be sent to the client.
//
// The return value describes the authentication process needed. In
// this function, three results are possible:
//
// AUTHENTICATION_SUCCESS Can serve object directly
// AUTHENTICATION_MUST_REVALIDATE Must revalidate with server
// AUTHENTICATION_MUST_PROXY Must not serve object
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Authentication_t
HttpTransact::AuthenticationNeeded(const OverridableHttpConfigParams *p, HTTPHdr *client_request, HTTPHdr *obj_response)
{
///////////////////////////////////////////////////////////////////////
// from RFC2068, sec 14.8, if a client request has the Authorization //
// header set, we can't serve it unless the response is public, or //
// if it has a Cache-Control revalidate flag, and we do revalidate. //
///////////////////////////////////////////////////////////////////////
if ((p->cache_ignore_auth == 0) && client_request->presence(MIME_PRESENCE_AUTHORIZATION)) {
if (obj_response->is_cache_control_set(HTTP_VALUE_MUST_REVALIDATE) ||
obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PUBLIC)) {
return AUTHENTICATION_SUCCESS;
} else {
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return AUTHENTICATION_MUST_PROXY;
}
}
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return (AUTHENTICATION_SUCCESS);
}
void
HttpTransact::handle_parent_died(State *s)
{
ink_assert(s->parent_result.result == PARENT_FAIL);
switch (s->current.state) {
case OUTBOUND_CONGESTION:
build_error_response(s, HTTP_STATUS_SERVICE_UNAVAILABLE, "Next Hop Congested", "congestion#retryAfter");
break;
case INACTIVE_TIMEOUT:
build_error_response(s, HTTP_STATUS_GATEWAY_TIMEOUT, "Next Hop Timeout", "timeout#inactivity");
break;
case ACTIVE_TIMEOUT:
build_error_response(s, HTTP_STATUS_GATEWAY_TIMEOUT, "Next Hop Timeout", "timeout#activity");
break;
default:
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect");
}
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, nullptr);
}
void
HttpTransact::handle_server_died(State *s)
{
const char *reason = nullptr;
const char *body_type = "UNKNOWN";
HTTPStatus status = HTTP_STATUS_BAD_GATEWAY;
////////////////////////////////////////////////////////
// FIX: all the body types below need to be filled in //
////////////////////////////////////////////////////////
switch (s->current.state) {
case CONNECTION_ALIVE: /* died while alive for unknown reason */
ink_release_assert(s->hdr_info.response_error != NO_RESPONSE_HEADER_ERROR);
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Unknown Error";
body_type = "response#bad_response";
break;
case CONNECTION_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = get_error_string(s->cause_of_death_errno == 0 ? -ENET_CONNECT_FAILED : s->cause_of_death_errno);
body_type = "connect#failed_connect";
break;
case OPEN_RAW_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Tunnel Connection Failed";
body_type = "connect#failed_connect";
break;
case CONNECTION_CLOSED:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Hangup";
body_type = "connect#hangup";
break;
case ACTIVE_TIMEOUT:
if (s->api_txn_active_timeout_value != -1) {
TxnDebug("http_timeout", "Maximum active time of %d msec exceeded", s->api_txn_active_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Maximum Transaction Time Exceeded";
body_type = "timeout#activity";
break;
case INACTIVE_TIMEOUT:
if (s->api_txn_connect_timeout_value != -1) {
TxnDebug("http_timeout", "Maximum connect time of %d msec exceeded", s->api_txn_connect_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Connection Timed Out";
body_type = "timeout#inactivity";
break;
case PARSE_ERROR:
case BAD_INCOMING_RESPONSE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Invalid HTTP Response";
body_type = "response#bad_response";
break;
case OUTBOUND_CONGESTION:
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Origin server congested";
body_type = "congestion#retryAfter";
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
break;
case STATE_UNDEFINED:
case TRANSACTION_COMPLETE:
default: /* unknown death */
ink_release_assert(!"[handle_server_died] Unreasonable state - not dead, shouldn't be here");
status = HTTP_STATUS_BAD_GATEWAY;
reason = nullptr;
body_type = "response#bad_response";
break;
}
////////////////////////////////////////////////////////
// FIX: comment stuff above and below here, not clear //
////////////////////////////////////////////////////////
switch (s->hdr_info.response_error) {
case NON_EXISTANT_RESPONSE_HEADER:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "No Response Header From Server";
body_type = "response#bad_response";
break;
case MISSING_REASON_PHRASE:
case NO_RESPONSE_HEADER_ERROR:
case NOT_A_RESPONSE_HEADER:
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
#endif
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response";
body_type = "response#bad_response";
break;
case MISSING_STATUS_CODE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response Status";
body_type = "response#bad_response";
break;
default:
break;
}
if (reason == nullptr) {
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Connection Failed";
body_type = "connect#failed_connect";
}
build_error_response(s, status, reason, body_type);
return;
}
// return true if the response to the given request is likely cacheable
// This function is called by build_request() to determine if the conditional
// headers should be removed from server request.
bool
HttpTransact::is_request_likely_cacheable(State *s, HTTPHdr *request)
{
if ((s->method == HTTP_WKSIDX_GET || s->api_req_cacheable) && !s->api_server_response_no_store &&
!request->presence(MIME_PRESENCE_AUTHORIZATION) &&
(!request->presence(MIME_PRESENCE_RANGE) || s->txn_conf->cache_range_write)) {
return true;
}
return false;
}
bool
HttpTransact::is_fresh_cache_hit(CacheLookupResult_t r)
{
return (r == CACHE_LOOKUP_HIT_FRESH || r == CACHE_LOOKUP_HIT_WARNING);
}
bool
HttpTransact::is_cache_hit(CacheLookupResult_t r)
{
return (is_fresh_cache_hit(r) || r == CACHE_LOOKUP_HIT_STALE);
}
void
HttpTransact::build_request(State *s, HTTPHdr *base_request, HTTPHdr *outgoing_request, HTTPVersion outgoing_version)
{
// this part is to restore the original URL in case, multiple cache
// lookups have happened - client request has been changed as the result
//
// notice that currently, based_request IS client_request
if (base_request == &s->hdr_info.client_request) {
if (!s->redirect_info.redirect_in_process) {
// this is for multiple cache lookup
URL *o_url = &s->cache_info.original_url;
if (o_url->valid()) {
base_request->url_get()->copy(o_url);
}
}
// Perform any configured normalization (including per-remap-rule configuration overrides) of the Accept-Encoding header
// field (if any). This has to be done in the request from the client, for the benefit of the gzip plugin.
//
HttpTransactHeaders::normalize_accept_encoding(s->txn_conf, base_request);
}
HttpTransactHeaders::copy_header_fields(base_request, outgoing_request, s->txn_conf->fwd_proxy_auth_to_parent);
add_client_ip_to_outgoing_request(s, outgoing_request);
HttpTransactHeaders::add_forwarded_field_to_request(s, outgoing_request);
HttpTransactHeaders::remove_privacy_headers_from_request(s->http_config_param, s->txn_conf, outgoing_request);
HttpTransactHeaders::add_global_user_agent_header_to_request(s->txn_conf, outgoing_request);
handle_request_keep_alive_headers(s, outgoing_version, outgoing_request);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
if (s->orig_scheme < 0) {
s->orig_scheme = URL_WKSIDX_HTTP;
}
if (s->txn_conf->insert_request_via_string) {
HttpTransactHeaders::insert_via_header_in_request(s, outgoing_request);
}
// We build 1.1 request header and then convert as necessary to
// the appropriate version in HttpTransact::build_request
outgoing_request->version_set(HTTP_1_1);
// Make sure our request version is defined
ink_assert(outgoing_version != HTTP_0_9);
// HttpTransactHeaders::convert_request(outgoing_version, outgoing_request); // commented out this idea
URL *url = outgoing_request->url_get();
// Remove fragment from upstream URL
url->fragment_set(nullptr, 0);
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (outgoing_version != HTTP_0_9 && !outgoing_request->presence(MIME_PRESENCE_HOST)) {
int host_len;
const char *host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = static_cast<char *>(alloca(host_len + 15));
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
}
// Figure out whether to force the outgoing request URL into absolute or relative styles.
if (outgoing_request->method_get_wksidx() == HTTP_WKSIDX_CONNECT) {
// CONNECT method requires a target in the URL, so always force it from the Host header.
outgoing_request->set_url_target_from_host_field();
} else if (s->current.request_to == PARENT_PROXY && parent_is_proxy(s)) {
// If we have a parent proxy set the URL target field.
if (!outgoing_request->is_target_in_url()) {
TxnDebug("http_trans", "adding target to URL for parent proxy");
outgoing_request->set_url_target_from_host_field();
}
} else if (s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS ||
s->next_hop_scheme == URL_WKSIDX_WS || s->next_hop_scheme == URL_WKSIDX_WSS) {
// Otherwise, remove the URL target from HTTP and Websocket URLs since certain origins
// cannot deal with absolute URLs.
TxnDebug("http_trans", "removing host name from url");
HttpTransactHeaders::remove_host_name_from_url(outgoing_request);
}
// If the response is most likely not cacheable, eg, request with Authorization,
// do we really want to remove conditional headers to get large 200 response?
// Answer: NO. Since if the response is most likely not cacheable,
// we don't remove conditional headers so that for a non-200 response
// from the O.S., we will save bandwidth between proxy and O.S.
if (s->current.mode == GENERIC_PROXY) {
if (is_request_likely_cacheable(s, base_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
TxnDebug("http_trans", "request like cacheable and conditional headers removed");
HttpTransactHeaders::remove_conditional_headers(outgoing_request);
} else {
TxnDebug("http_trans", "request like cacheable but keep conditional headers");
}
} else {
// In this case, we send a conditional request
// instead of the normal non-conditional request.
TxnDebug("http_trans", "request not like cacheable and conditional headers not removed");
}
}
if (s->hdr_info.client_request.m_100_continue_sent) {
HttpTransactHeaders::remove_100_continue_headers(s, outgoing_request);
TxnDebug("http_trans", "request expect 100-continue headers removed");
}
if (base_request->is_early_data()) {
outgoing_request->value_set_int(MIME_FIELD_EARLY_DATA, MIME_LEN_EARLY_DATA, 1);
}
s->request_sent_time = ink_local_time();
s->current.now = s->request_sent_time;
// The assert is backwards in this case because request is being (re)sent.
ink_assert(s->request_sent_time >= s->response_received_time);
TxnDebug("http_trans", "request_sent_time: %" PRId64, (int64_t)s->request_sent_time);
DUMP_HEADER("http_hdrs", outgoing_request, s->state_machine_id, "Proxy's Request");
HTTP_INCREMENT_DYN_STAT(http_outgoing_requests_stat);
}
// build a (status_code) response based upon the given info
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
build_response(s, base_response, outgoing_response, outgoing_version, HTTP_STATUS_NONE, nullptr);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *outgoing_response, HTTPVersion outgoing_version, HTTPStatus status_code,
const char *reason_phrase)
{
build_response(s, nullptr, outgoing_response, outgoing_version, status_code, reason_phrase);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version,
HTTPStatus status_code, const char *reason_phrase)
{
if (reason_phrase == nullptr) {
reason_phrase = http_hdr_reason_lookup(status_code);
}
if (base_response == nullptr) {
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase), s->current.now);
} else {
if ((status_code == HTTP_STATUS_NONE) || (status_code == base_response->status_get())) {
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent);
if (s->txn_conf->insert_age_in_response) {
HttpTransactHeaders::insert_time_and_age_headers_in_response(s->request_sent_time, s->response_received_time,
s->current.now, base_response, outgoing_response);
}
// Note: We need to handle the "Content-Length" header first here
// since handle_content_length_header()
// determines whether we accept origin server's content-length.
// We need to have made a decision regard the content-length
// before processing the keep_alive headers
//
handle_content_length_header(s, outgoing_response, base_response);
} else {
switch (status_code) {
case HTTP_STATUS_NOT_MODIFIED:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
// According to RFC 2616, Section 10.3.5,
// a 304 response MUST contain Date header,
// Etag and/or Content-location header,
// and Expires, Cache-control, and Vary
// (if they might be changed).
// Since a proxy doesn't know if a header differs from
// a user agent's cached document or not, all are sent.
{
static const struct {
const char *name;
int len;
uint64_t presence;
} fields[] = {
{MIME_FIELD_ETAG, MIME_LEN_ETAG, MIME_PRESENCE_ETAG},
{MIME_FIELD_CONTENT_LOCATION, MIME_LEN_CONTENT_LOCATION, MIME_PRESENCE_CONTENT_LOCATION},
{MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES, MIME_PRESENCE_EXPIRES},
{MIME_FIELD_CACHE_CONTROL, MIME_LEN_CACHE_CONTROL, MIME_PRESENCE_CACHE_CONTROL},
{MIME_FIELD_VARY, MIME_LEN_VARY, MIME_PRESENCE_VARY},
};
for (size_t i = 0; i < countof(fields); i++) {
if (base_response->presence(fields[i].presence)) {
MIMEField *field;
int len;
const char *value;
field = base_response->field_find(fields[i].name, fields[i].len);
ink_assert(field != nullptr);
value = field->value_get(&len);
outgoing_response->value_append(fields[i].name, fields[i].len, value, len, false);
if (field->has_dups()) {
field = field->m_next_dup;
while (field) {
value = field->value_get(&len);
outgoing_response->value_append(fields[i].name, fields[i].len, value, len, true);
field = field->m_next_dup;
}
}
}
}
}
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// fall through
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
break;
default:
// ink_assert(!"unexpected status code in build_response()");
break;
}
}
}
// the following is done whether base_response == NULL or not
// If the response is prohibited from containing a body,
// we know the content length is trustable for keep-alive
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.trust_response_cl = true;
}
handle_response_keep_alive_headers(s, outgoing_version, outgoing_response);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// Add HSTS header (Strict-Transport-Security) if max-age is set and the request was https
// and the incoming request was remapped correctly
if (s->orig_scheme == URL_WKSIDX_HTTPS && s->txn_conf->proxy_response_hsts_max_age >= 0 && s->url_remap_success == true) {
TxnDebug("http_hdrs", "hsts max-age=%" PRId64, s->txn_conf->proxy_response_hsts_max_age);
HttpTransactHeaders::insert_hsts_header_in_response(s, outgoing_response);
}
if (s->txn_conf->insert_response_via_string) {
HttpTransactHeaders::insert_via_header_in_response(s, outgoing_response);
}
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response);
// process reverse mappings on the location header
// TS-1364: do this regardless of response code
response_url_remap(outgoing_response, s->state_machine->m_remap);
if (s->http_config_param->enable_http_stats) {
HttpTransactHeaders::generate_and_set_squid_codes(outgoing_response, s->via_string, &s->squid_codes);
}
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
if (s->state_machine->ua_txn && s->state_machine->ua_txn->get_proxy_ssn()->is_draining()) {
HttpTransactHeaders::add_connection_close(outgoing_response);
}
if (is_debug_tag_set("http_hdrs")) {
if (base_response) {
DUMP_HEADER("http_hdrs", base_response, s->state_machine_id, "Base Header for Building Response");
}
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response 2");
}
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::build_error_response(
// State *s,
// HTTPStatus status_code,
// char *reason_phrase_or_null,
// char *error_body_type,
// char *format, ...)
//
// This method sets the requires state for an error reply, including
// the error text, status code, reason phrase, and reply headers. The
// caller calls the method with the HttpTransact::State <s>, the
// HTTP status code <status_code>, a user-specified reason phrase
// string (or NULL) <reason_phrase_or_null>, and a printf-like
// text format and arguments which are appended to the error text.
//
// The <error_body_type> is the error message type, as specified by
// the HttpBodyFactory customized error page system.
//
// If the descriptive text <format> is not NULL or "", it is also
// added to the error text body as descriptive text in the error body.
// If <reason_phrase_or_null> is NULL, the default HTTP reason phrase
// is used. This routine DOES NOT check for buffer overflows. The
// caller should keep the messages small to be sure the error text
// fits in the error buffer (ok, it's nasty, but at least I admit it!).
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_error_response(State *s, HTTPStatus status_code, const char *reason_phrase_or_null, const char *error_body_type)
{
char body_language[256], body_type[256];
if (nullptr == error_body_type) {
error_body_type = "default";
}
// Make sure that if this error occurred before we initialized the state variables that we do now.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
//////////////////////////////////////////////////////
// If there is a request body, we must disable //
// keep-alive to prevent the body being read as //
// the next header (unless we've already drained //
// which we do for NTLM auth) //
//////////////////////////////////////////////////////
if (status_code == HTTP_STATUS_REQUEST_TIMEOUT || s->hdr_info.client_request.get_content_length() != 0 ||
s->client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
// We don't have a request body. Since we are
// generating the error, we know we can trust
// the content-length
s->hdr_info.trust_response_cl = true;
}
// If transparent and the forward server connection looks unhappy don't
// keep alive the ua connection.
if ((s->state_machine->ua_txn && s->state_machine->ua_txn->is_outbound_transparent()) &&
(status_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || status_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
status_code == HTTP_STATUS_BAD_GATEWAY || status_code == HTTP_STATUS_SERVICE_UNAVAILABLE)) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
// If there is a parse error on reading the request it can leave reading the request stream in an undetermined state
if (status_code == HTTP_STATUS_BAD_REQUEST) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
switch (status_code) {
case HTTP_STATUS_BAD_REQUEST:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
// Did the via error already get set by the loop detection
if (s->via_string[VIA_ERROR_TYPE] != VIA_ERROR_LOOP_DETECTED) {
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_HEADER_SYNTAX);
}
break;
case HTTP_STATUS_BAD_GATEWAY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_CONNECTION);
break;
case HTTP_STATUS_GATEWAY_TIMEOUT:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_TIMEOUT);
break;
case HTTP_STATUS_NOT_FOUND:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_FORBIDDEN:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_FORBIDDEN);
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
if (Dns_error_body == error_body_type) {
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_DNS_FAILURE);
} else {
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_UNKNOWN);
}
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_MOVED_TEMPORARILY);
break;
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
case HTTP_STATUS_UNAUTHORIZED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
default:
break;
}
const char *reason_phrase =
(reason_phrase_or_null ? reason_phrase_or_null : const_cast<char *>(http_hdr_reason_lookup(status_code)));
if (unlikely(!reason_phrase)) {
reason_phrase = "Unknown HTTP Status";
}
// set the source to internal so that chunking is handled correctly
s->source = SOURCE_INTERNAL;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
if (status_code == HTTP_STATUS_SERVICE_UNAVAILABLE) {
int ret_tmp;
int retry_after = 0;
if (s->hdr_info.client_response.value_get(MIME_FIELD_RETRY_AFTER, MIME_LEN_RETRY_AFTER, &ret_tmp) != nullptr) {
retry_after = ret_tmp;
}
s->congestion_control_crat = retry_after;
} else if (status_code == HTTP_STATUS_BAD_REQUEST) {
// Close the client connection after a malformed request
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
// Add a bunch of headers to make sure that caches between
// the Traffic Server and the client do not cache the error
// page.
s->hdr_info.client_response.value_set(MIME_FIELD_CACHE_CONTROL, MIME_LEN_CACHE_CONTROL, "no-store", 8);
// Make sure there are no Expires and Last-Modified headers.
s->hdr_info.client_response.field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
s->hdr_info.client_response.field_delete(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED);
if ((status_code == HTTP_STATUS_PERMANENT_REDIRECT || status_code == HTTP_STATUS_TEMPORARY_REDIRECT ||
status_code == HTTP_STATUS_MOVED_TEMPORARILY || status_code == HTTP_STATUS_MOVED_PERMANENTLY) &&
s->remap_redirect) {
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, s->remap_redirect, strlen(s->remap_redirect));
}
////////////////////////////////////////////////////////////////////
// create the error message using the "body factory", which will //
// build a customized error message if available, or generate the //
// old style internal defaults otherwise --- the body factory //
// supports language targeting using the Accept-Language header //
////////////////////////////////////////////////////////////////////
int64_t len;
char *new_msg;
new_msg = body_factory->fabricate_with_old_api(
error_body_type, s, s->http_config_param->body_factory_response_max_size, &len, body_language, sizeof(body_language), body_type,
sizeof(body_type), s->internal_msg_buffer_size, s->internal_msg_buffer_size ? s->internal_msg_buffer : nullptr);
// After the body factory is called, a new "body" is allocated, and we must replace it. It is
// unfortunate that there's no way to avoid this fabrication even when there is no substitutions...
s->free_internal_msg_buffer();
if (len == 0) {
// If the file is empty, we may have a malloc(1) buffer. Release it.
new_msg = static_cast<char *>(ats_free_null(new_msg));
}
s->internal_msg_buffer = new_msg;
s->internal_msg_buffer_size = len;
s->internal_msg_buffer_fast_allocator_size = -1;
if (len > 0) {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, body_type, strlen(body_type));
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_LANGUAGE, MIME_LEN_CONTENT_LANGUAGE, body_language,
strlen(body_language));
} else {
s->hdr_info.client_response.field_delete(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
s->hdr_info.client_response.field_delete(MIME_FIELD_CONTENT_LANGUAGE, MIME_LEN_CONTENT_LANGUAGE);
}
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
return;
}
void
HttpTransact::build_redirect_response(State *s)
{
TxnDebug("http_redirect", "Entering HttpTransact::build_redirect_response");
URL *u;
const char *old_host;
int old_host_len;
const char *new_url = nullptr;
int new_url_len;
char *to_free = nullptr;
HTTPStatus status_code = HTTP_STATUS_MOVED_TEMPORARILY;
char *reason_phrase = const_cast<char *>(http_hdr_reason_lookup(status_code));
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
//////////////////////////////////////////////////////////
// figure out what new url should be. this little hack //
// inserts expanded hostname into old url in order to //
// get scheme information, then puts the old url back. //
//////////////////////////////////////////////////////////
u = s->hdr_info.client_request.url_get();
old_host = u->host_get(&old_host_len);
u->host_set(s->dns_info.lookup_name, strlen(s->dns_info.lookup_name));
new_url = to_free = u->string_get(&s->arena, &new_url_len);
if (new_url == nullptr) {
new_url = "";
}
u->host_set(old_host, old_host_len);
//////////////////////////
// set redirect headers //
//////////////////////////
HTTPHdr *h = &s->hdr_info.client_response;
if (s->txn_conf->insert_response_via_string) {
const char pa[] = "Proxy-agent";
h->value_append(pa, sizeof(pa) - 1, s->http_config_param->proxy_response_via_string,
s->http_config_param->proxy_response_via_string_len);
}
h->value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, new_url, new_url_len);
//////////////////////////
// set descriptive text //
//////////////////////////
s->free_internal_msg_buffer();
s->internal_msg_buffer_fast_allocator_size = -1;
// template redirect#temporarily can not be used here since there is no way to pass the computed url to the template.
s->internal_msg_buffer = body_factory->getFormat(8192, &s->internal_msg_buffer_size, "%s <a href=\"%s\">%s</a>. %s.",
"The document you requested is now", new_url, new_url,
"Please update your documents and bookmarks accordingly", nullptr);
h->set_content_length(s->internal_msg_buffer_size);
h->value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
s->arena.str_free(to_free);
}
const char *
HttpTransact::get_error_string(int erno)
{
if (erno >= 0) {
return (strerror(erno));
} else {
switch (-erno) {
case ENET_THROTTLING:
return ("throttling");
case ESOCK_DENIED:
return ("socks error - denied");
case ESOCK_TIMEOUT:
return ("socks error - timeout");
case ESOCK_NO_SOCK_SERVER_CONN:
return ("socks error - no server connection");
// this assumes that the following case occurs
// when HttpSM.cc::state_origin_server_read_response
// receives an HTTP_EVENT_EOS. (line 1729 in HttpSM.cc,
// version 1.145.2.13.2.57)
case ENET_CONNECT_FAILED:
return ("connect failed");
case UNKNOWN_INTERNAL_ERROR:
return ("internal error - server connection terminated");
default:
return ("");
}
}
}
ink_time_t
ink_local_time()
{
return ink_get_hrtime() / HRTIME_SECOND;
}
//
// The stat functions
//
void
HttpTransact::milestone_start_api_time(State *s)
{
s->state_machine->api_timer = ink_get_hrtime();
}
void
HttpTransact::milestone_update_api_time(State *s)
{
s->state_machine->milestone_update_api_time();
}
void
HttpTransact::histogram_response_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_inf_stat);
}
return;
}
void
HttpTransact::histogram_request_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_inf_stat);
}
return;
}
void
HttpTransact::user_agent_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime =
(transfer_time == 0) ? (nbytes) : (static_cast<float>(nbytes) / static_cast<float>(static_cast<int64_t>(transfer_time)));
int bytes_per_sec = static_cast<int>(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100M_stat);
}
return;
}
/*
* added request_process_time stat for loadshedding foo
*/
void
HttpTransact::client_result_stat(State *s, ink_hrtime total_time, ink_hrtime request_process_time)
{
ClientTransactionResult_t client_transaction_result = CLIENT_TRANSACTION_RESULT_UNDEFINED;
///////////////////////////////////////////////////////
// don't count errors we generated as hits or misses //
///////////////////////////////////////////////////////
int client_response_status = HTTP_STATUS_NONE;
if (s->hdr_info.client_response.valid()) {
client_response_status = s->hdr_info.client_response.status_get();
}
if ((s->source == SOURCE_INTERNAL) && client_response_status >= 400) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
}
switch (s->squid_codes.log_code) {
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL;
break;
case SQUID_LOG_TCP_CF_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_rww_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_MEM_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_mem_fresh_stat);
// fallthrough
case SQUID_LOG_TCP_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_cache_hit_fresh_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_reval_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED;
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REF_FAIL_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_stale_served_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_MISS:
if ((GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_IN_CACHE_NOT_ACCEPTABLE) || (GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_CACHE_MISS)) {
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
} else {
// FIX: what case is this for? can it ever happen?
HTTP_INCREMENT_DYN_STAT(http_cache_miss_uncacheable_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE;
}
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_changed_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CHANGED;
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_client_no_cache_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE;
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
case SQUID_LOG_TCP_SWAPFAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_read_error_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_ERR_READ_TIMEOUT:
case SQUID_LOG_TCP_DENIED:
// No cache result due to error
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
break;
default:
// FIX: What is the conditional below doing?
// if (s->local_trans_stats[http_cache_lookups_stat].count == 1L)
// HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
// FIX: I suspect the following line should not be set here,
// because it overrides the error classification above.
// Commenting out.
// client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
}
//////////////////////////////////////////
// don't count aborts as hits or misses //
//////////////////////////////////////////
if (s->client_info.abort == ABORTED) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_ABORT;
}
// Count the status codes, assuming the client didn't abort (i.e. there is an m_http)
if ((s->source != SOURCE_NONE) && (s->client_info.abort == DIDNOT_ABORT)) {
switch (client_response_status) {
case 100:
HTTP_INCREMENT_DYN_STAT(http_response_status_100_count_stat);
break;
case 101:
HTTP_INCREMENT_DYN_STAT(http_response_status_101_count_stat);
break;
case 200:
HTTP_INCREMENT_DYN_STAT(http_response_status_200_count_stat);
break;
case 201:
HTTP_INCREMENT_DYN_STAT(http_response_status_201_count_stat);
break;
case 202:
HTTP_INCREMENT_DYN_STAT(http_response_status_202_count_stat);
break;
case 203:
HTTP_INCREMENT_DYN_STAT(http_response_status_203_count_stat);
break;
case 204:
HTTP_INCREMENT_DYN_STAT(http_response_status_204_count_stat);
break;
case 205:
HTTP_INCREMENT_DYN_STAT(http_response_status_205_count_stat);
break;
case 206:
HTTP_INCREMENT_DYN_STAT(http_response_status_206_count_stat);
break;
case 300:
HTTP_INCREMENT_DYN_STAT(http_response_status_300_count_stat);
break;
case 301:
HTTP_INCREMENT_DYN_STAT(http_response_status_301_count_stat);
break;
case 302:
HTTP_INCREMENT_DYN_STAT(http_response_status_302_count_stat);
break;
case 303:
HTTP_INCREMENT_DYN_STAT(http_response_status_303_count_stat);
break;
case 304:
HTTP_INCREMENT_DYN_STAT(http_response_status_304_count_stat);
break;
case 305:
HTTP_INCREMENT_DYN_STAT(http_response_status_305_count_stat);
break;
case 307:
HTTP_INCREMENT_DYN_STAT(http_response_status_307_count_stat);
break;
case 308:
HTTP_INCREMENT_DYN_STAT(http_response_status_308_count_stat);
break;
case 400:
HTTP_INCREMENT_DYN_STAT(http_response_status_400_count_stat);
break;
case 401:
HTTP_INCREMENT_DYN_STAT(http_response_status_401_count_stat);
break;
case 402:
HTTP_INCREMENT_DYN_STAT(http_response_status_402_count_stat);
break;
case 403:
HTTP_INCREMENT_DYN_STAT(http_response_status_403_count_stat);
break;
case 404:
HTTP_INCREMENT_DYN_STAT(http_response_status_404_count_stat);
break;
case 405:
HTTP_INCREMENT_DYN_STAT(http_response_status_405_count_stat);
break;
case 406:
HTTP_INCREMENT_DYN_STAT(http_response_status_406_count_stat);
break;
case 407:
HTTP_INCREMENT_DYN_STAT(http_response_status_407_count_stat);
break;
case 408:
HTTP_INCREMENT_DYN_STAT(http_response_status_408_count_stat);
break;
case 409:
HTTP_INCREMENT_DYN_STAT(http_response_status_409_count_stat);
break;
case 410:
HTTP_INCREMENT_DYN_STAT(http_response_status_410_count_stat);
break;
case 411:
HTTP_INCREMENT_DYN_STAT(http_response_status_411_count_stat);
break;
case 412:
HTTP_INCREMENT_DYN_STAT(http_response_status_412_count_stat);
break;
case 413:
HTTP_INCREMENT_DYN_STAT(http_response_status_413_count_stat);
break;
case 414:
HTTP_INCREMENT_DYN_STAT(http_response_status_414_count_stat);
break;
case 415:
HTTP_INCREMENT_DYN_STAT(http_response_status_415_count_stat);
break;
case 416:
HTTP_INCREMENT_DYN_STAT(http_response_status_416_count_stat);
break;
case 500:
HTTP_INCREMENT_DYN_STAT(http_response_status_500_count_stat);
break;
case 501:
HTTP_INCREMENT_DYN_STAT(http_response_status_501_count_stat);
break;
case 502:
HTTP_INCREMENT_DYN_STAT(http_response_status_502_count_stat);
break;
case 503:
HTTP_INCREMENT_DYN_STAT(http_response_status_503_count_stat);
break;
case 504:
HTTP_INCREMENT_DYN_STAT(http_response_status_504_count_stat);
break;
case 505:
HTTP_INCREMENT_DYN_STAT(http_response_status_505_count_stat);
break;
default:
break;
}
switch (client_response_status / 100) {
case 1:
HTTP_INCREMENT_DYN_STAT(http_response_status_1xx_count_stat);
break;
case 2:
HTTP_INCREMENT_DYN_STAT(http_response_status_2xx_count_stat);
break;
case 3:
HTTP_INCREMENT_DYN_STAT(http_response_status_3xx_count_stat);
break;
case 4:
HTTP_INCREMENT_DYN_STAT(http_response_status_4xx_count_stat);
break;
case 5:
HTTP_INCREMENT_DYN_STAT(http_response_status_5xx_count_stat);
break;
default:
break;
}
}
// Increment the completed connection count
HTTP_INCREMENT_DYN_STAT(http_completed_requests_stat);
// Set the stat now that we know what happend
ink_hrtime total_msec = ink_hrtime_to_msec(total_time);
ink_hrtime process_msec = ink_hrtime_to_msec(request_process_time);
switch (client_transaction_result) {
case CLIENT_TRANSACTION_RESULT_HIT_FRESH:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_stat, total_msec);
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_process_stat, process_msec);
break;
case CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_reval_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_COLD:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_cold_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CHANGED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_changed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_client_no_cache_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_uncacheable_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_POSSIBLE_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_possible_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_connect_failed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_OTHER:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_other_stat, total_msec);
break;
default:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_other_unclassified_stat, total_msec);
// This can happen if a plugin manually sets the status code after an error.
TxnDebug("http", "Unclassified statistic");
break;
}
}
void
HttpTransact::origin_server_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime =
(transfer_time == 0) ? (nbytes) : (static_cast<float>(nbytes) / static_cast<float>(static_cast<int64_t>(transfer_time)));
int bytes_per_sec = static_cast<int>(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100M_stat);
}
return;
}
void
HttpTransact::update_size_and_time_stats(State *s, ink_hrtime total_time, ink_hrtime user_agent_write_time,
ink_hrtime origin_server_read_time, int user_agent_request_header_size,
int64_t user_agent_request_body_size, int user_agent_response_header_size,
int64_t user_agent_response_body_size, int origin_server_request_header_size,
int64_t origin_server_request_body_size, int origin_server_response_header_size,
int64_t origin_server_response_body_size, int pushed_response_header_size,
int64_t pushed_response_body_size, const TransactionMilestones &milestones)
{
int64_t user_agent_request_size = user_agent_request_header_size + user_agent_request_body_size;
int64_t user_agent_response_size = user_agent_response_header_size + user_agent_response_body_size;
int64_t user_agent_bytes = user_agent_request_size + user_agent_response_size;
int64_t origin_server_request_size = origin_server_request_header_size + origin_server_request_body_size;
int64_t origin_server_response_size = origin_server_response_header_size + origin_server_response_body_size;
int64_t origin_server_bytes = origin_server_request_size + origin_server_response_size;
// Background fill stats
switch (s->state_machine->background_fill) {
case BACKGROUND_FILL_COMPLETED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
bg_size = std::max(static_cast<int64_t>(0), bg_size);
HTTP_SUM_DYN_STAT(http_background_fill_bytes_completed_stat, bg_size);
break;
}
case BACKGROUND_FILL_ABORTED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
if (bg_size < 0) {
bg_size = 0;
}
HTTP_SUM_DYN_STAT(http_background_fill_bytes_aborted_stat, bg_size);
break;
}
case BACKGROUND_FILL_NONE:
break;
case BACKGROUND_FILL_STARTED:
default:
ink_assert(0);
}
// Bandwidth Savings
switch (s->squid_codes.log_code) {
case SQUID_LOG_TCP_HIT:
case SQUID_LOG_TCP_MEM_HIT:
case SQUID_LOG_TCP_CF_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_tcp_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_EXPIRED_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_expired_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_tcp_client_refresh_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CLIENT_ABORT:
HTTP_INCREMENT_DYN_STAT(http_err_client_abort_count_stat);
HTTP_SUM_DYN_STAT(http_err_client_abort_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_client_abort_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CLIENT_READ_ERROR:
HTTP_INCREMENT_DYN_STAT(http_err_client_read_error_count_stat);
HTTP_SUM_DYN_STAT(http_err_client_read_error_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_client_read_error_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_err_connect_fail_count_stat);
HTTP_SUM_DYN_STAT(http_err_connect_fail_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_connect_fail_origin_server_bytes_stat, origin_server_bytes);
break;
default:
HTTP_INCREMENT_DYN_STAT(http_misc_count_stat);
HTTP_SUM_DYN_STAT(http_misc_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_misc_origin_server_bytes_stat, origin_server_bytes);
break;
}
// times
HTTP_SUM_DYN_STAT(http_total_transactions_time_stat, total_time);
// sizes
HTTP_SUM_DYN_STAT(http_user_agent_request_header_total_size_stat, user_agent_request_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_header_total_size_stat, user_agent_response_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_request_document_total_size_stat, user_agent_request_body_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_document_total_size_stat, user_agent_response_body_size);
// proxy stats
if (s->current.request_to == HttpTransact::PARENT_PROXY) {
HTTP_SUM_DYN_STAT(http_parent_proxy_request_total_bytes_stat,
origin_server_request_header_size + origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_response_total_bytes_stat,
origin_server_response_header_size + origin_server_response_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_transaction_time_stat, total_time);
}
// request header zero means the document was cached.
// do not add to stats.
if (origin_server_request_header_size > 0) {
HTTP_SUM_DYN_STAT(http_origin_server_request_header_total_size_stat, origin_server_request_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_header_total_size_stat, origin_server_response_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_request_document_total_size_stat, origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_document_total_size_stat, origin_server_response_body_size);
}
if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_SUM_DYN_STAT(http_pushed_response_header_total_size_stat, pushed_response_header_size);
HTTP_SUM_DYN_STAT(http_pushed_document_total_size_stat, pushed_response_body_size);
}
histogram_request_document_size(s, user_agent_request_body_size);
histogram_response_document_size(s, user_agent_response_body_size);
if (user_agent_write_time >= 0) {
user_agent_connection_speed(s, user_agent_write_time, user_agent_response_size);
}
if (origin_server_request_header_size > 0 && origin_server_read_time > 0) {
origin_server_connection_speed(s, origin_server_read_time, origin_server_response_size);
}
// update milestones stats
HTTP_SUM_DYN_STAT(http_ua_begin_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN, 0));
HTTP_SUM_DYN_STAT(http_ua_first_read_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ, 0));
HTTP_SUM_DYN_STAT(http_ua_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE, 0));
HTTP_SUM_DYN_STAT(http_ua_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE, 0));
HTTP_SUM_DYN_STAT(http_ua_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE, 0));
HTTP_SUM_DYN_STAT(http_server_first_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_CONNECT, 0));
HTTP_SUM_DYN_STAT(http_server_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT, 0));
HTTP_SUM_DYN_STAT(http_server_connect_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END, 0));
HTTP_SUM_DYN_STAT(http_server_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_BEGIN_WRITE, 0));
HTTP_SUM_DYN_STAT(http_server_first_read_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ, 0));
HTTP_SUM_DYN_STAT(http_server_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE, 0));
HTTP_SUM_DYN_STAT(http_server_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE, 0));
HTTP_SUM_DYN_STAT(http_cache_open_read_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN, 0));
HTTP_SUM_DYN_STAT(http_cache_open_read_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END, 0));
HTTP_SUM_DYN_STAT(http_cache_open_write_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN, 0));
HTTP_SUM_DYN_STAT(http_cache_open_write_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_END, 0));
HTTP_SUM_DYN_STAT(http_dns_lookup_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN, 0));
HTTP_SUM_DYN_STAT(http_dns_lookup_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END, 0));
HTTP_SUM_DYN_STAT(http_sm_start_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_START, 0));
HTTP_SUM_DYN_STAT(http_sm_finish_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH, 0));
}
void
HttpTransact::delete_warning_value(HTTPHdr *to_warn, HTTPWarningCode warning_code)
{
int w_code = static_cast<int>(warning_code);
MIMEField *field = to_warn->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
// Loop over the values to see if we need to do anything
if (field) {
HdrCsvIter iter;
int val_code;
MIMEField *new_field = nullptr;
bool valid_p = iter.get_first_int(field, val_code);
while (valid_p) {
if (val_code == w_code) {
// Ok, found the value we're look to delete Look over and create a new field appending all
// elements that are not this value
valid_p = iter.get_first_int(field, val_code);
while (valid_p) {
if (val_code != warning_code) {
auto value = iter.get_current();
if (new_field) {
new_field->value_append(to_warn->m_heap, to_warn->m_mime, value.data(), value.size(), true);
} else {
new_field = to_warn->field_create();
to_warn->field_value_set(new_field, value.data(), value.size());
}
}
valid_p = iter.get_next_int(val_code);
}
to_warn->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
if (new_field) {
new_field->name_set(to_warn->m_heap, to_warn->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
to_warn->field_attach(new_field);
}
return;
}
valid_p = iter.get_next_int(val_code);
}
}
}
void
HttpTransact::change_response_header_because_of_range_request(State *s, HTTPHdr *header)
{
MIMEField *field;
char *reason_phrase;
TxnDebug("http_trans", "Partial content requested, re-calculating content-length");
header->status_set(HTTP_STATUS_PARTIAL_CONTENT);
reason_phrase = const_cast<char *>(http_hdr_reason_lookup(HTTP_STATUS_PARTIAL_CONTENT));
header->reason_set(reason_phrase, strlen(reason_phrase));
// set the right Content-Type for multiple entry Range
if (s->num_range_fields > 1) {
field = header->field_find(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
if (field != nullptr) {
header->field_delete(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
}
field = header->field_create(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
field->value_append(header->m_heap, header->m_mime, range_type, sizeof(range_type) - 1);
header->field_attach(field);
// TODO: There's a known bug here where the Content-Length is not correct for multi-part
// Range: requests.
header->set_content_length(s->range_output_cl);
} else {
if (s->cache_info.object_read && s->cache_info.object_read->valid()) {
// TODO: It's unclear under which conditions we need to update the Content-Range: header,
// many times it's already set correctly before calling this. For now, always try do it
// when we have the information for it available.
// TODO: Also, it's unclear as to why object_read->valid() is not always true here.
char numbers[RANGE_NUMBERS_LENGTH];
header->field_delete(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
field = header->field_create(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
snprintf(numbers, sizeof(numbers), "bytes %" PRId64 "-%" PRId64 "/%" PRId64, s->ranges[0]._start, s->ranges[0]._end,
s->cache_info.object_read->object_size_get());
field->value_set(header->m_heap, header->m_mime, numbers, strlen(numbers));
header->field_attach(field);
}
// Always update the Content-Length: header.
header->set_content_length(s->range_output_cl);
}
}
#if TS_HAS_TESTS
void forceLinkRegressionHttpTransact();
void
forceLinkRegressionHttpTransactCaller()
{
forceLinkRegressionHttpTransact();
}
#endif
|