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
|
/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2011-2014 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
STAGES
Accept connect password
|
\|/
Read header
|
\|/
+------+------+
| |
| |
\|/ |
Buffer |
request |
body |
| |
| |
\|/ |
Checkout <-------+
session
|
|
\|/
Send header
to app
|
|
\|/
Send request
body to app
OVERVIEW OF I/O CHANNELS, PIPES AND WATCHERS
OPTIONAL: appOutputWatcher
clientBodyBuffer (o)
| |
+----------+ | +-----------+ | +---------------+
| | ------ clientInput -----> | Request | ----------------> | |
| Client | fd | Handler | session | Application |
| | <--- clientOutputPipe --- | | <--- appInput --- | |
+----------+ | +-----------+ +---------------+
|
(o)
clientOutputWatcher
REQUEST BODY HANDLING STRATEGIES
This table describes how we should handle the request body (the part in the request
that comes after the request header, and may include WebSocket data), given various
factors. Strategies that are listed first have precedence.
Method 'Upgrade' 'Content-Length' or Application Action
header 'Transfer-Encoding' socket
present? header present? protocol
---------------------------------------------------------------------------------------------
GET/HEAD Y Y - Reject request[1]
Other Y - - Reject request[2]
GET/HEAD Y N http_session Set requestBodyLength=-1, keep socket open when done forwarding.
- N N http_session Set requestBodyLength=0, keep socket open when done forwarding.
- N Y http_session Keep socket open when done forwarding. If Transfer-Encoding is
chunked, rechunck the body during forwarding.
GET/HEAD Y N session Set requestBodyLength=-1, half-close app socket when done forwarding.
- N N session Set requestBodyLength=0, half-close app socket when done forwarding.
- N Y session Half-close app socket when done forwarding.
---------------------------------------------------------------------------------------------
[1] Supporting situations in which there is both an HTTP request body and WebSocket data
is way too complicated. The RequestHandler code is complicated enough as it is,
so we choose not to support requests like these.
[2] RFC 6455 states that WebSocket upgrades may only happen over GET requests.
We don't bother supporting non-WebSocket upgrades.
*/
#ifndef _PASSENGER_REQUEST_HANDLER_H_
#define _PASSENGER_REQUEST_HANDLER_H_
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/regex.hpp>
#include <boost/cstdint.hpp>
#include <ev++.h>
#if defined(__GLIBCXX__) || defined(__APPLE__)
#include <cxxabi.h>
#define CXX_ABI_API_AVAILABLE
#endif
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <utility>
#include <typeinfo>
#include <cassert>
#include <cctype>
#include <Logging.h>
#include <EventedBufferedInput.h>
#include <MessageReadersWriters.h>
#include <Constants.h>
#include <UnionStation/Core.h>
#include <UnionStation/Transaction.h>
#include <UnionStation/ScopeLog.h>
#include <ApplicationPool2/Pool.h>
#include <ApplicationPool2/ErrorRenderer.h>
#include <Utils/StrIntUtils.h>
#include <Utils/IOUtils.h>
#include <Utils/HttpHeaderBufferer.h>
#include <Utils/HttpConstants.h>
#include <Utils/Template.h>
#include <Utils/Timer.h>
#include <Utils/Dechunker.h>
#include <agents/HelperAgent/AgentOptions.h>
#include <agents/HelperAgent/FileBackedPipe.h>
#include <agents/HelperAgent/ScgiRequestParser.h>
namespace Passenger {
using namespace std;
using namespace boost;
using namespace oxt;
using namespace ApplicationPool2;
class RequestHandler;
#define MAX_STATUS_HEADER_SIZE 64
#define RH_ERROR(client, x) P_ERROR("[Client " << client->name() << "] " << x)
#define RH_WARN(client, x) P_WARN("[Client " << client->name() << "] " << x)
#define RH_DEBUG(client, x) P_DEBUG("[Client " << client->name() << "] " << x)
#define RH_TRACE(client, level, x) P_TRACE(level, "[Client " << client->name() << "] " << x)
#define RH_LOG_EVENT(client, eventName) \
char _clientName[7 + 8]; \
snprintf(_clientName, sizeof(_clientName), "Client %d", client->fdnum); \
TRACE_POINT_WITH_DATA(_clientName); \
RH_TRACE(client, 3, "Event: " eventName)
class Client: public boost::enable_shared_from_this<Client> {
private:
struct ev_loop *getLoop() const;
const SafeLibevPtr &getSafeLibev() const;
unsigned int getConnectPasswordTimeout(const RequestHandler *handler) const;
static size_t onClientInputData(const EventedBufferedInputPtr &source, const StaticString &data);
static void onClientInputError(const EventedBufferedInputPtr &source, const char *message, int errnoCode);
static void onClientBodyBufferData(const FileBackedPipePtr &source,
const char *data, size_t size,
const FileBackedPipe::ConsumeCallback &callback);
static void onClientBodyBufferEnd(const FileBackedPipePtr &source);
static void onClientBodyBufferError(const FileBackedPipePtr &source, int errorCode);
static void onClientBodyBufferCommit(const FileBackedPipePtr &source);
static void onClientOutputPipeData(const FileBackedPipePtr &source,
const char *data, size_t size,
const FileBackedPipe::ConsumeCallback &callback);
static void onClientOutputPipeEnd(const FileBackedPipePtr &source);
static void onClientOutputPipeError(const FileBackedPipePtr &source, int errorCode);
static void onClientOutputPipeCommit(const FileBackedPipePtr &source);
void onClientOutputWritable(ev::io &io, int revents);
static size_t onAppInputData(const EventedBufferedInputPtr &source, const StaticString &data);
static void onAppInputChunk(const char *data, size_t size, void *userData);
static void onAppInputChunkEnd(void *userData);
static void onAppInputError(const EventedBufferedInputPtr &source, const char *message, int errnoCode);
void onAppOutputWritable(ev::io &io, int revents);
void onTimeout(ev::timer &timer, int revents);
static const char *boolStr(bool val) {
static const char *strs[] = { "false", "true" };
return strs[val];
}
void resetPrimitiveFields() {
requestHandler = NULL;
state = DISCONNECTED;
backgroundOperations = 0;
requestBodyIsBuffered = false;
requestIsChunked = false;
freeBufferedConnectPassword();
connectedAt = 0;
requestBodyLength = 0;
requestBodyAlreadyRead = 0;
checkoutSessionAfterCommit = false;
stickySession = false;
sessionCheckedOut = false;
sessionCheckoutTry = 0;
responseHeaderSeen = false;
chunkedResponse = false;
responseContentLength = -1;
responseBodyAlreadyRead = 0;
appRoot.clear();
}
void freeScopeLogs() {
endScopeLog(&scopeLogs.requestProxying, false);
endScopeLog(&scopeLogs.getFromPool, false);
endScopeLog(&scopeLogs.bufferingRequestBody, false);
endScopeLog(&scopeLogs.requestProcessing, false);
}
public:
/** Back reference to the RequestHandler that this Client is associated with.
* NULL when this Client is not in the pool or is disconnected. */
RequestHandler *requestHandler;
/** File descriptor of the client socket. Is empty when this Client is not
* in the pool or is disconnected. */
FileDescriptor fd;
/** The last associated file descriptor number is stored here. It is not
* cleared after disassociating. Its only purpose is to make logging calls
* like RH_DEBUG() print the correct client name after disconnect() is called.
* Do not use this value for anything else as it may not refer to a valid
* file descriptor. */
int fdnum;
/***** Client <-> RequestHandler I/O channels, pipes and watchers *****/
/** Client input channel. */
EventedBufferedInputPtr clientInput;
/** If request body buffering is turned on, it will be buffered into this FileBackedPipe. */
FileBackedPipePtr clientBodyBuffer;
/** Client output pipe. */
FileBackedPipePtr clientOutputPipe;
/** Client output channel watcher. */
ev::io clientOutputWatcher;
/***** RequestHandler <-> Application I/O channels, pipes and watchers *****/
/** Application input channel. */
EventedBufferedInputPtr appInput;
string appOutputBuffer;
/** Application output channel watcher. */
ev::io appOutputWatcher;
/***** State variables *****/
enum {
BEGIN_READING_CONNECT_PASSWORD,
STILL_READING_CONNECT_PASSWORD,
READING_HEADER,
BUFFERING_REQUEST_BODY,
CHECKING_OUT_SESSION,
SENDING_HEADER_TO_APP,
FORWARDING_BODY_TO_APP,
// Special states
WRITING_SIMPLE_RESPONSE,
DISCONNECTED
} state;
/* How many background operations are currently in progress, e.g.
* an asyncGet() or bodyBuffer.add(). If the client is disconnected
* while this flag is true, then the Client object is not reassociateable
* in order to give the completion callbacks a chance to cancel properly.
*/
unsigned int backgroundOperations;
struct {
char *data;
unsigned int alreadyRead;
} bufferedConnectPassword;
// Used for enforcing the connection timeout.
ev::timer timeoutTimer;
ev_tstamp connectedAt;
/** The size of the request body. The request body is the part that comes
* after the request headers, which may be the HTTP request message body,
* but may also be any other arbitrary data that is sent over the request
* socket (e.g. WebSocket data).
*
* Possible values:
*
* -1: infinite. Should keep forwarding client body until end of stream.
* 0: no client body. Should stop after sending headers to application.
* >0: Should forward exactly this many bytes of the client body.
*/
long long requestBodyLength;
unsigned long long requestBodyAlreadyRead;
Options options;
ScgiRequestParser scgiParser;
SessionPtr session;
string appRoot;
struct {
UnionStation::ScopeLog
*requestProcessing,
*bufferingRequestBody,
*getFromPool,
*requestProxying;
} scopeLogs;
unsigned int sessionCheckoutTry;
bool requestBodyIsBuffered;
bool requestIsChunked;
bool sessionCheckedOut;
bool checkoutSessionAfterCommit;
bool stickySession;
bool responseHeaderSeen;
bool chunkedResponse;
/** The size of the response body, set based on the values of
* the Content-Length and Transfer-Encoding response headers.
* Possible values:
*
* -1: infinite. Should keep forwarding response body until end of stream.
* This is the case for WebSockets or for responses without Content-Length.
* Responses with "Transfer-Encoding: chunked" also fall under this
* category, though in this case encountering the zero-length chunk is
* treated the same as end of stream.
* 0 : no client body. Should immediately close connection after forwarding
* headers.
* >0: Should forward exactly this many bytes of the response body.
*/
long long responseContentLength;
unsigned long long responseBodyAlreadyRead;
HttpHeaderBufferer responseHeaderBufferer;
Dechunker responseDechunker;
Client() {
fdnum = -1;
clientInput = boost::make_shared< EventedBufferedInput<> >();
clientInput->onData = onClientInputData;
clientInput->onError = onClientInputError;
clientInput->userData = this;
clientBodyBuffer = boost::make_shared<FileBackedPipe>("/tmp");
clientBodyBuffer->userData = this;
clientBodyBuffer->onData = onClientBodyBufferData;
clientBodyBuffer->onEnd = onClientBodyBufferEnd;
clientBodyBuffer->onError = onClientBodyBufferError;
clientBodyBuffer->onCommit = onClientBodyBufferCommit;
clientOutputPipe = boost::make_shared<FileBackedPipe>("/tmp");
clientOutputPipe->userData = this;
clientOutputPipe->onData = onClientOutputPipeData;
clientOutputPipe->onEnd = onClientOutputPipeEnd;
clientOutputPipe->onError = onClientOutputPipeError;
clientOutputPipe->onCommit = onClientOutputPipeCommit;
clientOutputWatcher.set<Client, &Client::onClientOutputWritable>(this);
appInput = boost::make_shared< EventedBufferedInput<> >();
appInput->onData = onAppInputData;
appInput->onError = onAppInputError;
appInput->userData = this;
appOutputWatcher.set<Client, &Client::onAppOutputWritable>(this);
timeoutTimer.set<Client, &Client::onTimeout>(this);
responseDechunker.onData = onAppInputChunk;
responseDechunker.onEnd = onAppInputChunkEnd;
responseDechunker.userData = this;
bufferedConnectPassword.data = NULL;
bufferedConnectPassword.alreadyRead = 0;
memset(&scopeLogs, 0, sizeof(scopeLogs));
resetPrimitiveFields();
}
~Client() {
if (requestHandler != NULL) {
discard();
}
clientInput->userData = NULL;
clientBodyBuffer->userData = NULL;
clientOutputPipe->userData = NULL;
appInput->userData = NULL;
freeBufferedConnectPassword();
freeScopeLogs();
}
void associate(RequestHandler *handler, const FileDescriptor &_fd) {
assert(requestHandler == NULL);
requestHandler = handler;
fd = _fd;
fdnum = _fd;
state = BEGIN_READING_CONNECT_PASSWORD;
connectedAt = ev_time();
clientInput->reset(getSafeLibev().get(), _fd);
clientInput->start();
clientBodyBuffer->reset(getSafeLibev());
clientOutputPipe->reset(getSafeLibev());
clientOutputPipe->start();
clientOutputWatcher.set(getLoop());
clientOutputWatcher.set(_fd, ev::WRITE);
// appOutputWatcher is initialized in initiateSession.
timeoutTimer.set(getLoop());
timeoutTimer.start(getConnectPasswordTimeout(handler) / 1000.0, 0.0);
}
void disassociate() {
assert(requestHandler != NULL);
resetPrimitiveFields();
fd = FileDescriptor();
clientInput->reset(NULL, FileDescriptor());
clientBodyBuffer->reset();
clientOutputPipe->reset();
clientOutputWatcher.stop();
appInput->reset(NULL, FileDescriptor());
appOutputBuffer.resize(0);
appOutputWatcher.stop();
timeoutTimer.stop();
scgiParser.reset();
session.reset();
responseHeaderBufferer.reset();
responseDechunker.reset();
freeScopeLogs();
}
void discard() {
assert(requestHandler != NULL);
resetPrimitiveFields();
fd = FileDescriptor();
clientInput->stop();
clientBodyBuffer->reset();
clientOutputPipe->reset();
clientOutputWatcher.stop();
appInput->stop();
appOutputWatcher.stop();
timeoutTimer.stop();
freeScopeLogs();
requestHandler = NULL;
}
bool reassociateable() const {
return requestHandler == NULL
&& backgroundOperations == 0
&& clientInput->resetable()
&& clientBodyBuffer->resetable()
&& clientOutputPipe->resetable()
&& appInput->resetable();
}
string name() const {
if (fdnum == -1) {
return "(null)";
} else {
return toString(fdnum);
}
}
bool connected() const {
return requestHandler != NULL;
}
const char *getStateName() const {
switch (state) {
case BEGIN_READING_CONNECT_PASSWORD:
return "BEGIN_READING_CONNECT_PASSWORD";
case STILL_READING_CONNECT_PASSWORD:
return "STILL_READING_CONNECT_PASSWORD";
case READING_HEADER:
return "READING_HEADER";
case BUFFERING_REQUEST_BODY:
return "BUFFERING_REQUEST_BODY";
case CHECKING_OUT_SESSION:
return "CHECKING_OUT_SESSION";
case SENDING_HEADER_TO_APP:
return "SENDING_HEADER_TO_APP";
case FORWARDING_BODY_TO_APP:
return "FORWARDING_BODY_TO_APP";
case WRITING_SIMPLE_RESPONSE:
return "WRITING_SIMPLE_RESPONSE";
case DISCONNECTED:
return "DISCONNECTED";
default:
return "UNKNOWN";
}
}
void freeBufferedConnectPassword() {
if (bufferedConnectPassword.data != NULL) {
free(bufferedConnectPassword.data);
bufferedConnectPassword.data = NULL;
bufferedConnectPassword.alreadyRead = 0;
}
}
/**
* Checks whether we should half-close the application socket after forwarding
* the request. HTTP does not formally support half-closing, and Node.js treats a
* half-close as a full close, so we only half-close session sockets, not
* HTTP sockets.
*/
bool shouldHalfCloseWrite() const {
return session->getProtocol() == "session";
}
bool useUnionStation() const {
return options.transaction != NULL;
}
UnionStation::TransactionPtr getUnionStationTransaction() const {
return options.transaction;
}
void beginScopeLog(UnionStation::ScopeLog **scopeLog, const char *name) {
if (options.transaction != NULL) {
*scopeLog = new UnionStation::ScopeLog(options.transaction, name);
}
}
void endScopeLog(UnionStation::ScopeLog **scopeLog, bool success = true) {
if (success && *scopeLog != NULL) {
(*scopeLog)->success();
}
delete *scopeLog;
*scopeLog = NULL;
}
void logMessage(const StaticString &message) {
options.transaction->message(message);
}
void verifyInvariants() const {
assert((requestHandler == NULL) == (fd == -1));
assert((requestHandler == NULL) == (state == DISCONNECTED));
}
template<typename Stream>
void inspect(Stream &stream) const {
const char *indent = " ";
time_t the_time;
struct tm the_tm;
char timestr[60];
the_time = (time_t) connectedAt;
localtime_r(&the_time, &the_tm);
strftime(timestr, sizeof(timestr) - 1, "%F %H:%M:%S", &the_tm);
stream << indent << "host = " << (scgiParser.getHeader("HTTP_HOST").empty() ? "(empty)" : scgiParser.getHeader("HTTP_HOST")) << "\n";
stream << indent << "uri = " << (scgiParser.getHeader("REQUEST_URI").empty() ? "(empty)" : scgiParser.getHeader("REQUEST_URI")) << "\n";
stream << indent << "connected at = " << timestr << " (" << (unsigned long long) (ev_time() - connectedAt) << " sec ago)\n";
stream << indent << "state = " << getStateName() << "\n";
if (session == NULL) {
stream << indent << "session = NULL\n";
} else {
stream << indent << "session pid = " << session->getPid() << " (" <<
session->getGroup()->name << ")\n";
stream << indent << "session gupid = " << session->getGupid() << "\n";
stream << indent << "session initiated = " << boolStr(session->initiated()) << "\n";
}
stream
<< indent << "requestBodyIsBuffered = " << boolStr(requestBodyIsBuffered) << "\n"
<< indent << "requestIsChunked = " << boolStr(requestIsChunked) << "\n"
<< indent << "requestBodyLength = " << requestBodyLength << "\n"
<< indent << "requestBodyAlreadyRead = " << requestBodyAlreadyRead << "\n"
<< indent << "responseContentLength = " << responseContentLength << "\n"
<< indent << "responseBodyAlreadyRead = " << responseBodyAlreadyRead << "\n"
<< indent << "clientInput = " << clientInput.get() << " " << clientInput->inspect() << "\n"
<< indent << "clientInput started = " << boolStr(clientInput->isStarted()) << "\n"
<< indent << "clientBodyBuffer started = " << boolStr(clientBodyBuffer->isStarted()) << "\n"
<< indent << "clientBodyBuffer reachedEnd = " << boolStr(clientBodyBuffer->reachedEnd()) << "\n"
<< indent << "clientOutputPipe started = " << boolStr(clientOutputPipe->isStarted()) << "\n"
<< indent << "clientOutputPipe reachedEnd = " << boolStr(clientOutputPipe->reachedEnd()) << "\n"
<< indent << "clientOutputWatcher active = " << boolStr(clientOutputWatcher.is_active()) << "\n"
<< indent << "appInput = " << appInput.get() << " " << appInput->inspect() << "\n"
<< indent << "appInput started = " << boolStr(appInput->isStarted()) << "\n"
<< indent << "appInput reachedEnd = " << boolStr(appInput->endReached()) << "\n"
<< indent << "responseHeaderSeen = " << boolStr(responseHeaderSeen) << "\n"
<< indent << "useUnionStation = " << boolStr(useUnionStation()) << "\n"
;
}
};
typedef boost::shared_ptr<Client> ClientPtr;
class RequestHandler {
public:
enum BenchmarkPoint {
BP_NONE,
BP_AFTER_ACCEPT,
BP_AFTER_CHECK_CONNECT_PASSWORD,
BP_AFTER_PARSING_HEADER,
BP_BEFORE_CHECKOUT_SESSION
};
private:
friend class Client;
const SafeLibevPtr libev;
FileDescriptor requestSocket;
PoolPtr pool;
const AgentOptions &options;
const ResourceLocator resourceLocator;
UnionStation::CorePtr unionStationCore;
ev::io requestSocketWatcher;
ev::timer resumeSocketWatcherTimer;
HashMap<int, ClientPtr> clients;
Timer inactivityTimer;
bool accept4Available;
boost::regex upgradeHeaderRegex;
void disconnect(const ClientPtr &client) {
// Prevent Client object from being destroyed until we're done.
ClientPtr reference = client;
clients.erase(client->fd);
client->discard();
client->verifyInvariants();
RH_DEBUG(client, "Disconnected; new client count = " << clients.size());
if (clients.empty()) {
inactivityTimer.start();
}
}
void disconnectWithError(const ClientPtr &client, const StaticString &message) {
RH_WARN(client, "Disconnecting with error: " << message);
if (client->useUnionStation()) {
client->logMessage("Disconnecting with error: " + message);
}
disconnect(client);
}
void disconnectWithClientSocketWriteError(const ClientPtr &client, int e) {
stringstream message;
message << "client socket write error: ";
message << strerror(e);
message << " (errno=" << e << ")";
disconnectWithError(client, message.str());
}
void disconnectWithAppSocketWriteError(const ClientPtr &client, int e) {
stringstream message;
message << "app socket write error: ";
message << strerror(e);
message << " (errno=" << e << ")";
disconnectWithError(client, message.str());
}
void disconnectWithWarning(const ClientPtr &client, const StaticString &message) {
P_DEBUG("Disconnected client " << client->name() << " with warning: " << message);
disconnect(client);
}
template<typename Number>
static Number clamp(Number n, Number min, Number max) {
if (n < min) {
return min;
} else if (n > max) {
return max;
} else {
return n;
}
}
// GDB helper function, implemented in .cpp file to prevent inlining.
Client *getClientPointer(const ClientPtr &client);
void doResetInactivityTime() {
inactivityTimer.reset();
}
void getInactivityTime(unsigned long long *result) const {
*result = inactivityTimer.elapsed();
}
static bool getBoolOption(const ClientPtr &client, const StaticString &name, bool defaultValue = false) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
return it->second == "true";
} else {
return defaultValue;
}
}
static long long getULongLongOption(const ClientPtr &client, const StaticString &name, long long defaultValue = -1) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
long long result = stringToULL(it->second);
// The client may send a malicious integer, so check for this.
if (result < 0) {
return defaultValue;
} else {
return result;
}
} else {
return defaultValue;
}
}
bool friendlyErrorPagesEnabled(const ClientPtr &client) const {
bool defaultValue = client->options.environment != "staging"
&& client->options.environment != "production";
return getBoolOption(client, "PASSENGER_FRIENDLY_ERROR_PAGES", defaultValue);
}
void writeSimpleResponse(const ClientPtr &client, const StaticString &data, int code = 200) {
char header[256], statusBuffer[50];
char *pos = header;
const char *end = header + sizeof(header) - 1;
const char *status;
status = getStatusCodeAndReasonPhrase(code);
if (status == NULL) {
snprintf(statusBuffer, sizeof(statusBuffer), "%d Unknown Reason-Phrase", code);
status = statusBuffer;
}
if (getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
pos += snprintf(pos, end - pos, "HTTP/1.1 %s\r\n",
status);
}
pos += snprintf(pos, end - pos,
"Status: %s\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Cache-Control: no-cache, no-store, must-revalidate\r\n"
"\r\n",
status, (unsigned long) data.size());
client->clientOutputPipe->write(header, pos - header);
if (!client->connected()) {
return;
}
client->clientOutputPipe->write(data.data(), data.size());
if (!client->connected()) {
return;
}
client->clientOutputPipe->end();
if (!client->connected()) {
return;
}
if (client->useUnionStation()) {
snprintf(header, end - header, "Status: %d %s",
code, status);
client->logMessage(header);
}
}
void writeErrorResponse(const ClientPtr &client, const StaticString &message, const SpawnException *e = NULL) {
assert(client->state < Client::FORWARDING_BODY_TO_APP);
client->state = Client::WRITING_SIMPLE_RESPONSE;
ErrorRenderer renderer(resourceLocator);
string data;
if (friendlyErrorPagesEnabled(client)) {
try {
data = renderer.renderWithDetails(message, client->options, e);
} catch (const SystemException &e2) {
P_ERROR("Cannot render an error page: " << e2.what() << "\n" <<
e2.backtrace());
data = message;
}
} else {
try {
data = renderer.renderWithoutDetails();
} catch (const SystemException &e2) {
P_ERROR("Cannot render an error page: " << e2.what() << "\n" <<
e2.backtrace());
data = "Internal Server Error";
}
}
stringstream str;
if (getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
str << "HTTP/1.1 500 Internal Server Error\r\n";
}
str << "Status: 500 Internal Server Error\r\n";
str << "Content-Length: " << data.size() << "\r\n";
str << "Content-Type: text/html; charset=UTF-8\r\n";
str << "Cache-Control: no-cache, no-store, must-revalidate\r\n";
str << "\r\n";
const string header = str.str();
client->clientOutputPipe->write(header.data(), header.size());
if (!client->connected()) {
return;
}
client->clientOutputPipe->write(data.data(), data.size());
if (!client->connected()) {
return;
}
client->clientOutputPipe->end();
if (!client->connected()) {
return;
}
if (client->useUnionStation()) {
client->logMessage("Status: 500 Internal Server Error");
// TODO: record error message
}
}
static BenchmarkPoint getDefaultBenchmarkPoint() {
const char *val = getenv("PASSENGER_REQUEST_HANDLER_BENCHMARK_POINT");
if (val == NULL || *val == '\0') {
return BP_NONE;
} else if (strcmp(val, "after_accept") == 0) {
return BP_AFTER_ACCEPT;
} else if (strcmp(val, "after_check_connect_password") == 0) {
return BP_AFTER_CHECK_CONNECT_PASSWORD;
} else if (strcmp(val, "after_parsing_header") == 0) {
return BP_AFTER_PARSING_HEADER;
} else if (strcmp(val, "before_checkout_session") == 0) {
return BP_BEFORE_CHECKOUT_SESSION;
} else {
P_WARN("Invalid RequestHandler benchmark point requested: " << val);
return BP_NONE;
}
}
/*****************************************************
* COMPONENT: appInput -> clientOutputPipe plumbing
*
* The following code receives data from appInput,
* possibly modifies it, and forwards it to
* clientOutputPipe.
*****************************************************/
struct Header {
StaticString key;
StaticString value;
Header() { }
Header(const StaticString &_key, const StaticString &_value)
: key(_key),
value(_value)
{ }
bool empty() const {
return key.empty();
}
const char *begin() const {
return key.data();
}
const char *end() const {
return value.data() + value.size() + sizeof("\r\n") - 1;
}
size_t size() const {
return end() - begin();
}
};
/** Given a substring containing the start of the header value,
* extracts the substring that contains a single header value.
*
* const char *data =
* "Status: 200 OK\r\n"
* "Foo: bar\r\n";
* extractHeaderValue(data + strlen("Status:"), strlen(data) - strlen("Status:"));
* // "200 OK"
*/
static StaticString extractHeaderValue(const char *data, size_t size) {
const char *start = data;
const char *end = data + size;
const char *terminator;
while (start < end && *start == ' ') {
start++;
}
terminator = (const char *) memchr(start, '\r', end - start);
if (terminator == NULL) {
return StaticString();
} else {
return StaticString(start, terminator - start);
}
}
static Header lookupHeader(const StaticString &headerData, const StaticString &name) {
string::size_type searchStart = 0;
while (searchStart < headerData.size()) {
string::size_type pos = headerData.find(name, searchStart);
if (OXT_UNLIKELY(pos == string::npos)) {
return Header();
} else if ((pos == 0 || headerData[pos - 1] == '\n')
&& headerData.size() > pos + name.size()
&& headerData[pos + name.size()] == ':')
{
StaticString value = extractHeaderValue(
headerData.data() + pos + name.size() + 1,
headerData.size() - pos - name.size() - 1);
return Header(headerData.substr(pos, name.size()), value);
} else {
searchStart = pos + name.size() + 1;
}
}
return Header();
}
static Header lookupHeader(const StaticString &headerData, const StaticString &name,
const StaticString &name2)
{
Header header = lookupHeader(headerData, name);
if (header.empty()) {
header = lookupHeader(headerData, name2);
}
return header;
}
bool addStatusHeaderFromStatusLine(const ClientPtr &client, string &headerData) {
string::size_type begin, end;
begin = headerData.find(' ');
if (begin != string::npos) {
end = headerData.find("\r\n", begin + 1);
} else {
end = string::npos;
}
if (begin != string::npos && end != string::npos) {
StaticString statusValue(headerData.data() + begin + 1, end - begin);
if (statusValue.size() <= MAX_STATUS_HEADER_SIZE) {
char header[MAX_STATUS_HEADER_SIZE + sizeof("Status: \r\n")];
char *pos = header;
const char *end = header + sizeof(header);
pos = appendData(pos, end, "Status: ");
pos = appendData(pos, end, statusValue);
pos = appendData(pos, end, "\r\n");
headerData.append(StaticString(header, pos - header));
return true;
} else {
disconnectWithError(client, "application sent malformed response: the Status header's (" +
statusValue + ") exceeds the allowed limit of " +
toString(MAX_STATUS_HEADER_SIZE) + " bytes.");
return false;
}
} else {
disconnectWithError(client, "application sent malformed response: the HTTP status line is invalid.");
return false;
}
}
static bool addReasonPhrase(string &headerData, const Header &status) {
if (status.value.find(' ') == string::npos) {
int statusCode = stringToInt(status.value);
const char *statusCodeAndReasonPhrase = getStatusCodeAndReasonPhrase(statusCode);
char newStatus[100];
char *pos = newStatus;
const char *end = newStatus + sizeof(newStatus);
pos = appendData(pos, end, "Status: ");
if (statusCodeAndReasonPhrase == NULL) {
pos = appendData(pos, end, toString(statusCode));
pos = appendData(pos, end, " Unknown Reason-Phrase\r\n");
} else {
pos = appendData(pos, end, statusCodeAndReasonPhrase);
pos = appendData(pos, end, "\r\n");
}
headerData.replace(status.begin() - headerData.data(), status.size(),
newStatus, pos - newStatus);
return true;
} else {
return false;
}
}
bool removeStatusLine(const ClientPtr &client, string &headerData) {
string::size_type end = headerData.find("\r\n");
if (end != string::npos) {
headerData.erase(0, end + 2);
return true;
} else {
disconnectWithError(client, "application sent malformed response: the HTTP status line is invalid.");
return false;
}
}
static void addStatusLineFromStatusHeader(string &headerData, const Header &status) {
char statusLine[100];
char *pos = statusLine;
const char *end = statusLine + sizeof(statusLine);
pos = appendData(pos, end, "HTTP/1.1 ");
pos = appendData(pos, end, status.value);
pos = appendData(pos, end, "\r\n");
headerData.insert(0, statusLine, pos - statusLine);
}
static void removeHeader(string &headerData, const Header &header) {
headerData.erase(header.begin() - headerData.data(), header.size());
}
/*
* Given a full header, possibly modify the header and send it to the clientOutputPipe.
*/
bool processResponseHeader(const ClientPtr &client,
const StaticString &origHeaderData)
{
string headerData;
headerData.reserve(origHeaderData.size() + 150);
// Strip trailing CRLF.
headerData.append(origHeaderData.data(), origHeaderData.size() - 2);
if (startsWith(headerData, "HTTP/1.")) {
Header status = lookupHeader(headerData, "Status", "status");
if (status.empty()) {
// Add status header if necessary.
if (!addStatusHeaderFromStatusLine(client, headerData)) {
return false;
}
} else {
// Add reason phrase to existing status header if necessary.
addReasonPhrase(headerData, status);
}
// Remove status line if necesary.
if (!getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
if (!removeStatusLine(client, headerData)) {
return false;
}
}
} else {
Header status = lookupHeader(headerData, "Status", "status");
if (!status.empty()) {
// Add reason phrase to status header if necessary.
if (addReasonPhrase(headerData, status)) {
status = lookupHeader(headerData, "Status", "status");
}
// Add status line if necessary.
if (getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
addStatusLineFromStatusHeader(headerData, status);
}
} else {
disconnectWithError(client, "application sent malformed response: it didn't send an HTTP status line or a Status header.");
return false;
}
}
if (client->useUnionStation()) {
Header status = lookupHeader(headerData, "Status", "status");
string message = "Status: ";
message.append(status.value);
client->logMessage(message);
}
// Process chunked transfer encoding.
Header transferEncoding = lookupHeader(headerData, "Transfer-Encoding", "transfer-encoding");
if (!transferEncoding.empty() && transferEncoding.value == "chunked") {
RH_TRACE(client, 3, "Response with chunked transfer encoding detected.");
client->chunkedResponse = true;
removeHeader(headerData, transferEncoding);
} else {
Header contentLength = lookupHeader(headerData, "Content-Length", "content-length");
if (!contentLength.empty()) {
client->responseContentLength = stringToLL(contentLength.value);
}
}
Header connection = lookupHeader(headerData, "Connection", "connection");
if (!connection.empty() && (connection.value == "keep-alive"
|| connection.value == "Keep-Alive"))
{
RH_TRACE(client, 3, "Keep-alive response detected. Changing to non-keep alive.");
removeHeader(headerData, connection);
headerData.append("Connection: close\r\n");
}
// Add X-Powered-By.
if (getBoolOption(client, "PASSENGER_SHOW_VERSION_IN_HEADER", true)) {
headerData.append("X-Powered-By: Phusion Passenger " PASSENGER_VERSION "\r\n");
} else {
headerData.append("X-Powered-By: Phusion Passenger\r\n");
}
// Add sticky session ID.
if (client->stickySession && client->session != NULL) {
StaticString baseURI = client->scgiParser.getHeader("SCRIPT_NAME");
if (baseURI.empty()) {
baseURI = StaticString("/", 1);
}
StaticString cookieName = getStickySessionCookieName(client);
// Note that we do NOT set HttpOnly. If we set that flag then Chrome
// doesn't send cookies over WebSocket handshakes. Confirmed on Chrome 25.
headerData.append("Set-Cookie: ");
headerData.append(cookieName.data(), cookieName.size());
headerData.append("=");
headerData.append(toString(client->session->getStickySessionId()));
headerData.append("; Path=");
headerData.append(baseURI.data(), baseURI.size());
headerData.append("\r\n");
// Invalidate all cookies with a different route.
//
// TODO: This is not entirely correct. Clients MAY send multiple Cookie
// headers, although this is in practice extremely rare.
// http://stackoverflow.com/questions/16305814/are-multiple-cookie-headers-allowed-in-an-http-request
StaticString cookieHeader = client->scgiParser.getHeader("HTTP_COOKIE");
vector< pair<StaticString, StaticString> > cookies;
pair<StaticString, StaticString> cookie;
parseCookieHeader(cookieHeader, cookies);
foreach (cookie, cookies) {
if (cookie.first == cookieName) {
unsigned int stickySessionId = stringToUint(cookie.second);
if (stickySessionId != client->session->getStickySessionId()) {
headerData.append("Set-Cookie: ");
headerData.append(cookie.first.data(), cookie.first.size());
headerData.append("=");
headerData.append(cookie.second.data(), cookie.second.size());
headerData.append("; Path=");
headerData.append(baseURI.data(), baseURI.size());
headerData.append("; Expires=Thu, 01 Jan 1970 00:00:00 GMT\r\n");
}
}
}
}
// Add Date header. https://code.google.com/p/phusion-passenger/issues/detail?id=485
if (lookupHeader(headerData, "Date", "date").empty()) {
char dateStr[60];
char *pos = dateStr;
const char *end = dateStr + sizeof(dateStr) - 1;
time_t the_time = time(NULL);
struct tm the_tm;
pos = appendData(pos, end, "Date: ");
gmtime_r(&the_time, &the_tm);
pos += strftime(pos, end - pos, "%a, %d %b %Y %H:%M:%S %Z", &the_tm);
pos = appendData(pos, end, "\r\n");
headerData.append(dateStr, pos - dateStr);
}
// Detect out of band work request
Header oobw = lookupHeader(headerData, "X-Passenger-Request-OOB-Work", "x-passenger-request-oob-work");
if (!oobw.empty()) {
P_TRACE(3, "Response with oobw detected.");
if (client->session != NULL) {
client->session->requestOOBW();
}
removeHeader(headerData, oobw);
}
P_TRACE(2, "Fowarding response header from app client: " << headerData);
headerData.append("\r\n");
writeToClientOutputPipe(client, headerData);
return true;
}
void writeToClientOutputPipe(const ClientPtr &client, const StaticString &data) {
bool wasCommittingToDisk = client->clientOutputPipe->isCommittingToDisk();
bool nowCommittingToDisk = !client->clientOutputPipe->write(data.data(), data.size());
if (!client->connected()) {
// EPIPE/ECONNRESET detected.
return;
}
if (!wasCommittingToDisk && nowCommittingToDisk) {
RH_TRACE(client, 3, "Buffering response data to disk; temporarily stopping application socket.");
client->backgroundOperations++;
// If the data comes from writeErrorResponse(), then appInput is not available.
if (client->session != NULL && client->session->initiated()) {
client->appInput->stop();
}
}
}
size_t onAppInputData(const ClientPtr &client, const StaticString &data) {
RH_LOG_EVENT(client, "onAppInputData");
if (!client->connected()) {
return 0;
}
if (!data.empty()) {
RH_TRACE(client, 3, "Application sent data: \"" << cEscapeString(data) << "\"");
// Buffer the application response until we've encountered the end of the header.
if (!client->responseHeaderSeen) {
size_t consumed = client->responseHeaderBufferer.feed(data.data(), data.size());
if (!client->responseHeaderBufferer.acceptingInput()) {
if (client->responseHeaderBufferer.hasError()) {
disconnectWithError(client, "application response format error (invalid header)");
} else {
// Now that we have a full header, do something with it.
RH_TRACE(client, 3, "Response header fully buffered");
client->responseHeaderSeen = true;
StaticString header = client->responseHeaderBufferer.getData();
if (processResponseHeader(client, header)) {
if (client->responseContentLength == 0) {
RH_TRACE(client, 3, "Disconnecting client because response Content-Length = 0");
onAppInputEof(client);
}
return consumed;
} else {
assert(!client->connected());
}
}
}
// The header has already been processed so forward it
// directly to clientOutputPipe, possibly through a
// dechunker first.
} else if (client->chunkedResponse) {
client->responseDechunker.feed(data.data(), data.size());
} else {
onAppInputChunk(client, data);
}
return data.size();
} else {
onAppInputEof(client);
return 0;
}
}
void onAppInputChunk(const ClientPtr &client, const StaticString &data) {
RH_LOG_EVENT(client, "onAppInputChunk");
StaticString data2;
if (client->responseContentLength == -1) {
data2 = data;
} else {
size_t rest = client->responseContentLength -
client->responseBodyAlreadyRead;
data2 = StaticString(data.data(), std::min<size_t>(
rest, data.size()));
}
client->responseBodyAlreadyRead += data2.size();
assert(client->responseContentLength == -1 || client->responseBodyAlreadyRead <=
(unsigned long long) client->responseContentLength);
if (data2.empty()) {
// Client sent more data than was advertised through
// Content-Length. Ignore them.
return;
}
writeToClientOutputPipe(client, data2);
if (client->responseContentLength > 0) {
RH_TRACE(client, 3, client->responseBodyAlreadyRead << "/" <<
client->responseContentLength <<
" bytes of application data forwarded so far.");
if (client->connected() && (unsigned long long) client->responseContentLength
== client->responseBodyAlreadyRead)
{
RH_TRACE(client, 3, "Disconnecting client because application data has been fully forwarded.");
onAppInputEof(client);
}
}
}
void onAppInputChunkEnd(const ClientPtr &client) {
RH_LOG_EVENT(client, "onAppInputChunkEnd");
onAppInputEof(client);
}
void onAppInputEof(const ClientPtr &client) {
RH_LOG_EVENT(client, "onAppInputEof");
// Check for session == NULL in order to avoid executing the code twice on
// responses with chunked encoding.
// This also ensures that when onAppInputEof() is called twice (e.g. because
// additional data was received after onAppInputChunk has already called onAppInputEof()),
// we don't do things twice.
if (!client->connected() || client->session == NULL) {
return;
}
RH_DEBUG(client, "Application sent EOF");
client->appInput->stop();
client->session.reset();
client->endScopeLog(&client->scopeLogs.requestProxying);
client->clientOutputPipe->end();
}
void onAppInputError(const ClientPtr &client, const char *message, int errorCode) {
RH_LOG_EVENT(client, "onAppInputError");
if (!client->connected()) {
return;
}
if (errorCode == ECONNRESET) {
// We might as well treat ECONNRESET like an EOF.
// http://stackoverflow.com/questions/2974021/what-does-econnreset-mean-in-the-context-of-an-af-local-socket
onAppInputEof(client);
} else {
stringstream message;
message << "application socket read error: ";
message << strerror(errorCode);
message << " (fd=" << client->appInput->getFd();
message << ", errno=" << errorCode << ")";
disconnectWithError(client, message.str());
}
}
void onClientOutputPipeCommit(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientOutputPipeCommit");
if (!client->connected()) {
return;
}
RH_TRACE(client, 3, "Done buffering response data to disk; resuming application socket.");
client->backgroundOperations--;
// If the data comes from writeErrorResponse(), then appInput is not available.
if (client->session != NULL && client->session->initiated()) {
client->appInput->start();
}
}
/*****************************************************
* COMPONENT: clientOutputPipe -> client fd plumbing
*
* The following code handles forwarding data from
* clientOutputPipe to the client socket.
*****************************************************/
void onClientOutputPipeData(const ClientPtr &client, const char *data,
size_t size, const FileBackedPipe::ConsumeCallback &consumed)
{
RH_LOG_EVENT(client, "onClientOutputPipeData");
if (!client->connected()) {
return;
}
RH_TRACE(client, 3, "Forwarding " << size << " bytes of application data to client.");
ssize_t ret = syscalls::write(client->fd, data, size);
if (ret == -1) {
int e = errno;
RH_TRACE(client, 3, "Could not write to client socket: " << strerror(e) << " (errno=" << e << ")");
if (e == EAGAIN) {
RH_TRACE(client, 3, "Waiting until the client socket is writable again.");
client->clientOutputWatcher.start();
consumed(0, true);
} else if (e == EPIPE || e == ECONNRESET) {
// If the client closed the connection then disconnect quietly.
RH_TRACE(client, 3, "Client stopped reading prematurely");
if (client->useUnionStation()) {
client->logMessage("Disconnecting: client stopped reading prematurely");
}
disconnect(client);
} else {
disconnectWithClientSocketWriteError(client, e);
}
} else {
RH_TRACE(client, 3, "Managed to forward " << ret << " bytes.");
consumed(ret, false);
}
}
void onClientOutputPipeEnd(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientOutputPipeEnd");
if (!client->connected()) {
return;
}
RH_TRACE(client, 2, "Client output pipe ended; disconnecting client");
client->endScopeLog(&client->scopeLogs.requestProcessing);
disconnect(client);
}
void onClientOutputPipeError(const ClientPtr &client, int errorCode) {
RH_LOG_EVENT(client, "onClientOutputPipeError");
if (!client->connected()) {
return;
}
stringstream message;
message << "client output pipe error: ";
message << strerror(errorCode);
message << " (errno=" << errorCode << ")";
disconnectWithError(client, message.str());
}
void onClientOutputWritable(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientOutputWritable");
if (!client->connected()) {
return;
}
// Continue forwarding output data to the client.
RH_TRACE(client, 3, "Client socket became writable again.");
client->clientOutputWatcher.stop();
assert(!client->clientOutputPipe->isStarted());
client->clientOutputPipe->start();
}
/*****************************************************
* COMPONENT: client acceptor
*
* The following code accepts new client connections
* and forwards events to the appropriate functions
* depending on the client state.
*****************************************************/
FileDescriptor acceptNonBlockingSocket(int sock) {
union {
struct sockaddr_in inaddr;
struct sockaddr_un unaddr;
} u;
socklen_t addrlen = sizeof(u);
if (accept4Available) {
FileDescriptor fd(callAccept4(requestSocket,
(struct sockaddr *) &u, &addrlen, O_NONBLOCK));
// FreeBSD returns EINVAL if accept4() is called with invalid flags.
if (fd == -1 && (errno == ENOSYS || errno == EINVAL)) {
accept4Available = false;
return acceptNonBlockingSocket(sock);
} else {
return fd;
}
} else {
FileDescriptor fd(syscalls::accept(requestSocket,
(struct sockaddr *) &u, &addrlen));
if (fd != -1) {
int e = errno;
setNonBlocking(fd);
errno = e;
}
return fd;
}
}
void onResumeSocketWatcher(ev::timer &timer, int revents) {
P_INFO("Resuming listening on server socket.");
resumeSocketWatcherTimer.stop();
requestSocketWatcher.start();
}
void onAcceptable(ev::io &io, int revents) {
bool endReached = false;
unsigned int count = 0;
unsigned int maxAcceptTries = clamp<unsigned int>(clients.size(), 1, 10);
ClientPtr acceptedClients[10];
while (!endReached && count < maxAcceptTries) {
FileDescriptor fd = acceptNonBlockingSocket(requestSocket);
if (fd == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
endReached = true;
} else {
int e = errno;
P_ERROR("Cannot accept client: " << strerror(e) <<
" (errno=" << e << "). " <<
"Pausing listening on server socket for 3 seconds. " <<
"Current client count: " << clients.size());
requestSocketWatcher.stop();
resumeSocketWatcherTimer.start();
endReached = true;
}
} else if (benchmarkPoint == BP_AFTER_ACCEPT) {
writeExact(fd,
"HTTP/1.1 200 OK\r\n"
"Status: 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n"
"\r\n"
"Benchmark point: after_accept\n");
} else {
ClientPtr client = boost::make_shared<Client>();
client->associate(this, fd);
clients.insert(make_pair((int) fd, client));
acceptedClients[count] = client;
count++;
RH_DEBUG(client, "New client accepted; new client count = " << clients.size());
}
}
for (unsigned int i = 0; i < count; i++) {
acceptedClients[i]->clientInput->readNow();
}
if (OXT_LIKELY(!clients.empty())) {
inactivityTimer.stop();
}
}
size_t onClientInputData(const ClientPtr &client, const StaticString &data) {
RH_LOG_EVENT(client, "onClientInputData");
if (!client->connected()) {
return 0;
}
if (data.empty()) {
onClientEof(client);
return 0;
} else {
return onClientRealData(client, data.data(), data.size());
}
}
size_t onClientRealData(const ClientPtr &client, const char *buf, size_t size) {
size_t consumed = 0;
while (consumed < size && client->connected() && client->clientInput->isStarted()) {
const char *data = buf + consumed;
size_t len = size - consumed;
size_t locallyConsumed;
RH_TRACE(client, 3, "Processing client data: \"" << cEscapeString(StaticString(data, len)) << "\"");
switch (client->state) {
case Client::BEGIN_READING_CONNECT_PASSWORD:
locallyConsumed = state_beginReadingConnectPassword_onClientData(client, data, len);
break;
case Client::STILL_READING_CONNECT_PASSWORD:
locallyConsumed = state_stillReadingConnectPassword_onClientData(client, data, len);
break;
case Client::READING_HEADER:
locallyConsumed = state_readingHeader_onClientData(client, data, len);
break;
case Client::BUFFERING_REQUEST_BODY:
locallyConsumed = state_bufferingRequestBody_onClientData(client, data, len);
break;
case Client::FORWARDING_BODY_TO_APP:
locallyConsumed = state_forwardingBodyToApp_onClientData(client, data, len);
break;
default:
abort();
}
consumed += locallyConsumed;
RH_TRACE(client, 3, "Processed client data: consumed " << locallyConsumed << " bytes");
assert(consumed <= size);
}
return consumed;
}
void onClientEof(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientEof; client sent EOF");
switch (client->state) {
case Client::BUFFERING_REQUEST_BODY:
state_bufferingRequestBody_onClientEof(client);
break;
case Client::FORWARDING_BODY_TO_APP:
state_forwardingBodyToApp_onClientEof(client);
break;
default:
disconnect(client);
break;
}
}
void onClientInputError(const ClientPtr &client, const char *message, int errnoCode) {
RH_LOG_EVENT(client, "onClientInputError");
if (!client->connected()) {
return;
}
if (errnoCode == ECONNRESET) {
// We might as well treat ECONNRESET like an EOF.
// http://stackoverflow.com/questions/2974021/what-does-econnreset-mean-in-the-context-of-an-af-local-socket
RH_TRACE(client, 3, "Client socket ECONNRESET error; treating it as EOF");
onClientEof(client);
} else {
stringstream message;
message << "client socket read error: ";
message << strerror(errnoCode);
message << " (errno=" << errnoCode << ")";
disconnectWithError(client, message.str());
}
}
void onClientBodyBufferData(const ClientPtr &client, const char *data, size_t size, const FileBackedPipe::ConsumeCallback &consumed) {
RH_LOG_EVENT(client, "onClientBodyBufferData");
if (!client->connected()) {
return;
}
switch (client->state) {
case Client::FORWARDING_BODY_TO_APP:
state_forwardingBodyToApp_onClientBodyBufferData(client, data, size, consumed);
break;
default:
abort();
}
}
void onClientBodyBufferError(const ClientPtr &client, int errorCode) {
RH_LOG_EVENT(client, "onClientBodyBufferError");
if (!client->connected()) {
return;
}
stringstream message;
message << "client body buffer error: ";
message << strerror(errorCode);
message << " (errno=" << errorCode << ")";
disconnectWithError(client, message.str());
}
void onClientBodyBufferEnd(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientBodyBufferEnd");
if (!client->connected()) {
return;
}
switch (client->state) {
case Client::FORWARDING_BODY_TO_APP:
state_forwardingBodyToApp_onClientBodyBufferEnd(client);
break;
default:
abort();
}
}
void onClientBodyBufferCommit(const ClientPtr &client) {
RH_LOG_EVENT(client, "onClientBodyBufferCommit");
if (!client->connected()) {
return;
}
switch (client->state) {
case Client::BUFFERING_REQUEST_BODY:
state_bufferingRequestBody_onClientBodyBufferCommit(client);
break;
default:
abort();
}
}
void onAppOutputWritable(const ClientPtr &client) {
RH_LOG_EVENT(client, "onAppOutputWritable");
if (!client->connected()) {
return;
}
switch (client->state) {
case Client::SENDING_HEADER_TO_APP:
state_sendingHeaderToApp_onAppOutputWritable(client);
break;
case Client::FORWARDING_BODY_TO_APP:
state_forwardingBodyToApp_onAppOutputWritable(client);
break;
default:
abort();
}
}
void onTimeout(const ClientPtr &client) {
RH_LOG_EVENT(client, "onTimeout");
if (!client->connected()) {
return;
}
switch (client->state) {
case Client::BEGIN_READING_CONNECT_PASSWORD:
case Client::STILL_READING_CONNECT_PASSWORD:
disconnectWithError(client, "no connect password received within timeout");
break;
default:
disconnectWithError(client, "timeout");
break;
}
}
/*****************************************************
* COMPONENT: client -> application plumbing
*
* The following code implements forwarding data from
* the client to the application. Code is seperated
* by client state.
*****************************************************/
/******* State: BEGIN_READING_CONNECT_PASSWORD *******/
void checkConnectPassword(const ClientPtr &client, const char *data, unsigned int len) {
RH_TRACE(client, 3, "Given connect password: \"" << cEscapeString(StaticString(data, len)) << "\"");
if (constantTimeCompare(StaticString(data, len), options.requestSocketPassword)) {
RH_TRACE(client, 3, "Connect password is correct; reading header");
client->state = Client::READING_HEADER;
client->freeBufferedConnectPassword();
client->timeoutTimer.stop();
if (benchmarkPoint == BP_AFTER_CHECK_CONNECT_PASSWORD) {
writeSimpleResponse(client, "Benchmark point: after_check_connect_password\n");
}
} else {
disconnectWithError(client, "wrong connect password");
}
}
size_t state_beginReadingConnectPassword_onClientData(const ClientPtr &client, const char *data, size_t size) {
if (size >= options.requestSocketPassword.size()) {
checkConnectPassword(client, data, options.requestSocketPassword.size());
return options.requestSocketPassword.size();
} else {
client->bufferedConnectPassword.data = (char *) malloc(options.requestSocketPassword.size());
client->bufferedConnectPassword.alreadyRead = size;
memcpy(client->bufferedConnectPassword.data, data, size);
client->state = Client::STILL_READING_CONNECT_PASSWORD;
return size;
}
}
/******* State: STILL_READING_CONNECT_PASSWORD *******/
size_t state_stillReadingConnectPassword_onClientData(const ClientPtr &client, const char *data, size_t size) {
size_t consumed = std::min<size_t>(size,
options.requestSocketPassword.size() -
client->bufferedConnectPassword.alreadyRead);
memcpy(client->bufferedConnectPassword.data + client->bufferedConnectPassword.alreadyRead,
data, consumed);
client->bufferedConnectPassword.alreadyRead += consumed;
if (client->bufferedConnectPassword.alreadyRead == options.requestSocketPassword.size()) {
checkConnectPassword(client, client->bufferedConnectPassword.data,
options.requestSocketPassword.size());
}
return consumed;
}
/******* State: READING_HEADER *******/
bool modifyClientHeaders(const ClientPtr &client) {
ScgiRequestParser &parser = client->scgiParser;
ScgiRequestParser::HeaderMap &map = parser.getMap();
ScgiRequestParser::iterator it, end = map.end();
bool modified = false;
/* The Rack spec specifies that HTTP_CONTENT_LENGTH and HTTP_CONTENT_TYPE must
* not exist and that their respective non-HTTP_ versions should exist instead.
*/
if ((it = map.find("HTTP_CONTENT_LENGTH")) != end) {
if (map.find("CONTENT_LENGTH") == end) {
map["CONTENT_LENGTH"] = it->second;
map.erase("HTTP_CONTENT_LENGTH");
} else {
map.erase(it);
}
modified = true;
}
if ((it = map.find("HTTP_CONTENT_TYPE")) != end) {
if (map.find("CONTENT_TYPE") == end) {
map["CONTENT_TYPE"] = it->second;
map.erase("HTTP_CONTENT_TYPE");
} else {
map.erase(it);
}
modified = true;
}
return modified;
}
void reportBadRequestAndDisconnect(const ClientPtr &client, const char *message) {
writeSimpleResponse(client, message, 400);
if (client->connected()) {
disconnectWithError(client, message);
}
}
void checkAndInternalizeRequestHeaders(const ClientPtr &client) {
ScgiRequestParser &parser = client->scgiParser;
StaticString requestMethod = parser.getHeader("REQUEST_METHOD");
if (requestMethod.empty()) {
reportBadRequestAndDisconnect(client, "Bad request (no request method given)");
return;
}
// Check Content-Length and Transfer-Encoding.
long long contentLength = getULongLongOption(client, "CONTENT_LENGTH");
StaticString transferEncoding = parser.getHeader("HTTP_TRANSFER_ENCODING");
if (contentLength != -1 && !transferEncoding.empty()) {
reportBadRequestAndDisconnect(client, "Bad request (request may not contain both Content-Length and Transfer-Encoding)");
return;
}
if (!transferEncoding.empty() && transferEncoding != "chunked") {
reportBadRequestAndDisconnect(client, "Bad request (only Transfer-Encoding chunked is supported)");
return;
}
// According to the HTTP/1.1 spec, Content-Length may not be 0.
// We could reject the request, but some important HTTP clients are broken
// (*cough* Ruby Net::HTTP *cough*) and fixing them is too much of
// a pain, so we choose support it.
if (contentLength == 0) {
contentLength = -1;
assert(transferEncoding.empty());
}
StaticString upgrade = parser.getHeader("HTTP_UPGRADE");
const bool requestIsGetOrHead = requestMethod == "GET" || requestMethod == "HEAD";
const bool requestBodyOffered = contentLength != -1 || !transferEncoding.empty();
// Reject requests that have a request body and an Upgrade header.
if (!requestIsGetOrHead && !upgrade.empty()) {
reportBadRequestAndDisconnect(client, "Bad request (Upgrade header is only allowed for non-GET and non-HEAD requests)");
return;
}
if (!requestBodyOffered) {
if (upgrade.empty()) {
client->requestBodyLength = 0;
} else {
client->requestBodyLength = -1;
}
} else {
client->requestBodyLength = contentLength;
client->requestIsChunked = !transferEncoding.empty();
}
}
static void fillPoolOption(const ClientPtr &client, StaticString &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = it->second;
}
}
static void fillPoolOption(const ClientPtr &client, bool &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = it->second == "true";
}
}
static void fillPoolOption(const ClientPtr &client, unsigned int &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = stringToUint(it->second);
}
}
static void fillPoolOption(const ClientPtr &client, unsigned long &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = stringToUint(it->second);
}
}
static void fillPoolOption(const ClientPtr &client, long &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = stringToInt(it->second);
}
}
static void fillPoolOptionSecToMsec(const ClientPtr &client, unsigned int &field, const StaticString &name) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
field = stringToUint(it->second) * 1000;
}
}
void fillPoolOptions(const ClientPtr &client) {
Options &options = client->options;
ScgiRequestParser &parser = client->scgiParser;
ScgiRequestParser::const_iterator it, end = client->scgiParser.end();
options = Options();
StaticString scriptName = parser.getHeader("SCRIPT_NAME");
StaticString appRoot = parser.getHeader("PASSENGER_APP_ROOT");
if (scriptName.empty()) {
if (appRoot.empty()) {
StaticString documentRoot = parser.getHeader("DOCUMENT_ROOT");
if (documentRoot.empty()) {
disconnectWithError(client, "no PASSENGER_APP_ROOT or DOCUMENT_ROOT headers set.");
return;
}
client->appRoot = extractDirName(documentRoot);
options.appRoot = client->appRoot;
} else {
options.appRoot = appRoot;
}
} else {
if (appRoot.empty()) {
client->appRoot = extractDirName(resolveSymlink(parser.getHeader("DOCUMENT_ROOT")));
options.appRoot = client->appRoot;
} else {
options.appRoot = appRoot;
}
options.baseURI = scriptName;
}
options.ruby = this->options.defaultRubyCommand;
options.logLevel = getLogLevel();
options.loggingAgentAddress = this->options.loggingAgentAddress;
options.loggingAgentUsername = "logging";
options.loggingAgentPassword = this->options.loggingAgentPassword;
options.defaultUser = this->options.defaultUser;
options.defaultGroup = this->options.defaultGroup;
fillPoolOption(client, options.appGroupName, "PASSENGER_APP_GROUP_NAME");
fillPoolOption(client, options.appType, "PASSENGER_APP_TYPE");
fillPoolOption(client, options.environment, "PASSENGER_APP_ENV");
fillPoolOption(client, options.ruby, "PASSENGER_RUBY");
fillPoolOption(client, options.python, "PASSENGER_PYTHON");
fillPoolOption(client, options.nodejs, "PASSENGER_NODEJS");
fillPoolOption(client, options.user, "PASSENGER_USER");
fillPoolOption(client, options.group, "PASSENGER_GROUP");
fillPoolOption(client, options.minProcesses, "PASSENGER_MIN_PROCESSES");
fillPoolOption(client, options.maxProcesses, "PASSENGER_MAX_PROCESSES");
fillPoolOption(client, options.maxRequests, "PASSENGER_MAX_REQUESTS");
fillPoolOption(client, options.spawnMethod, "PASSENGER_SPAWN_METHOD");
fillPoolOption(client, options.startCommand, "PASSENGER_START_COMMAND");
fillPoolOptionSecToMsec(client, options.startTimeout, "PASSENGER_START_TIMEOUT");
fillPoolOption(client, options.maxPreloaderIdleTime, "PASSENGER_MAX_PRELOADER_IDLE_TIME");
fillPoolOption(client, options.maxRequestQueueSize, "PASSENGER_MAX_REQUEST_QUEUE_SIZE");
fillPoolOption(client, options.statThrottleRate, "PASSENGER_STAT_THROTTLE_RATE");
fillPoolOption(client, options.restartDir, "PASSENGER_RESTART_DIR");
fillPoolOption(client, options.startupFile, "PASSENGER_STARTUP_FILE");
fillPoolOption(client, options.loadShellEnvvars, "PASSENGER_LOAD_SHELL_ENVVARS");
fillPoolOption(client, options.debugger, "PASSENGER_DEBUGGER");
fillPoolOption(client, options.raiseInternalError, "PASSENGER_RAISE_INTERNAL_ERROR");
setStickySessionId(client);
/******************/
for (it = client->scgiParser.begin(); it != end; it++) {
if (!startsWith(it->first, "PASSENGER_")
&& !startsWith(it->first, "HTTP_")
&& it->first != "PATH_INFO"
&& it->first != "SCRIPT_NAME"
&& it->first != "CONTENT_LENGTH"
&& it->first != "CONTENT_TYPE")
{
options.environmentVariables.push_back(*it);
}
}
}
void initializeUnionStation(const ClientPtr &client) {
if (getBoolOption(client, "UNION_STATION_SUPPORT", false)) {
Options &options = client->options;
ScgiRequestParser &parser = client->scgiParser;
StaticString key = parser.getHeader("UNION_STATION_KEY");
StaticString filters = parser.getHeader("UNION_STATION_FILTERS");
if (key.empty()) {
disconnectWithError(client, "header UNION_STATION_KEY must be set.");
return;
}
client->options.transaction = unionStationCore->newTransaction(
options.getAppGroupName(), "requests", key, filters);
if (!client->options.transaction->isNull()) {
client->options.analytics = true;
client->options.unionStationKey = key;
}
client->beginScopeLog(&client->scopeLogs.requestProcessing, "request processing");
StaticString staticRequestMethod = parser.getHeader("REQUEST_METHOD");
client->logMessage("Request method: " + staticRequestMethod);
StaticString staticRequestURI = parser.getHeader("REQUEST_URI");
if (!staticRequestURI.empty()) {
client->logMessage("URI: " + staticRequestURI);
} else {
string requestURI = parser.getHeader("SCRIPT_NAME");
requestURI.append(parser.getHeader("PATH_INFO"));
StaticString queryString = parser.getHeader("QUERY_STRING");
if (!queryString.empty()) {
requestURI.append("?");
requestURI.append(queryString);
}
client->logMessage("URI: " + requestURI);
}
}
}
void parseCookieHeader(const StaticString &header,
vector< pair<StaticString, StaticString> > &cookies) const
{
// See http://stackoverflow.com/questions/6108207/definite-guide-to-valid-cookie-values
// for syntax grammar.
vector<StaticString> parts;
vector<StaticString>::const_iterator it, it_end;
split(header, ';', parts);
cookies.reserve(parts.size());
it_end = parts.end();
for (it = parts.begin(); it != it_end; it++) {
const char *begin = it->data();
const char *end = it->data() + it->size();
const char *sep;
skipLeadingWhitespaces(&begin, end);
skipTrailingWhitespaces(begin, &end);
// Find the separator ('=').
sep = (const char *) memchr(begin, '=', end - begin);
if (sep != NULL) {
// Valid cookie. Otherwise, ignore it.
const char *nameEnd = sep;
const char *valueBegin = sep + 1;
skipTrailingWhitespaces(begin, &nameEnd);
skipLeadingWhitespaces(&valueBegin, end);
cookies.push_back(make_pair(
StaticString(begin, nameEnd - begin),
StaticString(valueBegin, end - valueBegin)
));
}
}
}
void setStickySessionId(const ClientPtr &client) {
ScgiRequestParser &parser = client->scgiParser;
if (parser.getHeader("PASSENGER_STICKY_SESSIONS") == "true") {
// TODO: This is not entirely correct. Clients MAY send multiple Cookie
// headers, although this is in practice extremely rare.
// http://stackoverflow.com/questions/16305814/are-multiple-cookie-headers-allowed-in-an-http-request
StaticString cookieHeader = parser.getHeader("HTTP_COOKIE");
StaticString cookieName = getStickySessionCookieName(client);
vector< pair<StaticString, StaticString> > cookies;
pair<StaticString, StaticString> cookie;
client->stickySession = true;
parseCookieHeader(cookieHeader, cookies);
foreach (cookie, cookies) {
if (cookie.first == cookieName) {
// This cookie matches the one we're looking for.
client->options.stickySessionId = stringToUint(cookie.second);
return;
}
}
}
}
StaticString getStickySessionCookieName(const ClientPtr &client) const {
StaticString value = client->scgiParser.getHeader("PASSENGER_STICKY_SESSIONS_COOKIE_NAME");
if (value.empty()) {
return StaticString(DEFAULT_STICKY_SESSIONS_COOKIE_NAME,
sizeof(DEFAULT_STICKY_SESSIONS_COOKIE_NAME) - 1);
} else {
return value;
}
}
size_t state_readingHeader_onClientData(const ClientPtr &client, const char *data, size_t size) {
ScgiRequestParser &parser = client->scgiParser;
size_t consumed = parser.feed(data, size);
if (!parser.acceptingInput()) {
if (parser.getState() == ScgiRequestParser::ERROR) {
if (parser.getErrorReason() == ScgiRequestParser::LIMIT_REACHED) {
disconnectWithError(client, "SCGI header too large");
} else {
disconnectWithError(client, "invalid SCGI header");
}
return consumed;
}
if (benchmarkPoint == BP_AFTER_PARSING_HEADER) {
writeSimpleResponse(client, "Benchmark point: after_parsing_header\n");
return consumed;
}
bool modified = modifyClientHeaders(client);
/* TODO: in case the headers are not modified, we only need to rebuild the header data
* right now because the scgiParser buffer is invalidated as soon as onClientData exits.
* We should figure out a way to not copy anything if we can do everything before
* onClientData exits.
*/
parser.rebuildData(modified);
checkAndInternalizeRequestHeaders(client);
if (!client->connected()) {
return consumed;
}
fillPoolOptions(client);
if (!client->connected()) {
return consumed;
}
initializeUnionStation(client);
if (!client->connected()) {
return consumed;
}
if (getBoolOption(client, "PASSENGER_BUFFERING")) {
RH_TRACE(client, 3, "Valid SCGI header; buffering request body");
client->state = Client::BUFFERING_REQUEST_BODY;
client->requestBodyIsBuffered = true;
client->beginScopeLog(&client->scopeLogs.bufferingRequestBody, "buffering request body");
if (client->requestBodyLength == 0) {
client->clientInput->stop();
state_bufferingRequestBody_onClientEof(client);
return 0;
}
} else {
RH_TRACE(client, 3, "Valid SCGI header; not buffering request body; checking out session");
client->clientInput->stop();
checkoutSession(client);
}
}
return consumed;
}
/******* State: BUFFERING_REQUEST_BODY *******/
void state_bufferingRequestBody_verifyInvariants(const ClientPtr &client) const {
assert(client->requestBodyIsBuffered);
assert(!client->clientBodyBuffer->isStarted());
}
size_t state_bufferingRequestBody_onClientData(const ClientPtr &client, const char *data, size_t size) {
state_bufferingRequestBody_verifyInvariants(client);
assert(!client->clientBodyBuffer->isCommittingToDisk());
if (client->requestBodyLength >= 0) {
size = std::min<unsigned long long>(
size,
(unsigned long long) client->requestBodyLength - client->requestBodyAlreadyRead
);
}
if (!client->clientBodyBuffer->write(data, size)) {
// The pipe cannot write the data to disk quickly enough, so
// suspend reading from the client until the pipe is done.
client->backgroundOperations++; // TODO: figure out whether this is necessary
client->clientInput->stop();
}
client->requestBodyAlreadyRead += size;
RH_TRACE(client, 3, "Buffered " << size << " bytes of client body data; total=" <<
client->requestBodyAlreadyRead << ", content-length=" << client->requestBodyLength);
assert(client->requestBodyLength == -1 || client->requestBodyAlreadyRead <= (unsigned long long) client->requestBodyLength);
if (client->requestBodyLength >= 0 && client->requestBodyAlreadyRead == (unsigned long long) client->requestBodyLength) {
if (client->clientBodyBuffer->isCommittingToDisk()) {
RH_TRACE(client, 3, "Done buffering request body, but clientBodyBuffer not yet done committing data to disk; waiting until it's done");
client->checkoutSessionAfterCommit = true;
} else {
client->clientInput->stop();
state_bufferingRequestBody_onClientEof(client);
}
}
return size;
}
void state_bufferingRequestBody_onClientEof(const ClientPtr &client) {
state_bufferingRequestBody_verifyInvariants(client);
RH_TRACE(client, 3, "Done buffering request body; checking out session");
client->clientBodyBuffer->end();
client->endScopeLog(&client->scopeLogs.bufferingRequestBody);
checkoutSession(client);
}
void state_bufferingRequestBody_onClientBodyBufferCommit(const ClientPtr &client) {
// Now that the pipe has committed the data to disk
// resume reading from the client socket.
state_bufferingRequestBody_verifyInvariants(client);
assert(!client->clientInput->isStarted());
client->backgroundOperations--;
if (client->checkoutSessionAfterCommit) {
RH_TRACE(client, 3, "Done committing request body to disk");
state_bufferingRequestBody_onClientEof(client);
} else {
client->clientInput->start();
}
}
/******* State: CHECKING_OUT_SESSION *******/
void state_checkingOutSession_verifyInvariants(const ClientPtr &client) {
assert(!client->clientInput->isStarted());
assert(!client->clientBodyBuffer->isStarted());
}
void checkoutSession(const ClientPtr &client) {
if (benchmarkPoint != BP_BEFORE_CHECKOUT_SESSION) {
RH_TRACE(client, 2, "Checking out session: appRoot=" << client->options.appRoot);
client->state = Client::CHECKING_OUT_SESSION;
client->beginScopeLog(&client->scopeLogs.getFromPool, "get from pool");
pool->asyncGet(client->options, boost::bind(&RequestHandler::sessionCheckedOut,
this, client, _1, _2));
if (!client->sessionCheckedOut) {
client->backgroundOperations++;
}
} else {
writeSimpleResponse(client, "Benchmark point: before_checkout_session\n");
}
}
void sessionCheckedOut(ClientPtr client, const SessionPtr &session, const ExceptionPtr &e) {
if (!pthread_equal(pthread_self(), libev->getCurrentThread())) {
libev->runLater(boost::bind(&RequestHandler::sessionCheckedOut_real, this,
client, session, e));
} else {
sessionCheckedOut_real(client, session, e);
}
}
void sessionCheckedOut_real(ClientPtr client, const SessionPtr &session, const ExceptionPtr &e) {
RH_LOG_EVENT(client, "sessionCheckedOut");
if (!client->connected()) {
return;
}
state_checkingOutSession_verifyInvariants(client);
client->backgroundOperations--;
client->sessionCheckedOut = true;
if (e != NULL) {
client->endScopeLog(&client->scopeLogs.getFromPool, false);
{
boost::shared_ptr<RequestQueueFullException> e2 = dynamic_pointer_cast<RequestQueueFullException>(e);
if (e2 != NULL) {
writeRequestQueueFullExceptionErrorResponse(client);
return;
}
}
{
boost::shared_ptr<SpawnException> e2 = dynamic_pointer_cast<SpawnException>(e);
if (e2 != NULL) {
writeSpawnExceptionErrorResponse(client, e2);
return;
}
}
writeOtherExceptionErrorResponse(client, e);
} else {
RH_DEBUG(client, "Session checked out: pid=" << session->getPid() <<
", gupid=" << session->getGupid());
client->session = session;
initiateSession(client);
}
}
void writeRequestQueueFullExceptionErrorResponse(const ClientPtr &client) {
StaticString value = client->scgiParser.getHeader("PASSENGER_REQUEST_QUEUE_OVERFLOW_STATUS_CODE");
int requestQueueOverflowStatusCode = 503;
if (!value.empty()) {
requestQueueOverflowStatusCode = atoi(value.data());
}
writeSimpleResponse(client,
"<h1>This website is under heavy load</h1>"
"<p>We're sorry, too many people are accessing this website at the same "
"time. We're working on this problem. Please try again later.</p>",
requestQueueOverflowStatusCode);
}
void writeSpawnExceptionErrorResponse(const ClientPtr &client, const boost::shared_ptr<SpawnException> &e) {
RH_ERROR(client, "Cannot checkout session because a spawning error occurred. " <<
"The identifier of the error is " << e->get("error_id") << ". Please see earlier logs for " <<
"details about the error.");
writeErrorResponse(client, e->getErrorPage(), e.get());
}
void writeOtherExceptionErrorResponse(const ClientPtr &client, const ExceptionPtr &e) {
string typeName;
#ifdef CXX_ABI_API_AVAILABLE
int status;
char *tmp = abi::__cxa_demangle(typeid(*e).name(), 0, 0, &status);
if (tmp != NULL) {
typeName = tmp;
free(tmp);
} else {
typeName = typeid(*e).name();
}
#else
typeName = typeid(*e).name();
#endif
RH_WARN(client, "Cannot checkout session (exception type " <<
typeName << "): " << e->what());
string response = "An internal error occurred while trying to spawn the application.\n";
response.append("Exception type: ");
response.append(typeName);
response.append("\nError message: ");
response.append(e->what());
boost::shared_ptr<tracable_exception> e3 = dynamic_pointer_cast<tracable_exception>(e);
if (e3 != NULL) {
response.append("\nBacktrace:\n");
response.append(e3->backtrace());
}
writeErrorResponse(client, response);
}
void initiateSession(const ClientPtr &client) {
assert(client->state == Client::CHECKING_OUT_SESSION);
client->sessionCheckoutTry++;
try {
client->session->initiate();
} catch (const SystemException &e2) {
if (client->sessionCheckoutTry < 10) {
RH_DEBUG(client, "Error checking out session (" << e2.what() <<
"); retrying (attempt " << client->sessionCheckoutTry << ")");
client->sessionCheckedOut = false;
pool->asyncGet(client->options,
boost::bind(&RequestHandler::sessionCheckedOut,
this, client, _1, _2));
if (!client->sessionCheckedOut) {
client->backgroundOperations++;
}
} else {
string message = "could not initiate a session (";
message.append(e2.what());
message.append(")");
disconnectWithError(client, message);
}
return;
}
if (client->useUnionStation()) {
client->endScopeLog(&client->scopeLogs.getFromPool);
client->logMessage("Application PID: " +
toString(client->session->getPid()) +
" (GUPID: " + client->session->getGupid() + ")");
client->beginScopeLog(&client->scopeLogs.requestProxying, "request proxying");
}
RH_DEBUG(client, "Session initiated: fd=" << client->session->fd());
setNonBlocking(client->session->fd());
client->appInput->reset(libev.get(), client->session->fd());
client->appInput->start();
client->appOutputWatcher.set(libev->getLoop());
client->appOutputWatcher.set(client->session->fd(), ev::WRITE);
sendHeaderToApp(client);
}
/******* State: SENDING_HEADER_TO_APP *******/
void state_sendingHeaderToApp_verifyInvariants(const ClientPtr &client) {
assert(!client->clientInput->isStarted());
assert(!client->clientBodyBuffer->isStarted());
}
void sendHeaderToApp(const ClientPtr &client) {
assert(!client->clientInput->isStarted());
assert(!client->clientBodyBuffer->isStarted());
RH_TRACE(client, 2, "Sending headers to application");
if (client->session == NULL) {
disconnectWithError(client,
"Application sent EOF before we were able to send headers to it");
} else if (client->session->getProtocol() == "session") {
char sizeField[sizeof(boost::uint32_t)];
SmallVector<StaticString, 10> data;
data.push_back(StaticString(sizeField, sizeof(boost::uint32_t)));
data.push_back(client->scgiParser.getHeaderData());
data.push_back(makeStaticStringWithNull("PASSENGER_CONNECT_PASSWORD"));
data.push_back(makeStaticStringWithNull(client->session->getConnectPassword()));
if (client->options.analytics) {
data.push_back(makeStaticStringWithNull("PASSENGER_TXN_ID"));
data.push_back(makeStaticStringWithNull(client->options.transaction->getTxnId()));
}
boost::uint32_t dataSize = 0;
for (unsigned int i = 1; i < data.size(); i++) {
dataSize += (boost::uint32_t) data[i].size();
}
Uint32Message::generate(sizeField, dataSize);
ssize_t ret = gatheredWrite(client->session->fd(), &data[0],
data.size(), client->appOutputBuffer);
if (ret == -1 && errno != EAGAIN) {
disconnectWithAppSocketWriteError(client, errno);
} else if (!client->appOutputBuffer.empty()) {
client->state = Client::SENDING_HEADER_TO_APP;
client->appOutputWatcher.start();
} else {
sendBodyToApp(client);
}
} else {
assert(client->session->getProtocol() == "http_session");
const ScgiRequestParser &parser = client->scgiParser;
ScgiRequestParser::const_iterator it, end = parser.end();
string data;
data.reserve(parser.getHeaderData().size() + 128);
data.append(parser.getHeader("REQUEST_METHOD"));
data.append(" ");
data.append(parser.getHeader("REQUEST_URI"));
data.append(" HTTP/1.1\r\n");
for (it = parser.begin(); it != end; it++) {
if (startsWith(it->first, "HTTP_") && it->first != "HTTP_CONNECTION") {
string subheader = it->first.substr(sizeof("HTTP_") - 1);
string::size_type i;
for (i = 0; i < subheader.size(); i++) {
if (subheader[i] == '_') {
subheader[i] = '-';
} else if (i > 0 && subheader[i - 1] != '-') {
subheader[i] = tolower(subheader[i]);
}
}
data.append(subheader);
data.append(": ");
data.append(it->second);
data.append("\r\n");
}
}
StaticString connection = parser.getHeader("HTTP_CONNECTION");
if (regex_match(connection.data(), connection.data() + connection.size(),
upgradeHeaderRegex))
{
data.append("Connection: ");
data.append(connection.data(), connection.size());
data.append("\r\n");
} else {
data.append("Connection: close\r\n");
}
StaticString header = parser.getHeader("CONTENT_LENGTH");
if (!header.empty()) {
data.append("Content-Length: ");
data.append(header);
data.append("\r\n");
}
header = parser.getHeader("CONTENT_TYPE");
if (!header.empty()) {
data.append("Content-Type: ");
data.append(header);
data.append("\r\n");
}
header = parser.getHeader("HTTPS");
if (!header.empty()) {
data.append("X-Forwarded-Proto: https\r\n");
}
header = parser.getHeader("REMOTE_ADDR");
if (!header.empty()) {
data.append("X-Forwarded-For: ");
data.append(header);
data.append("\r\n");
}
if (client->options.analytics) {
data.append("Passenger-Txn-Id: ");
data.append(client->options.transaction->getTxnId());
data.append("\r\n");
}
P_TRACE(3, "Sending headers to application: " << data);
data.append("\r\n");
StaticString datas[] = { data };
ssize_t ret = gatheredWrite(client->session->fd(), datas,
1, client->appOutputBuffer);
if (ret == -1 && errno != EAGAIN) {
disconnectWithAppSocketWriteError(client, errno);
// TODO: what about other errors?
} else if (!client->appOutputBuffer.empty()) {
client->state = Client::SENDING_HEADER_TO_APP;
client->appOutputWatcher.start();
} else {
sendBodyToApp(client);
}
}
}
void state_sendingHeaderToApp_onAppOutputWritable(const ClientPtr &client) {
state_sendingHeaderToApp_verifyInvariants(client);
if (client->session == NULL) {
disconnectWithError(client,
"Application sent EOF before we were able to send headers to it");
} else {
ssize_t ret = gatheredWrite(client->session->fd(), NULL, 0, client->appOutputBuffer);
if (ret == -1) {
if (errno != EAGAIN && errno != EPIPE && errno != ECONNRESET) {
disconnectWithAppSocketWriteError(client, errno);
}
// TODO: what about other errors?
} else if (client->appOutputBuffer.empty()) {
client->appOutputWatcher.stop();
sendBodyToApp(client);
}
}
}
/******* State: FORWARDING_BODY_TO_APP *******/
void state_forwardingBodyToApp_verifyInvariants(const ClientPtr &client) const {
assert(client->state == Client::FORWARDING_BODY_TO_APP);
}
void sendBodyToApp(const ClientPtr &client) {
assert(client->appOutputBuffer.empty());
assert(!client->clientBodyBuffer->isStarted());
assert(!client->clientInput->isStarted());
assert(!client->appOutputWatcher.is_active());
RH_TRACE(client, 2, "Begin sending body to application");
client->state = Client::FORWARDING_BODY_TO_APP;
if (client->requestBodyIsBuffered) {
client->clientBodyBuffer->start();
} else if (client->requestBodyLength == 0) {
state_forwardingBodyToApp_onClientEof(client);
} else {
client->clientInput->start();
}
}
size_t state_forwardingBodyToApp_onClientData(const ClientPtr &client,
const char *data, size_t size)
{
state_forwardingBodyToApp_verifyInvariants(client);
assert(!client->requestBodyIsBuffered);
if (client->requestBodyLength >= 0) {
size = std::min<unsigned long long>(
size,
(unsigned long long) client->requestBodyLength - client->requestBodyAlreadyRead
);
}
RH_TRACE(client, 3, "Forwarding " << size << " bytes of client body data to application.");
if (client->session == NULL) {
RH_TRACE(client, 2, "Application had already sent EOF. Stop reading client input.");
client->clientInput->stop();
syscalls::shutdown(client->fd, SHUT_RD);
return 0;
}
ssize_t ret = syscalls::write(client->session->fd(), data, size);
int e = errno;
if (ret == -1) {
RH_TRACE(client, 3, "Could not write to application socket: " << strerror(e) << " (errno=" << e << ")");
if (e == EAGAIN) {
RH_TRACE(client, 3, "Waiting until the application socket is writable again.");
client->clientInput->stop();
client->appOutputWatcher.start();
} else if (e == EPIPE || e == ECONNRESET) {
// Client will be disconnected after response forwarding is done.
client->clientInput->stop();
syscalls::shutdown(client->fd, SHUT_RD);
} else {
disconnectWithAppSocketWriteError(client, e);
}
return 0;
} else {
client->requestBodyAlreadyRead += ret;
RH_TRACE(client, 3, "Managed to forward " << ret << " bytes; total=" <<
client->requestBodyAlreadyRead << ", content-length=" << client->requestBodyLength);
assert(client->requestBodyLength == -1 || client->requestBodyAlreadyRead <= (unsigned long long) client->requestBodyLength);
if (client->requestBodyLength >= 0 && client->requestBodyAlreadyRead == (unsigned long long) client->requestBodyLength) {
client->clientInput->stop();
state_forwardingBodyToApp_onClientEof(client);
}
return ret;
}
}
void state_forwardingBodyToApp_onClientEof(const ClientPtr &client) {
state_forwardingBodyToApp_verifyInvariants(client);
assert(!client->requestBodyIsBuffered);
RH_TRACE(client, 2, "End of (unbuffered) client body reached; done sending data to application");
client->clientInput->stop();
if (client->session != NULL && client->shouldHalfCloseWrite()) {
syscalls::shutdown(client->session->fd(), SHUT_WR);
}
}
void state_forwardingBodyToApp_onAppOutputWritable(const ClientPtr &client) {
state_forwardingBodyToApp_verifyInvariants(client);
RH_TRACE(client, 3, "Application socket became writable again.");
client->appOutputWatcher.stop();
if (client->requestBodyIsBuffered) {
assert(!client->clientBodyBuffer->isStarted());
client->clientBodyBuffer->start();
} else {
assert(!client->clientInput->isStarted());
client->clientInput->start();
}
}
void state_forwardingBodyToApp_onClientBodyBufferData(const ClientPtr &client,
const char *data, size_t size, const FileBackedPipe::ConsumeCallback &consumed)
{
state_forwardingBodyToApp_verifyInvariants(client);
assert(client->requestBodyIsBuffered);
RH_TRACE(client, 3, "Forwarding " << size << " bytes of buffered client body data to application.");
if (client->session == NULL) {
RH_TRACE(client, 2, "Application had already sent EOF. Stop reading client input.");
syscalls::shutdown(client->fd, SHUT_RD);
consumed(0, true);
return;
}
ssize_t ret = syscalls::write(client->session->fd(), data, size);
if (ret == -1) {
int e = errno;
RH_TRACE(client, 3, "Could not write to application socket: " << strerror(e) << " (errno=" << e << ")");
if (e == EAGAIN) {
RH_TRACE(client, 3, "Waiting until the application socket is writable again.");
client->appOutputWatcher.start();
consumed(0, true);
} else if (e == EPIPE || e == ECONNRESET) {
// Client will be disconnected after response forwarding is done.
syscalls::shutdown(client->fd, SHUT_RD);
consumed(0, true);
} else {
disconnectWithAppSocketWriteError(client, e);
}
} else {
RH_TRACE(client, 3, "Managed to forward " << ret << " bytes.");
consumed(ret, false);
}
}
void state_forwardingBodyToApp_onClientBodyBufferEnd(const ClientPtr &client) {
state_forwardingBodyToApp_verifyInvariants(client);
assert(client->requestBodyIsBuffered);
RH_TRACE(client, 2, "End of (buffered) client body reached; done sending data to application");
if (client->session != NULL && client->shouldHalfCloseWrite()) {
syscalls::shutdown(client->session->fd(), SHUT_WR);
}
}
public:
// For unit testing purposes.
unsigned int connectPasswordTimeout; // milliseconds
BenchmarkPoint benchmarkPoint;
RequestHandler(const SafeLibevPtr &_libev,
const FileDescriptor &_requestSocket,
const PoolPtr &_pool,
const AgentOptions &_options)
: libev(_libev),
requestSocket(_requestSocket),
pool(_pool),
options(_options),
resourceLocator(_options.passengerRoot),
upgradeHeaderRegex("(keep-alive, *)?upgrade(, *keep-alive)?",
boost::regex::perl | boost::regex::icase),
benchmarkPoint(getDefaultBenchmarkPoint())
{
accept4Available = true;
connectPasswordTimeout = 15000;
unionStationCore = pool->getUnionStationCore();
requestSocketWatcher.set(_requestSocket, ev::READ);
requestSocketWatcher.set(_libev->getLoop());
requestSocketWatcher.set<RequestHandler, &RequestHandler::onAcceptable>(this);
requestSocketWatcher.start();
resumeSocketWatcherTimer.set<RequestHandler, &RequestHandler::onResumeSocketWatcher>(this);
resumeSocketWatcherTimer.set(_libev->getLoop());
resumeSocketWatcherTimer.set(3, 3);
}
template<typename Stream>
void inspect(Stream &stream) const {
stream << clients.size() << " clients:\n";
HashMap<int, ClientPtr>::const_iterator it;
for (it = clients.begin(); it != clients.end(); it++) {
const ClientPtr &client = it->second;
stream << " Client " << client->fd << ":\n";
client->inspect(stream);
}
}
void resetInactivityTime() {
libev->run(boost::bind(&RequestHandler::doResetInactivityTime, this));
}
unsigned long long inactivityTime() const {
unsigned long long result;
libev->run(boost::bind(&RequestHandler::getInactivityTime, this, &result));
return result;
}
};
} // namespace Passenger
#endif /* _PASSENGER_REQUEST_HANDLER_H_ */
|