1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925
|
/* libhttpd.c - HTTP protocol library
**
** Copyright 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@acme.com>.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE.
*/
#include "config.h"
#include "version.h"
#ifdef SHOW_SERVER_VERSION
#define EXPOSED_SERVER_SOFTWARE SERVER_SOFTWARE
#else /* SHOW_SERVER_VERSION */
#define EXPOSED_SERVER_SOFTWARE "thttpd"
#endif /* SHOW_SERVER_VERSION */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif /* HAVE_MEMORY_H */
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <stdarg.h>
#ifdef HAVE_OSRELDATE_H
#include <osreldate.h>
#endif /* HAVE_OSRELDATE_H */
#ifdef HAVE_DIRENT_H
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# ifdef HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
# include <ndir.h>
# endif
#endif
extern char* crypt( const char* key, const char* setting );
#include "libhttpd.h"
#include "mmc.h"
#include "timers.h"
#include "match.h"
#include "tdate_parse.h"
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
/* Forwards. */
static void child_reaper( ClientData client_data, struct timeval* nowP );
static int do_reap( void );
static void check_options( void );
static void free_httpd_server( httpd_server* hs );
static int initialize_listen_socket( httpd_sockaddr* saP );
static void unlisten( httpd_server* hs );
static void add_response( httpd_conn* hc, char* str );
static void send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, int length, time_t mod );
static void send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg );
static void send_response_tail( httpd_conn* hc );
static void defang( char* str, char* dfstr, int dfsize );
#ifdef ERR_DIR
static int send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename );
#endif /* ERR_DIR */
#ifdef AUTH_FILE
static void send_authenticate( httpd_conn* hc, char* realm );
static int b64_decode( const char* str, unsigned char* space, int size );
static int auth_check( httpd_conn* hc, char* dirname );
static int auth_check2( httpd_conn* hc, char* dirname );
#endif /* AUTH_FILE */
static void send_dirredirect( httpd_conn* hc );
static int hexit( char c );
static void strdecode( char* to, char* from );
#ifdef GENERATE_INDEXES
static void strencode( char* to, int tosize, char* from );
#endif /* GENERATE_INDEXES */
#ifdef TILDE_MAP_1
static int tilde_map_1( httpd_conn* hc );
#endif /* TILDE_MAP_1 */
#ifdef TILDE_MAP_2
static int tilde_map_2( httpd_conn* hc );
#endif /* TILDE_MAP_2 */
static int vhost_map( httpd_conn* hc );
static char* expand_symlinks( char* path, char** restP, int no_symlink, int tildemapped );
static char* bufgets( httpd_conn* hc );
static void de_dotdot( char* file );
static void figure_mime( httpd_conn* hc );
#ifdef CGI_TIMELIMIT
static void cgi_kill2( ClientData client_data, struct timeval* nowP );
static void cgi_kill( ClientData client_data, struct timeval* nowP );
#endif /* CGI_TIMELIMIT */
#ifdef GENERATE_INDEXES
static off_t ls( httpd_conn* hc );
#endif /* GENERATE_INDEXES */
static char* build_env( char* fmt, char* arg );
#ifdef SERVER_NAME_LIST
static char* hostname_map( char* hostname );
#endif /* SERVER_NAME_LIST */
static char** make_envp( httpd_conn* hc );
static char** make_argp( httpd_conn* hc );
static void cgi_interpose_input( httpd_conn* hc, int wfd );
static void post_post_garbage_hack( httpd_conn* hc );
static void cgi_interpose_output( httpd_conn* hc, int rfd );
static void cgi_child( httpd_conn* hc );
static off_t cgi( httpd_conn* hc );
static int really_start_request( httpd_conn* hc, struct timeval* nowP );
static void make_log_entry( httpd_conn* hc, struct timeval* nowP );
static int check_referer( httpd_conn* hc );
static int really_check_referer( httpd_conn* hc );
static int sockaddr_check( httpd_sockaddr* saP );
static size_t sockaddr_len( httpd_sockaddr* saP );
static int my_snprintf( char* str, size_t size, const char* format, ... );
static int reap_time;
static void
child_reaper( ClientData client_data, struct timeval* nowP )
{
int child_count;
static int prev_child_count = 0;
child_count = do_reap();
/* Reschedule reaping, with adaptively changed time. */
if ( child_count > prev_child_count * 3 / 2 )
reap_time = max( reap_time / 2, MIN_REAP_TIME );
else if ( child_count < prev_child_count * 2 / 3 )
reap_time = min( reap_time * 5 / 4, MAX_REAP_TIME );
if ( tmr_create( nowP, child_reaper, JunkClientData, reap_time * 1000L, 0 ) == (Timer*) 0 )
{
syslog( LOG_CRIT, "tmr_create(child_reaper) failed" );
exit( 1 );
}
}
static int
do_reap( void )
{
int child_count;
pid_t pid;
int status;
/* Reap defunct children until there aren't any more. */
for ( child_count = 0; ; ++child_count )
{
#ifdef HAVE_WAITPID
pid = waitpid( (pid_t) -1, &status, WNOHANG );
#else /* HAVE_WAITPID */
pid = wait3( &status, WNOHANG, (struct rusage*) 0 );
#endif /* HAVE_WAITPID */
if ( (int) pid == 0 ) /* none left */
break;
if ( (int) pid < 0 )
{
if ( errno == EINTR ) /* because of ptrace */
continue;
/* ECHILD shouldn't happen with the WNOHANG option, but with
** some kernels it does anyway. Ignore it.
*/
if ( errno != ECHILD )
syslog( LOG_ERR, "waitpid - %m" );
break;
}
}
return child_count;
}
static void
check_options( void )
{
#if defined(TILDE_MAP_1) && defined(TILDE_MAP_2)
syslog( LOG_CRIT, "both TILDE_MAP_1 and TILDE_MAP_2 are defined" );
exit( 1 );
#endif /* both */
}
static void
free_httpd_server( httpd_server* hs )
{
if ( hs->binding_hostname != (char*) 0 )
free( (void*) hs->binding_hostname );
if ( hs->cwd != (char*) 0 )
free( (void*) hs->cwd );
if ( hs->cgi_pattern != (char*) 0 )
free( (void*) hs->cgi_pattern );
if ( hs->charset != (char*) 0 )
free( (void*) hs->charset );
if ( hs->url_pattern != (char*) 0 )
free( (void*) hs->url_pattern );
if ( hs->local_pattern != (char*) 0 )
free( (void*) hs->local_pattern );
free( (void*) hs );
}
httpd_server*
httpd_initialize(
char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P, int port,
char* cgi_pattern, char* charset, char* cwd, int no_log, FILE* logfp,
int no_symlink, int vhost, int global_passwd, char* url_pattern,
char* local_pattern, int no_empty_referers )
{
httpd_server* hs;
static char ghnbuf[256];
char* cp;
check_options();
/* Set up child-process reaper. */
reap_time = min( MIN_REAP_TIME * 4, MAX_REAP_TIME );
if ( tmr_create( (struct timeval*) 0, child_reaper, JunkClientData, reap_time * 1000L, 0 ) == (Timer*) 0 )
{
syslog( LOG_CRIT, "tmr_create(child_reaper) failed" );
return (httpd_server*) 0;
}
hs = NEW( httpd_server, 1 );
if ( hs == (httpd_server*) 0 )
{
syslog( LOG_CRIT, "out of memory allocating an httpd_server" );
return (httpd_server*) 0;
}
if ( hostname != (char*) 0 )
{
hs->binding_hostname = strdup( hostname );
if ( hs->binding_hostname == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying hostname" );
return (httpd_server*) 0;
}
hs->server_hostname = hs->binding_hostname;
}
else
{
hs->binding_hostname = (char*) 0;
hs->server_hostname = (char*) 0;
if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 )
ghnbuf[0] = '\0';
#ifdef SERVER_NAME_LIST
if ( ghnbuf[0] != '\0' )
hs->server_hostname = hostname_map( ghnbuf );
#endif /* SERVER_NAME_LIST */
if ( hs->server_hostname == (char*) 0 )
{
#ifdef SERVER_NAME
hs->server_hostname = SERVER_NAME;
#else /* SERVER_NAME */
if ( ghnbuf[0] != '\0' )
hs->server_hostname = ghnbuf;
#endif /* SERVER_NAME */
}
}
hs->port = port;
if ( cgi_pattern == (char*) 0 )
hs->cgi_pattern = (char*) 0;
else
{
/* Nuke any leading slashes. */
if ( cgi_pattern[0] == '/' )
++cgi_pattern;
hs->cgi_pattern = strdup( cgi_pattern );
if ( hs->cgi_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying cgi_pattern" );
return (httpd_server*) 0;
}
/* Nuke any leading slashes in the cgi pattern. */
while ( ( cp = strstr( hs->cgi_pattern, "|/" ) ) != (char*) 0 )
(void) strcpy( cp + 1, cp + 2 );
}
hs->charset = strdup( charset );
hs->cwd = strdup( cwd );
if ( hs->cwd == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying cwd" );
return (httpd_server*) 0;
}
if ( url_pattern == (char*) 0 )
hs->url_pattern = (char*) 0;
else
{
hs->url_pattern = strdup( url_pattern );
if ( hs->url_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying url_pattern" );
return (httpd_server*) 0;
}
}
if ( local_pattern == (char*) 0 )
hs->local_pattern = (char*) 0;
else
{
hs->local_pattern = strdup( local_pattern );
if ( hs->local_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying local_pattern" );
return (httpd_server*) 0;
}
}
hs->no_log = no_log;
hs->logfp = (FILE*) 0;
httpd_set_logfp( hs, logfp );
hs->no_symlink = no_symlink;
hs->vhost = vhost;
hs->global_passwd = global_passwd;
hs->no_empty_referers = no_empty_referers;
/* Initialize listen sockets. Try v6 first because of a Linux peculiarity;
** unlike other systems, it has magical v6 sockets that also listen for v4,
** but if you bind a v4 socket first then the v6 bind fails.
*/
if ( sa6P == (httpd_sockaddr*) 0 )
hs->listen6_fd = -1;
else
hs->listen6_fd = initialize_listen_socket( sa6P );
if ( sa4P == (httpd_sockaddr*) 0 )
hs->listen4_fd = -1;
else
hs->listen4_fd = initialize_listen_socket( sa4P );
/* If we didn't get any valid sockets, fail. */
if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 )
{
free_httpd_server( hs );
return (httpd_server*) 0;
}
/* Done initializing. */
if ( hs->binding_hostname == (char*) 0 )
syslog( LOG_INFO, "%.80s starting on port %d", SERVER_SOFTWARE, hs->port );
else
syslog(
LOG_INFO, "%.80s starting on %.80s, port %d", SERVER_SOFTWARE,
httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ), hs->port );
return hs;
}
static int
initialize_listen_socket( httpd_sockaddr* saP )
{
int listen_fd;
int on, flags;
/* Check sockaddr. */
if ( ! sockaddr_check( saP ) )
{
syslog( LOG_CRIT, "unknown sockaddr family on listen socket" );
return -1;
}
/* Create socket. */
listen_fd = socket( saP->sa.sa_family, SOCK_STREAM, 0 );
if ( listen_fd < 0 )
{
syslog( LOG_CRIT, "socket %.80s - %m", httpd_ntoa( saP ) );
return -1;
}
(void) fcntl( listen_fd, F_SETFD, 1 );
/* Allow reuse of local addresses. */
on = 1;
if ( setsockopt(
listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*) &on,
sizeof(on) ) < 0 )
syslog( LOG_CRIT, "setsockopt SO_REUSEADDR - %m" );
/* Use accept filtering, if available. */
#ifdef SO_ACCEPTFILTER
{
#if ( __FreeBSD_version >= 411000 )
#define ACCEPT_FILTER_NAME "httpready"
#else
#define ACCEPT_FILTER_NAME "dataready"
#endif
struct accept_filter_arg af;
(void) bzero( &af, sizeof(af) );
(void) strcpy( af.af_name, ACCEPT_FILTER_NAME );
(void) setsockopt(
listen_fd, SOL_SOCKET, SO_ACCEPTFILTER, (char*) &af, sizeof(af) );
}
#endif /* SO_ACCEPTFILTER */
/* Bind to it. */
if ( bind( listen_fd, &saP->sa, sockaddr_len( saP ) ) < 0 )
{
syslog(
LOG_CRIT, "bind %.80s - %m", httpd_ntoa( saP ) );
(void) close( listen_fd );
return -1;
}
/* Set the listen file descriptor to no-delay mode. */
flags = fcntl( listen_fd, F_GETFL, 0 );
if ( flags == -1 )
{
syslog( LOG_CRIT, "fcntl F_GETFL - %m" );
(void) close( listen_fd );
return -1;
}
if ( fcntl( listen_fd, F_SETFL, flags | O_NDELAY ) < 0 )
{
syslog( LOG_CRIT, "fcntl O_NDELAY - %m" );
(void) close( listen_fd );
return -1;
}
/* Start a listen going. */
if ( listen( listen_fd, LISTEN_BACKLOG ) < 0 )
{
syslog( LOG_CRIT, "listen - %m" );
(void) close( listen_fd );
return -1;
}
return listen_fd;
}
void
httpd_set_logfp( httpd_server* hs, FILE* logfp )
{
if ( hs->logfp != (FILE*) 0 )
(void) fclose( hs->logfp );
hs->logfp = logfp;
}
void
httpd_terminate( httpd_server* hs )
{
unlisten( hs );
if ( hs->logfp != (FILE*) 0 )
(void) fclose( hs->logfp );
free_httpd_server( hs );
}
static void
unlisten( httpd_server* hs )
{
if ( hs->listen4_fd != -1 )
(void) close( hs->listen4_fd );
if ( hs->listen6_fd != -1 )
(void) close( hs->listen6_fd );
}
/* Conditional macro to allow two alternate forms for use in the built-in
** error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more
** explicit error form is used; otherwise, the first and more generic
** form is used.
*/
#ifdef EXPLICIT_ERROR_PAGES
#define ERROR_FORM(a,b) b
#else /* EXPLICIT_ERROR_PAGES */
#define ERROR_FORM(a,b) a
#endif /* EXPLICIT_ERROR_PAGES */
static char* ok200title = "OK";
static char* ok206title = "Partial Content";
static char* err302title = "Found";
static char* err302form = "The actual URL is '%.80s'.\n";
static char* err304title = "Not Modified";
char* httpd_err400title = "Bad Request";
char* httpd_err400form =
"Your request has bad syntax or is inherently impossible to satisfy.\n";
#ifdef AUTH_FILE
static char* err401title = "Unauthorized";
static char* err401form =
"Authorization required for the URL '%.80s'.\n";
#endif /* AUTH_FILE */
static char* err403title = "Forbidden";
static char* err403form =
"You do not have permission to get URL '%.80s' from this server.\n";
static char* err404title = "Not Found";
static char* err404form =
"The requested URL '%.80s' was not found on this server.\n";
char* httpd_err408title = "Request Timeout";
char* httpd_err408form =
"No request appeared within a reasonable time period.\n";
static char* err500title = "Internal Error";
static char* err500form =
"There was an unusual problem serving the requested URL '%.80s'.\n";
static char* err501title = "Not Implemented";
static char* err501form =
"The requested method '%.80s' is not implemented by this server.\n";
char* httpd_err503title = "Service Temporarily Overloaded";
char* httpd_err503form =
"The requested URL '%.80s' is temporarily overloaded. Please try again later.\n";
/* Append a string to the buffer waiting to be sent as response. */
static void
add_response( httpd_conn* hc, char* str )
{
int len;
len = strlen( str );
httpd_realloc_str( &hc->response, &hc->maxresponse, hc->responselen + len );
(void) memcpy( &(hc->response[hc->responselen]), str, len );
hc->responselen += len;
}
/* Send the buffered response. */
void
httpd_write_response( httpd_conn* hc )
{
/* First turn off NDELAY mode. */
httpd_clear_ndelay( hc->conn_fd );
/* And send it, if necessary. */
if ( hc->responselen > 0 )
{
(void) write( hc->conn_fd, hc->response, hc->responselen );
hc->responselen = 0;
}
}
/* Set NDELAY mode on a socket. */
void
httpd_set_ndelay( int fd )
{
int flags, newflags;
flags = fcntl( fd, F_GETFL, 0 );
if ( flags != -1 )
{
newflags = flags | (int) O_NDELAY;
if ( newflags != flags )
(void) fcntl( fd, F_SETFL, newflags );
}
}
/* Clear NDELAY mode on a socket. */
void
httpd_clear_ndelay( int fd )
{
int flags, newflags;
flags = fcntl( fd, F_GETFL, 0 );
if ( flags != -1 )
{
newflags = flags & ~ (int) O_NDELAY;
if ( newflags != flags )
(void) fcntl( fd, F_SETFL, newflags );
}
}
static void
send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, int length, time_t mod )
{
time_t now;
const char* rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT";
char nowbuf[100];
char modbuf[100];
char fixed_type[500];
char buf[1000];
int partial_content;
hc->status = status;
hc->bytes_to_send = length;
if ( hc->mime_flag )
{
if ( status == 200 && hc->got_range &&
( hc->end_byte_loc >= hc->init_byte_loc ) &&
( ( hc->end_byte_loc != length - 1 ) ||
( hc->init_byte_loc != 0 ) ) &&
( hc->range_if == (time_t) -1 ||
hc->range_if == hc->sb.st_mtime ) )
{
partial_content = 1;
hc->status = status = 206;
title = ok206title;
}
else
partial_content = 0;
now = time( (time_t*) 0 );
if ( mod == (time_t) 0 )
mod = now;
(void) strftime( nowbuf, sizeof(nowbuf), rfc1123fmt, gmtime( &now ) );
(void) strftime( modbuf, sizeof(modbuf), rfc1123fmt, gmtime( &mod ) );
(void) my_snprintf(
fixed_type, sizeof(fixed_type), type, hc->hs->charset );
(void) my_snprintf( buf, sizeof(buf),
"%.20s %d %s\r\nServer: %s\r\nContent-Type: %s\r\nDate: %s\r\nLast-Modified: %s\r\nAccept-Ranges: bytes\r\nConnection: close\r\n",
hc->protocol, status, title, EXPOSED_SERVER_SOFTWARE, fixed_type,
nowbuf, modbuf );
add_response( hc, buf );
if ( encodings[0] != '\0' )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Encoding: %s\r\n", encodings );
add_response( hc, buf );
}
if ( partial_content )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Range: bytes %ld-%ld/%d\r\nContent-Length: %ld\r\n",
(long) hc->init_byte_loc, (long) hc->end_byte_loc, length,
(long) ( hc->end_byte_loc - hc->init_byte_loc + 1 ) );
add_response( hc, buf );
}
else if ( length >= 0 )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Length: %d\r\n", length );
add_response( hc, buf );
}
if ( extraheads[0] != '\0' )
add_response( hc, extraheads );
add_response( hc, "\r\n" );
}
}
static int str_alloc_count = 0;
static long str_alloc_size = 0;
void
httpd_realloc_str( char** strP, int* maxsizeP, int size )
{
if ( *maxsizeP == 0 )
{
*maxsizeP = MAX( 200, size ); /* arbitrary */
*strP = NEW( char, *maxsizeP + 1 );
++str_alloc_count;
str_alloc_size += *maxsizeP;
}
else if ( size > *maxsizeP )
{
str_alloc_size -= *maxsizeP;
*maxsizeP = MAX( *maxsizeP * 2, size * 5 / 4 );
*strP = RENEW( *strP, char, *maxsizeP + 1 );
str_alloc_size += *maxsizeP;
}
else
return;
if ( *strP == (char*) 0 )
{
syslog(
LOG_ERR, "out of memory reallocating a string to %d bytes",
*maxsizeP );
exit( 1 );
}
}
static void
send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
{
char defanged_arg[1000], buf[2000];
send_mime( hc, status, title, "", extraheads, "text/html; charset=%s", -1, 0 );
(void) my_snprintf( buf, sizeof(buf),
"<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n<BODY BGCOLOR=\"#cc9999\"><H2>%d %s</H2>\n",
status, title, status, title );
add_response( hc, buf );
defang( arg, defanged_arg, sizeof(defanged_arg) );
(void) my_snprintf( buf, sizeof(buf), form, defanged_arg );
add_response( hc, buf );
if ( match( "**MSIE**", hc->useragent ) )
{
int n;
add_response( hc, "<!--\n" );
for ( n = 0; n < 6; ++n )
add_response( hc, "Padding so that MSIE deigns to show this error instead of its own canned one.\n");
add_response( hc, "-->\n" );
}
send_response_tail( hc );
}
static void
send_response_tail( httpd_conn* hc )
{
char buf[1000];
(void) my_snprintf( buf, sizeof(buf),
"<HR>\n<ADDRESS><A HREF=\"%s\">%s</A></ADDRESS>\n</BODY></HTML>\n",
SERVER_ADDRESS, EXPOSED_SERVER_SOFTWARE );
add_response( hc, buf );
}
static void
defang( char* str, char* dfstr, int dfsize )
{
char* cp1;
char* cp2;
for ( cp1 = str, cp2 = dfstr;
*cp1 != '\0' && cp2 - dfstr < dfsize - 5;
++cp1, ++cp2 )
{
switch ( *cp1 )
{
case '<':
*cp2++ = '&';
*cp2++ = 'l';
*cp2++ = 't';
*cp2 = ';';
break;
case '>':
*cp2++ = '&';
*cp2++ = 'g';
*cp2++ = 't';
*cp2 = ';';
break;
default:
*cp2 = *cp1;
break;
}
}
*cp2 = '\0';
}
void
httpd_send_err( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
{
#ifdef ERR_DIR
char filename[1000];
/* Try virtual host error page. */
if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
{
(void) my_snprintf( filename, sizeof(filename),
"%s/%s/err%d.html", hc->hostdir, ERR_DIR, status );
if ( send_err_file( hc, status, title, extraheads, filename ) )
return;
}
/* Try server-wide error page. */
(void) my_snprintf( filename, sizeof(filename),
"%s/err%d.html", ERR_DIR, status );
if ( send_err_file( hc, status, title, extraheads, filename ) )
return;
/* Fall back on built-in error page. */
send_response( hc, status, title, extraheads, form, arg );
#else /* ERR_DIR */
send_response( hc, status, title, extraheads, form, arg );
#endif /* ERR_DIR */
}
#ifdef ERR_DIR
static int
send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename )
{
FILE* fp;
char buf[1000];
int r;
fp = fopen( filename, "r" );
if ( fp == (FILE*) 0 )
return 0;
send_mime( hc, status, title, "", extraheads, "text/html; charset=%s", -1, 0 );
for (;;)
{
r = fread( buf, 1, sizeof(buf) - 1, fp );
if ( r <= 0 )
break;
buf[r] = '\0';
add_response( hc, buf );
}
(void) fclose( fp );
#ifdef ERR_APPEND_SERVER_INFO
send_response_tail( hc );
#endif /* ERR_APPEND_SERVER_INFO */
return 1;
}
#endif /* ERR_DIR */
#ifdef AUTH_FILE
static void
send_authenticate( httpd_conn* hc, char* realm )
{
static char* header;
static int maxheader = 0;
static char headstr[] = "WWW-Authenticate: Basic realm=\"";
httpd_realloc_str(
&header, &maxheader, sizeof(headstr) + strlen( realm ) + 3 );
(void) my_snprintf( header, maxheader, "%s%s\"\r\n", headstr, realm );
httpd_send_err( hc, 401, err401title, header, err401form, hc->encodedurl );
/* If the request was a POST then there might still be data to be read,
** so we need to do a lingering close.
*/
if ( hc->method == METHOD_POST )
hc->should_linger = 1;
}
/* Base-64 decoding. This represents binary data as printable ASCII
** characters. Three 8-bit binary bytes are turned into four 6-bit
** values, like so:
**
** [11111111] [22222222] [33333333]
**
** [111111] [112222] [222233] [333333]
**
** Then the 6-bit values are represented using the characters "A-Za-z0-9+/".
*/
static int b64_decode_table[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
};
/* Do base-64 decoding on a string. Ignore any non-base64 bytes.
** Return the actual number of bytes generated. The decoded size will
** be at most 3/4 the size of the encoded, and may be smaller if there
** are padding characters (blanks, newlines).
*/
static int
b64_decode( const char* str, unsigned char* space, int size )
{
const char* cp;
int space_idx, phase;
int d, prev_d = 0;
unsigned char c;
space_idx = 0;
phase = 0;
for ( cp = str; *cp != '\0'; ++cp )
{
d = b64_decode_table[(int) *cp];
if ( d != -1 )
{
switch ( phase )
{
case 0:
++phase;
break;
case 1:
c = ( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) );
if ( space_idx < size )
space[space_idx++] = c;
++phase;
break;
case 2:
c = ( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) );
if ( space_idx < size )
space[space_idx++] = c;
++phase;
break;
case 3:
c = ( ( ( prev_d & 0x03 ) << 6 ) | d );
if ( space_idx < size )
space[space_idx++] = c;
phase = 0;
break;
}
prev_d = d;
}
}
return space_idx;
}
/* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */
static int
auth_check( httpd_conn* hc, char* dirname )
{
if ( hc->hs->global_passwd )
{
char* topdir;
if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
topdir = hc->hostdir;
else
topdir = ".";
switch ( auth_check2( hc, topdir ) )
{
case -1:
return -1;
case 1:
return 1;
}
}
return auth_check2( hc, dirname );
}
/* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */
static int
auth_check2( httpd_conn* hc, char* dirname )
{
static char* authpath;
static int maxauthpath = 0;
struct stat sb;
char authinfo[550];
char* authpass;
int l;
FILE* fp;
char line[500];
char* cryp;
static char* prevauthpath;
static int maxprevauthpath = 0;
static time_t prevmtime;
static char* prevuser;
static int maxprevuser = 0;
static char* prevcryp;
static int maxprevcryp = 0;
/* Construct auth filename. */
httpd_realloc_str(
&authpath, &maxauthpath, strlen( dirname ) + 1 + sizeof(AUTH_FILE) );
(void) my_snprintf( authpath, maxauthpath,
"%s/%s", dirname, AUTH_FILE );
/* Does this directory have an auth file? */
if ( stat( authpath, &sb ) < 0 )
/* Nope, let the request go through. */
return 0;
/* Does this request contain basic authorization info? */
if ( hc->authorization[0] == '\0' ||
strncmp( hc->authorization, "Basic ", 6 ) != 0 )
{
/* Nope, return a 401 Unauthorized. */
send_authenticate( hc, dirname );
return -1;
}
/* Decode it. */
l = b64_decode( &(hc->authorization[6]), authinfo, sizeof(authinfo) - 1 );
authinfo[l] = '\0';
/* Split into user and password. */
authpass = strchr( authinfo, ':' );
if ( authpass == (char*) 0 )
{
/* No colon? Bogus auth info. */
send_authenticate( hc, dirname );
return -1;
}
*authpass++ = '\0';
/* See if we have a cached entry and can use it. */
if ( maxprevauthpath != 0 &&
strcmp( authpath, prevauthpath ) == 0 &&
sb.st_mtime == prevmtime &&
strcmp( authinfo, prevuser ) == 0 )
{
/* Yes. Check against the cached encrypted password. */
if ( strcmp( crypt( authpass, prevcryp ), prevcryp ) == 0 )
{
/* Ok! */
httpd_realloc_str(
&hc->remoteuser, &hc->maxremoteuser, strlen( authinfo ) );
(void) strcpy( hc->remoteuser, authinfo );
return 1;
}
else
{
/* No. */
send_authenticate( hc, dirname );
return -1;
}
}
/* Open the password file. */
fp = fopen( authpath, "r" );
if ( fp == (FILE*) 0 )
{
/* The file exists but we can't open it? Disallow access. */
syslog(
LOG_ERR, "%.80s auth file %.80s could not be opened - %m",
httpd_ntoa( &hc->client_addr ), authpath );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' is protected by an authentication file, but the authentication file cannot be opened.\n" ),
hc->encodedurl );
return -1;
}
/* Read it. */
while ( fgets( line, sizeof(line), fp ) != (char*) 0 )
{
/* Nuke newline. */
l = strlen( line );
if ( line[l - 1] == '\n' )
line[l - 1] = '\0';
/* Split into user and encrypted password. */
cryp = strchr( line, ':' );
if ( cryp == (char*) 0 )
continue;
*cryp++ = '\0';
/* Is this the right user? */
if ( strcmp( line, authinfo ) == 0 )
{
/* Yes. */
(void) fclose( fp );
/* So is the password right? */
if ( strcmp( crypt( authpass, cryp ), cryp ) == 0 )
{
/* Ok! */
httpd_realloc_str(
&hc->remoteuser, &hc->maxremoteuser, strlen( line ) );
(void) strcpy( hc->remoteuser, line );
/* And cache this user's info for next time. */
httpd_realloc_str(
&prevauthpath, &maxprevauthpath, strlen( authpath ) );
(void) strcpy( prevauthpath, authpath );
prevmtime = sb.st_mtime;
httpd_realloc_str(
&prevuser, &maxprevuser, strlen( authinfo ) );
(void) strcpy( prevuser, authinfo );
httpd_realloc_str( &prevcryp, &maxprevcryp, strlen( cryp ) );
(void) strcpy( prevcryp, cryp );
return 1;
}
else
{
/* No. */
send_authenticate( hc, dirname );
return -1;
}
}
}
/* Didn't find that user. Access denied. */
(void) fclose( fp );
send_authenticate( hc, dirname );
return -1;
}
#endif /* AUTH_FILE */
static void
send_dirredirect( httpd_conn* hc )
{
static char* location;
static char* header;
static int maxlocation = 0, maxheader = 0;
static char headstr[] = "Location: ";
httpd_realloc_str( &location, &maxlocation, strlen( hc->encodedurl ) + 1 );
(void) my_snprintf( location, maxlocation,
"%s/", hc->encodedurl );
httpd_realloc_str(
&header, &maxheader, sizeof(headstr) + strlen( location ) );
(void) my_snprintf( header, maxheader,
"%s%s\r\n", headstr, location );
send_response( hc, 302, err302title, header, err302form, location );
}
char*
httpd_method_str( int method )
{
switch ( method )
{
case METHOD_GET: return "GET";
case METHOD_HEAD: return "HEAD";
case METHOD_POST: return "POST";
default: return "UNKNOWN";
}
}
static int
hexit( char c )
{
if ( c >= '0' && c <= '9' )
return c - '0';
if ( c >= 'a' && c <= 'f' )
return c - 'a' + 10;
if ( c >= 'A' && c <= 'F' )
return c - 'A' + 10;
return 0; /* shouldn't happen, we're guarded by isxdigit() */
}
/* Copies and decodes a string. It's ok for from and to to be the
** same string.
*/
static void
strdecode( char* to, char* from )
{
for ( ; *from != '\0'; ++to, ++from )
{
if ( from[0] == '%' && isxdigit( from[1] ) && isxdigit( from[2] ) )
{
*to = hexit( from[1] ) * 16 + hexit( from[2] );
from += 2;
}
else
*to = *from;
}
*to = '\0';
}
#ifdef GENERATE_INDEXES
/* Copies and encodes a string. */
static void
strencode( char* to, int tosize, char* from )
{
int tolen;
for ( tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from )
{
if ( isalnum(*from) || strchr( "/_.-~", *from ) != (char*) 0 )
{
*to = *from;
++to;
++tolen;
}
else
{
(void) sprintf( to, "%%%02x", (int) *from & 0xff );
to += 3;
tolen += 3;
}
}
*to = '\0';
}
#endif /* GENERATE_INDEXES */
#ifdef TILDE_MAP_1
/* Map a ~username/whatever URL into <prefix>/username. */
static int
tilde_map_1( httpd_conn* hc )
{
static char* temp;
static int maxtemp = 0;
int len;
static char* prefix = TILDE_MAP_1;
len = strlen( hc->expnfilename ) - 1;
httpd_realloc_str( &temp, &maxtemp, len );
(void) strcpy( temp, &hc->expnfilename[1] );
httpd_realloc_str(
&hc->expnfilename, &hc->maxexpnfilename, strlen( prefix ) + 1 + len );
(void) strcpy( hc->expnfilename, prefix );
if ( prefix[0] != '\0' )
(void) strcat( hc->expnfilename, "/" );
(void) strcat( hc->expnfilename, temp );
return 1;
}
#endif /* TILDE_MAP_1 */
#ifdef TILDE_MAP_2
/* Map a ~username/whatever URL into <user's homedir>/<postfix>. */
static int
tilde_map_2( httpd_conn* hc )
{
static char* temp;
static int maxtemp = 0;
static char* postfix = TILDE_MAP_2;
char* cp;
struct passwd* pw;
char* alt;
char* rest;
/* Get the username. */
httpd_realloc_str( &temp, &maxtemp, strlen( hc->expnfilename ) - 1 );
(void) strcpy( temp, &hc->expnfilename[1] );
cp = strchr( temp, '/' );
if ( cp != (char*) 0 )
*cp++ = '\0';
else
cp = "";
/* Get the passwd entry. */
pw = getpwnam( temp );
if ( pw == (struct passwd*) 0 )
return 0;
/* Set up altdir. */
httpd_realloc_str(
&hc->altdir, &hc->maxaltdir,
strlen( pw->pw_dir ) + 1 + strlen( postfix ) );
(void) strcpy( hc->altdir, pw->pw_dir );
if ( postfix[0] != '\0' )
{
(void) strcat( hc->altdir, "/" );
(void) strcat( hc->altdir, postfix );
}
alt = expand_symlinks( hc->altdir, &rest, 0, 1 );
if ( rest[0] != '\0' )
return 0;
httpd_realloc_str( &hc->altdir, &hc->maxaltdir, strlen( alt ) );
(void) strcpy( hc->altdir, alt );
/* And the filename becomes altdir plus the post-~ part of the original. */
httpd_realloc_str(
&hc->expnfilename, &hc->maxexpnfilename,
strlen( hc->altdir ) + 1 + strlen( cp ) );
(void) my_snprintf( hc->expnfilename, hc->maxexpnfilename,
"%s/%s", hc->altdir, cp );
/* For this type of tilde mapping, we want to defeat vhost mapping. */
hc->tildemapped = 1;
return 1;
}
#endif /* TILDE_MAP_2 */
/* Virtual host mapping. */
static int
vhost_map( httpd_conn* hc )
{
httpd_sockaddr sa;
int sz;
static char* tempfilename;
static int maxtempfilename = 0;
char* cp1;
int len;
#ifdef VHOST_DIRLEVELS
int i;
char* cp2;
#endif /* VHOST_DIRLEVELS */
/* Figure out the virtual hostname. */
if ( hc->reqhost[0] != '\0' )
hc->hostname = hc->reqhost;
else if ( hc->hdrhost[0] != '\0' )
hc->hostname = hc->hdrhost;
else
{
sz = sizeof(sa);
if ( getsockname( hc->conn_fd, &sa.sa, &sz ) < 0 )
{
syslog( LOG_ERR, "getsockname - %m" );
return 0;
}
hc->hostname = httpd_ntoa( &sa );
}
/* Pound it to lower case. */
for ( cp1 = hc->hostname; *cp1 != '\0'; ++cp1 )
if ( isupper( *cp1 ) )
*cp1 = tolower( *cp1 );
if ( hc->tildemapped )
return 1;
/* Figure out the host directory. */
#ifdef VHOST_DIRLEVELS
httpd_realloc_str(
&hc->hostdir, &hc->maxhostdir,
strlen( hc->hostname ) + 2 * VHOST_DIRLEVELS );
if ( strncmp( hc->hostname, "www.", 4 ) == 0 )
cp1 = &hc->hostname[4];
else
cp1 = hc->hostname;
for ( cp2 = hc->hostdir, i = 0; i < VHOST_DIRLEVELS; ++i )
{
/* Skip dots in the hostname. If we don't, then we get vhost
** directories in higher level of filestructure if dot gets
** involved into path construction. It's `while' used here instead
** of `if' for it's possible to have a hostname formed with two
** dots at the end of it.
*/
while ( *cp1 == '.' )
++cp1;
/* Copy a character from the hostname, or '_' if we ran out. */
if ( *cp1 != '\0' )
*cp2++ = *cp1++;
else
*cp2++ = '_';
/* Copy a slash. */
*cp2++ = '/';
}
(void) strcpy( cp2, hc->hostname );
#else /* VHOST_DIRLEVELS */
httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, strlen( hc->hostname ) );
(void) strcpy( hc->hostdir, hc->hostname );
#endif /* VHOST_DIRLEVELS */
/* Prepend hostdir to the filename. */
len = strlen( hc->expnfilename );
httpd_realloc_str( &tempfilename, &maxtempfilename, len );
(void) strcpy( tempfilename, hc->expnfilename );
httpd_realloc_str(
&hc->expnfilename, &hc->maxexpnfilename,
strlen( hc->hostdir ) + 1 + len );
(void) strcpy( hc->expnfilename, hc->hostdir );
(void) strcat( hc->expnfilename, "/" );
(void) strcat( hc->expnfilename, tempfilename );
return 1;
}
/* Expands all symlinks in the given filename, eliding ..'s and leading /'s.
** Returns the expanded path (pointer to static string), or (char*) 0 on
** errors. Also returns, in the string pointed to by restP, any trailing
** parts of the path that don't exist.
**
** This is a fairly nice little routine. It handles any size filenames
** without excessive mallocs.
*/
static char*
expand_symlinks( char* path, char** restP, int no_symlink, int tildemapped )
{
static char* checked;
static char* rest;
char link[5000];
static int maxchecked = 0, maxrest = 0;
int checkedlen, restlen, linklen, prevcheckedlen, prevrestlen, nlinks, i;
char* r;
char* cp1;
char* cp2;
if ( no_symlink )
{
/* If we are chrooted, we can actually skip the symlink-expansion,
** since it's impossible to get out of the tree. However, we still
** need to do the pathinfo check, and the existing symlink expansion
** code is a pretty reasonable way to do this. So, what we do is
** a single stat() of the whole filename - if it exists, then we
** return it as is with nothing in restP. If it doesn't exist, we
** fall through to the existing code.
**
** One side-effect of this is that users can't symlink to central
** approved CGIs any more. The workaround is to use the central
** URL for the CGI instead of a local symlinked one.
*/
struct stat sb;
if ( stat( path, &sb ) != -1 )
{
httpd_realloc_str( &checked, &maxchecked, strlen( path ) );
(void) strcpy( checked, path );
httpd_realloc_str( &rest, &maxrest, 0 );
rest[0] = '\0';
*restP = rest;
return checked;
}
}
/* Start out with nothing in checked and the whole filename in rest. */
httpd_realloc_str( &checked, &maxchecked, 1 );
checked[0] = '\0';
checkedlen = 0;
restlen = strlen( path );
httpd_realloc_str( &rest, &maxrest, restlen );
(void) strcpy( rest, path );
if ( rest[restlen - 1] == '/' )
rest[--restlen] = '\0'; /* trim trailing slash */
if ( ! tildemapped )
/* Remove any leading slashes. */
while ( rest[0] == '/' )
{
(void) strcpy( rest, &(rest[1]) );
--restlen;
}
r = rest;
nlinks = 0;
/* While there are still components to check... */
while ( restlen > 0 )
{
/* Save current checkedlen in case we get a symlink. Save current
** restlen in case we get a non-existant component.
*/
prevcheckedlen = checkedlen;
prevrestlen = restlen;
/* Grab one component from r and transfer it to checked. */
cp1 = strchr( r, '/' );
if ( cp1 != (char*) 0 )
{
i = cp1 - r;
if ( i == 0 )
{
/* Special case for absolute paths. */
httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 );
(void) strncpy( &checked[checkedlen], r, 1 );
checkedlen += 1;
}
else if ( strncmp( r, "..", MAX( i, 2 ) ) == 0 )
{
/* Ignore ..'s that go above the start of the path. */
if ( checkedlen != 0 )
{
cp2 = strrchr( checked, '/' );
if ( cp2 == (char*) 0 )
checkedlen = 0;
else if ( cp2 == checked )
checkedlen = 1;
else
checkedlen = cp2 - checked;
}
}
else
{
httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 + i );
if ( checkedlen > 0 && checked[checkedlen-1] != '/' )
checked[checkedlen++] = '/';
(void) strncpy( &checked[checkedlen], r, i );
checkedlen += i;
}
checked[checkedlen] = '\0';
r += i + 1;
restlen -= i + 1;
}
else
{
/* No slashes remaining, r is all one component. */
if ( strcmp( r, ".." ) == 0 )
{
/* Ignore ..'s that go above the start of the path. */
if ( checkedlen != 0 )
{
cp2 = strrchr( checked, '/' );
if ( cp2 == (char*) 0 )
checkedlen = 0;
else if ( cp2 == checked )
checkedlen = 1;
else
checkedlen = cp2 - checked;
checked[checkedlen] = '\0';
}
}
else
{
httpd_realloc_str(
&checked, &maxchecked, checkedlen + 1 + restlen );
if ( checkedlen > 0 && checked[checkedlen-1] != '/' )
checked[checkedlen++] = '/';
(void) strcpy( &checked[checkedlen], r );
checkedlen += restlen;
}
r += restlen;
restlen = 0;
}
/* Try reading the current filename as a symlink */
if ( checked[0] == '\0' )
continue;
linklen = readlink( checked, link, sizeof(link) );
if ( linklen == -1 )
{
if ( errno == EINVAL )
continue; /* not a symlink */
if ( errno == EACCES || errno == ENOENT || errno == ENOTDIR )
{
/* That last component was bogus. Restore and return. */
*restP = r - ( prevrestlen - restlen );
if ( prevcheckedlen == 0 )
(void) strcpy( checked, "." );
else
checked[prevcheckedlen] = '\0';
return checked;
}
syslog( LOG_ERR, "readlink %.80s - %m", checked );
return (char*) 0;
}
++nlinks;
if ( nlinks > MAX_LINKS )
{
syslog( LOG_ERR, "too many symlinks in %.80s", path );
return (char*) 0;
}
link[linklen] = '\0';
if ( link[linklen - 1] == '/' )
link[--linklen] = '\0'; /* trim trailing slash */
/* Insert the link contents in front of the rest of the filename. */
if ( restlen != 0 )
{
(void) strcpy( rest, r );
httpd_realloc_str( &rest, &maxrest, restlen + linklen + 1 );
for ( i = restlen; i >= 0; --i )
rest[i + linklen + 1] = rest[i];
(void) strcpy( rest, link );
rest[linklen] = '/';
restlen += linklen + 1;
r = rest;
}
else
{
/* There's nothing left in the filename, so the link contents
** becomes the rest.
*/
httpd_realloc_str( &rest, &maxrest, linklen );
(void) strcpy( rest, link );
restlen = linklen;
r = rest;
}
if ( rest[0] == '/' )
{
/* There must have been an absolute symlink - zero out checked. */
checked[0] = '\0';
checkedlen = 0;
}
else
{
/* Re-check this component. */
checkedlen = prevcheckedlen;
checked[checkedlen] = '\0';
}
}
/* Ok. */
*restP = r;
if ( checked[0] == '\0' )
(void) strcpy( checked, "." );
return checked;
}
int
httpd_get_conn( httpd_server* hs, int listen_fd, httpd_conn* hc )
{
httpd_sockaddr sa;
int sz;
if ( ! hc->initialized )
{
hc->read_size = 0;
httpd_realloc_str( &hc->read_buf, &hc->read_size, 500 );
hc->maxdecodedurl =
hc->maxorigfilename = hc->maxexpnfilename = hc->maxencodings =
hc->maxpathinfo = hc->maxquery = hc->maxaccept =
hc->maxaccepte = hc->maxreqhost = hc->maxhostdir =
hc->maxremoteuser = hc->maxresponse = 0;
#ifdef TILDE_MAP_2
hc->maxaltdir = 0;
#endif /* TILDE_MAP_2 */
httpd_realloc_str( &hc->decodedurl, &hc->maxdecodedurl, 1 );
httpd_realloc_str( &hc->origfilename, &hc->maxorigfilename, 1 );
httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, 0 );
httpd_realloc_str( &hc->encodings, &hc->maxencodings, 0 );
httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, 0 );
httpd_realloc_str( &hc->query, &hc->maxquery, 0 );
httpd_realloc_str( &hc->accept, &hc->maxaccept, 0 );
httpd_realloc_str( &hc->accepte, &hc->maxaccepte, 0 );
httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, 0 );
httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, 0 );
httpd_realloc_str( &hc->remoteuser, &hc->maxremoteuser, 0 );
httpd_realloc_str( &hc->response, &hc->maxresponse, 0 );
#ifdef TILDE_MAP_2
httpd_realloc_str( &hc->altdir, &hc->maxaltdir, 0 );
#endif /* TILDE_MAP_2 */
hc->initialized = 1;
}
/* Accept the new connection. */
sz = sizeof(sa);
hc->conn_fd = accept( listen_fd, &sa.sa, &sz );
if ( hc->conn_fd < 0 )
{
if ( errno == EWOULDBLOCK )
return GC_NO_MORE;
syslog( LOG_ERR, "accept - %m" );
return GC_FAIL;
}
if ( ! sockaddr_check( &sa ) )
{
syslog( LOG_ERR, "unknown sockaddr family" );
return GC_FAIL;
}
(void) fcntl( hc->conn_fd, F_SETFD, 1 );
hc->hs = hs;
memset( &hc->client_addr, 0, sizeof(hc->client_addr) );
memcpy( &hc->client_addr, &sa, sockaddr_len( &sa ) );
hc->read_idx = 0;
hc->checked_idx = 0;
hc->checked_state = CHST_FIRSTWORD;
hc->method = METHOD_UNKNOWN;
hc->status = 0;
hc->bytes_to_send = 0;
hc->bytes_sent = 0;
hc->encodedurl = "";
hc->decodedurl[0] = '\0';
hc->protocol = "UNKNOWN";
hc->origfilename[0] = '\0';
hc->expnfilename[0] = '\0';
hc->encodings[0] = '\0';
hc->pathinfo[0] = '\0';
hc->query[0] = '\0';
hc->referer = "";
hc->useragent = "";
hc->accept[0] = '\0';
hc->accepte[0] = '\0';
hc->acceptl = "";
hc->cookie = "";
hc->contenttype = "";
hc->reqhost[0] = '\0';
hc->hdrhost = "";
hc->hostdir[0] = '\0';
hc->authorization = "";
hc->remoteuser[0] = '\0';
hc->response[0] = '\0';
#ifdef TILDE_MAP_2
hc->altdir[0] = '\0';
#endif /* TILDE_MAP_2 */
hc->responselen = 0;
hc->if_modified_since = (time_t) -1;
hc->range_if = (time_t) -1;
hc->contentlength = -1;
hc->type = "";
hc->hostname = (char*) 0;
hc->mime_flag = 1;
hc->one_one = 0;
hc->got_range = 0;
hc->tildemapped = 0;
hc->init_byte_loc = 0;
hc->end_byte_loc = -1;
hc->keep_alive = 0;
hc->should_linger = 0;
hc->file_address = (char*) 0;
return GC_OK;
}
/* Checks hc->read_buf to see whether a complete request has been read so far;
** either the first line has two words (an HTTP/0.9 request), or the first
** line has three words and there's a blank line present.
**
** hc->read_idx is how much has been read in; hc->checked_idx is how much we
** have checked so far; and hc->checked_state is the current state of the
** finite state machine.
*/
int
httpd_got_request( httpd_conn* hc )
{
char c;
for ( ; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
{
c = hc->read_buf[hc->checked_idx];
switch ( hc->checked_state )
{
case CHST_FIRSTWORD:
switch ( c )
{
case ' ': case '\t':
hc->checked_state = CHST_FIRSTWS;
break;
case '\n': case '\r':
hc->checked_state = CHST_BOGUS;
return GR_BAD_REQUEST;
}
break;
case CHST_FIRSTWS:
switch ( c )
{
case ' ': case '\t':
break;
case '\n': case '\r':
hc->checked_state = CHST_BOGUS;
return GR_BAD_REQUEST;
default:
hc->checked_state = CHST_SECONDWORD;
break;
}
break;
case CHST_SECONDWORD:
switch ( c )
{
case ' ': case '\t':
hc->checked_state = CHST_SECONDWS;
break;
case '\n': case '\r':
/* The first line has only two words - an HTTP/0.9 request. */
return GR_GOT_REQUEST;
}
break;
case CHST_SECONDWS:
switch ( c )
{
case ' ': case '\t':
break;
case '\n': case '\r':
hc->checked_state = CHST_BOGUS;
return GR_BAD_REQUEST;
default:
hc->checked_state = CHST_THIRDWORD;
break;
}
break;
case CHST_THIRDWORD:
switch ( c )
{
case ' ': case '\t':
hc->checked_state = CHST_THIRDWS;
break;
case '\n':
hc->checked_state = CHST_LF;
break;
case '\r':
hc->checked_state = CHST_CR;
break;
}
break;
case CHST_THIRDWS:
switch ( c )
{
case ' ': case '\t':
break;
case '\n':
hc->checked_state = CHST_LF;
break;
case '\r':
hc->checked_state = CHST_CR;
break;
default:
hc->checked_state = CHST_BOGUS;
return GR_BAD_REQUEST;
}
break;
case CHST_LINE:
switch ( c )
{
case '\n':
hc->checked_state = CHST_LF;
break;
case '\r':
hc->checked_state = CHST_CR;
break;
}
break;
case CHST_LF:
switch ( c )
{
case '\n':
/* Two newlines in a row - a blank line - end of request. */
return GR_GOT_REQUEST;
case '\r':
hc->checked_state = CHST_CR;
break;
default:
hc->checked_state = CHST_LINE;
break;
}
break;
case CHST_CR:
switch ( c )
{
case '\n':
hc->checked_state = CHST_CRLF;
break;
case '\r':
/* Two returns in a row - end of request. */
return GR_GOT_REQUEST;
default:
hc->checked_state = CHST_LINE;
break;
}
break;
case CHST_CRLF:
switch ( c )
{
case '\n':
/* Two newlines in a row - end of request. */
return GR_GOT_REQUEST;
case '\r':
hc->checked_state = CHST_CRLFCR;
break;
default:
hc->checked_state = CHST_LINE;
break;
}
break;
case CHST_CRLFCR:
switch ( c )
{
case '\n': case '\r':
/* Two CRLFs or two CRs in a row - end of request. */
return GR_GOT_REQUEST;
default:
hc->checked_state = CHST_LINE;
break;
}
break;
case CHST_BOGUS:
return GR_BAD_REQUEST;
}
}
return GR_NO_REQUEST;
}
int
httpd_parse_request( httpd_conn* hc )
{
char* buf;
char* method_str;
char* url;
char* protocol;
char* reqhost;
char* eol;
char* cp;
char* pi;
hc->checked_idx = 0; /* reset */
method_str = bufgets( hc );
url = strpbrk( method_str, " \t\n\r" );
if ( url == (char*) 0 )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
*url++ = '\0';
url += strspn( url, " \t\n\r" );
protocol = strpbrk( url, " \t\n\r" );
if ( protocol == (char*) 0 )
{
protocol = "HTTP/0.9";
hc->mime_flag = 0;
}
else
{
*protocol++ = '\0';
protocol += strspn( protocol, " \t\n\r" );
if ( *protocol != '\0' )
{
eol = strpbrk( protocol, " \t\n\r" );
if ( eol != (char*) 0 )
*eol = '\0';
if ( strcasecmp( protocol, "HTTP/1.0" ) != 0 )
hc->one_one = 1;
}
}
/* Check for HTTP/1.1 absolute URL. */
if ( strncasecmp( url, "http://", 7 ) == 0 )
{
if ( ! hc->one_one )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
reqhost = url + 7;
url = strchr( reqhost, '/' );
if ( url == (char*) 0 )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
*url = '\0';
httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, strlen( reqhost ) );
(void) strcpy( hc->reqhost, reqhost );
*url = '/';
}
if ( strcasecmp( method_str, httpd_method_str( METHOD_GET ) ) == 0 )
hc->method = METHOD_GET;
else if ( strcasecmp( method_str, httpd_method_str( METHOD_HEAD ) ) == 0 )
hc->method = METHOD_HEAD;
else if ( strcasecmp( method_str, httpd_method_str( METHOD_POST ) ) == 0 )
hc->method = METHOD_POST;
else
{
httpd_send_err( hc, 501, err501title, "", err501form, method_str );
return -1;
}
hc->encodedurl = url;
httpd_realloc_str(
&hc->decodedurl, &hc->maxdecodedurl, strlen( hc->encodedurl ) );
strdecode( hc->decodedurl, hc->encodedurl );
de_dotdot( hc->decodedurl );
if ( hc->decodedurl[0] != '/' || hc->decodedurl[1] == '/' ||
( hc->decodedurl[1] == '.' && hc->decodedurl[2] == '.' &&
( hc->decodedurl[3] == '\0' || hc->decodedurl[3] == '/' ) ) )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
hc->protocol = protocol;
httpd_realloc_str(
&hc->origfilename, &hc->maxorigfilename, strlen( hc->decodedurl ) );
(void) strcpy( hc->origfilename, &hc->decodedurl[1] );
/* Special case for top-level URL. */
if ( hc->origfilename[0] == '\0' )
(void) strcpy( hc->origfilename, "." );
/* Extract query string from encoded URL. */
cp = strchr( hc->encodedurl, '?' );
if ( cp != (char*) 0 )
{
++cp;
httpd_realloc_str( &hc->query, &hc->maxquery, strlen( cp ) );
(void) strcpy( hc->query, cp );
}
/* And remove query from filename. */
cp = strchr( hc->origfilename, '?' );
if ( cp != (char*) 0 )
*cp = '\0';
if ( hc->mime_flag )
{
/* Read the MIME headers. */
while ( ( buf = bufgets( hc ) ) != (char*) 0 )
{
if ( buf[0] == '\0' )
break;
if ( strncasecmp( buf, "Referer:", 8 ) == 0 )
{
cp = &buf[8];
cp += strspn( cp, " \t" );
hc->referer = cp;
}
else if ( strncasecmp( buf, "User-Agent:", 11 ) == 0 )
{
cp = &buf[11];
cp += strspn( cp, " \t" );
hc->useragent = cp;
}
else if ( strncasecmp( buf, "Host:", 5 ) == 0 )
{
cp = &buf[5];
cp += strspn( cp, " \t" );
hc->hdrhost = cp;
cp = strchr( hc->hdrhost, ':' );
if ( cp != (char*) 0 )
*cp = '\0';
if ( ( hc->hdrhost[0] == '.' ) ||
( strchr( hc->hdrhost, '/' ) != (char*) 0 ))
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
}
else if ( strncasecmp( buf, "Accept:", 7 ) == 0 )
{
cp = &buf[7];
cp += strspn( cp, " \t" );
if ( hc->accept[0] != '\0' )
{
if ( strlen( hc->accept ) > 5000 )
{
syslog(
LOG_ERR, "%.80s way too much Accept: data",
httpd_ntoa( &hc->client_addr ) );
continue;
}
httpd_realloc_str(
&hc->accept, &hc->maxaccept,
strlen( hc->accept ) + 2 + strlen( cp ) );
(void) strcat( hc->accept, ", " );
}
else
httpd_realloc_str(
&hc->accept, &hc->maxaccept, strlen( cp ) );
(void) strcat( hc->accept, cp );
}
else if ( strncasecmp( buf, "Accept-Encoding:", 16 ) == 0 )
{
cp = &buf[16];
cp += strspn( cp, " \t" );
if ( hc->accepte[0] != '\0' )
{
if ( strlen( hc->accepte ) > 5000 )
{
syslog(
LOG_ERR, "%.80s way too much Accept-Encoding: data",
httpd_ntoa( &hc->client_addr ) );
continue;
}
httpd_realloc_str(
&hc->accepte, &hc->maxaccepte,
strlen( hc->accepte ) + 2 + strlen( cp ) );
(void) strcat( hc->accepte, ", " );
}
else
httpd_realloc_str(
&hc->accepte, &hc->maxaccepte, strlen( cp ) );
(void) strcpy( hc->accepte, cp );
}
else if ( strncasecmp( buf, "Accept-Language:", 16 ) == 0 )
{
cp = &buf[16];
cp += strspn( cp, " \t" );
hc->acceptl = cp;
}
else if ( strncasecmp( buf, "If-Modified-Since:", 18 ) == 0 )
{
cp = &buf[18];
hc->if_modified_since = tdate_parse( cp );
if ( hc->if_modified_since == (time_t) -1 )
syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
}
else if ( strncasecmp( buf, "Cookie:", 7 ) == 0 )
{
cp = &buf[7];
cp += strspn( cp, " \t" );
hc->cookie = cp;
}
else if ( strncasecmp( buf, "Range:", 6 ) == 0 )
{
/* Only support %d- and %d-%d, not %d-%d,%d-%d or -%d. */
if ( strchr( buf, ',' ) == (char*) 0 )
{
char* cp_dash;
cp = strpbrk( buf, "=" );
if ( cp != (char*) 0 )
{
cp_dash = strchr( cp + 1, '-' );
if ( cp_dash != (char*) 0 && cp_dash != cp + 1 )
{
*cp_dash = '\0';
hc->got_range = 1;
hc->init_byte_loc = atol( cp + 1 );
if ( isdigit( (int) cp_dash[1] ) )
hc->end_byte_loc = atol( cp_dash + 1 );
}
}
}
}
else if ( strncasecmp( buf, "Range-If:", 9 ) == 0 ||
strncasecmp( buf, "If-Range:", 9 ) == 0 )
{
cp = &buf[9];
hc->range_if = tdate_parse( cp );
if ( hc->range_if == (time_t) -1 )
syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
}
else if ( strncasecmp( buf, "Content-Type:", 13 ) == 0 )
{
cp = &buf[13];
cp += strspn( cp, " \t" );
hc->contenttype = cp;
}
else if ( strncasecmp( buf, "Content-Length:", 15 ) == 0 )
{
cp = &buf[15];
hc->contentlength = atol( cp );
}
else if ( strncasecmp( buf, "Authorization:", 14 ) == 0 )
{
cp = &buf[14];
cp += strspn( cp, " \t" );
hc->authorization = cp;
}
else if ( strncasecmp( buf, "Connection:", 11 ) == 0 )
{
cp = &buf[11];
cp += strspn( cp, " \t" );
if ( strcasecmp( cp, "keep-alive" ) == 0 )
hc->keep_alive = 1;
}
#ifdef LOG_UNKNOWN_HEADERS
else if ( strncasecmp( buf, "Accept-Charset:", 15 ) == 0 ||
strncasecmp( buf, "Accept-Language:", 16 ) == 0 ||
strncasecmp( buf, "Agent:", 6 ) == 0 ||
strncasecmp( buf, "Cache-Control:", 14 ) == 0 ||
strncasecmp( buf, "Cache-Info:", 11 ) == 0 ||
strncasecmp( buf, "Charge-To:", 10 ) == 0 ||
strncasecmp( buf, "Client-IP:", 10 ) == 0 ||
strncasecmp( buf, "Date:", 5 ) == 0 ||
strncasecmp( buf, "Extension:", 10 ) == 0 ||
strncasecmp( buf, "Forwarded:", 10 ) == 0 ||
strncasecmp( buf, "From:", 5 ) == 0 ||
strncasecmp( buf, "HTTP-Version:", 13 ) == 0 ||
strncasecmp( buf, "Max-Forwards:", 13 ) == 0 ||
strncasecmp( buf, "Message-Id:", 11 ) == 0 ||
strncasecmp( buf, "MIME-Version:", 13 ) == 0 ||
strncasecmp( buf, "Negotiate:", 10 ) == 0 ||
strncasecmp( buf, "Pragma:", 7 ) == 0 ||
strncasecmp( buf, "Proxy-Agent:", 12 ) == 0 ||
strncasecmp( buf, "Proxy-Connection:", 17 ) == 0 ||
strncasecmp( buf, "Security-Scheme:", 16 ) == 0 ||
strncasecmp( buf, "Session-Id:", 11 ) == 0 ||
strncasecmp( buf, "UA-Color:", 9 ) == 0 ||
strncasecmp( buf, "UA-CPU:", 7 ) == 0 ||
strncasecmp( buf, "UA-Disp:", 8 ) == 0 ||
strncasecmp( buf, "UA-OS:", 6 ) == 0 ||
strncasecmp( buf, "UA-Pixels:", 10 ) == 0 ||
strncasecmp( buf, "User:", 5 ) == 0 ||
strncasecmp( buf, "Via:", 4 ) == 0 ||
strncasecmp( buf, "X-", 2 ) == 0 )
; /* ignore */
else
syslog( LOG_DEBUG, "unknown request header: %.80s", buf );
#endif /* LOG_UNKNOWN_HEADERS */
}
}
if ( hc->one_one )
{
/* Check that HTTP/1.1 requests specify a host, as required. */
if ( hc->reqhost[0] == '\0' && hc->hdrhost[0] == '\0' )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
return -1;
}
/* If the client wants to do keep-alives, it might also be doing
** pipelining. There's no way for us to tell. Since we don't
** implement keep-alives yet, if we close such a connection there
** might be unread pipelined requests waiting. So, we have to
** do a lingering close.
*/
if ( hc->keep_alive )
hc->should_linger = 1;
}
/* Ok, the request has been parsed. Now we resolve stuff that
** may require the entire request.
*/
/* Copy original filename to expanded filename. */
httpd_realloc_str(
&hc->expnfilename, &hc->maxexpnfilename, strlen( hc->origfilename ) );
(void) strcpy( hc->expnfilename, hc->origfilename );
/* Tilde mapping. */
if ( hc->expnfilename[0] == '~' )
{
#ifdef TILDE_MAP_1
if ( ! tilde_map_1( hc ) )
{
httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
return -1;
}
#endif /* TILDE_MAP_1 */
#ifdef TILDE_MAP_2
if ( ! tilde_map_2( hc ) )
{
httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
return -1;
}
#endif /* TILDE_MAP_2 */
}
/* Virtual host mapping. */
if ( hc->hs->vhost )
if ( ! vhost_map( hc ) )
{
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
/* Expand all symbolic links in the filename. This also gives us
** any trailing non-existing components, for pathinfo.
*/
cp = expand_symlinks( hc->expnfilename, &pi, hc->hs->no_symlink, hc->tildemapped );
if ( cp == (char*) 0 )
{
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( cp ) );
(void) strcpy( hc->expnfilename, cp );
httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, strlen( pi ) );
(void) strcpy( hc->pathinfo, pi );
/* Remove pathinfo stuff from the original filename too. */
if ( hc->pathinfo[0] != '\0' )
{
int i;
i = strlen( hc->origfilename ) - strlen( hc->pathinfo );
if ( i > 0 && strcmp( &hc->origfilename[i], hc->pathinfo ) == 0 )
hc->origfilename[i - 1] = '\0';
}
/* If the expanded filename is an absolute path, check that it's still
** within the current directory or the alternate directory.
*/
if ( hc->expnfilename[0] == '/' )
{
if ( strncmp(
hc->expnfilename, hc->hs->cwd, strlen( hc->hs->cwd ) ) == 0 )
{
/* Elide the current directory. */
(void) strcpy(
hc->expnfilename, &hc->expnfilename[strlen( hc->hs->cwd )] );
}
#ifdef TILDE_MAP_2
else if ( hc->altdir[0] != '\0' &&
( strncmp(
hc->expnfilename, hc->altdir,
strlen( hc->altdir ) ) == 0 &&
( hc->expnfilename[strlen( hc->altdir )] == '\0' ||
hc->expnfilename[strlen( hc->altdir )] == '/' ) ) )
{}
#endif /* TILDE_MAP_2 */
else
{
syslog(
LOG_NOTICE, "%.80s URL \"%.80s\" goes outside the web tree",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file outside the permitted web server directory tree.\n" ),
hc->encodedurl );
return -1;
}
}
return 0;
}
static char*
bufgets( httpd_conn* hc )
{
int i;
char c;
for ( i = hc->checked_idx; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
{
c = hc->read_buf[hc->checked_idx];
if ( c == '\n' || c == '\r' )
{
hc->read_buf[hc->checked_idx] = '\0';
++hc->checked_idx;
if ( c == '\r' && hc->checked_idx < hc->read_idx &&
hc->read_buf[hc->checked_idx] == '\n' )
{
hc->read_buf[hc->checked_idx] = '\0';
++hc->checked_idx;
}
return &(hc->read_buf[i]);
}
}
return (char*) 0;
}
static void
de_dotdot( char* file )
{
char* cp;
char* cp2;
int l;
/* Collapse any multiple / sequences. */
while ( ( cp = strstr( file, "//") ) != (char*) 0 )
{
for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
continue;
(void) strcpy( cp + 1, cp2 );
}
/* Elide any xxx/../ sequences. */
while ( ( cp = strstr( file, "/../" ) ) != (char*) 0 )
{
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
if ( cp2 < file )
break;
(void) strcpy( cp2, cp + 3 );
}
/* Also elide any xxx/.. at the end. */
while ( ( l = strlen( file ) ) > 3 &&
strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
{
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
if ( cp2 < file )
break;
*cp2 = '\0';
}
}
void
httpd_close_conn( httpd_conn* hc, struct timeval* nowP )
{
make_log_entry( hc, nowP );
if ( hc->file_address != (char*) 0 )
{
mmc_unmap( hc->file_address, &(hc->sb), nowP );
hc->file_address = (char*) 0;
}
if ( hc->conn_fd >= 0 )
{
(void) close( hc->conn_fd );
hc->conn_fd = -1;
}
}
void
httpd_destroy_conn( httpd_conn* hc )
{
if ( hc->initialized )
{
free( (void*) hc->read_buf );
free( (void*) hc->decodedurl );
free( (void*) hc->origfilename );
free( (void*) hc->expnfilename );
free( (void*) hc->encodings );
free( (void*) hc->pathinfo );
free( (void*) hc->query );
free( (void*) hc->accept );
free( (void*) hc->accepte );
free( (void*) hc->reqhost );
free( (void*) hc->hostdir );
free( (void*) hc->remoteuser );
free( (void*) hc->response );
#ifdef TILDE_MAP_2
free( (void*) hc->altdir );
#endif /* TILDE_MAP_2 */
hc->initialized = 0;
}
}
/* Figures out MIME encodings and type based on the filename. Multiple
** encodings are separated by semicolons.
*/
static void
figure_mime( httpd_conn* hc )
{
int i, j, k, l;
int got_enc;
struct table {
char* ext;
char* val;
};
static struct table enc_tab[] = {
#include "mime_encodings.h"
};
static struct table typ_tab[] = {
#include "mime_types.h"
};
/* Look at the extensions on hc->expnfilename from the back forwards. */
i = strlen( hc->expnfilename );
for (;;)
{
j = i;
for (;;)
{
--i;
if ( i <= 0 )
{
/* No extensions left. */
hc->type = "text/plain; charset=%s";
return;
}
if ( hc->expnfilename[i] == '.' )
break;
}
/* Found an extension. */
got_enc = 0;
for ( k = 0; k < sizeof(enc_tab)/sizeof(*enc_tab); ++k )
{
l = strlen( enc_tab[k].ext );
if ( l == j - i - 1 &&
strncasecmp( &hc->expnfilename[i+1], enc_tab[k].ext, l ) == 0 )
{
httpd_realloc_str(
&hc->encodings, &hc->maxencodings,
strlen( enc_tab[k].val ) + 1 );
if ( hc->encodings[0] != '\0' )
(void) strcat( hc->encodings, ";" );
(void) strcat( hc->encodings, enc_tab[k].val );
got_enc = 1;
}
}
if ( ! got_enc )
{
/* No encoding extension found - time to try type extensions. */
for ( k = 0; k < sizeof(typ_tab)/sizeof(*typ_tab); ++k )
{
l = strlen( typ_tab[k].ext );
if ( l == j - i - 1 &&
strncasecmp(
&hc->expnfilename[i+1], typ_tab[k].ext, l ) == 0 )
{
hc->type = typ_tab[k].val;
return;
}
}
/* No recognized type extension found - return default. */
hc->type = "text/plain; charset=%s";
return;
}
}
}
#ifdef CGI_TIMELIMIT
static void
cgi_kill2( ClientData client_data, struct timeval* nowP )
{
pid_t pid;
/* Before trying to kill the CGI process, reap any zombie processes.
** That may get rid of the CGI process.
*/
(void) do_reap();
pid = (pid_t) client_data.i;
if ( kill( pid, SIGKILL ) == 0 )
syslog( LOG_ERR, "hard-killed CGI process %d", pid );
}
static void
cgi_kill( ClientData client_data, struct timeval* nowP )
{
pid_t pid;
/* Before trying to kill the CGI process, reap any zombie processes.
** That may get rid of the CGI process.
*/
(void) do_reap();
pid = (pid_t) client_data.i;
if ( kill( pid, SIGINT ) == 0 )
{
syslog( LOG_ERR, "killed CGI process %d", pid );
/* In case this isn't enough, schedule an uncatchable kill. */
if ( tmr_create( nowP, cgi_kill2, client_data, 5 * 1000L, 0 ) == (Timer*) 0 )
{
syslog( LOG_CRIT, "tmr_create(cgi_kill2) failed" );
exit( 1 );
}
}
}
#endif /* CGI_TIMELIMIT */
#ifdef GENERATE_INDEXES
/* qsort comparison routine - declared old-style on purpose, for portability. */
static int
name_compare( a, b )
char** a;
char** b;
{
return strcmp( *a, *b );
}
static off_t
ls( httpd_conn* hc )
{
DIR* dirp;
struct dirent* de;
int namlen;
static int maxnames = 0;
int nnames;
static char* names;
static char** nameptrs;
static char* name;
static int maxname = 0;
static char* rname;
static int maxrname = 0;
static char* encrname;
static int maxencrname = 0;
FILE* fp;
int i, r;
struct stat sb;
struct stat lsb;
char modestr[20];
char* linkprefix;
char link[MAXPATHLEN];
int linklen;
char* fileclass;
time_t now;
char* timestr;
ClientData client_data;
dirp = opendir( hc->expnfilename );
if ( dirp == (DIR*) 0 )
{
syslog( LOG_ERR, "opendir %.80s - %m", hc->expnfilename );
httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
return -1;
}
send_mime( hc, 200, ok200title, "", "", "text/html; charset=%s", -1, hc->sb.st_mtime );
if ( hc->method == METHOD_HEAD )
closedir( dirp );
else if ( hc->method == METHOD_GET )
{
httpd_write_response( hc );
r = fork( );
if ( r < 0 )
{
syslog( LOG_ERR, "fork - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
if ( r == 0 )
{
/* Child process. */
unlisten( hc->hs );
#ifdef CGI_NICE
/* Set priority. */
(void) nice( CGI_NICE );
#endif /* CGI_NICE */
/* Open a stdio stream so that we can use fprintf, which is more
** efficient than a bunch of separate write()s. We don't have
** to worry about double closes or file descriptor leaks cause
** we're in a subprocess.
*/
fp = fdopen( hc->conn_fd, "w" );
if ( fp == (FILE*) 0 )
{
syslog( LOG_ERR, "fdopen - %m" );
httpd_send_err(
hc, 500, err500title, "", err500form, hc->encodedurl );
closedir( dirp );
exit( 1 );
}
(void) fprintf( fp, "\
<HTML><HEAD><TITLE>Index of %.80s</TITLE></HEAD>\n\
<BODY BGCOLOR=\"#99cc99\">\n\
<H2>Index of %.80s</H2>\n\
<PRE>\n\
mode links bytes last-changed name\n\
<HR>",
hc->encodedurl, hc->encodedurl );
/* Read in names. */
nnames = 0;
while ( ( de = readdir( dirp ) ) != 0 ) /* dirent or direct */
{
if ( nnames >= maxnames )
{
if ( maxnames == 0 )
{
maxnames = 100;
names = NEW( char, maxnames * MAXPATHLEN );
nameptrs = NEW( char*, maxnames );
}
else
{
maxnames *= 2;
names = RENEW( names, char, maxnames * MAXPATHLEN );
nameptrs = RENEW( nameptrs, char*, maxnames );
}
if ( names == (char*) 0 || nameptrs == (char**) 0 )
{
syslog( LOG_ERR, "out of memory reallocating directory names" );
exit( 1 );
}
for ( i = 0; i < maxnames; ++i )
nameptrs[i] = &names[i * MAXPATHLEN];
}
namlen = NAMLEN(de);
(void) strncpy( nameptrs[nnames], de->d_name, namlen );
nameptrs[nnames][namlen] = '\0';
++nnames;
}
closedir( dirp );
/* Sort the names. */
qsort( nameptrs, nnames, sizeof(*nameptrs), name_compare );
/* Generate output. */
for ( i = 0; i < nnames; ++i )
{
httpd_realloc_str(
&name, &maxname,
strlen( hc->expnfilename ) + 1 + strlen( nameptrs[i] ) );
httpd_realloc_str(
&rname, &maxrname,
strlen( hc->origfilename ) + 1 + strlen( nameptrs[i] ) );
if ( hc->expnfilename[0] == '\0' ||
strcmp( hc->expnfilename, "." ) == 0 )
{
(void) strcpy( name, nameptrs[i] );
(void) strcpy( rname, nameptrs[i] );
}
else
{
(void) my_snprintf( name, maxname,
"%s/%s", hc->expnfilename, nameptrs[i] );
if ( strcmp( hc->origfilename, "." ) == 0 )
(void) my_snprintf( rname, maxrname,
"%s", nameptrs[i] );
else
(void) my_snprintf( rname, maxrname,
"%s%s", hc->origfilename, nameptrs[i] );
}
httpd_realloc_str(
&encrname, &maxencrname, 3 * strlen( rname ) + 1 );
strencode( encrname, maxencrname, rname );
if ( stat( name, &sb ) < 0 || lstat( name, &lsb ) < 0 )
continue;
linkprefix = "";
link[0] = '\0';
/* Break down mode word. First the file type. */
switch ( lsb.st_mode & S_IFMT )
{
case S_IFIFO: modestr[0] = 'p'; break;
case S_IFCHR: modestr[0] = 'c'; break;
case S_IFDIR: modestr[0] = 'd'; break;
case S_IFBLK: modestr[0] = 'b'; break;
case S_IFREG: modestr[0] = '-'; break;
case S_IFSOCK: modestr[0] = 's'; break;
case S_IFLNK: modestr[0] = 'l';
linklen = readlink( name, link, sizeof(link) );
if ( linklen != -1 )
{
link[linklen] = '\0';
linkprefix = " -> ";
}
break;
default: modestr[0] = '?'; break;
}
/* Now the world permissions. Owner and group permissions
** are not of interest to web clients.
*/
modestr[1] = ( lsb.st_mode & S_IROTH ) ? 'r' : '-';
modestr[2] = ( lsb.st_mode & S_IWOTH ) ? 'w' : '-';
modestr[3] = ( lsb.st_mode & S_IXOTH ) ? 'x' : '-';
modestr[4] = '\0';
/* We also leave out the owner and group name, they are
** also not of interest to web clients. Plus if we're
** running under chroot(), they would require a copy
** of /etc/passwd and /etc/group, which we want to avoid.
*/
/* Get time string. */
now = time( (time_t*) 0 );
timestr = ctime( &lsb.st_mtime );
timestr[ 0] = timestr[ 4];
timestr[ 1] = timestr[ 5];
timestr[ 2] = timestr[ 6];
timestr[ 3] = ' ';
timestr[ 4] = timestr[ 8];
timestr[ 5] = timestr[ 9];
timestr[ 6] = ' ';
if ( now - lsb.st_mtime > 60*60*24*182 ) /* 1/2 year */
{
timestr[ 7] = ' ';
timestr[ 8] = timestr[20];
timestr[ 9] = timestr[21];
timestr[10] = timestr[22];
timestr[11] = timestr[23];
}
else
{
timestr[ 7] = timestr[11];
timestr[ 8] = timestr[12];
timestr[ 9] = ':';
timestr[10] = timestr[14];
timestr[11] = timestr[15];
}
timestr[12] = '\0';
/* The ls -F file class. */
switch ( sb.st_mode & S_IFMT )
{
case S_IFDIR: fileclass = "/"; break;
case S_IFSOCK: fileclass = "="; break;
case S_IFLNK: fileclass = "@"; break;
default:
fileclass = ( sb.st_mode & S_IXOTH ) ? "*" : "";
break;
}
/* And print. */
(void) fprintf( fp,
"%s %3ld %8ld %s <A HREF=\"/%.500s%s\">%.80s</A>%s%s%s\n",
modestr, (long) lsb.st_nlink, (long) lsb.st_size, timestr,
encrname, S_ISDIR(sb.st_mode) ? "/" : "",
nameptrs[i], linkprefix, link, fileclass );
}
(void) fprintf( fp, "</PRE></BODY></HTML>\n" );
(void) fclose( fp );
exit( 0 );
}
/* Parent process. */
closedir( dirp );
syslog( LOG_INFO, "spawned indexing process %d for directory '%.200s'", r, hc->expnfilename );
#ifdef CGI_TIMELIMIT
/* Schedule a kill for the child process, in case it runs too long */
client_data.i = r;
if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
{
syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
exit( 1 );
}
#endif /* CGI_TIMELIMIT */
hc->status = 200;
hc->bytes_sent = CGI_BYTECOUNT;
hc->should_linger = 0;
}
else
{
httpd_send_err(
hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
return -1;
}
return 0;
}
#endif /* GENERATE_INDEXES */
static char*
build_env( char* fmt, char* arg )
{
char* cp;
int size;
static char* buf;
static int maxbuf = 0;
size = strlen( fmt ) + strlen( arg );
if ( size > maxbuf )
httpd_realloc_str( &buf, &maxbuf, size );
(void) my_snprintf( buf, maxbuf,
fmt, arg );
cp = strdup( buf );
if ( cp == (char*) 0 )
{
syslog( LOG_ERR, "out of memory copying environment variable" );
exit( 1 );
}
return cp;
}
#ifdef SERVER_NAME_LIST
static char*
hostname_map( char* hostname )
{
int len, n;
static char* list[] = { SERVER_NAME_LIST };
len = strlen( hostname );
for ( n = sizeof(list) / sizeof(*list) - 1; n >= 0; --n )
if ( strncasecmp( hostname, list[n], len ) == 0 )
if ( list[n][len] == '/' ) /* check in case of a substring match */
return &list[n][len + 1];
return (char*) 0;
}
#endif /* SERVER_NAME_LIST */
/* Set up environment variables. Be real careful here to avoid
** letting malicious clients overrun a buffer. We don't have
** to worry about freeing stuff since we're a sub-process.
*/
static char**
make_envp( httpd_conn* hc )
{
static char* envp[50];
int envn;
char* cp;
char buf[256];
envn = 0;
envp[envn++] = build_env( "PATH=%s", CGI_PATH );
#ifdef CGI_LD_LIBRARY_PATH
envp[envn++] = build_env( "LD_LIBRARY_PATH=%s", CGI_LD_LIBRARY_PATH );
#endif /* CGI_LD_LIBRARY_PATH */
envp[envn++] = build_env( "SERVER_SOFTWARE=%s", SERVER_SOFTWARE );
/* If vhosting, use that server-name here. */
if ( hc->hs->vhost && hc->hostname != (char*) 0 )
cp = hc->hostname;
else
cp = hc->hs->server_hostname;
if ( cp != (char*) 0 )
envp[envn++] = build_env( "SERVER_NAME=%s", cp );
envp[envn++] = "GATEWAY_INTERFACE=CGI/1.1";
envp[envn++] = build_env("SERVER_PROTOCOL=%s", hc->protocol);
(void) my_snprintf( buf, sizeof(buf),
"%d", hc->hs->port );
envp[envn++] = build_env( "SERVER_PORT=%s", buf );
envp[envn++] = build_env(
"REQUEST_METHOD=%s", httpd_method_str( hc->method ) );
if ( hc->pathinfo[0] != '\0' )
{
char* cp2;
int l;
envp[envn++] = build_env( "PATH_INFO=/%s", hc->pathinfo );
l = strlen( hc->hs->cwd ) + strlen( hc->pathinfo ) + 1;
cp2 = NEW( char, l );
if ( cp2 != (char*) 0 )
{
(void) my_snprintf( cp2, l,
"%s%s", hc->hs->cwd, hc->pathinfo );
envp[envn++] = build_env( "PATH_TRANSLATED=%s", cp2 );
}
}
envp[envn++] = build_env(
"SCRIPT_NAME=/%s", strcmp( hc->origfilename, "." ) == 0 ?
"" : hc->origfilename );
if ( hc->query[0] != '\0')
envp[envn++] = build_env( "QUERY_STRING=%s", hc->query );
envp[envn++] = build_env(
"REMOTE_ADDR=%s", httpd_ntoa( &hc->client_addr ) );
if ( hc->referer[0] != '\0' )
envp[envn++] = build_env( "HTTP_REFERER=%s", hc->referer );
if ( hc->useragent[0] != '\0' )
envp[envn++] = build_env( "HTTP_USER_AGENT=%s", hc->useragent );
if ( hc->accept[0] != '\0' )
envp[envn++] = build_env( "HTTP_ACCEPT=%s", hc->accept );
if ( hc->accepte[0] != '\0' )
envp[envn++] = build_env( "HTTP_ACCEPT_ENCODING=%s", hc->accepte );
if ( hc->acceptl[0] != '\0' )
envp[envn++] = build_env( "HTTP_ACCEPT_LANGUAGE=%s", hc->acceptl );
if ( hc->cookie[0] != '\0' )
envp[envn++] = build_env( "HTTP_COOKIE=%s", hc->cookie );
if ( hc->contenttype[0] != '\0' )
envp[envn++] = build_env( "CONTENT_TYPE=%s", hc->contenttype );
if ( hc->hdrhost[0] != '\0' )
envp[envn++] = build_env( "HTTP_HOST=%s", hc->hdrhost );
if ( hc->contentlength != -1 )
{
(void) my_snprintf( buf, sizeof(buf),
"%ld", (long) hc->contentlength );
envp[envn++] = build_env( "CONTENT_LENGTH=%s", buf );
}
if ( hc->remoteuser[0] != '\0' )
envp[envn++] = build_env( "REMOTE_USER=%s", hc->remoteuser );
if ( hc->authorization[0] == '\0' )
envp[envn++] = build_env( "AUTH_TYPE=%s", "Basic" );
/* We only support Basic auth at the moment. */
if ( getenv( "TZ" ) != (char*) 0 )
envp[envn++] = build_env( "TZ=%s", getenv( "TZ" ) );
envp[envn++] = build_env( "CGI_PATTERN=%s", hc->hs->cgi_pattern );
envp[envn] = (char*) 0;
return envp;
}
/* Set up argument vector. Again, we don't have to worry about freeing stuff
** since we're a sub-process. This gets done after make_envp() because we
** scribble on hc->query.
*/
static char**
make_argp( httpd_conn* hc )
{
char** argp;
int argn;
char* cp1;
char* cp2;
/* By allocating an arg slot for every character in the query, plus
** one for the filename and one for the NULL, we are guaranteed to
** have enough. We could actually use strlen/2.
*/
argp = NEW( char*, strlen( hc->query ) + 2 );
if ( argp == (char**) 0 )
return (char**) 0;
argp[0] = strrchr( hc->expnfilename, '/' );
if ( argp[0] != (char*) 0 )
++argp[0];
else
argp[0] = hc->expnfilename;
argn = 1;
/* According to the CGI spec at http://hoohoo.ncsa.uiuc.edu/cgi/cl.html,
** "The server should search the query information for a non-encoded =
** character to determine if the command line is to be used, if it finds
** one, the command line is not to be used."
*/
if ( strchr( hc->query, '=' ) == (char*) 0 )
{
for ( cp1 = cp2 = hc->query; *cp2 != '\0'; ++cp2 )
{
if ( *cp2 == '+' )
{
*cp2 = '\0';
strdecode( cp1, cp1 );
argp[argn++] = cp1;
cp1 = cp2 + 1;
}
}
if ( cp2 != cp1 )
{
strdecode( cp1, cp1 );
argp[argn++] = cp1;
}
}
argp[argn] = (char*) 0;
return argp;
}
/* This routine is used only for POST requests. It reads the data
** from the request and sends it to the child process. The only reason
** we need to do it this way instead of just letting the child read
** directly is that we have already read part of the data into our
** buffer.
*/
static void
cgi_interpose_input( httpd_conn* hc, int wfd )
{
int c, r;
char buf[1024];
c = hc->read_idx - hc->checked_idx;
if ( c > 0 )
{
if ( write( wfd, &(hc->read_buf[hc->checked_idx]), c ) != c )
return;
}
while ( c < hc->contentlength )
{
r = read( hc->conn_fd, buf, MIN( sizeof(buf), hc->contentlength - c ) );
if ( r == 0 )
sleep( 1 );
else if ( r < 0 )
{
if ( errno == EAGAIN )
sleep( 1 );
else
return;
}
else
{
if ( write( wfd, buf, r ) != r )
return;
c += r;
}
}
post_post_garbage_hack( hc );
}
/* Special hack to deal with broken browsers that send a LF or CRLF
** after POST data, causing TCP resets - we just read and discard up
** to 2 bytes. Unfortunately this doesn't fix the problem for CGIs
** which avoid the interposer process due to their POST data being
** short. Creating an interposer process for all POST CGIs is
** unacceptably expensive. The eventual fix will come when interposing
** gets integrated into the main loop as a tasklet instead of a process.
*/
static void
post_post_garbage_hack( httpd_conn* hc )
{
char buf[2];
int r;
r = recv( hc->conn_fd, buf, sizeof(buf), MSG_PEEK );
if ( r > 0 )
(void) read( hc->conn_fd, buf, r );
}
/* This routine is used for parsed-header CGIs. The idea here is that the
** CGI can return special headers such as "Status:" and "Location:" which
** change the return status of the response. Since the return status has to
** be the very first line written out, we have to accumulate all the headers
** and check for the special ones before writing the status. Then we write
** out the saved headers and proceed to echo the rest of the response.
*/
static void
cgi_interpose_output( httpd_conn* hc, int rfd )
{
int r;
char buf[1024];
int headers_size, headers_len;
char* headers;
char* br;
int status;
char* title;
char* cp;
/* Slurp in all headers. */
headers_size = 0;
httpd_realloc_str( &headers, &headers_size, 500 );
headers_len = 0;
for (;;)
{
r = read( rfd, buf, sizeof(buf) );
if ( r <= 0 )
{
br = &(headers[headers_len]);
break;
}
httpd_realloc_str( &headers, &headers_size, headers_len + r );
(void) memcpy( &(headers[headers_len]), buf, r );
headers_len += r;
headers[headers_len] = '\0';
if ( ( br = strstr( headers, "\r\n\r\n" ) ) != (char*) 0 ||
( br = strstr( headers, "\n\n" ) ) != (char*) 0 )
break;
}
/* Figure out the status. */
status = 200;
if ( ( cp = strstr( headers, "Status:" ) ) != (char*) 0 &&
cp < br &&
( cp == headers || *(cp-1) == '\n' ) )
{
cp += 7;
cp += strspn( cp, " \t" );
status = atoi( cp );
}
if ( ( cp = strstr( headers, "Location:" ) ) != (char*) 0 &&
cp < br &&
( cp == headers || *(cp-1) == '\n' ) )
status = 302;
/* Write the status line. */
switch ( status )
{
case 200: title = ok200title; break;
case 302: title = err302title; break;
case 304: title = err304title; break;
case 400: title = httpd_err400title; break;
#ifdef AUTH_FILE
case 401: title = err401title; break;
#endif /* AUTH_FILE */
case 403: title = err403title; break;
case 404: title = err404title; break;
case 408: title = httpd_err408title; break;
case 500: title = err500title; break;
case 501: title = err501title; break;
case 503: title = httpd_err503title; break;
default: title = "Something"; break;
}
(void) my_snprintf( buf, sizeof(buf), "HTTP/1.0 %d %s\r\n", status, title );
(void) write( hc->conn_fd, buf, strlen( buf ) );
/* Write the saved headers. */
(void) write( hc->conn_fd, headers, headers_len );
/* Echo the rest of the output. */
for (;;)
{
r = read( rfd, buf, sizeof(buf) );
if ( r <= 0 )
return;
if ( write( hc->conn_fd, buf, r ) != r )
return;
}
}
/* CGI child process. */
static void
cgi_child( httpd_conn* hc )
{
int r;
char** argp;
char** envp;
char* binary;
char* directory;
/* Unset close-on-exec flag for this socket. This actually shouldn't
** be necessary, according to POSIX a dup()'d file descriptor does
** *not* inherit the close-on-exec flag, its flag is always clear.
** However, Linux messes this up and does copy the flag to the
** dup()'d descriptor, so we have to clear it. This could be
** ifdeffed for Linux only.
*/
(void) fcntl( hc->conn_fd, F_SETFD, 0 );
/* Close the syslog descriptor so that the CGI program can't
** mess with it. All other open descriptors should be either
** the listen socket(s), sockets from accept(), or the file-logging
** fd, and all of those are set to close-on-exec, so we don't
** have to close anything else.
*/
closelog();
/* If the socket happens to be using one of the stdin/stdout/stderr
** descriptors, move it to another descriptor so that the dup2 calls
** below don't screw things up.
*/
if ( hc->conn_fd == STDIN_FILENO || hc->conn_fd == STDOUT_FILENO || hc->conn_fd == STDERR_FILENO )
{
int newfd = dup( hc->conn_fd );
if ( newfd >= 0 )
hc->conn_fd = newfd;
/* If the dup fails, shrug. We'll just take our chances.
** Shouldn't happen though.
**
** If the dup happens to produce an fd that is still one of
** the standard ones, we should be ok - I think it can be
** fd 2, stderr, but can never show up as 0 or 1 since at
** least two file descriptors are always in use. Because
** of the order in which we dup2 things below - stderr is
** always done last - it's actually ok for the socket to
** be fd 2. It'll just get dup2'd onto itself.
*/
}
/* Make the environment vector. */
envp = make_envp( hc );
/* Make the argument vector. */
argp = make_argp( hc );
/* Set up stdin. For POSTs we may have to set up a pipe from an
** interposer process, depending on if we've read some of the data
** into our buffer.
*/
if ( hc->method == METHOD_POST && hc->read_idx > hc->checked_idx )
{
int p[2];
if ( pipe( p ) < 0 )
{
syslog( LOG_ERR, "pipe - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
exit( 1 );
}
r = fork( );
if ( r < 0 )
{
syslog( LOG_ERR, "fork - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
exit( 1 );
}
if ( r == 0 )
{
/* Interposer process. */
(void) close( p[0] );
cgi_interpose_input( hc, p[1] );
exit( 0 );
}
(void) close( p[1] );
(void) dup2( p[0], STDIN_FILENO );
(void) close( p[0] );
}
else
{
/* Otherwise, the request socket is stdin. */
(void) dup2( hc->conn_fd, STDIN_FILENO );
}
/* Set up stdout/stderr. If we're doing CGI header parsing,
** we need an output interposer too.
*/
if ( strncmp( argp[0], "nph-", 4 ) != 0 && hc->mime_flag )
{
int p[2];
if ( pipe( p ) < 0 )
{
syslog( LOG_ERR, "pipe - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
exit( 1 );
}
r = fork( );
if ( r < 0 )
{
syslog( LOG_ERR, "fork - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
exit( 1 );
}
if ( r == 0 )
{
/* Interposer process. */
(void) close( p[1] );
cgi_interpose_output( hc, p[0] );
exit( 0 );
}
(void) close( p[0] );
(void) dup2( p[1], STDOUT_FILENO );
(void) dup2( p[1], STDERR_FILENO );
(void) close( p[1] );
}
else
{
/* Otherwise, the request socket is stdout/stderr. */
(void) dup2( hc->conn_fd, STDOUT_FILENO );
(void) dup2( hc->conn_fd, STDERR_FILENO );
}
/* At this point we would like to set close-on-exec again for hc->conn_fd
** (see previous comments on Linux's broken behavior re: close-on-exec
** and dup.) Unfortunately there seems to be another Linux problem, or
** perhaps a different aspect of the same problem - if we do this
** close-on-exec in Linux, the socket stays open but stderr gets
** closed - the last fd duped from the socket. What a mess. So we'll
** just leave the socket as is, which under other OSs means an extra
** file descriptor gets passed to the child process. Since the child
** probably already has that file open via stdin stdout and/or stderr,
** this is not a problem.
*/
/* (void) fcntl( hc->conn_fd, F_SETFD, 1 ); */
#ifdef CGI_NICE
/* Set priority. */
(void) nice( CGI_NICE );
#endif /* CGI_NICE */
/* Split the program into directory and binary, so we can chdir()
** to the program's own directory. This isn't in the CGI 1.1
** spec, but it's what other HTTP servers do.
*/
directory = strdup( hc->expnfilename );
if ( directory == (char*) 0 )
binary = hc->expnfilename; /* ignore errors */
else
{
binary = strrchr( directory, '/' );
if ( binary == (char*) 0 )
binary = hc->expnfilename;
else
{
*binary++ = '\0';
(void) chdir( directory ); /* ignore errors */
}
}
/* Default behavior for SIGPIPE. */
(void) signal( SIGPIPE, SIG_DFL );
/* Run the program. */
(void) execve( binary, argp, envp );
/* Something went wrong. */
syslog( LOG_ERR, "execve %.80s - %m", hc->expnfilename );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
exit( 1 );
}
static off_t
cgi( httpd_conn* hc )
{
int r;
ClientData client_data;
if ( hc->method == METHOD_GET || hc->method == METHOD_POST )
{
httpd_clear_ndelay( hc->conn_fd );
r = fork( );
if ( r < 0 )
{
syslog( LOG_ERR, "fork - %m" );
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
if ( r == 0 )
{
unlisten( hc->hs );
cgi_child( hc );
}
/* Parent process. */
syslog( LOG_INFO, "spawned CGI process %d for file '%.200s'", r, hc->expnfilename );
#ifdef CGI_TIMELIMIT
/* Schedule a kill for the child process, in case it runs too long */
client_data.i = r;
if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
{
syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
exit( 1 );
}
#endif /* CGI_TIMELIMIT */
hc->status = 200;
hc->bytes_sent = CGI_BYTECOUNT;
hc->should_linger = 0;
}
else
{
httpd_send_err(
hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
return -1;
}
return 0;
}
static int
really_start_request( httpd_conn* hc, struct timeval* nowP )
{
static char* indexname;
static int maxindexname = 0;
static const char* index_names[] = { INDEX_NAMES };
int i;
#ifdef AUTH_FILE
static char* dirname;
static int maxdirname = 0;
#endif /* AUTH_FILE */
int expnlen, indxlen;
char* cp;
char* pi;
expnlen = strlen( hc->expnfilename );
if ( hc->method != METHOD_GET && hc->method != METHOD_HEAD &&
hc->method != METHOD_POST )
{
httpd_send_err(
hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
return -1;
}
/* Stat the file. */
if ( stat( hc->expnfilename, &hc->sb ) < 0 )
{
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
/* Is it world-readable or world-executable? We check explicitly instead
** of just trying to open it, so that no one ever gets surprised by
** a file that's not set world-readable and yet somehow is
** readable by the HTTP server and therefore the *whole* world.
*/
if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
{
syslog(
LOG_INFO,
"%.80s URL \"%.80s\" resolves to a non world-readable file",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file that is not world-readable.\n" ),
hc->encodedurl );
return -1;
}
/* Is it a directory? */
if ( S_ISDIR(hc->sb.st_mode) )
{
/* If there's pathinfo, it's just a non-existent file. */
if ( hc->pathinfo[0] != '\0' )
{
httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
return -1;
}
/* Special handling for directory URLs that don't end in a slash.
** We send back an explicit redirect with the slash, because
** otherwise many clients can't build relative URLs properly.
*/
if ( hc->decodedurl[strlen( hc->decodedurl ) - 1] != '/' )
{
send_dirredirect( hc );
return -1;
}
/* Check for an index file. */
for ( i = 0; i < sizeof(index_names) / sizeof(char*); ++i )
{
httpd_realloc_str(
&indexname, &maxindexname,
expnlen + 1 + strlen( index_names[i] ) );
(void) strcpy( indexname, hc->expnfilename );
indxlen = strlen( indexname );
if ( indxlen == 0 || indexname[indxlen - 1] != '/' )
(void) strcat( indexname, "/" );
if ( strcmp( indexname, "./" ) == 0 )
indexname[0] = '\0';
(void) strcat( indexname, index_names[i] );
if ( stat( indexname, &hc->sb ) >= 0 )
goto got_one;
}
/* Nope, no index file, so it's an actual directory request. */
#ifdef GENERATE_INDEXES
/* Directories must be readable for indexing. */
if ( ! ( hc->sb.st_mode & S_IROTH ) )
{
syslog(
LOG_INFO,
"%.80s URL \"%.80s\" tried to index a directory with indexing disabled",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a directory that has indexing disabled.\n" ),
hc->encodedurl );
return -1;
}
#ifdef AUTH_FILE
/* Check authorization for this directory. */
if ( auth_check( hc, hc->expnfilename ) == -1 )
return -1;
#endif /* AUTH_FILE */
/* Referer check. */
if ( ! check_referer( hc ) )
return -1;
/* Ok, generate an index. */
return ls( hc );
#else /* GENERATE_INDEXES */
syslog(
LOG_INFO, "%.80s URL \"%.80s\" tried to index a directory",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' is a directory, and directory indexing is disabled on this server.\n" ),
hc->encodedurl );
return -1;
#endif /* GENERATE_INDEXES */
got_one: ;
/* Got an index file. Expand symlinks again. More pathinfo means
** something went wrong.
*/
cp = expand_symlinks( indexname, &pi, hc->hs->no_symlink, hc->tildemapped );
if ( cp == (char*) 0 || pi[0] != '\0' )
{
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
expnlen = strlen( cp );
httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, expnlen );
(void) strcpy( hc->expnfilename, cp );
/* Now, is the index version world-readable or world-executable? */
if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
{
syslog(
LOG_INFO,
"%.80s URL \"%.80s\" resolves to a non-world-readable index file",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to an index file that is not world-readable.\n" ),
hc->encodedurl );
return -1;
}
}
#ifdef AUTH_FILE
/* Check authorization for this directory. */
httpd_realloc_str( &dirname, &maxdirname, expnlen );
(void) strcpy( dirname, hc->expnfilename );
cp = strrchr( dirname, '/' );
if ( cp == (char*) 0 )
(void) strcpy( dirname, "." );
else
*cp = '\0';
if ( auth_check( hc, dirname ) == -1 )
return -1;
/* Check if the filename is the AUTH_FILE itself - that's verboten. */
if ( expnlen == sizeof(AUTH_FILE) - 1 )
{
if ( strcmp( hc->expnfilename, AUTH_FILE ) == 0 )
{
syslog(
LOG_NOTICE,
"%.80s URL \"%.80s\" tried to retrieve an auth file",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
hc->encodedurl );
return -1;
}
}
else if ( expnlen >= sizeof(AUTH_FILE) &&
strcmp( &(hc->expnfilename[expnlen - sizeof(AUTH_FILE) + 1]), AUTH_FILE ) == 0 &&
hc->expnfilename[expnlen - sizeof(AUTH_FILE)] == '/' )
{
syslog(
LOG_NOTICE,
"%.80s URL \"%.80s\" tried to retrieve an auth file",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
hc->encodedurl );
return -1;
}
#endif /* AUTH_FILE */
/* Referer check. */
if ( ! check_referer( hc ) )
return -1;
/* Is it world-executable and in the CGI area? */
if ( hc->hs->cgi_pattern != (char*) 0 &&
( hc->sb.st_mode & S_IXOTH ) &&
match( hc->hs->cgi_pattern, hc->expnfilename ) )
return cgi( hc );
/* It's not CGI. If it's executable or there's pathinfo, someone's
** trying to either serve or run a non-CGI file as CGI. Either case
** is prohibited.
*/
if ( hc->sb.st_mode & S_IXOTH )
{
syslog(
LOG_NOTICE, "%.80s URL \"%.80s\" is executable but isn't CGI",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file which is marked executable but is not a CGI file; retrieving it is forbidden.\n" ),
hc->encodedurl );
return -1;
}
if ( hc->pathinfo[0] != '\0' )
{
syslog(
LOG_INFO, "%.80s URL \"%.80s\" has pathinfo but isn't CGI",
httpd_ntoa( &hc->client_addr ), hc->encodedurl );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file plus CGI-style pathinfo, but the file is not a valid CGI file.\n" ),
hc->encodedurl );
return -1;
}
/* Fill in end_byte_loc, if necessary. */
if ( hc->got_range &&
( hc->end_byte_loc == -1 || hc->end_byte_loc >= hc->sb.st_size ) )
hc->end_byte_loc = hc->sb.st_size - 1;
figure_mime( hc );
if ( hc->method == METHOD_HEAD )
{
send_mime(
hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
hc->sb.st_mtime );
}
else if ( hc->if_modified_since != (time_t) -1 &&
hc->if_modified_since >= hc->sb.st_mtime )
{
hc->method = METHOD_HEAD;
send_mime(
hc, 304, err304title, hc->encodings, "", hc->type, hc->sb.st_size,
hc->sb.st_mtime );
}
else
{
hc->file_address = mmc_map( hc->expnfilename, &(hc->sb), nowP );
if ( hc->file_address == (char*) 0 )
{
httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
return -1;
}
send_mime(
hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
hc->sb.st_mtime );
}
return 0;
}
int
httpd_start_request( httpd_conn* hc, struct timeval* nowP )
{
int r;
/* Really start the request. */
r = really_start_request( hc, nowP );
/* And return the status. */
return r;
}
static void
make_log_entry( httpd_conn* hc, struct timeval* nowP )
{
char* ru;
char url[305];
char bytes[40];
if ( hc->hs->no_log )
return;
/* This is straight CERN Combined Log Format - the only tweak
** being that if we're using syslog() we leave out the date, because
** syslogd puts it in. The included syslogtocern script turns the
** results into true CERN format.
*/
/* Format remote user. */
if ( hc->remoteuser[0] != '\0' )
ru = hc->remoteuser;
else
ru = "-";
/* If we're vhosting, prepend the hostname to the url. This is
** a little weird, perhaps writing separate log files for
** each vhost would make more sense.
*/
if ( hc->hs->vhost && ! hc->tildemapped )
(void) my_snprintf( url, sizeof(url),
"/%.100s%.200s",
hc->hostname == (char*) 0 ? hc->hs->server_hostname : hc->hostname,
hc->encodedurl );
else
(void) my_snprintf( url, sizeof(url),
"%.200s", hc->encodedurl );
/* Format the bytes. */
if ( (long) hc->bytes_sent >= 0 )
(void) my_snprintf( bytes, sizeof(bytes),
"%ld", (long) hc->bytes_sent );
else
(void) strcpy( bytes, "-" );
/* Logfile or syslog? */
if ( hc->hs->logfp != (FILE*) 0 )
{
time_t now;
struct tm* t;
const char* cernfmt_nozone = "%d/%b/%Y:%H:%M:%S";
char date_nozone[100];
int zone;
char sign;
char date[100];
/* Get the current time, if necessary. */
if ( nowP != (struct timeval*) 0 )
now = nowP->tv_sec;
else
now = time( (time_t*) 0 );
/* Format the time, forcing a numeric timezone (some log analyzers
** are stoooopid about this).
*/
t = localtime( &now );
(void) strftime( date_nozone, sizeof(date_nozone), cernfmt_nozone, t );
#ifdef HAVE_TM_GMTOFF
zone = t->tm_gmtoff / 60L;
#else
zone = -timezone / 60L;
/* Probably have to add something about daylight time here. */
#endif
if ( zone >= 0 )
sign = '+';
else
{
sign = '-';
zone = -zone;
}
zone = ( zone / 60 ) * 100 + zone % 60;
(void) my_snprintf( date, sizeof(date),
"%s %c%04d", date_nozone, sign, zone );
/* And write the log entry. */
(void) fprintf( hc->hs->logfp,
"%.80s - %.80s [%s] \"%.80s %.300s %.80s\" %d %s \"%.200s\" \"%.80s\"\n",
httpd_ntoa( &hc->client_addr ), ru, date,
httpd_method_str( hc->method ), url, hc->protocol,
hc->status, bytes, hc->referer, hc->useragent );
(void) fflush( hc->hs->logfp ); /* don't need to flush every time */
}
else
syslog( LOG_INFO,
"%.80s - %.80s \"%.80s %.200s %.80s\" %d %s \"%.200s\" \"%.80s\"",
httpd_ntoa( &hc->client_addr ), ru,
httpd_method_str( hc->method ), url, hc->protocol,
hc->status, bytes, hc->referer, hc->useragent );
}
/* Returns 1 if ok to serve the url, 0 if not. */
static int
check_referer( httpd_conn* hc )
{
int r;
/* Are we doing referer checking at all? */
if ( hc->hs->url_pattern == (char*) 0 )
return 1;
r = really_check_referer( hc );
if ( ! r )
{
syslog(
LOG_INFO, "%.80s non-local referer \"%.80s\" \"%.80s\"",
httpd_ntoa( &hc->client_addr ), hc->encodedurl,
hc->referer );
httpd_send_err(
hc, 403, err403title, "",
ERROR_FORM( err403form, "You must supply a local referer to get URL '%.80s' from this server.\n" ),
hc->encodedurl );
}
return r;
}
/* Returns 1 if ok to serve the url, 0 if not. */
static int
really_check_referer( httpd_conn* hc )
{
httpd_server* hs;
char* cp1;
char* cp2;
char* cp3;
static char* refhost = (char*) 0;
static int refhost_size = 0;
char *lp;
hs = hc->hs;
/* Check for an empty referer. */
if ( hc->referer == (char*) 0 || hc->referer[0] == '\0' ||
( cp1 = strstr( hc->referer, "//" ) ) == (char*) 0 )
{
/* Disallow if we require a referer and the url matches. */
if ( hs->no_empty_referers && match( hs->url_pattern, hc->decodedurl ) )
return 0;
/* Otherwise ok. */
return 1;
}
/* Extract referer host. */
cp1 += 2;
for ( cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2 )
continue;
httpd_realloc_str( &refhost, &refhost_size, cp2 - cp1 );
for ( cp3 = refhost; cp1 < cp2; ++cp1, ++cp3 )
if ( isupper(*cp1) )
*cp3 = tolower(*cp1);
else
*cp3 = *cp1;
*cp3 = '\0';
/* Local pattern? */
if ( hs->local_pattern != (char*) 0 )
lp = hs->local_pattern;
else
{
/* No local pattern. What's our hostname? */
if ( ! hs->vhost )
{
/* Not vhosting, use the server name. */
lp = hs->server_hostname;
if ( lp == (char*) 0 )
/* Couldn't figure out local hostname - give up. */
return 1;
}
else
{
/* We are vhosting, use the hostname on this connection. */
lp = hc->hostname;
if ( lp == (char*) 0 )
/* Oops, no hostname. Maybe it's an old browser that
** doesn't send a Host: header. We could figure out
** the default hostname for this IP address, but it's
** not worth it for the few requests like this.
*/
return 1;
}
}
/* If the referer host doesn't match the local host pattern, and
** the URL does match the url pattern, it's an illegal reference.
*/
if ( ! match( lp, refhost ) && match( hs->url_pattern, hc->decodedurl ) )
return 0;
/* Otherwise ok. */
return 1;
}
char*
httpd_ntoa( httpd_sockaddr* saP )
{
#ifdef HAVE_GETNAMEINFO
static char str[200];
if ( getnameinfo( &saP->sa, sockaddr_len( saP ), str, sizeof(str), 0, 0, NI_NUMERICHOST ) != 0 )
{
str[0] = '?';
str[1] = '\0';
}
return str;
#else /* HAVE_GETNAMEINFO */
return inet_ntoa( saP->sa_in.sin_addr );
#endif /* HAVE_GETNAMEINFO */
}
static int
sockaddr_check( httpd_sockaddr* saP )
{
switch ( saP->sa.sa_family )
{
case AF_INET: return 1;
#if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
case AF_INET6: return 1;
#endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
default:
return 0;
}
}
static size_t
sockaddr_len( httpd_sockaddr* saP )
{
switch ( saP->sa.sa_family )
{
case AF_INET: return sizeof(struct sockaddr_in);
#if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
case AF_INET6: return sizeof(struct sockaddr_in6);
#endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
default:
return 0; /* shouldn't happen */
}
}
/* Some systems don't have snprintf(), so we make our own that uses
** either vsnprintf() or vsprintf(). If your system doesn't have
** vsnprintf(), it is probably vulnerable to buffer overruns.
** Upgrade!
*/
static int
my_snprintf( char* str, size_t size, const char* format, ... )
{
va_list ap;
int r;
va_start( ap, format );
#ifdef HAVE_VSNPRINTF
r = vsnprintf( str, size, format, ap );
#else /* HAVE_VSNPRINTF */
r = vsprintf( str, format, ap );
#endif /* HAVE_VSNPRINTF */
va_end( ap );
return r;
}
/* Generate debugging statistics syslog message. */
void
httpd_logstats( long secs )
{
syslog( LOG_NOTICE,
" libhttpd - %d strings allocated, %ld bytes (%g bytes/str)",
str_alloc_count, str_alloc_size,
(float) str_alloc_size / str_alloc_count );
}
|