1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532
|
/*
* Copyright (c) 1999, 2013 Tanuki Software, Ltd.
* http://www.tanukisoftware.com
* All rights reserved.
*
* This software is the proprietary information of Tanuki Software.
* You shall use it only in accordance with the terms of the
* license agreement you entered into with Tanuki Software.
* http://wrapper.tanukisoftware.com/doc/english/licenseOverview.html
*
*
* Portions of the Software have been derived from source code
* developed by Silver Egg Technology under the following license:
*
* Copyright (c) 2001 Silver Egg Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sub-license, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*/
/**
* Author:
* Leif Mortenson <leif@tanukisoftware.com>
* Ryan Shaw
*/
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef CUNIT
#include "CUnit/Basic.h"
#endif
#include "wrapper_i18n.h"
#include "wrapperinfo.h"
#include "wrapper.h"
#include "logger.h"
#include "wrapper_file.h"
#ifdef WIN32
#include <direct.h>
#include <winsock.h>
#include <shlwapi.h>
#include <windows.h>
#include <io.h>
/* MS Visual Studio 8 went and deprecated the POXIX names for functions.
* Fixing them all would be a big headache for UNIX versions. */
#pragma warning(disable : 4996)
/* Defines for MS Visual Studio 6 */
#ifndef _INTPTR_T_DEFINED
typedef long intptr_t;
#define _INTPTR_T_DEFINED
#endif
#define EADDRINUSE WSAEADDRINUSE
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTSOCK WSAENOTSOCK
#define ECONNRESET WSAECONNRESET
#else /* UNIX */
#include <ctype.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <pthread.h>
#include <langinfo.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SOCKET int
#define HANDLE int
#define INVALID_HANDLE_VALUE -1
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#if defined(SOLARIS)
#include <sys/errno.h>
#include <sys/fcntl.h>
#elif defined(AIX) || defined(HPUX) || defined(MACOSX) || defined(OSF1)
#elif defined(IRIX)
#define PATH_MAX FILENAME_MAX
#elif defined(FREEBSD) || defined(KFREEBSD)
#include <sys/param.h>
#include <errno.h>
#else /* LINUX */
#include <asm/errno.h>
#endif
/*
* Mac OSX 10.5 does not define the environ variable. This is work around for that.
*/
#ifdef MACOSX
#include <crt_externs.h>
#define environ *_NSGetEnviron();
#endif
extern char** environ;
#endif /* WIN32 */
WrapperConfig *wrapperData;
TCHAR packetBuffer[MAX_LOG_SIZE + 1];
TCHAR *keyChars = TEXT("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
/* Properties structure loaded in from the configuration file. */
Properties *properties;
/* Mutex for syncronization of the tick timer. */
#ifdef WIN32
HANDLE tickMutexHandle = NULL;
#else
pthread_mutex_t tickMutex = PTHREAD_MUTEX_INITIALIZER;
#endif
/* Server Pipe Handles. */
HANDLE protocolActiveServerPipeIn = INVALID_HANDLE_VALUE;
HANDLE protocolActiveServerPipeOut = INVALID_HANDLE_VALUE;
/* Flag for indicating the connected pipes */
int protocolActiveServerPipeConnected = FALSE;
/* Server Socket. */
SOCKET protocolActiveServerSD = INVALID_SOCKET;
/* Client Socket. */
SOCKET protocolActiveBackendSD = INVALID_SOCKET;
int disposed = FALSE;
int loadConfiguration();
#define READ_BUFFER_BLOCK_SIZE 1024
char *wrapperChildWorkBuffer = NULL;
size_t wrapperChildWorkBufferSize = 0;
size_t wrapperChildWorkBufferLen = 0;
time_t wrapperChildWorkLastDataTime = 0;
int wrapperChildWorkLastDataTimeMillis = 0;
/**
* Constructs a tm structure from a pair of Strings like "20091116" and "1514".
* The time returned will be in the local time zone. This is not 100% accurate
* as it doesn't take into account the time zone in which the dates were
* originally set.
*/
struct tm getInfoTime(const TCHAR *date, const TCHAR *time) {
struct tm buildTM;
TCHAR temp[5];
memset(&buildTM, 0, sizeof(struct tm));
/* Year */
_tcsncpy( temp, date, 4 );
temp[4] = 0;
buildTM.tm_year = _ttoi( temp ) - 1900;
/* Month */
_tcsncpy( temp, date + 4, 2 );
temp[2] = 0;
buildTM.tm_mon = _ttoi( temp ) - 1;
/* Day */
_tcsncpy( temp, date + 6, 2 );
temp[2] = 0;
buildTM.tm_mday = _ttoi( temp );
/* Hour */
_tcsncpy( temp, time, 2 );
temp[2] = 0;
buildTM.tm_hour = _ttoi( temp );
/* Minute */
_tcsncpy( temp, time + 2, 2 );
temp[2] = 0;
buildTM.tm_min = _ttoi( temp );
return buildTM;
}
struct tm wrapperGetReleaseTime() {
return getInfoTime(wrapperReleaseDate, wrapperReleaseTime);
}
struct tm wrapperGetBuildTime() {
return getInfoTime(wrapperBuildDate, wrapperBuildTime);
}
/**
* Adds default properties used to set global environment variables.
*
* These are done by setting properties rather than call setEnv directly
* so that it will be impossible for users to override their values by
* creating a "set.XXX=NNN" property in the configuration file.
*/
void wrapperAddDefaultProperties() {
size_t bufferLen;
TCHAR* buffer, *langTemp, *confDirTemp;
#ifdef WIN32
int work, pos2;
TCHAR pathSep = TEXT('\\');
#else
TCHAR pathSep = TEXT('/');
#endif
int pos;
/* IMPORTANT - If any new values are added here, this work buffer length may need to be calculated differently. */
bufferLen = 1;
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_LANG=")) + 3 + 1);
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_PID=")) + 10 + 1); /* 32-bit PID would be max of 10 characters */
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_BITS=")) + _tcslen(wrapperBits) + 1);
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_ARCH=")) + _tcslen(wrapperArch) + 1);
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_OS=")) + _tcslen(wrapperOS) + 1);
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_HOSTNAME=")) + _tcslen(wrapperData->hostName) + 1);
bufferLen = __max(bufferLen, _tcslen(TEXT("set.WRAPPER_HOST_NAME=")) + _tcslen(wrapperData->hostName) + 1);
if (wrapperData->confDir == NULL) {
if (_tcsrchr(wrapperData->argConfFile, pathSep) != NULL) {
pos = (int)(_tcsrchr(wrapperData->argConfFile, pathSep) - wrapperData->argConfFile);
} else {
pos = -1;
}
#ifdef WIN32
if (_tcsrchr(wrapperData->argConfFile, TEXT('/')) != NULL) {
pos2 = (int)(_tcsrchr(wrapperData->argConfFile, TEXT('/')) - wrapperData->argConfFile);
} else {
pos2 = -1;
}
pos = __max(pos, pos2);
#endif
if (pos == -1) {
confDirTemp = malloc(sizeof(TCHAR) * 2);
if (!confDirTemp) {
outOfMemory(TEXT("WADP"), 1);
return;
}
_tcsncpy(confDirTemp, TEXT("."), 2);
} else if (pos == 0) {
confDirTemp = malloc(sizeof(TCHAR) * 2);
if (!confDirTemp) {
outOfMemory(TEXT("WADP"), 2);
return;
}
_sntprintf(confDirTemp, 2, TEXT("%c"), pathSep);
} else {
confDirTemp = malloc(sizeof(TCHAR) * (pos + 1));
if (!confDirTemp) {
outOfMemory(TEXT("WADP"), 3);
return;
}
_tcsncpy(confDirTemp, wrapperData->argConfFile, pos);
confDirTemp[pos] = TEXT('\0');
}
#ifdef WIN32
/* Get buffer size, including '\0' */
work = GetFullPathName(confDirTemp, 0, NULL, NULL);
if (!work) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the conf directory: %s"), getLastErrorText());
free(confDirTemp);
return;
}
wrapperData->confDir = malloc(sizeof(TCHAR) * work);
if (!wrapperData->confDir) {
outOfMemory(TEXT("WADP"), 4);
free(confDirTemp);
return;
}
if (!GetFullPathName(confDirTemp, work, wrapperData->confDir, NULL)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the conf directory: %s"), getLastErrorText());
free(confDirTemp);
return;
}
#else
/* The solaris implementation of realpath will return a relative path if a relative
* path is provided. We always need an abosulte path here. So build up one and
* then use realpath to remove any .. or other relative references. */
wrapperData->confDir = malloc(sizeof(TCHAR) * (PATH_MAX + 1));
if (!wrapperData->confDir) {
outOfMemory(TEXT("WADP"), 5);
free(confDirTemp);
return;
}
if (_trealpath(confDirTemp, wrapperData->confDir) == NULL) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the original working directory: %s"), getLastErrorText());
free(confDirTemp);
return;
}
#endif
setEnv(TEXT("WRAPPER_CONF_DIR"), wrapperData->confDir, ENV_SOURCE_WRAPPER);
free(confDirTemp);
}
buffer = malloc(sizeof(TCHAR) * bufferLen);
if (!buffer) {
outOfMemory(TEXT("WADP"), 1);
return;
}
langTemp = _tgetenv(TEXT("LANG"));
if ((langTemp == NULL) || (_tcslen(langTemp) == 0)) {
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_LANG=en"));
} else {
#ifdef WIN32
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_LANG=%.2s"), langTemp);
#else
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_LANG=%.2S"), langTemp);
#endif
}
#if !defined(WIN32) && defined(UNICODE)
if (langTemp) {
free(langTemp);
}
#endif
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_PID=%d"), wrapperData->wrapperPID);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_BITS=%s"), wrapperBits);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_ARCH=%s"), wrapperArch);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_OS=%s"), wrapperOS);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_HOSTNAME=%s"), wrapperData->hostName);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
_sntprintf(buffer, bufferLen, TEXT("set.WRAPPER_HOST_NAME=%s"), wrapperData->hostName);
addPropertyPair(properties, NULL, 0, buffer, TRUE, FALSE, TRUE);
#ifdef WIN32
addPropertyPair(properties, NULL, 0, TEXT("set.WRAPPER_FILE_SEPARATOR=\\"), TRUE, FALSE, TRUE);
addPropertyPair(properties, NULL, 0, TEXT("set.WRAPPER_PATH_SEPARATOR=;"), TRUE, FALSE, TRUE);
#else
addPropertyPair(properties, NULL, 0, TEXT("set.WRAPPER_FILE_SEPARATOR=/"), TRUE, FALSE, TRUE);
addPropertyPair(properties, NULL, 0, TEXT("set.WRAPPER_PATH_SEPARATOR=:"), TRUE, FALSE, TRUE);
#endif
free(buffer);
}
/**
* This function is here to help Community Edition users who are attempting
* to generate a hostId.
*/
int showHostIds(int logLevel) {
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT("The Community Edition of the Java Service Wrapper does not implement\nHostIds."));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT("If you have requested a trial license, or purchased a license, you\nmay be looking for the Standard or Professional Editions of the Java\nService Wrapper. They can be downloaded here:"));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(" http://wrapper.tanukisoftware.com/download"));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(""));
return FALSE;
}
/**
* Loads the current environment into a table so we can debug it later.
*
* @return TRUE if there were problems, FALSE if successful.
*/
int loadEnvironment() {
size_t len;
TCHAR *sourcePair;
TCHAR *pair;
TCHAR *equal;
TCHAR *name;
TCHAR *value;
#ifdef WIN32
LPTCH lpvEnv;
LPTSTR lpszVariable;
#else
/* The compiler won't let us reverence environ directly in the for loop on OSX because it is actually a function. */
char **environment = environ;
int i;
#endif
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Loading Environment..."));
#endif
#ifdef WIN32
lpvEnv = GetEnvironmentStrings();
if (!lpvEnv)
{
_tprintf(TEXT("GetEnvironmentStrings failed (%s)\n"), getLastErrorText());
return TRUE;
}
lpszVariable = (LPTSTR)lpvEnv;
while (lpszVariable[0] != '\0') {
sourcePair = lpszVariable;
#else
i = 0;
while (environment[i]) {
len = mbstowcs(NULL, environment[i], 0);
if (len == (size_t)-1) {
/* Invalid string. Skip. */
} else {
sourcePair = malloc(sizeof(TCHAR) * (len + 1));
if (!sourcePair) {
outOfMemory(TEXT("LE"), 1);
_tprintf(TEXT(" Invalid character string: %s (%s)\n"), environment[i], getLastErrorText());
return TRUE;
}
mbstowcs(sourcePair, environment[i], len + 1);
#endif
len = _tcslen(sourcePair);
/* We need a copy of the variable pair so we can split it. */
pair = malloc(sizeof(TCHAR) * (len + 1));
if (!pair) {
outOfMemory(TEXT("LE"), 1);
#ifndef WIN32
free(sourcePair);
#endif
return TRUE;
}
_sntprintf(pair, len + 1, TEXT("%s"), sourcePair);
equal = _tcschr(pair, TEXT('='));
if (equal) {
name = pair;
value = &(equal[1]);
equal[0] = TEXT('\0');
if (_tcslen(name) <= 0) {
name = NULL;
}
if (_tcslen(value) <= 0) {
value = NULL;
}
/* It is possible that the name was empty. */
if (name) {
setEnv(name, value, ENV_SOURCE_PARENT);
}
}
free(pair);
#ifdef WIN32
lpszVariable += len + 1;
#else
free(sourcePair);
}
i++;
#endif
}
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Loading Environment complete."));
#endif
return FALSE;
}
/**
* Updates a string value by making a copy of the original. Any old value is
* first freed.
*/
void updateStringValue(TCHAR **ptr, const TCHAR *value) {
if (*ptr != NULL) {
free(*ptr);
*ptr = NULL;
}
if (value != NULL) {
*ptr = malloc(sizeof(TCHAR) * (_tcslen(value) + 1));
if (!(*ptr)) {
outOfMemory(TEXT("USV"), 1);
/* TODO: This is pretty bad. Not sure how to recover... */
} else {
_tcsncpy(*ptr, value, _tcslen(value) + 1);
}
}
}
#ifndef WIN32 /* UNIX */
int getSignalMode(const TCHAR *modeName, int defaultMode) {
if (!modeName) {
return defaultMode;
}
if (strcmpIgnoreCase(modeName, TEXT("IGNORE")) == 0) {
return WRAPPER_SIGNAL_MODE_IGNORE;
} else if (strcmpIgnoreCase(modeName, TEXT("RESTART")) == 0) {
return WRAPPER_SIGNAL_MODE_RESTART;
} else if (strcmpIgnoreCase(modeName, TEXT("SHUTDOWN")) == 0) {
return WRAPPER_SIGNAL_MODE_SHUTDOWN;
} else if (strcmpIgnoreCase(modeName, TEXT("FORWARD")) == 0) {
return WRAPPER_SIGNAL_MODE_FORWARD;
} else {
return defaultMode;
}
}
/**
* Return FALSE if successful, TRUE if there were problems.
*/
int wrapperBuildUnixDaemonInfo() {
if (!wrapperData->configured) {
/** Get the daemonize flag. */
wrapperData->daemonize = getBooleanProperty(properties, TEXT("wrapper.daemonize"), FALSE);
/** Configure the HUP signal handler. */
wrapperData->signalHUPMode = getSignalMode(getStringProperty(properties, TEXT("wrapper.signal.mode.hup"), NULL), WRAPPER_SIGNAL_MODE_FORWARD);
/** Configure the USR1 signal handler. */
wrapperData->signalUSR1Mode = getSignalMode(getStringProperty(properties, TEXT("wrapper.signal.mode.usr1"), NULL), WRAPPER_SIGNAL_MODE_FORWARD);
/** Configure the USR2 signal handler. */
wrapperData->signalUSR2Mode = getSignalMode(getStringProperty(properties, TEXT("wrapper.signal.mode.usr2"), NULL), WRAPPER_SIGNAL_MODE_FORWARD);
}
return FALSE;
}
#endif
/**
* Dumps the table of environment variables, and their sources.
*
* @param logLevel Level at which to log the output.
*/
void dumpEnvironment(int logLevel) {
EnvSrc *envSrc;
TCHAR *envVal;
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT("Environment variables (Source | Name=Value) BEGIN:"));
envSrc = baseEnvSrc;
while (envSrc) {
envVal = _tgetenv(envSrc->name);
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(" %c%c%c%c%c | %s=%s"),
(envSrc->source & ENV_SOURCE_PARENT ? TEXT('P') : TEXT('-')),
#ifdef WIN32
(envSrc->source & ENV_SOURCE_REG_SYSTEM ? TEXT('S') : TEXT('-')),
(envSrc->source & ENV_SOURCE_REG_ACCOUNT ? TEXT('A') : TEXT('-')),
#else
TEXT('-'),
TEXT('-'),
#endif
(envSrc->source & ENV_SOURCE_WRAPPER ? TEXT('W') : TEXT('-')),
(envSrc->source & ENV_SOURCE_CONFIG ? TEXT('C') : TEXT('-')),
envSrc->name,
(envVal ? envVal : TEXT("<null>"))
);
#if !defined(WIN32) && defined(UNICODE)
if (envVal) {
free(envVal);
}
#endif
envSrc = envSrc->next;
}
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT("Environment variables END:"));
log_printf(WRAPPER_SOURCE_WRAPPER, logLevel, TEXT(""));
}
void wrapperLoadLoggingProperties(int preload) {
const TCHAR *logfilePath;
int logfileRollMode;
setLogPropertyWarnings(properties, !preload);
setLogPropertyWarningLogLevel(properties, getLogLevelForName(getStringProperty(properties, TEXT("wrapper.property_warning.loglevel"), TEXT("WARN"))));
setLogWarningThreshold(getIntProperty(properties, TEXT("wrapper.log.warning.threshold"), 0));
wrapperData->logLFDelayThreshold = propIntMax(propIntMin(getIntProperty(properties, TEXT("wrapper.log.lf_delay.threshold"), 500), 3600000), 0);
logfilePath = getFileSafeStringProperty(properties, TEXT("wrapper.logfile"), TEXT("wrapper.log"));
setLogfilePath(logfilePath, wrapperData->workingDir, preload);
logfileRollMode = getLogfileRollModeForName(getStringProperty(properties, TEXT("wrapper.logfile.rollmode"), TEXT("SIZE")));
if (logfileRollMode == ROLL_MODE_UNKNOWN) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.logfile.rollmode invalid. Disabling log file rolling."));
logfileRollMode = ROLL_MODE_NONE;
} else if (logfileRollMode == ROLL_MODE_DATE) {
if (!_tcsstr(logfilePath, ROLL_MODE_DATE_TOKEN)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.logfile must contain \"%s\" for a roll mode of DATE. Disabling log file rolling."),
ROLL_MODE_DATE_TOKEN);
logfileRollMode = ROLL_MODE_NONE;
}
}
setLogfileRollMode(logfileRollMode);
/* Load log file format */
setLogfileFormat(getStringProperty(properties, TEXT("wrapper.logfile.format"), LOG_FORMAT_LOGFILE_DEFAULT));
/* Load log file log level */
setLogfileLevel(getStringProperty(properties, TEXT("wrapper.logfile.loglevel"), TEXT("INFO")));
/* Load max log filesize log level */
setLogfileMaxFileSize(getStringProperty(properties, TEXT("wrapper.logfile.maxsize"), TEXT("0")));
/* Load log files level */
setLogfileMaxLogFiles(getIntProperty(properties, TEXT("wrapper.logfile.maxfiles"), 0));
/* Load log file purge pattern */
setLogfilePurgePattern(getFileSafeStringProperty(properties, TEXT("wrapper.logfile.purge.pattern"), TEXT("")));
/* Load log file purge sort */
setLogfilePurgeSortMode(wrapperFileGetSortMode(getStringProperty(properties, TEXT("wrapper.logfile.purge.sort"), TEXT("TIMES"))));
/* Get the close timeout. */
wrapperData->logfileCloseTimeout = propIntMax(propIntMin(getIntProperty(properties, TEXT("wrapper.logfile.close.timeout"), getIntProperty(properties, TEXT("wrapper.logfile.inactivity.timeout"), 1)), 3600), -1);
setLogfileAutoClose(wrapperData->logfileCloseTimeout == 0);
/* Get the flush timeout. */
wrapperData->logfileFlushTimeout = propIntMax(propIntMin(getIntProperty(properties, TEXT("wrapper.logfile.flush.timeout"), 1), 3600), 0);
setLogfileAutoFlush(wrapperData->logfileFlushTimeout == 0);
/* Load console format */
setConsoleLogFormat(getStringProperty(properties, TEXT("wrapper.console.format"), LOG_FORMAT_CONSOLE_DEFAULT));
setConsoleLogLevel(getStringProperty(properties, TEXT("wrapper.console.loglevel"), TEXT("INFO")));
/* Load the console flush flag. */
setConsoleFlush(getBooleanProperty(properties, TEXT("wrapper.console.flush"), FALSE));
#ifdef WIN32
/* Load the console direct flag. */
setConsoleDirect(getBooleanProperty(properties, TEXT("wrapper.console.direct"), TRUE));
#endif
/* Load the console loglevel targets. */
setConsoleFatalToStdErr(getBooleanProperty(properties, TEXT("wrapper.console.fatal_to_stderr"), TRUE));
setConsoleErrorToStdErr(getBooleanProperty(properties, TEXT("wrapper.console.error_to_stderr"), TRUE));
setConsoleWarnToStdErr(getBooleanProperty(properties, TEXT("wrapper.console.warn_to_stderr"), FALSE));
/* Load syslog log level */
setSyslogLevel(getStringProperty(properties, TEXT("wrapper.syslog.loglevel"), TEXT("NONE")));
#ifndef WIN32
/* Load syslog facility */
setSyslogFacility(getStringProperty(properties, TEXT("wrapper.syslog.facility"), TEXT("USER")));
#endif
/* Load syslog event source name */
setSyslogEventSourceName(getStringProperty(properties, TEXT("wrapper.syslog.ident"), getStringProperty(properties, TEXT("wrapper.name"), getStringProperty(properties, TEXT("wrapper.ntservice.name"), TEXT("wrapper")))));
/* Register the syslog message file if syslog is enabled */
if (getSyslogLevelInt() < LEVEL_NONE) {
registerSyslogMessageFile();
}
/* Get the debug status (Property is deprecated but flag is still used) */
wrapperData->isDebugging = getBooleanProperty(properties, TEXT("wrapper.debug"), FALSE);
if (wrapperData->isDebugging) {
/* For backwards compatability */
setConsoleLogLevelInt(LEVEL_DEBUG);
setLogfileLevelInt(LEVEL_DEBUG);
} else {
if (getLowLogLevel() <= LEVEL_DEBUG) {
wrapperData->isDebugging = TRUE;
}
}
}
/**
* Load the configuration.
*
* @param preload TRUE if the configuration is being preloaded.
*
* Return TRUE if there were any problems.
*/
int wrapperLoadConfigurationProperties(int preload) {
int i;
int firstCall;
#ifdef WIN32
int work;
int defaultUMask;
#else
mode_t defaultUMask;
#endif
const TCHAR* prop;
/* Unless this is the first call, we need to dispose the previous properties object. */
if (properties) {
firstCall = FALSE;
disposeProperties(properties);
properties = NULL;
} else {
firstCall = TRUE;
if (wrapperData->originalWorkingDir) {
free(wrapperData->originalWorkingDir);
}
/* This is the first time, so preserve the working directory. */
#ifdef WIN32
/* Get buffer size, including '\0' */
work = GetFullPathName(TEXT("."), 0, NULL, NULL);
if (!work) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the original working directory: %s"), getLastErrorText());
return TRUE;
}
wrapperData->originalWorkingDir = malloc(sizeof(TCHAR) * work);
if (!wrapperData->originalWorkingDir) {
outOfMemory(TEXT("WLCP"), 3);
return TRUE;
}
if (!GetFullPathName(TEXT("."), work, wrapperData->originalWorkingDir, NULL)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the original working directory: %s"), getLastErrorText());
return TRUE;
}
#else
/* The solaris implementation of realpath will return a relative path if a relative
* path is provided. We always need an abosulte path here. So build up one and
* then use realpath to remove any .. or other relative references. */
wrapperData->originalWorkingDir = malloc(sizeof(TCHAR) * (PATH_MAX + 1));
if (!wrapperData->originalWorkingDir) {
outOfMemory(TEXT("WLCP"), 4);
return TRUE;
}
if (_trealpath(TEXT("."), wrapperData->originalWorkingDir) == NULL) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the original working directory: %s"), getLastErrorText());
return TRUE;
}
#endif
if (wrapperData->configFile) {
free(wrapperData->configFile);
}
/* This is the first time, so preserve the full canonical location of the
* configuration file. */
#ifdef WIN32
work = GetFullPathName(wrapperData->argConfFile, 0, NULL, NULL);
if (!work) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the full path of the configuration file, %s: %s"),
wrapperData->argConfFile, getLastErrorText());
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Current working directory is: %s"), wrapperData->originalWorkingDir);
return TRUE;
}
wrapperData->configFile = malloc(sizeof(TCHAR) * work);
if (!wrapperData->configFile) {
outOfMemory(TEXT("WLCP"), 1);
return TRUE;
}
if (!GetFullPathName(wrapperData->argConfFile, work, wrapperData->configFile, NULL)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the full path of the configuration file, %s: %s"),
wrapperData->argConfFile, getLastErrorText());
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT(
"Current working directory is: %s"), wrapperData->originalWorkingDir);
return TRUE;
}
#else
/* The solaris implementation of realpath will return a relative path if a relative
* path is provided. We always need an abosulte path here. So build up one and
* then use realpath to remove any .. or other relative references. */
wrapperData->configFile = malloc(sizeof(TCHAR) * (PATH_MAX + 1));
if (!wrapperData->configFile) {
outOfMemory(TEXT("WLCP"), 2);
return TRUE;
}
if (_trealpath(wrapperData->argConfFile, wrapperData->configFile) == NULL) {
/* Most likely the file does not exist. The wrapperData->configFile has the first
* file that could not be found. May not be the config file directly if symbolic
* links are involved. */
if (wrapperData->argConfFileDefault) {
/* The output buffer is likely to contain undefined data.
* To be on the safe side and in order to report the error
* below correctly we need to override the data first.*/
_sntprintf(wrapperData->configFile, PATH_MAX + 1, TEXT("%s"), wrapperData->argConfFile);
/* This was the default config file name. We know that the working directory
* could be resolved so the problem must be that the default config file does
* not exist. This problem will be reported later and the wrapperData->configFile
* variable will have the correct full path.
* Fall through for now and the user will get a better error later. */
} else {
if (!preload) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT(
"Unable to open configuration file: %s (%s)\n Current working directory: %s"),
wrapperData->argConfFile, getLastErrorText(), wrapperData->originalWorkingDir);
}
return TRUE;
}
}
#endif
}
/* Create a Properties structure. */
properties = createProperties();
if (!properties) {
return TRUE;
}
setLogPropertyWarnings(properties, !preload);
wrapperAddDefaultProperties();
/* The argument prior to the argBase will be the configuration file, followed
* by 0 or more command line properties. The command line properties need to be
* loaded first, followed by the configuration file. */
if (strcmpIgnoreCase(wrapperData->argCommand, TEXT("-translate")) != 0) {
for (i = 0; i < wrapperData->argCount; i++) {
if (addPropertyPair(properties, NULL, 0, wrapperData->argValues[i], TRUE, TRUE, FALSE)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("The argument '%s' is not a valid property name-value pair."),
wrapperData->argValues[i]);
return TRUE;
}
}
}
/* Now load the configuration file.
* When this happens, the working directory MUST be set to the original working dir. */
#ifdef WIN32
if (loadProperties(properties, wrapperData->configFile, preload)) {
#else
if (loadProperties(properties, wrapperData->configFile, (preload | wrapperData->daemonize))) {
#endif
/* File not found. */
/* If this was a default file name then we don't want to show this as
* an error here. It will be handled by the caller. */
/* Debug is not yet available as the config file is not yet loaded. */
if ((!preload) && (!wrapperData->argConfFileDefault)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Failed to load configuration: %s"), wrapperData->configFile);
}
return TRUE;
}
/* Config file found. */
wrapperData->argConfFileFound = TRUE;
if (firstCall) {
/* If the working dir was configured, we need to extract it and preserve its value.
* This must be done after the configuration has been completely loaded. */
prop = getStringProperty(properties, TEXT("wrapper.working.dir"), TEXT("."));
if (prop && (_tcslen(prop) > 0)) {
if (wrapperData->workingDir) {
free(wrapperData->workingDir);
}
#ifdef WIN32
work = GetFullPathName(prop, 0, NULL, NULL);
if (!work) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the working directory %s: %s"), prop, getLastErrorText());
return TRUE;
}
wrapperData->workingDir = malloc(sizeof(TCHAR) * work);
if (!wrapperData->workingDir) {
outOfMemory(TEXT("WLCP"), 5);
return TRUE;
}
if (!GetFullPathName(prop, work, wrapperData->workingDir, NULL)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the working directory %s: %s"), prop, getLastErrorText());
return TRUE;
}
#else
/* The solaris implementation of realpath will return a relative path if a relative
* path is provided. We always need an abosulte path here. So build up one and
* then use realpath to remove any .. or other relative references. */
wrapperData->workingDir = malloc(sizeof(TCHAR) * (PATH_MAX + 1));
if (!wrapperData->workingDir) {
outOfMemory(TEXT("WLCP"), 6);
return TRUE;
}
if (_trealpath(prop, wrapperData->workingDir) == NULL) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to resolve the working directory %s: %s"), prop, getLastErrorText());
return TRUE;
}
#endif
}
}
#ifdef _DEBUG
/* Display the active properties */
_tprintf(TEXT("Debug Configuration Properties:\n"));
dumpProperties(properties);
#endif
/* Now that the configuration is loaded, we need to update the working directory if the user specified one.
* This must be done now so that anything that references the working directory, including the log file
* and language pack locations will work correctly. */
if (wrapperData->workingDir && wrapperSetWorkingDir(wrapperData->workingDir, !preload)) {
return TRUE;
}
if (wrapperData->umask == -1) {
/** Get the umask value for the various files. */
#ifdef WIN32
defaultUMask = _umask(0);
_umask(defaultUMask);
#else
defaultUMask = umask((mode_t)0);
umask(defaultUMask);
#endif
wrapperData->umask = getIntProperty(properties, TEXT("wrapper.umask"), defaultUMask);
}
wrapperData->javaUmask = getIntProperty(properties, TEXT("wrapper.java.umask"), wrapperData->umask);
wrapperData->pidFileUmask = getIntProperty(properties, TEXT("wrapper.pidfile.umask"), wrapperData->umask);
wrapperData->lockFileUmask = getIntProperty(properties, TEXT("wrapper.lockfile.umask"), wrapperData->umask);
wrapperData->javaPidFileUmask = getIntProperty(properties, TEXT("wrapper.java.pidfile.umask"), wrapperData->umask);
wrapperData->javaIdFileUmask = getIntProperty(properties, TEXT("wrapper.java.idfile.umask"), wrapperData->umask);
wrapperData->statusFileUmask = getIntProperty(properties, TEXT("wrapper.statusfile.umask"), wrapperData->umask);
wrapperData->javaStatusFileUmask = getIntProperty(properties, TEXT("wrapper.java.statusfile.umask"), wrapperData->umask);
wrapperData->anchorFileUmask = getIntProperty(properties, TEXT("wrapper.anchorfile.umask"), wrapperData->umask);
setLogfileUmask(getIntProperty(properties, TEXT("wrapper.logfile.umask"), wrapperData->umask));
#ifndef WIN32
/** If in the first call here and the wrapper will deamonize, then we don't need
* to proceed any further anymore as the properties will be loaded properly at
* the second time...
*/
if ((firstCall == TRUE) && (!wrapperBuildUnixDaemonInfo()) && wrapperData->daemonize) {
return FALSE;
}
#endif
/* Load the configuration. */
if ((strcmpIgnoreCase(wrapperData->argCommand, TEXT("-translate")) != 0) && loadConfiguration()) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Problem loading wrapper configuration file: %s"), wrapperData->configFile);
return TRUE;
}
return FALSE;
}
void wrapperGetCurrentTime(struct timeb *timeBuffer) {
#ifdef WIN32
ftime(timeBuffer);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
timeBuffer->time = (time_t)tv.tv_sec;
timeBuffer->millitm = (unsigned short)(tv.tv_usec / 1000);
#endif
}
/**
* This function stops the pipes (quite in a brutal way)
*/
void protocolStopServerPipe() {
if (protocolActiveServerPipeIn != INVALID_HANDLE_VALUE) {
#ifdef WIN32
CloseHandle(protocolActiveServerPipeIn);
#else
close(protocolActiveServerPipeIn);
#endif
protocolActiveServerPipeIn = INVALID_HANDLE_VALUE;
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_INFO, TEXT("backend pipe closed."));
}
if (protocolActiveServerPipeOut != INVALID_HANDLE_VALUE) {
#ifdef WIN32
CloseHandle(protocolActiveServerPipeOut);
#else
close(protocolActiveServerPipeOut);
#endif
protocolActiveServerPipeOut = INVALID_HANDLE_VALUE;
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_INFO, TEXT("backend pipe closed."));
}
}
void protocolStopServerSocket() {
int rc;
/* Close the socket. */
if (protocolActiveServerSD != INVALID_SOCKET) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("closing backend server."));
}
#ifdef WIN32
rc = closesocket(protocolActiveServerSD);
#else /* UNIX */
rc = close(protocolActiveServerSD);
#endif
if (rc == SOCKET_ERROR) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("server socket close failed. (%d)"), wrapperGetLastError());
}
}
protocolActiveServerSD = INVALID_SOCKET;
}
wrapperData->actualPort = 0;
}
void protocolStopServer() {
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
protocolStopServerPipe();
} else {
protocolStopServerSocket();
}
}
int protocolActiveServerPipeStarted = FALSE;
void protocolStartServerPipe() {
size_t pipeNameLen;
TCHAR *pipeName;
#ifdef WIN32
pipeNameLen = 17 + 10 + 1 + 10 + 3;
#else
pipeNameLen = 12 + 10 + 1 + 10 + 3;
#endif
pipeName = malloc(sizeof(TCHAR) * (pipeNameLen + 1));
if (!pipeName) {
outOfMemory(TEXT("PSSP"), 1);
return;
}
#ifdef WIN32
_sntprintf(pipeName, pipeNameLen, TEXT("\\\\.\\pipe\\wrapper-%d-%d-out"), wrapperData->wrapperPID, wrapperData->jvmRestarts + 1);
if ((protocolActiveServerPipeOut = CreateNamedPipe(pipeName,
PIPE_ACCESS_OUTBOUND,/* + FILE_FLAG_FIRST_PIPE_INSTANCE, */
PIPE_TYPE_MESSAGE | /* message type pipe */
PIPE_READMODE_MESSAGE | /* message-read mode */
PIPE_NOWAIT, /* nonblocking mode */
1, /* only allow 1 connection at a time */
32768,
32768,
0,
NULL)) == INVALID_HANDLE_VALUE) {
#else
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-out"), wrapperData->wrapperPID, wrapperData->jvmRestarts + 1);
if (_tmkfifo(pipeName, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == INVALID_HANDLE_VALUE) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT("Unable to create backend pipe: %s"), getLastErrorText());
free(pipeName);
return;
}
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("server listening on pipe %s."), pipeName);
}
#ifdef WIN32
_sntprintf(pipeName, pipeNameLen, TEXT("\\\\.\\pipe\\wrapper-%d-%d-in"), wrapperData->wrapperPID, wrapperData->jvmRestarts + 1);
if ((protocolActiveServerPipeIn = CreateNamedPipe(pipeName,
PIPE_ACCESS_INBOUND,/* + FILE_FLAG_FIRST_PIPE_INSTANCE,*/
PIPE_TYPE_MESSAGE | /* message type pipe */
PIPE_READMODE_MESSAGE | /* message-read mode*/
PIPE_NOWAIT, /* nonblocking mode*/
1,
32768,
32768,
0,
NULL)) == INVALID_HANDLE_VALUE) {
#else
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-in"), wrapperData->wrapperPID, wrapperData->jvmRestarts + 1);
if (_tmkfifo(pipeName, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == INVALID_HANDLE_VALUE) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT("Unable to create backend pipe: %s"), getLastErrorText());
free(pipeName);
return;
}
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("server listening on pipe %s."), pipeName);
}
protocolActiveServerPipeStarted = TRUE;
free(pipeName);
}
void protocolStartServerSocket() {
struct sockaddr_in addr_srv;
int rc;
int port;
int fixedPort;
#ifdef UNICODE
char* tempAddress;
size_t len;
#endif
/*int optVal;*/
#ifdef WIN32
u_long dwNoBlock = TRUE;
#endif
/* Create the server socket. */
protocolActiveServerSD = socket(AF_INET, SOCK_STREAM, 0);
if (protocolActiveServerSD == INVALID_SOCKET) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR,
TEXT("server socket creation failed. (%s)"), getLastErrorText());
return;
}
/* Make sure the socket is reused. */
/* We actually do not want to do this as it makes it possible for more than one Wrapper
* instance to bind to the same port. The second instance succeeds to bind, but any
* attempts to connect to that port will go to the first Wrapper. This would of course
* cause attempts to launch the second JVM to fail.
* Leave this code here as a future development note.
optVal = 1;
#ifdef WIN32
if (setsockopt(protocolActiveServerSD, SOL_SOCKET, SO_REUSEADDR, (TCHAR *)&optVal, sizeof(optVal)) < 0) {
#else
if (setsockopt(protocolActiveServerSD, SOL_SOCKET, SO_REUSEADDR, &optVal, sizeof(optVal)) < 0) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR,
"server socket SO_REUSEADDR failed. (%s)", getLastErrorText());
wrapperProtocolClose();
protocolStopServer();
return;
}
*/
/* Make the socket non-blocking */
#ifdef WIN32
rc = ioctlsocket(protocolActiveServerSD, FIONBIO, &dwNoBlock);
#else /* UNIX */
rc = fcntl(protocolActiveServerSD, F_SETFL, O_NONBLOCK);
#endif
if (rc == SOCKET_ERROR) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR,
TEXT("server socket ioctlsocket failed. (%s)"), getLastErrorText());
wrapperProtocolClose();
protocolStopServer();
return;
}
/* If a port was specified in the configuration file then we want to
* try to use that port or find the next available port. If 0 was
* specified, then we will silently start looking for an available
* port starting at 32000. */
port = wrapperData->port;
if (port <= 0) {
port = wrapperData->portMin;
fixedPort = FALSE;
} else {
fixedPort = TRUE;
}
tryagain:
/* Try binding to the port. */
/*log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_STATUS, TEXT("Trying port %d"), port);*/
/* Cleanup the addr_srv first */
memset(&addr_srv, 0, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
if (wrapperData->portAddress == NULL) {
addr_srv.sin_addr.s_addr = inet_addr("127.0.0.1");
} else {
#ifdef UNICODE
#ifdef WIN32
len = WideCharToMultiByte(CP_OEMCP, 0, wrapperData->portAddress, -1, NULL, 0, NULL, NULL);
if (len <= 0) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN,
TEXT("Invalid multibyte sequence in port address \"%s\" : %s"), wrapperData->portAddress, getLastErrorText());
return;
}
tempAddress = malloc(len);
if (!tempAddress) {
outOfMemory(TEXT("PSSS"), 1);
return;
}
WideCharToMultiByte(CP_OEMCP, 0, wrapperData->portAddress, -1, tempAddress, (int)len, NULL, NULL);
#else
len = wcstombs(NULL, wrapperData->portAddress, 0) + 1;
_tprintf(TEXT("%d hanth %s\n"), len, wrapperData->portAddress);
if (len == (size_t)-1) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN,
TEXT("Invalid multibyte sequence in port address \"%s\" : %s"), wrapperData->portAddress, getLastErrorText());
return;
}
tempAddress = malloc(len);
if (!tempAddress) {
outOfMemory(TEXT("PSSS"), 2);
return;
}
wcstombs(tempAddress, wrapperData->portAddress, len);
_tprintf(TEXT("%d hanth % s\n"), len, tempAddress);
#endif
addr_srv.sin_addr.s_addr = inet_addr(tempAddress);
free(tempAddress);
#else
addr_srv.sin_addr.s_addr = inet_addr(wrapperData->portAddress);
#endif
}
addr_srv.sin_port = htons((u_short)port);
#ifdef WIN32
rc = bind(protocolActiveServerSD, (struct sockaddr FAR *)&addr_srv, sizeof(addr_srv));
#else /* UNIX */
rc = bind(protocolActiveServerSD, (struct sockaddr *)&addr_srv, sizeof(addr_srv));
#endif
if (rc == SOCKET_ERROR) {
rc = wrapperGetLastError();
/* The specified port could bot be bound. */
if (rc == EADDRINUSE ||
#ifdef WIN32
rc == WSAEACCES) {
#else
rc == EACCES) {
#endif
/* Address in use, try looking at the next one. */
if (fixedPort) {
/* The last port checked was the defined fixed port, switch to the dynamic range. */
port = wrapperData->portMin;
fixedPort = FALSE;
goto tryagain;
} else {
port++;
if (port <= wrapperData->portMax) {
goto tryagain;
}
}
}
/* Log an error. This is fatal, so die. */
if (wrapperData->port <= 0) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_FATAL,
TEXT("unable to bind listener to any port in the range %d to %d. (%s)"),
wrapperData->portMin, wrapperData->portMax, getLastErrorText());
} else {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_FATAL,
TEXT("unable to bind listener port %d, or any port in the range %d to %d. (%s)"),
wrapperData->port, wrapperData->portMin, wrapperData->portMax, getLastErrorText());
}
wrapperStopProcess(getLastError(), TRUE);
wrapperProtocolClose();
protocolStopServer();
wrapperData->exitRequested = TRUE;
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_NO;
return;
}
/* If we got here, then we are bound to the port */
if ((wrapperData->port > 0) && (port != wrapperData->port)) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_INFO, TEXT("port %d already in use, using port %d instead."), wrapperData->port, port);
}
wrapperData->actualPort = port;
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("server listening on port %d."), wrapperData->actualPort);
}
/* Tell the socket to start listening. */
rc = listen(protocolActiveServerSD, 1);
if (rc == SOCKET_ERROR) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT("server socket listen failed. (%d)"), wrapperGetLastError());
wrapperProtocolClose();
protocolStopServer();
return;
}
}
void protocolStartServer() {
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
protocolStartServerPipe();
} else {
protocolStartServerSocket();
}
}
/* this functions connects the pipes once the other end is there */
void protocolOpenPipe() {
#ifdef WIN32
int result;
result = ConnectNamedPipe(protocolActiveServerPipeOut, NULL);
if (GetLastError() == ERROR_PIPE_LISTENING) {
return;
}
result = ConnectNamedPipe(protocolActiveServerPipeIn, NULL);
if (GetLastError() == ERROR_PIPE_LISTENING) {
return;
}
if ((result == 0) && (GetLastError() != ERROR_PIPE_CONNECTED) && (GetLastError() != ERROR_NO_DATA)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Pipe connect failed: %s"), getLastErrorText());
return;
}
#else
size_t pipeNameLen;
TCHAR *pipeName;
pipeNameLen = 12 + 10 + 1 + 10 + 3;
pipeName = malloc(sizeof(TCHAR) * (pipeNameLen + 1));
if (!pipeName) {
outOfMemory(TEXT("PSSP"), 1);
return;
}
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-out"), wrapperData->wrapperPID, wrapperData->jvmRestarts);
protocolActiveServerPipeOut = _topen(pipeName, O_WRONLY | O_NONBLOCK, S_IWUSR | S_IRUSR);
if (protocolActiveServerPipeOut == INVALID_HANDLE_VALUE) {
free(pipeName);
return;
}
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-in"), wrapperData->wrapperPID, wrapperData->jvmRestarts);
protocolActiveServerPipeIn = _topen(pipeName, O_RDONLY | O_NONBLOCK, S_IRUSR);
if (protocolActiveServerPipeIn == INVALID_HANDLE_VALUE) {
free(pipeName);
return;
}
free(pipeName);
#endif
protocolActiveServerPipeConnected = TRUE;
}
void protocolOpenSocket() {
struct sockaddr_in addr_srv;
int rc;
#if defined(WIN32)
u_long dwNoBlock = TRUE;
u_long addr_srv_len;
#elif (defined(HPUX) && !defined(ARCH_IA)) || defined(OSF1) || defined(IRIX)
int addr_srv_len;
#else
socklen_t addr_srv_len;
#endif
SOCKET newBackendSD = INVALID_SOCKET;
/* Is the server socket open? */
if (protocolActiveServerSD == INVALID_SOCKET) {
/* can't do anything yet. */
return;
}
/* Try accepting a socket. */
addr_srv_len = sizeof(addr_srv);
#ifdef WIN32
newBackendSD = accept(protocolActiveServerSD, (struct sockaddr FAR *)&addr_srv, &addr_srv_len);
#else /* UNIX */
newBackendSD = accept(protocolActiveServerSD, (struct sockaddr *)&addr_srv, &addr_srv_len);
#endif
if (newBackendSD == INVALID_SOCKET) {
rc = wrapperGetLastError();
/* EWOULDBLOCK != EAGAIN on some platforms. */
if ((rc == EWOULDBLOCK) || (rc == EAGAIN)) {
/* There are no incomming sockets right now. */
return;
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG,
TEXT("socket creation failed. (%s)"), getLastErrorText());
}
return;
}
}
/* Is it already open? */
if (protocolActiveBackendSD != INVALID_SOCKET) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN, TEXT("Ignoring unexpected backend socket connection from %s on port %d"),
(char *)inet_ntoa(addr_srv.sin_addr), ntohs(addr_srv.sin_port));
#ifdef WIN32
rc = closesocket(newBackendSD);
#else /* UNIX */
rc = close(newBackendSD);
#endif
if (rc == SOCKET_ERROR) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("socket close failed. (%d)"), wrapperGetLastError());
}
}
return;
}
/* New connection, so continue. */
protocolActiveBackendSD = newBackendSD;
if (wrapperData->isDebugging) {
#ifdef UNICODE
TCHAR* socketSource;
int req;
#ifdef WIN32
req = MultiByteToWideChar(CP_OEMCP, 0, inet_ntoa(addr_srv.sin_addr), -1, NULL, 0);
socketSource = malloc(sizeof(TCHAR) * (req + 1));
if (!socketSource) {
outOfMemory(TEXT("PO"), 1);
return;
}
MultiByteToWideChar(CP_OEMCP, 0, inet_ntoa(addr_srv.sin_addr), -1, socketSource, req + 1);
#else
req = mbstowcs(NULL, inet_ntoa(addr_srv.sin_addr), 0);
socketSource = malloc(sizeof(TCHAR) * (req + 1));
if (!socketSource) {
outOfMemory(TEXT("PO"), 2);
return;
}
mbstowcs(socketSource, inet_ntoa(addr_srv.sin_addr), req + 1);
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("accepted a socket from %s on port %d"),
socketSource, ntohs(addr_srv.sin_port));
free(socketSource);
#else
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("accepted a socket from %s on port %d"),
inet_ntoa(addr_srv.sin_addr), ntohs(addr_srv.sin_port));
#endif
}
/* Make the socket non-blocking */
#ifdef WIN32
rc = ioctlsocket(protocolActiveBackendSD, FIONBIO, &dwNoBlock);
#else /* UNIX */
rc = fcntl(protocolActiveBackendSD, F_SETFL, O_NONBLOCK);
#endif
if (rc == SOCKET_ERROR) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG,
TEXT("socket ioctlsocket failed. (%s)"), getLastErrorText());
}
wrapperProtocolClose();
return;
}
/* We got an incoming connection, so close down the listener to prevent further connections. */
protocolStopServer();
}
/**
* Attempt to accept a connection from a JVM client.
*/
void protocolOpen() {
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
protocolOpenPipe();
} else {
protocolOpenSocket();
}
}
void protocolClosePipe() {
#ifndef WIN32
size_t pipeNameLen;
TCHAR *pipeName;
pipeNameLen = 12 + 10 + 1 + 10 + 3;
#endif
if (protocolActiveServerPipeConnected) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("Closing backend pipe."));
}
#ifdef WIN32
if (protocolActiveServerPipeIn != INVALID_HANDLE_VALUE && !CloseHandle(protocolActiveServerPipeIn)) {
#else
if (close(protocolActiveServerPipeIn) == -1) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT("Failed to close backend pipe: %s"), getLastErrorText());
}
#ifdef WIN32
if (protocolActiveServerPipeOut != INVALID_HANDLE_VALUE && !CloseHandle(protocolActiveServerPipeOut)) {
#else
if (close(protocolActiveServerPipeOut) == -1) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT("Failed to close backend pipe: %s"), getLastErrorText());
}
#ifndef WIN32
pipeName = malloc(sizeof(TCHAR) * (pipeNameLen + 1));
if (!pipeName) {
outOfMemory(TEXT("PCP"), 1);
return;
}
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-in"), wrapperData->wrapperPID, wrapperData->jvmRestarts);
_tunlink(pipeName);
_sntprintf(pipeName, pipeNameLen, TEXT("/tmp/wrapper-%d-%d-out"), wrapperData->wrapperPID, wrapperData->jvmRestarts);
_tunlink(pipeName);
#endif
protocolActiveServerPipeConnected = FALSE;
protocolActiveServerPipeStarted = FALSE;
protocolActiveServerPipeIn = INVALID_HANDLE_VALUE;
protocolActiveServerPipeOut = INVALID_HANDLE_VALUE;
}
}
void protocolCloseSocket() {
int rc;
/* Close the socket. */
if (protocolActiveBackendSD != INVALID_SOCKET) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("Closing backend socket."));
}
#ifdef WIN32
rc = closesocket(protocolActiveBackendSD);
#else /* UNIX */
rc = close(protocolActiveBackendSD);
#endif
if (rc == SOCKET_ERROR) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("socket close failed. (%d)"), wrapperGetLastError());
}
}
protocolActiveBackendSD = INVALID_SOCKET;
}
}
/**
* Close the backend socket.
*/
void wrapperProtocolClose() {
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
protocolClosePipe();
} else {
protocolCloseSocket();
}
}
/**
* Returns the name of a given function code for debug purposes.
*/
TCHAR *wrapperProtocolGetCodeName(char code) {
static TCHAR unknownBuffer[14];
TCHAR *name;
switch (code) {
case WRAPPER_MSG_START:
name = TEXT("START");
break;
case WRAPPER_MSG_STOP:
name = TEXT("STOP");
break;
case WRAPPER_MSG_RESTART:
name = TEXT("RESTART");
break;
case WRAPPER_MSG_PING:
name = TEXT("PING");
break;
case WRAPPER_MSG_STOP_PENDING:
name = TEXT("STOP_PENDING");
break;
case WRAPPER_MSG_START_PENDING:
name = TEXT("START_PENDING");
break;
case WRAPPER_MSG_STARTED:
name = TEXT("STARTED");
break;
case WRAPPER_MSG_STOPPED:
name = TEXT("STOPPED");
break;
case WRAPPER_MSG_KEY:
name = TEXT("KEY");
break;
case WRAPPER_MSG_BADKEY:
name = TEXT("BADKEY");
break;
case WRAPPER_MSG_LOW_LOG_LEVEL:
name = TEXT("LOW_LOG_LEVEL");
break;
case WRAPPER_MSG_PING_TIMEOUT: /* No longer used. */
name = TEXT("PING_TIMEOUT");
break;
case WRAPPER_MSG_SERVICE_CONTROL_CODE:
name = TEXT("SERVICE_CONTROL_CODE");
break;
case WRAPPER_MSG_PROPERTIES:
name = TEXT("PROPERTIES");
break;
case WRAPPER_MSG_LOG + LEVEL_DEBUG:
name = TEXT("LOG(DEBUG)");
break;
case WRAPPER_MSG_LOG + LEVEL_INFO:
name = TEXT("LOG(INFO)");
break;
case WRAPPER_MSG_LOG + LEVEL_STATUS:
name = TEXT("LOG(STATUS)");
break;
case WRAPPER_MSG_LOG + LEVEL_WARN:
name = TEXT("LOG(WARN)");
break;
case WRAPPER_MSG_LOG + LEVEL_ERROR:
name = TEXT("LOG(ERROR)");
break;
case WRAPPER_MSG_LOG + LEVEL_FATAL:
name = TEXT("LOG(FATAL)");
break;
case WRAPPER_MSG_LOG + LEVEL_ADVICE:
name = TEXT("LOG(ADVICE)");
break;
case WRAPPER_MSG_LOG + LEVEL_NOTICE:
name = TEXT("LOG(NOTICE)");
break;
case WRAPPER_MSG_LOGFILE:
name = TEXT("LOGFILE");
break;
case WRAPPER_MSG_APPEAR_ORPHAN: /* No longer used. */
name = TEXT("APPEAR_ORPHAN");
break;
case WRAPPER_MSG_PAUSE:
name = TEXT("PAUSE");
break;
case WRAPPER_MSG_RESUME:
name = TEXT("RESUME");
break;
case WRAPPER_MSG_GC:
name = TEXT("GC");
break;
default:
_sntprintf(unknownBuffer, 14, TEXT("UNKNOWN(%d)"), code);
name = unknownBuffer;
break;
}
return name;
}
/* Mutex for syncronization of the wrapperProtocolFunction function. */
#ifdef WIN32
HANDLE protocolMutexHandle = NULL;
#else
pthread_mutex_t protocolMutex = PTHREAD_MUTEX_INITIALIZER;
#endif
/** Obtains a lock on the protocol mutex. */
int lockProtocolMutex() {
#ifdef WIN32
switch (WaitForSingleObject(protocolMutexHandle, INFINITE)) {
case WAIT_ABANDONED:
_tprintf(TEXT("Protocol mutex was abandoned.\n"));
fflush(NULL);
return -1;
case WAIT_FAILED:
_tprintf(TEXT("Protocol mutex wait failed.\n"));
fflush(NULL);
return -1;
case WAIT_TIMEOUT:
_tprintf(TEXT("Protocol mutex wait timed out.\n"));
fflush(NULL);
return -1;
default:
/* Ok */
break;
}
#else
if (pthread_mutex_lock(&protocolMutex)) {
_tprintf(TEXT("Failed to lock the Protocol mutex. %s\n"), getLastErrorText());
return -1;
}
#endif
return 0;
}
/** Releases a lock on the protocol mutex. */
int releaseProtocolMutex() {
#ifdef WIN32
if (!ReleaseMutex(protocolMutexHandle)) {
_tprintf(TEXT("Failed to release Protocol mutex. %s\n"), getLastErrorText());
fflush(NULL);
return -1;
}
#else
if (pthread_mutex_unlock(&protocolMutex)) {
_tprintf(TEXT("Failed to unlock the Protocol mutex. %s\n"), getLastErrorText());
return -1;
}
#endif
return 0;
}
size_t protocolSendBufferSize = 0;
char *protocolSendBuffer = NULL;
/**
* Sends a command to the JVM process.
*
* @param function The command to send. (This is intentionally an 8-bit char.)
* @param message Message to send along with the command.
*
* @return TRUE if there were any problems.
*/
int wrapperProtocolFunction(char function, const TCHAR *messageW) {
int rc;
int cnt, inWritten;
size_t len;
const TCHAR *logMsgW;
char *messageMB = NULL;
int returnVal = FALSE;
int ok = TRUE;
/* It is important than there is never more than one thread allowed in here at a time. */
if (lockProtocolMutex()) {
return TRUE;
}
/* We don't want to show the full properties log message. It is quite long and distracting. */
if (function == WRAPPER_MSG_PROPERTIES) {
logMsgW = TEXT("(Property Values)");
} else {
logMsgW = messageW;
}
if (ok) {
/* We will be trasmitting a MultiByte string of characters. So we need to convert the messageW. */
if (messageW) {
#ifdef UNICODE
#ifdef WIN32
len = WideCharToMultiByte(CP_OEMCP, 0, messageW, -1, NULL, 0, NULL, NULL);
if (len <= 0) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN,
TEXT("Invalid multibyte sequence in protocol message \"%s\" : %s"), messageW, getLastErrorText());
returnVal = TRUE;
ok = FALSE;
} else {
messageMB = malloc(len);
if (!messageMB) {
outOfMemory(TEXT("WPF"), 1);
returnVal = TRUE;
ok = FALSE;
} else {
WideCharToMultiByte(CP_OEMCP, 0, messageW, -1, messageMB, (int)len, NULL, NULL);
}
}
#else
len = wcstombs(NULL, messageW, 0) + 1;
if (len == (size_t)-1) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN,
TEXT("Invalid multibyte sequence in protocol message \"%s\" : %s"), messageW, getLastErrorText());
returnVal = TRUE;
ok = FALSE;
} else {
messageMB = malloc(len);
if (!messageMB) {
outOfMemory(TEXT("WPF"), 2);
returnVal = TRUE;
ok = FALSE;
} else {
wcstombs(messageMB, messageW, len);
}
}
#endif
#else
len = _tscslen(messageW) + 1;
messageMB = malloc(len);
if (!messageMB) {
outOfMemory(TEXT("WPF"), 3);
returnVal = TRUE;
ok = FALSE;
} else {
_tcsncpy(messageMB, messageW, len);
}
#endif
} else {
messageMB = NULL;
}
}
if (ok) {
/* We need to construct a single string that will be used to transmit the command + message. */
if (messageMB) {
len = 1 + strlen(messageMB) + 1;
} else {
len = 2;
}
if (protocolSendBufferSize < len) {
if (protocolSendBuffer) {
free(protocolSendBuffer);
}
protocolSendBuffer = malloc(sizeof(char) * len);
if (!protocolSendBuffer) {
outOfMemory(TEXT("WPF"), 4);
returnVal = TRUE;
ok = FALSE;
} else {
/* Build the packet */
protocolSendBuffer[0] = function;
if (messageMB) {
strncpy(&(protocolSendBuffer[1]), messageMB, len - 1);
} else {
protocolSendBuffer[1] = 0;
}
}
}
if (messageMB) {
free(messageMB);
}
}
if (ok) {
if (((protocolActiveBackendSD == INVALID_SOCKET) && (wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET))
|| ((protocolActiveServerPipeConnected == FALSE) && (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE))) {
/* A socket was not opened */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG,
TEXT("socket not open, so packet not sent %s : %s"),
wrapperProtocolGetCodeName(function), (logMsgW == NULL ? TEXT("NULL") : logMsgW));
}
returnVal = TRUE;
} else {
if (wrapperData->isDebugging) {
if ((function == WRAPPER_MSG_PING) && messageW && (_tcsstr(messageW, TEXT("silent")) == messageW)) {
/*
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG,
TEXT("send a silent ping packet %s : %s"),
wrapperProtocolGetCodeName(function), (logMsgW == NULL ? TEXT("NULL") : logMsgW));
*/
} else {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG,
TEXT("send a packet %s : %s"),
wrapperProtocolGetCodeName(function), (logMsgW == NULL ? TEXT("NULL") : logMsgW));
}
}
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
#ifdef WIN32
if (WriteFile(protocolActiveServerPipeOut, protocolSendBuffer, sizeof(char) * (int)len, &inWritten, NULL) == FALSE) {
#else
if ((inWritten = write(protocolActiveServerPipeOut, protocolSendBuffer, sizeof(char) * (int)len)) == -1) {
#endif
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_FATAL, TEXT("Writing to the backend pipe failed (%d): %s"), wrapperGetLastError(), getLastErrorText());
return FALSE;
}
} else {
cnt = 0;
do {
if (cnt > 0) {
wrapperSleep(10);
}
rc = send(protocolActiveBackendSD, protocolSendBuffer, sizeof(char) * (int)len, 0);
cnt++;
} while ((rc == SOCKET_ERROR) && (wrapperGetLastError() == EWOULDBLOCK) && (cnt < 200));
if (rc == SOCKET_ERROR) {
if (wrapperGetLastError() == EWOULDBLOCK) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_WARN, TEXT(
"socket send failed. Blocked for 2 seconds. %s"),
getLastErrorText());
#ifdef WIN32
} else if (wrapperGetLastError() == WSAECONNRESET) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_ERROR, TEXT(
"socket send failed. %s"), getLastErrorText());
#endif
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT(
"socket send failed. %s"), getLastErrorText());
}
}
wrapperProtocolClose();
returnVal = TRUE;
} else {
returnVal = FALSE;
}
}
}
}
/* Always make sure the mutex is released. */
if (releaseProtocolMutex()) {
returnVal = TRUE;
}
return returnVal;
}
/**
* Checks the status of the server backend.
*
* The backend will be initialized if the JVM is in a state where it should
* be up, otherwise the backend will be left alone.
*
* If the forceOpen flag is set then an attempt will be made to initialize
* the backend regardless of the JVM state.
*
* Returns TRUE if the backend is open and ready on return, FALSE if not.
*/
int wrapperCheckServerBackend(int forceOpen) {
if (((wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) && (protocolActiveServerSD == INVALID_SOCKET)) ||
((wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) && (protocolActiveServerPipeStarted == FALSE))) {
/* The backend is not currently open and needs to be started,
* unless the JVM is DOWN or in a state where it is not needed. */
if ((!forceOpen) &&
((wrapperData->jState == WRAPPER_JSTATE_DOWN_CLEAN) ||
(wrapperData->jState == WRAPPER_JSTATE_LAUNCH_DELAY) ||
(wrapperData->jState == WRAPPER_JSTATE_RESTART) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPED) ||
(wrapperData->jState == WRAPPER_JSTATE_KILLING) ||
(wrapperData->jState == WRAPPER_JSTATE_KILL) ||
(wrapperData->jState == WRAPPER_JSTATE_KILLED) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CHECK) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_FLUSH))) {
/* The JVM is down or in a state where the backend is not needed. */
return FALSE;
} else {
/* The backend should be open, try doing so. */
protocolStartServer();
if (((wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) && (protocolActiveServerSD == INVALID_SOCKET)) ||
((wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) && (protocolActiveServerPipeStarted == FALSE))) {
/* Failed. */
return FALSE;
} else {
return TRUE;
}
}
} else {
/* Backend is ready. */
return TRUE;
}
}
/**
* Simple function to parse hexidecimal numbers into a TICKS
*/
TICKS hexToTICKS(TCHAR *buffer) {
TICKS value = 0;
TCHAR c;
int pos = 0;
while (TRUE) {
c = buffer[pos];
if ((c >= TEXT('a')) && (c <= TEXT('f'))) {
value = (value << 4) + (10 + c - TEXT('a'));
} else if ((c >= TEXT('A')) && (c <= TEXT('F'))) {
value = (value << 4) + (10 + c - TEXT('A'));
} else if ((c >= TEXT('0')) && (c <= TEXT('9'))) {
value = (value << 4) + (c - TEXT('0'));
} else {
/* Any other character or null is the end of the number. */
return value;
}
pos++;
}
}
/**
* Read any data sent from the JVM. This function will loop and read as many
* packets are available. The loop will only be allowed to go for 250ms to
* ensure that other functions are handled correctly.
*
* Returns 0 if all available data has been read, 1 if more data is waiting.
*/
int wrapperProtocolRead() {
char c;
char code;
int len;
#ifdef WIN32
int maxlen;
#endif
int pos;
TCHAR *tc;
int err;
struct timeb timeBuffer;
time_t startTime;
int startTimeMillis;
time_t now;
int nowMillis;
time_t durr;
wrapperGetCurrentTime(&timeBuffer);
startTime = now = timeBuffer.time;
startTimeMillis = nowMillis = timeBuffer.millitm;
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("now=%ld, nowMillis=%d"), now, nowMillis);
*/
while((durr = (now - startTime) * 1000 + (nowMillis - startTimeMillis)) < 250) {
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("durr=%ld"), durr);
*/
/* If we have an open client backend, then use it. */
if (((wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) && (protocolActiveBackendSD == INVALID_SOCKET)) ||
((wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) && (protocolActiveServerPipeConnected == FALSE))) {
/* A Client backend is not open */
/* Is the server backend open? */
if (!wrapperCheckServerBackend(FALSE)) {
/* Backend is down. We can not read any packets. */
return 0;
}
/* Try accepting a connection */
protocolOpen();
if (((wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) && (protocolActiveBackendSD == INVALID_SOCKET)) ||
((wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) && (protocolActiveServerPipeConnected == FALSE))) {
return 0;
}
}
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) {
/* Try receiving a packet code */
len = recv(protocolActiveBackendSD, (void*) &c, 1, 0);
if (len == SOCKET_ERROR) {
err = wrapperGetLastError();
if ((err != EWOULDBLOCK) && /* Windows - Would block. */
(err != EAGAIN)) { /* UNIX - Would block. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("socket read failed. (%s)"), getLastErrorText());
}
wrapperProtocolClose();
}
return 0;
} else if (len != 1) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("socket read no code (closed?)."));
}
wrapperProtocolClose();
return 0;
}
code = (char)c;
/* Read in any message */
pos = 0;
do {
len = recv(protocolActiveBackendSD, (void*) &c, 1, 0);
if (len == 1) {
if (c == 0) {
/* End of string */
len = 0;
} else if (pos < MAX_LOG_SIZE) {
packetBuffer[pos] = c;
pos++;
}
} else {
len = 0;
}
} while (len == 1);
/* terminate the string; */
packetBuffer[pos] = TEXT('\0');
} else if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
#ifdef WIN32
err = PeekNamedPipe(protocolActiveServerPipeIn, NULL, 0, NULL, &maxlen, NULL);
if ((err == 0) && (GetLastError() == ERROR_BROKEN_PIPE)) {
/* ERROR_BROKEN_PIPE - the client has closed the pipe. So most likely it just exited */
protocolActiveServerPipeIn = INVALID_HANDLE_VALUE;
}
if (maxlen == 0) {
/*no data available */
return 0;
}
if (ReadFile(protocolActiveServerPipeIn, &c, 1, &len, NULL) == TRUE || GetLastError() == ERROR_MORE_DATA) {
code = (char)c;
--maxlen;
pos = 0;
do {
ReadFile(protocolActiveServerPipeIn, &c, 1, &len, NULL);
if (len == 1) {
if (c == 0) {
/* End of string */
len = 0;
} else if (pos < MAX_LOG_SIZE) {
packetBuffer[pos] = c;
pos++;
}
} else {
len = 0;
}
} while (len == 1 && maxlen-- >= 0);
packetBuffer[pos] = TEXT('\0');
} else {
if (GetLastError() == ERROR_INVALID_HANDLE) {
return 0;
} else {
wrapperProtocolClose();
return 0;
}
}
#else
len = read(protocolActiveServerPipeIn, (void*) &c, 1);
if (len == SOCKET_ERROR) {
err = wrapperGetLastError();
if ((err != EWOULDBLOCK) && /* Windows - Would block. */
(err != EAGAIN)) { /* UNIX - Would block. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("pipe read failed. (%s)"), getLastErrorText());
}
wrapperProtocolClose();
}
return 0;
} else if (len == 0) {
/*nothing read...*/
return 0;
}
code = (char)c;
/* Read in any message */
pos = 0;
do {
len = read(protocolActiveServerPipeIn, (void*) &c, 1);
if (len == 1) {
if (c == 0) {
/* End of string */
len = 0;
} else if (pos < MAX_LOG_SIZE) {
packetBuffer[pos] = c;
pos++;
}
} else {
len = 0;
}
} while (len == 1);
/* terminate the string; */
packetBuffer[pos] = TEXT('\0');
#endif
} else {
return 0;
}
if (wrapperData->isDebugging) {
if ((code == WRAPPER_MSG_PING) && (_tcsstr(packetBuffer, TEXT("silent")) == packetBuffer)) {
/*
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("read a silent ping packet %s : %s"),
wrapperProtocolGetCodeName(code), packetBuffer);
*/
} else {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("read a packet %s : %s"),
wrapperProtocolGetCodeName(code), packetBuffer);
}
}
switch (code) {
case WRAPPER_MSG_STOP:
wrapperStopRequested(_ttoi(packetBuffer));
break;
case WRAPPER_MSG_RESTART:
wrapperRestartRequested();
break;
case WRAPPER_MSG_PING:
/* Because all versions of the wrapper.jar simply bounce back the ping message, the pingSendTicks should always exist. */
tc = _tcschr(packetBuffer, TEXT(' '));
if (tc) {
/* A pingSendTicks should exist. Parse the id following the space. It will be in the format 0xffffffff. */
wrapperPingResponded(hexToTICKS(&tc[1]), TRUE);
} else {
/* Should not happen, but just in case use the current ticks. */
wrapperPingResponded(wrapperGetTicks(), FALSE);
}
break;
case WRAPPER_MSG_STOP_PENDING:
wrapperStopPendingSignaled(_ttoi(packetBuffer));
break;
case WRAPPER_MSG_STOPPED:
wrapperStoppedSignaled();
break;
case WRAPPER_MSG_START_PENDING:
wrapperStartPendingSignaled(_ttoi(packetBuffer));
break;
case WRAPPER_MSG_STARTED:
wrapperStartedSignaled();
break;
case WRAPPER_MSG_KEY:
wrapperKeyRegistered(packetBuffer);
break;
case WRAPPER_MSG_LOG + LEVEL_DEBUG:
case WRAPPER_MSG_LOG + LEVEL_INFO:
case WRAPPER_MSG_LOG + LEVEL_STATUS:
case WRAPPER_MSG_LOG + LEVEL_WARN:
case WRAPPER_MSG_LOG + LEVEL_ERROR:
case WRAPPER_MSG_LOG + LEVEL_FATAL:
wrapperLogSignaled(code - WRAPPER_MSG_LOG, packetBuffer);
break;
case WRAPPER_MSG_APPEAR_ORPHAN:
/* No longer used. This is still here in case a mix of versions are used. */
break;
default:
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_PROTOCOL, LEVEL_DEBUG, TEXT("received unknown packet (%d:%s)"), code, packetBuffer);
}
break;
}
/* Get the time again */
wrapperGetCurrentTime(&timeBuffer);
now = timeBuffer.time;
nowMillis = timeBuffer.millitm;
}
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("done durr=%ld"), durr);
*/
if ((durr = (now - startTime) * 1000 + (nowMillis - startTimeMillis)) < 250) {
return 0;
} else {
return 1;
}
}
/******************************************************************************
* Wrapper inner methods.
*****************************************************************************/
/**
* IMPORTANT - Any logging done in here needs to be queued or it would cause a recursion problem.
*
* It is also critical that this is NEVER called from within the protocol function because it
* would cause a deadlock with the protocol semaphore. This means that it can never be called
* from within log_printf(...).
*/
void wrapperLogFileChanged(const TCHAR *logFile) {
if (wrapperData->isDebugging) {
log_printf_queue(TRUE, WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("active log file changed: %s"), logFile);
}
/* On startup, this function will always be called the first time the log file is set,
* we don't want to send the command in this case as it clutters the debug log output.
* Besides, the JVM will not be running anyway. */
if (wrapperData->jState != WRAPPER_JSTATE_DOWN_CLEAN) {
wrapperProtocolFunction(WRAPPER_MSG_LOGFILE, logFile);
}
}
/**
* Pre initialize the wrapper.
*/
int wrapperInitialize() {
TCHAR *retLocale;
#ifdef WIN32
int maxPathLen = _MAX_PATH;
#else
int maxPathLen = PATH_MAX;
#endif
/* Initialize the properties variable. */
properties = NULL;
/* Initialize the random seed. */
srand((unsigned)time(NULL));
/* Make sure all values are reliably set to 0. All required values should also be
* set below, but this extra step will protect against future changes. Some
* platforms appear to initialize maloc'd memory to 0 while others do not. */
wrapperData = malloc(sizeof(WrapperConfig));
if (!wrapperData) {
outOfMemory(TEXT("WI"), 1);
return 1;
}
memset(wrapperData, 0, sizeof(WrapperConfig));
/* Setup the initial values of required properties. */
wrapperData->configured = FALSE;
wrapperData->isConsole = TRUE;
wrapperSetWrapperState(WRAPPER_WSTATE_STARTING);
wrapperSetJavaState(WRAPPER_JSTATE_DOWN_CLEAN, 0, -1);
wrapperData->lastPingTicks = wrapperGetTicks();
wrapperData->lastLoggedPingTicks = wrapperGetTicks();
wrapperData->jvmCommand = NULL;
wrapperData->exitRequested = FALSE;
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_INITIAL; /* The first JVM needs to be started. */
wrapperData->exitCode = 0;
wrapperData->jvmRestarts = 0;
wrapperData->jvmLaunchTicks = wrapperGetTicks();
wrapperData->failedInvocationCount = 0;
wrapperData->originalWorkingDir = NULL;
wrapperData->configFile = NULL;
wrapperData->workingDir = NULL;
wrapperData->outputFilterCount = 0;
wrapperData->confDir = NULL;
wrapperData->umask = -1;
wrapperData->language = NULL;
wrapperData->portAddress = NULL;
wrapperData->pingTimedOut = FALSE;
#ifdef WIN32
if (!(tickMutexHandle = CreateMutex(NULL, FALSE, NULL))) {
printf("Failed to create tick mutex. %s\n", getLastErrorText());
return 1;
}
/* Initialize control code queue. */
wrapperData->ctrlCodeQueue = malloc(sizeof(int) * CTRL_CODE_QUEUE_SIZE);
if (!wrapperData->ctrlCodeQueue) {
outOfMemory(TEXT("WI"), 2);
return 1;
}
wrapperData->ctrlCodeQueueWriteIndex = 0;
wrapperData->ctrlCodeQueueReadIndex = 0;
wrapperData->ctrlCodeQueueWrapped = FALSE;
#endif
if (initLogging(wrapperLogFileChanged)) {
return 1;
}
/* This will only be called by the main thread on startup.
* Immediately register this thread with the logger.
* This has to happen after the logging is initialized. */
logRegisterThread(WRAPPER_THREAD_MAIN);
setLogfilePath(TEXT("wrapper.log"), NULL, FALSE);
setLogfileRollMode(ROLL_MODE_SIZE);
setLogfileFormat(TEXT("LPTM"));
setLogfileLevelInt(LEVEL_DEBUG);
setLogfileAutoClose(FALSE);
setConsoleLogFormat(TEXT("LPM"));
setConsoleLogLevelInt(LEVEL_DEBUG);
setConsoleFlush(TRUE); /* Always flush immediately until the logfile is configured to make sure that problems are in a consistent location. */
setSyslogLevelInt(LEVEL_NONE);
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Wrapper Initializing... Minimum logging configured."));
#endif
/** Remember what the initial user directory was when the Wrapper was launched. */
wrapperData->initialPath = (TCHAR *)malloc((maxPathLen + 1) * sizeof(TCHAR));
if (!wrapperData->initialPath) {
outOfMemory(TEXT("WI"), 3);
return 1;
} else {
if (!(wrapperData->initialPath = _tgetcwd((TCHAR*)wrapperData->initialPath, maxPathLen + 1))) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Failed to get the initial directory. (%s)"), getLastErrorText());
return 1;
}
}
/* Set a variable to the initial working directory. */
setEnv(TEXT("WRAPPER_INIT_DIR"), wrapperData->initialPath, ENV_SOURCE_WRAPPER);
#ifdef WIN32
if (!(protocolMutexHandle = CreateMutex(NULL, FALSE, NULL))) {
_tprintf(TEXT("Failed to create protocol mutex. %s\n"), getLastErrorText());
fflush(NULL);
return 1;
}
#endif
/* This is a sanity check to make sure that the datatype used for tick counts is correct. */
if (sizeof(TICKS) != 4) {
printf("Tick size incorrect %d != 4\n", (int)sizeof(TICKS));
fflush(NULL);
return 1;
}
/* Set the default locale here so any startup error messages will have a chance of working.
* We will go back and try to set the actual locale again later once it is configured. */
retLocale = _tsetlocale(LC_ALL, TEXT(""));
if (retLocale) {
/* Success. */
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("tsetlocale() returned \"%s\""), retLocale);
#endif
#if !defined(WIN32) && defined(UNICODE)
free(retLocale);
#endif
} else {
/* Failure. */
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("tsetlocale() returned NULL"));
#endif
}
if (loadEnvironment()) {
return 1;
}
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Wrapper Initialization complete."));
#endif
return 0;
}
void wrapperDataDispose() {
int i;
if (wrapperData->workingDir) {
free(wrapperData->workingDir);
wrapperData->workingDir = NULL;
}
if (wrapperData->originalWorkingDir) {
free(wrapperData->originalWorkingDir);
wrapperData->originalWorkingDir = NULL;
}
if (wrapperData->configFile) {
free(wrapperData->configFile);
wrapperData->configFile = NULL;
}
if (wrapperData->initialPath) {
free(wrapperData->initialPath);
wrapperData->initialPath = NULL;
}
if (wrapperData->classpath) {
free(wrapperData->classpath);
wrapperData->classpath = NULL;
}
if (wrapperData->portAddress) {
free(wrapperData->portAddress);
wrapperData->portAddress = NULL;
}
#ifdef WIN32
if (wrapperData->jvmCommand) {
free(wrapperData->jvmCommand);
wrapperData->jvmCommand = NULL;
}
if (wrapperData->userName) {
free(wrapperData->userName);
wrapperData->userName = NULL;
}
if (wrapperData->domainName) {
free(wrapperData->domainName);
wrapperData->domainName = NULL;
}
if (wrapperData->ntServiceLoadOrderGroup) {
free(wrapperData->ntServiceLoadOrderGroup);
wrapperData->ntServiceLoadOrderGroup = NULL;
}
if (wrapperData->ntServiceDependencies) {
free(wrapperData->ntServiceDependencies);
wrapperData->ntServiceDependencies = NULL;
}
if (wrapperData->ntServiceAccount) {
free(wrapperData->ntServiceAccount);
wrapperData->ntServiceAccount = NULL;
}
if (wrapperData->ntServicePassword) {
free(wrapperData->ntServicePassword);
wrapperData->ntServicePassword = NULL;
}
if (wrapperData->ctrlCodeQueue) {
free(wrapperData->ctrlCodeQueue);
wrapperData->ctrlCodeQueue = NULL;
}
#else
if(wrapperData->jvmCommand) {
for (i = 0; wrapperData->jvmCommand[i] != NULL; i++) {
free(wrapperData->jvmCommand[i]);
wrapperData->jvmCommand[i] = NULL;
}
free(wrapperData->jvmCommand);
wrapperData->jvmCommand = NULL;
}
#endif
if (wrapperData->outputFilterCount > 0) {
for (i = 0; i < wrapperData->outputFilterCount; i++) {
if (wrapperData->outputFilters[i]) {
free(wrapperData->outputFilters[i]);
wrapperData->outputFilters[i] = NULL;
}
if (wrapperData->outputFilterActionLists[i]) {
free(wrapperData->outputFilterActionLists[i]);
wrapperData->outputFilterActionLists[i] = NULL;
}
}
if (wrapperData->outputFilters) {
free(wrapperData->outputFilters);
wrapperData->outputFilters = NULL;
}
if (wrapperData->outputFilterActionLists) {
free(wrapperData->outputFilterActionLists);
wrapperData->outputFilterActionLists = NULL;
}
if (wrapperData->outputFilterMessages) {
free(wrapperData->outputFilterMessages);
wrapperData->outputFilterMessages = NULL;
}
if (wrapperData->outputFilterAllowWildFlags) {
free(wrapperData->outputFilterAllowWildFlags);
wrapperData->outputFilterAllowWildFlags = NULL;
}
if (wrapperData->outputFilterMinLens) {
free(wrapperData->outputFilterMinLens);
wrapperData->outputFilterMinLens = NULL;
}
}
if (wrapperData->pidFilename) {
free(wrapperData->pidFilename);
wrapperData->pidFilename = NULL;
}
if (wrapperData->lockFilename) {
free(wrapperData->lockFilename);
wrapperData->lockFilename = NULL;
}
if (wrapperData->javaPidFilename) {
free(wrapperData->javaPidFilename);
wrapperData->javaPidFilename = NULL;
}
if (wrapperData->javaIdFilename) {
free(wrapperData->javaIdFilename);
wrapperData->javaIdFilename = NULL;
}
if (wrapperData->statusFilename) {
free(wrapperData->statusFilename);
wrapperData->statusFilename = NULL;
}
if (wrapperData->javaStatusFilename) {
free(wrapperData->javaStatusFilename);
wrapperData->javaStatusFilename = NULL;
}
if (wrapperData->commandFilename) {
free(wrapperData->commandFilename);
wrapperData->commandFilename = NULL;
}
if (wrapperData->consoleTitle) {
free(wrapperData->consoleTitle);
wrapperData->consoleTitle = NULL;
}
if (wrapperData->serviceName) {
free(wrapperData->serviceName);
wrapperData->serviceName = NULL;
}
if (wrapperData->serviceDisplayName) {
free(wrapperData->serviceDisplayName);
wrapperData->serviceDisplayName = NULL;
}
if (wrapperData->serviceDescription) {
free(wrapperData->serviceDescription);
wrapperData->serviceDescription = NULL;
}
if (wrapperData->hostName) {
free(wrapperData->hostName);
wrapperData->hostName = NULL;
}
if (wrapperData->confDir) {
free(wrapperData->confDir);
wrapperData->confDir = NULL;
}
if (wrapperData->argConfFileDefault && wrapperData->argConfFile) {
free(wrapperData->argConfFile);
wrapperData->argConfFile = NULL;
}
if (wrapperData) {
free(wrapperData);
wrapperData = NULL;
}
}
/** Common wrapper cleanup code. */
void wrapperDispose() {
/* Make sure not to dispose twice. This should not happen, but check for safety. */
if (disposed) {
_tprintf(TEXT("wrapperDispose was called more than once."));
return;
}
disposed = TRUE;
#ifdef WIN32
if (protocolMutexHandle) {
if (!CloseHandle(protocolMutexHandle)) {
_tprintf(TEXT("Unable to close protocol mutex handle. %s\n"), getLastErrorText());
fflush(NULL);
}
}
/* Make sure that the startup thread has completed. */
disposeStartup();
#endif
/* Clean up the javaIO thread. This should be done before the timer thread. */
if (wrapperData->useJavaIOThread) {
disposeJavaIO();
}
/* Clean up the timer thread. */
if (!wrapperData->useSystemTime) {
disposeTimer();
}
/* Clean up the properties structure. */
disposeProperties(properties);
properties = NULL;
disposeEnvironment();
if (wrapperChildWorkBuffer) {
free(wrapperChildWorkBuffer);
wrapperChildWorkBuffer = NULL;
}
if (protocolSendBuffer) {
free(protocolSendBuffer);
protocolSendBuffer = NULL;
}
/* Clean up the logging system. Should happen near last. */
disposeLogging();
/* clean up the main wrapper data structure. This must be done last.*/
wrapperDataDispose();
}
/**
* Returns the file name base as a newly malloced TCHAR *. The resulting
* base file name will have any path and extension stripped.
*
* baseName should be long enough to always contain the base name.
* (_tcslen(fileName) + 1) is safe.
*/
void wrapperGetFileBase(const TCHAR *fileName, TCHAR *baseName) {
const TCHAR *start;
const TCHAR *end;
const TCHAR *c;
start = fileName;
end = &fileName[_tcslen(fileName)];
/* Strip off any path. */
#ifdef WIN32
c = _tcsrchr(start, TEXT('\\'));
#else
c = _tcsrchr(start, TEXT('/'));
#endif
if (c) {
start = &c[1];
}
/* Strip off any extension. */
c = _tcsrchr(start, TEXT('.'));
if (c) {
end = c;
}
/* Now create the new base name. */
_tcsncpy(baseName, start, end - start);
baseName[end - start] = TEXT('\0');
}
/**
* Returns a buffer containing a multi-line version banner. It is the responsibility of the caller
* to make sure it gets freed.
*/
TCHAR *generateVersionBanner() {
TCHAR *banner = TEXT("Java Service Wrapper %s Edition %s-bit %s\n Copyright (C) 1999-%s Tanuki Software, Ltd. All Rights Reserved.\n http://wrapper.tanukisoftware.com");
TCHAR *product = TEXT("Community");
TCHAR *copyright = TEXT("2013");
TCHAR *buffer;
size_t len;
len = _tcslen(banner) + _tcslen(product) + _tcslen(wrapperBits) + _tcslen(wrapperVersionRoot) + _tcslen(copyright) + 1;
buffer = malloc(sizeof(TCHAR) * len);
if (!buffer) {
outOfMemory(TEXT("GVB"), 1);
return NULL;
}
_sntprintf(buffer, len, banner, product, wrapperBits, wrapperVersionRoot, copyright);
return buffer;
}
/**
* Output the version.
*/
void wrapperVersionBanner() {
TCHAR *banner = generateVersionBanner();
if (!banner) {
return;
}
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, banner);
free(banner);
}
/**
* Output the application usage.
*/
void wrapperUsage(TCHAR *appName) {
TCHAR *confFileBase;
confFileBase = malloc(sizeof(TCHAR) * (_tcslen(appName) + 1));
if (!confFileBase) {
outOfMemory(TEXT("WU"), 1);
return;
}
wrapperGetFileBase(appName, confFileBase);
setSimpleLogLevels();
wrapperVersionBanner();
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Usage:"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" %s <command> <configuration file> [configuration properties] [...]"), appName);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" %s <configuration file> [configuration properties] [...]"), appName);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" (<command> implicitly '-c')"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" %s <command>"), appName);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" (<configuration file> implicitly '%s.conf')"), confFileBase);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" %s"), appName);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" (<command> implicitly '-c' and <configuration file> '%s.conf')"), confFileBase);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("where <command> can be one of:"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -c --console run as a Console application"));
#ifdef WIN32
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -t --start starT an NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -a --pause pAuse a started NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -e --resume rEsume a paused NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -p --stop stoP a running NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -i --install Install as an NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -it --installstart Install and sTart as an NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -r --remove Uninstall/Remove as an NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -l=<code> --controlcode=<code> send a user controL Code to a running NT service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -d --dump request a thread Dump"));
/** Return mask: installed:1 running:2 interactive:4 automatic:8 manual:16 disabled:32 */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -q --query Query the current status of the service"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -qs --querysilent Silently Query the current status of the service"));
/* Omit '-s' option from help as it is only used by the service manager. */
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -s --service used by service manager")); */
#endif
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -v --version print the wrapper's version information."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -? --help print this help message"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" -- <args> mark the end of Wrapper arguments. All arguments after the\n '--' will be passed through unmodified to the java application."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("<configuration file> is the wrapper.conf to use. Name must be absolute or relative"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" to the location of %s"), appName);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("[configuration properties] are configuration name-value pairs which override values"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" in wrapper.conf. For example:"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" wrapper.debug=true"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" Please note that any file references must be absolute or relative to the location\n of the Wrapper executable."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
free(confFileBase);
}
/**
* Parse the main arguments.
*
* Returns FALSE if the application should exit with an error. A message will
* already have been logged.
*/
int wrapperParseArguments(int argc, TCHAR **argv) {
TCHAR *argConfFileBase;
TCHAR *c;
int delimiter, wrapperArgCount;
wrapperData->javaArgValueCount = 0;
delimiter = 1;
if (argc > 1
) {
for (delimiter = 0; delimiter < argc ; delimiter++) {
if ( _tcscmp(argv[delimiter], TEXT("--")) == 0) {
#if !defined(WIN32) && defined(UNICODE)
free(argv[delimiter]);
#endif
argv[delimiter] = NULL;
wrapperData->javaArgValueCount = argc - delimiter - 1;
if (delimiter + 1 < argc) {
wrapperData->javaArgValues = &argv[delimiter + 1];
}
break;
}
}
}
wrapperArgCount = delimiter ;
if (wrapperArgCount > 1) {
/* Store the name of the binary.*/
wrapperData->argBinary = argv[0];
if (argv[1][0] == TEXT('-')) {
/* Syntax 1 or 3 */
/* A command appears to have been specified. */
wrapperData->argCommand = &argv[1][1]; /* Strip off the '-' */
if (wrapperData->argCommand[0] == TEXT('\0')) {
wrapperUsage(argv[0]);
return FALSE;
}
/* Does the argument have a value? */
c = _tcschr(wrapperData->argCommand, TEXT('='));
if (c == NULL) {
wrapperData->argCommandArg = NULL;
} else {
wrapperData->argCommandArg = (TCHAR *)(c + 1);
c[0] = TEXT('\0');
}
if (wrapperArgCount > 2) {
if (_tcsncmp(wrapperData->argCommand, TEXT("-translate"), 5) == 0) {
if (wrapperArgCount > 3) {
wrapperData->argConfFile = argv[3];
wrapperData->argCount = wrapperArgCount - 4;
wrapperData->argValues = &argv[4];
}
return TRUE;
}
/* Syntax 1 */
/* A command and conf file were specified. */
wrapperData->argConfFile = argv[2];
wrapperData->argCount = wrapperArgCount - 3;
wrapperData->argValues = &argv[3];
} else {
/* Syntax 3 */
/* Only a command was specified. Assume a default config file name. */
argConfFileBase = malloc(sizeof(TCHAR) * (_tcslen(argv[0]) + 1));
if (!argConfFileBase) {
outOfMemory(TEXT("WPA"), 1);
return FALSE;
}
wrapperGetFileBase(argv[0], argConfFileBase);
/* The following malloc is only called once, but is never freed. */
wrapperData->argConfFile = malloc((_tcslen(argConfFileBase) + 5 + 1) * sizeof(TCHAR));
if (!wrapperData->argConfFile) {
outOfMemory(TEXT("WPA"), 2);
free(argConfFileBase);
return FALSE;
}
_sntprintf(wrapperData->argConfFile, _tcslen(argConfFileBase) + 5 + 1, TEXT("%s.conf"), argConfFileBase);
free(argConfFileBase);
wrapperData->argConfFileDefault = TRUE;
wrapperData->argCount = wrapperArgCount - 2;
wrapperData->argValues = &argv[2];
}
} else {
/* Syntax 2 */
/* A command was not specified, but there may be a config file. */
wrapperData->argCommand = TEXT("c");
wrapperData->argCommandArg = NULL;
wrapperData->argConfFile = argv[1];
wrapperData->argCount = wrapperArgCount - 2;
wrapperData->argValues = &argv[2];
}
} else {
/* Systax 4 */
/* A config file was not specified. Assume a default config file name. */
wrapperData->argCommand = TEXT("c");
wrapperData->argCommandArg = NULL;
argConfFileBase = malloc(sizeof(TCHAR) * (_tcslen(argv[0]) + 1));
if (!argConfFileBase) {
outOfMemory(TEXT("WPA"), 3);
return FALSE;
}
wrapperGetFileBase(argv[0], argConfFileBase);
/* The following malloc is only called once, but is never freed. */
wrapperData->argConfFile = malloc((_tcslen(argConfFileBase) + 5 + 1) * sizeof(TCHAR));
if (!wrapperData->argConfFile) {
outOfMemory(TEXT("WPA"), 4);
free(argConfFileBase);
return FALSE;
}
_sntprintf(wrapperData->argConfFile, _tcslen(argConfFileBase) + 5 + 1, TEXT("%s.conf"), argConfFileBase);
free(argConfFileBase);
wrapperData->argConfFileDefault = TRUE;
wrapperData->argCount = wrapperArgCount - 1;
wrapperData->argValues = &argv[1];
}
return TRUE;
}
/**
* Performs the specified action,
*
* @param actionList An array of action Ids ending with a value ACTION_LIST_END.
* Negative values are standard actions, positive are user
* custom events.
* @param triggerMsg The reason the actions are being fired.
* @param actionSourceCode Tracks where the action originated.
* @param logForActionNone Flag stating whether or not a message should be logged
* for the NONE action.
* @param exitCode Error code to use in case the action results in a shutdown.
*/
void wrapperProcessActionList(int *actionList, const TCHAR *triggerMsg, int actionSourceCode, int logForActionNone, int exitCode) {
int i;
int action;
if (actionList) {
i = 0;
while ((action = actionList[i]) != ACTION_LIST_END) {
switch(action) {
case ACTION_RESTART:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Restarting JVM."), triggerMsg);
wrapperRestartProcess();
break;
case ACTION_SHUTDOWN:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Shutting down."), triggerMsg);
wrapperStopProcess(exitCode, FALSE);
break;
case ACTION_DUMP:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Requesting thread dump."), triggerMsg);
wrapperRequestDumpJVMState();
break;
case ACTION_DEBUG:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Debugging."), triggerMsg);
break;
case ACTION_PAUSE:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Pausing..."), triggerMsg);
wrapperPauseProcess(actionSourceCode);
break;
case ACTION_RESUME:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Resuming..."), triggerMsg);
wrapperResumeProcess(actionSourceCode);
break;
#if defined(MACOSX)
case ACTION_ADVICE_NIL_SERVER:
if (wrapperData->isAdviserEnabled) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(
"--------------------------------------------------------------------"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(
"Advice:"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(
"MACOSX is known to have problems displaying GUIs from processes\nrunning as a daemon launched from launchd. The above\n\"Returning nil _server\" means that you are encountering this\nproblem. This usually results in a long timeout which is affecting\nthe performance of your application."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(
"--------------------------------------------------------------------"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ADVICE, TEXT(""));
}
break;
#endif
case ACTION_NONE:
if (logForActionNone) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s"), triggerMsg);
}
/* Do nothing but masks later filters */
break;
case ACTION_SUCCESS:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Application has signalled success, consider this application started successful..."), triggerMsg);
wrapperData->failedInvocationCount = 0;
break;
case ACTION_GC:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("%s Requesting GC..."), triggerMsg);
wrapperRequestJVMGC(actionSourceCode);
break;
default:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Unknown action type: %d"), action);
break;
}
i++;
}
}
}
/**
* Function that will recursively attempt to match two strings where the
* pattern can contain '?' or '*' wildcard characters. This function requires
* that the pattern be matched from the beginning of the text.
*
* @param text Text to be searched.
* @param textLen Length of the text.
* @param pattern Pattern to search for.
* @param patternLen Length of the pattern.
* @param minTextLen Minimum number of characters that the text needs to possibly match the pattern.
*
* @return TRUE if found, FALSE otherwise.
*
* 1) text=abcdefg textLen=7 pattern=a*d*efg patternLen=7 minTextLen=5
* 1.1) text=bcdefg textLen=6 pattern=d*efg patternLen=5 minTextLen=4
* 1.2) text=cdefg textLen=5 pattern=d*efg patternLen=5 minTextLen=4
* 1.3) text=defg textLen=4 pattern=d*efg patternLen=5 minTextLen=4
* 1.3.1) text=efg textLen=3 pattern=efg patternLen=3 minTextLen=3
*/
int wildcardMatchInner(const TCHAR *text, size_t textLen, const TCHAR *pattern, size_t patternLen, size_t minTextLen) {
size_t textIndex;
size_t patternIndex;
TCHAR patternChar;
size_t textIndex2;
TCHAR textChar;
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d)"), text, textLen, pattern, patternLen, minTextLen);*/
textIndex = 0;
patternIndex = 0;
while ((textIndex < textLen) && (patternIndex < patternLen)) {
patternChar = pattern[patternIndex];
if (patternChar == TEXT('*')) {
/* The pattern '*' can match 0 or more characters. This requires a bit of recursion to work it out. */
textIndex2 = textIndex;
/* Loop over all possible starting locations. We know how many characters are needed to match (minTextLen - patternIndex) so we can stop there. */
while (textIndex2 < textLen - (minTextLen - (patternIndex + 1))) {
if (wildcardMatchInner(&(text[textIndex2]), textLen - textIndex2, &(pattern[patternIndex + 1]), patternLen - (patternIndex + 1), minTextLen - patternIndex)) {
/* Got a match in recursion. */
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d) -> HERE1 textIndex=%d, patternIndex=%d, textIndex2=%d TRUE"), text, textLen, pattern, patternLen, minTextLen, textIndex, patternIndex, textIndex2);*/
return TRUE;
} else {
/* Failed to match. Try matching one more character against the '*'. */
textIndex2++;
}
}
/* If we get here then all possible starting locations failed. */
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d) -> HERE2 textIndex=%d, patternIndex=%d, textIndex2=%d FALSE"), text, textLen, pattern, patternLen, minTextLen, textIndex, patternIndex, textIndex2);*/
return FALSE;
} else if (patternChar == TEXT('?')) {
/* Match any character. */
patternIndex++;
textIndex++;
} else {
textChar = text[textIndex];
if (patternChar == textChar) {
/* Characters match. */
patternIndex++;
textIndex++;
} else {
/* Characters do not match. We are done. */
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d) -> HERE3 textIndex=%d, patternIndex=%d FALSE"), text, textLen, pattern, patternLen, minTextLen, textIndex, patternIndex);*/
return FALSE;
}
}
}
/* It is ok if there are text characters left over as we only need to match a substring, not the whole string. */
/* If there are any pattern chars left. Make sure that they are all wildcards. */
while (patternIndex < patternLen) {
if (pattern[patternIndex] != TEXT('*')) {
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d) -> HERE4 pattern[%d]=%c FALSE"), text, textLen, pattern, patternLen, minTextLen, patternIndex, pattern[patternIndex]);*/
return FALSE;
}
patternIndex++;
}
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" wildcardMatchInner(\"%s\", %d, \"%s\", %d, %d) -> HERE5 textIndex=%d, patternIndex=%d TRUE"), text, textLen, pattern, patternLen, minTextLen, textIndex, patternIndex);*/
return TRUE;
}
/**
* Test function to pause the current thread for the specified amount of time.
* This is used to test how the rest of the Wrapper behaves when a particular
* thread blocks for any reason.
*
* @param pauseTime Number of seconds to pause for. -1 will pause indefinitely.
* @param threadName Name of the thread that will be logged prior to pausing.
*/
void wrapperPauseThread(int pauseTime, const TCHAR *threadName) {
int i;
if (pauseTime > 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Pausing the \"%s\" thread for %d seconds..."), threadName, pauseTime);
for (i = 0; i < pauseTime; i++) {
wrapperSleep(1000);
}
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Resuming the \"%s\" thread..."), threadName);
} else if (pauseTime < 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Pausing the \"%s\" thread indefinitely."), threadName);
while(TRUE) {
wrapperSleep(1000);
}
}
}
/**
* Function that will recursively attempt to match two strings where the
* pattern can contain '?' or '*' wildcard characters.
*
* @param text Text to be searched.
* @param pattern Pattern to search for.
* @param patternLen Length of the pattern.
* @param minTextLen Minimum number of characters that the text needs to possibly match the pattern.
*
* @return TRUE if found, FALSE otherwise.
*/
int wrapperWildcardMatch(const TCHAR *text, const TCHAR *pattern, size_t minTextLen) {
size_t textLen;
size_t patternLen;
size_t textIndex;
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperWildcardMatch(\"%s\", \"%s\", %d)"), text, pattern, minTextLen);*/
textLen = _tcslen(text);
if (textLen < minTextLen) {
return FALSE;
}
patternLen = _tcslen(pattern);
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" textLen=%d, patternLen=%d"), textLen, patternLen);*/
textIndex = 0;
while (textIndex <= textLen - minTextLen) {
if (wildcardMatchInner(&(text[textIndex]), textLen - textIndex, pattern, patternLen, minTextLen)) {
return TRUE;
}
textIndex++;
}
return FALSE;
}
/**
* Calculates the minimum text length which could be matched by the specified pattern.
* Patterns can contain '*' or '?' wildcards.
* '*' matches 0 or more characters.
* '?' matches exactly one character.
*
* @param pattern Pattern to calculate.
*
* @return The minimum text length of the pattern.
*/
size_t wrapperGetMinimumTextLengthForPattern(const TCHAR *pattern) {
size_t patternLen;
size_t patternIndex;
size_t minLen;
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperGetMinimumTextLengthForPattern(%s)"), pattern);*/
patternLen = _tcslen(pattern);
minLen = 0;
for (patternIndex = 0; patternIndex < patternLen; patternIndex++) {
if (pattern[patternIndex] == TEXT('*')) {
/* Matches 0 or more characters, so don't increment the minLen */
} else {
minLen++;
}
}
/*log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperGetMinimumTextLengthForPattern(%s) -> %d"), pattern, minLen);*/
return minLen;
}
void logApplyFilters(const TCHAR *log) {
int i;
const TCHAR *filter;
const TCHAR *filterMessage;
int matched;
/* Look for output filters in the output. Only match the first. */
for (i = 0; i < wrapperData->outputFilterCount; i++) {
if (_tcslen(wrapperData->outputFilters[i]) > 0) {
/* The filter is defined. */
matched = FALSE;
filter = wrapperData->outputFilters[i];
if (wrapperData->outputFilterAllowWildFlags[i]) {
if (wrapperWildcardMatch(log, filter, wrapperData->outputFilterMinLens[i])) {
matched = TRUE;
}
} else {
/* Do a simple check to see if the pattern is found exactly as is. */
if (_tcsstr(log, filter)) {
/* Found an exact match for the pattern. */
/* Any wildcards in the pattern can be matched exactly if they exist in the output. This is by design. */
matched = TRUE;
}
}
if (matched) {
filterMessage = wrapperData->outputFilterMessages[i];
if ((!filterMessage) || (_tcslen(filterMessage) <= 0)) {
filterMessage = TEXT("Filter trigger matched.");
}
wrapperProcessActionList(wrapperData->outputFilterActionLists[i], filterMessage, WRAPPER_ACTION_SOURCE_CODE_FILTER, FALSE, 1);
/* break out of the loop */
break;
}
}
}
}
/**
* Logs a single line of child output allowing any filtering
* to be done in a common location.
*/
void logChildOutput(const char* log) {
TCHAR* tlog;
#ifdef UNICODE
int size;
#ifdef WIN32
TCHAR buffer[16];
UINT cp;
#endif
#endif
#ifdef UNICODE
#ifdef WIN32
GetLocaleInfo(GetThreadLocale(), LOCALE_IDEFAULTANSICODEPAGE, buffer, sizeof(buffer));
cp = _ttoi(buffer);
size = MultiByteToWideChar(cp, 0, log, -1 , NULL, 0) + 1;
tlog = (TCHAR*)malloc(size * sizeof(TCHAR));
if (!tlog) {
outOfMemory(TEXT("WLCO"), 1);
return;
}
MultiByteToWideChar(cp, 0, log, -1, (TCHAR*)tlog, size);
#else
size = mbstowcs(NULL, log, 0) + 1;
tlog = malloc(size * sizeof(TCHAR));
if (!tlog) {
outOfMemory(TEXT("WLCO"), 1);
return;
}
mbstowcs(tlog, log, size);
#endif
#else
tlog = (TCHAR*)log;
#endif
log_printf(wrapperData->jvmRestarts, LEVEL_INFO, tlog);
/* Look for output filters in the output. Only match the first. */
logApplyFilters(tlog);
#ifdef UNICODE
free(tlog);
#endif
}
/**
* This function is for moving a buffer inside itself.
*/
void safeMemCpy(char *buffer, size_t target, size_t src, size_t nbyte) {
size_t i;
for (i = 0; i < nbyte; i++) {
buffer[target + i] = buffer[src + i];
}
}
#define CHAR_LF 0x0a
/**
* Read and process any output from the child JVM Process.
*
* When maxTimeMS is non-zero this function will only be allowed to run for that maximum
* amount of time. This is done to make sure the calling function is allowed CPU for
* other activities. When timing out for this reason when there is more data in the
* pipe, this function will return TRUE to let the calling code know that it should
* not to any unnecessary sleeps. Otherwise FALSE will be returned.
*
* @param maxTimeMS The maximum number of milliseconds that this function will be allowed
* to run without returning. In reality no new reads will happen after
* this time, but actual processing may take longer.
*
* @return TRUE if the calling code should call this function again as soon as possible.
*/
int wrapperReadChildOutput(int maxTimeMS) {
struct timeb timeBuffer;
time_t startTime;
int startTimeMillis;
time_t now;
int nowMillis;
time_t durr;
char *tempBuffer;
char *cLF;
int currentBlockRead;
size_t loggedOffset;
int defer = FALSE;
int readThisPass = FALSE;
if (!wrapperChildWorkBuffer) {
/* Initialize the wrapperChildWorkBuffer. Set its initial size to the block size + 1.
* This is so that we can always add a \0 to the end of it. */
wrapperChildWorkBuffer = malloc(sizeof(char) * ((READ_BUFFER_BLOCK_SIZE * 2) + 1));
if (!wrapperChildWorkBuffer) {
outOfMemory(TEXT("WRCO"), 1);
return FALSE;
}
wrapperChildWorkBufferSize = READ_BUFFER_BLOCK_SIZE * 2;
}
wrapperGetCurrentTime(&timeBuffer);
startTime = now = timeBuffer.time;
startTimeMillis = nowMillis = timeBuffer.millitm;
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperReadChildOutput() BEGIN"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("now=%ld, nowMillis=%d"), now, nowMillis);
#endif
/* Loop and read in CHILD_BLOCK_SIZE characters at a time.
*
* To keep a JVM outputting lots of content from freezing the Wrapper, we force a return every 250ms. */
while ((maxTimeMS <= 0) || ((durr = (now - startTime) * 1000 + (nowMillis - startTimeMillis)) < maxTimeMS)) {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("durr=%ld"), durr);
#endif
/* If there is not enough space in the work buffer to read in a full block then it needs to be extended. */
if (wrapperChildWorkBufferLen + READ_BUFFER_BLOCK_SIZE > wrapperChildWorkBufferSize) {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Expand buffer."));
#endif
/* Increase the buffer quickly, but try not to get too big. Increase to a size that is the
* greater of size + 1024 or size * 1.1.
* Also make sure the new buffer is larger than the buffer len. This should not be necessary
* but is safer. */
wrapperChildWorkBufferSize = __max(wrapperChildWorkBufferLen + 1, __max(wrapperChildWorkBufferSize + READ_BUFFER_BLOCK_SIZE, wrapperChildWorkBufferSize + wrapperChildWorkBufferSize / 10));
tempBuffer = malloc(wrapperChildWorkBufferSize + 1);
if (!tempBuffer) {
outOfMemory(TEXT("WRCO"), 2);
return FALSE;
}
memcpy(tempBuffer, wrapperChildWorkBuffer, wrapperChildWorkBufferLen);
tempBuffer[wrapperChildWorkBufferLen] = '\0';
free(wrapperChildWorkBuffer);
wrapperChildWorkBuffer = tempBuffer;
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("buffer now %d bytes"), wrapperChildWorkBufferSize);
#endif
}
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Try reading from pipe. totalBuffLen=%d, buffSize=%d"), wrapperChildWorkBufferLen, wrapperChildWorkBufferSize);
#endif
if (wrapperReadChildOutputBlock(wrapperChildWorkBuffer + (wrapperChildWorkBufferLen), (int)(wrapperChildWorkBufferSize - wrapperChildWorkBufferLen), ¤tBlockRead)) {
/* Error already reported. */
return FALSE;
}
if (currentBlockRead > 0) {
/* We read in a block, so increase the length. */
wrapperChildWorkBufferLen += currentBlockRead;
wrapperChildWorkLastDataTime = now;
wrapperChildWorkLastDataTimeMillis = nowMillis;
readThisPass = TRUE;
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" Read %d bytes of new output. totalBuffLen=%d, buffSize=%d"), currentBlockRead, wrapperChildWorkBufferLen, wrapperChildWorkBufferSize);
#endif
}
/* Terminate the string just to avoid errors. The buffer has an extra character to handle this. */
wrapperChildWorkBuffer[wrapperChildWorkBufferLen] = '\0';
/* Loop over the contents of the buffer and try and extract as many lines as possible.
* Keep track of where we are to avoid unnecessary memory copies.
* At this point, the entire buffer will always be unlogged. */
loggedOffset = 0;
defer = FALSE;
while ((wrapperChildWorkBufferLen > loggedOffset) && (!defer)) {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Inner loop. totalBuffLen=%d, loggedOffset=%d, unloggedBuffLen=%d, buffSize=%d"), wrapperChildWorkBufferLen, loggedOffset, wrapperChildWorkBufferLen - loggedOffset, wrapperChildWorkBufferSize);
#endif
/* We have something in the buffer. Loop and see if we have a complete line to log.
* We will always find a LF at the end of the line. On Windows there may be a CR immediately before it. */
cLF = strchr(wrapperChildWorkBuffer + loggedOffset, (char)CHAR_LF);
if (cLF != NULL) {
/* We found a valid LF so we know that a full line is ready to be logged. */
#ifdef WIN32
if ((cLF > wrapperChildWorkBuffer) && ((cLF - sizeof(char))[0] == 0x0d)) {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Found CR+LF"));
#endif
/* Replace the CR with a NULL */
(cLF - sizeof(char))[0] = 0;
} else {
#endif
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Found LF"));
#endif
#ifdef WIN32
}
#endif
/* Replace the LF with a NULL */
cLF[0] = '\0';
/* We have a string to log. */
#ifdef DEBUG_CHILD_OUTPUT
#ifdef UNICODE
/* It is not easy to log the string as is because they are not wide chars. Send it only to stdout. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Log: (see stdout)"));
#ifdef WIN32
wprintf(TEXT("Log: [%S]\n"), wrapperChildWorkBuffer + loggedOffset);
#else
wprintf(TEXT("Log: [%s]\n"), wrapperChildWorkBuffer + loggedOffset);
#endif
#else
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Log: [%s]"), wrapperChildWorkBuffer + loggedOffset);
#endif
#endif
/* Actually log the individual line of output. */
logChildOutput(wrapperChildWorkBuffer + loggedOffset);
/* Update the offset so we know how far we've logged. */
loggedOffset = cLF - wrapperChildWorkBuffer + 1;
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("loggedOffset: %d"), loggedOffset);
#endif
} else {
/* If we read this pass or if the last character is a CR on Windows then we always want to defer. */
if (readThisPass
#ifdef WIN32
|| (wrapperChildWorkBuffer[wrapperChildWorkBufferLen - 1] == 0x0d)
#endif
/* Avoid dumping partial lines because we call this funtion too quickly more than once.
* Never let the line be partial unless more than the LF-Delay threshold has expired. */
|| (wrapperData->logLFDelayThreshold == 0)
|| (((now - wrapperChildWorkLastDataTime) * 1000 + (nowMillis - wrapperChildWorkLastDataTimeMillis)) < wrapperData->logLFDelayThreshold)
) {
#ifdef DEBUG_CHILD_OUTPUT
#ifdef UNICODE
/* It is not easy to log the string as is because they are not wide chars. Send it only to stdout. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Incomplete line. Defer: (see stdout) Age: %d"),
(now - wrapperChildWorkLastDataTime) * 1000 + (nowMillis - wrapperChildWorkLastDataTimeMillis));
#ifdef WIN32
wprintf(TEXT("Defer Log: [%S]\n"), wrapperChildWorkBuffer + loggedOffset);
#else
wprintf(TEXT("Defer Log: [%s]\n"), wrapperChildWorkBuffer + loggedOffset);
#endif
#else
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Incomplete line. Defer: [%s] Age: %d"), wrapperChildWorkBuffer,
(now - wrapperChildWorkLastDataTime) * 1000 + (nowMillis - wrapperChildWorkLastDataTimeMillis));
#endif
#endif
defer = TRUE;
} else {
/* We have an incomplete line, but it was from a previous pass and is old enough, so we want to log it as it may be a prompt.
* This will always be the complete buffer. */
#ifdef DEBUG_CHILD_OUTPUT
#ifdef UNICODE
/* It is not easy to log the string as is because they are not wide chars. Send it only to stdout. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Incomplete line, but log now: (see stdout) Age: %d"),
(now - wrapperChildWorkLastDataTime) * 1000 + (nowMillis - wrapperChildWorkLastDataTimeMillis));
#ifdef WIN32
wprintf(TEXT("Log: [%S]\n"), wrapperChildWorkBuffer + loggedOffset);
#else
wprintf(TEXT("Log: [%s]\n"), wrapperChildWorkBuffer + loggedOffset);
#endif
#else
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Incomplete line, but log now: [%s] Age: %d"), wrapperChildWorkBuffer,
(now - wrapperChildWorkLastDataTime) * 1000 + (nowMillis - wrapperChildWorkLastDataTimeMillis));
#endif
#endif
logChildOutput(wrapperChildWorkBuffer + loggedOffset);
/* We know we read everything. */
loggedOffset = wrapperChildWorkBufferLen;
/* So we can safely reset the loggedOffset and clear the buffer. */
wrapperChildWorkBuffer[0] = '\0';
wrapperChildWorkBufferLen = 0;
loggedOffset = 0;
}
}
}
/* We have read as many lines from the buffered output as possible.
* If we still have any partial lines, then we need to make sure they are moved to the beginning of the buffer so we can read in another block. */
if (loggedOffset > 0) {
if (loggedOffset >= wrapperChildWorkBufferLen) {
/* We know we have read everything in. So we can efficiently clear the buffer. */
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Cleared Buffer as everything was logged."));
#endif
wrapperChildWorkBuffer[0] = '\0';
wrapperChildWorkBufferLen = 0;
/* loggedOffset = 0; Not needed. */
} else {
/* We have logged one or more lines from the buffer, but unlogged content still exists. It needs to be moved to the head of the buffer. */
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("Moving %d bytes in buffer for next cycle."), wrapperChildWorkBufferLen - loggedOffset);
#endif
/* NOTE - This line intentionally does the copy within the same memory space. It is safe the way it is working however. */
wrapperChildWorkBufferLen = wrapperChildWorkBufferLen - loggedOffset;
safeMemCpy(wrapperChildWorkBuffer, 0, loggedOffset, wrapperChildWorkBufferLen);
/* Shouldn't be needed, but just to make sure the buffer has been ended properly */
wrapperChildWorkBuffer[wrapperChildWorkBufferLen] = 0;
/* loggedOffset = 0; Not needed. */
}
} else {
}
if (currentBlockRead <= 0) {
/* All done for now. */
if (wrapperChildWorkBufferLen > 0) {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperReadChildOutput() END (Incomplete)"));
#endif
} else {
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperReadChildOutput() END"));
#endif
}
return FALSE;
}
/* Get the time again */
wrapperGetCurrentTime(&timeBuffer);
now = timeBuffer.time;
nowMillis = timeBuffer.millitm;
}
/* If we got here then we timed out. */
#ifdef DEBUG_CHILD_OUTPUT
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperReadChildOutput() END TIMEOUT"));
#endif
return TRUE;
}
/**
* Immediately after a JVM is launched and whenever the log file name changes,
* the log file name is sent to the JVM where it can be referenced by applications.
*/
void sendLogFileName() {
TCHAR *currentLogFilePath;
currentLogFilePath = getCurrentLogfilePath();
wrapperProtocolFunction(WRAPPER_MSG_LOGFILE, currentLogFilePath);
free(currentLogFilePath);
}
/**
* Immediately after a JVM is launched, the wrapper configuration is sent to the
* JVM where it can be used as a properties object.
*/
void sendProperties() {
TCHAR *buffer;
buffer = linearizeProperties(properties, TEXT('\t'));
if (buffer) {
wrapperProtocolFunction(WRAPPER_MSG_PROPERTIES, buffer);
free(buffer);
}
}
/**
* Common cleanup code which should get called when we first decide that the JVM was down.
*/
void wrapperJVMDownCleanup(int setState) {
/* Only set the state to DOWN_CHECK if we are not already in a state which reflects this. */
if (setState) {
if (wrapperData->jvmCleanupTimeout > 0) {
wrapperSetJavaState(WRAPPER_JSTATE_DOWN_CHECK, wrapperGetTicks(), wrapperData->jvmCleanupTimeout);
} else {
wrapperSetJavaState(WRAPPER_JSTATE_DOWN_CHECK, wrapperGetTicks(), -1);
}
}
/* Remove java pid file if it was registered and created by this process. */
if (wrapperData->javaPidFilename) {
_tunlink(wrapperData->javaPidFilename);
}
#ifdef WIN32
if (!CloseHandle(wrapperData->javaProcess)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("Failed to close the Java process handle: %s"), getLastErrorText());
}
wrapperData->javaProcess = NULL;
#endif
/* Close any open socket to the JVM */
if (wrapperData->stoppedPacketReceived) {
wrapperProtocolClose();
} else {
/* Leave the socket open so the Wrapper has the chance to read any outstanding packets. */
}
}
/**
* Immediately kill the JVM process and set the JVM state to
* WRAPPER_JSTATE_DOWN_CHECK.
*/
int wrapperKillProcessNow() {
#ifdef WIN32
int ret;
#endif
/* Check to make sure that the JVM process is still running */
#ifdef WIN32
ret = WaitForSingleObject(wrapperData->javaProcess, 0);
if (ret == WAIT_TIMEOUT) {
#else
if (waitpid(wrapperData->javaPID, NULL, WNOHANG) == 0) {
#endif
/* JVM is still up when it should have already stopped itself. */
/* The JVM process is not responding so the only choice we have is to
* kill it. */
#ifdef WIN32
/* The TerminateProcess funtion will kill the process, but it
* does not correctly notify the process's DLLs that it is shutting
* down. Ideally, we would call ExitProcess, but that can only be
* called from within the process being killed. */
if (TerminateProcess(wrapperData->javaProcess, 0)) {
#else
if (kill(wrapperData->javaPID, SIGKILL) == 0) {
#endif
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("JVM did not exit on request, termination requested."));
return FALSE;
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("JVM did not exit on request."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT(" Attempt to terminate process failed: %s"), getLastErrorText());
/* Terminating the current JVM failed. Cancel pending restart requests */
wrapperJVMDownCleanup(TRUE);
wrapperData->exitCode = 1;
return TRUE;
}
}
wrapperJVMDownCleanup(TRUE);
return FALSE;
}
/**
* Puts the Wrapper into a state where the JVM will be killed at the soonest
* possible opportunity. It is necessary to wait a moment if a final thread
* dump is to be requested. This call wll always set the JVM state to
* WRAPPER_JSTATE_KILLING.
*/
void wrapperKillProcess() {
#ifdef WIN32
int ret;
#endif
int delay = 0;
if ((wrapperData->jState == WRAPPER_JSTATE_DOWN_CLEAN) ||
(wrapperData->jState == WRAPPER_JSTATE_LAUNCH_DELAY) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CHECK) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_FLUSH)) {
/* Already down. */
if (wrapperData->jState == WRAPPER_JSTATE_LAUNCH_DELAY) {
wrapperSetJavaState(WRAPPER_JSTATE_DOWN_CLEAN, wrapperGetTicks(), 0);
}
return;
}
/* Check to make sure that the JVM process is still running */
#ifdef WIN32
ret = WaitForSingleObject(wrapperData->javaProcess, 0);
if (ret == WAIT_TIMEOUT) {
#else
if (waitpid(wrapperData->javaPID, NULL, WNOHANG) == 0) {
#endif
/* JVM is still up when it should have already stopped itself. */
if (wrapperData->requestThreadDumpOnFailedJVMExit) {
wrapperRequestDumpJVMState();
delay = wrapperData->requestThreadDumpOnFailedJVMExitDelay;
}
}
wrapperSetJavaState(WRAPPER_JSTATE_KILLING, wrapperGetTicks(), delay);
}
/**
* Add some checks of the properties to try to catch the case where the user is making use of TestWrapper scripts.
*
* @return TRUE if there is such a missconfiguration. FALSE if all is Ok.
*/
int checkForTestWrapperScripts() {
const TCHAR* prop;
prop = getStringProperty(properties, TEXT("wrapper.java.mainclass"), NULL);
if (prop) {
if (_tcscmp(prop, TEXT("org.tanukisoftware.wrapper.test.Main")) == 0) {
/* This is the TestWrapper app. So don't check. */
} else {
/* This is a user application, so make sure that they are not using the TestWrapper scripts. */
prop = getStringProperty(properties, TEXT("wrapper.app.parameter.2"), NULL);
if (prop) {
if (_tcscmp(prop, TEXT("{{TestWrapperBat}}")) == 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"--------------------------------------------------------------------"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"We have detected that you are making use of the sample batch files\nthat are designed for the TestWrapper Example Application. When\nsetting up your own application, please copy fresh files over from\nthe Wrapper's src\\bin directory."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"Shutting down as this will likely cause problems with your\napplication startup."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"Please see the integration section of the documentation for more\ninformation."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
" http://wrapper.tanukisoftware.com/integrate"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"--------------------------------------------------------------------"));
return TRUE;
} else if (_tcscmp(prop, TEXT("{{TestWrapperSh}}")) == 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"--------------------------------------------------------------------"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"We have detected that you are making use of the sample shell scripts\nthat are designed for the TestWrapper Example Application. When\nsetting up your own application, please copy fresh files over from\nthe Wrapper's src/bin directory."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"Shutting down as this will likely cause problems with your\napplication startup."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"Please see the integration section of the documentation for more\ninformation."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
" http://wrapper.tanukisoftware.com/integrate"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"--------------------------------------------------------------------"));
return TRUE;
}
}
}
}
return FALSE;
}
#ifdef WIN32
#define OSBUFSIZE 256
/**
* Creates a human readable representation of the Windows OS the Wrapper is run on.
*
* @param pszOS the buffer the information gets stored to
* @return FALSE if error or no information could be retrieved. TRUE otherwise.
*/
BOOL GetOSDisplayString(TCHAR** pszOS) {
OSVERSIONINFOEX osvi;
SYSTEM_INFO si;
FARPROC pGNSI;
FARPROC pGPI;
DWORD dwType;
TCHAR buf[80];
ZeroMemory(&si, sizeof(SYSTEM_INFO));
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!GetVersionEx((OSVERSIONINFO*) &osvi)) {
return FALSE;
}
/* Call GetNativeSystemInfo if supported or GetSystemInfo otherwise.*/
pGNSI = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
if (NULL != pGNSI) {
pGNSI(&si);
} else {
GetSystemInfo(&si);
}
if ((VER_PLATFORM_WIN32_NT == osvi.dwPlatformId) && (osvi.dwMajorVersion > 4)) {
_tcsncpy(*pszOS, TEXT("Microsoft "), OSBUFSIZE);
/* Test for the specific product. */
if (osvi.dwMajorVersion == 6) {
if (osvi.dwMinorVersion == 0 ) {
if (osvi.wProductType == VER_NT_WORKSTATION) {
_tcsncat(*pszOS, TEXT("Windows Vista "), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Windows Server 2008 "), OSBUFSIZE);
}
}
if (osvi.dwMinorVersion == 1) {
if (osvi.wProductType == VER_NT_WORKSTATION) {
_tcsncat(*pszOS, TEXT("Windows 7 "), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Windows Server 2008 R2 "), OSBUFSIZE);
}
}
pGPI = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo");
pGPI(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType);
switch (dwType) {
case 1:
_tcsncat(*pszOS, TEXT("Ultimate Edition" ), OSBUFSIZE);
break;
case 48:
_tcsncat(*pszOS, TEXT("Professional"), OSBUFSIZE);
break;
case 3:
_tcsncat(*pszOS, TEXT("Home Premium Edition"), OSBUFSIZE);
break;
case 67:
_tcsncat(*pszOS, TEXT("Home Basic Edition"), OSBUFSIZE);
break;
case 4:
_tcsncat(*pszOS, TEXT("Enterprise Edition"), OSBUFSIZE);
break;
case 6:
_tcsncat(*pszOS, TEXT("Business Edition"), OSBUFSIZE);
break;
case 11:
_tcsncat(*pszOS, TEXT("Starter Edition"), OSBUFSIZE);
break;
case 18:
_tcsncat(*pszOS, TEXT("Cluster Server Edition"), OSBUFSIZE);
break;
case 8:
_tcsncat(*pszOS, TEXT("Datacenter Edition"), OSBUFSIZE);
break;
case 12:
_tcsncat(*pszOS, TEXT("Datacenter Edition (core installation)"), OSBUFSIZE);
break;
case 10:
_tcsncat(*pszOS, TEXT("Enterprise Edition"), OSBUFSIZE);
break;
case 14:
_tcsncat(*pszOS, TEXT("Enterprise Edition (core installation)"), OSBUFSIZE);
break;
case 15:
_tcsncat(*pszOS, TEXT("Enterprise Edition for Itanium-based Systems"), OSBUFSIZE);
break;
case 9:
_tcsncat(*pszOS, TEXT("Small Business Server"), OSBUFSIZE);
break;
case 25:
_tcsncat(*pszOS, TEXT("Small Business Server Premium Edition"), OSBUFSIZE);
break;
case 7:
_tcsncat(*pszOS, TEXT("Standard Edition"), OSBUFSIZE);
break;
case 13:
_tcsncat(*pszOS, TEXT("Standard Edition (core installation)"), OSBUFSIZE);
break;
case 17:
_tcsncat(*pszOS, TEXT("Web Server Edition"), OSBUFSIZE);
break;
}
}
if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2)) {
if (GetSystemMetrics(89)) {
_tcsncat(*pszOS, TEXT("Windows Server 2003 R2, "), OSBUFSIZE);
} else if (osvi.wSuiteMask & 8192) {
_tcsncat(*pszOS, TEXT("Windows Storage Server 2003"), OSBUFSIZE);
} else if (osvi.wSuiteMask & 32768) {
_tcsncat(*pszOS, TEXT("Windows Home Server"), OSBUFSIZE);
} else if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) {
_tcsncat(*pszOS, TEXT("Windows XP Professional x64 Edition"), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Windows Server 2003, "), OSBUFSIZE);
}
/* Test for the server type. */
if (osvi.wProductType != VER_NT_WORKSTATION) {
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) {
if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
_tcsncat(*pszOS, TEXT("Datacenter Edition for Itanium-based Systems"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
_tcsncat(*pszOS, TEXT("Enterprise Edition for Itanium-based Systems"), OSBUFSIZE);
}
} else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
_tcsncat(*pszOS, TEXT("Datacenter x64 Edition"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
_tcsncat(*pszOS, TEXT("Enterprise x64 Edition"), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Standard x64 Edition"), OSBUFSIZE);
}
} else {
if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER) {
_tcsncat(*pszOS, TEXT("Compute Cluster Edition"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
_tcsncat(*pszOS, TEXT("Datacenter Edition"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
_tcsncat(*pszOS, TEXT("Enterprise Edition"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_BLADE) {
_tcsncat(*pszOS, TEXT("Web Edition" ), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Standard Edition"), OSBUFSIZE);
}
}
}
}
if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1)) {
_tcsncat(*pszOS, TEXT("Windows XP "), OSBUFSIZE);
if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
_tcsncat(*pszOS, TEXT("Home Edition"), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Professional"), OSBUFSIZE);
}
}
if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0)) {
_tcsncat(*pszOS, TEXT("Windows 2000 "), OSBUFSIZE);
if (osvi.wProductType == VER_NT_WORKSTATION) {
_tcsncat(*pszOS, TEXT("Professional"), OSBUFSIZE);
} else {
if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
_tcsncat(*pszOS, TEXT("Datacenter Server"), OSBUFSIZE);
} else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
_tcsncat(*pszOS, TEXT("Advanced Server"), OSBUFSIZE);
} else {
_tcsncat(*pszOS, TEXT("Server"), OSBUFSIZE);
}
}
}
/* Include service pack (if any) and build number. */
if (_tcslen(osvi.szCSDVersion) > 0) {
_tcsncat(*pszOS, TEXT(" "), OSBUFSIZE);
_tcsncat(*pszOS, osvi.szCSDVersion, OSBUFSIZE);
}
_sntprintf(buf, 80, TEXT(" (build %d)"), osvi.dwBuildNumber);
_tcsncat(*pszOS, buf, OSBUFSIZE);
if (osvi.dwMajorVersion >= 6) {
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
_tcsncat(*pszOS, TEXT(", 64-bit"), OSBUFSIZE);
} else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) {
_tcsncat(*pszOS, TEXT(", 32-bit"), OSBUFSIZE);
}
}
return TRUE;
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Unknown Windows Version"));
return FALSE;
}
}
#endif
/**
* Launch common setup code.
*/
int wrapperRunCommonInner() {
const TCHAR *prop;
#ifdef WIN32
TCHAR* szOS;
#endif
struct tm timeTM;
TCHAR* tz1;
TCHAR* tz2;
#if defined(UNICODE)
size_t req;
#endif
/* Make sure the tick timer is working correctly. */
if (wrapperTickAssertions()) {
return 1;
}
/* Log a startup banner. */
wrapperVersionBanner();
/* The following code will display a licensed to block if a license key is found
* in the Wrapper configuration. This piece of code is required as is for
* Development License owners to be in complience with their development license.
* This code does not do any validation of the license keys and works differently
* from the license code found in the Standard and Professional Editions of the
* Wrapper. */
prop = getStringProperty(properties, TEXT("wrapper.license.type"), TEXT(""));
if (strcmpIgnoreCase(prop, TEXT("DEV")) == 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS,
TEXT(" Licensed to %s for %s"),
getStringProperty(properties, TEXT("wrapper.license.licensee"), TEXT("(LICENSE INVALID)")),
getStringProperty(properties, TEXT("wrapper.license.dev_application"), TEXT("(LICENSE INVALID)")));
}
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
if (checkForTestWrapperScripts()) {
return 1;
}
#ifdef WIN32
if (initializeStartup()) {
return 1;
}
#endif
if (wrapperData->isDebugging) {
timeTM = wrapperGetReleaseTime();
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Release time: %04d/%02d/%02d %02d:%02d:%02d"),
timeTM.tm_year + 1900, timeTM.tm_mon + 1, timeTM.tm_mday,
timeTM.tm_hour, timeTM.tm_min, timeTM.tm_sec );
timeTM = wrapperGetBuildTime();
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Build time: %04d/%02d/%02d %02d:%02d:%02d"),
timeTM.tm_year + 1900, timeTM.tm_mon + 1, timeTM.tm_mday,
timeTM.tm_hour, timeTM.tm_min, timeTM.tm_sec );
/* Display timezone information. */
tzset();
#if defined(UNICODE)
#if !defined(WIN32)
req = mbstowcs(NULL, tzname[0], 0) + 1;
tz1 = malloc(req * sizeof(TCHAR));
if (!tz1) {
outOfMemory(TEXT("LHN"), 1);
} else {
mbstowcs(tz1, tzname[0], req);
req = mbstowcs(NULL, tzname[1], 0) + 1;
tz2 = malloc(req * sizeof(TCHAR));
if (!tz2) {
outOfMemory(TEXT("LHN"), 2);
free(tz1);
} else {
mbstowcs(tz2, tzname[1], req);
#else
req = MultiByteToWideChar(CP_OEMCP, 0, tzname[0], -1, NULL, 0);
tz1 = malloc(req * sizeof(TCHAR));
if (!tz1) {
outOfMemory(TEXT("LHN"), 1);
} else {
MultiByteToWideChar(CP_OEMCP,0, tzname[0], -1, tz1, (int)req);
req = MultiByteToWideChar(CP_OEMCP, 0, tzname[1], -1, NULL, 0);
tz2 = malloc(req * sizeof(TCHAR));
if (!tz2) {
free(tz1);
outOfMemory(TEXT("LHN"), 2);
} else {
MultiByteToWideChar(CP_OEMCP,0, tzname[1], -1, tz2, (int)req);
#endif
#else
tz1 = tzname[0];
tz2 = tzname[1];
#endif
#ifndef FREEBSD
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Timezone: %s (%s) Offset: %ld, hasDaylight: %d"),
tz1, tz2, timezone, daylight);
#else
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Timezone: %s (%s) Offset: %ld"),
tz1, tz2, timezone);
#endif
if (wrapperData->useSystemTime) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Using system timer."));
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Using tick timer."));
}
#ifdef UNICODE
free(tz1);
free(tz2);
}
}
#endif
}
#ifdef WIN32
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Current User: %s Domain: %s"), (wrapperData->userName ? wrapperData->userName : TEXT("N/A")), (wrapperData->domainName ? wrapperData->domainName : TEXT("N/A")));
szOS = calloc(OSBUFSIZE, sizeof(TCHAR));
if (szOS) {
if (GetOSDisplayString(&szOS)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Operating System ID: %s"), szOS);
}
free(szOS);
}
}
#endif
/* Should we dump the environment variables?
* If the the user specifically wants the environment, show it as the status log level, otherwise include it in debug output if enabled. */
if (getBooleanProperty(properties, TEXT("wrapper.environment.dump"), FALSE)) {
dumpEnvironment(LEVEL_INFO);
} else if (getBooleanProperty(properties, TEXT("wrapper.debug"), FALSE)) {
dumpEnvironment(LEVEL_DEBUG);
}
#ifdef _DEBUG
/* Multi-line logging tests. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("----- Should be 5 lines -----"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("\nLINE2:\n\nLINE4:\n"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("----- Next is one line ------"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(""));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("----- Next is two lines -----"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("\n"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("----- Next is two lines -----"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("ABC\nDEF"));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("-----------------------------"));
#endif
#ifdef WRAPPER_FILE_DEBUG
wrapperFileTests();
#endif
return 0;
}
int wrapperRunCommon(const TCHAR *runMode) {
int exitCode;
/* Setup the wrapperData structure. */
wrapperSetWrapperState(WRAPPER_WSTATE_STARTING);
wrapperSetJavaState(WRAPPER_JSTATE_DOWN_CLEAN, 0, -1);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("--> Wrapper Started as %s"), runMode);
/* Initialize the wrapper */
exitCode = wrapperInitializeRun();
if (exitCode == 0) {
if (!wrapperRunCommonInner()) {
/* Enter main event loop */
wrapperEventLoop();
/* Clean up any open sockets. */
wrapperProtocolClose();
protocolStopServer();
exitCode = wrapperData->exitCode;
} else {
exitCode = 1;
}
}
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("<-- Wrapper Stopped"));
return exitCode;
}
/**
* Launch the wrapper as a console application.
*/
int wrapperRunConsole() {
return wrapperRunCommon(TEXT("Console"));
}
/**
* Launch the wrapper as a service application.
*/
int wrapperRunService() {
return wrapperRunCommon(
#ifdef WIN32
TEXT("Service")
#else
TEXT("Daemon")
#endif
);
}
/**
* Used to ask the state engine to shut down the JVM and Wrapper.
*
* @param exitCode Exit code to use when shutting down.
* @param force True to force the Wrapper to shutdown even if some configuration
* had previously asked that the JVM be restarted. This will reset
* any existing restart requests, but it will still be possible for
* later actions to request a restart.
*/
void wrapperStopProcess(int exitCode, int force) {
/* If we are are not aready shutting down, then do so. */
if ((wrapperData->wState == WRAPPER_WSTATE_STOPPING) ||
(wrapperData->wState == WRAPPER_WSTATE_STOPPED)) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("wrapperStopProcess(%d, %s) called while stopping. (IGNORED)"), exitCode, (force ? TEXT("TRUE") : TEXT("FALSE")));
}
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("wrapperStopProcess(%d, %s) called."), exitCode, (force ? TEXT("TRUE") : TEXT("FALSE")));
}
/* If it has not already been set, set the exit request flag. */
if (wrapperData->exitRequested ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CLEAN) ||
(wrapperData->jState == WRAPPER_JSTATE_STOP) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPING) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPED) ||
(wrapperData->jState == WRAPPER_JSTATE_KILLING) ||
(wrapperData->jState == WRAPPER_JSTATE_KILLED) ||
(wrapperData->jState == WRAPPER_JSTATE_KILL) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CHECK) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_FLUSH)) {
/* JVM is already down or going down. */
} else {
wrapperData->exitRequested = TRUE;
}
wrapperData->exitCode = exitCode;
if (force) {
/* Make sure that further restarts are disabled. */
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_NO;
/* Do not call wrapperSetWrapperState(WRAPPER_WSTATE_STOPPING) here.
* It will be called by the wrappereventloop.c.jStateDown once the
* the JVM is completely down. Calling it here will make it
* impossible to trap and restart based on exit codes or other
* Wrapper configurations. */
if (wrapperData->isDebugging) {
if ((wrapperData->restartRequested == WRAPPER_RESTART_REQUESTED_AUTOMATIC) || (wrapperData->restartRequested == WRAPPER_RESTART_REQUESTED_CONFIGURED)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(" Overriding request to restart JVM."));
}
}
} else {
/* Do not call wrapperSetWrapperState(WRAPPER_WSTATE_STOPPING) here.
* It will be called by the wrappereventloop.c.jStateDown once the
* the JVM is completely down. Calling it here will make it
* impossible to trap and restart based on exit codes. */
if (wrapperData->isDebugging) {
if ((wrapperData->restartRequested == WRAPPER_RESTART_REQUESTED_AUTOMATIC) || (wrapperData->restartRequested == WRAPPER_RESTART_REQUESTED_CONFIGURED)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(" Stop ignored. Continuing to restart JVM."));
}
}
}
}
}
/**
* Used to ask the state engine to shut down the JVM. This are always intentional restart requests.
*/
void wrapperRestartProcess() {
/* If it has not already been set, set the restart request flag in the wrapper data. */
if (wrapperData->exitRequested || wrapperData->restartRequested ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CLEAN) ||
(wrapperData->jState == WRAPPER_JSTATE_STOP) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPING) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPED) ||
(wrapperData->jState == WRAPPER_JSTATE_KILLING) ||
(wrapperData->jState == WRAPPER_JSTATE_KILL) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_CHECK) ||
(wrapperData->jState == WRAPPER_JSTATE_DOWN_FLUSH) ||
(wrapperData->jState == WRAPPER_JSTATE_LAUNCH_DELAY)) { /* Down but not yet restarted. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("wrapperRestartProcess() called. (IGNORED)"));
}
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("wrapperRestartProcess() called."));
}
wrapperData->exitRequested = TRUE;
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_CONFIGURED;
}
}
/**
* Used to ask the state engine to pause the JVM.
*
* @param actionSourceCode Tracks where the action originated.
*/
void wrapperPauseProcess(int actionSourceCode) {
TCHAR msgBuffer[10];
if (!wrapperData->pausable) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperPauseProcess() called but wrapper.pausable is FALSE. (IGNORED)"));
}
return;
}
if ((wrapperData->wState == WRAPPER_WSTATE_STOPPING) ||
(wrapperData->wState == WRAPPER_WSTATE_STOPPED)) {
/* If we are already shutting down, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperPauseProcess() called while stopping. (IGNORED)"));
}
} else if (wrapperData->wState == WRAPPER_WSTATE_PAUSING) {
/* If we are currently being paused, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperPauseProcess() called while pausing. (IGNORED)"));
}
} else if (wrapperData->wState == WRAPPER_WSTATE_PAUSED) {
/* If we are currently paused, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperPauseProcess() called while paused. (IGNORED)"));
}
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperPauseProcess() called."));
}
wrapperSetWrapperState(WRAPPER_WSTATE_PAUSING);
if (!wrapperData->pausableStopJVM) {
/* Notify the Java process. */
_sntprintf(msgBuffer, 10, TEXT("%d"), actionSourceCode);
wrapperProtocolFunction(WRAPPER_MSG_PAUSE, msgBuffer);
}
}
}
/**
* Used to ask the state engine to resume a paused the JVM.
*
* @param actionSourceCode Tracks where the action originated.
*/
void wrapperResumeProcess(int actionSourceCode) {
TCHAR msgBuffer[10];
if ((wrapperData->wState == WRAPPER_WSTATE_STOPPING) ||
(wrapperData->wState == WRAPPER_WSTATE_STOPPED)) {
/* If we are already shutting down, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperResumeProcess() called while stopping. (IGNORED)"));
}
} else if (wrapperData->wState == WRAPPER_WSTATE_STARTING) {
/* If we are currently being started, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperResumeProcess() called while starting. (IGNORED)"));
}
} else if (wrapperData->wState == WRAPPER_WSTATE_STARTED) {
/* If we are currently started, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperResumeProcess() called while started. (IGNORED)"));
}
} else if (wrapperData->wState == WRAPPER_WSTATE_RESUMING) {
/* If we are currently being continued, then ignore and continue to do so. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperResumeProcess() called while resuming. (IGNORED)"));
}
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"wrapperResumeProcess() called."));
}
/* If we were configured to stop the JVM then we want to reset its failed
* invocation count as the current stoppage was expected. */
if (wrapperData->pausableStopJVM) {
wrapperData->failedInvocationCount = 0;
}
wrapperSetWrapperState(WRAPPER_WSTATE_RESUMING);
if (!wrapperData->pausableStopJVM) {
/* Notify the Java process. */
_sntprintf(msgBuffer, 10, TEXT("%d"), actionSourceCode);
wrapperProtocolFunction(WRAPPER_MSG_RESUME, msgBuffer);
}
}
}
/**
* Sends a command off to the JVM asking it to perform a garbage collection sweep.
*
* @param actionSourceCode Tracks where the action originated.
*/
void wrapperRequestJVMGC(int actionSourceCode) {
TCHAR msgBuffer[10];
/* Notify the Java process. */
_sntprintf(msgBuffer, 10, TEXT("%d"), actionSourceCode);
wrapperProtocolFunction(WRAPPER_MSG_GC, msgBuffer);
}
/**
* Loops over and strips all double quotes from prop and places the
* stripped version into propStripped.
*
* The exception is double quotes that are preceeded by a backslash
* in this case the backslash is stripped.
*
* If two backslashes are found in a row, then the first escapes the
* second and the second is removed.
*/
static size_t wrapperStripQuotesInner(const TCHAR *prop, size_t propLen, TCHAR *propStripped) {
size_t len;
int i, j;
len = propLen;
j = 0;
for (i = 0; i < (int)len; i++) {
if ((prop[i] == TEXT('\\')) && (i < (int)len - 1)) {
if (prop[i + 1] == TEXT('\\')) {
/* Double backslash. Keep the first, and skip the second. */
propStripped[j] = prop[i];
j++;
i++;
} else if (prop[i + 1] == TEXT('\"')) {
/* Escaped quote. Keep the quote. */
propStripped[j] = prop[i + 1];
j++;
i++;
} else {
/* Include the backslash as normal. */
propStripped[j] = prop[i];
j++;
}
} else if (prop[i] == TEXT('\"')) {
/* Quote. Skip it. */
} else {
propStripped[j] = prop[i];
j++;
}
}
return j;
}
void wrapperStripQuotes(const TCHAR *prop, TCHAR *propStripped) {
size_t len;
len = wrapperStripQuotesInner(prop, _tcslen(prop), propStripped);
propStripped[len] = TEXT('\0');
}
/*
* Corrects a windows path in place by replacing all '/' characters with '\'
* on Windows versions.
*
* filename - Filename to be modified. Could be null.
*/
void correctWindowsPath(TCHAR *filename) {
#ifdef WIN32
TCHAR *c;
if (filename) {
c = (TCHAR *)filename;
while((c = _tcschr(c, TEXT('/'))) != NULL) {
c[0] = TEXT('\\');
}
}
#endif
}
/**
* Adds quotes around the specified string in such a way that everything is
* escaped correctly. If the bufferSize is not large enough then the
* required size will be returned. 0 is returned if successful.
*/
size_t wrapperQuoteValue(const TCHAR* value, TCHAR *buffer, size_t bufferSize) {
size_t len = _tcslen(value);
size_t in = 0;
size_t out = 0;
size_t in2;
int escape;
/* Initial quote. */
if (out < bufferSize) {
buffer[out] = TEXT('"');
}
out++;
/* Copy over characters of value. */
while ((in < len) && (value[in] != TEXT('\0'))) {
escape = FALSE;
if (value[in] == TEXT('\\')) {
/* All '\' characters in a row prior to a '"' or the end of the string need to be
* escaped */
in2 = in + 1;
while ((in2 < len) && (value[in2] == TEXT('\\'))) {
in2++;
}
escape = ((in2 >= len) || (value[in2] == TEXT('"')));
} else if (value[in] == TEXT('"')) {
escape = TRUE;
}
if (escape) {
/* Needs to be escaped. */
if (out < bufferSize) {
buffer[out] = TEXT('\\');
}
out++;
}
if (out < bufferSize) {
buffer[out] = value[in];
}
out++;
in++;
}
/* Trailing quote. */
if (out < bufferSize) {
buffer[out] = TEXT('"');
}
out++;
/* Null terminate. */
if (out < bufferSize) {
buffer[out] = TEXT('\0');
}
out++;
if (out <= bufferSize) {
return 0;
} else {
return out;
}
}
/**
* Checks the quotes in the value and displays an error if there are any problems.
* This can be useful to help users debug quote problems.
*/
int wrapperCheckQuotes(const TCHAR *value, const TCHAR *propName) {
size_t len = _tcslen(value);
size_t in = 0;
size_t in2 = 0;
int inQuote = FALSE;
int escaped;
while (in < len) {
if (value[in] == TEXT('"')) {
/* Decide whether or not this '"' is escaped. */
in2 = in - 1;
escaped = FALSE;
while (value[in2] == TEXT('\\')) {
escaped = !escaped;
if (in2 > 0) {
in2--;
} else {
break;
}
}
if (!escaped) {
inQuote = !inQuote;
}
} else if (inQuote) {
/* Quoted text. */
} else {
/* Unquoted. white space is bad. */
if (value[in] == TEXT(' ')) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("The value of property '%s', '%s' contains unquoted spaces and will most likely result in an invalid java command line."),
propName, value);
return 1;
}
}
in++;
}
if (inQuote) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("The value of property '%s', '%s' contains an unterminated quote and will most likely result in an invalid java command line."),
propName, value);
return 1;
}
return 0;
}
#ifndef WIN32
int checkIfExecutable(const TCHAR *filename) {
int result;
#if defined(WIN32) && !defined(WIN64)
struct _stat64i32 statInfo;
#else
struct stat statInfo;
#endif
result = _tstat(filename, &statInfo);
if (result < 0) {
return 0;
}
if (!S_ISREG(statInfo.st_mode)) {
return 0;
}
if (statInfo.st_uid == geteuid()) {
return statInfo.st_mode & S_IXUSR;
}
if (statInfo.st_gid == getegid()) {
return statInfo.st_mode & S_IXGRP;
}
return statInfo.st_mode & S_IXOTH;
}
#endif
int checkIfBinary(const TCHAR *filename) {
FILE* f;
unsigned char head[5];
int r;
f = _tfopen(filename, TEXT("rb"));
if (!f) { /*couldnt find the java command... wrapper will moan later*/
return 1;
} else {
r = (int)fread( head,1, 4, f);
if (r != 4)
{
fclose(f);
return 0;
}
fclose(f);
head[4] = '\0';
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Magic number for file %s: 0x%02x%02x%02x%02x"), filename, head[0], head[1], head[2], head[3]);
}
#if defined(LINUX) || defined(FREEBSD) || defined(KFREEBSD) || defined(SOLARIS)
if (head[1] == 'E' && head[2] == 'L' && head[3] == 'F') {
return 1; /*ELF */
#elif defined(AIX)
/* http://en.wikipedia.org/wiki/XCOFF */
if (head[0] == 0x01 && head[1] == 0xf7 && head[2] == 0x00) { /* 0x01f700NN */
return 1; /*xcoff 64*/
} else if (head[0] == 0x01 && head[1] == 0xdf && head[2] == 0x00) { /* 0x01df00NN */
return 1; /*xcoff 32*/
#elif defined(MACOSX)
if (head[0] == 0xca && head[1] == 0xfe && head[2] == 0xba && head[3] == 0xbe) { /* 0xcafebabe */
return 1; /*MACOS Universal binary*/
} else if (head[0] == 0xcf && head[1] == 0xfa && head[2] == 0xed && head[3] == 0xfe) { /* 0xcffaedfe */
return 1; /*MACOS x86_64 binary*/
} else if (head[0] == 0xce && head[1] == 0xfa && head[2] == 0xed && head[3] == 0xfe) { /* 0xcefaedfe */
return 1; /*MACOS i386 binary*/
} else if (head[0] == 0xfe && head[1] == 0xed && head[2] == 0xfa && head[3] == 0xce) { /* 0xfeedface */
return 1; /*MACOS ppc, ppc64 binary*/
#elif defined(HPUX)
if (head[0] == 0x02 && head[1] == 0x10 && head[2] == 0x01 && head[3] == 0x08) { /* 0x02100108 PA-RISC 1.1 */
return 1; /*HP UX PA RISC 32*/
} else if (head[0] == 0x02 && head[1] == 0x14 && head[2] == 0x01 && head[3] == 0x07) { /* 0x02140107 PA-RISC 2.0 */
return 1; /*HP UX PA RISC 32*/
} else if (head[1] == 'E' && head[2] == 'L' && head[3] == 'F') {
return 1; /*ELF */
#elif defined(WIN32)
if (head[0] == 'M' && head[1] == 'Z') {
return 1; /* MS */
#else
if (FALSE) {
#error I dont know what to do for this host type. (in checkIfBinary())
#endif
} else {
return 0;
}
}
}
#ifndef WIN32
TCHAR* findPathOf(const TCHAR *exe, const TCHAR *name) {
TCHAR *searchPath;
TCHAR *beg, *end;
int stop, found;
TCHAR pth[PATH_MAX + 1];
TCHAR *ret;
TCHAR resolvedPath[PATH_MAX + 1];
if (exe[0] == TEXT('/')) {
/* This is an absolute reference. */
if (_trealpath(exe, resolvedPath)) {
_tcsncpy(pth, resolvedPath, PATH_MAX + 1);
if (checkIfExecutable(pth)) {
ret = malloc((_tcslen(pth) + 1) * sizeof(TCHAR));
if (!ret) {
outOfMemory(TEXT("FPO"), 1);
return NULL;
}
_tcsncpy(ret, pth, _tcslen(pth) + 1);
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Resolved the real path of %s as an absolute reference: %s"), name, ret);
}
return ret;
}
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Unable to resolve the real path of %s as an absolute reference: %s (Problem at: %s)"), name, exe, resolvedPath);
}
}
return NULL;
}
/* This is a non-absolute reference. See if it is a relative reference. */
if (_trealpath(exe, resolvedPath)) {
/* Resolved. See if the file exists. */
_tcsncpy(pth, resolvedPath, PATH_MAX + 1);
if (checkIfExecutable(pth)) {
ret = malloc((_tcslen(pth) + 1) * sizeof(TCHAR));
if (!ret) {
outOfMemory(TEXT("FPO"), 2);
return NULL;
}
_tcsncpy(ret, pth, _tcslen(pth) + 1);
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Resolved the real path of %s as a relative reference: %s"), name, ret);
}
return ret;
}
} else {
if (wrapperData->isDebugging) {
/* Some platforms (MACOSX) will return the point that was the problem, it seems to work
* on some other platforms but is documented as undefined. To be safe and keep things
* in sync, don't use it. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Unable to resolve the real path of %s as a relative reference: %s"), name, exe);
}
}
/* The file was not a direct relative reference. If and only if it does not contain any relative path components, we can search the PATH. */
if (_tcschr(exe, TEXT('/')) == NULL) {
searchPath = _tgetenv(TEXT("PATH"));
if (searchPath && (_tcslen(searchPath) <= 0)) {
#if !defined(WIN32) && defined(UNICODE)
free(searchPath);
#endif
searchPath = NULL;
}
if (searchPath) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Attempt to locate %s on system PATH: %s"), name, exe);
}
beg = searchPath;
stop = 0; found = 0;
do {
end = _tcschr(beg, TEXT(':'));
if (end == NULL) {
/* This is the last element in the PATH, so we want the whole thing. */
stop = 1;
_tcsncpy(pth, beg, PATH_MAX + 1);
} else {
/* Copy the single path entry. */
_tcsncpy(pth, beg, end - beg);
pth[end - beg] = TEXT('\0');
}
if (pth[_tcslen(pth) - 1] != TEXT('/')) {
_tcsncat(pth, TEXT("/"), PATH_MAX + 1);
}
_tcsncat(pth, exe, PATH_MAX + 1);
/* The file can exist on the path, but via a symbolic link, so we need to expand it. Ignore errors here. */
#ifdef _DEBUG
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(" Check PATH entry: %s"), pth);
}
#endif
if (_trealpath(pth, resolvedPath) != NULL) {
/* Copy over the result. */
_tcsncpy(pth, resolvedPath, PATH_MAX + 1);
found = checkIfExecutable(pth);
}
if (!stop) {
beg = end + 1;
}
} while (!stop && !found);
#if !defined(WIN32) && defined(UNICODE)
free(searchPath);
#endif
if (found) {
ret = malloc((_tcslen(pth) + 1) * sizeof(TCHAR));
if (!ret) {
outOfMemory(TEXT("FPO"), 3);
return NULL;
}
_tcsncpy(ret, pth, _tcslen(pth) + 1);
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Resolved the real path of %s from system PATH: %s"), name, ret);
}
return ret;
} else {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Unable to resolve the real path of %s on the system PATH: %s"), name, exe);
}
}
}
}
/* Still did not find the file. So it must not exist. */
return NULL;
}
#endif
/**
* Checks to see if the speicified executable is a regular binary. This will continue
* in either case, but a warning will be logged if the binary is invalid.
*
* @param para The binary to check. On UNIX, the para memory may be freed and reallocated by this call.
*/
void checkIfRegularExe(TCHAR** para) {
TCHAR* path;
#ifdef WIN32
int len, start;
#endif
#ifdef WIN32
if (_tcschr(*para, TEXT('\"')) != NULL){
start = 1;
len = (int)_tcslen(*para) - 2;
} else {
start = 0;
len = (int)_tcslen(*para);
}
path = malloc(sizeof(TCHAR) * (len + 1));
if (!path){
outOfMemory(TEXT("CIRE"), 1);
} else {
_tcsncpy(path, (*para) + start, len);
path[len] = TEXT('\0');
#else
int replacePath;
path = findPathOf(*para, TEXT("wrapper.java.command"));
if (!path) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("The configured wrapper.java.command could not be found, attempting to launch anyway: %s"), *para);
} else {
replacePath = getBooleanProperty(properties, TEXT("wrapper.java.command.resolve"), TRUE);
if (replacePath == TRUE) {
free(*para);
*para = malloc((_tcslen(path) + 1) * sizeof(TCHAR));
if (!(*para)) {
outOfMemory(TEXT("CIRE"), 2);
free(path);
return;
}
_tcsncpy(*para, path, _tcslen(path) + 1);
}
#endif
if (!checkIfBinary(path)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("The value of wrapper.java.command does not appear to be a java binary."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("The use of scripts is not supported. Trying to continue, but some features may not work correctly.."));
}
free(path);
}
}
/**
* Builds up the java command section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayJavaCommand(TCHAR **strings, int addQuotes, int detectDebugJVM, int index) {
const TCHAR *prop;
TCHAR *c;
#ifdef WIN32
TCHAR cpPath[512];
int found;
#endif
if (strings) {
prop = getStringProperty(properties, TEXT("wrapper.java.command"), TEXT("java"));
#ifdef WIN32
found = 0;
if (_tcscmp(prop, TEXT("")) == 0) {
/* If the java command is an empty string, we want to look for the
* the java command in the windows registry. */
if (wrapperGetJavaHomeFromWindowsRegistry(cpPath)) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("Loaded java home from registry: %s"), cpPath);
}
addProperty(properties, NULL, 0, TEXT("set.WRAPPER_JAVA_HOME"), cpPath, TRUE, FALSE, FALSE, TRUE);
_tcsncat(cpPath, TEXT("\\bin\\java.exe"), 512);
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("Found Java Runtime Environment home directory in system registry."));
}
found = 1;
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("The Java Runtime Environment home directory could not be located in the system registry."));
found = 0;
return -1;
}
} else {
/* To avoid problems on Windows XP systems, the '/' characters must
* be replaced by '\' characters in the specified path.
* prop is supposed to be constant, but allow this change as it is
* the actual value that we want. */
correctWindowsPath((TCHAR *)prop);
/* If the full path to the java command was not specified, then we
* need to try and resolve it here to avoid problems later when
* calling CreateProcess. CreateProcess will look in the windows
* system directory before searching the PATH. This can lead to
* the wrong JVM being run. */
_sntprintf(cpPath, 512, TEXT("%s"), prop);
if ((PathFindOnPath((TCHAR*)cpPath, (TCHAR**)wrapperGetSystemPath())) && (!PathIsDirectory(cpPath))) {
/*printf("Found %s on path.\n", cpPath); */
found = 1;
} else {
/*printf("Could not find %s on path.\n", cpPath); */
/* Try adding .exe to the end */
_sntprintf(cpPath, 512, TEXT("%s.exe"), prop);
if ((PathFindOnPath(cpPath, wrapperGetSystemPath())) && (!PathIsDirectory(cpPath))) {
/*printf("Found %s on path.\n", cpPath); */
found = 1;
} else {
/*printf("Could not find %s on path.\n", cpPath); */
}
}
}
if (found) {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(cpPath) + 2 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAJC"), 1);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], _tcslen(cpPath) + 2 + 1, TEXT("\"%s\""), cpPath);
} else {
_sntprintf(strings[index], _tcslen(cpPath) + 2 + 1, TEXT("%s"), cpPath);
}
} else {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(prop) + 2 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAJC"), 2);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], _tcslen(prop) + 2 + 1, TEXT("\"%s\""), prop);
} else {
_sntprintf(strings[index], _tcslen(prop) + 2 + 1, TEXT("%s"), prop);
}
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], TEXT("wrapper.java.command"));
}
#else /* UNIX */
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(prop) + 2 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAJC"), 3);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], _tcslen(prop) + 2 + 1, TEXT("\"%s\""), prop);
} else {
_sntprintf(strings[index], _tcslen(prop) + 2 + 1, TEXT("%s"), prop);
}
#endif
checkIfRegularExe(&strings[index]);
if (detectDebugJVM) {
c = _tcsstr(strings[index], TEXT("jdb"));
if (c && ((unsigned int)(c - strings[index]) == _tcslen(strings[index]) - 3 - 1)) {
/* Ends with "jdb". The jdb debugger is being used directly. go into debug JVM mode. */
wrapperData->debugJVM = TRUE;
} else {
c = _tcsstr(strings[index], TEXT("jdb.exe"));
if (c && ((unsigned int)(c - strings[index]) == _tcslen(strings[index]) - 7 - 1)) {
/* Ends with "jdb". The jdb debugger is being used directly. go into debug JVM mode. */
wrapperData->debugJVM = TRUE;
}
}
}
}
index++;
return index;
}
/**
* Builds up the additional section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayJavaAdditional(TCHAR **strings, int addQuotes, int detectDebugJVM, int index) {
const TCHAR *prop;
int i;
size_t len;
TCHAR paramBuffer2[128];
int quotable;
int defaultStripQuote;
int stripQuote;
TCHAR *propStripped;
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
if (getStringProperties(properties, TEXT("wrapper.java.additional."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
return -1;
}
defaultStripQuote = getBooleanProperty(properties, TEXT("wrapper.java.additional.default.stripquotes"), FALSE);
i = 0;
while (propertyNames[i]) {
prop = propertyValues[i];
if (prop) {
if (_tcslen(prop) > 0) {
/* All additional parameters must begin with a - or they will be interpretted
* as the being the main class name by Java. */
if (!((_tcsstr(prop, TEXT("-")) == prop) || (_tcsstr(prop, TEXT("\"-")) == prop))) {
/* Only log the message on the second pass. */
if (strings) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The value of property '%s', '%s' is not a valid argument to the JVM. Skipping."),
propertyNames[i], prop);
}
} else {
if (strings) {
/* is quotable also changes the value of the property!
therefore prop can potentially point to free'd memory*/
quotable = isQuotableProperty(properties, propertyNames[i]);
prop = getStringProperty(properties, propertyNames[i], NULL);
propertyValues[i] = (TCHAR*) prop;
if (prop == NULL) {
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
_sntprintf(paramBuffer2, 128, TEXT("wrapper.java.additional.%lu.stripquotes"), propertyIndices[i]);
if (addQuotes) {
stripQuote = FALSE;
} else {
stripQuote = getBooleanProperty(properties, paramBuffer2, defaultStripQuote);
}
if (stripQuote) {
propStripped = malloc(sizeof(TCHAR) * (_tcslen(prop) + 1));
if (!propStripped) {
freeStringProperties(propertyNames, propertyValues, propertyIndices);
outOfMemory(TEXT("WBJCAJA"), 2);
return -1;
}
wrapperStripQuotes(prop, propStripped);
} else {
propStripped = (TCHAR *)prop;
}
if (addQuotes && quotable && _tcschr(propStripped, TEXT(' '))) {
len = wrapperQuoteValue(propStripped, NULL, 0);
strings[index] = malloc(sizeof(TCHAR) * len);
if (!strings[index]) {
outOfMemory(TEXT("WBJCAJA"), 3);
freeStringProperties(propertyNames, propertyValues, propertyIndices);
if (stripQuote) {
free(propStripped);
}
return -1;
}
wrapperQuoteValue(propStripped, strings[index], len);
} else {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(propStripped) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAJA"), 4);
freeStringProperties(propertyNames, propertyValues, propertyIndices);
if (stripQuote) {
free(propStripped);
}
return -1;
}
_sntprintf(strings[index], _tcslen(propStripped) + 1, TEXT("%s"), propStripped);
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], propertyNames[i]);
}
if (stripQuote) {
free(propStripped);
propStripped = NULL;
}
/* Set if this paremeter enables debugging. */
if (detectDebugJVM) {
if (_tcsstr(strings[index], TEXT("-Xdebug")) == strings[index]) {
wrapperData->debugJVM = TRUE;
}
}
}
index++;
}
}
i++;
}
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return index;
}
/**
* Java command line callback.
*/
static int loadParameterFileCallbackParam_AddArg(LoadParameterFileCallbackParam *param, TCHAR *arg, size_t argLen)
{
TCHAR str[MAX_PROPERTY_VALUE_LENGTH];
TCHAR *s;
size_t len;
#ifdef _DEBUG
memcpy(str, arg, sizeof(TCHAR) * argLen);
str[argLen] = TEXT('\0');
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_NOTICE, TEXT(" :> %s"), str);
#endif
if (param->isJVMParam == TRUE) {
/* As in wrapperBuildJavaCommandArrayJavaAdditional(), skip an
argument which does not begin with '-'. */
if ((arg[0] != TEXT('-')) && !((arg[0] == TEXT('"')) && (arg[1] == TEXT('-')))) {
if (param->strings) {
memcpy(str, arg, sizeof(TCHAR) * argLen);
str[argLen] = TEXT('\0');
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The value '%s' is not a valid argument to the JVM. Skipping."), str);
}
return TRUE;
}
}
if (param->strings) {
if (!param->stripQuote) {
s = arg;
len = argLen;
} else {
len = wrapperStripQuotesInner(arg, argLen, str);
s = str;
}
param->strings[param->index] = malloc(sizeof(TCHAR) * (len + 1));
if (!param->strings[param->index]) {
return FALSE;
}
memcpy(param->strings[param->index], s, sizeof(TCHAR) * len);
param->strings[param->index][len] = TEXT('\0');
}
param->index++;
return TRUE;
}
static int loadParameterFileCallback(void *callbackParam, const TCHAR *fileName, int lineNumber, TCHAR *config, int debugProperties)
{
LoadParameterFileCallbackParam *param = (LoadParameterFileCallbackParam *)callbackParam;
TCHAR *tail_bound;
TCHAR *arg;
TCHAR *s;
int InDelim = FALSE;
int InQuotes = FALSE;
int Escaped = FALSE;
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_NOTICE, TEXT(" : %s"), config);
#endif
/* Assume that the line `config' has no white spaces at its
beginning and end. */
assert(config && _tcslen(config) > 0);
assert(config[0] != TEXT(' ') && config[_tcslen(config) - 1] != TEXT(' '));
tail_bound = config + _tcslen(config) + 1;
for (arg = s = config; s < tail_bound; s++) {
switch (*s) {
case TEXT('\0'):
if (!loadParameterFileCallbackParam_AddArg(param, arg, s - arg)) {
outOfMemory(TEXT("LJAC"), 1);
return FALSE;
}
break;
case TEXT(' '):
Escaped = FALSE;
if (!InDelim && !InQuotes) {
InDelim = TRUE;
if (!loadParameterFileCallbackParam_AddArg(param, arg, s - arg)) {
outOfMemory(TEXT("LJAC"), 2);
return FALSE;
}
}
break;
case TEXT('"'):
if (!Escaped) {
InQuotes = !InQuotes;
}
Escaped = FALSE;
if (InDelim) {
InDelim = FALSE;
arg = s;
}
break;
case TEXT('\\'):
Escaped = !Escaped;
if (InDelim) {
InDelim = FALSE;
arg = s;
}
break;
default:
Escaped = FALSE;
if (InDelim) {
InDelim = FALSE;
arg = s;
}
break;
}
}
return TRUE;
}
/**
* Builds up the additional section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperLoadParameterFile(TCHAR **strings, int addQuotes, int detectDebugJVM, int index, TCHAR *parameterName, int isJVMParameter) {
const TCHAR *parameterFilePath;
LoadParameterFileCallbackParam callbackParam;
ConfigFileReader reader;
int readResult;
TCHAR prop[256];
parameterFilePath = getFileSafeStringProperty(properties, parameterName, TEXT(""));
#ifdef _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_NOTICE,
TEXT("%s=%s"), parameterName, parameterFilePath ? parameterFilePath : TEXT(""));
#endif
if (_tcslen(parameterFilePath) == 0) {
return index;
}
if (addQuotes) {
callbackParam.stripQuote = FALSE;
} else {
_sntprintf(prop, 256, TEXT("%s.stripquotes"), parameterName);
callbackParam.stripQuote = getBooleanProperty(properties, prop, FALSE);
}
callbackParam.strings = strings;
callbackParam.index = index;
callbackParam.isJVMParam = isJVMParameter;
configFileReader_Initialize(&reader, loadParameterFileCallback, &callbackParam, FALSE);
readResult = configFileReader_Read(&reader, parameterFilePath, TRUE, 0, NULL, 0);
switch (readResult) {
case CONFIG_FILE_READER_SUCCESS:
return callbackParam.index;
case CONFIG_FILE_READER_FAIL:
case CONFIG_FILE_READER_HARD_FAIL:
return -1;
default:
_tprintf(TEXT("Unexpected read error %d\n"), readResult);
return index;
};
}
/**
* Builds up the library path section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayLibraryPath(TCHAR **strings, int addQuotes, int index) {
const TCHAR *prop;
int i, j;
size_t len2;
size_t cpLen, cpLenAlloc;
TCHAR *tmpString;
TCHAR *systemPath;
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
if (strings) {
if (wrapperData->libraryPathAppendPath) {
/* We are going to want to append the full system path to
* whatever library path is generated. */
#ifdef WIN32
systemPath = _tgetenv(TEXT("PATH"));
#else
systemPath = _tgetenv(TEXT("LD_LIBRARY_PATH"));
#endif
if (systemPath) {
/* If we are going to add our own quotes then we need to make sure that the system
* PATH doesn't contain any of its own. Windows allows users to do this... */
if (addQuotes) {
i = 0;
j = 0;
do {
if (systemPath[i] != TEXT('"') ) {
systemPath[j] = systemPath[i];
j++;
}
i++;
} while (systemPath[j] != TEXT('\0'));
}
}
} else {
systemPath = NULL;
}
prop = getStringProperty(properties, TEXT("wrapper.java.library.path"), NULL);
if (prop) {
/* An old style library path was specified.
* If quotes are being added, check the last character before the
* closing quote. If it is a backslash then Windows will use it to
* escape the quote. To make things work correctly, we need to add
* another backslash first so it will result in a single backslash
* before the quote. */
if (systemPath) {
strings[index] = malloc(sizeof(TCHAR) * (22 + _tcslen(prop) + 1 + _tcslen(systemPath) + 1 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCALP"), 1);
#if !defined(WIN32) && defined(UNICODE)
free(systemPath);
#endif
return -1;
}
if (addQuotes) {
if ((_tcslen(systemPath) > 1) && (systemPath[_tcslen(systemPath) - 1] == TEXT('\\'))) {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + _tcslen(systemPath) + 1 + 1, TEXT("-Djava.library.path=\"%s%c%s\\\""), prop, wrapperClasspathSeparator, systemPath);
} else {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + _tcslen(systemPath) + 1 + 1, TEXT("-Djava.library.path=\"%s%c%s\""), prop, wrapperClasspathSeparator, systemPath);
}
} else {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + _tcslen(systemPath) + 1 + 1, TEXT("-Djava.library.path=%s%c%s"), prop, wrapperClasspathSeparator, systemPath);
}
} else {
strings[index] = malloc(sizeof(TCHAR) * (22 + _tcslen(prop) + 1 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCALP"), 2);
return -1;
}
if (addQuotes) {
if ((_tcslen(prop) > 1) && (prop[_tcslen(prop) - 1] == TEXT('\\'))) {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + 1, TEXT("-Djava.library.path=\"%s\\\""), prop);
} else {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + 1, TEXT("-Djava.library.path=\"%s\""), prop);
}
} else {
_sntprintf(strings[index], 22 + _tcslen(prop) + 1 + 1, TEXT("-Djava.library.path=%s"), prop);
}
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], TEXT("wrapper.java.library.path"));
}
} else {
/* Look for a multiline library path. */
cpLen = 0;
cpLenAlloc = 1024;
strings[index] = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!strings[index]) {
outOfMemory(TEXT("WBJCALP"), 3);
#if !defined(WIN32) && defined(UNICODE)
if (systemPath) {
free(systemPath);
}
#endif
return -1;
}
/* Start with the property value. */
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("-Djava.library.path="));
cpLen += 20;
/* Add an open quote to the library path */
if (addQuotes) {
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("\""));
cpLen++;
}
/* Loop over the library path entries adding each one */
if (getStringProperties(properties, TEXT("wrapper.java.library.path."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
#if !defined(WIN32) && defined(UNICODE)
if (systemPath) {
free(systemPath);
}
#endif
return -1;
}
i = 0;
j = 0;
while (propertyNames[i]) {
prop = propertyValues[i];
if (prop) {
len2 = _tcslen(prop);
if (len2 > 0) {
/* Is there room for the entry? */
while (cpLen + len2 + 3 > cpLenAlloc) {
/* Resize the buffer */
tmpString = strings[index];
cpLenAlloc += 1024;
strings[index] = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!strings[index]) {
outOfMemory(TEXT("WBJCALP"), 4);
#if !defined(WIN32) && defined(UNICODE)
if (systemPath) {
free(systemPath);
}
#endif
return -1;
}
_sntprintf(strings[index], cpLenAlloc, TEXT("%s"), tmpString);
free(tmpString);
tmpString = NULL;
}
if (j > 0) {
strings[index][cpLen++] = wrapperClasspathSeparator; /* separator */
}
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("%s"), prop);
cpLen += len2;
j++;
}
i++;
}
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
if (systemPath) {
/* We need to append the system path. */
len2 = _tcslen(systemPath);
if (len2 > 0) {
/* Is there room for the entry? */
while (cpLen + len2 + 3 > cpLenAlloc) {
/* Resize the buffer */
tmpString = strings[index];
cpLenAlloc += 1024;
strings[index] = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!strings[index]) {
outOfMemory(TEXT("WBJCALP"), 5);
#if !defined(WIN32) && defined(UNICODE)
free(systemPath);
#endif
return -1;
}
_sntprintf(strings[index], cpLenAlloc, TEXT("%s"), tmpString);
free(tmpString);
tmpString = NULL;
}
if (j > 0) {
strings[index][cpLen++] = wrapperClasspathSeparator; /* separator */
}
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("%s"), systemPath);
cpLen += len2;
j++;
}
}
if (j == 0) {
/* No library path, use default. always room */
_sntprintf(&(strings[index][cpLen++]), cpLenAlloc, TEXT("./"));
}
/* Add ending quote. If the previous character is a backslash then
* Windows will use it to escape the quote. To make things work
* correctly, we need to add another backslash first so it will
* result in a single backslash before the quote. */
if (addQuotes) {
if (strings[index][cpLen - 1] == TEXT('\\')) {
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("\\"));
cpLen++;
}
_sntprintf(&(strings[index][cpLen]), cpLenAlloc, TEXT("\""));
cpLen++;
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], TEXT("wrapper.java.library.path.<n>"));
}
}
#if !defined(WIN32) && defined(UNICODE)
if (systemPath) {
free(systemPath);
}
#endif
}
index++;
return index;
}
/**
* Builds up the java classpath.
*
* @return 0 if successful, or -1 if there were any problems.
*/
int wrapperBuildJavaClasspath(TCHAR **classpath) {
const TCHAR *prop;
TCHAR *propStripped;
TCHAR *propBaseDir;
int i, j;
size_t cpLen, cpLenAlloc;
size_t len2;
TCHAR *tmpString;
#if defined(WIN32) && !defined(WIN64)
struct _stat64i32 statBuffer;
#else
struct stat statBuffer;
#endif
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
TCHAR **files;
int cnt;
/* Build a classpath */
cpLen = 0;
cpLenAlloc = 1024;
*classpath = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!*classpath) {
outOfMemory(TEXT("WBJCP"), 1);
return -1;
}
/* Loop over the classpath entries adding each one. */
if (getStringProperties(properties, TEXT("wrapper.java.classpath."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
return -1;
}
i = 0;
j = 0;
while (propertyNames[i]) {
prop = propertyValues[i];
/* Does this contain any quotes? */
if (_tcschr(prop, TEXT('"'))) {
propStripped = malloc(sizeof(TCHAR) * (_tcslen(prop) + 1));
if (!propStripped) {
outOfMemory(TEXT("WBJCP"), 2);
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
wrapperStripQuotes(prop, propStripped);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"Classpath element, %s, should not contain quotes: %s, stripping and continuing: %s"), propertyNames[i], prop, propStripped);
} else {
propStripped = (TCHAR *)prop;
}
len2 = _tcslen(propStripped);
if (len2 > 0) {
/* Does this contain wildcards? */
if ((_tcsrchr(propStripped, TEXT('*')) != NULL) || (_tcschr(propStripped, TEXT('?')) != NULL)) {
/* Need to do a wildcard search */
files = wrapperFileGetFiles(propStripped, WRAPPER_FILE_SORT_MODE_NAMES_ASC);
if (!files) {
/* Failed */
if (propStripped != prop) {
free(propStripped);
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
/* Loop over the files. */
cnt = 0;
while (files[cnt]) {
len2 = _tcslen(files[cnt]);
/* Is there room for the entry? */
if (cpLen + len2 + 3 > cpLenAlloc) {
/* Resize the buffer */
tmpString = *classpath;
cpLenAlloc += len2 + 3;
*classpath = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!*classpath) {
if (propStripped != prop) {
free(propStripped);
}
wrapperFileFreeFiles(files);
freeStringProperties(propertyNames, propertyValues, propertyIndices);
outOfMemory(TEXT("WBJCP"), 2);
return -1;
}
if (j > 0) {
_sntprintf(*classpath, cpLenAlloc, TEXT("%s"), tmpString);
}
free(tmpString);
tmpString = NULL;
}
if (j > 0) {
(*classpath)[cpLen++] = wrapperClasspathSeparator; /* separator */
}
_sntprintf(&((*classpath)[cpLen]), cpLenAlloc, TEXT("%s"), files[cnt]);
cpLen += len2;
j++;
cnt++;
}
wrapperFileFreeFiles(files);
} else {
/* This classpath entry does not contain any wildcards. */
/* If the path element is a directory then we want to strip the trailing slash if it exists. */
propBaseDir = (TCHAR*)propStripped;
if ((propStripped[_tcslen(propStripped) - 1] == TEXT('/')) || (propStripped[_tcslen(propStripped) - 1] == TEXT('\\'))) {
propBaseDir = malloc(sizeof(TCHAR) * _tcslen(propStripped));
if (!propBaseDir) {
outOfMemory(TEXT("WBJCP"), 3);
if (propStripped != prop) {
free(propStripped);
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
_tcsncpy(propBaseDir, propStripped, _tcslen(propStripped) - 1);
propBaseDir[_tcslen(propStripped) - 1] = TEXT('\0');
}
/* See if it exists so we can display a debug warning if it does not. */
if (_tstat(propBaseDir, &statBuffer)) {
/* Encountered an error of some kind. */
if ((errno == ENOENT) || (errno == 3)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT(
"Classpath element, %s, does not exist: %s"), propertyNames[i], propStripped);
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT(
"Unable to get information of classpath element: %s (%s)"),
propStripped, getLastErrorText());
}
} else {
/* Got the stat info. */
}
/* If we allocated the propBaseDir buffer then free it up. */
if (propBaseDir != propStripped) {
free(propBaseDir);
}
propBaseDir = NULL;
/* Is there room for the entry? */
if (cpLen + len2 + 3 > cpLenAlloc) {
/* Resize the buffer */
tmpString = *classpath;
cpLenAlloc += len2 + 3;
*classpath = malloc(sizeof(TCHAR) * cpLenAlloc);
if (!*classpath) {
outOfMemory(TEXT("WBJCP"), 4);
if (propStripped != prop) {
free(propStripped);
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
if (j > 0) {
_sntprintf(*classpath, cpLenAlloc, TEXT("%s"), tmpString);
}
free(tmpString);
tmpString = NULL;
}
if (j > 0) {
(*classpath)[cpLen++] = wrapperClasspathSeparator; /* separator */
}
_sntprintf(&((*classpath)[cpLen]), cpLenAlloc - cpLen, TEXT("%s"), propStripped);
cpLen += len2;
j++;
}
}
/* If we allocated the propStripped buffer then free it up. */
if (propStripped != prop) {
free(propStripped);
}
propStripped = NULL;
i++;
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
if (j == 0) {
/* No classpath, use default. always room */
_sntprintf(&(*classpath[cpLen++]), cpLenAlloc, TEXT("./"));
}
return 0;
}
/**
* Builds up the java classpath section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayClasspath(TCHAR **strings, int addQuotes, int index, const TCHAR *classpath) {
size_t len;
size_t cpLen;
/* Store the classpath */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (10 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAC"), 1);
return -1;
}
_sntprintf(strings[index], 10 + 1, TEXT("-classpath"));
}
index++;
if (strings) {
cpLen = 0;
len = _tcslen(classpath);
strings[index] = malloc(sizeof(TCHAR) * (len + 4));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAC"), 2);
return -1;
}
/* Add an open quote the classpath */
if (addQuotes) {
_sntprintf(&(strings[index][cpLen]), len + 4, TEXT("\""));
cpLen++;
}
_sntprintf(&(strings[index][cpLen]), len + 4, TEXT("%s"), classpath);
cpLen += len;
/* Add ending quote. If the previous character is a backslash then
* Windows will use it to escape the quote. To make things work
* correctly, we need to add another backslash first so it will
* result in a single backslash before the quote. */
if (addQuotes) {
if (strings[index][cpLen - 1] == TEXT('\\')) {
_sntprintf(&(strings[index][cpLen]), len + 4, TEXT("\\"));
cpLen++;
}
_sntprintf(&(strings[index][cpLen]), len + 4, TEXT("\""));
cpLen++;
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], TEXT("wrapper.java.classpath.<n>"));
}
}
index++;
return index;
}
/**
* Builds up the app parameters section of the Java command line.
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayAppParameters(TCHAR **strings, int addQuotes, int index, int thisIsTestWrapper) {
const TCHAR *prop;
int i;
int quotable;
TCHAR *propStripped;
int defaultStripQuote;
int stripQuote;
TCHAR paramBuffer2[128];
size_t len;
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
if (getStringProperties(properties, TEXT("wrapper.app.parameter."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
return -1;
}
defaultStripQuote = getBooleanProperty(properties, TEXT("wrapper.app.parameter.default.stripquotes"), FALSE);
i = 0;
while (propertyNames[i]) {
prop = propertyValues[i];
if (_tcslen(prop) > 0) {
if (thisIsTestWrapper && (i == 1) && ((_tcscmp(prop, TEXT("{{TestWrapperBat}}")) == 0) || (_tcscmp(prop, TEXT("{{TestWrapperSh}}")) == 0))) {
/* This is the TestWrapper dummy parameter. Simply skip over it so it doesn't get put into the command line. */
} else {
if (strings) {
quotable = isQuotableProperty(properties, propertyNames[i]);
_sntprintf(paramBuffer2, 128, TEXT("wrapper.app.parameter.%lu.stripquotes"), propertyIndices[i]);
if (addQuotes) {
stripQuote = FALSE;
} else {
stripQuote = getBooleanProperty(properties, paramBuffer2, defaultStripQuote);
}
if (stripQuote) {
propStripped = malloc(sizeof(TCHAR) * (_tcslen(prop) + 1));
if (!propStripped) {
outOfMemory(TEXT("WBJCAAP"), 1);
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
wrapperStripQuotes(prop, propStripped);
} else {
propStripped = (TCHAR *)prop;
}
if (addQuotes && quotable && _tcschr(propStripped, TEXT(' '))) {
len = wrapperQuoteValue(propStripped, NULL, 0);
strings[index] = malloc(sizeof(TCHAR) * len);
if (!strings[index]) {
outOfMemory(TEXT("WBJCAAP"), 2);
if (stripQuote) {
free(propStripped);
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return -1;
}
wrapperQuoteValue(propStripped, strings[index], len);
} else {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(propStripped) + 1));
if (!strings[index]) {
if (stripQuote) {
free(propStripped);
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
outOfMemory(TEXT("WBJCAAP"), 3);
return -1;
}
_sntprintf(strings[index], _tcslen(propStripped) + 1, TEXT("%s"), propStripped);
}
if (addQuotes) {
wrapperCheckQuotes(strings[index], propertyNames[i]);
}
if (stripQuote) {
free(propStripped);
propStripped = NULL;
}
}
index++;
}
}
i++;
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
/* precede command line parameters */
if (wrapperData->javaArgValueCount > 0) {
for (i = 0; i < wrapperData->javaArgValueCount; i++) {
if (strings) {
if (addQuotes && _tcschr(wrapperData->javaArgValues[i], TEXT(' '))) {
len = wrapperQuoteValue(wrapperData->javaArgValues[i], NULL, 0);
strings[index] = malloc(sizeof(TCHAR) * len);
if (!strings[index]) {
outOfMemory(TEXT("WBJCAAP"), 4);
return -1;
}
wrapperQuoteValue(wrapperData->javaArgValues[i], strings[index], len);
} else {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(wrapperData->javaArgValues[i]) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAAP"), 5);
return -1;
}
_sntprintf(strings[index], _tcslen(wrapperData->javaArgValues[i]) + 1, TEXT("%s"), wrapperData->javaArgValues[i]);
}
}
index++;
}
}
return index;
}
/**
* Loops over and stores all necessary commands into an array which
* can be used to launch a process.
* This method will only count the elements if stringsPtr is NULL.
*
* Note - Next Out Of Memory is #47
*
* @return The final index into the strings array, or -1 if there were any problems.
*/
int wrapperBuildJavaCommandArrayInner(TCHAR **strings, int addQuotes, const TCHAR *classpath) {
int index;
int detectDebugJVM;
const TCHAR *prop;
int initMemory = 0;
int maxMemory;
int thisIsTestWrapper;
setLogPropertyWarnings(properties, strings != NULL);
index = 0;
detectDebugJVM = getBooleanProperty(properties, TEXT("wrapper.java.detect_debug_jvm"), TRUE);
/* Java commnd */
if ((index = wrapperBuildJavaCommandArrayJavaCommand(strings, addQuotes, detectDebugJVM, index)) < 0) {
return -1;
}
/* See if the auto bits parameter is set. Ignored by all but the following platforms. */
#if /*defined(WIN32) || defined(LINUX) ||*/ defined(HPUX) || defined(MACOSX) || defined(SOLARIS) || defined(FREEBSD)
if (getBooleanProperty(properties,
/*#ifdef WIN32
TEXT("wrapper.java.additional.auto_bits.windows"),
#elif defined(LINUX)
TEXT("wrapper.java.additional.auto_bits.linux"),
*/
#if defined(HPUX)
TEXT("wrapper.java.additional.auto_bits.hpux"),
#elif defined(SOLARIS)
TEXT("wrapper.java.additional.auto_bits.solaris"),
#elif defined(FREEBSD)
TEXT("wrapper.java.additional.auto_bits.freebsd"),
#elif defined(KFREEBSD)
TEXT("wrapper.java.additional.auto_bits.kfreebsd"),
#elif defined(MACOSX)
TEXT("wrapper.java.additional.auto_bits.macosx"),
#endif
getBooleanProperty(properties, TEXT("wrapper.java.additional.auto_bits"), FALSE))) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * 5);
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 46);
return -1;
}
_sntprintf(strings[index], 5, TEXT("-d%s"), wrapperBits);
}
index++;
}
#endif
/* Store additional java parameters */
if ((index = wrapperBuildJavaCommandArrayJavaAdditional(strings, addQuotes, detectDebugJVM, index)) < 0) {
return -1;
}
/* Store additional java parameters specified in the parameter file */
if ((index = wrapperLoadParameterFile(strings, addQuotes, detectDebugJVM, index, TEXT("wrapper.java.additional_file"), TRUE)) < 0) {
return -1;
}
/* Initial JVM memory */
initMemory = getIntProperty(properties, TEXT("wrapper.java.initmemory"), 0);
if (initMemory > 0) {
if (strings) {
initMemory = __max(initMemory, 1); /* 1 <= n */
strings[index] = malloc(sizeof(TCHAR) * (5 + 10 + 1)); /* Allow up to 10 digits. */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 8);
return -1;
}
_sntprintf(strings[index], 5 + 10 + 1, TEXT("-Xms%dm"), initMemory);
}
index++;
} else {
/* Set the initMemory so the checks in the maxMemory section below will work correctly. */
initMemory = 3;
}
/* Maximum JVM memory */
maxMemory = getIntProperty(properties, TEXT("wrapper.java.maxmemory"), 0);
if (maxMemory > 0) {
if (strings) {
maxMemory = __max(maxMemory, initMemory); /* initMemory <= n */
strings[index] = malloc(sizeof(TCHAR) * (5 + 10 + 1)); /* Allow up to 10 digits. */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 10);
return -1;
}
_sntprintf(strings[index], 5 + 10 + 1, TEXT("-Xmx%dm"), maxMemory);
}
index++;
}
/* Library Path */
if ((index = wrapperBuildJavaCommandArrayLibraryPath(strings, addQuotes, index)) < 0) {
return -1;
}
/* Classpath */
if (!wrapperData->environmentClasspath) {
if ((index = wrapperBuildJavaCommandArrayClasspath(strings, addQuotes, index, classpath)) < 0) {
return -1;
}
}
/* Store the Wrapper key */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (16 + _tcslen(wrapperData->key) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 24);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 16 + _tcslen(wrapperData->key) + 1, TEXT("-Dwrapper.key=\"%s\""), wrapperData->key);
} else {
_sntprintf(strings[index], 16 + _tcslen(wrapperData->key) + 1, TEXT("-Dwrapper.key=%s"), wrapperData->key);
}
}
index++;
/* Store the backend connection information. */
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_PIPE) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (22 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 25);
return -1;
}
_sntprintf(strings[index], 22 + 1, TEXT("-Dwrapper.backend=pipe"));
}
index++;
} else {
/* Store the Wrapper server port */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (15 + 5 + 1)); /* Port up to 5 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 26);
return -1;
}
_sntprintf(strings[index], 15 + 5 + 1, TEXT("-Dwrapper.port=%d"), (int)wrapperData->actualPort);
}
index++;
}
/* Store the Wrapper jvm min and max ports. */
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_SOCKET) {
if (wrapperData->portAddress != NULL) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(TEXT("-Dwrapper.port.address=")) + _tcslen(wrapperData->portAddress) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 27);
return -1;
}
_sntprintf(strings[index], _tcslen(TEXT("-Dwrapper.port.address=")) + _tcslen(wrapperData->portAddress) + 1, TEXT("-Dwrapper.port.address=%s"), wrapperData->portAddress);
}
index++;
}
if (wrapperData->jvmPort >= 0) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (19 + 5 + 1)); /* Port up to 5 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 28);
return -1;
}
_sntprintf(strings[index], 19 + 5 + 1, TEXT("-Dwrapper.jvm.port=%d"), (int)wrapperData->jvmPort);
}
index++;
}
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (23 + 5 + 1)); /* Port up to 5 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 29);
return -1;
}
_sntprintf(strings[index], 23 + 5 + 1, TEXT("-Dwrapper.jvm.port.min=%d"), (int)wrapperData->jvmPortMin);
}
index++;
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (23 + 5 + 1)); /* Port up to 5 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 30);
return -1;
}
_sntprintf(strings[index], 23 + 5 + 1, TEXT("-Dwrapper.jvm.port.max=%d"), (int)wrapperData->jvmPortMax);
}
index++;
}
/* Store the Wrapper debug flag */
if (wrapperData->isDebugging) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (22 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 31);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 22 + 1, TEXT("-Dwrapper.debug=\"TRUE\""));
} else {
_sntprintf(strings[index], 22 + 1, TEXT("-Dwrapper.debug=TRUE"));
}
}
index++;
}
/* Store the Wrapper disable console input flag. */
if (getBooleanProperty(properties, TEXT("wrapper.disable_console_input"),
#ifdef WIN32
FALSE
#else
wrapperData->daemonize /* We want to disable console input by default when daemonized. */
#endif
)) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (38 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 32);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.disable_console_input=\"TRUE\""));
} else {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.disable_console_input=TRUE"));
}
}
index++;
}
/* Store the Wrapper listener force stop flag. */
if (getBooleanProperty(properties, TEXT("wrapper.listener.force_stop"), FALSE)) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (38 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 33);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.listener.force_stop=\"TRUE\""));
} else {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.listener.force_stop=TRUE"));
}
}
index++;
}
/* Store the Wrapper PID */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (24 + 1)); /* Pid up to 10 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 34);
return -1;
}
#if defined(SOLARIS) && (!defined(_LP64))
_sntprintf(strings[index], 24 + 1, TEXT("-Dwrapper.pid=%ld"), wrapperData->wrapperPID);
#else
_sntprintf(strings[index], 24 + 1, TEXT("-Dwrapper.pid=%d"), wrapperData->wrapperPID);
#endif
}
index++;
/* Store a flag telling the JVM to use the system clock. */
if (wrapperData->useSystemTime) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (32 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 35);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 32 + 1, TEXT("-Dwrapper.use_system_time=\"TRUE\""));
} else {
_sntprintf(strings[index], 32 + 1, TEXT("-Dwrapper.use_system_time=TRUE"));
}
}
index++;
} else {
/* Only pass the timer fast and slow thresholds to the JVM if they are not default.
* These are only used if the system time is not being used. */
if (wrapperData->timerFastThreshold != WRAPPER_TIMER_FAST_THRESHOLD) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (43 + 1)); /* Allow for 10 digits */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 36);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 43 + 1, TEXT("-Dwrapper.timer_fast_threshold=\"%d\""), wrapperData->timerFastThreshold * WRAPPER_TICK_MS / 1000);
} else {
_sntprintf(strings[index], 43 + 1, TEXT("-Dwrapper.timer_fast_threshold=%d"), wrapperData->timerFastThreshold * WRAPPER_TICK_MS / 1000);
}
}
index++;
}
if (wrapperData->timerSlowThreshold != WRAPPER_TIMER_SLOW_THRESHOLD) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (43 + 1)); /* Allow for 10 digits */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 37);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 43 + 1, TEXT("-Dwrapper.timer_slow_threshold=\"%d\""), wrapperData->timerSlowThreshold * WRAPPER_TICK_MS / 1000);
} else {
_sntprintf(strings[index], 43 + 1, TEXT("-Dwrapper.timer_slow_threshold=%d"), wrapperData->timerSlowThreshold * WRAPPER_TICK_MS / 1000);
}
}
index++;
}
}
/* Always write the version of the wrapper binary as a property. The
* WrapperManager class uses it to verify that the version matches. */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (20 + _tcslen(wrapperVersion) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 37);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 20 + _tcslen(wrapperVersion) + 1, TEXT("-Dwrapper.version=\"%s\""), wrapperVersion);
} else {
_sntprintf(strings[index], 20 + _tcslen(wrapperVersion) + 1, TEXT("-Dwrapper.version=%s"), wrapperVersion);
}
}
index++;
/* Store the base name of the native library. */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (27 + _tcslen(wrapperData->nativeLibrary) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 38);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 27 + _tcslen(wrapperData->nativeLibrary) + 1, TEXT("-Dwrapper.native_library=\"%s\""), wrapperData->nativeLibrary);
} else {
_sntprintf(strings[index], 27 + _tcslen(wrapperData->nativeLibrary) + 1, TEXT("-Dwrapper.native_library=%s"), wrapperData->nativeLibrary);
}
}
index++;
/* Store the arch name of the wrapper. */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (17 + _tcslen(wrapperArch) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 39);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 17 + _tcslen(wrapperArch) + 1, TEXT("-Dwrapper.arch=\"%s\""), wrapperArch);
} else {
_sntprintf(strings[index], 17 + _tcslen(wrapperArch) + 1, TEXT("-Dwrapper.arch=%s"), wrapperArch);
}
}
index++;
/* Store the ignore signals flag if configured to do so */
if (wrapperData->ignoreSignals & WRAPPER_IGNORE_SIGNALS_JAVA) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (31 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 40);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 31 + 1, TEXT("-Dwrapper.ignore_signals=\"TRUE\""));
} else {
_sntprintf(strings[index], 31 + 1, TEXT("-Dwrapper.ignore_signals=TRUE"));
}
}
index++;
}
/* If this is being run as a service, add a service flag. */
if (!wrapperData->isConsole) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (24 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 41);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 24 + 1, TEXT("-Dwrapper.service=\"TRUE\""));
} else {
_sntprintf(strings[index], 24 + 1, TEXT("-Dwrapper.service=TRUE"));
}
}
index++;
}
/* Store the Disable Tests flag */
if (wrapperData->isTestsDisabled) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (30 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 42);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 30 + 1, TEXT("-Dwrapper.disable_tests=\"TRUE\""));
} else {
_sntprintf(strings[index], 30 + 1, TEXT("-Dwrapper.disable_tests=TRUE"));
}
}
index++;
}
/* Store the Disable Shutdown Hook flag */
if (wrapperData->isShutdownHookDisabled) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (38 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 43);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.disable_shutdown_hook=\"TRUE\""));
} else {
_sntprintf(strings[index], 38 + 1, TEXT("-Dwrapper.disable_shutdown_hook=TRUE"));
}
}
index++;
}
/* Store the CPU Timeout value */
if (strings) {
/* Just to be safe, allow 20 characters for the timeout value */
strings[index] = malloc(sizeof(TCHAR) * (24 + 20 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 44);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 24 + 20 + 1, TEXT("-Dwrapper.cpu.timeout=\"%d\""), wrapperData->cpuTimeout);
} else {
_sntprintf(strings[index], 24 + 20 + 1, TEXT("-Dwrapper.cpu.timeout=%d"), wrapperData->cpuTimeout);
}
}
index++;
if ((prop = getStringProperty(properties, TEXT("wrapper.java.outfile"), NULL))) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (25 + _tcslen(prop) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 46);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 25 + _tcslen(prop) + 1, TEXT("-Dwrapper.java.outfile=\"%s\""), prop);
} else {
_sntprintf(strings[index], 25 + _tcslen(prop) + 1, TEXT("-Dwrapper.java.outfile=%s"), prop);
}
}
index++;
}
if ((prop = getStringProperty(properties, TEXT("wrapper.java.errfile"), NULL))) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (25 + _tcslen(prop) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 47);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 25 + _tcslen(prop) + 1, TEXT("-Dwrapper.java.errfile=\"%s\""), prop);
} else {
_sntprintf(strings[index], 25 + _tcslen(prop) + 1, TEXT("-Dwrapper.java.errfile=%s"), prop);
}
}
index++;
}
/* Store the Wrapper JVM ID. (Get here before incremented) */
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (16 + 5 + 1)); /* jvmid up to 5 characters */
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 48);
return -1;
}
_sntprintf(strings[index], 16 + 5 + 1, TEXT("-Dwrapper.jvmid=%d"), (wrapperData->jvmRestarts + 1));
}
index++;
/* If this JVM will be detached after startup, it needs to know that. */
if (wrapperData->detachStarted) {
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (30 + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 51);
return -1;
}
if (addQuotes) {
_sntprintf(strings[index], 30 + 1, TEXT("-Dwrapper.detachStarted=\"TRUE\""));
} else {
_sntprintf(strings[index], 30 + 1, TEXT("-Dwrapper.detachStarted=TRUE"));
}
}
index++;
}
/* Store the main class */
thisIsTestWrapper = FALSE;
prop = getStringProperty(properties, TEXT("wrapper.java.mainclass"), TEXT("Main"));
if (_tcscmp(prop, TEXT("org.tanukisoftware.wrapper.test.Main")) == 0) {
thisIsTestWrapper = TRUE;
} else {
thisIsTestWrapper = FALSE;
}
if (strings) {
strings[index] = malloc(sizeof(TCHAR) * (_tcslen(prop) + 1));
if (!strings[index]) {
outOfMemory(TEXT("WBJCAI"), 52);
return -1;
}
_sntprintf(strings[index], _tcslen(prop) + 1, TEXT("%s"), prop);
}
index++;
/* Store any application parameters */
if ((index = wrapperBuildJavaCommandArrayAppParameters(strings, addQuotes, index, thisIsTestWrapper)) < 0) {
return -1;
}
if ((index = wrapperLoadParameterFile(strings, addQuotes, detectDebugJVM, index, TEXT("wrapper.app.parameter_file"), FALSE)) < 0) {
return -1;
}
return index;
}
/**
* command is a pointer to a pointer of an array of character strings.
* length is the number of strings in the above array.
*
* @return TRUE if there were any problems.
*/
int wrapperBuildJavaCommandArray(TCHAR ***stringsPtr, int *length, int addQuotes, const TCHAR *classpath) {
int reqLen;
/* Reset the flag stating that the JVM is a debug JVM. */
wrapperData->debugJVM = FALSE;
wrapperData->debugJVMTimeoutNotified = FALSE;
/* Find out how long the array needs to be first. */
reqLen = wrapperBuildJavaCommandArrayInner(NULL, addQuotes, classpath);
if (reqLen < 0) {
return TRUE;
}
*length = reqLen;
/* Allocate the correct amount of memory */
*stringsPtr = malloc((*length) * sizeof **stringsPtr );
if (!(*stringsPtr)) {
outOfMemory(TEXT("WBJCA"), 1);
return TRUE;
}
/* Now actually fill in the strings */
reqLen = wrapperBuildJavaCommandArrayInner(*stringsPtr, addQuotes, classpath);
if (reqLen < 0) {
return TRUE;
}
if (wrapperData->debugJVM) {
if ((wrapperData->startupTimeout > 0) || (wrapperData->pingTimeout > 0) ||
(wrapperData->shutdownTimeout > 0) || (wrapperData->jvmExitTimeout > 0)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("---------------------------------------------------------------------") );
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT(
"The JVM is being launched with a debugger enabled and could possibly\nbe suspended. To avoid unwanted shutdowns, timeouts will be\ndisabled, removing the ability to detect and restart frozen JVMs."));
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("---------------------------------------------------------------------") );
}
}
return FALSE;
}
void wrapperFreeJavaCommandArray(TCHAR **strings, int length) {
int i;
if (strings != NULL) {
/* Loop over and free each of the strings in the array */
for (i = 0; i < length; i++) {
if (strings[i] != NULL) {
free(strings[i]);
strings[i] = NULL;
}
}
free(strings);
strings = NULL;
}
}
/**
* Called when the Wrapper detects that the JVM process has exited.
* Contains code common to all platforms.
*/
void wrapperJVMProcessExited(TICKS nowTicks, int exitCode) {
int setState = TRUE;
if (exitCode == 0) {
/* The JVM exit code was 0, so leave any current exit code as is. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM process exited with a code of %d, leaving the wrapper exit code set to %d."),
exitCode, wrapperData->exitCode);
} else if (wrapperData->exitCode == 0) {
/* Update the wrapper exitCode. */
wrapperData->exitCode = exitCode;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM process exited with a code of %d, setting the wrapper exit code to %d."),
exitCode, wrapperData->exitCode);
} else {
/* The wrapper exit code was already non-zero, so leave it as is. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM process exited with a code of %d, however the wrapper exit code was already %d."),
exitCode, wrapperData->exitCode);
}
switch(wrapperData->jState) {
case WRAPPER_JSTATE_DOWN_CLEAN:
case WRAPPER_JSTATE_DOWN_CHECK:
case WRAPPER_JSTATE_DOWN_FLUSH:
/* Shouldn't be called in this state. But just in case. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM already down."));
}
setState = FALSE;
break;
case WRAPPER_JSTATE_LAUNCH_DELAY:
/* We got a message that the JVM process died when we already thought is was down.
* Most likely this was caused by a SIGCHLD signal. We are already in the expected
* state so go ahead and ignore it. Do NOT go back to DOWN or the restart flag
* and all restart counts will have be lost */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("Received a message that the JVM is down when in the LAUNCH(DELAY) state."));
}
setState = FALSE;
break;
case WRAPPER_JSTATE_RESTART:
/* We got a message that the JVM process died when we already thought is was down.
* Most likely this was caused by a SIGCHLD signal. We are already in the expected
* state so go ahead and ignore it. Do NOT go back to DOWN or the restart flag
* and all restart counts will have be lost */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("Received a message that the JVM is down when in the RESTART state."));
}
setState = FALSE;
break;
case WRAPPER_JSTATE_LAUNCH:
/* We got a message that the JVM process died when we already thought is was down.
* Most likely this was caused by a SIGCHLD signal. We are already in the expected
* state so go ahead and ignore it. Do NOT go back to DOWN or the restart flag
* and all restart counts will have be lost.
* This can happen if the Java process dies Immediately after it is launched. It
* is very rare if Java is launched, but can happen if the configuration is set to
* launch something else. */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("Received a message that the JVM is down when in the LAUNCH state."));
}
setState = FALSE;
break;
case WRAPPER_JSTATE_LAUNCHING:
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_AUTOMATIC;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("JVM exited while loading the application."));
break;
case WRAPPER_JSTATE_LAUNCHED:
/* Shouldn't be called in this state, but just in case. */
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_AUTOMATIC;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("JVM exited before starting the application."));
break;
case WRAPPER_JSTATE_STARTING:
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_AUTOMATIC;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("JVM exited while starting the application."));
break;
case WRAPPER_JSTATE_STARTED:
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_AUTOMATIC;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("JVM exited unexpectedly."));
break;
case WRAPPER_JSTATE_STOP:
case WRAPPER_JSTATE_STOPPING:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("JVM exited unexpectedly while stopping the application."));
break;
case WRAPPER_JSTATE_STOPPED:
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM exited normally."));
}
break;
case WRAPPER_JSTATE_KILLING:
case WRAPPER_JSTATE_KILL:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO,
TEXT("JVM exited on its own while waiting to kill the application."));
break;
case WRAPPER_JSTATE_KILLED:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS,
TEXT("JVM exited after being requested to terminate."));
break;
default:
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("Unexpected jState=%d in wrapperJVMProcessExited."), wrapperData->jState);
break;
}
wrapperJVMDownCleanup(setState);
}
void wrapperBuildKey() {
int i;
size_t kcNum;
size_t num;
static int seeded = FALSE;
/* Seed the randomizer */
if (!seeded) {
srand((unsigned)time(NULL));
seeded = TRUE;
}
/* Start by generating a key */
num = _tcslen(keyChars);
for (i = 0; i < 16; i++) {
/* The way rand works, this will sometimes equal num, which is too big.
* This is rare so just round those cases down. */
/* Some platforms use very large RAND_MAX values that cause overflow problems in our math */
if (RAND_MAX > 0x10000) {
kcNum = (size_t)((rand() >> 8) * num / (RAND_MAX >> 8));
} else {
kcNum = (size_t)(rand() * num / RAND_MAX);
}
if (kcNum >= num) {
kcNum = num - 1;
}
wrapperData->key[i] = keyChars[kcNum];
}
wrapperData->key[16] = TEXT('\0');
/*
printf(" Key=%s Len=%lu\n", wrapperData->key, _tcslen(wrapperData->key));
*/
}
#ifdef WIN32
/* The ABOVE and BELOW normal priority class constants are not defined in MFVC 6.0 headers. */
#ifndef ABOVE_NORMAL_PRIORITY_CLASS
#define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
#endif
#ifndef BELOW_NORMAL_PRIORITY_CLASS
#define BELOW_NORMAL_PRIORITY_CLASS 0x00004000
#endif
/**
* Return FALSE if successful, TRUE if there were problems.
*/
int wrapperBuildNTServiceInfo() {
TCHAR *work;
const TCHAR *priority;
size_t len;
size_t valLen;
size_t workLen;
int i;
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
if (!wrapperData->configured) {
/* Load the service load order group */
updateStringValue(&wrapperData->ntServiceLoadOrderGroup, getStringProperty(properties, TEXT("wrapper.ntservice.load_order_group"), TEXT("")));
if (getStringProperties(properties, TEXT("wrapper.ntservice.dependency."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
return TRUE;
}
/* Build the dependency list. Decide how large the list needs to be */
len = 0;
i = 0;
while (propertyNames[i]) {
valLen = _tcslen(propertyValues[i]);
if (valLen > 0) {
len += valLen + 1;
}
i++;
}
/* List must end with a double '\0'. If the list is not empty then it will end with 3. But that is fine. */
len += 2;
/* Actually build the buffer */
if (wrapperData->ntServiceDependencies) {
/** This is a reload, so free up the old data. */
free(wrapperData->ntServiceDependencies);
wrapperData->ntServiceDependencies = NULL;
}
work = wrapperData->ntServiceDependencies = malloc(sizeof(TCHAR) * len);
if (!work) {
outOfMemory(TEXT("WBNTSI"), 1);
return TRUE;
}
workLen = len;
/* Now actually build up the list. Each value is separated with a '\0'. */
i = 0;
while (propertyNames[i]) {
valLen = _tcslen(propertyValues[i]);
if (valLen > 0) {
_tcsncpy(work, propertyValues[i], workLen);
work += valLen + 1;
workLen -= valLen + 1;
}
i++;
}
/* Add two more nulls to the end of the list. */
work[0] = TEXT('\0');
work[1] = TEXT('\0');
/* Memory allocated in work is stored in wrapperData. The memory should not be released here. */
work = NULL;
freeStringProperties(propertyNames, propertyValues, propertyIndices);
/* Set the service start type */
if (strcmpIgnoreCase(getStringProperty(properties, TEXT("wrapper.ntservice.starttype"), TEXT("DEMAND_START")), TEXT("AUTO_START")) == 0) {
wrapperData->ntServiceStartType = SERVICE_AUTO_START;
} else {
wrapperData->ntServiceStartType = SERVICE_DEMAND_START;
}
/* Set the service priority class */
priority = getStringProperty(properties, TEXT("wrapper.ntservice.process_priority"), TEXT("NORMAL"));
if ( (strcmpIgnoreCase(priority, TEXT("LOW")) == 0) || (strcmpIgnoreCase(priority, TEXT("IDLE")) == 0) ) {
wrapperData->ntServicePriorityClass = IDLE_PRIORITY_CLASS;
} else if (strcmpIgnoreCase(priority, TEXT("HIGH")) == 0) {
wrapperData->ntServicePriorityClass = HIGH_PRIORITY_CLASS;
} else if (strcmpIgnoreCase(priority, TEXT("REALTIME")) == 0) {
wrapperData->ntServicePriorityClass = REALTIME_PRIORITY_CLASS;
} else if (strcmpIgnoreCase(priority, TEXT("ABOVE_NORMAL")) == 0) {
wrapperData->ntServicePriorityClass = ABOVE_NORMAL_PRIORITY_CLASS;
} else if (strcmpIgnoreCase(priority, TEXT("BELOW_NORMAL")) == 0) {
wrapperData->ntServicePriorityClass = BELOW_NORMAL_PRIORITY_CLASS;
} else {
wrapperData->ntServicePriorityClass = NORMAL_PRIORITY_CLASS;
}
/* Account name */
updateStringValue(&wrapperData->ntServiceAccount, getStringProperty(properties, TEXT("wrapper.ntservice.account"), NULL));
if (wrapperData->ntServiceAccount && (_tcslen(wrapperData->ntServiceAccount) <= 0)) {
wrapperData->ntServiceAccount = NULL;
}
/* Account password */
wrapperData->ntServicePrompt = getBooleanProperty(properties, TEXT("wrapper.ntservice.account.prompt"), FALSE);
if (wrapperData->ntServicePrompt == TRUE) {
wrapperData->ntServicePasswordPrompt = TRUE;
} else {
wrapperData->ntServicePasswordPrompt = getBooleanProperty(properties, TEXT("wrapper.ntservice.password.prompt"), FALSE);
}
wrapperData->ntServicePasswordPromptMask = getBooleanProperty(properties, TEXT("wrapper.ntservice.password.prompt.mask"), TRUE);
updateStringValue(&wrapperData->ntServicePassword, getStringProperty(properties, TEXT("wrapper.ntservice.password"), NULL));
if ( wrapperData->ntServicePassword && ( _tcslen( wrapperData->ntServicePassword ) <= 0 ) ) {
wrapperData->ntServicePassword = NULL;
}
if (!wrapperData->ntServiceAccount) {
/* If there is not account name, then the password must not be set. */
wrapperData->ntServicePassword = NULL;
}
/* Interactive */
wrapperData->ntServiceInteractive = getBooleanProperty(properties, TEXT("wrapper.ntservice.interactive"), FALSE);
/* The interactive flag can not be set if an account is also set. */
if (wrapperData->ntServiceAccount && wrapperData->ntServiceInteractive) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("Ignoring the wrapper.ntservice.interactive property because it can not be set when wrapper.ntservice.account is also set."));
wrapperData->ntServiceInteractive = FALSE;
}
/* Display a Console Window. */
wrapperData->ntAllocConsole = getBooleanProperty(properties, TEXT("wrapper.ntservice.console"), FALSE);
/* Set the default hide wrapper console flag to the inverse of the alloc console flag. */
wrapperData->ntHideWrapperConsole = !wrapperData->ntAllocConsole;
/* Hide the JVM Console Window. */
wrapperData->ntHideJVMConsole = getBooleanProperty(properties, TEXT("wrapper.ntservice.hide_console"), TRUE);
/* Make sure that a console is always generated to support thread dumps */
wrapperData->generateConsole = getBooleanProperty(properties, TEXT("wrapper.ntservice.generate_console"), TRUE);
}
/* Set the single invocation flag. */
wrapperData->isSingleInvocation = getBooleanProperty(properties, TEXT("wrapper.single_invocation"), FALSE);
wrapperData->threadDumpControlCode = getIntProperty(properties, TEXT("wrapper.thread_dump_control_code"), 255);
if (wrapperData->threadDumpControlCode <= 0) {
/* Disabled */
} else if ((wrapperData->threadDumpControlCode < 128) || (wrapperData->threadDumpControlCode > 255)) {
wrapperData->threadDumpControlCode = 255;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("Ignoring the wrapper.thread_dump_control_code property because it must be in the range 128-255 or 0."));
}
return FALSE;
}
#endif
int validateTimeout(const TCHAR* propertyName, int value) {
int okValue;
if (value <= 0) {
okValue = 0;
} else if (value > WRAPPER_TIMEOUT_MAX) {
okValue = WRAPPER_TIMEOUT_MAX;
} else {
okValue = value;
}
if (okValue != value) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The value of %s must be in the range 1 to %d seconds (%d days), or 0 to disable. Changing to %d."),
propertyName, WRAPPER_TIMEOUT_MAX, WRAPPER_TIMEOUT_MAX / 86400, okValue);
}
return okValue;
}
void wrapperLoadHostName() {
char hostName[80];
TCHAR* hostName2;
#ifdef UNICODE
int len;
#endif
if (gethostname(hostName, sizeof(hostName))) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Unable to obtain host name. %s"),
getLastErrorText());
} else {
#ifdef UNICODE
#ifdef WIN32
len = MultiByteToWideChar(CP_OEMCP, 0, hostName, -1, NULL, 0);
hostName2 = malloc((len + 1) * sizeof(LPWSTR));
if (!hostName2) {
outOfMemory(TEXT("LHN"), 1);
return;
}
MultiByteToWideChar(CP_OEMCP,0, hostName, -1, hostName2, len + 1);
#else
len = mbstowcs(NULL, hostName, 0) + 1;
hostName2 = malloc(len * sizeof(TCHAR));
if (!hostName2) {
outOfMemory(TEXT("LHN"), 2);
return;
}
mbstowcs(hostName2, hostName, len);
#endif
#else
/* No conversion needed. Do an extra malloc here to keep the code simple below. */
len = _tcslen(hostName) + 1;
hostName2 = malloc(len * sizeof(TCHAR));
if (!hostName2) {
outOfMemory(TEXT("LHN"), 3);
return;
}
_tcsncpy(hostName2, hostName, len);
#endif
wrapperData->hostName = malloc(sizeof(TCHAR) * (_tcslen(hostName2) + 1));
if (!wrapperData->hostName) {
outOfMemory(TEXT("LHN"), 2);
free(hostName2);
return;
}
_tcsncpy(wrapperData->hostName, hostName2, _tcslen(hostName2) + 1);
free(hostName2);
}
}
/**
* Resolves an action name into an actionId.
*
* @param actionName Action to be resolved. (Contents of buffer will be converted to upper case.)
* @param propertyName The name of the property where the action name originated.
* @param logErrors TRUE if errors should be logged.
*
* @return The action Id, or 0 if it was unknown.
*/
int getActionForName(TCHAR *actionName, const TCHAR *propertyName, int logErrors) {
size_t len;
size_t i;
int action;
/* We need the actionName in upper case. */
len = _tcslen(actionName);
for (i = 0; i < len; i++) {
actionName[i] = _totupper(actionName[i]);
}
if (_tcscmp(actionName, TEXT("RESTART")) == 0) {
action = ACTION_RESTART;
} else if (_tcscmp(actionName, TEXT("SHUTDOWN")) == 0) {
action = ACTION_SHUTDOWN;
} else if (_tcscmp(actionName, TEXT("DUMP")) == 0) {
action = ACTION_DUMP;
} else if (_tcscmp(actionName, TEXT("NONE")) == 0) {
action = ACTION_NONE;
} else if (_tcscmp(actionName, TEXT("DEBUG")) == 0) {
action = ACTION_DEBUG;
} else if (_tcscmp(actionName, TEXT("SUCCESS")) == 0) {
action = ACTION_SUCCESS;
} else if (_tcscmp(actionName, TEXT("GC")) == 0) {
action = ACTION_GC;
} else if (_tcscmp(actionName, TEXT("PAUSE")) == 0) {
if (logErrors) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Pause actions require the Standard Edition. Ignoring action '%s' in the %s property."), actionName, propertyName);
}
action = 0;
} else if (_tcscmp(actionName, TEXT("RESUME")) == 0) {
if (logErrors) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Resume actions require the Standard Edition. Ignoring action '%s' in the %s property."), actionName, propertyName);
}
action = 0;
} else if (_tcsstr(actionName, TEXT("USER_")) == actionName) {
if (logErrors) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("User actions require the Professional Edition. Ignoring action '%s' in the %s property."), actionName, propertyName);
}
action = 0;
} else {
if (logErrors) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN, TEXT("Encountered an unknown action '%s' in the %s property. Skipping."), actionName, propertyName);
}
action = 0;
}
return action;
}
/**
* Parses a list of actions for an action property.
*
* @param actionNameList A space separated list of action names.
* @param propertyName The name of the property where the action name originated.
*
* @return an array of integer action ids, or NULL if there were any problems.
*/
int *wrapperGetActionListForNames(const TCHAR *actionNameList, const TCHAR *propertyName) {
size_t len;
TCHAR *workBuffer;
TCHAR *token;
int actionCount;
int action;
int *actionList = NULL;
#if defined(UNICODE) && !defined(WIN32)
TCHAR *state;
#endif
#if _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT("wrapperGetActionListForNames(%s, %s)"), actionNameList, propertyName);
#endif
/* First get a count of the number of valid actions. */
len = _tcslen(actionNameList);
workBuffer = malloc(sizeof(TCHAR) * (len + 1));
if (!workBuffer) {
outOfMemory(TEXT("GALFN"), 1);
} else {
actionCount = 0;
_tcsncpy(workBuffer, actionNameList, len + 1);
token = _tcstok(workBuffer, TEXT(" ,")
#if defined(UNICODE) && !defined(WIN32)
, &state
#endif
);
while (token != NULL) {
action = getActionForName(token, propertyName, TRUE);
if (action == 0) {
/* Unknown action */
} else {
actionCount++;
}
#if _DEBUG
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_INFO, TEXT(" action='%s' -> %d"), token, action);
#endif
token = _tcstok(NULL, TEXT(" ,")
#if defined(UNICODE) && !defined(WIN32)
, &state
#endif
);
}
/* Add ACTION_LIST_END */
actionCount++;
/* Create the action list to return. */
actionList = malloc(sizeof(int) * actionCount);
if (!actionList) {
outOfMemory(TEXT("GALFN"), 2);
} else {
/* Now actually pull out the actions */
actionCount = 0;
_tcsncpy(workBuffer, actionNameList, len + 1);
token = _tcstok(workBuffer, TEXT(" ,")
#if defined(UNICODE) && !defined(WIN32)
, &state
#endif
);
while (token != NULL) {
action = getActionForName(token, propertyName, FALSE);
if (action == 0) {
/* Unknown action */
} else {
actionList[actionCount] = action;
actionCount++;
}
token = _tcstok(NULL, TEXT(" ,")
#if defined(UNICODE) && !defined(WIN32)
, &state
#endif
);
}
/* Add ACTION_LIST_END */
actionList[actionCount] = ACTION_LIST_END;
actionCount++;
/* actionList returned, so don't free it. */
}
free(workBuffer);
}
return actionList;
}
/**
* Loads in the configuration triggers.
*
* @return Returns FALSE if successful, TRUE if there were any problems.
*/
int loadConfigurationTriggers() {
const TCHAR *prop;
TCHAR propName[256];
int i;
TCHAR **propertyNames;
TCHAR **propertyValues;
long unsigned int *propertyIndices;
#ifdef _DEBUG
int j;
#endif
/* To support reloading, we need to free up any previously loaded filters. */
if (wrapperData->outputFilterCount > 0) {
for (i = 0; i < wrapperData->outputFilterCount; i++) {
free(wrapperData->outputFilters[i]);
wrapperData->outputFilters[i] = NULL;
}
free(wrapperData->outputFilters);
wrapperData->outputFilters = NULL;
if (wrapperData->outputFilterActionLists) {
for (i = 0; i < wrapperData->outputFilterCount; i++) {
free(wrapperData->outputFilterActionLists[i]);
wrapperData->outputFilterActionLists[i] = NULL;
}
free(wrapperData->outputFilterActionLists);
wrapperData->outputFilterActionLists = NULL;
}
/* Individual messages are references to property values and are not malloced. */
free(wrapperData->outputFilterMessages);
wrapperData->outputFilterMessages = NULL;
free(wrapperData->outputFilterAllowWildFlags);
wrapperData->outputFilterAllowWildFlags = NULL;
free(wrapperData->outputFilterMinLens);
wrapperData->outputFilterMinLens = NULL;
}
wrapperData->outputFilterCount = 0;
if (getStringProperties(properties, TEXT("wrapper.filter.trigger."), TEXT(""), wrapperData->ignoreSequenceGaps, FALSE, &propertyNames, &propertyValues, &propertyIndices)) {
/* Failed */
return TRUE;
}
/* Loop over the properties and count how many triggers there are. */
i = 0;
while (propertyNames[i]) {
wrapperData->outputFilterCount++;
i++;
}
#if defined(MACOSX)
wrapperData->outputFilterCount++;
i++;
#endif
/* Now that a count is known, allocate memory to hold the filters and actions and load them in. */
if (wrapperData->outputFilterCount > 0) {
wrapperData->outputFilters = malloc(sizeof(TCHAR *) * wrapperData->outputFilterCount);
if (!wrapperData->outputFilters) {
outOfMemory(TEXT("LC"), 1);
return TRUE;
}
memset(wrapperData->outputFilters, 0, sizeof(TCHAR *) * wrapperData->outputFilterCount);
wrapperData->outputFilterActionLists = malloc(sizeof(int*) * wrapperData->outputFilterCount);
if (!wrapperData->outputFilterActionLists) {
outOfMemory(TEXT("LC"), 2);
return TRUE;
}
memset(wrapperData->outputFilterActionLists, 0, sizeof(int*) * wrapperData->outputFilterCount);
wrapperData->outputFilterMessages = malloc(sizeof(TCHAR *) * wrapperData->outputFilterCount);
if (!wrapperData->outputFilterMessages) {
outOfMemory(TEXT("LC"), 3);
return TRUE;
}
wrapperData->outputFilterAllowWildFlags = malloc(sizeof(int) * wrapperData->outputFilterCount);
if (!wrapperData->outputFilterAllowWildFlags) {
outOfMemory(TEXT("LC"), 4);
return TRUE;
}
memset(wrapperData->outputFilterAllowWildFlags, 0, sizeof(int) * wrapperData->outputFilterCount);
wrapperData->outputFilterMinLens = malloc(sizeof(size_t) * wrapperData->outputFilterCount);
if (!wrapperData->outputFilterMinLens) {
outOfMemory(TEXT("LC"), 5);
return TRUE;
}
memset(wrapperData->outputFilterMinLens, 0, sizeof(size_t) * wrapperData->outputFilterCount);
i = 0;
while (propertyNames[i]) {
prop = propertyValues[i];
wrapperData->outputFilters[i] = malloc(sizeof(TCHAR) * (_tcslen(prop) + 1));
if (!wrapperData->outputFilters[i]) {
outOfMemory(TEXT("LC"), 3);
return TRUE;
}
_tcsncpy(wrapperData->outputFilters[i], prop, _tcslen(prop) + 1);
/* Get the action */
_sntprintf(propName, 256, TEXT("wrapper.filter.action.%lu"), propertyIndices[i]);
prop = getStringProperty(properties, propName, TEXT("RESTART"));
wrapperData->outputFilterActionLists[i] = wrapperGetActionListForNames(prop, propName);
/* Get the message */
_sntprintf(propName, 256, TEXT("wrapper.filter.message.%lu"), propertyIndices[i]);
prop = getStringProperty(properties, propName, NULL);
wrapperData->outputFilterMessages[i] = (TCHAR *)prop;
/* Get the wildcard flags. */
_sntprintf(propName, 256, TEXT("wrapper.filter.allow_wildcards.%lu"), propertyIndices[i]);
wrapperData->outputFilterAllowWildFlags[i] = getBooleanProperty(properties, propName, FALSE);
if (wrapperData->outputFilterAllowWildFlags[i]) {
/* Calculate the minimum text length. */
wrapperData->outputFilterMinLens[i] = wrapperGetMinimumTextLengthForPattern(wrapperData->outputFilters[i]);
}
#ifdef _DEBUG
_tprintf(TEXT("filter #%lu, actions=("), propertyIndices[i]);
if (wrapperData->outputFilterActionLists[i]) {
j = 0;
while (wrapperData->outputFilterActionLists[i][j]) {
if (j > 0) {
_tprintf(TEXT(","));
}
_tprintf(TEXT("%d"), wrapperData->outputFilterActionLists[i][j]);
j++;
}
}
_tprintf(TEXT("), filter='%s'\n"), wrapperData->outputFilters[i]);
#endif
i++;
}
#if defined(MACOSX)
wrapperData->outputFilters[i] = malloc(sizeof(TCHAR) * (_tcslen(TRIGGER_ADVICE_NIL_SERVER) + 1));
if (!wrapperData->outputFilters[i]) {
outOfMemory(TEXT("LC"), 4);
return TRUE;
}
_tcsncpy(wrapperData->outputFilters[i], TRIGGER_ADVICE_NIL_SERVER, _tcslen(TRIGGER_ADVICE_NIL_SERVER) + 1);
wrapperData->outputFilterActionLists[i] = malloc(sizeof(int) * 2);
if (!wrapperData->outputFilters[i]) {
outOfMemory(TEXT("LC"), 5);
return TRUE;
}
wrapperData->outputFilterActionLists[i][0] = ACTION_ADVICE_NIL_SERVER;
wrapperData->outputFilterActionLists[i][1] = ACTION_LIST_END;
wrapperData->outputFilterMessages[i] = NULL;
wrapperData->outputFilterAllowWildFlags[i] = FALSE;
wrapperData->outputFilterMinLens[i] = 0;
i++;
#endif
}
freeStringProperties(propertyNames, propertyValues, propertyIndices);
return FALSE;
}
int getBackendTypeForName(const TCHAR *typeName) {
if (strcmpIgnoreCase(typeName, TEXT("SOCKET")) == 0) {
return WRAPPER_BACKEND_TYPE_SOCKET;
} else if (strcmpIgnoreCase(typeName, TEXT("PIPE")) == 0) {
return WRAPPER_BACKEND_TYPE_PIPE;
} else {
return WRAPPER_BACKEND_TYPE_UNKNOWN;
}
}
/**
* Return FALSE if successful, TRUE if there were problems.
*/
int loadConfiguration() {
TCHAR propName[256];
const TCHAR* val;
int startupDelay;
wrapperLoadLoggingProperties(FALSE);
/* Decide on the backend type to use. */
wrapperData->backendType = getBackendTypeForName(getStringProperty(properties, TEXT("wrapper.backend.type"), TEXT("SOCKET")));
if (wrapperData->backendType == WRAPPER_BACKEND_TYPE_UNKNOWN) {
wrapperData->backendType = WRAPPER_BACKEND_TYPE_SOCKET;
}
/* Decide whether the classpath should be passed via the environment. */
wrapperData->environmentClasspath = getBooleanProperty(properties, TEXT("wrapper.java.classpath.use_environment"), FALSE);
/* Decide how sequence gaps should be handled before any other properties are loaded. */
wrapperData->ignoreSequenceGaps = getBooleanProperty(properties, TEXT("wrapper.ignore_sequence_gaps"), FALSE);
/* Make sure that the configured log file directory is accessible. */
checkLogfileDir();
/* To make configuration reloading work correctly with changes to the log file,
* it needs to be closed here. */
closeLogfile();
/* Maintain the logger just in case we wrote any queued errors. */
maintainLogger();
/* Because the first call could cause errors as well, do it again to clear them out.
* This is only a one-time thing on startup as we test the new logfile configuration. */
maintainLogger();
/* Initialize some values not loaded */
wrapperData->exitCode = 0;
updateStringValue(&wrapperData->portAddress, getStringProperty(properties, TEXT("wrapper.port.address"), NULL));
/* Get the port. The int will wrap within the 0-65535 valid range, so no need to test the value. */
wrapperData->port = getIntProperty(properties, TEXT("wrapper.port"), 0);
wrapperData->portMin = getIntProperty(properties, TEXT("wrapper.port.min"), 32000);
if ((wrapperData->portMin < 1) || (wrapperData->portMin > 65535)) {
wrapperData->portMin = 32000;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d. Changing to %d."), TEXT("wrapper.port.min"), 1, 65535, wrapperData->portMin);
}
wrapperData->portMax = getIntProperty(properties, TEXT("wrapper.port.max"), 32999);
if ((wrapperData->portMax < 1) || (wrapperData->portMax > 65535)) {
wrapperData->portMax = __min(wrapperData->portMin + 999, 65535);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d. Changing to %d."), TEXT("wrapper.port.max"), 1, 65535, wrapperData->portMax);
} else if (wrapperData->portMax < wrapperData->portMin) {
wrapperData->portMax = __min(wrapperData->portMin + 999, 65535);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be greater than or equal to %s. Changing to %d."), TEXT("wrapper.port.max"), TEXT("wrapper.port.min"), wrapperData->portMax);
}
/* Get the port for the JVM side of the socket. */
wrapperData->jvmPort = getIntProperty(properties, TEXT("wrapper.jvm.port"), -1);
if (wrapperData->jvmPort > 0) {
if (wrapperData->jvmPort == wrapperData->port) {
wrapperData->jvmPort = -1;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.jvm.port must not equal wrapper.port. Changing to the default."));
}
}
wrapperData->jvmPortMin = getIntProperty(properties, TEXT("wrapper.jvm.port.min"), 31000);
if ((wrapperData->jvmPortMin < 1) || (wrapperData->jvmPortMin > 65535)) {
wrapperData->jvmPortMin = 31000;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d. Changing to %d."), TEXT("wrapper.jvm.port.min"), 1, 65535, wrapperData->jvmPortMin);
}
wrapperData->jvmPortMax = getIntProperty(properties, TEXT("wrapper.jvm.port.max"), 31999);
if ((wrapperData->jvmPortMax < 1) || (wrapperData->jvmPortMax > 65535)) {
wrapperData->jvmPortMax = __min(wrapperData->jvmPortMin + 999, 65535);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d. Changing to %d."), TEXT("wrapper.jvm.port.max"), 1, 65535, wrapperData->jvmPortMax);
} else if (wrapperData->jvmPortMax < wrapperData->jvmPortMin) {
wrapperData->jvmPortMax = __min(wrapperData->jvmPortMin + 999, 65535);
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be greater than or equal to %s. Changing to %d."), TEXT("wrapper.jvm.port.max"), TEXT("wrapper.jvm.port.min"), wrapperData->jvmPortMax);
}
wrapperData->printJVMVersion = getBooleanProperty(properties, TEXT("wrapper.java.version.output"), FALSE);
/* Get the wrapper command log level. */
wrapperData->commandLogLevel = getLogLevelForName(
getStringProperty(properties, TEXT("wrapper.java.command.loglevel"), TEXT("DEBUG")));
/* Should we detach the JVM on startup. */
if (wrapperData->isConsole) {
wrapperData->detachStarted = getBooleanProperty(properties, TEXT("wrapper.jvm_detach_started"), FALSE);
}
/* Get the adviser status */
wrapperData->isAdviserEnabled = getBooleanProperty(properties, TEXT("wrapper.adviser"), TRUE);
/* The adviser is always enabled if debug is enabled. */
if (wrapperData->isDebugging) {
wrapperData->isAdviserEnabled = TRUE;
}
/* Get the use system time flag. */
if (!wrapperData->configured) {
wrapperData->useSystemTime = getBooleanProperty(properties, TEXT("wrapper.use_system_time"), FALSE);
}
if (!wrapperData->configured) {
wrapperData->logBufferGrowth = getBooleanProperty(properties, TEXT("wrapper.log_buffer_growth"), FALSE);
setLogBufferGrowth(wrapperData->logBufferGrowth);
}
#ifdef WIN32
/* Get the use javaio buffer size. */
if (!wrapperData->configured) {
wrapperData->javaIOBufferSize = getIntProperty(properties, TEXT("wrapper.javaio.buffer_size"), WRAPPER_JAVAIO_BUFFER_SIZE_DEFAULT);
if (wrapperData->javaIOBufferSize == WRAPPER_JAVAIO_BUFFER_SIZE_SYSTEM_DEFAULT) {
/* Ok. System default buffer size. */
} else if (wrapperData->javaIOBufferSize < WRAPPER_JAVAIO_BUFFER_SIZE_MIN) {
wrapperData->javaIOBufferSize = WRAPPER_JAVAIO_BUFFER_SIZE_MIN;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d or %d. Changing to %d."), TEXT("wrapper.javaio.buffer_size"), WRAPPER_JAVAIO_BUFFER_SIZE_MIN, WRAPPER_JAVAIO_BUFFER_SIZE_MAX, WRAPPER_JAVAIO_BUFFER_SIZE_SYSTEM_DEFAULT, wrapperData->javaIOBufferSize);
} else if (wrapperData->javaIOBufferSize > WRAPPER_JAVAIO_BUFFER_SIZE_MAX) {
wrapperData->javaIOBufferSize = WRAPPER_JAVAIO_BUFFER_SIZE_MAX;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("%s must be in the range %d to %d or %d. Changing to %d."), TEXT("wrapper.javaio.buffer_size"), WRAPPER_JAVAIO_BUFFER_SIZE_MIN, WRAPPER_JAVAIO_BUFFER_SIZE_MAX, WRAPPER_JAVAIO_BUFFER_SIZE_SYSTEM_DEFAULT, wrapperData->javaIOBufferSize);
}
}
#endif
/* Get the use javaio thread flag. */
if (!wrapperData->configured) {
wrapperData->useJavaIOThread = getBooleanProperty(properties, TEXT("wrapper.javaio.use_thread"), getBooleanProperty(properties, TEXT("wrapper.use_javaio_thread"), FALSE));
}
/* Decide whether or not a mutex should be used to protect the tick timer. */
if (!wrapperData->configured) {
wrapperData->useTickMutex = getBooleanProperty(properties, TEXT("wrapper.use_tick_mutex"), FALSE);
}
/* Get the timer thresholds. Properties are in seconds, but internally we use ticks. */
wrapperData->timerFastThreshold = getIntProperty(properties, TEXT("wrapper.timer_fast_threshold"), WRAPPER_TIMER_FAST_THRESHOLD * WRAPPER_TICK_MS / 1000) * 1000 / WRAPPER_TICK_MS;
wrapperData->timerSlowThreshold = getIntProperty(properties, TEXT("wrapper.timer_slow_threshold"), WRAPPER_TIMER_SLOW_THRESHOLD * WRAPPER_TICK_MS / 1000) * 1000 / WRAPPER_TICK_MS;
/* Load the name of the native library to be loaded. */
wrapperData->nativeLibrary = getStringProperty(properties, TEXT("wrapper.native_library"), TEXT("wrapper"));
/* Get the append PATH to library path flag. */
wrapperData->libraryPathAppendPath = getBooleanProperty(properties, TEXT("wrapper.java.library.path.append_system_path"), FALSE);
/* Get the state output status. */
wrapperData->isStateOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.state_output"), FALSE);
/* Get the tick output status. */
wrapperData->isTickOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.tick_output"), FALSE);
/* Get the loop debug output status. */
wrapperData->isLoopOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.loop_output"), FALSE);
/* Get the sleep debug output status. */
wrapperData->isSleepOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.sleep_output"), FALSE);
/* Get the memory output status. */
wrapperData->isMemoryOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.memory_output"), FALSE);
wrapperData->memoryOutputInterval = getIntProperty(properties, TEXT("wrapper.memory_output.interval"), 1);
/* Get the cpu output status. */
wrapperData->isCPUOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.cpu_output"), FALSE);
wrapperData->cpuOutputInterval = getIntProperty(properties, TEXT("wrapper.cpu_output.interval"), 1);
/* Get the pageFault output status. */
if (!wrapperData->configured) {
wrapperData->isPageFaultOutputEnabled = getBooleanProperty(properties, TEXT("wrapper.pagefault_output"), FALSE);
wrapperData->pageFaultOutputInterval = getIntProperty(properties, TEXT("wrapper.pagefault_output.interval"), 1);
}
/* Get the disable tests flag. */
wrapperData->isTestsDisabled = getBooleanProperty(properties, TEXT("wrapper.disable_tests"), FALSE);
/* Get the shutdown hook status */
wrapperData->isShutdownHookDisabled = getBooleanProperty(properties, TEXT("wrapper.disable_shutdown_hook"), FALSE);
/* Get the forced shutdown flag status. */
wrapperData->isForcedShutdownDisabled = getBooleanProperty(properties, TEXT("wrapper.disable_forced_shutdown"), FALSE);
/* Get the startup delay. */
startupDelay = getIntProperty(properties, TEXT("wrapper.startup.delay"), 0);
wrapperData->startupDelayConsole = getIntProperty(properties, TEXT("wrapper.startup.delay.console"), startupDelay);
if (wrapperData->startupDelayConsole < 0) {
wrapperData->startupDelayConsole = 0;
}
wrapperData->startupDelayService = getIntProperty(properties, TEXT("wrapper.startup.delay.service"), startupDelay);
if (wrapperData->startupDelayService < 0) {
wrapperData->startupDelayService = 0;
}
/* Get the restart delay. */
wrapperData->restartDelay = getIntProperty(properties, TEXT("wrapper.restart.delay"), 5);
if (wrapperData->restartDelay < 0) {
wrapperData->restartDelay = 0;
}
/* Get the flag which decides whether or not configuration should be reloaded on JVM restart. */
wrapperData->restartReloadConf = getBooleanProperty(properties, TEXT("wrapper.restart.reload_configuration"), FALSE);
/* Get the disable restart flag */
wrapperData->isRestartDisabled = getBooleanProperty(properties, TEXT("wrapper.disable_restarts"), FALSE);
wrapperData->isAutoRestartDisabled = getBooleanProperty(properties, TEXT("wrapper.disable_restarts.automatic"), wrapperData->isRestartDisabled);
/* Get the timeout settings */
wrapperData->cpuTimeout = getIntProperty(properties, TEXT("wrapper.cpu.timeout"), 10);
wrapperData->startupTimeout = getIntProperty(properties, TEXT("wrapper.startup.timeout"), 30);
wrapperData->pingTimeout = getIntProperty(properties, TEXT("wrapper.ping.timeout"), 30);
if (wrapperData->pingActionList) {
free(wrapperData->pingActionList);
}
wrapperData->pingActionList = wrapperGetActionListForNames(getStringProperty(properties, TEXT("wrapper.ping.timeout.action"), TEXT("RESTART")), TEXT("wrapper.ping.timeout.action"));
wrapperData->pingAlertThreshold = getIntProperty(properties, TEXT("wrapper.ping.alert.threshold"), __max(1, wrapperData->pingTimeout / 4));
wrapperData->pingAlertLogLevel = getLogLevelForName(getStringProperty(properties, TEXT("wrapper.ping.alert.loglevel"), TEXT("STATUS")));
wrapperData->pingInterval = getIntProperty(properties, TEXT("wrapper.ping.interval"), 5);
wrapperData->pingIntervalLogged = getIntProperty(properties, TEXT("wrapper.ping.interval.logged"), 1);
wrapperData->shutdownTimeout = getIntProperty(properties, TEXT("wrapper.shutdown.timeout"), 30);
wrapperData->jvmExitTimeout = getIntProperty(properties, TEXT("wrapper.jvm_exit.timeout"), 15);
wrapperData->jvmCleanupTimeout = getIntProperty(properties, TEXT("wrapper.jvm_cleanup.timeout"), 10);
wrapperData->jvmTerminateTimeout = getIntProperty(properties, TEXT("wrapper.jvm_terminate.timeout"), 10);
wrapperData->cpuTimeout = validateTimeout(TEXT("wrapper.cpu.timeout"), wrapperData->cpuTimeout);
wrapperData->startupTimeout = validateTimeout(TEXT("wrapper.startup.timeout"), wrapperData->startupTimeout);
wrapperData->pingTimeout = validateTimeout(TEXT("wrapper.ping.timeout"), wrapperData->pingTimeout);
wrapperData->shutdownTimeout = validateTimeout(TEXT("wrapper.shutdown.timeout"), wrapperData->shutdownTimeout);
wrapperData->jvmExitTimeout = validateTimeout(TEXT("wrapper.jvm_exit.timeout"), wrapperData->jvmExitTimeout);
wrapperData->jvmTerminateTimeout = validateTimeout(TEXT("wrapper.jvm_terminate.timeout"), wrapperData->jvmTerminateTimeout);
wrapperData->jvmCleanupTimeout = validateTimeout(TEXT("wrapper.jvm_cleanup.timeout"), wrapperData->jvmCleanupTimeout);
if (wrapperData->pingInterval < 1) {
wrapperData->pingInterval = 1;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The value of %s must be at least %d second(s). Changing to %d."), TEXT("wrapper.ping.interval"), 1, wrapperData->pingInterval);
} else if (wrapperData->pingInterval > 3600) {
wrapperData->pingInterval = 3600;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.ping.interval must be less than or equal to 1 hour (3600 seconds). Changing to 3600."));
}
if (wrapperData->pingIntervalLogged < 1) {
wrapperData->pingIntervalLogged = 1;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The value of %s must be at least %d second(s). Changing to %d."), TEXT("wrapper.ping.interval.logged"), 1, wrapperData->pingIntervalLogged);
} else if (wrapperData->pingIntervalLogged > 86400) {
wrapperData->pingIntervalLogged = 86400;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.ping.interval.logged must be less than or equal to 1 day (86400 seconds). Changing to 86400."));
}
if ((wrapperData->pingTimeout > 0) && (wrapperData->pingTimeout < wrapperData->pingInterval + 5)) {
wrapperData->pingTimeout = wrapperData->pingInterval + 5;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.ping.timeout must be at least 5 seconds longer than wrapper.ping.interval. Changing to %d."), wrapperData->pingTimeout);
}
if (wrapperData->pingAlertThreshold <= 0) {
/* Ping Alerts disabled. */
wrapperData->pingAlertThreshold = 0;
} else if ((wrapperData->pingTimeout > 0) && (wrapperData->pingAlertThreshold > wrapperData->pingTimeout)) {
wrapperData->pingAlertThreshold = wrapperData->pingTimeout;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("wrapper.ping.alert.threshold must be less than or equal to the value of wrapper.ping.timeout (%d seconds). Changing to %d."),
wrapperData->pingInterval, wrapperData->pingTimeout);
}
if (wrapperData->cpuTimeout > 0) {
/* Make sure that the timeouts are all longer than the cpu timeout. */
if ((wrapperData->startupTimeout > 0) && (wrapperData->startupTimeout < wrapperData->cpuTimeout)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("CPU timeout detection may not operate correctly during startup because wrapper.cpu.timeout is not smaller than wrapper.startup.timeout."));
}
if ((wrapperData->pingTimeout > 0) && (wrapperData->pingTimeout < wrapperData->cpuTimeout)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("CPU timeout detection may not operate correctly because wrapper.cpu.timeout is not smaller than wrapper.ping.timeout."));
}
if ((wrapperData->shutdownTimeout > 0) && (wrapperData->shutdownTimeout < wrapperData->cpuTimeout)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("CPU timeout detection may not operate correctly during shutdown because wrapper.cpu.timeout is not smaller than wrapper.shutdown.timeout."));
}
/* jvmExit timeout can be shorter than the cpu timeout. */
}
/* Load properties controlling the number times the JVM can be restarted. */
wrapperData->maxFailedInvocations = getIntProperty(properties, TEXT("wrapper.max_failed_invocations"), 5);
wrapperData->successfulInvocationTime = getIntProperty(properties, TEXT("wrapper.successful_invocation_time"), 300);
if (wrapperData->maxFailedInvocations < 1) {
wrapperData->maxFailedInvocations = 1;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("The value of %s must be at least %d second(s). Changing to %d."), TEXT("wrapper.max_failed_invocations"), 1, wrapperData->maxFailedInvocations);
}
/* TRUE if the JVM should be asked to dump its state when it fails to halt on request. */
wrapperData->requestThreadDumpOnFailedJVMExit = getBooleanProperty(properties, TEXT("wrapper.request_thread_dump_on_failed_jvm_exit"), FALSE);
wrapperData->requestThreadDumpOnFailedJVMExitDelay = getIntProperty(properties, TEXT("wrapper.request_thread_dump_on_failed_jvm_exit.delay"), 5);
if (wrapperData->requestThreadDumpOnFailedJVMExitDelay < 1) {
wrapperData->requestThreadDumpOnFailedJVMExitDelay = 1;
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR,
TEXT("The value of %s must be at least %d second(s). Changing to %d."), TEXT("wrapper.request_thread_dump_on_failed_jvm_exit.delay"), 1, wrapperData->requestThreadDumpOnFailedJVMExitDelay);
}
/* Load the output filters. */
if (loadConfigurationTriggers()) {
return TRUE;
}
/** Get the pid files if any. May be NULL */
if (!wrapperData->configured) {
updateStringValue(&wrapperData->pidFilename, getFileSafeStringProperty(properties, TEXT("wrapper.pidfile"), NULL));
correctWindowsPath(wrapperData->pidFilename);
}
wrapperData->pidFileStrict = getBooleanProperty(properties, TEXT("wrapper.pidfile.strict"), FALSE);
updateStringValue(&wrapperData->javaPidFilename, getFileSafeStringProperty(properties, TEXT("wrapper.java.pidfile"), NULL));
correctWindowsPath(wrapperData->javaPidFilename);
/** Get the lock file if any. May be NULL */
if (!wrapperData->configured) {
updateStringValue(&wrapperData->lockFilename, getFileSafeStringProperty(properties, TEXT("wrapper.lockfile"), NULL));
correctWindowsPath(wrapperData->lockFilename);
}
/** Get the java id file. May be NULL */
updateStringValue(&wrapperData->javaIdFilename, getFileSafeStringProperty(properties, TEXT("wrapper.java.idfile"), NULL));
correctWindowsPath(wrapperData->javaIdFilename);
/** Get the status files if any. May be NULL */
if (!wrapperData->configured) {
updateStringValue(&wrapperData->statusFilename, getFileSafeStringProperty(properties, TEXT("wrapper.statusfile"), NULL));
correctWindowsPath(wrapperData->statusFilename);
}
updateStringValue(&wrapperData->javaStatusFilename, getFileSafeStringProperty(properties, TEXT("wrapper.java.statusfile"), NULL));
correctWindowsPath(wrapperData->javaStatusFilename);
/** Get the command file if any. May be NULL */
updateStringValue(&wrapperData->commandFilename, getFileSafeStringProperty(properties, TEXT("wrapper.commandfile"), NULL));
correctWindowsPath(wrapperData->commandFilename);
wrapperData->commandFileTests = getBooleanProperty(properties, TEXT("wrapper.commandfile.enable_tests"), FALSE);
/** Get the interval at which the command file will be polled. */
wrapperData->commandPollInterval = propIntMin(propIntMax(getIntProperty(properties, TEXT("wrapper.command.poll_interval"), 5), 1), 3600);
/** Get the anchor file if any. May be NULL */
if (!wrapperData->configured) {
updateStringValue(&wrapperData->anchorFilename, getFileSafeStringProperty(properties, TEXT("wrapper.anchorfile"), NULL));
correctWindowsPath(wrapperData->anchorFilename);
}
/** Get the interval at which the anchor file will be polled. */
wrapperData->anchorPollInterval = propIntMin(propIntMax(getIntProperty(properties, TEXT("wrapper.anchor.poll_interval"), 5), 1), 3600);
/** Flag controlling whether or not system signals should be ignored. */
val = getStringProperty(properties, TEXT("wrapper.ignore_signals"), TEXT("FALSE"));
if ( ( strcmpIgnoreCase( val, TEXT("TRUE") ) == 0 ) || ( strcmpIgnoreCase( val, TEXT("BOTH") ) == 0 ) ) {
wrapperData->ignoreSignals = WRAPPER_IGNORE_SIGNALS_WRAPPER + WRAPPER_IGNORE_SIGNALS_JAVA;
} else if ( strcmpIgnoreCase( val, TEXT("WRAPPER") ) == 0 ) {
wrapperData->ignoreSignals = WRAPPER_IGNORE_SIGNALS_WRAPPER;
} else if ( strcmpIgnoreCase( val, TEXT("JAVA") ) == 0 ) {
wrapperData->ignoreSignals = WRAPPER_IGNORE_SIGNALS_JAVA;
} else {
wrapperData->ignoreSignals = 0;
}
/* Obtain the Console Title. */
_sntprintf(propName, 256, TEXT("wrapper.console.title.%s"), wrapperOS);
updateStringValue(&wrapperData->consoleTitle, getStringProperty(properties, propName, getStringProperty(properties, TEXT("wrapper.console.title"), NULL)));
/* Load the service name (Used to be windows specific so use those properties if set.) */
updateStringValue(&wrapperData->serviceName, getStringProperty(properties, TEXT("wrapper.name"), getStringProperty(properties, TEXT("wrapper.ntservice.name"), TEXT("wrapper"))));
/* Load the service display name (Used to be windows specific so use those properties if set.) */
updateStringValue(&wrapperData->serviceDisplayName, getStringProperty(properties, TEXT("wrapper.displayname"), getStringProperty(properties, TEXT("wrapper.ntservice.displayname"), wrapperData->serviceName)));
/* Load the service description, default to display name (Used to be windows specific so use those properties if set.) */
updateStringValue(&wrapperData->serviceDescription, getStringProperty(properties, TEXT("wrapper.description"), getStringProperty(properties, TEXT("wrapper.ntservice.description"), wrapperData->serviceDisplayName)));
/* Pausable */
wrapperData->pausable = getBooleanProperty(properties, TEXT("wrapper.pausable"), getBooleanProperty(properties, TEXT("wrapper.ntservice.pausable"), FALSE));
wrapperData->pausableStopJVM = getBooleanProperty(properties, TEXT("wrapper.pausable.stop_jvm"), getBooleanProperty(properties, TEXT("wrapper.ntservice.pausable.stop_jvm"), TRUE));
if (!wrapperData->configured) {
wrapperData->initiallyPaused = getBooleanProperty(properties, TEXT("wrapper.pause_on_startup"), FALSE);
}
#ifdef WIN32
wrapperData->ignoreUserLogoffs = getBooleanProperty(properties, TEXT("wrapper.ignore_user_logoffs"), FALSE);
/* Configure the NT service information */
if (wrapperBuildNTServiceInfo()) {
return TRUE;
}
if (wrapperData->generateConsole) {
if (!wrapperData->ntAllocConsole) {
/* We need to allocate a console in order for the thread dumps to work
* when running as a service. But the user did not request that a
* console be visible so we want to hide it. */
wrapperData->ntAllocConsole = TRUE;
wrapperData->ntHideWrapperConsole = TRUE;
}
}
#ifdef WIN32
if ((!strcmpIgnoreCase(wrapperData->argCommand, TEXT("s")) || !strcmpIgnoreCase(wrapperData->argCommand, TEXT("-service")))
&& (!wrapperData->ntAllocConsole || wrapperData->ntHideWrapperConsole)) {
#else
if (!wrapperData->isConsole) {
#endif
/* The console is not visible, so we shouldn't waste time logging to it. */
setConsoleLogLevelInt(LEVEL_NONE);
}
#else /* UNIX */
/* Configure the Unix daemon information */
if (wrapperBuildUnixDaemonInfo()) {
return TRUE;
}
#endif
if (_tcscmp(wrapperVersionRoot, getStringProperty(properties, TEXT("wrapper.script.version"), wrapperVersionRoot)) != 0) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_WARN,
TEXT("The version of the script (%s) doesn't match the version of this Wrapper (%s). This might cause some problems"),
getStringProperty(properties, TEXT("wrapper.script.version"), wrapperVersionRoot), wrapperVersionRoot);
}
wrapperData->configured = TRUE;
return FALSE;
}
/**
* Requests a lock on the tick mutex.
*
* @return TRUE if there were any problems, FALSE if successful.
*/
int wrapperLockTickMutex() {
#ifdef WIN32
switch (WaitForSingleObject(tickMutexHandle, INFINITE)) {
case WAIT_ABANDONED:
_tprintf(TEXT("Tick was abandoned.\n"));
return TRUE;
case WAIT_FAILED:
_tprintf(TEXT("Tick wait failed.\n"));
return TRUE;
case WAIT_TIMEOUT:
_tprintf(TEXT("Tick wait timed out.\n"));
return TRUE;
default:
/* Ok */
break;
}
#else
if (pthread_mutex_lock(&tickMutex)) {
_tprintf(TEXT("Failed to lock the Tick mutex. %s\n"), getLastErrorText());
return TRUE;
}
#endif
return FALSE;
}
/**
* Releases a lock on the tick mutex.
*
* @return TRUE if there were any problems, FALSE if successful.
*/
int wrapperReleaseTickMutex() {
#ifdef WIN32
if (!ReleaseMutex(tickMutexHandle)) {
_tprintf(TEXT("Failed to release tick mutex. %s\n"), getLastErrorText());
return TRUE;
}
#else
if (pthread_mutex_unlock(&tickMutex)) {
_tprintf(TEXT("Failed to unlock the tick mutex. %s\n"), getLastErrorText());
return TRUE;
}
#endif
return FALSE;
}
/**
* Calculates a tick count using the system time.
*
* We normally need 64 bits to do this calculation. Play some games to get
* the correct values with 32 bit variables.
*/
TICKS wrapperGetSystemTicks() {
struct timeb timeBuffer;
DWORD high, low;
TICKS sum;
#ifdef _DEBUG
TICKS assertSum;
#endif
wrapperGetCurrentTime(&timeBuffer);
/* Break in half. */
high = (DWORD)(timeBuffer.time >> 16) & 0xffff;
low = (DWORD)(timeBuffer.time & 0xffff);
/* Work on each half. */
high = high * 1000 / WRAPPER_TICK_MS;
low = (low * 1000 + timeBuffer.millitm) / WRAPPER_TICK_MS;
/* Now combine them in such a way that the correct bits are truncated. */
high = high + ((low >> 16) & 0xffff);
sum = (TICKS)(((high & 0xffff) << 16) + (low & 0xffff));
/* Check the result. */
#ifdef _DEBUG
#ifdef WIN32
assertSum = (TICKS)((timeBuffer.time * 1000UI64 + timeBuffer.millitm) / WRAPPER_TICK_MS);
#else
/* This will produce the following warning on some compilers:
* warning: ANSI C forbids long long integer constants
* Is there another way to do this? */
assertSum = (TICKS)((timeBuffer.time * 1000ULL + timeBuffer.millitm) / WRAPPER_TICK_MS);
#endif
if (assertSum != sum) {
_tprintf(TEXT("wrapperGetSystemTicks() resulted in %08x rather than %08x\n"), sum, assertSum);
}
#endif
return sum;
}
/**
* Returns difference in seconds between the start and end ticks. This function
* handles cases where the tick counter has wrapped between when the start
* and end tick counts were taken. See the wrapperGetTicks() function.
*
* This can be done safely in 32 bits
*/
int wrapperGetTickAgeSeconds(TICKS start, TICKS end) {
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" wrapperGetTickAgeSeconds(%08x, %08x) -> %08x"), start, end, (int)((end - start) * WRAPPER_TICK_MS) / 1000);
*/
/* Simply subtracting the values will always work even if end has wrapped
* due to overflow.
* 0x00000001 - 0xffffffff = 0x00000002 = 2
* 0xffffffff - 0x00000001 = 0xfffffffe = -2
*/
return (int)((end - start) * WRAPPER_TICK_MS) / 1000;
}
/**
* Returns difference in ticks between the start and end ticks. This function
* handles cases where the tick counter has wrapped between when the start
* and end tick counts were taken. See the wrapperGetTicks() function.
*
* This can be done safely in 32 bits
*/
int wrapperGetTickAgeTicks(TICKS start, TICKS end) {
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" wrapperGetTickAgeSeconds(%08x, %08x) -> %08x"), start, end, (int)(end - start));
*/
/* Simply subtracting the values will always work even if end has wrapped
* due to overflow.
* 0x00000001 - 0xffffffff = 0x00000002 = 2
* 0xffffffff - 0x00000001 = 0xfffffffe = -2
*/
return (int)(end - start);
}
/**
* Returns TRUE if the specified tick timeout has expired relative to the
* specified tick count.
*/
int wrapperTickExpired(TICKS nowTicks, TICKS timeoutTicks) {
/* Convert to a signed value. */
int age = nowTicks - timeoutTicks;
if (age >= 0) {
return TRUE;
} else {
return FALSE;
}
}
/**
* Returns a tick count that is the specified number of seconds later than
* the base tick count.
*
* This calculation will work as long as the number of seconds is not large
* enough to require more than 32 bits when multiplied by 1000.
*/
TICKS wrapperAddToTicks(TICKS start, int seconds) {
/*
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" wrapperAddToTicks(%08x, %08x) -> %08x"), start, seconds, start + (seconds * 1000 / WRAPPER_TICK_MS));
*/
return start + (seconds * 1000 / WRAPPER_TICK_MS);
}
/**
* Do some sanity checks on the tick timer math.
*/
int wrapperTickAssertions() {
int result = FALSE;
TICKS ticks1, ticks2, ticksR, ticksE;
int value1, valueR, valueE;
/** wrapperGetTickAgeTicks test. */
ticks1 = 0xfffffffe;
ticks2 = 0xffffffff;
valueE = 1;
valueR = wrapperGetTickAgeTicks(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeTicks(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0xffffffff;
ticks2 = 0xfffffffe;
valueE = -1;
valueR = wrapperGetTickAgeTicks(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeTicks(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0xffffffff;
ticks2 = 0x00000000;
valueE = 1;
valueR = wrapperGetTickAgeTicks(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeTicks(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0x00000000;
ticks2 = 0xffffffff;
valueE = -1;
valueR = wrapperGetTickAgeTicks(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeTicks(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
/** wrapperGetTickAgeSeconds test. */
ticks1 = 0xfffffff0;
ticks2 = 0xffffffff;
valueE = 1;
valueR = wrapperGetTickAgeSeconds(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeSeconds(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0xffffffff;
ticks2 = 0x0000000f;
valueE = 1;
valueR = wrapperGetTickAgeSeconds(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeSeconds(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0x0000000f;
ticks2 = 0xffffffff;
valueE = -1;
valueR = wrapperGetTickAgeSeconds(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperGetTickAgeSeconds(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
/** wrapperTickExpired test. */
ticks1 = 0xfffffffe;
ticks2 = 0xffffffff;
valueE = FALSE;
valueR = wrapperTickExpired(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperTickExpired(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0xffffffff;
ticks2 = 0xffffffff;
valueE = TRUE;
valueR = wrapperTickExpired(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperTickExpired(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0xffffffff;
ticks2 = 0x00000001;
valueE = FALSE;
valueR = wrapperTickExpired(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperTickExpired(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
ticks1 = 0x00000001;
ticks2 = 0xffffffff;
valueE = TRUE;
valueR = wrapperTickExpired(ticks1, ticks2);
if (valueR != valueE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperTickExpired(%08x, %08x) == %0d != %0d"), ticks1, ticks2, valueR, valueE);
result = TRUE;
}
/** wrapperAddToTicks test. */
ticks1 = 0xffffffff;
value1 = 1;
ticksE = 0x00000009;
ticksR = wrapperAddToTicks(ticks1, value1);
if (ticksR != ticksE) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL, TEXT("Assert Failed: wrapperAddToTicks(%08x, %d) == %08x != %08x"), ticks1, value1, ticksR, ticksE);
result = TRUE;
}
return result;
}
/**
* Sets the working directory of the Wrapper to the specified directory.
* The directory can be relative or absolute.
* If there are any problems then a non-zero value will be returned.
*
* @param dir Directory to change to.
* @param logErrors TRUE if errors should be logged.
*/
int wrapperSetWorkingDir(const TCHAR* dir, int logErrors) {
int showOutput = wrapperData->configured;
if (_tchdir(dir)) {
if ( logErrors )
{
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_FATAL,
TEXT("Unable to set working directory to: %s (%s)"), dir, getLastErrorText());
}
return TRUE;
}
/* This function is sometimes called before the configuration is loaded. */
#ifdef _DEBUG
showOutput = TRUE;
#endif
if (showOutput) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Working directory set to: %s"), dir);
}
/* Set a variable to the location of the binary. */
setEnv(TEXT("WRAPPER_WORKING_DIR"), dir, ENV_SOURCE_WRAPPER);
return FALSE;
}
/******************************************************************************
* Protocol callback functions
*****************************************************************************/
void wrapperLogSignaled(int logLevel, TCHAR *msg) {
/* */
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Got a log message from JVM: %s"), msg);
}
/* */
log_printf(wrapperData->jvmRestarts, logLevel, msg);
}
void wrapperKeyRegistered(TCHAR *key) {
/* Allow for a large integer + \0 */
TCHAR buffer[11];
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("Got key from JVM: %s"), key);
}
switch (wrapperData->jState) {
case WRAPPER_JSTATE_LAUNCHING:
/* We now know that the Java side wrapper code has started and
* registered with a key. We still need to verify that it is
* the correct key however. */
if (_tcscmp(key, wrapperData->key) == 0) {
/* This is the correct key. */
/* We now know that the Java side wrapper code has started. */
wrapperSetJavaState(WRAPPER_JSTATE_LAUNCHED, 0, -1);
/* Send the low log level to the JVM so that it can control output via the log method. */
_sntprintf(buffer, 11, TEXT("%d"), getLowLogLevel());
wrapperProtocolFunction(WRAPPER_MSG_LOW_LOG_LEVEL, buffer);
/* Send the log file name. */
sendLogFileName();
/* Send the properties. */
sendProperties();
} else {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("Received a connection request with an incorrect key. Waiting for another connection."));
/* This was the wrong key. Send a response. */
wrapperProtocolFunction(WRAPPER_MSG_BADKEY, TEXT("Incorrect key. Connection rejected."));
/* Close the current connection. Assume that the real JVM
* is still out there trying to connect. So don't change
* the state. If for some reason, this was the correct
* JVM, but the key was wrong. then this state will time
* out and recover. */
wrapperProtocolClose();
}
break;
case WRAPPER_JSTATE_STOP:
/* We got a key registration. This means that the JVM thinks it was
* being launched but the Wrapper is trying to stop. This state
* will clean up correctly. */
break;
case WRAPPER_JSTATE_STOPPING:
/* We got a key registration. This means that the JVM thinks it was
* being launched but the Wrapper is trying to stop. Now that the
* connection to the JVM has been opened, tell it to stop cleanly. */
wrapperSetJavaState(WRAPPER_JSTATE_STOP, 0, -1);
break;
default:
/* We got a key registration that we were not expecting. Ignore it. */
break;
}
}
/**
* Called when a ping is first determined to be slower than the wrapper.ping.alert.threshold.
* This will happen before it has actually been responded to.
*/
void wrapperPingSlow() {
}
/**
* Called when a ping is responded to, but was slower than the wrapper.ping.alert.threshold.
*
* @param tickAge The number of seconds it took to respond.
*/
void wrapperPingRespondedSlow(int tickAge) {
log_printf(WRAPPER_SOURCE_WRAPPER, wrapperData->pingAlertLogLevel, TEXT("Pinging the JVM took %d seconds to respond."), tickAge);
}
/**
* Called when a ping response is received.
*
* @param pingSendTicks Time in ticks when the ping was originally sent.
* @param queueWarnings TRUE if warnings about the queue should be logged, FALSE if the ping response did not contain a time.
*/
void wrapperPingResponded(TICKS pingSendTicks, int queueWarnings) {
TICKS nowTicks;
int tickAge;
PPendingPing pendingPing;
int pingSearchDone;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Ping Response (tick %08x)"), pingSendTicks);
#endif
/* We want to purge the ping from the PendingPing list. */
do {
pendingPing = wrapperData->firstPendingPing;
if (pendingPing != NULL) {
tickAge = wrapperGetTickAgeTicks(pingSendTicks, pendingPing->sentTicks);
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE First Queued Ping (tick %08x, age %d)"), pendingPing->sentTicks, tickAge);
#endif
if (tickAge > 0) { /* pendingPing->sentTicks > pingSendTicks */
/* We received a ping response that is earlier than the one we were expecting.
* If the pendingPingQueue has overflown then we will stop writing to it. Don't long warning messages when in this state as they would be confusing and are expected.
* Leave this one in the queue for later. */
if (queueWarnings) {
if ((!wrapperData->pendingPingQueueOverflow) && (!wrapperData->pendingPingQueueOverflowEmptied)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("Received an unexpected ping response, sent at tick %08x. First expected ping was sent at tick %08x."), pingSendTicks, pendingPing->sentTicks);
} else {
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Silently skipping unexpected ping response. (tick %08x) (First tick %08x)"), pingSendTicks, pendingPing->sentTicks);
#endif
}
}
pendingPing = NULL;
pingSearchDone = TRUE;
} else {
if (tickAge < 0) {
/* This PendingPing object was sent before the PING that we received. This means that we somehow lost a ping. */
if (queueWarnings) {
if ((!wrapperData->pendingPingQueueOverflow) && (!wrapperData->pendingPingQueueOverflowEmptied)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("Lost a ping response, sent at tick %08x."), pendingPing->sentTicks);
} else {
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Silently skipping lost ping response. (tick %08x)"), pendingPing->sentTicks);
#endif
}
}
pingSearchDone = FALSE;
} else {
/* This PendingPing object is for this PING event. */
pingSearchDone = TRUE;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Expected Ping Response. (tick %08x)"), pendingPing->sentTicks);
#endif
/* When the emptied flag is set, we know that we are recovering from an overflow.
* That flag is reset on the first expected PendingPing found in the queue. */
if (wrapperData->pendingPingQueueOverflowEmptied) {
wrapperData->pendingPingQueueOverflowEmptied = FALSE;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Emptied Set flag reset."));
#endif
}
}
/* Detach the PendingPing from the queue. */
if (pendingPing->nextPendingPing != NULL) {
/* This was the first PendingPing of several in the queue. */
wrapperData->pendingPingCount--;
if (wrapperData->firstUnwarnedPendingPing == wrapperData->firstPendingPing) {
wrapperData->firstUnwarnedPendingPing = pendingPing->nextPendingPing;
}
wrapperData->firstPendingPing = pendingPing->nextPendingPing;
pendingPing->nextPendingPing = NULL;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("--- PING QUEUE Size: %d"), wrapperData->pendingPingCount);
#endif
} else {
/* This was the only PendingPing in the queue. */
wrapperData->pendingPingCount = 0;
wrapperData->firstUnwarnedPendingPing = NULL;
wrapperData->firstPendingPing = NULL;
wrapperData->lastPendingPing = NULL;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("--- PING QUEUE Empty.") );
#endif
if (wrapperData->pendingPingQueueOverflow) {
wrapperData->pendingPingQueueOverflowEmptied = TRUE;
wrapperData->pendingPingQueueOverflow = FALSE;
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Reset Overflow, Emptied Set.") );
#endif
}
}
/* Free up the pendingPing object. */
if (pendingPing != NULL) {
free(pendingPing);
pendingPing = NULL;
}
}
} else {
/* Got a ping response when the queue was empty. */
if (queueWarnings) {
if ((!wrapperData->pendingPingQueueOverflow) && (!wrapperData->pendingPingQueueOverflowEmptied)) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_ERROR, TEXT("Received an unexpected ping response, sent at tick %08x."), pingSendTicks);
} else {
#ifdef DEBUG_PING_QUEUE
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT(" PING QUEUE Silently skipping unexpected ping response. (tick %08x) (Empty)"), pingSendTicks);
#endif
}
}
pingSearchDone = TRUE;
}
} while (!pingSearchDone);
/* Depending on the current JVM state, do something. */
switch (wrapperData->jState) {
case WRAPPER_JSTATE_STARTED:
/* We got a response to a ping. */
nowTicks = wrapperGetTicks();
/* Figure out how long it took for us to get this ping response in seconds. */
tickAge = wrapperGetTickAgeSeconds(pingSendTicks, nowTicks);
/* If we took longer than the threshold then we want to log a message. */
if ((wrapperData->pingAlertThreshold > 0) && (tickAge >= wrapperData->pingAlertThreshold)) {
wrapperPingRespondedSlow(tickAge);
}
/* Allow 5 + <pingTimeout> more seconds before the JVM is considered to be dead. */
if (wrapperData->pingTimeout > 0) {
wrapperUpdateJavaStateTimeout(nowTicks, 5 + wrapperData->pingTimeout);
} else {
wrapperUpdateJavaStateTimeout(nowTicks, -1);
}
break;
default:
/* We got a ping response that we were not expecting. Ignore it. */
break;
}
}
void wrapperPingTimeoutResponded() {
wrapperProcessActionList(wrapperData->pingActionList, TEXT("JVM appears hung: Timed out waiting for signal from JVM."),
WRAPPER_ACTION_SOURCE_CODE_PING_TIMEOUT, TRUE, 1);
}
void wrapperStopRequested(int exitCode) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG,
TEXT("JVM requested a shutdown. (%d)"), exitCode);
}
/* Get things stopping on this end. Ask the JVM to stop again in case the
* user code on the Java side is not written correctly. */
wrapperStopProcess(exitCode, FALSE);
}
void wrapperRestartRequested() {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("JVM requested a restart."));
/* Make a note of the fact that we received this restart packet. */
wrapperData->restartPacketReceived = TRUE;
wrapperRestartProcess();
}
/**
* If the current state of the JVM is STOPPING then this message is used to
* extend the time that the wrapper will wait for a STOPPED message before
* giving up on the JVM and killing it.
*/
void wrapperStopPendingSignaled(int waitHint) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("JVM signaled a stop pending with waitHint of %d millis."), waitHint);
}
if (wrapperData->jState == WRAPPER_JSTATE_STARTED) {
/* Change the state to STOPPING */
wrapperSetJavaState(WRAPPER_JSTATE_STOPPING, 0, -1);
/* Don't need to set the timeout here because it will be set below. */
}
if (wrapperData->jState == WRAPPER_JSTATE_STOPPING) {
if (waitHint < 0) {
waitHint = 0;
}
wrapperUpdateJavaStateTimeout(wrapperGetTicks(), (int)ceil(waitHint / 1000.0));
}
}
/**
* The wrapper received a signal from the JVM that it has completed the stop
* process. If the state of the JVM is STOPPING, then change the state to
* STOPPED. It is possible to get this request after the Wrapper has given up
* waiting for the JVM. In this case, the message is ignored.
*/
void wrapperStoppedSignaled() {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("JVM signaled that it was stopped."));
}
/* If the restart mode is already set and it is WRAPPER_RESTART_REQUESTED_AUTOMATIC but we
* have not yet received a RESTART packet, this means that state engine got confused because
* of an unexpected delay. The fact that the STOPPED packet arived but not the RESTART packet
* means that the application did not intend for the restart to take place.
* Reset the restart and let the Wrapper exit. */
if ((wrapperData->restartRequested == WRAPPER_RESTART_REQUESTED_AUTOMATIC) && (!wrapperData->restartPacketReceived)) {
/* If we get here it is because the Wrapper previously decided to do a restart to recover.
* That means that another message was already shown to the user. We want to show another
* message here so there is a record of why we don't restart. */
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("Received Stopped packet late. Cancel automatic restart."));
wrapperData->restartRequested = WRAPPER_RESTART_REQUESTED_NO;
}
/* Make a note of the fact that we received this stopped packet. */
wrapperData->stoppedPacketReceived = TRUE;
if ((wrapperData->jState == WRAPPER_JSTATE_STARTING) ||
(wrapperData->jState == WRAPPER_JSTATE_STARTED) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPING)) {
/* The Java side of the wrapper signaled that it stopped
* allow 5 + jvmExitTimeout seconds for the JVM to exit. */
if (wrapperData->jvmExitTimeout > 0) {
wrapperSetJavaState(WRAPPER_JSTATE_STOPPED, wrapperGetTicks(), 5 + wrapperData->jvmExitTimeout);
} else {
wrapperSetJavaState(WRAPPER_JSTATE_STOPPED, 0, -1);
}
}
}
/**
* If the current state of the JVM is STARTING then this message is used to
* extend the time that the wrapper will wait for a STARTED message before
* giving up on the JVM and killing it.
*/
void wrapperStartPendingSignaled(int waitHint) {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("JVM signaled a start pending with waitHint of %d millis."), waitHint);
}
/* Only process the start pending signal if the JVM state is starting or
* stopping. Stopping are included because if the user hits CTRL-C while
* the application is starting, then the stop request will not be noticed
* until the application has completed its startup. */
if ((wrapperData->jState == WRAPPER_JSTATE_STARTING) ||
(wrapperData->jState == WRAPPER_JSTATE_STOPPING)) {
if (waitHint < 0) {
waitHint = 0;
}
wrapperUpdateJavaStateTimeout(wrapperGetTicks(), (int)ceil(waitHint / 1000.0));
}
}
/**
* The wrapper received a signal from the JVM that it has completed the startup
* process. If the state of the JVM is STARTING, then change the state to
* STARTED. It is possible to get this request after the Wrapper has given up
* waiting for the JVM. In this case, the message is ignored.
*/
void wrapperStartedSignaled() {
if (wrapperData->isDebugging) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_DEBUG, TEXT("JVM signaled that it was started."));
}
if (wrapperData->jState == WRAPPER_JSTATE_STARTING) {
/* We got the expected started packed. Now start pinging. Allow 5 + <pingTimeout> more seconds before the JVM
* is considered to be dead. */
if (wrapperData->pingTimeout > 0) {
wrapperSetJavaState(WRAPPER_JSTATE_STARTED, wrapperGetTicks(), 5 + wrapperData->pingTimeout);
} else {
wrapperSetJavaState(WRAPPER_JSTATE_STARTED, 0, -1);
}
/* Is the wrapper state STARTING? */
if (wrapperData->wState == WRAPPER_WSTATE_STARTING) {
wrapperSetWrapperState(WRAPPER_WSTATE_STARTED);
if (!wrapperData->isConsole) {
/* Tell the service manager that we started */
wrapperReportStatus(FALSE, WRAPPER_WSTATE_STARTED, 0, 0);
}
}
/* If we are configured to detach and shutdown when the JVM is started then start doing so. */
if (wrapperData->detachStarted) {
log_printf(WRAPPER_SOURCE_WRAPPER, LEVEL_STATUS, TEXT("JVM launched and detached. Wrapper Shutting down..."));
wrapperProtocolClose();
wrapperDetachJava();
wrapperStopProcess(0, FALSE);
}
} else if (wrapperData->jState == WRAPPER_JSTATE_STOP) {
/* This will happen if the Wrapper was asked to stop as the JVM is being launched. */
} else if (wrapperData->jState == WRAPPER_JSTATE_STOPPING) {
/* This will happen if the Wrapper was asked to stop as the JVM is being launched. */
wrapperSetJavaState(WRAPPER_JSTATE_STOP, 0, -1);
}
}
#ifdef CUNIT
static void subTestJavaAdditionalParamSuite(int stripQuote, TCHAR *config, TCHAR **strings, int strings_len, int isJVMParam) {
LoadParameterFileCallbackParam param;
int ret;
int i;
param.stripQuote = stripQuote;
param.strings = NULL;
param.index = 0;
param.isJVMParam = isJVMParam;
ret = loadParameterFileCallback((void *)(¶m), NULL, 0, config, FALSE);
CU_ASSERT_TRUE(ret);
CU_ASSERT(strings_len == param.index);
param.stripQuote = stripQuote;
param.strings = (TCHAR **)malloc(sizeof(TCHAR *) * strings_len);
param.index = 0;
param.isJVMParam = isJVMParam;
CU_ASSERT(param.strings != NULL);
ret = loadParameterFileCallback((void *)(¶m), NULL, 0, config, FALSE);
CU_ASSERT_TRUE(ret);
CU_ASSERT(strings_len == param.index);
for (i = 0; i < strings_len; i++) {
CU_ASSERT(_tcscmp(strings[i], param.strings[i]) == 0);
}
}
#define ARRAY_LENGTH(a) (sizeof(a) / sizeof(a[0]))
void testJavaAdditionalParamSuite(void) {
int stripQuote;
int i = 0;
int isJVM = TRUE;
for (i = 0; i < 2; i++) {
_tprintf(TEXT("%d round\n"), i);
if (i > 0) {
isJVM = FALSE;
}
/* Test set #1 */
{
/* Single parameter in 1 line. */
TCHAR *config = TEXT("-Dsomething=something");
TCHAR *strings[1];
strings[0] = TEXT("-Dsomething=something");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Multiple parameters in 1 line. */
TCHAR *config = TEXT("-Dsomething=something -Dxxx=xxx");
TCHAR *strings[2];
strings[0] = TEXT("-Dsomething=something");
strings[1] = TEXT("-Dxxx=xxx");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Horizontal Tab is not a delimiter. */
TCHAR *config = TEXT("-Dsomething1=something1\t-Dsomething2=something2 -Dxxx=xxx");
TCHAR *strings[2];
strings[0] = TEXT("-Dsomething1=something1\t-Dsomething2=something2");
strings[1] = TEXT("-Dxxx=xxx");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Horizontal Tab is not a delimiter. */
TCHAR *config = TEXT("-Dsomething1=something1\t-Dsomething2=something2 -Dxxx=xxx");
TCHAR *strings[2];
strings[0] = TEXT("-Dsomething1=something1\t-Dsomething2=something2");
strings[1] = TEXT("-Dxxx=xxx");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
if (isJVM == TRUE) {
{
/* A parameter without heading '-' will be skipped. */
TCHAR *config = TEXT("something=something -Dxxx=xxx");
TCHAR *strings[1];
strings[0] = TEXT("-Dxxx=xxx");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
} else {
{
/* A parameter without heading '-' will not be skipped. */
TCHAR *config = TEXT("something=something -Dxxx=xxx");
TCHAR *strings[2];
strings[0] = TEXT("something=something");
strings[1] = TEXT("-Dxxx=xxx");
subTestJavaAdditionalParamSuite(FALSE, config, strings, ARRAY_LENGTH(strings), isJVM);
}
}
/* Test set #2 : without stripping double quotations */
stripQuote = FALSE;
{
/* Quotations #1 */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=\"Hello World.\"");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Quotations #2 */
TCHAR *config = TEXT("\"-DmyApp.x1=Hello World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("\"-DmyApp.x1=Hello World.\"");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Escaped quotation */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello \\\"World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=\"Hello \\\"World.\"");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Escaped backslash */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello World.\\\\\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=\"Hello World.\\\\\"");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
/* Test set #3 : with stripping double quotations */
stripQuote = TRUE;
{
/* Quotations #1 */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=Hello World.");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Quotations #2 */
TCHAR *config = TEXT("\"-DmyApp.x1=Hello World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=Hello World.");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Escaped quotation */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello \\\"World.\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=Hello \"World.");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
{
/* Escaped backslash */
TCHAR *config = TEXT("-DmyApp.x1=\"Hello World.\\\\\" -DmyApp.x2=x2");
TCHAR *strings[2];
strings[0] = TEXT("-DmyApp.x1=Hello World.\\");
strings[1] = TEXT("-DmyApp.x2=x2");
subTestJavaAdditionalParamSuite(stripQuote, config, strings, ARRAY_LENGTH(strings), isJVM);
}
}
}
#endif /* CUNIT */
|