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
|
/*
//
// htp.c
//
// main(), major functionality modules
//
// Copyright (c) 1995-96 Jim Nelson. Permission to distribute
// granted by the author. No warranties are made on the fitness of this
// source code.
//
*/
#include "htp.h"
/*
// default response filename
*/
const char *DEFAULT_RESPONSE_FILE = "htp.rsp";
/*
// variable types
*/
#define VAR_TYPE_SET_MACRO (1)
#define VAR_TYPE_BLOCK_MACRO (2)
#define VAR_TYPE_INTERNAL (3)
#define VAR_TYPE_ALTTEXT (4)
#define VAR_TYPE_DEF_MACRO (5)
/*
// variable flags
*/
#define VAR_FLAG_NONE (0x0000)
#define VAR_FLAG_QUOTED (0x0001)
/*
// specialized markup processors type definitions
*/
/* MARKUP_FUNC return codes */
#define MARKUP_OKAY (0)
#define MARKUP_REPLACED (1)
#define DISCARD_MARKUP (2)
#define MARKUP_ERROR ((uint) -1)
#define NEW_MARKUP (3)
/*
// when reading source files, need to dynamically allocate memory to avoid
// overruns ... use a stronger strategy for "real" operating systems, more
// conservative for wimpy DOS
*/
#if __MSDOS__
#define MIN_PLAINTEXT_SIZE (128)
#define PLAINTEXT_GROW_SIZE (32)
#else
#define MIN_PLAINTEXT_SIZE (16 * KBYTE)
#define PLAINTEXT_GROW_SIZE (4 * KBYTE)
#endif
/*
// miscellaneous definitions
*/
#define MAX_TIME_DATE_SIZE (128)
#define DEFAULT_PRECISION (0)
#define SEARCH_PATH_SIZE (1024)
/*
// htp task structure
//
// (the word "task" is not to be confused with the traditional operating system
// term ... it is used here to represent all the information associated with
// the particular job at hand, which is reading in a file, writing out to
// a file, and maintaining information during the entire operation)
*/
typedef struct tagTASK
{
TEXTFILE *infile;
TEXTFILE *outfile;
VARSTORE *varstore;
const char *sourceFilename;
} TASK;
/*
// markup processor function and array association structure
*/
typedef uint (*MARKUP_FUNC)(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext);
typedef struct tagMARKUP_PROCESSORS
{
const char *tag;
uint markupType;
MARKUP_FUNC markupFunc;
} MARKUP_PROCESSORS;
/*
// template file name (used internally to store name for post-processing)
// use squirrelly characters and a space to avoid conflicting with
// user names
*/
const char *VAR_TEMPLATE_NAME = "__!TEMPLATE FILE~";
/*
// forward references
*/
BOOL ProcessTask(TASK *task);
BOOL OptionCallback(const char *name, const char *value, ulong userParam);
/*
// the user can configure what kind of characters to use to surround htp
// markups, to avoid conflicts with HTML markups ... default is the standard
// greater-than/less-than bracketing, but also acceptable are square
// brackets and curly brackets (parentheses are just too common in normal
// text to be useful)
//
// Because htp also processes standard HTML markups, a IS_OPEN_MARKUP and
// IS_CLOSE_MARKUP macros are used instead of standard comparisons ... watch
// out for side-effects
//
// MARKUP_TYPE_ANY is used for markup processors to define they are
// interested in either kind of markup (currently unused)
//
// MARKUP_OPEN_DELIM and MARKUP_CLOSE_DELIM are used to return the proper
// delimiter given the markup type
*/
#define HTML_OPEN_MARKUP ('<')
#define HTML_CLOSE_MARKUP ('>')
char htpOpenMarkup = HTML_OPEN_MARKUP;
char htpCloseMarkup = HTML_CLOSE_MARKUP;
#define IS_OPEN_MARKUP(c) (((c) == '<') || ((c) == htpOpenMarkup))
#define IS_CLOSE_MARKUP(c) (((c) == '>') || ((c) == htpCloseMarkup))
#define MARKUP_TYPE_HTML (0x0001)
#define MARKUP_TYPE_HTP (0x0002)
#define MARKUP_TYPE_ANY (0xFFFF)
#define MARKUP_OPEN_DELIM(t) \
(((t) & MARKUP_TYPE_HTP) ? htpOpenMarkup : HTML_OPEN_MARKUP)
#define MARKUP_CLOSE_DELIM(t) \
(((t) & MARKUP_TYPE_HTP) ? htpCloseMarkup : HTML_CLOSE_MARKUP)
/*
// the global variable store ... holds permanent, file-to-file macros
// (these are set in the global default file) ... filename kept for
// dependency checking
*/
VARSTORE globalVarStore;
char globalFilename[MAX_PATHNAME_LEN];
/*
// the "project" variable store ... holds macros only for files in current
// directory, or project (this is loaded from the project default file,
// which is called htp.def)
*/
VARSTORE projectVarStore;
char projectFilename[MAX_PATHNAME_LEN];
/*
// include file search path
*/
char searchPath[SEARCH_PATH_SIZE] = { 0, };
/*
// ALT text macro store
*/
VARSTORE altTextVarStore;
/*
// for tracking ExpandMacros performance, debug version only
*/
#if DEBUG
uint expandSkipped = 0;
uint expandPerformed = 0;
#endif
/*
//
// generic, global utility functions
//
*/
/*
// temporary file name generator
*/
BOOL CreateTempFilename(char *tempfilename, uint size)
{
static char *tempDir;
char *tmpName;
assert(tempfilename != NULL);
/* find a preferred temporary directory if not found already */
if(tempDir == NULL)
{
if((tempDir = getenv("TEMP")) == NULL)
{
if((tempDir = getenv("TMP")) == NULL)
{
tempDir = DIR_CURRENT_STRING;
}
}
}
/* get a temporary filename */
if((tmpName = tempnam(tempDir, (char *) PROGRAM_NAME)) != NULL)
{
/* copy the filename to the callers buffer */
StringCopy(tempfilename, tmpName, size);
/* free the tempnam buffer and return success */
free(tmpName);
return TRUE;
}
return FALSE;
}
#if 0
/*
// extract directory from a filename, if present
*/
char *GetFileDirectory(const char *filename, char *directory, uint size)
{
const char *filePtr;
uint len;
*directory = NUL;
len = strlen(filename);
if(len == 0)
{
return directory;
}
filePtr = filename + len - 1;
while(filePtr != filename)
{
if(*filePtr == DIR_DELIMITER)
{
return StringCopy(directory, filename, (len <= size) ? len : size);
}
filePtr--;
len--;
}
return directory;
}
#endif
/*
// ParseFilename
//
// Returns a pointer to the filename in a full pathname
*/
char *FindFilename(char *pathname)
{
char *filePtr;
uint len;
assert(pathname != NULL);
if(pathname == NULL)
{
return NULL;
}
len = strlen(pathname);
if(len == 0)
{
return pathname;
}
filePtr = pathname + len - 1;
while(filePtr != pathname)
{
if(strchr(ALL_FILESYSTEM_DELIMITERS, *filePtr) != NULL)
{
/* found the first delimiter, return pointer to character just */
/* past this one */
/* if pathname ended in a delimiter, then this will return a */
/* pointer to NUL, which is acceptable */
return filePtr + 1;
}
filePtr--;
}
return pathname;
}
/*
// safe strncpy() wrapper (suggested by joseph.dandrea@att.com) ... strncpy()
// by itself has some ugly problems, and strcpy() is simply dangerous.
// Joseph recommended a macro, but I'm sticking to the bulkier solution of
// using a function
*/
char *StringCopy(char *dest, const char *src, uint size)
{
assert(dest != NULL);
assert(src != NULL);
strncpy(dest, src, size);
dest[size - 1] = NUL;
return dest;
}
/*
// re-entrant string tokenizer ... used because option.c requires simultaneous
// uses of strtok(), and the standard version just dont cut it
*/
char *StringFirstToken(FIND_TOKEN *findToken, char *string, const char *tokens)
{
char *ptr;
assert(string != NULL);
assert(findToken != NULL);
findToken->tokens = tokens;
findToken->lastChar = string + strlen(string);
findToken->nextStart = findToken->lastChar;
if(tokens == NULL)
{
return string;
}
if((ptr = strpbrk(string, tokens)) != NULL)
{
*ptr = NUL;
findToken->nextStart = ptr;
}
return string;
}
char *StringNextToken(FIND_TOKEN *findToken)
{
char *ptr;
char *start;
assert(findToken != NULL);
assert(findToken->lastChar != NULL);
ptr = findToken->nextStart;
/* check if this is the end of the original string */
if(ptr == findToken->lastChar)
{
return NULL;
}
/* nextStart points to NUL left by last search, skip past it */
ptr++;
start = ptr;
/* keep going */
if((ptr = strpbrk(ptr, findToken->tokens)) != NULL)
{
*ptr = NUL;
findToken->nextStart = ptr;
}
else
{
findToken->nextStart = findToken->lastChar;
}
return start;
}
/*
// Wrapper function to (a) allocate memory for the duplicated string and
// (b) copy the source string into the new memory location. Caller is
// responsible to free the string eventually.
*/
char *DuplicateString(const char *src)
{
char *new;
uint size;
assert(src != NULL);
size = strlen(src) + 1;
/* allocate memory for the duplicate string */
if((new = AllocMemory(size)) == NULL)
{
return NULL;
}
/* copy the string */
return memcpy(new, src, size);
}
/*
// returns the full, qualified pathname of the default htp include file
//
// Returns FALSE if unable to find the file.
*/
BOOL HtpDefaultFilename(char *filename, uint size)
{
char *defFile;
/* get the name of the default file from the HTPDEF environement */
/* variable */
if((defFile = getenv("HTPDEF")) == NULL)
{
return FALSE;
}
/* verify that the file exists */
if(FileExists(defFile) == FALSE)
{
return FALSE;
}
/* copy the filename into the buffer and skeedaddle */
StringCopy(filename, defFile, size);
return TRUE;
}
/*
// compare files modified time/date stamp, as a dependency check ... returns
// TRUE if the dependency does not require an update, FALSE otherwise (which
// could either be a timestamp discrepency, or simply that the resulting file
// does not exist) ... if dependency checking is turned off, this function
// will always return FALSE.
//
// Returns ERROR if dependency file does not exist.
*/
BOOL IsTargetUpdated(const char *dependency, const char *target)
{
struct stat dependStat;
struct stat targetStat;
char *dependName;
char *targetName;
assert(dependency != NULL);
assert(target != NULL);
/* always update targets? */
if(DEPEND == FALSE)
{
return FALSE;
}
/* convert the dependency and target filenames for this filesystem */
if((dependName = ConvertDirDelimiter(dependency)) == NULL)
{
return ERROR;
}
if((targetName = ConvertDirDelimiter(target)) == NULL)
{
FreeMemory(dependName);
return ERROR;
}
/* get information on the dependency file */
if(stat(dependName, &dependStat) != 0)
{
/* dependency file needs to exist */
FreeMemory(dependName);
FreeMemory(targetName);
return ERROR;
}
/* get information on the target file */
if(stat(targetName, &targetStat) != 0)
{
/* target file does not exist, dependency needs to be updated */
FreeMemory(dependName);
FreeMemory(targetName);
return FALSE;
}
FreeMemory(dependName);
FreeMemory(targetName);
/* compare modification times to determine if up-to-date */
return (dependStat.st_mtime <= targetStat.st_mtime) ? TRUE : FALSE;
}
/*
// converts directory delimiters for any pathname into one supporting the
// delimiters used by the present filesystem ... it is encumbent on the
// caller to free() the string returned once finished
*/
char *ConvertDirDelimiter(const char *pathname)
{
char *newPathname;
char *strptr;
if(pathname == NULL)
{
return NULL;
}
/* duplicate the pathname for conversion */
if((newPathname = DuplicateString(pathname)) == NULL)
{
return NULL;
}
/* walk the string, looking for delimiters belonging to other filesystems */
/* replace with native filesystems delimiter */
strptr = newPathname;
while(*strptr != NUL)
{
if(strchr(OTHER_FILESYSTEM_DELIMITER, *strptr) != NULL)
{
*strptr = DIR_DELIMITER;
}
strptr++;
}
return newPathname;
}
/*
// uses stat() to check for file existance ... maybe not the best way?
*/
BOOL FileExists(const char *pathname)
{
struct stat dummy;
return (stat(pathname, &dummy) == 0) ? TRUE : FALSE;
}
/*
// searches for the specified file in the search path ... this function is
// very stupid, it simply gets the first directory in the search string,
// appends the file directly to the end, and tests for existance. Repeat.
*/
BOOL SearchForFile(const char *filename, char *fullPathname, uint size)
{
char *searchPathCopy;
char *ptr;
char *convertedName;
FIND_TOKEN findToken;
/* quick check for search path even being defined */
if(searchPath[0] == NUL)
{
return FALSE;
}
/* need to make a copy of the search path for String...Token() to butcher up */
if((searchPathCopy = DuplicateString(searchPath)) == NULL)
{
printf("%s: unable to allocate temporary buffer for include path (out of memory?)\n",
PROGRAM_NAME);
return FALSE;
}
/* look for ';' delimiter */
ptr = StringFirstToken(&findToken, searchPathCopy, ";");
while(ptr != NULL)
{
StringCopy(fullPathname, ptr, size);
/* if the last character is not a directory delimiter, add it */
if(strchr(ALL_FILESYSTEM_DELIMITERS, fullPathname[strlen(fullPathname) - 1]) == NULL)
{
strncat(fullPathname, DIR_DELIMITER_STRING, size);
}
/* append the file name */
strncat(fullPathname, filename, size);
/* need to do a complete conversion of delimiters in the filename, but */
/* ConvertDirDelimiter() returns a AllocMemory()'d copy of the string ... */
convertedName = ConvertDirDelimiter(fullPathname);
/* check for existance */
if(FileExists(convertedName) == TRUE)
{
/* clean up and get outta here */
StringCopy(fullPathname, convertedName, size);
FreeMemory(searchPathCopy);
FreeMemory(convertedName);
return TRUE;
}
FreeMemory(convertedName);
convertedName = NULL;
ptr = StringNextToken(&findToken);
}
/* clean up */
FreeMemory(searchPathCopy);
return FALSE;
}
/*
// HTML file stream functions
*/
/*
// returns the markup type flag ... either the closing or opening delimiter
// in the markup can be passed in
*/
uint MarkupType(char delim)
{
uint markupType;
markupType = 0;
if((delim == HTML_OPEN_MARKUP) || (delim == HTML_CLOSE_MARKUP))
{
markupType |= MARKUP_TYPE_HTML;
}
if((delim == htpOpenMarkup) || (delim == htpCloseMarkup))
{
markupType |= MARKUP_TYPE_HTP;
}
return markupType;
}
/*
// TRUE = plaintext is filled with new plain text markup, FALSE if end of file,
// ERROR if a problem
// !! Don't like using ERROR in any BOOL return values
*/
BOOL ReadHtmlFile(TEXTFILE *infile, TEXTFILE *outfile, char **plaintext,
uint *markupType)
{
char ch;
uint ctr;
char *buffer;
char *newbuffer;
uint size;
uint bytesReadPrevLine;
BOOL inQuotes;
uint startLine;
assert(infile != NULL);
assert(plaintext != NULL);
/* if outfile is NULL, then the input stream is just being walked and */
/* not parsed for output ... i.e., don't assert outfile != NULL */
/* allocate some space for markup plaintext ... this will dynamically */
/* expand if necessary, and has to be freed by the caller */
if((buffer = AllocMemory(MIN_PLAINTEXT_SIZE)) == NULL)
{
HtpMsg(MSG_ERROR, NULL, "unable to allocate memory to read HTML file");
return ERROR;
}
/* track the buffer size */
size = MIN_PLAINTEXT_SIZE;
for(;;)
{
/* GetFileChar() will reset bytesReadThisLine if a EOL char is read */
/* so save it for later evaluation ... (bytesReadPrevLine is named */
/* to indicate it is only evaluated if a EOL char is read) */
bytesReadPrevLine = infile->bytesReadThisLine;
if(GetFileChar(infile, &ch) == FALSE)
{
break;
}
if(IS_OPEN_MARKUP(ch) == FALSE)
{
/* normal text, just copy it to the output file (if there is one) */
if(outfile != NULL)
{
/* this is used to catch spurious EOLs sneaking into the final output */
/* essentially, if bytes were read but none were written, it */
/* is assumed that the only text on the line were htp directives */
/* and therefore it is unnecessary (and ugly) to write out the */
/* EOL at the end of the line */
if(ch == '\n')
{
if((bytesReadPrevLine > 0) && (outfile->bytesWrittenThisLine == 0))
{
continue;
}
}
PutFileChar(outfile, ch);
}
}
else
{
/* get the type of markup for caller */
*markupType = MarkupType(ch);
/* copy the markup into the buffer */
ctr = 0;
inQuotes = FALSE;
startLine = infile->lineNumber;
for(;;)
{
if(GetFileChar(infile, &ch) == FALSE)
{
/* EOF ... this is not acceptable before the markup is */
/* terminated */
FreeMemory(buffer);
HtpMsg(MSG_ERROR, infile, "EOF encountered inside markup tag (started on line %u)",
startLine);
return ERROR;
}
if((IS_CLOSE_MARKUP(ch))
&& (inQuotes == FALSE)
&& (MarkupType(ch) == *markupType))
{
/* end of markup, terminate string and exit */
buffer[ctr] = NUL;
break;
}
/* track quotation marks ... can only close markup when */
/* all quotes have been closed */
if(ch == '\"')
{
inQuotes = (inQuotes == TRUE) ? FALSE : TRUE;
}
/* copy it into the plaintext buffer */
buffer[ctr++] = ch;
/* check for overflow ... resize buffer if necessary */
if(ctr == size)
{
newbuffer = ResizeMemory(buffer, size + PLAINTEXT_GROW_SIZE);
if(newbuffer == NULL)
{
/* unable to enlarge buffer area */
HtpMsg(MSG_ERROR, NULL, "unable to reallocate memory for reading HTML file");
FreeMemory(buffer);
return ERROR;
}
buffer = newbuffer;
size += PLAINTEXT_GROW_SIZE;
}
}
/* give the buffer pointer to the caller */
*plaintext = buffer;
return TRUE;
}
}
/* no markup found, end of file */
FreeMemory(buffer);
return FALSE;
}
/*
// specialized markup processors
*/
uint ImageProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
const char *imgfilename;
char str[32];
IMAGEFILE imageFile;
WORD width, height;
char *imgSource;
const char *originalSource;
char *imgFilename;
const char *imgText;
UNREF_PARAM(newPlaintext);
/* try to find ALT text in store */
/* first: is there already ALT attribute? if so, skip this step */
if(IsAttributeInMarkup(htmlMarkup, "ALT") == FALSE)
{
/* parse down the image source to just the filename */
originalSource = MarkupAttributeValue(htmlMarkup, "SRC");
if(originalSource == NULL)
{
HtpMsg(MSG_WARNING, task->infile, "image SRC not specified, skipping");
return MARKUP_OKAY;
}
imgSource = DuplicateString(originalSource);
if(imgSource == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "out of memory processing IMG tag");
return MARKUP_ERROR;
}
/* parse the image name, just find the filename */
imgFilename = FindFilename(imgSource);
/* is the image in the ALT text store? */
if(VariableExists(&altTextVarStore, imgFilename) == TRUE)
{
/* add the specified text to the image */
imgText = GetVariableValue(&altTextVarStore, imgFilename);
assert(imgText != NULL);
AddAttributeToMarkup(htmlMarkup, "ALT", imgText, TRUE);
HtpMsg(MSG_INFO, task->infile, "ALT text \"%s\" added to IMG \"%s\"",
imgText, imgSource);
}
FreeMemory(imgSource);
imgSource = NULL;
}
/* if option is turned off, then just include the markup as-is */
if(IMGXY == FALSE)
{
return MARKUP_OKAY;
}
/* if width and/or height are already specified, then include the */
/* markup as-is with no modifications */
if(IsAttributeInMarkup(htmlMarkup, "HEIGHT")
|| IsAttributeInMarkup(htmlMarkup, "WIDTH"))
{
return MARKUP_OKAY;
}
/* get the filename of the image */
if((imgfilename = MarkupAttributeValue(htmlMarkup, "SRC")) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to retrieve image source name");
return MARKUP_ERROR;
}
/* open the image file, get its dimensions, and close the file */
if(OpenImageFile(imgfilename, &imageFile) == FALSE)
{
HtpMsg(MSG_WARNING, task->infile, "unable to open image file \"%s\"",
imgfilename);
return MARKUP_OKAY;
}
if(GetImageDimensions(&imageFile, &width, &height) == FALSE)
{
HtpMsg(MSG_WARNING, task->infile, "unable to determine image file \"%s\" dimensions",
imgfilename);
CloseImageFile(&imageFile);
return MARKUP_OKAY;
}
CloseImageFile(&imageFile);
/* add the width and height specifier for the image */
sprintf(str, "%u", width);
AddAttributeToMarkup(htmlMarkup, "WIDTH", str, TRUE);
sprintf(str, "%u", height);
AddAttributeToMarkup(htmlMarkup, "HEIGHT", str, TRUE);
/* print out an informational message to the user */
HtpMsg(MSG_INFO, task->outfile, "image file \"%s\" dimensions (%u x %u) added",
imgfilename, width, height);
/* include the markup in the final output */
return MARKUP_OKAY;
}
BOOL OptionCallback(const char *name, const char *value, ulong userParam)
{
TASK *task;
BOOL printMsg;
task = (TASK *) userParam;
printMsg = (task == NULL) ? FALSE : TRUE;
if(name == NULL)
{
/* dont like it, but dont stop processing either */
HtpMsg(MSG_WARNING, task->infile, "unknown option \"%s\" specified", value);
return TRUE;
}
if(stricmp(name, OPT_N_QUIET) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
SetMessageSeverityLevel(MSG_WARNING);
}
else
{
SetMessageSeverityLevel(MSG_INFO);
}
}
if(stricmp(name, OPT_N_IMGXY) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "image pre-processing turned ON");
}
}
else
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "image pre-processing turned OFF");
}
}
}
if(stricmp(name, OPT_N_DEPEND) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "dependency checking turned ON");
}
}
else
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "dependency checking turned OFF");
}
}
}
if(stricmp(name, OPT_N_PRECIOUS) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "precious output turned ON");
}
}
else
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "precious output turned OFF");
}
}
}
if(stricmp(name, OPT_N_CONDENSE) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "output will be condensed");
}
if(task != NULL)
{
SuppressLinefeeds(task->outfile);
}
}
else
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "output will not be condensed");
}
if(task != NULL)
{
AllowLinefeeds(task->outfile);
}
}
}
if(stricmp(name, OPT_N_KEEP_TEMP) == 0)
{
if(stricmp(value, OPT_V_TRUE) == 0)
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "DEBUG: keeping temporary files");
}
}
else
{
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "DEBUG: not keeping temporary files");
}
}
}
if(stricmp(name, OPT_N_SET_DELIM) == 0)
{
if(stricmp(value, OPT_V_DELIM_HTML) == 0)
{
htpOpenMarkup = '<';
htpCloseMarkup = '>';
}
else if(stricmp(value, OPT_V_DELIM_SQUARE) == 0)
{
htpOpenMarkup = '[';
htpCloseMarkup = ']';
}
else if(stricmp(value, OPT_V_DELIM_CURLY) == 0)
{
htpOpenMarkup = '{';
htpCloseMarkup = '}';
}
if(printMsg)
{
HtpMsg(MSG_INFO, task->infile, "markup delimiter set to \"%s\"",
value);
}
}
return TRUE;
}
uint OptionProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
UNREF_PARAM(newPlaintext);
if(ParseMarkupOption(htmlMarkup, OptionCallback, (ulong) task) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "error parsing markup options (out of memory?)");
return MARKUP_ERROR;
}
return DISCARD_MARKUP;
}
uint ExternalFileProcessor(TASK *task, HTML_MARKUP *htmlMarkup,
const char *externalName, char **newPlaintext)
{
struct stat fileStat;
struct tm *fileTime;
uint precision;
const char *attribValue;
const char *precisionString;
const char *value;
assert(externalName != NULL);
assert(htmlMarkup != NULL);
/* get information on the file itself */
if(stat(externalName, &fileStat) != 0)
{
HtpMsg(MSG_ERROR, task->infile, "unable to retrieve file information on \"%s\"",
externalName);
return MARKUP_ERROR;
}
/* get the precision attribute value, if present */
/* (this is only valid for SIZE attribute, but not checking for simplicity */
/* ignored for other types of FILE attributes) */
precision = DEFAULT_PRECISION;
if(IsAttributeInMarkup(htmlMarkup, "PRECISION"))
{
precisionString = MarkupAttributeValue(htmlMarkup, "PRECISION");
if(precisionString != NULL)
{
precision = atoi(precisionString);
}
else
{
HtpMsg(MSG_WARNING, task->infile, "precision attribute needs a value");
}
}
/* allocate room for the replacment plaintext */
if((*newPlaintext = AllocMemory(MAX_TIME_DATE_SIZE)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to allocate memory for expansion");
return MARKUP_ERROR;
}
/* create new plaintext depending on what extra information is specified */
/* !! this is technically not correct ... SIZE, TIME, and DATE are */
/* not allowed in the same markup but not checking that only one is */
/* present and not any others */
if(IsAttributeInMarkup(htmlMarkup, "SIZE"))
{
attribValue = MarkupAttributeValue(htmlMarkup, "SIZE");
/* expand markup depending on how SIZE should be represented */
if((attribValue == NULL) || (stricmp(attribValue, "BYTE") == 0))
{
/* byte representation is default */
sprintf(*newPlaintext, "%lu", fileStat.st_size);
}
else if(stricmp(attribValue, "KBYTE") == 0)
{
sprintf(*newPlaintext, "%.*f", (int) precision,
(double) ((double) fileStat.st_size / (double) KBYTE));
}
else if(stricmp(attribValue, "MBYTE") == 0)
{
sprintf(*newPlaintext, "%.*f", (int) precision,
(double) ((double) fileStat.st_size / (double) MBYTE));
}
else if(stricmp(attribValue, "GBYTE") == 0)
{
sprintf(*newPlaintext, "%.*f", (int) precision,
(double) ((double) fileStat.st_size / (double) GBYTE));
}
else
{
/* free the plaintext memory before returning */
HtpMsg(MSG_ERROR, task->infile, "unknown SIZE specifier");
FreeMemory(*newPlaintext);
*newPlaintext = NULL;
return MARKUP_ERROR;
}
}
else if(IsAttributeInMarkup(htmlMarkup, "TIME"))
{
const char *value;
/* convert into an ANSI time structure */
fileTime = localtime(&fileStat.st_mtime);
/* see if the attribute has a value ... if so, let it be the */
/* strftime() formatter */
if((value = MarkupAttributeValue(htmlMarkup, "TIME")) != NULL)
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, value, fileTime);
}
else
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, "%I:%M:%S %p", fileTime);
}
}
else if(IsAttributeInMarkup(htmlMarkup, "DATE"))
{
/* convert into an ANSI time structure */
fileTime = localtime(&fileStat.st_mtime);
/* see if the attribute has a value ... if so, let it be the */
/* strftime() formatter */
if((value = MarkupAttributeValue(htmlMarkup, "DATE")) != NULL)
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, value, fileTime);
}
else
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, "%a %b %d, %Y", fileTime);
}
}
else
{
/* free the plaintext, unused */
FreeMemory(*newPlaintext);
*newPlaintext = NULL;
HtpMsg(MSG_ERROR, task->infile, "bad file information specifier");
return MARKUP_ERROR;
}
/* the new plaintext was created successfully */
return NEW_MARKUP;
}
uint FileExecuteProcessor(TASK *task, HTML_MARKUP *htmlMarkup)
{
const char *cmdline;
const char *output;
char newCmdline[MAX_CMDLINE_LEN];
char tempFilename[MAX_PATHNAME_LEN];
BOOL redirect;
TEXTFILE infile;
TASK newTask;
BOOL result;
uint exitCode;
assert(task != NULL);
assert(htmlMarkup != NULL);
if((cmdline = MarkupAttributeValue(htmlMarkup, "EXECUTE")) == NULL)
{
HtpMsg(MSG_ERROR, task->infile,"FILE EXECUTE must specify a command-line");
return MARKUP_ERROR;
}
output = MarkupAttributeValue(htmlMarkup, "OUTPUT");
redirect = IsAttributeInMarkup(htmlMarkup, "REDIRECT");
/* either output or redirect, but not both, must be specified */
if((output == NULL) && (redirect == FALSE))
{
HtpMsg(MSG_ERROR, task->infile, "Either REDIRECT or OUTPUT must be specified for FILE EXECUTE");
return MARKUP_ERROR;
}
if((output != NULL) && (redirect == TRUE))
{
HtpMsg(MSG_ERROR, task->infile, "REDIRECT and OUTPUT cannot both be specified for FILE EXECUTE");
return MARKUP_ERROR;
}
StringCopy(newCmdline, cmdline, MAX_CMDLINE_LEN);
/* if redirection required, append to the command-line a redirector to */
/* a temporary file */
if(redirect)
{
if(CreateTempFilename(tempFilename, MAX_PATHNAME_LEN) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to create a temporary file for redirection");
return MARKUP_ERROR;
}
strncat(newCmdline, " > ", MAX_PATHNAME_LEN);
strncat(newCmdline, tempFilename, MAX_PATHNAME_LEN);
}
else
{
/* the specified output file is the "temporary" filename */
StringCopy(tempFilename, output, MAX_PATHNAME_LEN);
}
HtpMsg(MSG_INFO, task->infile, "Executing command \"%s\" ...", newCmdline);
/* execute the command */
exitCode = system(newCmdline);
if(exitCode != 0)
{
if(IsAttributeInMarkup(htmlMarkup, "NOERROR") == FALSE)
{
/* the program has exited with an error condition */
HtpMsg(MSG_ERROR, task->infile, "Command \"%s\" exited with an error code of %u",
newCmdline, exitCode);
/* remove the temporary file, in case it was partially created */
remove(tempFilename);
return MARKUP_ERROR;
}
}
/* include the output file like it was anything else */
/* first, open it */
if(OpenFile(tempFilename, tempFilename, "r", &infile) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to open execute result file");
return MARKUP_ERROR;
}
/* build a new task */
newTask.infile = &infile;
newTask.outfile = task->outfile;
newTask.varstore = task->varstore;
newTask.sourceFilename = task->sourceFilename;
/* process the file */
result = ProcessTask(&newTask);
/* close and destroy the output file */
CloseFile(&infile);
remove(tempFilename);
return (result == TRUE) ? DISCARD_MARKUP : MARKUP_ERROR;
}
uint FileTemplateProcessor(TASK *task, HTML_MARKUP *htmlMarkup)
{
const char *templateFile;
assert(task != NULL);
assert(htmlMarkup != NULL);
if((templateFile = MarkupAttributeValue(htmlMarkup, "TEMPLATE")) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "a template file must be specified");
return MARKUP_ERROR;
}
/* the template file is not actually processed now, but rather when the */
/* rest of the file is completed ... to postpone processing, the template */
/* name is kept in the variable store under a special name and retrieved */
/* later */
if(StoreVariable(task->varstore, VAR_TEMPLATE_NAME, templateFile,
VAR_TYPE_INTERNAL, 0, NULL, NULL) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"unable to store template filename for post-processing (out of memory?)");
return MARKUP_ERROR;
}
return DISCARD_MARKUP;
}
uint FileIncludeProcessor(TASK *task, HTML_MARKUP *htmlMarkup)
{
TEXTFILE incfile;
BOOL result;
TASK newTask;
char fullPathname[MAX_PATHNAME_LEN];
const char *attribValue;
VARSTORE varstore;
VARSTORE *topVarstore;
uint ctr;
uint flag;
/* get the filename to include */
attribValue = MarkupAttributeValue(htmlMarkup, "INCLUDE");
if(attribValue == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "include filename not specified");
return MARKUP_ERROR;
}
/* open the include file as input */
if(OpenFile(attribValue, attribValue, "r", &incfile) == FALSE)
{
/* use the search path to find the file */
if(SearchForFile(attribValue, fullPathname, MAX_PATHNAME_LEN) == FALSE)
{
/* could not find the file in the search path either */
HtpMsg(MSG_ERROR, task->infile, "unable to open include file \"%s\"",
attribValue);
return MARKUP_ERROR;
}
if(OpenFile(fullPathname, fullPathname, "r", &incfile) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to open include file \"%s\"",
fullPathname);
return MARKUP_ERROR;
}
}
else
{
StringCopy(fullPathname, attribValue, MAX_PATHNAME_LEN);
}
/* if additional parameters exist in the tag, build a local varstore */
/* and push it onto the context */
if(htmlMarkup->attribCount > 1)
{
if(InitializeVariableStore(&varstore) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to initialize context for include file");
CloseFile(&incfile);
return MARKUP_ERROR;
}
/* start including the parameters as local macros */
for(ctr = 1; ctr < htmlMarkup->attribCount; ctr++)
{
flag = (htmlMarkup->attrib[ctr].quoted == TRUE) ? VAR_FLAG_QUOTED
: VAR_FLAG_NONE;
if(StoreVariable(&varstore, htmlMarkup->attrib[ctr].name,
htmlMarkup->attrib[ctr].value, VAR_TYPE_SET_MACRO,
flag, NULL, NULL) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to add variable to context for include file");
CloseFile(&incfile);
DestroyVariableStore(&varstore);
return MARKUP_ERROR;
}
}
/* push this onto the context and use it for the include file */
PushVariableStoreContext(task->varstore, &varstore);
topVarstore = &varstore;
}
else
{
topVarstore = task->varstore;
}
/* build a new task structure */
newTask.infile = &incfile;
newTask.outfile = task->outfile;
newTask.varstore = topVarstore;
newTask.sourceFilename = task->sourceFilename;
/* informational message for the user */
HtpMsg(MSG_INFO, task->infile, "including file \"%s\"", fullPathname);
/* process the new input file */
result = ProcessTask(&newTask);
/* pop the local context */
if(topVarstore == &varstore)
{
assert(PeekVariableStoreContext(topVarstore) == topVarstore);
PopVariableStoreContext(topVarstore);
DestroyVariableStore(&varstore);
}
CloseFile(&incfile);
/* if the new file did not process, return an error, otherwise discard */
/* the markup */
return (result == TRUE) ? DISCARD_MARKUP : MARKUP_ERROR;
}
uint FileProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
const char *attribName;
const char *attribValue;
const char *externalName;
struct tm *timeNow;
struct stat fileStat;
/* if a NAME attribute is found, and it contains a value, use the */
/* ExternalFileProcessor to create the plaintext (this function only */
/* reports output file's time, date, name) */
if(IsAttributeInMarkup(htmlMarkup, "NAME"))
{
if((externalName = MarkupAttributeValue(htmlMarkup, "NAME")) != NULL)
{
return ExternalFileProcessor(task, htmlMarkup, externalName,
newPlaintext);
}
}
/* if NAME attribute not in markup, or no external filename specified, */
/* only one attribute can be used: NAME, SIZE, TIME, DATE , or INCLUDE */
/* (the exception being EXECUTE and TEMPLATE) */
if(IsAttributeInMarkup(htmlMarkup, "EXECUTE") == TRUE)
{
return FileExecuteProcessor(task, htmlMarkup);
}
if(IsAttributeInMarkup(htmlMarkup, "TEMPLATE") == TRUE)
{
return FileTemplateProcessor(task, htmlMarkup);
}
if(IsAttributeInMarkup(htmlMarkup, "INCLUDE") == TRUE)
{
return FileIncludeProcessor(task, htmlMarkup);
}
if(htmlMarkup->attribCount != 1)
{
HtpMsg(MSG_ERROR, task->infile, "improper FILE syntax");
return MARKUP_ERROR;
}
/* get the attribute */
attribName = htmlMarkup->attrib[0].name;
attribValue = htmlMarkup->attrib[0].value;
/* act on the attribute */
if(stricmp(attribName, "SEARCH") == 0)
{
/* set the include search path to what was specified */
if(attribValue != NULL)
{
StringCopy(searchPath, attribValue, SEARCH_PATH_SIZE);
}
else
{
/* search path is cleared */
searchPath[0] = NUL;
}
return DISCARD_MARKUP;
}
else
{
/* NAME, TIME, DATE or bad tag */
/* first, allocate some space for the (possibly) new markup */
if((*newPlaintext = AllocMemory(MAX_TIME_DATE_SIZE)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to allocate memory for expansion");
return MARKUP_ERROR;
}
/* get the input files time, in case the attribute is TIME or DATE */
if(stat(task->sourceFilename, &fileStat) != 0)
{
HtpMsg(MSG_ERROR, task->infile, "unable to get information for file \"%s\"\n",
task->infile->filename);
return MARKUP_ERROR;
}
timeNow = localtime(&fileStat.st_mtime);
if(stricmp(attribName, "TIME") == 0)
{
if(attribValue != NULL)
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, attribValue, timeNow);
}
else
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, "%I:%M:%S %p", timeNow);
}
HtpMsg(MSG_INFO, task->outfile, "adding local time");
}
else if(stricmp(attribName, "DATE") == 0)
{
if(attribValue != NULL)
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, attribValue, timeNow);
}
else
{
strftime(*newPlaintext, MAX_TIME_DATE_SIZE, "%a %b %d, %Y", timeNow);
}
HtpMsg(MSG_INFO, task->outfile, "adding local date");
}
else if(stricmp(attribName, "NAME") == 0)
{
StringCopy(*newPlaintext, task->outfile->name, MAX_TIME_DATE_SIZE);
HtpMsg(MSG_INFO, task->outfile, "adding output filename");
}
else
{
/* no appropriate tags found */
HtpMsg(MSG_ERROR, task->infile, "invalid FILE tag attribute \"%s\"",
attribName);
/* free the allocated plaintext buffer */
FreeMemory(*newPlaintext);
*newPlaintext = NULL;
return MARKUP_ERROR;
}
}
/* the new plaintext has been created */
return NEW_MARKUP;
}
uint SetProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
char *name;
char *value;
uint ctr;
uint flag;
HTML_ATTRIBUTE *attrib;
UNREF_PARAM(newPlaintext);
/* have to declare at least one macro, but more are acceptable */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "incomplete macro declaration");
return MARKUP_ERROR;
}
attrib = &htmlMarkup->attrib[0];
/* walk the list and add each macro to the variable store */
for(ctr = 0; ctr < htmlMarkup->attribCount; ctr++)
{
/* get a private copy of the macro name */
if((name = DuplicateString(attrib->name)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to store macro's value (out of memory?)");
return MARKUP_ERROR;
}
value = attrib->value;
flag = (attrib->quoted) ? VAR_FLAG_QUOTED : VAR_FLAG_NONE;
/* put the new variable into the store */
if(StoreVariable(task->varstore, name, value, VAR_TYPE_SET_MACRO, flag,
NULL, NULL) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to store macro \"%s\" (out of memory?)",
name);
FreeMemory(name);
return MARKUP_ERROR;
}
if(value != NULL)
{
HtpMsg(MSG_INFO, task->infile, "macro \"%s\" assigned value \"%s\"",
name, value);
}
else
{
HtpMsg(MSG_INFO, task->infile, "macro \"%s\" created with null value",
name);
}
FreeMemory(name);
attrib++;
}
return DISCARD_MARKUP;
}
uint UnsetProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
uint ctr;
uint type;
const char *name;
UNREF_PARAM(newPlaintext);
/* have to specify at least one macro to remove, but more are acceptable */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "UNSET tag improperly specified");
}
/* walk the attributes list */
for(ctr = 0; ctr < htmlMarkup->attribCount; ctr++)
{
name = htmlMarkup->attrib[ctr].name;
/* verify that the variable exists */
if(VariableExists(task->varstore, name) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "bad macro name \"%s\"", name);
return MARKUP_ERROR;
}
/* remove it from the variable store if its not a DEF macro */
type = GetVariableType(task->varstore, name);
if((type == VAR_TYPE_SET_MACRO) || (type == VAR_TYPE_BLOCK_MACRO))
{
RemoveVariable(task->varstore, name);
}
HtpMsg(MSG_INFO, task->infile, "variable \"%s\" removed", name);
}
return DISCARD_MARKUP;
}
uint UseProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
char *name;
const char *value;
TEXTFILE incfile;
int result;
uint type;
VARSTORE varstore;
VARSTORE *topVarstore;
uint ctr;
uint flag;
/* must declare at least 1 attribute, the macro name */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "macro declaration not complete");
return MARKUP_ERROR;
}
/* a variable reference should NOT include a new declaration */
if(htmlMarkup->attrib[0].value != NULL)
{
HtpMsg(MSG_ERROR, task->infile, "improper USE syntax");
return MARKUP_ERROR;
}
/* get a private copy of the name variable, this function will modify */
/* its own copy */
if((name = DuplicateString(htmlMarkup->attrib[0].name)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to expand macro (out of memory?)");
return MARKUP_ERROR;
}
/* verify the macro exists */
if(VariableExists(task->varstore, name) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "macro %s has not been declared", name);
FreeMemory(name);
return MARKUP_ERROR;
}
/* get the value of the macro */
value = GetVariableValue(task->varstore, name);
/* get the type of macro */
type = GetVariableType(task->varstore, name);
if(type == VAR_TYPE_INTERNAL)
{
/* oof ... the user picked a variable name we use internally */
/* !! a fix is to use both type and name as a key to get variable */
/* out of hash, and therefore the name is not the only identifier */
/* this will have to wait for later */
HtpMsg(MSG_ERROR, task->infile,
"reserved variable name \"%s\" used ... please use different name in HTP file",
name);
FreeMemory(name);
return MARKUP_ERROR;
}
if(type == VAR_TYPE_DEF_MACRO)
{
/* nope */
HtpMsg(MSG_ERROR, task->infile,
"illegal to dereference a DEF macro with USE");
FreeMemory(name);
return MARKUP_ERROR;
}
assert((type == VAR_TYPE_SET_MACRO) || (type == VAR_TYPE_BLOCK_MACRO));
/* if more than one parameter is on the USE tag, then assume they are */
/* local variables for the macro */
if(htmlMarkup->attribCount > 1)
{
if(type == VAR_TYPE_SET_MACRO)
{
/* nope, not yet */
HtpMsg(MSG_ERROR, task->infile, "macro parameters can only be used for BLOCK macros");
FreeMemory(name);
return MARKUP_ERROR;
}
/* create a local variable store */
if(InitializeVariableStore(&varstore) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to initialize local context for macro");
FreeMemory(name);
return MARKUP_ERROR;
}
/* add each additional parameter to the local varstore */
for(ctr = 1; ctr < htmlMarkup->attribCount; ctr++)
{
flag = (htmlMarkup->attrib[ctr].quoted == TRUE) ? VAR_FLAG_QUOTED
: VAR_FLAG_NONE;
if(StoreVariable(&varstore, htmlMarkup->attrib[ctr].name,
htmlMarkup->attrib[ctr].value, VAR_TYPE_SET_MACRO, flag,
NULL, NULL) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to add variable to block's local context");
DestroyVariableStore(&varstore);
FreeMemory(name);
return MARKUP_ERROR;
}
}
/* make this variable store the topmost context */
PushVariableStoreContext(task->varstore, &varstore);
topVarstore = &varstore;
}
else
{
topVarstore = task->varstore;
}
if(type == VAR_TYPE_SET_MACRO)
{
/* if NULL, then the macro was declared with no value, this is okay, */
/* just don't do anything */
if(value == NULL)
{
FreeMemory(name);
return DISCARD_MARKUP;
}
/* allocate the new plaintext buffer and copy in the macro value */
if((*newPlaintext = DuplicateString(value)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to allocate memory for macro expansion");
FreeMemory(name);
return MARKUP_ERROR;
}
HtpMsg(MSG_INFO, task->infile, "macro \"%s\" dereferenced", name);
FreeMemory(name);
return NEW_MARKUP;
}
else if(type == VAR_TYPE_BLOCK_MACRO)
{
/* !! magic number */
char blockName[128];
TASK newTask;
/* if NULL, big-time error */
if(value == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "block macro \"%s\" incorrectly stored, fatal internal error",
name);
if(topVarstore == &varstore)
{
assert(PeekVariableStoreContext(topVarstore) == topVarstore);
PopVariableStoreContext(topVarstore);
DestroyVariableStore(&varstore);
}
FreeMemory(name);
exit(1);
}
/* build the block macro name (printed in place of the temporary */
/* filename in all messages regarding it) */
sprintf(blockName, "Block macro \"%s\"", name);
/* block macro value is the name of a temporary file containing */
/* macro contents */
if(OpenFile(blockName, value, "r", &incfile) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"unable to open temporary file \"%s\" for block macro \"%s\"",
value, name);
FreeMemory(name);
return MARKUP_ERROR;
}
HtpMsg(MSG_INFO, task->infile, "dereferencing block macro \"%s\"", name);
/* build a new task structure */
newTask.infile = &incfile;
newTask.outfile = task->outfile;
newTask.sourceFilename = task->sourceFilename;
/* re-use current variable store if no local variable store was */
/* allocated, otherwise use the new one */
newTask.varstore = topVarstore;
/* process the new input file */
result = ProcessTask(&newTask);
/* remove the new context (and make sure it is, in fact, the block's */
/* context) */
if(topVarstore == &varstore)
{
assert(PeekVariableStoreContext(topVarstore) == topVarstore);
PopVariableStoreContext(topVarstore);
DestroyVariableStore(&varstore);
}
CloseFile(&incfile);
FreeMemory(name);
/* if the new file did not process, return an error, otherwise discard */
/* the markup */
return (result == TRUE) ? DISCARD_MARKUP : MARKUP_ERROR;
}
else
{
/* fatal error */
printf("%s: fatal internal error (USE)\n", PROGRAM_NAME);
FreeMemory(name);
exit(1);
/* to prevent compiler warning */
return MARKUP_ERROR;
}
}
/*
// Block macro destructor callback ... used whenever a block macro is
// destroyed with a RemoveVariable() or ClearVariableList()
*/
void BlockDestructor(const char *name, const char *value, uint type, uint flags,
void *param)
{
UNREF_PARAM(name);
UNREF_PARAM(type);
UNREF_PARAM(flags);
/* in debug versions of htp, a special "secret" option can be set to */
/* keep BLOCK temporary files around, for later inspection ... */
/* not real useful in release versions */
#if DEBUG
if(KEEPTEMP == FALSE)
{
remove(value);
}
else
{
HtpMsg(MSG_INFO, NULL, "DEBUG: keeping temporary file %s", value);
}
#else
/* simply delete the temporary file holding the block macro text */
DEBUG_PRINT(("deleting file %s for block macro %s\n", value, name));
remove(value);
#endif
/* DEF macros use param */
if(param != NULL)
{
FreeMemory(param);
}
}
uint BlockProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
char *name;
char *plaintext;
char newfile[MAX_PATHNAME_LEN];
HTML_MARKUP newHtml;
TEXTFILE blockFile;
BOOL result;
static uint blockDepth = 0;
uint markupType;
BOOL blockMacro;
uint macroType;
const char *macroTypeName;
const char *openTag;
const char *closeTag;
const char *defName;
char *param;
UNREF_PARAM(newPlaintext);
/* first: is this a BLOCK macro or a DEF macro? This function is */
/* overloaded to handle both types, and must internally change its */
/* functionality for each type */
/* if this is false, this is a DEF macro */
if(stricmp(htmlMarkup->tag, "BLOCK") == 0)
{
blockMacro = TRUE;
macroType = VAR_TYPE_BLOCK_MACRO;
macroTypeName = "BLOCK";
openTag = "BLOCK";
closeTag = "/BLOCK";
}
else
{
assert(stricmp(htmlMarkup->tag, "DEF") == 0);
blockMacro = FALSE;
macroType = VAR_TYPE_DEF_MACRO;
macroTypeName = "DEF";
openTag = "DEF";
closeTag = "/DEF";
}
/* check markup */
if(blockMacro == TRUE)
{
/* is a name specified? (only one name can be specified) */
if(htmlMarkup->attribCount != 1)
{
HtpMsg(MSG_ERROR, task->infile, "bad BLOCK markup specified");
return MARKUP_ERROR;
}
/* no extra varstore parameter for a block macro */
param = NULL;
}
else
{
/* DEF requires at least one parameter */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "bad DEF markup specified");
return MARKUP_ERROR;
}
/* check that the NAME attribute is present */
if(IsAttributeInMarkup(htmlMarkup, "NAME") == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "DEF requires NAME attribute");
return MARKUP_ERROR;
}
if(MarkupAttributeValue(htmlMarkup, "NAME") == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "DEF requires a NAME attribute to have a value");
return MARKUP_ERROR;
}
/* if OPTION is specified, squirrel it away with the macro */
if(IsAttributeInMarkup(htmlMarkup, "OPTION") == TRUE)
{
if((param = DuplicateString(MarkupAttributeValue(htmlMarkup, "OPTION")))
== NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to create OPTION copy for DEF macro");
return MARKUP_ERROR;
}
}
else
{
param = NULL;
}
}
/* create a temporary filename to save the text block into */
if(CreateTempFilename(newfile, MAX_PATHNAME_LEN) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to generate temporary filename for %s macro",
macroTypeName);
FreeMemory(param);
return MARKUP_ERROR;
}
/* try and create the temporary file */
if(OpenFile(newfile, newfile, "w", &blockFile) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"unable to create temporary file \"%s\" for %s macro", newfile,
macroTypeName);
FreeMemory(param);
return MARKUP_ERROR;
}
/* need a private copy of the macro name */
if(blockMacro == TRUE)
{
if((name = DuplicateString(htmlMarkup->attrib[0].name)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to allocate memory for %s macro",
macroTypeName);
FreeMemory(param);
CloseFile(&blockFile);
return MARKUP_ERROR;
}
}
else
{
defName = MarkupAttributeValue(htmlMarkup, "NAME");
assert(defName != NULL);
if((name = DuplicateString(defName)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "unable to allocate memory for %s macro",
macroTypeName);
FreeMemory(param);
CloseFile(&blockFile);
return MARKUP_ERROR;
}
}
/* store the block file name and the block macro name as a variable */
if(StoreVariable(task->varstore, name, newfile, macroType, VAR_FLAG_NONE,
param, BlockDestructor) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to store macro information (out of memory?)");
FreeMemory(name);
FreeMemory(param);
CloseFile(&blockFile);
return MARKUP_ERROR;
}
/* the name is no longer used, dont free param it will be freed in */
/* the block destructor */
FreeMemory(name);
name = NULL;
/* start copying the file into the temporary file, looking for the */
/* BLOCK or /BLOCK tag if block macro, DEF or /DEF otherwise ... */
/* just squirrel away all other tags and text */
for(;;)
{
result = ReadHtmlFile(task->infile, &blockFile, &plaintext, &markupType);
if(result == ERROR)
{
CloseFile(&blockFile);
return MARKUP_ERROR;
}
else if(result == FALSE)
{
/* end-of-file encountered before end-of-block */
HtpMsg(MSG_ERROR, task->infile, "EOF encountered before %s macro declaration closed",
macroTypeName);
CloseFile(&blockFile);
return MARKUP_ERROR;
}
/* turn the plain text into HTML structure, but don't destroy */
/* the plaintext, this will be used to copy into output file if */
/* necessary */
if(PlaintextToMarkup(plaintext, &newHtml) == FALSE)
{
/* memory alloc failed, most likely */
HtpMsg(MSG_ERROR, task->infile, "could not process markup (out of memory?)");
CloseFile(&blockFile);
FreeMemory(plaintext);
return MARKUP_ERROR;
}
if(markupType & MARKUP_TYPE_HTP)
{
/* check for embedded block declarations */
if(IsMarkupTag(&newHtml, openTag))
{
/* add to the block macro depth and continue */
blockDepth++;
}
else if(IsMarkupTag(&newHtml, closeTag) == TRUE)
{
if(blockDepth > 0)
{
/* depth has decreased one */
blockDepth--;
}
else
{
/* found the end of the macro block */
DestroyMarkupStruct(&newHtml);
FreeMemory(plaintext);
break;
}
}
}
/* if continuing, then the plaintext is put into the output stream */
/* as-is ... there is no case where the processor continues scanning */
/* but discards a markup */
PutFileString(&blockFile, "%c%s%c", MARKUP_OPEN_DELIM(markupType),
plaintext, MARKUP_CLOSE_DELIM(markupType));
/* destroy the HTML markup, not needed any longer */
DestroyMarkupStruct(&newHtml);
/* destroy the plaintext buffer */
FreeMemory(plaintext);
plaintext = NULL;
}
CloseFile(&blockFile);
return DISCARD_MARKUP;
}
BOOL DiscardConditionalBlock(TEXTFILE *infile)
{
char *plaintext;
HTML_MARKUP htmlMarkup;
BOOL result;
uint embeddedConditionals;
uint markupType;
/* discard the block, looking for the matching ELSE or /IF statement */
embeddedConditionals = 0;
for(;;)
{
result = ReadHtmlFile(infile, NULL, &plaintext, &markupType);
if(result == ERROR)
{
return FALSE;
}
else if(result == FALSE)
{
/* end-of-file before end-of-conditional ... error */
HtpMsg(MSG_ERROR, infile, "EOF encountered before conditional closed");
return FALSE;
}
if(PlaintextToMarkup(plaintext, &htmlMarkup) == FALSE)
{
/* memory alloc error */
HtpMsg(MSG_ERROR, infile, "could not parse markup tag (out of memory?)");
FreeMemory(plaintext);
return FALSE;
}
/* FreeMemory the plaintext buffer, not needed any longer */
FreeMemory(plaintext);
plaintext = NULL;
/* another conditional started? */
if(IsMarkupTag(&htmlMarkup, "IF"))
{
embeddedConditionals++;
}
else if(IsMarkupTag(&htmlMarkup, "/IF"))
{
/* end of the conditional? */
if(embeddedConditionals == 0)
{
DestroyMarkupStruct(&htmlMarkup);
break;
}
embeddedConditionals--;
}
else if(IsMarkupTag(&htmlMarkup, "ELSE"))
{
/* start of TRUE block? */
if(embeddedConditionals == 0)
{
DestroyMarkupStruct(&htmlMarkup);
break;
}
}
/* destroy and continue */
DestroyMarkupStruct(&htmlMarkup);
}
return TRUE;
}
uint BooleanProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
static uint conditionalLevel = 0;
const char *value;
uint type;
BOOL condTrue;
HTML_ATTRIBUTE *attrib;
BOOL notTagFound;
UNREF_PARAM(newPlaintext);
condTrue = FALSE;
/* conditionalLevel keeps track of boolean depth */
if(conditionalLevel == 0)
{
if((IsMarkupTag(htmlMarkup, "/IF")) || (IsMarkupTag(htmlMarkup, "ELSE")))
{
HtpMsg(MSG_ERROR, task->infile, "conditional block must start with IF tag");
return MARKUP_ERROR;
}
}
if(IsMarkupTag(htmlMarkup, "IF"))
{
conditionalLevel++;
/* this is an ugly way to handle the IF-IF NOT test, but will need */
/* be cleaned up in the future */
/* should either be one or two attributes in markup */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "no conditional to test");
return MARKUP_ERROR;
}
if(htmlMarkup->attribCount > 2)
{
HtpMsg(MSG_ERROR, task->infile, "too many items in conditional expression");
return MARKUP_ERROR;
}
/* find the attribute to evaluate and search for NOT attribute */
notTagFound = FALSE;
attrib = NULL;
if(stricmp(htmlMarkup->attrib[0].name, "NOT") == 0)
{
/* check to make sure the second attribute is present */
if(htmlMarkup->attribCount == 1)
{
HtpMsg(MSG_ERROR, task->infile, "NOT listed, no conditional to test");
return MARKUP_ERROR;
}
notTagFound = TRUE;
attrib = &htmlMarkup->attrib[1];
}
else if(htmlMarkup->attribCount == 2)
{
if(stricmp(htmlMarkup->attrib[1].name, "NOT") == 0)
{
notTagFound = TRUE;
attrib = &htmlMarkup->attrib[0];
}
else
{
/* this should have been the NOT expression */
HtpMsg(MSG_ERROR, task->infile, "too many conditionals to test");
return MARKUP_ERROR;
}
}
else
{
attrib = &htmlMarkup->attrib[0];
}
/* get the macros associated value (NULL if macro not defined) */
if((value = GetVariableValue(task->varstore, attrib->name)) != NULL)
{
type = GetVariableType(task->varstore, attrib->name);
}
else
{
type = VAR_TYPE_SET_MACRO;
}
/* if only a name is specified, only care if macro is defined */
if(attrib->value == NULL)
{
condTrue = (value != NULL) ? TRUE : FALSE;
}
else
{
/* macro value comparison */
if(type == VAR_TYPE_SET_MACRO)
{
/* macro comparison (case-sensitive) */
condTrue = (strcmp(value, attrib->value) == 0) ? TRUE : FALSE;
}
else
{
/* block macro, comparisons not allowed */
condTrue = FALSE;
}
}
/* reverse conditional if NOT attribute found */
if(notTagFound == TRUE)
{
condTrue = (condTrue == TRUE) ? FALSE : TRUE;
}
if(condTrue == TRUE)
{
/* simply discard the markup and let the file processor continue */
return DISCARD_MARKUP;
}
/* discard the rest of the conditional block since this portion has */
/* evaluated false */
if(DiscardConditionalBlock(task->infile) == FALSE)
{
return MARKUP_ERROR;
}
}
else if(IsMarkupTag(htmlMarkup, "ELSE"))
{
/* this can only occur if the associated conditional statement */
/* evaluated TRUE, so the remaining block must be discarded */
if(DiscardConditionalBlock(task->infile) == FALSE)
{
return MARKUP_ERROR;
}
}
else
{
/* end of conditional */
assert(conditionalLevel > 0);
conditionalLevel--;
}
return DISCARD_MARKUP;
}
uint CommentProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
UNREF_PARAM(htmlMarkup);
UNREF_PARAM(newPlaintext);
/* authors ego-gratifying easter egg */
/* put a final comment at the end of the output file */
PutFileString(task->outfile, "\n\n<!-- HTML pre-processed by %s %d.%02d %s -->\n\n",
PROGRAM_NAME, VER_MAJOR, VER_MINOR, VER_STAGE);
return MARKUP_OKAY;
}
uint ConditionalWarning(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
UNREF_PARAM(htmlMarkup);
UNREF_PARAM(newPlaintext);
HtpMsg(MSG_ERROR, task->infile, "IFNOT tag no longer recognized; use IF NOT instead");
return MARKUP_ERROR;
}
uint PreProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
UNREF_PARAM(htmlMarkup);
UNREF_PARAM(newPlaintext);
/* the CONDENSE option cannot be utilized inside a <PRE>...</PRE> */
/* block, because there HTML DOES interpret CR's */
if(CONDENSE)
{
if(IsMarkupTag(htmlMarkup, "PRE"))
{
AllowLinefeeds(task->outfile);
}
else if(IsMarkupTag(htmlMarkup, "/PRE"))
{
SuppressLinefeeds(task->outfile);
}
}
return MARKUP_OKAY;
}
uint AltTextProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
const char *imgName;
const char *imgText;
UNREF_PARAM(newPlaintext);
/* requires at least a NAME parameter */
if(IsAttributeInMarkup(htmlMarkup, "NAME") == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "ALTTEXT requires a NAME attribute");
return MARKUP_ERROR;
}
/* get the relevant information */
imgName = MarkupAttributeValue(htmlMarkup, "NAME");
if(imgName == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "NAME must be specified with a filename");
return MARKUP_ERROR;
}
if(IsAttributeInMarkup(htmlMarkup, "TEXT") == TRUE)
{
imgText = MarkupAttributeValue(htmlMarkup, "TEXT");
if(imgText == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "TEXT must be specified with a value (\"\" is acceptable)");
return MARKUP_ERROR;
}
}
else
{
imgText = NULL;
}
/* try to find the graphic name in the ALTTEXT store */
if(VariableExists(&altTextVarStore, imgName) == TRUE)
{
/* if no name specified, delete it from the store */
if(imgText == NULL)
{
RemoveVariable(&altTextVarStore, imgName);
HtpMsg(MSG_INFO, task->infile, "ALT text for image \"%s\" removed",
imgName);
return DISCARD_MARKUP;
}
/* since it exists, simply re-storing the value will delete the */
/* old one and replace with new one */
}
else if(imgText == NULL)
{
/* tried to delete an image not already in the store */
/* just post a warning */
HtpMsg(MSG_WARNING, task->infile, "attempted to delete image text not already defined");
return DISCARD_MARKUP;
}
StoreVariable(&altTextVarStore, imgName, imgText, VAR_TYPE_ALTTEXT,
VAR_FLAG_NONE, NULL, NULL);
HtpMsg(MSG_INFO, task->infile, "ALT text for image \"%s\" set to \"%s\"",
imgName, imgText);
return DISCARD_MARKUP;
}
uint UndefProcessor(TASK *task, HTML_MARKUP *htmlMarkup, char **newPlaintext)
{
uint ctr;
const char *name;
UNREF_PARAM(newPlaintext);
/* need at least one attribute to undef */
if(htmlMarkup->attribCount == 0)
{
HtpMsg(MSG_ERROR, task->infile, "UNDEF requires at least one name");
return MARKUP_ERROR;
}
/* walk the list of attributes, deleting them as found */
for(ctr = 0; ctr < htmlMarkup->attribCount; ctr++)
{
name = htmlMarkup->attrib[ctr].name;
/* is it in the store? */
if(VariableExists(task->varstore, name) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "No metatag \"%s\" to undefine",
name);
return MARKUP_ERROR;
}
/* only remove it if a DEF macro */
if(GetVariableType(task->varstore, name) == VAR_TYPE_DEF_MACRO)
{
RemoveVariable(task->varstore, name);
}
HtpMsg(MSG_INFO, task->infile, "metatag \"%s\" removed", name);
}
return DISCARD_MARKUP;
}
#define MARKUP_PROCESSOR_COUNT (17)
MARKUP_PROCESSORS markupProcessor[MARKUP_PROCESSOR_COUNT] =
{
{ "IMG", MARKUP_TYPE_HTML, ImageProcessor },
{ "OPT", MARKUP_TYPE_HTP, OptionProcessor },
{ "FILE", MARKUP_TYPE_HTP, FileProcessor },
{ "SET", MARKUP_TYPE_HTP, SetProcessor },
{ "BLOCK", MARKUP_TYPE_HTP, BlockProcessor },
{ "USE", MARKUP_TYPE_HTP, UseProcessor },
{ "IF", MARKUP_TYPE_HTP, BooleanProcessor },
{ "/IF", MARKUP_TYPE_HTP, BooleanProcessor },
{ "IFNOT", MARKUP_TYPE_HTP, ConditionalWarning },
{ "ELSE", MARKUP_TYPE_HTP, BooleanProcessor },
{ "/BODY", MARKUP_TYPE_HTML, CommentProcessor },
{ "UNSET", MARKUP_TYPE_HTP, UnsetProcessor },
{ "PRE", MARKUP_TYPE_HTML, PreProcessor },
{ "/PRE", MARKUP_TYPE_HTML, PreProcessor },
{ "ALTTEXT", MARKUP_TYPE_HTP, AltTextProcessor },
{ "DEF", MARKUP_TYPE_HTP, BlockProcessor },
{ "UNDEF", MARKUP_TYPE_HTP, UndefProcessor }
};
/*
// HTML processing
*/
BOOL ExpandMacrosInString(TASK *task, const char *text, char *newText,
uint newTextSize, BOOL *quoted, uint *changeCount)
{
const char *expansion;
char macro[MAX_VARVALUE_LEN];
char *textPtr;
uint insertStartPos;
uint insertEndPos;
uint newTextLength;
assert(task != NULL);
assert(text != NULL);
assert(newText != NULL);
assert(newTextSize > 0);
assert(quoted != NULL);
assert(changeCount != NULL);
*changeCount = 0;
insertStartPos = 0;
insertEndPos = 0;
/* optimization: if no '$' in text, no need to go futher */
if(strchr(text, '$') == NULL)
{
#if DEBUG
expandSkipped++;
#endif
return TRUE;
}
#if DEBUG
expandPerformed++;
#endif
/* Allan Todd fix: only check buffer size when its known to be needed */
assert(newTextSize >= strlen(text));
/* copy the old text directly into the new text buffer, and use that */
/* as working space */
StringCopy(newText, text, newTextSize);
/* loop repeatedly to evaluate the string until no more macros are found */
for(;;)
{
macro[0] = NUL;
/* search the value for a $-preceded macro name */
textPtr = strchr(newText, '$');
while(textPtr != NULL)
{
/* if only one contiguous '$' found, stop looking and process */
if(textPtr[1] != '$')
{
break;
}
textPtr = strchr(textPtr + 2, '$');
}
/* if nothing found, exit */
if(textPtr == NULL)
{
break;
}
/* this is used later more than once, but could change each iteration */
newTextLength = strlen(newText);
/* process the macro */
/* save the position to insert the macro */
insertStartPos = textPtr - newText;
/* skip the '$' */
textPtr++;
/* copy macro name into macro[] array and set up the text pointer */
/* macro specified with braces? */
if(*textPtr == '{')
{
char *endPtr;
/* start of a macro */
/* skip opening curly brace and find the closing curly brace */
endPtr = strchr(++textPtr, '}');
if(endPtr == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "ending brace not found in macro name");
return FALSE;
}
/* copy in the enclosed text */
StringCopy(macro, textPtr, endPtr - textPtr + 1);
/* set end insertion point */
insertEndPos = endPtr - newText + 1;
}
else
{
/* start of macro, no braces */
/* copy macro name until EOS */
StringCopy(macro, textPtr, MAX_VARVALUE_LEN);
/* set end insertion point */
insertEndPos = newTextLength;
}
/* if no macro name found, stop */
if(macro[0] == NUL)
{
break;
}
/* make sure variable exists in store */
if(VariableExists(task->varstore, macro) != TRUE)
{
/* only a warning ... stop processing to prevent infinite */
/* loop */
HtpMsg(MSG_WARNING, task->infile, "unrecognized macro name \"%s\"",
macro);
break;
}
/* block macros cannot be expanded inside of markup tags */
if(GetVariableType(task->varstore, macro) == VAR_TYPE_BLOCK_MACRO)
{
HtpMsg(MSG_ERROR, task->infile, "cannot expand block macro \"%s\" inside a markup",
macro);
return FALSE;
}
/* get the macros value and replace the attribute value */
expansion = GetVariableValue(task->varstore, macro);
if(expansion != NULL)
{
HtpMsg(MSG_INFO, task->infile, "expanding macro \"%s\" to \"%s\"",
macro, expansion);
}
else
{
HtpMsg(MSG_INFO, task->infile, "expanding macro \"%s\" to null text",
macro);
}
/* build a new string using the expanded macro */
/* if the macro is embedded inside a larger string, */
/* actually go through the rigamarole of piecing together */
/* a new value string */
if((insertStartPos != 0)
|| (insertEndPos != newTextLength))
{
char *dupString;
/* make a copy of the text buffer */
/* can't use DuplicateString() because extra buffer past EOS needed */
dupString = AllocMemory(newTextSize);
if(dupString == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "out of memory during macro expansion");
return FALSE;
}
StringCopy(dupString, newText, newTextSize);
/* copy in the expanded macro at the insertion point */
if(expansion != NULL)
{
StringCopy(dupString + insertStartPos, expansion,
newTextSize - insertStartPos);
}
else
{
dupString[insertStartPos] = NUL;
}
/* copy in any characters after the macro ended */
strncat(dupString, newText + insertEndPos, newTextSize);
/* copy it back to the old string buffer and free */
StringCopy(newText, dupString, newTextSize);
FreeMemory(dupString);
dupString = NULL;
/* let the surrounding text dictate quote marks */
}
else
{
/* since the macro is the entire value, no harm (and */
/* more robust) to surround it by quotes */
StringCopy(newText, expansion, MAX_VARVALUE_LEN);
*quoted = TRUE;
}
/* increment the change count */
*changeCount = *changeCount + 1;
/* need to go back and re-evaluate the value for more macros */
}
/* guess what! need to re-process the value again to strip the */
/* double '$' ... this couldn't be done previously because the newly */
/* single '$' would have been processed as macro as the loop went */
/* back around to finish off the next dereferenced macro */
textPtr = strchr(newText, '$');
while(textPtr != NULL)
{
/* look for adjacent '$' */
if(textPtr[1] == '$')
{
/* terminate the preceding characters */
textPtr[1] = NUL;
/* concatenate the rest of the string */
memmove(textPtr + 1, textPtr + 2, strlen(textPtr + 2) + 1);
/* increment the change count */
*changeCount = *changeCount + 1;
/* start looking at the beginning of the new string */
textPtr = strchr(newText, '$');
continue;
}
/* just keep looking otherwise */
textPtr = strchr(textPtr + 1, '$');
}
return TRUE;
}
BOOL ExpandMacros(TASK *task, HTML_MARKUP *htmlMarkup)
{
uint ctr;
HTML_ATTRIBUTE *attrib;
BOOL result;
union
{
char newTag[MAX_VARNAME_LEN];
char newName[MAX_VARNAME_LEN];
char newValue[MAX_VARVALUE_LEN];
} newText;
BOOL quoted;
BOOL changeCount;
assert(task != NULL);
assert(htmlMarkup != NULL);
/* expand any macros in the tags */
if(htmlMarkup->tag != NULL)
{
if(ExpandMacrosInString(task, htmlMarkup->tag, newText.newTag,
MAX_VARNAME_LEN, "ed, &changeCount) != TRUE)
{
return FALSE;
}
if(changeCount > 0)
{
ChangeMarkupTag(htmlMarkup, newText.newTag);
}
}
/* do the same for all attributes, both name and value */
result = TRUE;
for(ctr = 0; ctr < htmlMarkup->attribCount; ctr++)
{
attrib = &htmlMarkup->attrib[ctr];
if(attrib->name != NULL)
{
result = ExpandMacrosInString(task, attrib->name, newText.newName,
MAX_VARNAME_LEN, "ed, &changeCount);
if(result != TRUE)
{
break;
}
if(changeCount > 0)
{
ChangeAttributeName(attrib, newText.newName);
}
}
if(attrib->value != NULL)
{
quoted = attrib->quoted;
result = ExpandMacrosInString(task, attrib->value, newText.newValue,
MAX_VARVALUE_LEN, "ed, &changeCount);
if(result != TRUE)
{
break;
}
if(changeCount > 0)
{
ChangeAttributeValue(attrib, newText.newValue, quoted);
}
}
}
return result;
}
#define METATAG_MAX_OPTIONS (256)
uint ExpandMetatag(TASK *task, HTML_MARKUP *htmlMarkup)
{
const char *options;
char *optionCopy;
FIND_TOKEN findToken;
char *optionPtr;
uint optionCount;
uint ctr;
uint optionCtr;
const char *optionArray[METATAG_MAX_OPTIONS];
const HTML_ATTRIBUTE *attrib;
BOOL found;
VARSTORE defVarstore;
uint flag;
VARSTORE *topVarstore;
char defBlockName[64];
const char *defFilename;
const char *defName;
TEXTFILE defFile;
TASK newTask;
BOOL result;
/* first things first: find the tag in the metatag store */
if(VariableExists(task->varstore, htmlMarkup->tag) == FALSE)
{
/* don't change a thing */
return MARKUP_OKAY;
}
/* verify the macro in the store is a metatag definition */
if(GetVariableType(task->varstore, htmlMarkup->tag) != VAR_TYPE_DEF_MACRO)
{
return MARKUP_OKAY;
}
/* get a pointer to the name */
defName = htmlMarkup->tag;
/* get the filename the DEF macro is held in */
if((defFilename = GetVariableValue(task->varstore, defName)) == NULL)
{
/* this shouldnt be */
HtpMsg(MSG_ERROR, task->infile, "DEF macro \"%s\" was not store properly",
defName);
return MARKUP_ERROR;
}
/* get options to compare against markups paramater list */
options = GetVariableParam(task->varstore, defName);
/* initialize a local variable store, even if its not used */
InitializeVariableStore(&defVarstore);
/* if NULL, then no options allowed */
if(options == NULL)
{
if(htmlMarkup->attribCount > 0)
{
HtpMsg(MSG_ERROR, task->infile, "DEF macro \"%s\" does not specify any options",
defName);
DestroyVariableStore(&defVarstore);
return MARKUP_ERROR;
}
/* keep the current store context */
topVarstore = task->varstore;
}
else
{
/* options should be space-delimited, use StringToken() */
if((optionCopy = DuplicateString(options)) == NULL)
{
HtpMsg(MSG_ERROR, task->infile, "Unable to duplicate option macro (out of memory?)");
DestroyVariableStore(&defVarstore);
return MARKUP_ERROR;
}
/* build array of pointers to null-terminated option */
optionCount = 0;
optionPtr = StringFirstToken(&findToken, optionCopy, " ");
while((optionPtr != NULL) && (optionCount < METATAG_MAX_OPTIONS))
{
/* ignore multiple spaces */
if(*optionPtr != ' ')
{
/* save a pointer to the token */
optionArray[optionCount++] = optionPtr;
}
optionPtr = StringNextToken(&findToken);
}
/* now, see if every paramater in the markup is also in the option list */
/* (the reverse is not required) */
for(ctr = 0; (attrib = MarkupAttribute(htmlMarkup, ctr)) != NULL; ctr++)
{
found = FALSE;
for(optionCtr = 0; optionCtr < optionCount; optionCtr++)
{
if(stricmp(optionArray[optionCtr], attrib->name) == 0)
{
found = TRUE;
break;
}
}
if(found == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"DEF macro \"%s\" does not accept a parameter named \"%s\"",
defName, attrib->name);
FreeMemory(optionCopy);
DestroyVariableStore(&defVarstore);
return MARKUP_ERROR;
}
/* since this is a good attribute, add it to the local store */
flag = (attrib->quoted == TRUE) ? VAR_FLAG_QUOTED : VAR_FLAG_NONE;
if(StoreVariable(&defVarstore, attrib->name, attrib->value,
VAR_TYPE_SET_MACRO, flag, NULL, NULL) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"Unable to store local macro for metatag");
DestroyVariableStore(&defVarstore);
FreeMemory(optionCopy);
return MARKUP_ERROR;
}
}
/* looks good, this is no longer needed */
FreeMemory(optionCopy);
/* make this the topmost context */
PushVariableStoreContext(task->varstore, &defVarstore);
topVarstore = &defVarstore;
}
/* expand the DEF macro like a block macro ... */
/* set up the DEF macro name for user messages */
sprintf(defBlockName, "Metatag \"%s\"", defName);
/* open the file the macro is held in */
if(OpenFile(defBlockName, defFilename, "r", &defFile) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile,
"unable to open temporary file \"%s\" for DEF macro \"%s\"",
defFilename, defName);
return MARKUP_ERROR;
}
HtpMsg(MSG_INFO, task->infile, "dereferencing metatag macro \"%s\"", defName);
/* build a new task structure */
newTask.infile = &defFile;
newTask.outfile = task->outfile;
newTask.sourceFilename = task->sourceFilename;
/* re-user current variable store if no local store was made */
newTask.varstore = topVarstore;
/* process the new input file */
result = ProcessTask(&newTask);
/* remove the new context if necessary */
if(topVarstore == &defVarstore)
{
assert(PeekVariableStoreContext(topVarstore) == topVarstore);
PopVariableStoreContext(topVarstore);
}
/* no matter what, destroy the local store */
DestroyVariableStore(&defVarstore);
CloseFile(&defFile);
return (result == TRUE) ? DISCARD_MARKUP : MARKUP_ERROR;
}
BOOL ProcessTask(TASK *task)
{
char *newPlaintext;
uint ctr;
uint markupResult;
HTML_MARKUP htmlMarkup;
BOOL result;
uint markupType;
assert(task != NULL);
assert(task->infile != NULL);
assert(task->outfile != NULL);
assert(task->varstore != NULL);
for(;;)
{
result = ReadHtmlFile(task->infile, task->outfile, &newPlaintext,
&markupType);
if(result == ERROR)
{
/* problem reading in the file */
return FALSE;
}
else if(result == FALSE)
{
/* end-of-file */
break;
}
/* use the new markup plain text to build an HTML_MARKUP structure */
if(PlaintextToMarkup(newPlaintext, &htmlMarkup) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "could not parse markup tag (out of memory?)");
FreeMemory(newPlaintext);
return FALSE;
}
/* destroy the ORIGINAL plain text, not needed again */
FreeMemory(newPlaintext);
newPlaintext = NULL;
/* give the default processor a chance to expand macros, etc. */
if(ExpandMacros(task, &htmlMarkup) == FALSE)
{
/* problem encountered trying to expand macros */
DestroyMarkupStruct(&htmlMarkup);
return FALSE;
}
/* give the metatag processor a chance to expand metatags */
/* this is a little strange, but if MARKUP_OKAY it means the the */
/* metatag processor didnt recognize the tag, and therefore should */
/* be handled by the other processors */
if((markupResult = ExpandMetatag(task, &htmlMarkup)) == MARKUP_OKAY)
{
/* find the first processor that wants to do something with the */
/* markup tag */
for(ctr = 0; ctr < MARKUP_PROCESSOR_COUNT; ctr++)
{
if(markupProcessor[ctr].markupType & markupType)
{
if(IsMarkupTag(&htmlMarkup, markupProcessor[ctr].tag))
{
assert(markupProcessor[ctr].markupFunc != NULL);
markupResult = markupProcessor[ctr].markupFunc(task,
&htmlMarkup, &newPlaintext);
break;
}
}
}
}
/* unless the function requested to use its new markup string, */
/* take the HTML_MARKUP structure and build a new markup */
if((markupResult != NEW_MARKUP) && (markupResult != DISCARD_MARKUP))
{
if(MarkupToPlaintext(&htmlMarkup, &newPlaintext) == FALSE)
{
HtpMsg(MSG_ERROR, task->infile, "unable to build plain text from markup (out of memory?)");
return FALSE;
}
}
/* destroy the structure, now only interested in the markup string */
DestroyMarkupStruct(&htmlMarkup);
switch(markupResult)
{
case MARKUP_OKAY:
{
/* add the markup to the output file as it should appear */
PutFileString(task->outfile, "%c%s%c", MARKUP_OPEN_DELIM(markupType),
newPlaintext, MARKUP_CLOSE_DELIM(markupType));
}
break;
case NEW_MARKUP:
case MARKUP_REPLACED:
{
/* the markup has been replaced by a normal string */
PutFileString(task->outfile, "%s", newPlaintext);
}
break;
case DISCARD_MARKUP:
{
/* markup will not be included in final output */
}
break;
case MARKUP_ERROR:
{
/* (need to destroy plaintext buffer before exiting) */
FreeMemory(newPlaintext);
return FALSE;
}
default:
{
FreeMemory(newPlaintext);
printf("%s: serious internal error\n", PROGRAM_NAME);
exit(1);
}
}
/* free the plain text buffer and continue with processing */
FreeMemory(newPlaintext);
newPlaintext = NULL;
}
return TRUE;
}
BOOL FullyCheckDependencies(const char *in, const char *out)
{
BOOL result;
TEXTFILE infile;
char *plaintext;
char title[128];
HTML_MARKUP markup;
const char *includeFile;
const char *imageFile;
BOOL readResult;
BOOL checkResult;
uint markupType;
assert(in != NULL);
assert(out != NULL);
if(DEPEND == FALSE)
{
/* outta here */
return FALSE;
}
/* check if target file is completely up to date compared to input file */
result = IsTargetUpdated(in, out);
if(result == ERROR)
{
printf("%s: unable to get file information for file \"%s\"\n",
PROGRAM_NAME, in);
return ERROR;
}
else if(result == FALSE)
{
/* target is not updated */
return FALSE;
}
/* because target is up to date, need to search dependency file for */
/* FILE INCLUDE tags and check those files likewise */
/* open file */
sprintf(title, "Dependency check for %s", in);
if(OpenFile(title, in, "r", &infile) == FALSE)
{
printf("%s: unable to open file \"%s\" for reading while checking dependencies\n",
PROGRAM_NAME, in);
return ERROR;
}
/* assume everything is hunky-dory unless otherwise discovered */
checkResult = TRUE;
/* get the next markup tag from the input file */
while((readResult = ReadHtmlFile(&infile, NULL, &plaintext, &markupType)) != FALSE)
{
if(readResult == ERROR)
{
/* error occurred processing the HTML file */
checkResult = ERROR;
break;
}
/* check markup type ... only interested in htp markups currently */
if((markupType & MARKUP_TYPE_HTP) == 0)
{
continue;
}
/* received a markup ... check if its an INCLUDE markup */
PlaintextToMarkup(plaintext, &markup);
/* do not need plaintext any further */
FreeMemory(plaintext);
plaintext = NULL;
/* if FILE INCLUDE markup, get the filename specified */
includeFile = NULL;
imageFile = NULL;
if(IsMarkupTag(&markup, "FILE"))
{
if(IsAttributeInMarkup(&markup, "INCLUDE"))
{
includeFile = MarkupAttributeValue(&markup, "INCLUDE");
}
else if(IsAttributeInMarkup(&markup, "TEMPLATE"))
{
includeFile = MarkupAttributeValue(&markup, "TEMPLATE");
}
}
else if(IsMarkupTag(&markup, "IMG"))
{
if(IsAttributeInMarkup(&markup, "SRC"))
{
imageFile = MarkupAttributeValue(&markup, "SRC");
}
}
else if(IsMarkupTag(&markup, "OPT"))
{
if(IsAttributeInMarkup(&markup, "NODEPEND"))
{
/* !! dependency checking disabled in source file ... since this */
/* can swing back and forth throughout the files, and its just */
/* a pain to track what is technically the last one set, */
/* if one is found, dependency checking is disabled and the */
/* targets are not considered updated */
/* this could be fixed with some work */
checkResult = FALSE;
DestroyMarkupStruct(&markup);
break;
}
}
/* by default assume everything is up to date unless more information */
/* is available through other files */
result = TRUE;
/* check include or image file timestamps */
if(includeFile != NULL)
{
/* !! the accursed recursion strikes again */
/* check the dependencies based on this new file */
result = FullyCheckDependencies(includeFile, out);
}
else if(imageFile != NULL)
{
/* check the image files timestamp as part of dependency checking */
if(FileExists(imageFile))
{
result = IsTargetUpdated(imageFile, out);
}
}
/* unneeded now */
DestroyMarkupStruct(&markup);
if(result != TRUE)
{
/* if FALSE, not up to date, no need to go further */
/* if ERROR, need to stop and report to caller */
checkResult = result;
break;
}
/* otherwise, TRUE indicates that everything is okay, */
/* so keep searching */
}
/* EOF encountered in the HTML input file ... target is updated */
CloseFile(&infile);
return checkResult;
}
BOOL ProcessFileByName(const char *in, const char *out)
{
TEXTFILE infile;
TEXTFILE outfile;
TASK task;
BOOL result;
TEXTFILE project;
const char *templateFile;
assert(in != NULL);
assert(out != NULL);
/* before proceeding, find a local project default file */
if(FileExists("htp.def"))
{
StringCopy(projectFilename, "htp.def", MAX_PATHNAME_LEN);
}
else
{
projectFilename[0] = NUL;
}
/* assume no processing required */
result = TRUE;
/* check the global and project default files first */
if(*globalFilename != NUL)
{
if((result = FullyCheckDependencies(globalFilename, out)) == ERROR)
{
return FALSE;
}
}
if((result == TRUE) && (*projectFilename != NUL))
{
if((result = FullyCheckDependencies(projectFilename, out)) == ERROR)
{
return FALSE;
}
}
/* check the dependencies of the target file to see whether or not */
/* to proceed ... the global and project default files are checked as well */
if(result == TRUE)
{
if((result = FullyCheckDependencies(in, out)) == ERROR)
{
/* did not process the files */
return FALSE;
}
}
/* if TRUE, no need to go any further */
if(result == TRUE)
{
/* explain why no processing required, and return as if processing */
/* was completed */
printf("%s: File \"%s\" is completely up to date.\n", PROGRAM_NAME,
out);
return TRUE;
}
/* continue, at least one file was found that requires out to be updated */
/* initialize the project variable store and push it onto context */
InitializeVariableStore(&projectVarStore);
PushVariableStoreContext(&globalVarStore, &projectVarStore);
/* initialize the ALT text store (used by the ALTTEXT tag) */
InitializeVariableStore(&altTextVarStore);
/* open the output file first, the project default file needs it */
if(OpenFile(out, out, "w", &outfile) == FALSE)
{
printf("%s: unable to open file \"%s\" for writing\n", PROGRAM_NAME, out);
DestroyVariableStore(&altTextVarStore);
DestroyVariableStore(&projectVarStore);
return FALSE;
}
if(CONDENSE)
{
/* suppress all linefeeds for this file, makes the HTML output smaller */
SuppressLinefeeds(&outfile);
}
/* clear the task struct, in case there is no project file */
memset(&task, 0, sizeof(TASK));
if(projectFilename[0] != NUL)
{
/* process the default project file */
if(OpenFile(projectFilename, projectFilename, "r", &project) == FALSE)
{
printf("%s: unable to open file \"%s\" for reading\n", PROGRAM_NAME,
projectFilename);
CloseFile(&outfile);
DestroyVariableStore(&projectVarStore);
DestroyVariableStore(&altTextVarStore);
return FALSE;
}
/* build a task structure */
task.infile = &project;
task.outfile = &outfile;
task.varstore = &projectVarStore;
task.sourceFilename = in;
printf("%s: Processing default project file \"%s\" ...\n", PROGRAM_NAME,
projectFilename);
result = ProcessTask(&task);
CloseFile(&project);
if(result != TRUE)
{
if(PRECIOUS == FALSE)
{
remove(out);
}
printf("%s: error during processing of default project file \"%s\"\n",
PROGRAM_NAME, projectFilename);
CloseFile(&outfile);
DestroyVariableStore(&projectVarStore);
DestroyVariableStore(&altTextVarStore);
return result;
}
}
if(OpenFile(in, in, "r", &infile) == FALSE)
{
printf("%s: unable to open file \"%s\" for reading\n", PROGRAM_NAME, in);
CloseFile(&outfile);
DestroyVariableStore(&projectVarStore);
DestroyVariableStore(&altTextVarStore);
return FALSE;
}
if(InitializeLocalOption() == FALSE)
{
printf("%s: unable to initialize local option store\n", PROGRAM_NAME);
CloseFile(&infile);
CloseFile(&outfile);
DestroyVariableStore(&projectVarStore);
DestroyVariableStore(&altTextVarStore);
return FALSE;
}
/* build a task structure */
task.infile = &infile;
task.outfile = &outfile;
task.varstore = &projectVarStore;
task.sourceFilename = in;
printf("%s: Processing file \"%s\" to output file \"%s\" ...\n",
PROGRAM_NAME, in, out);
result = ProcessTask(&task);
/* need to check for a template file */
while((result == TRUE) && (VariableExists(&projectVarStore, VAR_TEMPLATE_NAME)))
{
/* go process it */
/* done with this file, want to reuse struct */
CloseFile(&infile);
templateFile = GetVariableValue(&projectVarStore, VAR_TEMPLATE_NAME);
if(OpenFile(templateFile, templateFile, "r", &infile) == FALSE)
{
printf("%s: unable to open template file \"%s\"\n",
PROGRAM_NAME, templateFile);
CloseFile(&outfile);
DestroyLocalOption();
DestroyVariableStore(&altTextVarStore);
DestroyVariableStore(&projectVarStore);
return FALSE;
}
task.infile = &infile;
task.outfile = &outfile;
task.varstore = &projectVarStore;
task.sourceFilename = in;
printf("%s: Processing template file \"%s\" ...\n", PROGRAM_NAME,
templateFile);
result = ProcessTask(&task);
/* because this template file can, legally, reference another */
/* template file, remove the current variable and let the while loop */
/* continue until no more template files are specified */
/* yes, this can lead to infinite loops and such, but the syntax */
/* shouldnt bar this, and after all, the same problem could exist if */
/* the user kept doing circular FILE INCLUDEs */
/* Pilot error! */
RemoveVariable(&projectVarStore, VAR_TEMPLATE_NAME);
}
if(result == TRUE)
{
printf("%s: final output file \"%s\" successfully created\n\n",
PROGRAM_NAME, outfile.name);
}
else
{
printf("\n%s: error encountered, file \"%s\" not completed\n\n",
PROGRAM_NAME, outfile.name);
}
CloseFile(&outfile);
CloseFile(&infile);
/* destroy incomplete file if not configured elsewise */
if(result != TRUE)
{
if(PRECIOUS == FALSE)
{
assert(out != NULL);
remove(out);
}
}
/* destroy the local options for these files */
DestroyLocalOption();
/* destroy the project store as well */
DestroyVariableStore(&projectVarStore);
/* destroy the ALT text store */
DestroyVariableStore(&altTextVarStore);
return result;
}
BOOL ProcessResponseFile(const char *resp)
{
char textline[128];
char defResp[MAX_PATHNAME_LEN];
char newDirectory[MAX_PATHNAME_LEN];
char oldDirectory[MAX_PATHNAME_LEN];
TEXTFILE respfile;
int result;
char *in;
char *out;
char *ptr;
BOOL useNewDir;
BOOL respFileOpen;
FIND_TOKEN findToken;
assert(resp != NULL);
useNewDir = FALSE;
if(strchr(ALL_FILESYSTEM_DELIMITERS, resp[strlen(resp) - 1]) != NULL)
{
/* some tests as done to ensure that (a) newDirectory does not trail */
/* with a directory separator and that (b) the separator is present */
/* before appending the filename ... requirement (a) is a DOS issue */
/* the response file is actually a directory the response file is */
/* possibly kept in ... copy it to the newDirectory variable for */
/* later use, but remove the trailing delimiter (MS-DOS issue) */
strcpy(newDirectory, resp);
newDirectory[strlen(newDirectory) - 1] = NUL;
/* now, see if default response file is present */
strcpy(defResp, newDirectory);
strcat(defResp, DIR_DELIMITER_STRING);
strcat(defResp, DEFAULT_RESPONSE_FILE);
useNewDir = TRUE;
respFileOpen = OpenFile(defResp, defResp, "r", &respfile);
}
else
{
respFileOpen = OpenFile(resp, resp, "r", &respfile);
}
if(respFileOpen == FALSE)
{
printf("%s: unable to open \"%s\" as a response file\n", PROGRAM_NAME,
resp);
return FALSE;
}
printf("%s: Processing response file \"%s\" ...\n", PROGRAM_NAME,
respfile.name);
/* processing a response file in another directory, change to that */
/* directory before processing the files */
if(useNewDir)
{
getcwd(oldDirectory, sizeof oldDirectory);
chdir(newDirectory);
}
result = TRUE;
do
{
if(GetFileLine(&respfile, textline, sizeof(textline)) == FALSE)
{
break;
}
in = NULL;
out = NULL;
/* walk tokens ... allow for tab character as token and ignore */
/* multiple token characters between filenames */
ptr = StringFirstToken(&findToken, textline, " \t");
while(ptr != NULL)
{
/* is this just a repeated token? */
if((*ptr == ' ') || (*ptr == '\t'))
{
ptr = StringNextToken(&findToken);
continue;
}
/* found something ... like parsing the command-line, look for */
/* options, then response files, then regular in and out filenames */
if((*ptr == '-') || (*ptr == '/'))
{
/* option */
ParseTextOption(ptr, OptionCallback, 0);
}
else if(*ptr == ';')
{
/* comment, ignore the rest of the line */
break;
}
else if(in == NULL)
{
in = ptr;
}
else if(out == NULL)
{
out = ptr;
}
else
{
/* hmm ... extra information on line */
HtpMsg(MSG_WARNING, &respfile, "extra option \"%s\" specified in response file, ignoring",
ptr);
}
ptr = StringNextToken(&findToken);
}
/* if in and out NULL, ignore the line entirely (all options or blank) */
if((in == NULL) && (out == NULL))
{
continue;
}
if(out == NULL)
{
/* in is the response file ... recurse like theres no tomorrow */
result = ProcessResponseFile(in);
continue;
}
/* both in and out were specified, do it */
result = ProcessFileByName(in, out);
} while(result == TRUE);
CloseFile(&respfile);
/* restore the directory this all started in */
if(useNewDir)
{
chdir(oldDirectory);
}
return result;
}
BOOL ProcessDefaultFile(void)
{
TASK defTask;
TEXTFILE infile;
TEXTFILE outfile;
BOOL result;
/* get the default filename */
if(HtpDefaultFilename(globalFilename, MAX_PATHNAME_LEN) == FALSE)
{
/* nothing to do, but no error either */
globalFilename[0] = NUL;
return TRUE;
}
if(OpenFile(globalFilename, globalFilename, "r", &infile) == FALSE)
{
printf("%s: unable to open default file \"%s\"\n", PROGRAM_NAME,
globalFilename);
return FALSE;
}
/* use a null outfile because there is no file to write to */
CreateNullFile(&outfile);
/* build a task (just like any other) and process the file */
/* use the global variable store to hold all the macros found */
defTask.infile = &infile;
defTask.outfile = &outfile;
defTask.varstore = &globalVarStore;
defTask.sourceFilename = globalFilename;
printf("%s: Processing default file \"%s\" ... \n", PROGRAM_NAME,
globalFilename);
result = ProcessTask(&defTask);
CloseFile(&infile);
CloseFile(&outfile);
return result;
}
int main(int argc, char *argv[])
{
int result;
uint ctr;
char *in;
char *out;
char *resp;
DisplayHeader();
if(argc == 1)
{
usage();
return 1;
}
/* initialize debugging */
#if DEBUG
DebugInit("htpdeb.out");
atexit(DebugTerminate);
#endif
/* initialize the suballoc memory module */
InitializeMemory();
atexit(TerminateMemory);
/* initialize global variable options */
if(InitializeGlobalOption(OptionCallback, 0) == FALSE)
{
printf("%s: fatal error, unable to initialize internal options\n",
PROGRAM_NAME);
return 1;
}
in = NULL;
out = NULL;
resp = NULL;
/* search command-line for options */
for(ctr = 1; ctr < (uint) argc; ctr++)
{
if((*argv[ctr] == '-') || (*argv[ctr] == '/'))
{
/* command-line option specified */
ParseTextOption(argv[ctr], OptionCallback, 0);
}
else if(*argv[ctr] == '@')
{
/* response file specified */
resp = argv[ctr] + 1;
if(*resp == NUL)
{
resp = (char *) DEFAULT_RESPONSE_FILE;
}
}
else if(in == NULL)
{
/* input file was specified */
in = argv[ctr];
}
else if(out == NULL)
{
/* output file was specified */
out = argv[ctr];
}
else
{
printf("%s: unknown argument \"%s\" specified\n",
PROGRAM_NAME, argv[ctr]);
return 1;
}
}
if(USAGE == TRUE)
{
usage();
return 1;
}
if((in == NULL || out == NULL) && (resp == NULL))
{
usage();
return 1;
}
/* initialize the global variable store before proceeding */
if(InitializeVariableStore(&globalVarStore) != TRUE)
{
printf("%s: unable to initialize global variable store (out of memory?)\n",
PROGRAM_NAME);
return 1;
}
/* before reading in the response file or processing any files, handle */
/* the default file, if there is one ... all of its macros are held in */
/* the global variable store */
ProcessDefaultFile();
/* now, process the response file (if there is one) or the files */
/* specified on the command-line */
if(resp != NULL)
{
result = ProcessResponseFile(resp);
}
else
{
result = ProcessFileByName(in, out);
}
/* display varstore stats */
DEBUG_PRINT(("Variable lookups=%u string cmps=%u missed string cmps=%u cache hits=%u hash calcs=%u\n",
variableLookups, variableStringCompares, variableMissedStringCompares,
variableCacheHits, variableHashCalcs));
/* display macro expansion stats */
DEBUG_PRINT(("Expansion skipped=%u performed=%u\n", expandSkipped,
expandPerformed));
/* destroy the global variable store */
DestroyVariableStore(&globalVarStore);
/* destroy global option */
DestroyGlobalOption();
/* display suballoc stats */
DEBUG_PRINT(("suballoc total allocations=%u free pool hits=%u system heap allocs=%u\n",
totalAllocations, freePoolHits, totalAllocations - freePoolHits));
return (result == TRUE) ? 0 : 1;
}
|