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
|
/**
NSFileManager.m
Copyright (C) 1997-2020 Free Software Foundation, Inc.
Author: Mircea Oancea <mircea@jupiter.elcom.pub.ro>
Author: Ovidiu Predescu <ovidiu@net-community.com>
Date: Feb 1997
Updates and fixes: Richard Frith-Macdonald
Author: Nicola Pero <n.pero@mi.flashnet.it>
Date: Apr 2001
Rewritten NSDirectoryEnumerator
Author: Richard Frith-Macdonald <rfm@gnu.org>
Date: Sep 2002
Rewritten attribute handling code
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSFileManager class reference</title>
$Date$ $Revision$
*/
/* The following define is needed for Solaris get(pw/gr)(nam/uid)_r declartions
which default to pre POSIX declaration. */
#define _POSIX_PTHREAD_SEMANTICS
#import "common.h"
#define EXPOSE_NSFileManager_IVARS 1
#define EXPOSE_NSDirectoryEnumerator_IVARS 1
#import "Foundation/NSArray.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSError.h"
#import "Foundation/NSException.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSProcessInfo.h"
#import "Foundation/NSSet.h"
#import "Foundation/NSURL.h"
#import "Foundation/NSValue.h"
#import "GSPrivate.h"
#import "GNUstepBase/NSString+GNUstepBase.h"
#import "GNUstepBase/NSTask+GNUstepBase.h"
#include <stdio.h>
/* determine directory reading files */
#if defined(HAVE_DIRENT_H)
# include <dirent.h>
#elif defined(HAVE_SYS_DIR_H)
# include <sys/dir.h>
#elif defined(HAVE_SYS_NDIR_H)
# include <sys/ndir.h>
#elif defined(HAVE_NDIR_H)
# include <ndir.h>
#elif defined(_MSC_VER)
// we provide our own version of dirent.h on Windows MSVC
# include <win32/dirent.h>
#endif
#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#if defined(_WIN32)
#include <stdio.h>
#include <tchar.h>
#include <wchar.h>
#include <accctrl.h>
#include <aclapi.h>
#define WIN32ERR ((DWORD)0xFFFFFFFF)
#endif
/* determine filesystem max path length */
#if defined(_POSIX_VERSION) || defined(_WIN32)
# if defined(_WIN32)
# include <sys/utime.h>
# else
# include <utime.h>
# endif
#endif
#ifdef HAVE_SYS_CDEFS_H
# include <sys/cdefs.h>
#endif
#ifdef HAVE_SYS_SYSLIMITS_H
# include <sys/syslimits.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h> /* for MAXPATHLEN */
#endif
#ifndef PATH_MAX
# ifdef _POSIX_VERSION
# define PATH_MAX _POSIX_PATH_MAX
# else
# ifdef MAXPATHLEN
# define PATH_MAX MAXPATHLEN
# else
# define PATH_MAX 1024
# endif
# endif
#endif
/* determine if we have statfs struct and function */
#ifdef HAVE_SYS_VFS_H
# include <sys/vfs.h>
#endif
#ifdef HAVE_SYS_STATVFS_H
# include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_STATFS_H
# include <sys/statfs.h>
#endif
#if defined(HAVE_SYS_FILE_H)
# include <sys/file.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#elif defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h> /* For struct passwd */
#endif
#ifdef HAVE_GRP_H
#include <grp.h> /* For struct group */
#endif
#ifdef HAVE_UTIME_H
# include <utime.h>
#endif
/*
* On systems that have the O_BINARY flag, use it for a binary copy.
*/
#if defined(O_BINARY)
#define GSBINIO O_BINARY
#else
#define GSBINIO 0
#endif
@interface NSDirectoryEnumerator (Local)
- (id) initWithDirectoryPath: (NSString*)path
recurseIntoSubdirectories: (BOOL)recurse
followSymlinks: (BOOL)follow
justContents: (BOOL)justContents
for: (NSFileManager*)mgr;
- (id) initWithDirectoryPath: (NSString*)path
recurseIntoSubdirectories: (BOOL)recurse
followSymlinks: (BOOL)follow
justContents: (BOOL)justContents
skipHidden: (BOOL)skipHidden
errorHandler: (GSDirEnumErrorHandler) handler
for: (NSFileManager*)mgr;
- (void) _setSkipHidden: (BOOL)flag;
- (void) _setErrorHandler: (GSDirEnumErrorHandler) handler;
@end
/*
* Macros to handle unichar filesystem support.
*/
#if defined(_WIN32)
#define _CHMOD(A,B) _wchmod(A,B)
#define _CLOSEDIR(A) _wclosedir(A)
#define _OPENDIR(A) _wopendir(A)
#define _READDIR(A) _wreaddir(A)
#define _RENAME(A,B) (MoveFileExW(A,B,MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)==0)?-1:0
#define _RMDIR(A) _wrmdir(A)
#define _STAT(A,B) _wstat(A,B)
#define _UTIME(A,B) _wutime(A,B)
#define _DIR _WDIR
#define _DIRENT _wdirent
#define _STATB _stat
#define _UTIMB _utimbuf
#define _NUL L'\0'
#else
#define _CHMOD(A,B) chmod(A,B)
#define _CLOSEDIR(A) closedir(A)
#define _OPENDIR(A) opendir(A)
#define _READDIR(A) readdir(A)
#define _RENAME(A,B) rename(A,B)
#define _RMDIR(A) rmdir(A)
#define _STAT(A,B) stat(A,B)
#define _UTIME(A,B) utime(A,B)
#define _DIR DIR
#define _DIRENT dirent
#define _STATB stat
#define _UTIMB utimbuf
#define _NUL '\0'
#endif
#define _CHAR GSNativeChar
#define _CCP const _CHAR*
/*
* GSAttrDictionary is a private NSDictionary subclass used to
* handle file attributes efficiently ... using lazy evaluation
* to ensure that we only do the minimum work necessary at any time.
*/
@interface GSAttrDictionary : NSDictionary
{
@public
struct _STATB statbuf;
_CHAR _path[0];
}
+ (NSDictionary*) attributesAt: (NSString *)path
traverseLink: (BOOL)traverse;
@end
static Class GSAttrDictionaryClass = 0;
/*
* We also need a special enumerator class to enumerate the dictionary.
*/
@interface GSAttrDictionaryEnumerator : NSEnumerator
{
NSDictionary *dictionary;
NSEnumerator *enumerator;
}
+ (NSEnumerator*) enumeratorFor: (NSDictionary*)d;
@end
@interface NSFileManager (PrivateMethods)
/* Copies the contents of source file to destination file. Assumes source
and destination are regular files or symbolic links. */
- (BOOL) _copyFile: (NSString*)source
toFile: (NSString*)destination
handler: (id)handler;
/* Recursively copies the contents of source directory to destination. */
- (BOOL) _copyPath: (NSString*)source
toPath: (NSString*)destination
handler: (id)handler;
/* Recursively links the contents of source directory to destination. */
- (BOOL) _linkPath: (NSString*)source
toPath: (NSString*)destination
handler: handler;
/* encapsulates the will Process check for existence of selector. */
- (void) _sendToHandler: (id) handler
willProcessPath: (NSString*) path;
/* methods to encapsulates setting up and calling the handler
in case of an error */
- (BOOL) _proceedAccordingToHandler: (id) handler
forError: (NSString*) error
inPath: (NSString*) path;
- (BOOL) _proceedAccordingToHandler: (id) handler
forError: (NSString*) error
inPath: (NSString*) path
fromPath: (NSString*) fromPath
toPath: (NSString*) toPath;
/* A convenience method to return an NSError object.
* If the _lastError message is set, this creates an NSError using
* that message in the NSCocoaErrorDomain, otherwise it used the
* most recent system error and the Posix error domain.
* The userInfo is set to contain NSLocalizedDescriptionKey for the
* message text, 'Path' if only the fromPath argument is specified,
* and 'FromPath' and 'ToPath' if both path argument are specified.
*/
- (NSError*) _errorFrom: (NSString*)fromPath to: (NSString*)toPath;
@end /* NSFileManager (PrivateMethods) */
/**
* This is the main class for platform-independent management of the local
* filesystem, which allows you to read and save files, create/list
* directories, and move or delete files and directories. In addition to
* simply listing directories, you may obtain an [NSDirectoryEnumerator]
* instance for recursive directory contents enumeration.
*/
@implementation NSFileManager
// Getting the default manager
static NSFileManager* defaultManager = nil;
static NSStringEncoding defaultEncoding;
+ (NSFileManager*) defaultManager
{
if (defaultManager == nil)
{
NS_DURING
{
[gnustep_global_lock lock];
if (defaultManager == nil)
{
defaultManager = [[self alloc] init];
}
[gnustep_global_lock unlock];
}
NS_HANDLER
{
// unlock then re-raise the exception
[gnustep_global_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
return defaultManager;
}
+ (void) initialize
{
defaultEncoding = [NSString defaultCStringEncoding];
GSAttrDictionaryClass = [GSAttrDictionary class];
}
- (void) dealloc
{
TEST_RELEASE(_lastError);
[super dealloc];
}
- (id<NSFileManagerDelegate>) delegate
{
return _delegate;
}
- (void) setDelegate: (id<NSFileManagerDelegate>)delegate
{
_delegate = delegate;
}
- (BOOL) changeCurrentDirectoryPath: (NSString*)path
{
static Class bundleClass = 0;
const _CHAR *lpath = [self fileSystemRepresentationWithPath: path];
/*
* On some systems the only way NSBundle can determine the path to the
* executable is by searching for it ... so it needs to know what was
* the current directory at launch time ... so we must make sure it is
* initialised before we change the current directory.
*/
if (bundleClass == 0)
{
bundleClass = [NSBundle class];
}
#if defined(_WIN32)
return SetCurrentDirectoryW(lpath) == TRUE ? YES : NO;
#else
return (chdir(lpath) == 0) ? YES : NO;
#endif
}
/**
* Change the attributes of the file at path to those specified.<br />
* Returns YES if all requested changes were made (or if the dictionary
* was nil or empty, so no changes were requested), NO otherwise.<br />
* On failure, some of the requested changes may have taken place.<br />
*/
- (BOOL) changeFileAttributes: (NSDictionary*)attributes atPath: (NSString*)path
{
NSDictionary *old;
const _CHAR *lpath = 0;
NSUInteger num;
NSString *str;
NSDate *date;
BOOL allOk = YES;
if (0 == [attributes count])
{
return YES;
}
old = [self fileAttributesAtPath: path traverseLink: YES];
lpath = [defaultManager fileSystemRepresentationWithPath: path];
#ifndef _WIN32
if (object_getClass(attributes) == GSAttrDictionaryClass)
{
num = ((GSAttrDictionary*)attributes)->statbuf.st_uid;
}
else
{
NSNumber *tmpNum = [attributes fileOwnerAccountID];
num = tmpNum ? [tmpNum unsignedLongValue] : NSNotFound;
}
if (num != NSNotFound && num != [[old fileOwnerAccountID] unsignedLongValue])
{
if (chown(lpath, num, -1) != 0)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileOwnerAccountID to '%"PRIuPTR"' - %@",
num, [NSError _last]];
ASSIGN(_lastError, str);
}
}
else
{
if ((str = [attributes fileOwnerAccountName]) != nil
&& NO == [str isEqual: [old fileOwnerAccountName]])
{
BOOL ok = NO;
#ifdef HAVE_PWD_H
#if defined(HAVE_GETPWNAM_R)
struct passwd pw;
struct passwd *p;
char buf[BUFSIZ*10];
if (getpwnam_r([str cStringUsingEncoding: defaultEncoding],
&pw, buf, sizeof(buf), &p) == 0)
{
ok = (chown(lpath, pw.pw_uid, -1) == 0);
(void)chown(lpath, -1, pw.pw_gid);
}
#else
#if defined(HAVE_GETPWNAM)
struct passwd *pw;
[gnustep_global_lock lock];
pw = getpwnam([str cStringUsingEncoding: defaultEncoding]);
if (pw != 0)
{
ok = (chown(lpath, pw->pw_uid, -1) == 0);
(void)chown(lpath, -1, pw->pw_gid);
}
[gnustep_global_lock unlock];
#endif
#endif
#endif
if (ok == NO)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileOwnerAccountName to '%@' - %@",
str, [NSError _last]];
ASSIGN(_lastError, str);
}
}
}
if (object_getClass(attributes) == GSAttrDictionaryClass)
{
num = ((GSAttrDictionary*)attributes)->statbuf.st_gid;
}
else
{
NSNumber *tmpNum = [attributes fileGroupOwnerAccountID];
num = tmpNum ? [tmpNum unsignedLongValue] : NSNotFound;
}
if (num != NSNotFound
&& num != [[old fileGroupOwnerAccountID] unsignedLongValue])
{
if (chown(lpath, -1, num) != 0)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileGroupOwnerAccountID to '%"PRIuPTR"' - %@",
num, [NSError _last]];
ASSIGN(_lastError, str);
}
}
else if ((str = [attributes fileGroupOwnerAccountName]) != nil
&& NO == [str isEqual: [old fileGroupOwnerAccountName]])
{
BOOL ok = NO;
#ifdef HAVE_GRP_H
#ifdef HAVE_GETGRNAM_R
struct group gp;
struct group *p;
char buf[BUFSIZ*10];
if (getgrnam_r([str cStringUsingEncoding: defaultEncoding], &gp,
buf, sizeof(buf), &p) == 0)
{
if (chown(lpath, -1, gp.gr_gid) == 0)
ok = YES;
}
#else
#ifdef HAVE_GETGRNAM
struct group *gp;
[gnustep_global_lock lock];
gp = getgrnam([str cStringUsingEncoding: defaultEncoding]);
if (gp)
{
if (chown(lpath, -1, gp->gr_gid) == 0)
ok = YES;
}
[gnustep_global_lock unlock];
#endif
#endif
#endif
if (ok == NO)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileGroupOwnerAccountName to '%@' - %@",
str, [NSError _last]];
ASSIGN(_lastError, str);
}
}
#endif /* _WIN32 */
num = [attributes filePosixPermissions];
if (num != NSNotFound && num != [old filePosixPermissions])
{
if (_CHMOD(lpath, num) != 0)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFilePosixPermissions to '%o' - %@",
(unsigned)num, [NSError _last]];
ASSIGN(_lastError, str);
}
}
date = [attributes fileCreationDate];
if (date != nil && NO == [date isEqual: [old fileCreationDate]])
{
BOOL ok = NO;
struct _STATB sb;
const _CHAR *lpath;
lpath = [self fileSystemRepresentationWithPath: path];
if (_STAT(lpath, &sb) != 0)
{
ok = NO;
}
#if defined(_WIN32)
else if (sb.st_mode & _S_IFDIR)
{
ok = YES; // Directories don't have creation times.
}
#endif
else
{
#if defined(_WIN32)
FILETIME ctime;
HANDLE fh;
ULONGLONG nanosecs = ((ULONGLONG)([date timeIntervalSince1970]*10000000)+116444736000000000ULL);
fh = CreateFileW(lpath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL );
if (fh == INVALID_HANDLE_VALUE)
{
ok = NO;
}
else
{
ctime.dwLowDateTime = (DWORD) (nanosecs & 0xFFFFFFFF );
ctime.dwHighDateTime = (DWORD) (nanosecs >> 32 );
ok = SetFileTime(fh, &ctime, NULL, NULL);
CloseHandle(fh);
}
#else
NSTimeInterval ti = [date timeIntervalSince1970];
/* on Unix we try setting the creation date by setting the modification date earlier than the current one */
#if defined (HAVE_UTIMENSAT)
struct timespec ub[2];
ub[0].tv_sec = 0;
ub[0].tv_nsec = UTIME_OMIT; // we don't touch access time
ub[1].tv_sec = (time_t)trunc(ti);
ub[1].tv_nsec = (long)trunc((ti - trunc(ti)) * 1.0e9);
ok = (utimensat(AT_FDCWD, lpath, ub, 0) == 0);
#elif defined(_POSIX_VERSION)
struct _UTIMB ub;
ub.actime = sb.st_atime;
ub.modtime = ti;
ok = (_UTIME(lpath, &ub) == 0);
#else
time_t ub[2];
ub[0] = sb.st_atime;
ub[1] = ti;
ok = (_UTIME(lpath, ub) == 0);
#endif
#endif
}
if (ok == NO)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileCreationDate to '%@' - %@",
date, [NSError _last]];
ASSIGN(_lastError, str);
}
}
date = [attributes fileModificationDate];
if (date != nil && NO == [date isEqual: [old fileModificationDate]])
{
BOOL ok = NO;
struct _STATB sb;
if (_STAT(lpath, &sb) != 0)
{
ok = NO;
}
#if defined(_WIN32)
else if (sb.st_mode & _S_IFDIR)
{
ok = YES; // Directories don't have modification times.
}
#endif
else
{
NSTimeInterval ti = [date timeIntervalSince1970];
#if defined (HAVE_UTIMENSAT)
struct timespec ub[2];
ub[0].tv_sec = 0;
ub[0].tv_nsec = UTIME_OMIT; // we don't touch access time
ub[1].tv_sec = (time_t)trunc(ti);
ub[1].tv_nsec = (long)trunc((ti - trunc(ti)) * 1.0e9);
ok = (utimensat(AT_FDCWD, lpath, ub, 0) == 0);
#elif defined(_WIN32) || defined(_POSIX_VERSION)
struct _UTIMB ub;
ub.actime = sb.st_atime;
ub.modtime = ti;
ok = (_UTIME(lpath, &ub) == 0);
#else
time_t ub[2];
ub[0] = sb.st_atime;
ub[1] = ti;
ok = (_UTIME(lpath, ub) == 0);
#endif
}
if (ok == NO)
{
allOk = NO;
str = [NSString stringWithFormat:
@"Unable to change NSFileModificationDate to '%@' - %@",
date, [NSError _last]];
ASSIGN(_lastError, str);
}
}
return allOk;
}
/**
* Returns an array of path components suitably modified for display
* to the end user. This modification may render the returned strings
* unusable for path manipulation, so you should work with two arrays ...
* one returned by this method (for display to the user), and a
* parallel one returned by [NSString-pathComponents] (for path
* manipulation).
*/
- (NSArray*) componentsToDisplayForPath: (NSString*)path
{
return [path pathComponents];
}
/**
* Reads the file at path an returns its contents as an NSData object.<br />
* If an error occurs or if path specifies a directory etc then nil is
* returned.
*/
- (NSData*) contentsAtPath: (NSString*)path
{
return [NSData dataWithContentsOfFile: path];
}
/**
* Returns YES if the contents of the file or directory at path1 are the same
* as those at path2.<br />
* If path1 and path2 are files, this is a simple comparison. If they are
* directories, the contents of the files in those subdirectories are
* compared recursively.<br />
* Symbolic links are not followed.<br />
* A comparison checks first file identity, then size, then content.
*/
- (BOOL) contentsEqualAtPath: (NSString*)path1 andPath: (NSString*)path2
{
NSDictionary *d1;
NSDictionary *d2;
NSString *t;
if ([path1 isEqual: path2])
return YES;
d1 = [self fileAttributesAtPath: path1 traverseLink: NO];
d2 = [self fileAttributesAtPath: path2 traverseLink: NO];
t = [d1 fileType];
if ([t isEqual: [d2 fileType]] == NO)
{
return NO;
}
if ([t isEqual: NSFileTypeRegular])
{
if ([d1 fileSize] == [d2 fileSize])
{
NSData *c1 = [NSData dataWithContentsOfFile: path1];
NSData *c2 = [NSData dataWithContentsOfFile: path2];
if ([c1 isEqual: c2])
{
return YES;
}
}
return NO;
}
else if ([t isEqual: NSFileTypeDirectory])
{
NSArray *a1 = [self directoryContentsAtPath: path1];
NSArray *a2 = [self directoryContentsAtPath: path2];
unsigned index, count = [a1 count];
BOOL ok = YES;
if ([a1 isEqual: a2] == NO)
{
return NO;
}
for (index = 0; ok == YES && index < count; index++)
{
NSString *n = [a1 objectAtIndex: index];
NSString *p1;
NSString *p2;
ENTER_POOL
p1 = [path1 stringByAppendingPathComponent: n];
p2 = [path2 stringByAppendingPathComponent: n];
d1 = [self fileAttributesAtPath: p1 traverseLink: NO];
d2 = [self fileAttributesAtPath: p2 traverseLink: NO];
t = [d1 fileType];
if ([t isEqual: [d2 fileType]] == NO)
{
ok = NO;
}
else if ([t isEqual: NSFileTypeDirectory]
|| [t isEqual: NSFileTypeRegular])
{
ok = [self contentsEqualAtPath: p1 andPath: p2];
}
LEAVE_POOL
}
return ok;
}
else
{
return YES;
}
}
- (NSArray*) contentsOfDirectoryAtURL: (NSURL*)url
includingPropertiesForKeys: (NSArray*)keys
options: (NSDirectoryEnumerationOptions)mask
error: (NSError **)error
{
NSArray *result;
NSDirectoryEnumerator *direnum;
NSString *path;
DESTROY(_lastError);
if (![[url scheme] isEqualToString: @"file"])
{
return nil;
}
path = [url path];
direnum = [[NSDirectoryEnumerator alloc]
initWithDirectoryPath: path
recurseIntoSubdirectories: NO
followSymlinks: NO
justContents: NO
for: self];
/* we make an array of NSURLs */
result = nil;
if (nil != direnum)
{
IMP nxtImp;
NSMutableArray *urlArray;
NSString *tempPath;
nxtImp = [direnum methodForSelector: @selector(nextObject)];
urlArray = [NSMutableArray arrayWithCapacity: 128];
while ((tempPath = (*nxtImp)(direnum, @selector(nextObject))) != nil)
{
NSURL *tempURL;
NSString *lastComponent;
tempURL = [NSURL fileURLWithPath: tempPath];
lastComponent = [tempPath lastPathComponent];
/* we purge files beginning with . */
if (!((mask & NSDirectoryEnumerationSkipsHiddenFiles)
&& [lastComponent hasPrefix: @"."]))
{
[urlArray addObject: tempURL];
}
}
RELEASE(direnum);
if ([urlArray count] > 0)
{
result = [NSArray arrayWithArray: urlArray];
}
}
if (error != NULL)
{
if (nil == result)
{
*error = [self _errorFrom: path to: nil];
}
}
return result;
}
- (NSURL *)URLForDirectory: (NSSearchPathDirectory)directory
inDomain: (NSSearchPathDomainMask)domain
appropriateForURL: (NSURL *)url
create: (BOOL)shouldCreate
error: (NSError **)error
{
NSURL *result = nil;
NSArray *urlArray = NSSearchPathForDirectoriesInDomains(directory, domain, YES);
// Find out the URL exists...
if ([urlArray count] > 0)
{
result = [NSURL URLWithString: [urlArray objectAtIndex: 0]];
}
if (directory == NSItemReplacementDirectory)
{
result = [NSURL URLWithString: NSTemporaryDirectory()];
}
if (![self fileExistsAtPath: [result absoluteString]])
{
// If we should created it, create it...
if (shouldCreate)
{
[self createDirectoryAtPath: [result absoluteString]
withIntermediateDirectories: YES
attributes: nil
error: error];
}
}
return result;
}
- (NSDirectoryEnumerator *)enumeratorAtURL: (NSURL *)url
includingPropertiesForKeys: (NSArray *)keys
options: (NSDirectoryEnumerationOptions)mask
errorHandler: (GSDirEnumErrorHandler)handler
{
NSDirectoryEnumerator *direnum;
NSString *path;
DESTROY(_lastError);
if (![[url scheme] isEqualToString: @"file"])
{
return nil;
}
path = [url path];
direnum = [[NSDirectoryEnumerator alloc]
initWithDirectoryPath: path
recurseIntoSubdirectories: !(mask & NSDirectoryEnumerationSkipsSubdirectoryDescendants)
followSymlinks: NO
justContents: NO
skipHidden: (mask & NSDirectoryEnumerationSkipsHiddenFiles)
errorHandler: handler
for: self];
return direnum;
}
- (NSArray*) contentsOfDirectoryAtPath: (NSString*)path error: (NSError**)error
{
NSArray *result;
DESTROY(_lastError);
result = [self directoryContentsAtPath: path];
if (error != NULL)
{
if (nil == result)
{
*error = [self _errorFrom: path to: nil];
}
}
return result;
}
/**
* Creates a new directory (and all intermediate directories if flag is YES).
* Creates only the last directory in the path if flag is NO.<br />
* The directory is created with the attributes specified, and any problem
* is returned in error.<br />
* Returns YES if the directory is created (or flag is YES and the directory
* already exists), NO on failure.
*/
- (BOOL) createDirectoryAtPath: (NSString *)path
withIntermediateDirectories: (BOOL)flag
attributes: (NSDictionary *)attributes
error: (NSError **)error
{
BOOL result = NO;
DESTROY(_lastError);
if (YES == flag)
{
NSEnumerator *paths = [[path pathComponents] objectEnumerator];
NSString *path = nil;
NSString *dir = [NSString string];
result = YES;
while (YES == result && (path = (NSString *)[paths nextObject]) != nil)
{
dir = [dir stringByAppendingPathComponent: path];
// create directory only if it doesn't exist
if (NO == [self fileExistsAtPath: dir])
{
result = [self createDirectoryAtPath: dir
attributes: attributes];
}
}
}
else
{
BOOL isDir;
if ([self fileExistsAtPath: [path stringByDeletingLastPathComponent]
isDirectory: &isDir] && isDir)
{
result = [self createDirectoryAtPath: path
attributes: attributes];
}
else
{
result = NO;
ASSIGN(_lastError, @"Could not create directory - intermediate path did not exist or was not a directory");
}
}
if (error != NULL)
{
if (NO == result)
{
*error = [self _errorFrom: path to: nil];
}
}
return result;
}
/**
* Creates a new directory and all intermediate directories in the file URL
* if flag is YES.<br />
* Creates only the last directory in the URL if flag is NO.<br />
* The directory is created with the attributes specified and any problem
* is returned in error.<br />
* Returns YES if the directory is created (or flag is YES and the directory
* already exists), NO on failure.
*/
- (BOOL) createDirectoryAtURL: (NSURL *)url
withIntermediateDirectories: (BOOL)flag
attributes: (NSDictionary *)attributes
error: (NSError **) error
{
return [self createDirectoryAtPath: [url path]
withIntermediateDirectories: flag
attributes: attributes
error: error];
}
/**
* Creates a new directory, and sets its attributes as specified.<br />
* Fails if directories in the path are missing.<br />
* Returns YES if the directory was actually created, NO otherwise.
*/
- (BOOL) createDirectoryAtPath: (NSString*)path
attributes: (NSDictionary*)attributes
{
BOOL isDir;
/* This is consistent with MacOSX - just return NO for an invalid path. */
if ([path length] == 0)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
if (YES == [self fileExistsAtPath: path isDirectory: &isDir])
{
NSString *e;
if (NO == isDir)
{
e = [NSString stringWithFormat:
@"path %@ exists, but is not a directory", path];
}
else
{
e = [NSString stringWithFormat:
@"path %@ exists ... cannot create", path];
}
ASSIGN(_lastError, e);
return NO;
}
else
{
const _CHAR *lpath;
lpath = [self fileSystemRepresentationWithPath: path];
#if defined(_WIN32)
isDir = (CreateDirectoryW(lpath, 0) != FALSE) ? YES : NO;
#else
isDir = (mkdir(lpath, 0777) == 0) ? YES : NO;
if (YES == isDir)
{
/*
* If there is no file owner specified, and we are running
* setuid to root, then we assume we need to change ownership
* to the correct user.
*/
if (attributes == nil || ([attributes fileOwnerAccountID] == nil
&& [attributes fileOwnerAccountName] == nil))
{
if (geteuid() == 0
&& [@"root" isEqualToString: NSUserName()] == NO)
{
NSMutableDictionary *m;
m = [[attributes mutableCopy] autorelease];
if (nil == m)
{
m = [NSMutableDictionary dictionaryWithCapacity: 1];
}
[m setObject: NSUserName()
forKey: NSFileOwnerAccountName];
attributes = m;
}
}
}
#endif
if (NO == isDir)
{
NSString *e;
e = [NSString stringWithFormat:
@"Could not create '%@' - '%@'",
path, [NSError _last]];
ASSIGN(_lastError, e);
return NO;
}
}
return [self changeFileAttributes: attributes atPath: path];
}
/**
* Creates a new file, and sets its attributes as specified.<br />
* Initialises the file content with the specified data.<br />
* Returns YES on success, NO on failure.
*/
- (BOOL) createFileAtPath: (NSString*)path
contents: (NSData*)contents
attributes: (NSDictionary*)attributes
{
#if defined(_WIN32)
const _CHAR *lpath = [self fileSystemRepresentationWithPath: path];
HANDLE fh;
DWORD written = 0;
DWORD len = [contents length];
#else
const _CHAR *lpath;
int fd;
int len;
int written;
#endif
/* This is consistent with MacOSX - just return NO for an invalid path. */
if ([path length] == 0)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
fh = CreateFileW(lpath, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, 0);
if (fh == INVALID_HANDLE_VALUE)
{
return NO;
}
else
{
if (len > 0)
{
WriteFile(fh, [contents bytes], len, &written, 0);
}
CloseHandle(fh);
if (attributes != nil
&& [self changeFileAttributes: attributes atPath: path] == NO)
{
return NO;
}
return YES;
}
#else
lpath = [self fileSystemRepresentationWithPath: path];
fd = open(lpath, GSBINIO|O_WRONLY|O_TRUNC|O_CREAT, 0644);
if (fd < 0)
{
return NO;
}
if (attributes != nil
&& [self changeFileAttributes: attributes atPath: path] == NO)
{
close (fd);
return NO;
}
/*
* If there is no file owner specified, and we are running setuid to
* root, then we assume we need to change ownership to correct user.
*/
if (attributes == nil || ([attributes fileOwnerAccountID] == nil
&& [attributes fileOwnerAccountName] == nil))
{
if (geteuid() == 0 && [@"root" isEqualToString: NSUserName()] == NO)
{
attributes = [NSDictionary dictionaryWithObjectsAndKeys:
NSFileOwnerAccountName, NSUserName(), nil];
if (![self changeFileAttributes: attributes atPath: path])
{
NSDebugLog(@"Failed to change ownership of '%@' to '%@'",
path, NSUserName());
}
}
}
len = [contents length];
if (len > 0)
{
written = write(fd, [contents bytes], len);
}
else
{
written = 0;
}
close (fd);
#endif
return written == len;
}
/**
* Returns the current working directory used by all instance of the file
* manager in the current task.
*/
- (NSString*) currentDirectoryPath
{
NSString *currentDir = nil;
#if defined(_WIN32)
int len = GetCurrentDirectoryW(0, 0);
if (len > 0)
{
_CHAR *lpath = (_CHAR*)calloc(len+10,sizeof(_CHAR));
if (lpath != 0)
{
if (GetCurrentDirectoryW(len, lpath)>0)
{
NSString *path;
// Windows may count the trailing nul ... we don't want to.
if (len > 0 && lpath[len] == 0) len--;
path = [[NSString alloc] initWithCharacters: lpath length: len];
// Standardise to get rid of backslashes
currentDir = [path stringByStandardizingPath];
RELEASE(path);
}
free(lpath);
}
}
#else
_CHAR path[PATH_MAX];
#ifdef HAVE_GETCWD
if (getcwd(path, PATH_MAX-1) == 0)
return nil;
#else
if (getwd(path) == 0)
return nil;
#endif /* HAVE_GETCWD */
currentDir = [self stringWithFileSystemRepresentation: path
length: strlen(path)];
#endif /* !_WIN32 */
return currentDir;
}
/**
* Copies the file or directory at source to destination, using a
* handler object which should respond to
* [NSObject(NSFileManagerHandler)-fileManager:willProcessPath:] and
* [NSObject(NSFileManagerHandler)-fileManager:shouldProceedAfterError:]
* messages.<br />
* Will not copy to a destination which already exists.
*/
- (BOOL) copyPath: (NSString*)source
toPath: (NSString*)destination
handler: (id)handler
{
NSDictionary *attrs;
NSString *fileType;
if ([self fileExistsAtPath: destination] == YES)
{
return NO;
}
attrs = [self fileAttributesAtPath: source traverseLink: NO];
if (attrs == nil)
{
return NO;
}
fileType = [attrs fileType];
/* Don't attempt to retain ownership of copy ... we want the copy
* to be owned by the current user.
* However, the new copy should have the creation/modification date
* of the original (unlike Posix semantics).
*/
attrs = AUTORELEASE([attrs mutableCopy]);
[(NSMutableDictionary*)attrs removeObjectForKey: NSFileOwnerAccountID];
[(NSMutableDictionary*)attrs removeObjectForKey: NSFileGroupOwnerAccountID];
[(NSMutableDictionary*)attrs removeObjectForKey: NSFileGroupOwnerAccountName];
[(NSMutableDictionary*)attrs setObject: NSUserName()
forKey: NSFileOwnerAccountName];
if ([fileType isEqualToString: NSFileTypeDirectory] == YES)
{
/* If destination directory is a descendant of source directory copying
* isn't possible.
*/
if ([[destination stringByAppendingString: @"/"]
hasPrefix: [source stringByAppendingString: @"/"]])
{
ASSIGN(_lastError,
@"Could not copy - destination is a descendant of source");
return NO;
}
[self _sendToHandler: handler willProcessPath: destination];
if ([self createDirectoryAtPath: destination attributes: attrs] == NO)
{
return [self _proceedAccordingToHandler: handler
forError: _lastError
inPath: destination
fromPath: source
toPath: destination];
}
if ([self _copyPath: source toPath: destination handler: handler] == NO)
{
return NO;
}
}
else if ([fileType isEqualToString: NSFileTypeSymbolicLink] == YES)
{
NSString *path;
BOOL result;
[self _sendToHandler: handler willProcessPath: source];
path = [self pathContentOfSymbolicLinkAtPath: source];
result = [self createSymbolicLinkAtPath: destination pathContent: path];
if (result == NO)
{
result = [self _proceedAccordingToHandler: handler
forError: @"cannot link to file"
inPath: source
fromPath: source
toPath: destination];
if (result == NO)
{
return NO;
}
}
}
else
{
[self _sendToHandler: handler willProcessPath: source];
if ([self _copyFile: source toFile: destination handler: handler] == NO)
{
return NO;
}
}
[self changeFileAttributes: attrs atPath: destination];
return YES;
}
- (BOOL) copyItemAtPath: (NSString*)src
toPath: (NSString*)dst
error: (NSError**)error
{
BOOL result;
DESTROY(_lastError);
result = [self copyPath: src toPath: dst handler: nil];
if (error != NULL)
{
if (NO == result)
{
*error = [self _errorFrom: src to: dst];
}
}
return result;
}
- (BOOL) copyItemAtURL: (NSURL*)src
toURL: (NSURL*)dst
error: (NSError**)error
{
return [self copyItemAtPath: [src path] toPath: [dst path] error: error];
}
/**
* Moves the file or directory at source to destination, using a
* handler object which should respond to
* [NSObject(NSFileManagerHandler)-fileManager:willProcessPath:] and
* [NSObject(NSFileManagerHandler)-fileManager:shouldProceedAfterError:]
* messages.
* Will not move to a destination which already exists.<br />
*/
- (BOOL) movePath: (NSString*)source
toPath: (NSString*)destination
handler: (id)handler
{
BOOL sourceIsDir;
BOOL fileExists;
NSString *destinationParent;
unsigned int sourceDevice;
unsigned int destinationDevice;
const _CHAR *sourcePath;
const _CHAR *destPath;
sourcePath = [self fileSystemRepresentationWithPath: source];
destPath = [self fileSystemRepresentationWithPath: destination];
if ([self fileExistsAtPath: destination] == YES)
{
return NO;
}
fileExists = [self fileExistsAtPath: source isDirectory: &sourceIsDir];
if (!fileExists)
{
return NO;
}
/* Check to see if the source and destination's parent are on the same
physical device so we can perform a rename syscall directly. */
sourceDevice = [[self fileSystemAttributesAtPath: source] fileSystemNumber];
destinationParent = [destination stringByDeletingLastPathComponent];
if ([destinationParent isEqual: @""])
destinationParent = @".";
destinationDevice
= [[self fileSystemAttributesAtPath: destinationParent] fileSystemNumber];
if (sourceDevice != destinationDevice)
{
/* If destination directory is a descendant of source directory moving
isn't possible. */
if (sourceIsDir && [[destination stringByAppendingString: @"/"]
hasPrefix: [source stringByAppendingString: @"/"]])
{
ASSIGN(_lastError, @"Could not move - destination is a descendant of source");
return NO;
}
if ([self copyPath: source toPath: destination handler: handler])
{
NSDictionary *attributes;
attributes = [self fileAttributesAtPath: source
traverseLink: NO];
[self changeFileAttributes: attributes atPath: destination];
return [self removeFileAtPath: source handler: handler];
}
else
{
return NO;
}
}
else
{
/* source and destination are on the same device so we can simply
invoke rename on source. */
[self _sendToHandler: handler willProcessPath: source];
if (_RENAME (sourcePath, destPath) == -1)
{
return [self _proceedAccordingToHandler: handler
forError: @"cannot move file"
inPath: source
fromPath: source
toPath: destination];
}
return YES;
}
return NO;
}
- (BOOL) moveItemAtPath: (NSString*)src
toPath: (NSString*)dst
error: (NSError**)error
{
BOOL result;
DESTROY(_lastError);
result = [self movePath: src toPath: dst handler: nil];
if (error != NULL)
{
if (NO == result)
{
*error = [self _errorFrom: src to: dst];
}
}
return result;
}
- (BOOL) moveItemAtURL: (NSURL*)src
toURL: (NSURL*)dst
error: (NSError**)error
{
return [self moveItemAtPath: [src path] toPath: [dst path] error: error];
}
/**
* <p>Links the file or directory at source to destination, using a
* handler object which should respond to
* [NSObject(NSFileManagerHandler)-fileManager:willProcessPath:] and
* [NSObject(NSFileManagerHandler)-fileManager:shouldProceedAfterError:]
* messages.
* </p>
* <p>If the destination is a directory, the source path is linked
* into that directory, otherwise the destination must not exist,
* but its parent directory must exist and the source will be linked
* into the parent as the name specified by the destination.
* </p>
* <p>If the source is a symbolic link, it is copied to the destination.<br />
* If the source is a directory, it is copied to the destination and its
* contents are linked into the new directory.<br />
* Otherwise, a hard link is made from the destination to the source.
* </p>
*/
- (BOOL) linkPath: (NSString*)source
toPath: (NSString*)destination
handler: (id)handler
{
#ifdef HAVE_LINK
NSDictionary *attrs;
NSString *fileType;
BOOL isDir;
if ([self fileExistsAtPath: destination isDirectory: &isDir] == YES
&& isDir == YES)
{
destination = [destination stringByAppendingPathComponent:
[source lastPathComponent]];
}
attrs = [self fileAttributesAtPath: source traverseLink: NO];
if (attrs == nil)
{
return NO;
}
[self _sendToHandler: handler willProcessPath: destination];
fileType = [attrs fileType];
if ([fileType isEqualToString: NSFileTypeDirectory] == YES)
{
/* If destination directory is a descendant of source directory linking
isn't possible because of recursion. */
if ([[destination stringByAppendingString: @"/"]
hasPrefix: [source stringByAppendingString: @"/"]])
{
ASSIGN(_lastError, @"Could not link - destination is a descendant of source");
return NO;
}
if ([self createDirectoryAtPath: destination attributes: attrs] == NO)
{
return [self _proceedAccordingToHandler: handler
forError: _lastError
inPath: destination
fromPath: source
toPath: destination];
}
if ([self _linkPath: source toPath: destination handler: handler] == NO)
{
return NO;
}
}
else if ([fileType isEqual: NSFileTypeSymbolicLink])
{
NSString *path;
path = [self pathContentOfSymbolicLinkAtPath: source];
if ([self createSymbolicLinkAtPath: destination
pathContent: path] == NO)
{
if ([self _proceedAccordingToHandler: handler
forError: @"cannot create symbolic link"
inPath: source
fromPath: source
toPath: destination] == NO)
{
return NO;
}
}
}
else
{
if (link([self fileSystemRepresentationWithPath: source],
[self fileSystemRepresentationWithPath: destination]) < 0)
{
if ([self _proceedAccordingToHandler: handler
forError: @"cannot create hard link"
inPath: source
fromPath: source
toPath: destination] == NO)
{
return NO;
}
}
}
[self changeFileAttributes: attrs atPath: destination];
return YES;
#else
ASSIGN(_lastError, @"Links not supported on this platform");
return NO;
#endif
}
- (BOOL) removeFileAtPath: (NSString*)path
handler: handler
{
BOOL is_dir;
const _CHAR *lpath;
if ([path isEqualToString: @"."] || [path isEqualToString: @".."])
{
[NSException raise: NSInvalidArgumentException
format: @"Attempt to remove illegal path"];
}
[self _sendToHandler: handler willProcessPath: path];
lpath = [self fileSystemRepresentationWithPath: path];
if (lpath == 0 || *lpath == 0)
{
ASSIGN(_lastError, @"Could not remove - no path");
return NO;
}
else
{
#if defined(_WIN32)
DWORD res;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
if (res & FILE_ATTRIBUTE_DIRECTORY)
{
is_dir = YES;
}
else
{
is_dir = NO;
}
#else
struct _STATB statbuf;
if (lstat(lpath, &statbuf) != 0)
{
return NO;
}
is_dir = ((statbuf.st_mode & S_IFMT) == S_IFDIR);
#endif /* _WIN32 */
}
if (!is_dir)
{
#if defined(_WIN32)
if (DeleteFileW(lpath) == FALSE)
#else
if (unlink(lpath) < 0)
#endif
{
NSString *message = [[NSError _last] localizedDescription];
return [self _proceedAccordingToHandler: handler
forError: message
inPath: path];
}
else
{
return YES;
}
}
else
{
NSArray *contents = [self directoryContentsAtPath: path];
unsigned count = [contents count];
unsigned i;
for (i = 0; i < count; i++)
{
NSString *item;
NSString *next;
BOOL result;
ENTER_POOL
item = [contents objectAtIndex: i];
next = [path stringByAppendingPathComponent: item];
result = [self removeFileAtPath: next handler: handler];
LEAVE_POOL
if (result == NO)
{
return NO;
}
}
if (_RMDIR([self fileSystemRepresentationWithPath: path]) < 0)
{
NSString *message = [[NSError _last] localizedDescription];
return [self _proceedAccordingToHandler: handler
forError: message
inPath: path];
}
else
{
return YES;
}
}
}
- (BOOL) removeItemAtPath: (NSString*)path
error: (NSError**)error
{
BOOL result;
DESTROY(_lastError);
result = [self removeFileAtPath: path handler: nil];
if (error != NULL)
{
if (NO == result)
{
*error = [self _errorFrom: path to: nil];
}
}
return result;
}
- (BOOL) removeItemAtURL: (NSURL*)url
error: (NSError**)error
{
return [self removeItemAtPath: [url path] error: error];
}
- (BOOL) createSymbolicLinkAtPath: (NSString*)path
withDestinationPath: (NSString*)destPath
error: (NSError**)error
{
BOOL result;
DESTROY(_lastError);
result = [self createSymbolicLinkAtPath: path pathContent: destPath];
if (error != NULL)
{
if (NO == result)
{
*error = [self _errorFrom: path to: destPath];
}
}
return result;
}
- (BOOL) fileExistsAtPath: (NSString*)path
{
return [self fileExistsAtPath: path isDirectory: 0];
}
- (BOOL) fileExistsAtPath: (NSString*)path isDirectory: (BOOL*)isDirectory
{
const _CHAR *lpath = [self fileSystemRepresentationWithPath: path];
if (isDirectory != 0)
{
*isDirectory = NO;
}
if (lpath == 0 || *lpath == _NUL)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
{
DWORD res;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
if (isDirectory != 0)
{
if (res & FILE_ATTRIBUTE_DIRECTORY)
{
*isDirectory = YES;
}
}
return YES;
}
#else
{
struct _STATB statbuf;
if (_STAT(lpath, &statbuf) != 0)
{
#ifdef __ANDROID__
/* Android: try using asset manager if path is in
* main bundle resources
*/
AAsset *asset = [NSBundle assetForPath: path];
if (asset)
{
AAsset_close(asset);
return YES;
}
AAssetDir *assetDir = [NSBundle assetDirForPath: path];
if (assetDir)
{
AAssetDir_close(assetDir);
if (isDirectory)
{
*isDirectory = YES;
}
return YES;
}
#endif
return NO;
}
if (isDirectory)
{
if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
{
*isDirectory = YES;
}
}
return YES;
}
#endif /* _WIN32 */
}
/**
* Returns YES if a file (or directory etc) exists at the specified path
* and is readable.
*/
- (BOOL) isReadableFileAtPath: (NSString*)path
{
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
if (lpath == 0 || *lpath == _NUL)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
{
DWORD res;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
return YES;
}
#else
{
if (access(lpath, R_OK) == 0)
{
return YES;
}
#ifdef __ANDROID__
/* Android: try using asset manager if path is in
* main bundle resources
*/
AAsset *asset = [NSBundle assetForPath: path];
if (asset)
{
AAsset_close(asset);
return YES;
}
AAssetDir *assetDir = [NSBundle assetDirForPath: path];
if (assetDir)
{
AAssetDir_close(assetDir);
return YES;
}
#endif
return NO;
}
#endif
}
/**
* Returns YES if a file (or directory etc) exists at the specified path
* and is writable.
*/
- (BOOL) isWritableFileAtPath: (NSString*)path
{
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
if (lpath == 0 || *lpath == _NUL)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
{
DWORD res;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
if (res & FILE_ATTRIBUTE_READONLY)
{
return NO;
}
return YES;
}
#else
{
if (access(lpath, W_OK) == 0)
{
return YES;
}
return NO;
}
#endif
}
/**
* Returns YES if a file (or directory etc) exists at the specified path
* and is executable (if a directory is executable, you can access its
* contents).
*/
- (BOOL) isExecutableFileAtPath: (NSString*)path
{
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
if (lpath == 0 || *lpath == _NUL)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
{
DWORD res;
NSString *ext;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
ext = [[path pathExtension] uppercaseString];
if ([ext length] > 0)
{
static NSSet *executable = nil;
if (nil == executable)
{
executable = [[NSTask executableExtensions] copy];
}
if (nil != [executable member: ext])
{
return YES;
}
}
/* FIXME: On unix, directory accessible == executable, so we simulate that
here for Windows. Is there a better check for directory access? */
if (res & FILE_ATTRIBUTE_DIRECTORY)
{
return YES;
}
return NO;
}
#else
{
if (access(lpath, X_OK) == 0)
{
return YES;
}
return NO;
}
#endif
}
/**
* Returns YES if a file (or directory etc) exists at the specified path
* and is deletable.
*/
- (BOOL) isDeletableFileAtPath: (NSString*)path
{
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
if (lpath == 0 || *lpath == _NUL)
{
ASSIGN(_lastError, @"no path given");
return NO;
}
#if defined(_WIN32)
// TODO - handle directories
{
DWORD res;
res = GetFileAttributesW(lpath);
if (res == WIN32ERR)
{
return NO;
}
return (res & FILE_ATTRIBUTE_READONLY) ? NO : YES;
}
#else
{
// TODO - handle directories
path = [path stringByDeletingLastPathComponent];
if ([path length] == 0)
{
path = @".";
}
lpath = [self fileSystemRepresentationWithPath: path];
if (access(lpath, X_OK | W_OK) == 0)
{
return YES;
}
return NO;
}
#endif
}
/**
* If a file (or directory etc) exists at the specified path, and can be
* queried for its attributes, this method returns a dictionary containing
* the various attributes of that file. Otherwise nil is returned.<br />
* If the flag is NO and the file is a symbolic link, the attributes of
* the link itself (rather than the file it points to) are returned.<br />
* <p>
* The dictionary keys for attributes are -
* </p>
* <deflist>
* <term><code>NSFileAppendOnly</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileCreationDate</code></term>
* <desc>NSDate when the file was created (if supported)</desc>
* <term><code>NSFileDeviceIdentifier</code></term>
* <desc>NSNumber (identifies the device on which the file is stored)</desc>
* <term><code>NSFileExtensionHidden</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileGroupOwnerAccountName</code></term>
* <desc>NSString name of the file group</desc>
* <term><code>NSFileGroupOwnerAccountID</code></term>
* <desc>NSNumber ID of the file group</desc>
* <term><code>NSFileHFSCreatorCode</code></term>
* <desc>NSNumber not used</desc>
* <term><code>NSFileHFSTypeCode</code></term>
* <desc>NSNumber not used</desc>
* <term><code>NSFileImmutable</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileModificationDate</code></term>
* <desc>NSDate when the file was last modified</desc>
* <term><code>NSFileOwnerAccountName</code></term>
* <desc>NSString name of the file owner</desc>
* <term><code>NSFileOwnerAccountID</code></term>
* <desc>NSNumber ID of the file owner</desc>
* <term><code>NSFilePosixPermissions</code></term>
* <desc>NSNumber posix access permissions mask</desc>
* <term><code>NSFileReferenceCount</code></term>
* <desc>NSNumber number of links to this file</desc>
* <term><code>NSFileSize</code></term>
* <desc>NSNumber size of the file in bytes</desc>
* <term><code>NSFileSystemFileNumber</code></term>
* <desc>NSNumber the identifier for the file on the filesystem</desc>
* <term><code>NSFileSystemNumber</code></term>
* <desc>NSNumber the filesystem on which the file is stored</desc>
* <term><code>NSFileType</code></term>
* <desc>NSString the type of file</desc>
* </deflist>
* <p>
* The [NSDictionary] class also has a set of convenience accessor methods
* which enable you to get at file attribute information more efficiently
* than using the keys above to extract it. You should generally
* use the accessor methods where they are available.
* </p>
* <list>
* <item>[NSDictionary(NSFileAttributes)-fileCreationDate]</item>
* <item>[NSDictionary(NSFileAttributes)-fileExtensionHidden]</item>
* <item>[NSDictionary(NSFileAttributes)-fileHFSCreatorCode]</item>
* <item>[NSDictionary(NSFileAttributes)-fileHFSTypeCode]</item>
* <item>[NSDictionary(NSFileAttributes)-fileIsAppendOnly]</item>
* <item>[NSDictionary(NSFileAttributes)-fileIsImmutable]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSize]</item>
* <item>[NSDictionary(NSFileAttributes)-fileType]</item>
* <item>[NSDictionary(NSFileAttributes)-fileOwnerAccountName]</item>
* <item>[NSDictionary(NSFileAttributes)-fileOwnerAccountID]</item>
* <item>[NSDictionary(NSFileAttributes)-fileGroupOwnerAccountName]</item>
* <item>[NSDictionary(NSFileAttributes)-fileGroupOwnerAccountID]</item>
* <item>[NSDictionary(NSFileAttributes)-fileModificationDate]</item>
* <item>[NSDictionary(NSFileAttributes)-filePosixPermissions]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSystemNumber]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSystemFileNumber]</item>
* </list>
*/
- (NSDictionary*) fileAttributesAtPath: (NSString*)path traverseLink: (BOOL)flag
{
NSDictionary *d;
d = [GSAttrDictionaryClass attributesAt: path traverseLink: flag];
return d;
}
/**
* If a file (or directory etc) exists at the specified path, and can be
* queried for its attributes, this method returns a dictionary containing
* the various attributes of that file. Otherwise nil is returned.<br />
* If an error occurs, error describes the problem.
* Pass NULL if you do not want error information.
* <p>
* The dictionary keys for attributes are -
* </p>
* <deflist>
* <term><code>NSFileAppendOnly</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileCreationDate</code></term>
* <desc>NSDate when the file was created (if supported)</desc>
* <term><code>NSFileDeviceIdentifier</code></term>
* <desc>NSNumber (identifies the device on which the file is stored)</desc>
* <term><code>NSFileExtensionHidden</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileGroupOwnerAccountName</code></term>
* <desc>NSString name of the file group</desc>
* <term><code>NSFileGroupOwnerAccountID</code></term>
* <desc>NSNumber ID of the file group</desc>
* <term><code>NSFileHFSCreatorCode</code></term>
* <desc>NSNumber not used</desc>
* <term><code>NSFileHFSTypeCode</code></term>
* <desc>NSNumber not used</desc>
* <term><code>NSFileImmutable</code></term>
* <desc>NSNumber ... boolean</desc>
* <term><code>NSFileModificationDate</code></term>
* <desc>NSDate when the file was last modified</desc>
* <term><code>NSFileOwnerAccountName</code></term>
* <desc>NSString name of the file owner</desc>
* <term><code>NSFileOwnerAccountID</code></term>
* <desc>NSNumber ID of the file owner</desc>
* <term><code>NSFilePosixPermissions</code></term>
* <desc>NSNumber posix access permissions mask</desc>
* <term><code>NSFileReferenceCount</code></term>
* <desc>NSNumber number of links to this file</desc>
* <term><code>NSFileSize</code></term>
* <desc>NSNumber size of the file in bytes</desc>
* <term><code>NSFileSystemFileNumber</code></term>
* <desc>NSNumber the identifier for the file on the filesystem</desc>
* <term><code>NSFileSystemNumber</code></term>
* <desc>NSNumber the filesystem on which the file is stored</desc>
* <term><code>NSFileType</code></term>
* <desc>NSString the type of file</desc>
* </deflist>
* <p>
* The [NSDictionary] class also has a set of convenience accessor methods
* which enable you to get at file attribute information more efficiently
* than using the keys above to extract it. You should generally
* use the accessor methods where they are available.
* </p>
* <list>
* <item>[NSDictionary(NSFileAttributes)-fileCreationDate]</item>
* <item>[NSDictionary(NSFileAttributes)-fileExtensionHidden]</item>
* <item>[NSDictionary(NSFileAttributes)-fileHFSCreatorCode]</item>
* <item>[NSDictionary(NSFileAttributes)-fileHFSTypeCode]</item>
* <item>[NSDictionary(NSFileAttributes)-fileIsAppendOnly]</item>
* <item>[NSDictionary(NSFileAttributes)-fileIsImmutable]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSize]</item>
* <item>[NSDictionary(NSFileAttributes)-fileType]</item>
* <item>[NSDictionary(NSFileAttributes)-fileOwnerAccountName]</item>
* <item>[NSDictionary(NSFileAttributes)-fileOwnerAccountID]</item>
* <item>[NSDictionary(NSFileAttributes)-fileGroupOwnerAccountName]</item>
* <item>[NSDictionary(NSFileAttributes)-fileGroupOwnerAccountID]</item>
* <item>[NSDictionary(NSFileAttributes)-fileModificationDate]</item>
* <item>[NSDictionary(NSFileAttributes)-filePosixPermissions]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSystemNumber]</item>
* <item>[NSDictionary(NSFileAttributes)-fileSystemFileNumber]</item>
* </list>
*/
- (NSDictionary*) attributesOfItemAtPath: (NSString*)path
error: (NSError**)error
{
NSDictionary *d;
DESTROY(_lastError);
d = [GSAttrDictionaryClass attributesAt: path traverseLink: NO];
if (error != NULL)
{
if (nil == d)
{
*error = [self _errorFrom: path to: nil];
}
}
return d;
}
- (NSDictionary*) attributesOfFileSystemForPath: (NSString*)path
error: (NSError**)error
{
#if defined(_WIN32)
unsigned long long totalsize, freesize;
id values[5];
id keys[5] = {
NSFileSystemSize,
NSFileSystemFreeSize,
NSFileSystemNodes,
NSFileSystemFreeNodes,
NSFileSystemNumber
};
DWORD SectorsPerCluster, BytesPerSector, NumberFreeClusters;
DWORD TotalNumberClusters;
DWORD volumeSerialNumber = 0;
const _CHAR *lpath = [self fileSystemRepresentationWithPath: path];
_CHAR volumePathName[128];
if (!GetVolumePathNameW(lpath, volumePathName, 128))
{
if (error != NULL)
{
*error = [NSError _last];
}
return nil;
}
GetVolumeInformationW(volumePathName, NULL, 0, &volumeSerialNumber,
NULL, NULL, NULL, 0);
if (!GetDiskFreeSpaceW(volumePathName, &SectorsPerCluster,
&BytesPerSector, &NumberFreeClusters, &TotalNumberClusters))
{
if (error != NULL)
{
*error = [NSError _last];
}
return nil;
}
totalsize = (unsigned long long)TotalNumberClusters
* (unsigned long long)SectorsPerCluster
* (unsigned long long)BytesPerSector;
freesize = (unsigned long long)NumberFreeClusters
* (unsigned long long)SectorsPerCluster
* (unsigned long long)BytesPerSector;
values[0] = [NSNumber numberWithUnsignedLongLong: totalsize];
values[1] = [NSNumber numberWithUnsignedLongLong: freesize];
values[2] = [NSNumber numberWithLong: LONG_MAX];
values[3] = [NSNumber numberWithLong: LONG_MAX];
values[4] = [NSNumber numberWithUnsignedInt: volumeSerialNumber];
return [NSDictionary dictionaryWithObjects: values forKeys: keys count: 5];
#else
#if defined(HAVE_SYS_VFS_H) || defined(HAVE_SYS_STATFS_H) \
|| defined(HAVE_SYS_MOUNT_H)
struct _STATB statbuf;
#ifdef HAVE_STATVFS
struct statvfs statfsbuf;
#else
struct statfs statfsbuf;
#endif
unsigned long long totalsize, freesize;
unsigned long blocksize;
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
id values[5];
id keys[5] = {
NSFileSystemSize,
NSFileSystemFreeSize,
NSFileSystemNodes,
NSFileSystemFreeNodes,
NSFileSystemNumber
};
if (_STAT(lpath, &statbuf) != 0)
{
if (error != NULL)
{
*error = [NSError _last];
}
NSDebugMLLog(@"NSFileManager", @"stat failed for '%s' ... %@",
lpath, [NSError _last]);
return nil;
}
#ifdef HAVE_STATVFS
if (statvfs(lpath, &statfsbuf) != 0)
{
if (error != NULL)
{
*error = [NSError _last];
}
NSDebugMLLog(@"NSFileManager", @"statvfs failed for '%s' ... %@",
lpath, [NSError _last]);
return nil;
}
blocksize = statfsbuf.f_frsize;
#else
if (statfs(lpath, &statfsbuf) != 0)
{
if (error != NULL)
{
*error = [NSError _last];
}
NSDebugMLLog(@"NSFileManager", @"statfs failed for '%s' ... %@",
lpath, [NSError _last]);
return nil;
}
blocksize = statfsbuf.f_bsize;
#endif
totalsize = (unsigned long long) blocksize
* (unsigned long long) statfsbuf.f_blocks;
freesize = (unsigned long long) blocksize
* (unsigned long long) statfsbuf.f_bavail;
values[0] = [NSNumber numberWithUnsignedLongLong: totalsize];
values[1] = [NSNumber numberWithUnsignedLongLong: freesize];
values[2] = [NSNumber numberWithLong: statfsbuf.f_files];
values[3] = [NSNumber numberWithLong: statfsbuf.f_ffree];
values[4] = [NSNumber numberWithUnsignedLong: statbuf.st_dev];
return [NSDictionary dictionaryWithObjects: values forKeys: keys count: 5];
#else
GSOnceMLog(@"NSFileManager", @"no support for filesystem attributes");
ASSIGN(_lastError, @"no support for filesystem attributes");
return nil;
#endif
#endif /* _WIN32 */
}
/**
* Returns a dictionary containing the filesystem attributes for the
* specified path (or nil if the path is not valid).<br />
* <deflist>
* <term><code>NSFileSystemSize</code></term>
* <desc>NSNumber the size of the filesystem in bytes</desc>
* <term><code>NSFileSystemFreeSize</code></term>
* <desc>NSNumber the amount of unused space on the filesystem in bytes</desc>
* <term><code>NSFileSystemNodes</code></term>
* <desc>NSNumber the number of nodes in use to store files</desc>
* <term><code>NSFileSystemFreeNodes</code></term>
* <desc>NSNumber the number of nodes available to create files</desc>
* <term><code>NSFileSystemNumber</code></term>
* <desc>NSNumber the identifying number for the filesystem</desc>
* </deflist>
*/
- (NSDictionary*) fileSystemAttributesAtPath: (NSString*)path
{
return [self attributesOfFileSystemForPath: path
error: NULL];
}
/**
* Returns an array of the contents of the specified directory.<br />
* The listing does <strong>not</strong> recursively list subdirectories.<br />
* The special files '.' and '..' are not listed.<br />
* Indicates an error by returning nil (eg. if path is not a directory or
* it can't be read for some reason).
*/
- (NSArray*) directoryContentsAtPath: (NSString*)path
{
NSDirectoryEnumerator *direnum;
NSMutableArray *content;
BOOL is_dir;
/*
* See if this is a directory (don't follow links).
*/
if ([self fileExistsAtPath: path isDirectory: &is_dir] == NO || is_dir == NO)
{
return nil;
}
content = [NSMutableArray arrayWithCapacity: 128];
/* We initialize the directory enumerator with justContents == YES,
which tells the NSDirectoryEnumerator code that we only enumerate
the contents non-recursively once, and exit. NSDirectoryEnumerator
can perform some optimisations using this assumption. */
direnum = [[NSDirectoryEnumerator alloc] initWithDirectoryPath: path
recurseIntoSubdirectories: NO
followSymlinks: NO
justContents: YES
for: self];
if (nil != direnum)
{
IMP nxtImp;
IMP addImp;
nxtImp = [direnum methodForSelector: @selector(nextObject)];
addImp = [content methodForSelector: @selector(addObject:)];
while ((path = (*nxtImp)(direnum, @selector(nextObject))) != nil)
{
(*addImp)(content, @selector(addObject:), path);
}
RELEASE(direnum);
}
return GS_IMMUTABLE(content);
}
/**
* Returns the name of the file or directory at path. Converts it into
* a format for display to an end user. This may render it unusable as
* part of a file/path name.<br />
* For instance, if a user has elected not to see file extensions, this
* method may return filenames with the extension removed.<br />
* The default operation is to return the result of calling
* [NSString-lastPathComponent] on the path.
*/
- (NSString*) displayNameAtPath: (NSString*)path
{
return [path lastPathComponent];
}
- (NSDirectoryEnumerator*) enumeratorAtPath: (NSString*)path
{
return AUTORELEASE([[NSDirectoryEnumerator alloc]
initWithDirectoryPath: path
recurseIntoSubdirectories: YES
followSymlinks: NO
justContents: NO
for: self]);
}
/**
* Returns an array containing the (relative) paths of all the items
* in the directory at path.<br />
* The listing follows all subdirectories, so it can produce a very
* large array ... use with care.
*/
- (NSArray*) subpathsAtPath: (NSString*)path
{
NSDirectoryEnumerator *direnum;
NSMutableArray *content;
BOOL isDir;
if (![self fileExistsAtPath: path isDirectory: &isDir] || !isDir)
{
return nil;
}
content = [NSMutableArray arrayWithCapacity: 128];
direnum = [[NSDirectoryEnumerator alloc] initWithDirectoryPath: path
recurseIntoSubdirectories: YES
followSymlinks: NO
justContents: NO
for: self];
if (nil != direnum)
{
IMP nxtImp;
IMP addImp;
nxtImp = [direnum methodForSelector: @selector(nextObject)];
addImp = [content methodForSelector: @selector(addObject:)];
while ((path = (*nxtImp)(direnum, @selector(nextObject))) != nil)
{
(*addImp)(content, @selector(addObject:), path);
}
RELEASE(direnum);
}
return GS_IMMUTABLE(content);
}
/**
* Creates a symbolic link at path which links to the location
* specified by otherPath.
*/
- (BOOL) createSymbolicLinkAtPath: (NSString*)path
pathContent: (NSString*)otherPath
{
#ifdef HAVE_SYMLINK
const _CHAR* newpath = [self fileSystemRepresentationWithPath: path];
const _CHAR* oldpath = [self fileSystemRepresentationWithPath: otherPath];
return (symlink(oldpath, newpath) == 0);
#else
ASSIGN(_lastError, @"symbolic links not supported on this system");
return NO;
#endif
}
/**
* Returns the name of the file or directory that the symbolic link
* at path points to.
*/
- (NSString*) pathContentOfSymbolicLinkAtPath: (NSString*)path
{
#ifdef HAVE_READLINK
char buf[PATH_MAX];
const _CHAR* lpath = [self fileSystemRepresentationWithPath: path];
int llen = readlink(lpath, buf, PATH_MAX-1);
if (llen > 0)
{
return [self stringWithFileSystemRepresentation: buf length: llen];
}
else
{
return nil;
}
#else
ASSIGN(_lastError, @"symbolic links not supported on this system");
return nil;
#endif
}
#if defined(_WIN32)
- (const GSNativeChar*) fileSystemRepresentationWithPath: (NSString*)path
{
if (path != nil && [path rangeOfString: @"/"].length > 0)
{
path = [path stringByReplacingString: @"/" withString: @"\\"];
}
return
(const GSNativeChar*)[path cStringUsingEncoding: NSUnicodeStringEncoding];
}
- (NSString*) stringWithFileSystemRepresentation: (const GSNativeChar*)string
length: (NSUInteger)len
{
return [NSString stringWithCharacters: string length: len];
}
#else
- (const GSNativeChar*) fileSystemRepresentationWithPath: (NSString*)path
{
return
(const GSNativeChar*)[path cStringUsingEncoding: defaultEncoding];
}
- (NSString*) stringWithFileSystemRepresentation: (const GSNativeChar*)string
length: (NSUInteger)len
{
return AUTORELEASE([[NSString allocWithZone: NSDefaultMallocZone()]
initWithBytes: string length: len encoding: defaultEncoding]);
}
#endif
@end /* NSFileManager */
/* A directory to enumerate. We keep a stack of the directories we
still have to enumerate. We start by putting the top-level
directory into the stack, then we start reading files from it
(using readdir). If we find a file which is actually a directory,
and if we have to recurse into it, we create a new
GSEnumeratedDirectory struct for the subdirectory, open its DIR
*pointer for reading, and put it on top of the stack, so next time
-nextObject is called, it will read from that directory instead of
the top level one. Once all the subdirectory is read, it is
removed from the stack, so the top of the stack if the top
directory again, and enumeration continues in there. */
typedef struct _GSEnumeratedDirectory {
NSString *path;
_DIR *pointer;
#ifdef __ANDROID__
AAssetDir *assetDir;
#endif
} GSEnumeratedDirectory;
static inline void gsedRelease(GSEnumeratedDirectory X)
{
DESTROY(X.path);
_CLOSEDIR(X.pointer);
#ifdef __ANDROID__
if (X.assetDir)
{
AAssetDir_close(X.assetDir);
}
#endif
}
#define GSI_ARRAY_TYPES 0
#define GSI_ARRAY_TYPE GSEnumeratedDirectory
#define GSI_ARRAY_RELEASE(A, X) gsedRelease(X.ext)
#define GSI_ARRAY_RETAIN(A, X)
#include "GNUstepBase/GSIArray.h"
@implementation NSDirectoryEnumerator
/*
* The Objective-C interface hides a traditional C implementation.
* This was the only way I could get near the speed of standard unix
* tools for big directories.
*/
+ (void) initialize
{
if (self == [NSDirectoryEnumerator class])
{
}
}
- (void) _setSkipHidden: (BOOL)flag
{
_flags.skipHidden = flag;
}
- (void) _setErrorHandler: (GSDirEnumErrorHandler) handler
{
_errorHandler = handler;
}
- (id) initWithDirectoryPath: (NSString*)path
recurseIntoSubdirectories: (BOOL)recurse
followSymlinks: (BOOL)follow
justContents: (BOOL)justContents
skipHidden: (BOOL)skipHidden
errorHandler: (GSDirEnumErrorHandler) handler
for: (NSFileManager*)mgr
{
if (nil != (self = [super init]))
{
//TODO: the justContents flag is currently basically useless and should be
// removed
_DIR *dir_pointer;
const _CHAR *localPath;
_mgr = RETAIN(mgr);
_stack = NSZoneMalloc([self zone], sizeof(GSIArray_t));
GSIArrayInitWithZoneAndCapacity(_stack, [self zone], 64);
_flags.isRecursive = recurse;
_flags.isFollowing = follow;
_flags.justContents = justContents;
_flags.skipHidden = skipHidden;
_errorHandler = handler;
_topPath = [[NSString alloc] initWithString: path];
localPath = [_mgr fileSystemRepresentationWithPath: path];
dir_pointer = _OPENDIR(localPath);
#ifdef __ANDROID__
AAssetDir *assetDir = NULL;
if (!dir_pointer)
{
/* Android: try using asset manager if path is in
* main bundle resources
*/
assetDir = [NSBundle assetDirForPath: path];
}
if (dir_pointer || assetDir)
#else
if (dir_pointer)
#endif
{
GSIArrayItem item;
item.ext.path = @"";
item.ext.pointer = dir_pointer;
#ifdef __ANDROID__
item.ext.assetDir = assetDir;
#endif
GSIArrayAddItem(_stack, item);
}
else
{
NSDebugLog(@"Failed to recurse into directory '%@' - %@", path,
[NSError _last]);
}
}
return self;
}
/**
* Initialize instance to enumerate contents at path, which should be a
* directory and can be specified in relative or absolute, and may include
* Unix conventions like '<code>~</code>' for user home directory, which will
* be appropriately converted on Windoze systems. The justContents flag, if
* set, is equivalent to recurseIntoSubdirectories = NO and followSymlinks =
* NO, but the implementation will be made more efficient.
*/
- (id) initWithDirectoryPath: (NSString*)path
recurseIntoSubdirectories: (BOOL)recurse
followSymlinks: (BOOL)follow
justContents: (BOOL)justContents
for: (NSFileManager*)mgr
{
return [self initWithDirectoryPath: path
recurseIntoSubdirectories: recurse
followSymlinks: follow
justContents: justContents
skipHidden: NO
errorHandler: NULL
for: mgr];
}
- (void) dealloc
{
GSIArrayEmpty(_stack);
NSZoneFree([self zone], _stack);
DESTROY(_topPath);
DESTROY(_currentFilePath);
DESTROY(_mgr);
[super dealloc];
}
/**
* Returns a dictionary containing the attributes of the directory
* at which enumeration started. <br />
* The contents of this dictionary are as produced by
* [NSFileManager-fileAttributesAtPath:traverseLink:]
*/
- (NSDictionary*) directoryAttributes
{
return [_mgr fileAttributesAtPath: _topPath
traverseLink: _flags.isFollowing];
}
/**
* Returns a dictionary containing the attributes of the file
* currently being enumerated. <br />
* The contents of this dictionary are as produced by
* [NSFileManager-fileAttributesAtPath:traverseLink:]
*/
- (NSDictionary*) fileAttributes
{
return [_mgr fileAttributesAtPath: _currentFilePath
traverseLink: _flags.isFollowing];
}
/**
* Informs the receiver that any descendents of the current directory
* should be skipped rather than enumerated. Use this to avoid enumerating
* the contents of directories you are not interested in.
*/
- (void) skipDescendents
{
if (GSIArrayCount(_stack) > 0)
{
GSIArrayRemoveLastItem(_stack);
if (_currentFilePath != 0)
{
DESTROY(_currentFilePath);
}
}
}
/*
* finds the next file according to the top enumerator
* - if there is a next file it is put in currentFile
* - if the current file is a directory and if isRecursive calls
* recurseIntoDirectory: currentFile
* - if the current file is a symlink to a directory and if isRecursive
* and isFollowing calls recurseIntoDirectory: currentFile
* - if at end of current directory pops stack and attempts to
* find the next entry in the parent
* - sets currentFile to nil if there are no more files to enumerate
*/
- (id) nextObject
{
NSString *returnFileName = 0;
if (_currentFilePath != 0)
{
DESTROY(_currentFilePath);
}
while (GSIArrayCount(_stack) > 0)
{
GSEnumeratedDirectory dir = GSIArrayLastItem(_stack).ext;
struct _STATB statbuf;
const _CHAR *dirname = NULL;
#ifdef __ANDROID__
if (dir.assetDir)
{
/* This will only return files and not directories, which means that
* recursion is not supported.
* See https://issuetracker.google.com/issues/37002833
*/
dirname = AAssetDir_getNextFileName(dir.assetDir);
}
else if (dir.pointer)
#endif
{
struct _DIRENT *dirbuf = _READDIR(dir.pointer);
if (dirbuf)
{
dirname = dirbuf->d_name;
}
}
if (dirname)
{
// Skip it if it is hidden and flag is yes...
if ([[dir.path lastPathComponent] hasPrefix: @"."]
&& _flags.skipHidden == YES)
{
continue;
}
#if defined(_WIN32)
/* Skip "." and ".." directory entries */
if (wcscmp(dirname, L".") == 0
|| wcscmp(dirname, L"..") == 0)
{
continue;
}
/* Name of file to return */
returnFileName = [_mgr
stringWithFileSystemRepresentation: dirname
length: wcslen(dirname)];
#else
/* Skip "." and ".." directory entries */
if (strcmp(dirname, ".") == 0
|| strcmp(dirname, "..") == 0)
{
continue;
}
/* Name of file to return */
returnFileName = [_mgr
stringWithFileSystemRepresentation: dirname
length: strlen(dirname)];
#endif
/* if we have a null FileName something went wrong (charset?)
* and we skip it */
if (returnFileName == nil)
continue;
returnFileName = RETAIN([dir.path stringByAppendingPathComponent:
returnFileName]);
if (!_flags.justContents)
_currentFilePath = RETAIN([_topPath stringByAppendingPathComponent:
returnFileName]);
if (_flags.isRecursive == YES)
{
// Do not follow links
#ifdef S_IFLNK
#ifdef _WIN32
#warning "lstat does not support unichars"
#else
if (!_flags.isFollowing)
{
if (lstat([_mgr fileSystemRepresentationWithPath:
_currentFilePath], &statbuf) != 0)
{
break;
}
// If link then return it as link
if (S_IFLNK == (S_IFMT & statbuf.st_mode))
{
break;
}
}
else
#endif
#endif
{
if (_STAT([_mgr fileSystemRepresentationWithPath:
_currentFilePath], &statbuf) != 0)
{
break;
}
}
if (S_IFDIR == (S_IFMT & statbuf.st_mode))
{
_DIR *dir_pointer;
dir_pointer
= _OPENDIR([_mgr fileSystemRepresentationWithPath:
_currentFilePath]);
if (dir_pointer)
{
GSIArrayItem item;
item.ext.path = RETAIN(returnFileName);
item.ext.pointer = dir_pointer;
GSIArrayAddItem(_stack, item);
}
else
{
BOOL flag = YES;
NSDebugLog(@"Failed to recurse into directory '%@' - %@",
_currentFilePath, [NSError _last]);
if (_errorHandler != NULL)
{
flag = CALL_BLOCK(_errorHandler,
[NSURL URLWithString: _currentFilePath],
[NSError _last]);
}
if (flag == NO)
{
return nil; // Stop enumeration...
}
}
}
}
break; // Got a file name - break out of loop
}
else
{
GSIArrayRemoveLastItem(_stack);
if (_currentFilePath != 0)
{
DESTROY(_currentFilePath);
}
}
}
return AUTORELEASE(returnFileName);
}
@end /* NSDirectoryEnumerator */
/**
* Convenience methods for accessing named file attributes in a dictionary.
*/
@implementation NSDictionary(NSFileAttributes)
/**
* Return the file creation date attribute (or nil if not found).
*/
- (NSDate*) fileCreationDate
{
return [self objectForKey: NSFileCreationDate];
}
/**
* Return the file extension hidden attribute (or NO if not found).
*/
- (BOOL) fileExtensionHidden
{
return [[self objectForKey: NSFileExtensionHidden] boolValue];
}
/**
* Returns HFS creator attribute (OS X).
*/
- (OSType) fileHFSCreatorCode
{
return [[self objectForKey: NSFileHFSCreatorCode] unsignedLongValue];
}
/**
* Returns HFS type code attribute (OS X).
*/
- (OSType) fileHFSTypeCode
{
return [[self objectForKey: NSFileHFSTypeCode] unsignedLongValue];
}
/**
* Return the file append only attribute (or NO if not found).
*/
- (BOOL) fileIsAppendOnly
{
return [[self objectForKey: NSFileAppendOnly] boolValue];
}
/**
* Return the file immutable attribute (or NO if not found).
*/
- (BOOL) fileIsImmutable
{
return [[self objectForKey: NSFileImmutable] boolValue];
}
/**
* Return the size of the file, or NSNotFound if the file size attribute
* is not found in the dictionary.
*/
- (unsigned long long) fileSize
{
NSNumber *n = [self objectForKey: NSFileSize];
if (n == nil)
{
return NSNotFound;
}
return [n unsignedLongLongValue];
}
/**
* Return the file type attribute or nil if not present.
*/
- (NSString*) fileType
{
return [self objectForKey: NSFileType];
}
/**
* Return the file owner account name attribute or nil if not present.
*/
- (NSString*) fileOwnerAccountName
{
return [self objectForKey: NSFileOwnerAccountName];
}
/**
* Return an NSNumber with the numeric value of the NSFileOwnerAccountID attribute
* in the dictionary, or nil if the attribute is not present.
*/
- (NSNumber*) fileOwnerAccountID
{
return [self objectForKey: NSFileOwnerAccountID];
}
/**
* Return the file group owner account name attribute or nil if not present.
*/
- (NSString*) fileGroupOwnerAccountName
{
return [self objectForKey: NSFileGroupOwnerAccountName];
}
/**
* Return an NSNumber with the numeric value of the NSFileGroupOwnerAccountID attribute
* in the dictionary, or nil if the attribute is not present.
*/
- (NSNumber*) fileGroupOwnerAccountID
{
return [self objectForKey: NSFileGroupOwnerAccountID];
}
/**
* Return the file modification date attribute (or nil if not found)
*/
- (NSDate*) fileModificationDate
{
return [self objectForKey: NSFileModificationDate];
}
/**
* Return the file posix permissions attribute (or NSNotFound if
* the attribute is not present in the dictionary).
*/
- (NSUInteger) filePosixPermissions
{
NSNumber *n = [self objectForKey: NSFilePosixPermissions];
if (n == nil)
{
return NSNotFound;
}
return [n unsignedIntegerValue];
}
/**
* Return the file system number attribute (or NSNotFound if
* the attribute is not present in the dictionary).
*/
- (NSUInteger) fileSystemNumber
{
NSNumber *n = [self objectForKey: NSFileSystemNumber];
if (n == nil)
{
return NSNotFound;
}
return [n unsignedIntegerValue];
}
/**
* Return the file system file identification number attribute
* or NSNotFound if the attribute is not present in the dictionary).
*/
- (NSUInteger) fileSystemFileNumber
{
NSNumber *n = [self objectForKey: NSFileSystemFileNumber];
if (n == nil)
{
return NSNotFound;
}
return [n unsignedIntegerValue];
}
@end
@implementation NSFileManager (PrivateMethods)
- (BOOL) _copyFile: (NSString*)source
toFile: (NSString*)destination
handler: (id)handler
{
#if defined(_WIN32)
if (CopyFileW([self fileSystemRepresentationWithPath: source],
[self fileSystemRepresentationWithPath: destination], NO))
{
return YES;
}
return [self _proceedAccordingToHandler: handler
forError: @"cannot copy file"
inPath: source
fromPath: source
toPath: destination];
#else
NSDictionary *attributes;
NSDate *modification;
unsigned long long fileSize;
unsigned long long i;
int bufsize = 8096;
int sourceFd;
int destFd;
int fileMode;
int rbytes;
int wbytes;
char buffer[bufsize];
#ifdef __ANDROID__
AAsset *asset = NULL;
#endif
attributes = [self fileAttributesAtPath: source traverseLink: NO];
if (nil == attributes)
{
return [self _proceedAccordingToHandler: handler
forError: @"source file does not exist"
inPath: source
fromPath: source
toPath: destination];
}
fileSize = [attributes fileSize];
fileMode = [attributes filePosixPermissions];
modification = [attributes fileModificationDate];
/* Open the source file. In case of error call the handler. */
sourceFd = open([self fileSystemRepresentationWithPath: source],
GSBINIO|O_RDONLY);
#ifdef __ANDROID__
if (sourceFd < 0)
{
// Android: try using asset manager if path is in main bundle resources
asset = [NSBundle assetForPath: source withMode: AASSET_MODE_STREAMING];
}
if (sourceFd < 0 && asset == NULL)
#else
if (sourceFd < 0)
#endif
{
return [self _proceedAccordingToHandler: handler
forError: @"cannot open file for reading"
inPath: source
fromPath: source
toPath: destination];
}
/* Open the destination file. In case of error call the handler. */
destFd = open([self fileSystemRepresentationWithPath: destination],
GSBINIO|O_WRONLY|O_CREAT|O_TRUNC, fileMode);
if (destFd < 0)
{
#ifdef __ANDROID__
if (asset)
{
AAsset_close(asset);
}
else
#endif
close (sourceFd);
return [self _proceedAccordingToHandler: handler
forError: @"cannot open file for writing"
inPath: destination
fromPath: source
toPath: destination];
}
/* Read bufsize bytes from source file and write them into the destination
file. In case of errors call the handler and abort the operation. */
for (i = 0; i < fileSize; i += rbytes)
{
#ifdef __ANDROID__
if (asset)
{
rbytes = AAsset_read(asset, buffer, bufsize);
}
else
#endif
rbytes = read (sourceFd, buffer, bufsize);
if (rbytes <= 0)
{
if (0 == rbytes)
{
break; // End of input file
}
#ifdef __ANDROID__
if (asset)
{
AAsset_close(asset);
}
else
#endif
close (sourceFd);
close (destFd);
return [self _proceedAccordingToHandler: handler
forError: @"cannot read from file"
inPath: source
fromPath: source
toPath: destination];
}
wbytes = write (destFd, buffer, rbytes);
if (wbytes != rbytes)
{
#ifdef __ANDROID__
if (asset)
{
AAsset_close(asset);
}
else
#endif
close (sourceFd);
close (destFd);
return [self _proceedAccordingToHandler: handler
forError: @"cannot write to file"
inPath: destination
fromPath: source
toPath: destination];
}
}
#ifdef __ANDROID__
if (asset)
{
AAsset_close(asset);
}
else
#endif
close (sourceFd);
close (destFd);
/* Check for modification during copy.
*/
attributes = [self fileAttributesAtPath: source traverseLink: NO];
if (NO == [modification isEqual: [attributes fileModificationDate]]
|| [attributes fileSize] != fileSize)
{
return [self _proceedAccordingToHandler: handler
forError: @"source modified during copy"
inPath: destination
fromPath: source
toPath: destination];
}
return YES;
#endif
}
- (BOOL) _copyPath: (NSString*)source
toPath: (NSString*)destination
handler: handler
{
NSDirectoryEnumerator *enumerator;
NSString *dirEntry;
BOOL result = YES;
ENTER_POOL
enumerator = [self enumeratorAtPath: source];
while ((dirEntry = [enumerator nextObject]))
{
NSString *sourceFile;
NSString *fileType;
NSString *destinationFile;
NSDictionary *attributes;
attributes = [enumerator fileAttributes];
fileType = [attributes fileType];
sourceFile = [source stringByAppendingPathComponent: dirEntry];
destinationFile
= [destination stringByAppendingPathComponent: dirEntry];
[self _sendToHandler: handler willProcessPath: sourceFile];
if ([fileType isEqual: NSFileTypeDirectory])
{
NSMutableDictionary *newAttributes;
BOOL dirOK;
newAttributes = [attributes mutableCopy];
[newAttributes removeObjectForKey: NSFileOwnerAccountID];
[newAttributes removeObjectForKey: NSFileGroupOwnerAccountID];
[newAttributes removeObjectForKey: NSFileGroupOwnerAccountName];
[newAttributes setObject: NSUserName()
forKey: NSFileOwnerAccountName];
dirOK = [self createDirectoryAtPath: destinationFile
attributes: newAttributes];
RELEASE(newAttributes);
if (dirOK == NO)
{
if (![self _proceedAccordingToHandler: handler
forError: _lastError
inPath: destinationFile
fromPath: sourceFile
toPath: destinationFile])
{
result = NO;
break;
}
/*
* We may have managed to create the directory but not set
* its attributes ... if so we can continue copying.
*/
if (![self fileExistsAtPath: destinationFile isDirectory: &dirOK])
{
dirOK = NO;
}
}
if (dirOK == YES)
{
[enumerator skipDescendents];
if (![self _copyPath: sourceFile
toPath: destinationFile
handler: handler])
{
result = NO;
break;
}
}
}
else if ([fileType isEqual: NSFileTypeRegular])
{
if (![self _copyFile: sourceFile
toFile: destinationFile
handler: handler])
{
result = NO;
break;
}
}
else if ([fileType isEqual: NSFileTypeSymbolicLink])
{
NSString *path;
path = [self pathContentOfSymbolicLinkAtPath: sourceFile];
if (![self createSymbolicLinkAtPath: destinationFile
pathContent: path])
{
if (![self _proceedAccordingToHandler: handler
forError: @"cannot create symbolic link"
inPath: sourceFile
fromPath: sourceFile
toPath: destinationFile])
{
result = NO;
break;
}
}
}
else
{
NSString *s;
s = [NSString stringWithFormat: @"cannot copy file type '%@'",
fileType];
ASSIGN(_lastError, s);
NSDebugLog(@"%@: %@", sourceFile, s);
continue;
}
[self changeFileAttributes: attributes atPath: destinationFile];
}
LEAVE_POOL
return result;
}
- (BOOL) _linkPath: (NSString*)source
toPath: (NSString*)destination
handler: handler
{
#ifdef HAVE_LINK
NSDirectoryEnumerator *enumerator;
NSString *dirEntry;
BOOL result = YES;
ENTER_POOL
enumerator = [self enumeratorAtPath: source];
while ((dirEntry = [enumerator nextObject]))
{
NSString *sourceFile;
NSString *fileType;
NSString *destinationFile;
NSDictionary *attributes;
attributes = [enumerator fileAttributes];
fileType = [attributes fileType];
sourceFile = [source stringByAppendingPathComponent: dirEntry];
destinationFile
= [destination stringByAppendingPathComponent: dirEntry];
[self _sendToHandler: handler willProcessPath: sourceFile];
if ([fileType isEqual: NSFileTypeDirectory] == YES)
{
if ([self createDirectoryAtPath: destinationFile
attributes: attributes] == NO)
{
if ([self _proceedAccordingToHandler: handler
forError: _lastError
inPath: destinationFile
fromPath: sourceFile
toPath: destinationFile] == NO)
{
result = NO;
break;
}
}
else
{
[enumerator skipDescendents];
if ([self _linkPath: sourceFile
toPath: destinationFile
handler: handler] == NO)
{
result = NO;
break;
}
}
}
else if ([fileType isEqual: NSFileTypeSymbolicLink])
{
NSString *path;
path = [self pathContentOfSymbolicLinkAtPath: sourceFile];
if ([self createSymbolicLinkAtPath: destinationFile
pathContent: path] == NO)
{
if ([self _proceedAccordingToHandler: handler
forError: @"cannot create symbolic link"
inPath: sourceFile
fromPath: sourceFile
toPath: destinationFile] == NO)
{
result = NO;
break;
}
}
}
else
{
if (link([self fileSystemRepresentationWithPath: sourceFile],
[self fileSystemRepresentationWithPath: destinationFile]) < 0)
{
if ([self _proceedAccordingToHandler: handler
forError: @"cannot create hard link"
inPath: sourceFile
fromPath: sourceFile
toPath: destinationFile] == NO)
{
result = NO;
break;
}
}
}
[self changeFileAttributes: attributes atPath: destinationFile];
}
LEAVE_POOL
return result;
#else
ASSIGN(_lastError, @"Links not supported on this platform");
return NO;
#endif
}
- (void) _sendToHandler: (id) handler
willProcessPath: (NSString*) path
{
if ([handler respondsToSelector: @selector (fileManager:willProcessPath:)])
{
[handler fileManager: self willProcessPath: path];
}
}
- (BOOL) _proceedAccordingToHandler: (id) handler
forError: (NSString*) error
inPath: (NSString*) path
{
if ([handler respondsToSelector:
@selector (fileManager:shouldProceedAfterError:)])
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
path, NSFilePathErrorKey,
error, @"Error", nil];
return [handler fileManager: self
shouldProceedAfterError: errorInfo];
}
return NO;
}
- (BOOL) _proceedAccordingToHandler: (id) handler
forError: (NSString*) error
inPath: (NSString*) path
fromPath: (NSString*) fromPath
toPath: (NSString*) toPath
{
if ([handler respondsToSelector:
@selector (fileManager:shouldProceedAfterError:)])
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
path, NSFilePathErrorKey,
fromPath, @"FromPath",
toPath, @"ToPath",
error, @"Error", nil];
return [handler fileManager: self
shouldProceedAfterError: errorInfo];
}
return NO;
}
- (NSError*) _errorFrom: (NSString *)fromPath to: (NSString *)toPath
{
NSError *error;
NSDictionary *errorInfo;
NSString *message;
NSString *domain;
NSInteger code;
if (_lastError)
{
message = _lastError;
domain = NSCocoaErrorDomain;
code = 0;
}
else
{
error = [NSError _last];
message = [error localizedDescription];
domain = [error domain];
code = [error code];
}
if (fromPath && toPath)
{
errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
fromPath, @"FromPath",
toPath, @"ToPath",
message, NSLocalizedDescriptionKey,
nil];
}
else if (fromPath)
{
errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
fromPath, NSFilePathErrorKey,
message, NSLocalizedDescriptionKey,
nil];
}
else
{
errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
message, NSLocalizedDescriptionKey,
nil];
}
error = [NSError errorWithDomain: domain
code: code
userInfo: errorInfo];
DESTROY(_lastError);
return error;
}
@end /* NSFileManager (PrivateMethods) */
@implementation GSAttrDictionary
static NSSet *fileKeys = nil;
+ (NSDictionary*) attributesAt: (NSString *)path
traverseLink: (BOOL)traverse
{
GSAttrDictionary *d;
unsigned l = 0;
unsigned i;
const _CHAR *lpath = [defaultManager fileSystemRepresentationWithPath: path];
#ifdef __ANDROID__
AAsset *asset = NULL;
#endif
if (lpath == 0 || *lpath == 0)
{
return nil;
}
while (lpath[l] != 0)
{
l++;
}
d = (GSAttrDictionary*)NSAllocateObject(self, (l+1)*sizeof(_CHAR),
NSDefaultMallocZone());
#if defined(S_IFLNK) && !defined(_WIN32)
if (traverse == NO)
{
if (lstat(lpath, &d->statbuf) != 0)
{
#ifdef __ANDROID__
/* Android: try using asset manager if path is in
* main bundle resources
*/
asset = [NSBundle assetForPath: path];
if (asset == NULL)
#endif
DESTROY(d);
}
}
else
#endif
if (_STAT(lpath, &d->statbuf) != 0)
{
#ifdef __ANDROID__
// Android: try using asset manager if path is in main bundle resources
asset = [NSBundle assetForPath: path];
if (asset == NULL)
#endif
DESTROY(d);
}
if (d != nil)
{
for (i = 0; i <= l; i++)
{
d->_path[i] = lpath[i];
}
#ifdef __ANDROID__
if (asset)
{
// set some basic stat values for Android assets
memset(&d->statbuf, 0, sizeof(d->statbuf));
d->statbuf.st_mode = S_IRUSR;
d->statbuf.st_size = AAsset_getLength(asset);
AAsset_close(asset);
}
#endif
}
return AUTORELEASE(d);
}
+ (void) initialize
{
if (fileKeys == nil)
{
fileKeys = [[NSSet alloc] initWithObjects:
NSFileAppendOnly,
NSFileCreationDate,
NSFileDeviceIdentifier,
NSFileExtensionHidden,
NSFileGroupOwnerAccountName,
NSFileGroupOwnerAccountID,
NSFileHFSCreatorCode,
NSFileHFSTypeCode,
NSFileImmutable,
NSFileModificationDate,
NSFileOwnerAccountName,
NSFileOwnerAccountID,
NSFilePosixPermissions,
NSFileReferenceCount,
NSFileSize,
NSFileSystemFileNumber,
NSFileSystemNumber,
NSFileType,
nil];
[[NSObject leakAt: &fileKeys] release];
}
}
- (NSUInteger) count
{
return [fileKeys count];
}
- (NSDate*) fileCreationDate
{
#if defined(_WIN32)
return [NSDate dateWithTimeIntervalSince1970: statbuf.st_ctime];
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIM)
NSTimeInterval ti;
ti = statbuf.st_birthtim.tv_sec + (double)statbuf.st_birthtim.tv_nsec / 1.0e9;
return [NSDate dateWithTimeIntervalSince1970: ti];
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIME)
return [NSDate dateWithTimeIntervalSince1970: statbuf.st_birthtime];
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) || defined (HAVE_STRUCT_STAT64_ST_BIRTHTIMESPEC)
NSTimeInterval ti;
ti = statbuf.st_birthtimespec.tv_sec + (double)statbuf.st_birthtimespec.tv_nsec / 1.0e9;
return [NSDate dateWithTimeIntervalSince1970: ti];
#else
/* We don't know a better way to get creation date, it is not defined in POSIX
* Use the earlier of ctime or mtime
*/
if (statbuf.st_ctime < statbuf.st_mtime)
return [NSDate dateWithTimeIntervalSince1970: statbuf.st_ctime];
else
return [NSDate dateWithTimeIntervalSince1970: statbuf.st_mtime];
#endif
}
- (BOOL) fileExtensionHidden
{
return NO;
}
- (NSNumber*) fileGroupOwnerAccountID
{
return [NSNumber numberWithInt: statbuf.st_gid];
}
- (NSString*) fileGroupOwnerAccountName
{
NSString *group = @"UnknownGroup";
#if defined(_WIN32)
DWORD returnCode = 0;
PSID sidOwner;
int result = TRUE;
_CHAR account[BUFSIZ];
_CHAR domain[BUFSIZ];
DWORD accountSize = 1024;
DWORD domainSize = 1024;
SID_NAME_USE eUse = SidTypeUnknown;
HANDLE hFile;
PSECURITY_DESCRIPTOR pSD;
// Get the handle of the file object.
hFile = CreateFileW(
_path,
GENERIC_READ,
FILE_SHARE_READ,
0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0);
// Check GetLastError for CreateFile error code.
if (hFile == INVALID_HANDLE_VALUE)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
NSDebugMLog(@"Error %d getting file handle for '%S'",
dwErrorCode, _path);
return group;
}
// Get the group SID of the file.
returnCode = GetSecurityInfo(
hFile,
SE_FILE_OBJECT,
GROUP_SECURITY_INFORMATION,
0,
&sidOwner,
0,
0,
&pSD);
CloseHandle(hFile);
// Check GetLastError for GetSecurityInfo error condition.
if (returnCode != ERROR_SUCCESS)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
NSDebugMLog(@"Error %d getting security info for '%S'",
dwErrorCode, _path);
return group;
}
// First call to LookupAccountSid to get the buffer sizes.
result = LookupAccountSidW(
0, // local computer
sidOwner,
account,
(LPDWORD)&accountSize,
domain,
(LPDWORD)&domainSize,
&eUse);
// Check GetLastError for LookupAccountSid error condition.
if (result == FALSE)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
if (dwErrorCode == ERROR_NONE_MAPPED)
NSDebugMLog(@"Error %d in LookupAccountSid for '%S'", _path);
else
NSDebugMLog(@"Error %d getting security info for '%S'",
dwErrorCode, _path);
return group;
}
if (accountSize >= 1024)
{
NSDebugMLog(@"Account name for '%S' is unreasonably long", _path);
return group;
}
return [NSString stringWithCharacters: account length: accountSize];
#else
#if defined(HAVE_GRP_H)
#if defined(HAVE_GETGRGID_H)
struct group gp;
struct group *p;
char buf[BUFSIZ*10];
if (getgrgid_r(statbuf.st_gid, &gp, buf, sizeof(buf), &p) == 0)
{
group = [NSString stringWithCString: gp.gr_name
encoding: defaultEncoding];
}
#else
#if defined(HAVE_GETGRGID)
struct group *gp;
[gnustep_global_lock lock];
gp = getgrgid(statbuf.st_gid);
if (gp != 0)
{
group = [NSString stringWithCString: gp->gr_name
encoding: defaultEncoding];
}
[gnustep_global_lock unlock];
#endif
#endif
#endif
#endif
return group;
}
- (OSType) fileHFSCreatorCode
{
return 0;
}
- (OSType) fileHFSTypeCode
{
return 0;
}
- (BOOL) fileIsAppendOnly
{
return 0;
}
- (BOOL) fileIsImmutable
{
return 0;
}
- (NSDate*) fileModificationDate
{
NSTimeInterval ti;
#if defined (HAVE_STRUCT_STAT_ST_MTIM)
ti = statbuf.st_mtim.tv_sec + (double)statbuf.st_mtim.tv_nsec / 1.0e9;
#else
ti = (double)statbuf.st_mtime;
#endif
return [NSDate dateWithTimeIntervalSince1970: ti];
}
- (NSUInteger) filePosixPermissions
{
return (statbuf.st_mode & ~S_IFMT);
}
- (NSNumber*) fileOwnerAccountID
{
return [NSNumber numberWithInt: statbuf.st_uid];
}
- (NSString*) fileOwnerAccountName
{
NSString *owner = @"UnknownUser";
#if defined(_WIN32)
DWORD returnCode = 0;
PSID sidOwner;
int result = TRUE;
_CHAR account[BUFSIZ];
_CHAR domain[BUFSIZ];
DWORD accountSize = 1024;
DWORD domainSize = 1024;
SID_NAME_USE eUse = SidTypeUnknown;
HANDLE hFile;
PSECURITY_DESCRIPTOR pSD;
// Get the handle of the file object.
hFile = CreateFileW(
_path,
GENERIC_READ,
FILE_SHARE_READ,
0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0);
// Check GetLastError for CreateFile error code.
if (hFile == INVALID_HANDLE_VALUE)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
NSDebugMLog(@"Error %d getting file handle for '%S'",
dwErrorCode, _path);
return owner;
}
// Get the owner SID of the file.
returnCode = GetSecurityInfo(
hFile,
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
&sidOwner,
0,
0,
0,
&pSD);
CloseHandle(hFile);
// Check GetLastError for GetSecurityInfo error condition.
if (returnCode != ERROR_SUCCESS)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
NSDebugMLog(@"Error %d getting security info for '%S'",
dwErrorCode, _path);
return owner;
}
// First call to LookupAccountSid to get the buffer sizes.
result = LookupAccountSidW(
0, // local computer
sidOwner,
account,
(LPDWORD)&accountSize,
domain,
(LPDWORD)&domainSize,
&eUse);
// Check GetLastError for LookupAccountSid error condition.
if (result == FALSE)
{
DWORD dwErrorCode = 0;
dwErrorCode = GetLastError();
if (dwErrorCode == ERROR_NONE_MAPPED)
NSDebugMLog(@"Error %d in LookupAccountSid for '%S'", _path);
else
NSDebugMLog(@"Error %d getting security info for '%S'",
dwErrorCode, _path);
return owner;
}
if (accountSize >= 1024)
{
NSDebugMLog(@"Account name for '%S' is unreasonably long", _path);
return owner;
}
return [NSString stringWithCharacters: account length: accountSize];
#else
#ifdef HAVE_PWD_H
#if defined(HAVE_GETPWUID_R)
struct passwd pw;
struct passwd *p;
char buf[BUFSIZ*10];
if (getpwuid_r(statbuf.st_uid, &pw, buf, sizeof(buf), &p) == 0)
{
owner = [NSString stringWithCString: pw.pw_name
encoding: defaultEncoding];
}
#else
#if defined(HAVE_GETPWUID)
struct passwd *pw;
[gnustep_global_lock lock];
pw = getpwuid(statbuf.st_uid);
if (pw != 0)
{
owner = [NSString stringWithCString: pw->pw_name
encoding: defaultEncoding];
}
[gnustep_global_lock unlock];
#endif
#endif
#endif /* HAVE_PWD_H */
#endif
return owner;
}
- (unsigned long long) fileSize
{
return statbuf.st_size;
}
- (NSUInteger) fileSystemFileNumber
{
return statbuf.st_ino;
}
- (NSUInteger) fileSystemNumber
{
#if defined(_WIN32)
DWORD volumeSerialNumber = 0;
_CHAR volumePathName[128];
if (GetVolumePathNameW(_path,volumePathName,128))
{
GetVolumeInformationW(volumePathName,NULL,0,&volumeSerialNumber,NULL,NULL,NULL,0);
}
return (NSUInteger)volumeSerialNumber;
#else
return statbuf.st_dev;
#endif
}
- (NSString*) fileType
{
switch (statbuf.st_mode & S_IFMT)
{
case S_IFREG: return NSFileTypeRegular;
case S_IFDIR: return NSFileTypeDirectory;
case S_IFCHR: return NSFileTypeCharacterSpecial;
#if defined(S_IFBLK) && !defined(_WIN32)
case S_IFBLK: return NSFileTypeBlockSpecial;
#endif
#if defined(S_IFLNK) && !defined(_WIN32)
case S_IFLNK: return NSFileTypeSymbolicLink;
#endif
#ifdef S_IFIFO
case S_IFIFO: return NSFileTypeFifo;
#endif
#ifdef S_IFSOCK
case S_IFSOCK: return NSFileTypeSocket;
#endif
default: return NSFileTypeUnknown;
}
}
- (NSEnumerator*) keyEnumerator
{
return [fileKeys objectEnumerator];
}
- (NSEnumerator*) objectEnumerator
{
return [GSAttrDictionaryEnumerator enumeratorFor: self];
}
- (id) objectForKey: (id)key
{
int count = 0;
while (key != 0 && count < 2)
{
if (key == NSFileAppendOnly)
return [NSNumber numberWithBool: [self fileIsAppendOnly]];
if (key == NSFileCreationDate)
return [self fileCreationDate];
if (key == NSFileDeviceIdentifier)
return [NSNumber numberWithUnsignedInt: statbuf.st_dev];
if (key == NSFileExtensionHidden)
return [NSNumber numberWithBool: [self fileExtensionHidden]];
if (key == NSFileGroupOwnerAccountName)
return [self fileGroupOwnerAccountName];
if (key == NSFileGroupOwnerAccountID)
return [self fileGroupOwnerAccountID];
if (key == NSFileHFSCreatorCode)
return [NSNumber numberWithUnsignedLong: [self fileHFSCreatorCode]];
if (key == NSFileHFSTypeCode)
return [NSNumber numberWithUnsignedLong: [self fileHFSTypeCode]];
if (key == NSFileImmutable)
return [NSNumber numberWithBool: [self fileIsImmutable]];
if (key == NSFileModificationDate)
return [self fileModificationDate];
if (key == NSFileOwnerAccountName)
return [self fileOwnerAccountName];
if (key == NSFileOwnerAccountID)
return [self fileOwnerAccountID];
if (key == NSFilePosixPermissions)
return [NSNumber numberWithUnsignedInt: [self filePosixPermissions]];
if (key == NSFileReferenceCount)
return [NSNumber numberWithUnsignedInt: statbuf.st_nlink];
if (key == NSFileSize)
return [NSNumber numberWithUnsignedLongLong: [self fileSize]];
if (key == NSFileSystemFileNumber)
return [NSNumber numberWithUnsignedInt: [self fileSystemFileNumber]];
if (key == NSFileSystemNumber)
return [NSNumber numberWithUnsignedInt: [self fileSystemNumber]];
if (key == NSFileType)
return [self fileType];
/*
* Now, if we didn't get an exact pointer match, check for
* string equalities and ensure we get an exact match next
* time round the loop.
*/
count++;
key = [fileKeys member: key];
}
if (count >= 2)
{
NSDebugLog(@"Warning ... key '%@' not handled", key);
}
return nil;
}
@end /* GSAttrDictionary */
@implementation GSAttrDictionaryEnumerator
+ (NSEnumerator*) enumeratorFor: (NSDictionary*)d
{
GSAttrDictionaryEnumerator *e;
e = (GSAttrDictionaryEnumerator*)
NSAllocateObject(self, 0, NSDefaultMallocZone());
e->dictionary = RETAIN(d);
e->enumerator = RETAIN([fileKeys objectEnumerator]);
return AUTORELEASE(e);
}
- (void) dealloc
{
RELEASE(enumerator);
RELEASE(dictionary);
[super dealloc];
}
- (id) nextObject
{
NSString *key = [enumerator nextObject];
id val = nil;
if (key != nil)
{
val = [dictionary objectForKey: key];
}
return val;
}
@end
|