1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082
|
/*********************************************************
* Copyright (C) 1998-2008 VMware, Inc. All rights reserved.
*
* This program 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 version 2.1 and no later version.
*
* This program 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 Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*********************************************************/
/*
* hgfsServerLinux.c --
*
* This file contains the linux implementation of the server half
* of the Host/Guest File System (hgfs), a.k.a. "Shared Folder".
*
* The hgfs server carries out filesystem requests that it receives
* over the backdoor from a driver in the other world.
*/
#define _GNU_SOURCE // for O_NOFOLLOW
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h> // for utimes(2)
#include <sys/syscall.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#if defined(__FreeBSD__)
# include <sys/param.h>
#else
# include <wchar.h>
# include <wctype.h>
#endif
#include "vmware.h"
#include "hgfsServerPolicy.h" // for security policy
#include "hgfsServerInt.h"
#include "hgfsEscape.h"
#include "str.h"
#include "cpNameLite.h"
#include "hgfsUtil.h" // for cross-platform time conversion
#include "posix.h"
#include "file.h"
#include "util.h"
#include "syncMutex.h"
#include "su.h"
#include "codeset.h"
#include "unicodeOperations.h"
#if defined(linux) && !defined(SYS_getdents64)
/* For DT_UNKNOWN */
# include <dirent.h>
#endif
#ifndef VMX86_TOOLS
# include "config.h"
#endif
#define LOGLEVEL_MODULE hgfs
#include "loglevel_user.h"
#if defined(__APPLE__)
#include <CoreServices/CoreServices.h> // for the alias manager
#include <CoreFoundation/CoreFoundation.h> // for CFString and CFURL
#include <sys/attr.h> // for getattrlist
#include <sys/vnode.h> // for VERG / VDIR
#endif
/*
* ALLPERMS (mode 07777) and ACCESSPERMS (mode 0777) are not defined in the
* Solaris version of <sys/stat.h>.
*/
#ifdef sun
# define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO)
# define ALLPERMS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
#endif
#ifdef HGFS_OPLOCKS
# include <signal.h>
# include "sig.h"
#endif
#if defined(linux) && !defined(GLIBC_VERSION_21)
/*
* Implements the system call (it is not wrapped by glibc 2.1.1)
*/
static INLINE int
_llseek(unsigned int fd,
unsigned long offset_high,
unsigned long offset_low,
loff_t *result,
unsigned int whence)
{
return syscall(SYS__llseek, fd, offset_high, offset_low, result, whence);
}
#endif
/*
* On Linux, we must wrap getdents64, as glibc does not wrap it for us. We use getdents64
* (rather than getdents) because with the latter, we'll get 64-bit offsets and inode
* numbers. Note that getdents64 isn't supported everywhere, in particular, kernels older
* than 2.4.1 do not implement it. On those older guests, we try using getdents(), and
* translating the results to our DirectoryEntry structure...
*
* On FreeBSD and Mac platforms, getdents is implemented as getdirentries, and takes an
* additional parameter which returns the position of the block read, which we don't care
* about.
*/
#if defined(linux)
static INLINE int
getdents_linux(unsigned int fd,
DirectoryEntry *dirp,
unsigned int count)
{
# if defined(SYS_getdents64)
return syscall(SYS_getdents64, fd, dirp, count);
# else
/*
* Fall back to regular getdents on older Linux systems that don't have
* getdents64. Because glibc does translation between the kernel's "struct dirent" and
* the libc "struct dirent", this structure matches the one in linux/dirent.h, rather
* than us using the libc 'struct dirent' directly
*/
struct linux_dirent {
long d_ino;
long d_off; /* __kernel_off_t expands to long on RHL 6.2 */
unsigned short d_reclen;
char d_name[NAME_MAX];
} *dirp_temp;
int retval;
dirp_temp = alloca((sizeof *dirp_temp) * count);
retval = syscall(SYS_getdents, fd, dirp_temp, count);
if (retval > 0) {
int i;
/*
* Translate from the Linux 'struct dirent' to the hgfs DirectoryEntry, since
* they're not always the same layout.
*/
for (i = 0; i < count; i++) {
dirp[i].d_ino = dirp_temp[i].d_ino;
dirp[i].d_off = dirp_temp[i].d_off;
dirp[i].d_reclen = dirp_temp[i].d_reclen;
dirp[i].d_type = DT_UNKNOWN;
memcpy(dirp[i].d_name, dirp_temp[i].d_name,
((sizeof dirp->d_name) < (sizeof dirp_temp->d_name))
? (sizeof dirp->d_name)
: (sizeof dirp_temp->d_name));
}
}
return retval;
# endif
}
# define getdents getdents_linux
#elif defined(__FreeBSD__) || defined(__APPLE__)
#define getdents(fd, dirp, count) \
({ \
long basep; \
getdirentries(fd, dirp, count, &basep); \
})
#endif
/*
* O_DIRECTORY is only relevant on Linux. For other platforms, we'll hope that
* the kernel is smart enough to deny getdents(2) (or getdirentries(2)) on
* files which aren't directories.
*
* Likewise, O_NOFOLLOW doesn't exist on Solaris 9. Oh well.
*/
#ifndef O_DIRECTORY
#define O_DIRECTORY 0
#endif
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
#if defined(sun) || defined(linux) || \
(defined(__FreeBSD_version) && __FreeBSD_version < 490000)
/*
* Implements futimes(), which was introduced in glibc 2.3.3. FreeBSD 3.2
* doesn't have it, but 4.9 does. Unfortunately, these early FreeBSD versions
* don't have /proc/self, so futimes() will simply fail. For now the only
* caller to futimes() is HgfsServerSetattr which doesn't get invoked at all
* in the HGFS server which runs in the Tools, so it's OK.
*/
#define PROC_SELF_FD "/proc/self/fd/"
#define STRLEN_OF_MAXINT_AS_STRING 10
int
futimes(int fd, const struct timeval times[2])
{
#ifndef sun
/*
* Hack to allow the timevals in futimes() to be const even when utimes()
* expects non-const timevals. This is the case on glibc up to 2.3 or
* thereabouts.
*/
struct timeval mytimes[2];
/* Maximum size of "/proc/self/fd/<fd>" as a string. Accounts for nul. */
char nameBuffer[sizeof PROC_SELF_FD + STRLEN_OF_MAXINT_AS_STRING];
mytimes[0] = times[0];
mytimes[1] = times[1];
if (snprintf(nameBuffer, sizeof nameBuffer, PROC_SELF_FD "%d", fd) < 0) {
return -1;
}
return Posix_Utimes(nameBuffer, mytimes);
#else /* !sun */
return futimesat(fd, NULL, times);
#endif /* !sun */
}
#undef PROC_SELF_FD
#undef STRLEN_OF_MAXINT_AS_STRING
#endif
#if defined(__APPLE__)
struct FInfoAttrBuf {
uint32 length;
fsobj_type_t objType;
char finderInfo[32];
};
#endif
/*
* Server open flags, indexed by HgfsOpenFlags. Stolen from
* lib/fileIOPosix.c
*
* Using O_NOFOLLOW will allow us to forgo a (racy) symlink check just
* before opening the file.
*
* Using O_NONBLOCK will prevent us from blocking the HGFS server if
* we open a FIFO.
*/
static const int HgfsServerOpenFlags[] = {
O_NONBLOCK | O_NOFOLLOW,
O_NONBLOCK | O_NOFOLLOW | O_TRUNC,
O_NONBLOCK | O_NOFOLLOW | O_CREAT,
O_NONBLOCK | O_NOFOLLOW | O_CREAT | O_EXCL,
O_NONBLOCK | O_NOFOLLOW | O_CREAT | O_TRUNC,
};
/*
* Server open mode, indexed by HgfsOpenMode.
*/
static const int HgfsServerOpenMode[] = {
O_RDONLY,
O_WRONLY,
O_RDWR,
};
/* Local functions. */
static HgfsInternalStatus HgfsConvertFromNameStatus(HgfsNameStatus status);
static HgfsInternalStatus HgfsGetattrResolveAlias(char const *fileName,
char **targetName);
static HgfsInternalStatus HgfsGetattrFromName(char *fileName,
HgfsShareOptions configOptions,
char *shareName,
HgfsFileAttrInfo *attr,
char **targetName);
static HgfsInternalStatus HgfsAccess(char *fileName,
char *shareName,
size_t shareNameLen);
static HgfsInternalStatus HgfsGetattrFromFd(int fd,
HgfsSessionInfo *session,
HgfsFileAttrInfo *attr);
static void HgfsStatToFileAttr(struct stat *stats,
uint64 *creationTime,
HgfsFileAttrInfo *attr);
static int HgfsStat(const char* fileName,
Bool followLink,
struct stat *stats,
uint64 *creationTime);
static int HgfsFStat(int fd,
struct stat *stats,
uint64 *creationTime);
static int HgfsConvertComponentCase(char *currentComponent,
const char *dirPath,
const char **convertedComponent,
size_t *convertedComponentSize);
static int HgfsConstructConvertedPath(char **path,
size_t *pathSize,
char *convertedPath,
size_t convertedPathSize);
static int HgfsCaseInsensitiveLookup(const char *sharePath,
size_t sharePathLength,
char *fileName,
size_t fileNameLength,
char **convertedFileName,
size_t *convertedFileNameLength);
static Bool HgfsSetattrMode(struct stat *statBuf,
HgfsFileAttrInfo *attr,
mode_t *newPermissions);
static Bool HgfsSetattrOwnership(HgfsFileAttrInfo *attr,
uid_t *newUid,
gid_t *newGid);
static HgfsInternalStatus HgfsSetattrTimes(struct stat *statBuf,
HgfsFileAttrInfo *attr,
HgfsAttrHint hints,
struct timeval *accessTime,
struct timeval *modTime,
Bool *timesChanged);
static HgfsInternalStatus HgfsSetattrFromFd(HgfsHandle file,
HgfsSessionInfo *session,
HgfsFileAttrInfo *attr,
HgfsAttrHint hints);
static HgfsInternalStatus HgfsSetattrFromName(char *cpName,
size_t cpNameSize,
HgfsFileAttrInfo *attr,
HgfsAttrHint hints,
uint32 caseFlags,
HgfsSessionInfo *session);
static Bool HgfsIsShareRoot(char const *cpName, size_t cpNameSize);
static HgfsInternalStatus HgfsGetHiddenXAttr(char const *fileName, Bool *attribute);
static HgfsInternalStatus HgfsSetHiddenXAttr(char const *fileName, Bool value);
static HgfsInternalStatus HgfsEffectivePermissions(char *fileName,
Bool readOnlyShare,
uint32 *permissions);
#if defined(__APPLE__)
static void HgfsConvertStat64ToStat(const struct stat64 *stats64,
struct stat *stats,
uint64 *creationTime);
#else
static uint64 HgfsGetCreationTime(const struct stat *stats);
#endif
#ifdef HGFS_OPLOCKS
/*
*-----------------------------------------------------------------------------
*
* HgfsServerSigOplockBreak --
*
* Handle a pending oplock break. Called from the VMX poll loop context.
* All we really do is set up the state for an oplock break and call
* HgfsServerOplockBreak which will do the rest of the work.
*
* Results:
* None.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static void
HgfsServerSigOplockBreak(int sigNum, // IN: Signal number
siginfo_t *info, // IN: Additional info about signal
ucontext_t *u, // IN: Interrupted context (regs etc)
void *clientData) // IN: Ignored
{
ServerLockData *lockData;
int newLease, fd;
HgfsServerLock newServerLock;
ASSERT(sigNum == SIGIO);
ASSERT(info);
ASSERT(clientData == NULL);
fd = info->si_fd;
LOG(4, ("HgfsServerSigOplockBreak: Received SIGIO for fd %d\n", fd));
/*
* We've got all we need from the signal handler, let it continue handling
* signals of this type.
*/
Sig_Continue(sigNum);
/*
* According to locks.c in kernel source, doing F_GETLEASE when a lease
* break is pending will return the new lease we should use. It'll be
* F_RDLCK if we can downgrade, or F_UNLCK if we should break altogether.
*/
newLease = fcntl(fd, F_GETLEASE);
if (newLease == F_RDLCK) {
newServerLock = HGFS_LOCK_SHARED;
} else if (newLease == F_UNLCK) {
newServerLock = HGFS_LOCK_NONE;
} else if (newLease == -1) {
int error = errno;
Log("HgfsServerSigOplockBreak: Could not get old lease for fd %d: %s\n",
fd, strerror(error));
goto error;
} else {
Log("HgfsServerSigOplockBreak: Unexpected reply to get lease for fd %d: "
"%d\n", fd, newLease);
goto error;
}
/*
* Setup a ServerLockData struct so that we can make use of
* HgfsServerOplockBreak which does the heavy lifting of discovering which
* HGFS handle we're interested in breaking, sending the break, receiving
* the acknowledgement, and firing the platform-specific acknowledgement
* function (where we'll downgrade the lease).
*/
lockData = malloc(sizeof *lockData);
if (lockData) {
lockData->fileDesc = fd;
lockData->serverLock = newServerLock;
lockData->event = 0; // not needed
/*
* Relinquish control of this data. It'll get freed later, when the RPC
* command completes.
*/
HgfsServerOplockBreak(lockData);
return;
} else {
Log("HgfsServerSigOplockBreak: Could not allocate memory for lease "
"break on behalf of fd %d\n", fd);
}
error:
/* Clean up as best we can. */
fcntl(fd, F_SETLEASE, F_UNLCK);
HgfsUpdateNodeServerLock(fd, HGFS_LOCK_NONE);
}
#endif /* HGFS_OPLOCKS */
/*
*-----------------------------------------------------------------------------
*
* HgfsConvertFromNameStatus --
*
* This function converts between a status code used in processing a cross
* platform filename, and a platform-specific status code.
*
* Because the two status codes never go down the wire, there is no danger
* of backwards compatibility here, and we should ASSERT if we encounter
* an status code that we're not familiar with.
*
* Results:
* Converted status code.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsConvertFromNameStatus(HgfsNameStatus status) // IN
{
switch(status) {
case HGFS_NAME_STATUS_COMPLETE:
return 0;
case HGFS_NAME_STATUS_FAILURE:
case HGFS_NAME_STATUS_INCOMPLETE_BASE:
case HGFS_NAME_STATUS_INCOMPLETE_ROOT:
case HGFS_NAME_STATUS_INCOMPLETE_DRIVE:
case HGFS_NAME_STATUS_INCOMPLETE_UNC:
case HGFS_NAME_STATUS_INCOMPLETE_UNC_MACH:
return EINVAL;
case HGFS_NAME_STATUS_DOES_NOT_EXIST:
return ENOENT;
case HGFS_NAME_STATUS_ACCESS_DENIED:
return EACCES;
case HGFS_NAME_STATUS_SYMBOLIC_LINK:
return ELOOP;
case HGFS_NAME_STATUS_OUT_OF_MEMORY:
return ENOMEM;
case HGFS_NAME_STATUS_TOO_LONG:
return ENAMETOOLONG;
case HGFS_NAME_STATUS_NOT_A_DIRECTORY:
return ENOTDIR;
default:
NOT_IMPLEMENTED();
}
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerGetDefaultDirAttrs --
*
* Get default directory attributes. Permissions are Read and
* Execute permission only.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static void
HgfsServerGetDefaultDirAttrs(HgfsFileAttrInfo *attr) // OUT
{
struct timeval tv;
uint64 hgfsTime;
ASSERT(attr);
attr->type = HGFS_FILE_TYPE_DIRECTORY;
attr->size = 4192;
/*
* Linux and friends are OK with receiving timestamps of 0, but just
* for consistency with the Windows server, we'll pass back the
* host's time in a virtual directory's timestamps.
*/
if (gettimeofday(&tv, NULL) != 0) {
hgfsTime = 0;
} else {
hgfsTime = HgfsConvertToNtTime(tv.tv_sec, tv.tv_usec * 1000);
}
attr->creationTime = hgfsTime;
attr->accessTime = hgfsTime;
attr->writeTime = hgfsTime;
attr->attrChangeTime = hgfsTime;
attr->specialPerms = 0;
attr->ownerPerms = HGFS_PERM_READ | HGFS_PERM_EXEC;
attr->groupPerms = HGFS_PERM_READ | HGFS_PERM_EXEC;
attr->otherPerms = HGFS_PERM_READ | HGFS_PERM_EXEC;
attr->mask = HGFS_ATTR_VALID_TYPE |
HGFS_ATTR_VALID_SIZE |
HGFS_ATTR_VALID_CREATE_TIME |
HGFS_ATTR_VALID_ACCESS_TIME |
HGFS_ATTR_VALID_WRITE_TIME |
HGFS_ATTR_VALID_CHANGE_TIME |
HGFS_ATTR_VALID_SPECIAL_PERMS |
HGFS_ATTR_VALID_OWNER_PERMS |
HGFS_ATTR_VALID_GROUP_PERMS |
HGFS_ATTR_VALID_OTHER_PERMS;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerGetOpenFlags --
*
* Retrieve system open flags from HgfsOpenFlags.
*
* Does the correct bounds checking on the HgfsOpenFlags before
* indexing into the array of flags to use. See bug 54429.
*
* Results:
* TRUE on success
* FALSE on failure
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static Bool
HgfsServerGetOpenFlags(HgfsOpenFlags flagsIn, // IN
int *flagsOut) // OUT
{
unsigned int arraySize;
ASSERT(flagsOut);
arraySize = ARRAYSIZE(HgfsServerOpenFlags);
if (flagsIn < 0 || flagsIn >= arraySize) {
Log("HgfsServerGetOpenFlags: Invalid HgfsOpenFlags %d\n", flagsIn);
return FALSE;
}
*flagsOut = HgfsServerOpenFlags[flagsIn];
return TRUE;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerPlatformInit --
*
* Set up any state needed to start Linux HGFS server.
*
* Results:
* None.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
Bool
HgfsServerPlatformInit(void)
{
#ifdef HGFS_OPLOCKS
/* Register a signal handler to catch oplock break signals. */
Sig_Callback(SIGIO, SIG_SAFE, HgfsServerSigOplockBreak, NULL);
#endif
return TRUE;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerPlatformDestroy --
*
* Tear down any state used for Linux HGFS server.
*
* Results:
* None.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
void
HgfsServerPlatformDestroy(void)
{
#ifdef HGFS_OPLOCKS
/* Tear down oplock state, so we no longer catch signals. */
Sig_Callback(SIGIO, SIG_NOHANDLER, NULL, NULL);
#endif
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerGetOpenMode --
*
* Retrieve system open mode from HgfsOpenMode.
*
* Does the correct bounds checking on the HgfsOpenMode before
* indexing into the array of modes to use. See bug 54429.
*
* This is just the POSIX implementation; the Windows implementation is
* more complicated, hence the need for the HgfsFileOpenInfo as an
* argument.
*
* Results:
* TRUE on success
* FALSE on failure
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
Bool
HgfsServerGetOpenMode(HgfsFileOpenInfo *openInfo, // IN: Open info to examine
uint32 *modeOut) // OUT: Local mode
{
ASSERT(modeOut);
/*
* If we didn't get the mode in the open request, we'll return a mode of 0.
* This has the effect of failing the call to open(2) later, which is
* exactly what we want.
*/
if ((openInfo->mask & HGFS_OPEN_VALID_MODE) == 0) {
*modeOut = 0;
return TRUE;
}
if (!HGFS_OPEN_MODE_IS_VALID_MODE(openInfo->mode)) {
Log("HgfsServerGetOpenMode: Invalid HgfsOpenMode %d\n", openInfo->mode);
return FALSE;
}
*modeOut = HgfsServerOpenMode[HGFS_OPEN_MODE_ACCMODE(openInfo->mode)];
return TRUE;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsCloseFile --
*
* Closes the file descriptor.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsCloseFile(fileDesc fileDesc) // IN: File descriptor
{
if (close(fileDesc) != 0) {
int error = errno;
LOG(4, ("HgfsCloseFile: Could not close fd %d: %s\n", fileDesc,
strerror(error)));
return error;
}
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsCheckFileNode --
*
* Check if a file node is still valid (i.e. if the file name stored in the
* file node still refers to the same file)
*
* Results:
* Zero if the file node is valid
* Non-zero if the file node is stale
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsCheckFileNode(char const *localName, // IN
HgfsLocalId const *localId) // IN
{
struct stat nodeStat;
ASSERT(localName);
ASSERT(localId);
/*
* A file is uniquely identified by a (device; inode) pair. Check that the
* file name still refers to the same pair
*/
if (Posix_Stat(localName, &nodeStat) < 0) {
int error = errno;
LOG(4, ("HgfsCheckFileNode: couldn't stat local file \"%s\": %s\n",
localName, strerror(error)));
return error;
}
if ( nodeStat.st_dev != localId->volumeId
|| nodeStat.st_ino != localId->fileId) {
LOG(4, ("HgfsCheckFileNode: local Id mismatch\n"));
return ENOENT;
}
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsGetFd --
*
* Returns the file descriptor associated with the node. If the node is
* cached then it just returns the cached file descriptor (checking for
* correct write flags). Otherwise, it opens a new file, caches the node
* and returns the file desriptor.
*
* Results:
* Zero on success. fd contains the opened file descriptor.
* Non-zero on error.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetFd(HgfsHandle hgfsHandle, // IN: HGFS file handle
HgfsSessionInfo *session, // IN: Session info
Bool append, // IN: Open with append flag
fileDesc *fd) // OUT: Opened file descriptor
{
int newFd = -1, openFlags = 0;
HgfsFileNode node;
HgfsInternalStatus status = 0;
ASSERT(fd);
ASSERT(session);
/*
* Use node copy convenience function to get the node information.
* Note that we shouldn't keep this node around for too long because
* the information can become stale. However, it's ok to get all the
* fields in one step, instead of getting them all separate.
*
* XXX: It would be better if we didn't do this node copy on the fast
* path. Unfortuntely, even the fast path may need to look at the node's
* append flag.
*/
node.utf8Name = NULL;
if (!HgfsGetNodeCopy(hgfsHandle, session, TRUE, &node)) {
/* XXX: Technically, this can also fail if we're out of memory. */
LOG(4, ("HgfsGetFd: Invalid hgfs handle.\n"));
status = EBADF;
goto exit;
}
/* If the node is found in the cache */
if (HgfsIsCached(hgfsHandle, session)) {
/*
* If the append flag is set check to see if the file was opened
* in append mode. If not, close the file and reopen it in append
* mode.
*/
if (append && !(node.flags & HGFS_FILE_NODE_APPEND_FL)) {
status = HgfsCloseFile(node.fileDesc);
if (status != 0) {
LOG(4, ("HgfsGetFd: Couldn't close file \"%s\" for reopening\n",
node.utf8Name));
goto exit;
}
/*
* Update the node in the cache with the new value of the append
* flag.
*/
if (!HgfsUpdateNodeAppendFlag(hgfsHandle, session, TRUE)) {
LOG(4, ("HgfsGetFd: Could not update the node in the cache\n"));
status = EBADF;
goto exit;
}
} else {
newFd = node.fileDesc;
goto exit;
}
}
/*
* If we got here then the file was either not in the cache or needs
* reopening. This means we need to open a file. But first, verify
* that the file we intend to open isn't stale.
*/
status = HgfsCheckFileNode(node.utf8Name, &node.localId);
if (status != 0) {
goto exit;
}
/*
* We're not interested in creating a new file. So let's just get the
* flags for a simple open request. This really should always work.
*/
HgfsServerGetOpenFlags(0, &openFlags);
/*
* We don't need to specify open permissions here because we're only
* reopening an existing file, not creating a new one.
*
* XXX: We should use O_LARGEFILE, see lib/file/fileIOPosix.c --hpreg
*/
newFd = Posix_Open(node.utf8Name,
node.mode | openFlags | (append ? O_APPEND : 0));
if (newFd < 0) {
int error = errno;
LOG(4, ("HgfsGetFd: Couldn't open file \"%s\": %s\n",
node.utf8Name, strerror(errno)));
status = error;
goto exit;
}
/*
* Update the original node with the new value of the file desc.
* This call might fail if the node is not used anymore.
*/
if (!HgfsUpdateNodeFileDesc(hgfsHandle, session, newFd)) {
LOG(4, ("HgfsGetFd: Could not update the node -- node is not used.\n"));
status = EBADF;
goto exit;
}
/* Add the node to the cache. */
if (!HgfsAddToCache(hgfsHandle, session)) {
LOG(4, ("HgfsGetFd: Could not add node to the cache\n"));
status = EBADF;
goto exit;
}
exit:
if (status == 0) {
*fd = newFd;
}
free(node.utf8Name);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsValidateOpen --
*
* Verify that the file with the given local name exists in the
* local filesystem by trying to open the file with the requested
* mode and permissions. If the open succeeds we stat the file
* and fill in the volumeId and fileId with the file's local
* filesystem device and inode number, respectively.
*
* Results:
* Zero on success
* Non-zero on failure.
*
* Side effects:
* File with name "localName" may be created or truncated.
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsValidateOpen(HgfsFileOpenInfo *openInfo, // IN: Open info struct
int followSymlinks, // IN: followSymlinks config option
HgfsSessionInfo *session, // IN: session info
HgfsLocalId *localId, // OUT: Local unique file ID
int *fileDesc) // OUT: Handle to the file
{
struct stat fileStat;
int fd;
int error;
int openMode = 0, openFlags = 0;
mode_t openPerms;
HgfsServerLock serverLock;
HgfsInternalStatus status = 0;
Bool needToSetAttribute = FALSE;
ASSERT(openInfo);
ASSERT(localId);
ASSERT(fileDesc);
ASSERT(session);
/*
* Get correct system flags and mode from the HgfsOpenFlags and
* HgfsOpenMode. This is related to bug 54429.
*/
if (!HgfsServerGetOpenFlags(openInfo->mask & HGFS_OPEN_VALID_FLAGS ?
openInfo->flags : 0,
&openFlags) ||
!HgfsServerGetOpenMode(openInfo, &openMode)) {
status = EPROTO;
goto exit;
}
/*
* Create mode_t for use in open(). If owner permissions are missing, use
* read/write for the owner permissions. If group or other permissions
* are missing, use the owner permissions.
*
* This sort of makes sense. If the Windows driver wants to make a file
* read-only, it probably intended for the file to be 555. Since creating
* a file requires a valid mode, it's highly unlikely that we'll ever
* be creating a file without owner permissions.
*/
openPerms = ~ALLPERMS;
openPerms |= openInfo->mask & HGFS_OPEN_VALID_SPECIAL_PERMS ?
openInfo->specialPerms << 9 : 0;
openPerms |= openInfo->mask & HGFS_OPEN_VALID_OWNER_PERMS ?
openInfo->ownerPerms << 6 : S_IWUSR | S_IRUSR;
openPerms |= openInfo->mask & HGFS_OPEN_VALID_GROUP_PERMS ?
openInfo->groupPerms << 3 : (openPerms & S_IRWXU) >> 3;
openPerms |= openInfo->mask & HGFS_OPEN_VALID_OTHER_PERMS ?
openInfo->otherPerms : (openPerms & S_IRWXU) >> 6;
/*
* By default we don't follow symlinks, O_NOFOLLOW is always set.
* Unset it if followSymlinks config option is specified.
*/
if (followSymlinks) {
openFlags &= ~O_NOFOLLOW;
}
/*
* Need to validate that open does not change the file for read
* only shared folders.
*/
status = 0;
if (!openInfo->shareInfo.writePermissions) {
if ((openFlags & (O_APPEND | O_CREAT | O_TRUNC)) ||
(openMode & (O_WRONLY | O_RDWR))) {
status = access(openInfo->utf8Name, F_OK);
if (status < 0) {
status = errno;
if (status == ENOENT && (openFlags & O_CREAT) != 0) {
status = EACCES;
}
} else {
/*
* Handle the case when the file already exists:
* If there is an attempt to createa new file, fail with "EEXIST"
* error, otherwise set error to "EACCES".
*/
if ((openFlags & O_CREAT) && (openFlags & O_EXCL)) {
status = EEXIST;
} else {
status = EACCES;
}
}
}
if (status != 0) {
goto exit;
}
}
if (!openInfo->shareInfo.readPermissions) {
/*
* "Drop Box" / "FTP incoming" type of shared folders.
* Allow creating a new file. Deny opening exisitng file.
*/
status = access(openInfo->utf8Name, F_OK);
if (status < 0) {
status = errno;
if (status != ENOENT || (openFlags & O_CREAT) == 0) {
status = EACCES;
}
} else {
status = EACCES;
}
if (status != 0) {
goto exit;
}
}
/*
* Determine if hidden attribute needs to be updated.
* It needs to be updated if a new file is created or an existing file is truncated.
* Since Posix_Open does not tell us if a new file has been created when O_CREAT is
* specified we need to find out if the file exists before an open that may create
* it.
*/
if (openInfo->mask & HGFS_OPEN_VALID_FILE_ATTR) {
if ((openFlags & O_TRUNC) ||
((openFlags & O_CREAT) && (openFlags & O_EXCL))) {
needToSetAttribute = TRUE;
} else if (openFlags & O_CREAT) {
int err = access(openInfo->utf8Name, F_OK);
needToSetAttribute = (err != 0) && (errno == ENOENT);
}
}
/*
* Try to open the file with the requested mode, flags and permissions.
*/
fd = Posix_Open(openInfo->utf8Name,
openMode | openFlags,
openPerms);
if (fd < 0) {
error = errno;
LOG(4, ("HgfsValidateOpen: couldn't open file \"%s\": %s\n",
openInfo->utf8Name, strerror(error)));
status = error;
goto exit;
}
/* Set the rest of the Windows specific attributes if necessary. */
if (needToSetAttribute) {
HgfsSetHiddenXAttr(openInfo->utf8Name, openInfo->attr & HGFS_ATTR_HIDDEN);
}
/* Stat file to get its volume and file info */
if (fstat(fd, &fileStat) < 0) {
error = errno;
LOG(4, ("HgfsValidateOpen: couldn't stat local file \"%s\": %s\n",
openInfo->utf8Name, strerror(error)));
close(fd);
status = error;
goto exit;
}
/* Try to acquire an oplock. */
if (openInfo->mask & HGFS_OPEN_VALID_SERVER_LOCK) {
serverLock = openInfo->desiredLock;
if (!HgfsAcquireServerLock(fd, session, &serverLock)) {
openInfo->acquiredLock = HGFS_LOCK_NONE;
} else {
openInfo->acquiredLock = serverLock;
}
} else {
openInfo->acquiredLock = HGFS_LOCK_NONE;
}
*fileDesc = fd;
/* Set volume and file ids from stat results */
localId->volumeId = fileStat.st_dev;
localId->fileId = fileStat.st_ino;
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsAcquireServerLock --
*
* Acquire a lease for the open file. Typically we try and get the exact
* lease desired, but if the client asked for HGFS_LOCK_OPPORTUNISTIC, we'll
* take the "best" lease we can get.
*
* Results:
* TRUE on success. serverLock contains the type of the lock acquired.
* FALSE on failure. serverLock is HGFS_LOCK_NONE.
*
* XXX: This function has the potential to return per-platform error codes,
* but since it is opportunistic by nature, it isn't necessary to do so.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
Bool
HgfsAcquireServerLock(fileDesc fileDesc, // IN: OS handle
HgfsSessionInfo *session, // IN: session info
HgfsServerLock *serverLock) // IN/OUT: Oplock asked for/granted
{
#ifdef HGFS_OPLOCKS
HgfsServerLock desiredLock;
int leaseType, error;
ASSERT(serverLock);
ASSERT(session);
desiredLock = *serverLock;
if (desiredLock == HGFS_LOCK_NONE) {
return TRUE;
}
if (!HgfsIsServerLockAllowed(session)) {
return FALSE;
}
/*
* First tell the kernel which signal to send us. SIGIO is already the
* default, but if we skip this step, we won't get the siginfo_t when
* a lease break occurs.
*
* XXX: Do I need to do fcntl(fileDesc, F_SETOWN, getpid())?
*/
if (fcntl(fileDesc, F_SETSIG, SIGIO)) {
error = errno;
Log("HgfsAcquireServerLock: Could not set SIGIO as the desired lease "
"break signal for fd %d: %s\n", fileDesc, strerror(error));
return FALSE;
}
/*
* If the client just wanted the best lock possible, start off with a write
* lease and move down to a read lease if that was unavailable.
*/
if ((desiredLock == HGFS_LOCK_OPPORTUNISTIC) ||
(desiredLock == HGFS_LOCK_EXCLUSIVE)) {
leaseType = F_WRLCK;
} else if (desiredLock == HGFS_LOCK_SHARED) {
leaseType = F_RDLCK;
} else {
LOG(4, ("HgfsAcquireServerLock: Unknown server lock\n"));
return FALSE;
}
if (fcntl(fileDesc, F_SETLEASE, leaseType)) {
/*
* If our client was opportunistic and we failed to get his lease because
* someone else is already writing or reading to the file, try again with
* a read lease.
*/
if (desiredLock == HGFS_LOCK_OPPORTUNISTIC &&
(errno == EAGAIN || errno == EACCES)) {
leaseType = F_RDLCK;
if (fcntl(fileDesc, F_SETLEASE, leaseType)) {
error = errno;
LOG(4, ("HgfsAcquireServerLock: Could not get any opportunistic "
"lease for fd %d: %s\n", fileDesc, strerror(error)));
return FALSE;
}
} else {
error = errno;
LOG(4, ("HgfsAcquireServerLock: Could not get %s lease for fd %d: "
"%s\n", leaseType == F_WRLCK ? "write" : "read", fileDesc,
strerror(errno)));
return FALSE;
}
}
/* Got a lease of some kind. */
LOG(4, ("HgfsAcquireServerLock: Got %s lease for fd %d\n",
leaseType == F_WRLCK ? "write" : "read", fileDesc));
*serverLock = leaseType == F_WRLCK ? HGFS_LOCK_EXCLUSIVE : HGFS_LOCK_SHARED;
return TRUE;
#else
return FALSE;
#endif
}
/*
*-----------------------------------------------------------------------------
*
* HgfsGetattrResolveAlias --
*
* Mac OS defines a special file type known as an alias which behaves like a
* symlink when viewed through the Finder, but is actually a regular file
* otherwise. Unlike symlinks, aliases cannot be broken; if the target file
* is deleted, so is the alias.
*
* If the given filename is (or contains) an alias, this function will
* resolve it completely and set targetName to something non-NULL.
*
* Results:
* Zero on success. targetName is allocated if the file was an alias, and
* NULL otherwise.
* Non-zero on failure. targetName is unmodified.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetattrResolveAlias(char const *fileName, // IN: Input filename
char **targetName) // OUT: Target filename
{
#ifndef __APPLE__
*targetName = NULL;
return 0;
#else
char *myTargetName = NULL;
HgfsInternalStatus status = HGFS_INTERNAL_STATUS_ERROR;
CFURLRef resolvedRef = NULL;
CFStringRef resolvedString;
FSRef fileRef;
Boolean targetIsFolder;
Boolean wasAliased;
OSStatus osStatus;
ASSERT_ON_COMPILE(sizeof osStatus == sizeof (int32));
/*
* Create and resolve an FSRef of the desired path. We pass FALSE to
* resolveAliasChains because aliases to aliases should behave as
* symlinks to symlinks. If the file is an alias, wasAliased will be set to
* TRUE and fileRef will reference the target file.
*/
osStatus = FSPathMakeRef(fileName, &fileRef, NULL);
if (osStatus != noErr) {
LOG(4, ("HgfsGetattrResolveAlias: could not create file reference: "
"error %d\n", (int32)osStatus));
goto exit;
}
/*
* If alias points to an unmounted volume, the volume needs to be explicitly
* mounted on the host. Mount flag kResolveAliasFileNoUI serves the purpose.
*
* XXX: This function returns fnfErr (file not found) if it encounters a
* broken alias. Perhaps we should make that look like a dangling symlink
* instead of returning an error?
*
* XXX: It also returns errors if it encounters a file with a .alias suffix
* that isn't a real alias. That's OK for now because our caller
* (HgfsGetattrFromName) will assume that an error means the file is a
* regular file.
*/
osStatus = FSResolveAliasFileWithMountFlags(&fileRef, FALSE, &targetIsFolder,
&wasAliased, kResolveAliasFileNoUI);
if (osStatus != noErr) {
LOG(4, ("HgfsGetattrResolveAlias: could not resolve reference: error "
"%d\n", (int32)osStatus));
goto exit;
}
if (wasAliased) {
CFIndex maxPath;
/*
* This is somewhat convoluted. We create a CFURL from the FSRef because
* we want to call CFURLGetFileSystemRepresentation() to get a UTF-8
* string representing the target of the alias. But to call
* CFStringGetMaximumSizeOfFileSystemRepresentation(), we need a
* CFString, so we make one from the CFURL. Once we've got the max number
* of bytes for a filename on the filesystem, we allocate some memory
* and convert the CFURL to a basic UTF-8 string using a call to
* CFURLGetFileSystemRepresentation().
*/
resolvedRef = CFURLCreateFromFSRef(NULL, &fileRef);
if (resolvedRef == NULL) {
LOG(4, ("HgfsGetattrResolveAlias: could not create resolved URL "
"reference from resolved filesystem reference\n"));
goto exit;
}
resolvedString = CFURLGetString(resolvedRef);
if (resolvedString == NULL) {
LOG(4, ("HgfsGetattrResolveAlias: could not create resolved string "
"reference from resolved URL reference\n"));
goto exit;
}
maxPath = CFStringGetMaximumSizeOfFileSystemRepresentation(resolvedString);
myTargetName = malloc(maxPath);
if (myTargetName == NULL) {
LOG(4, ("HgfsGetattrResolveAlias: could not allocate %"FMTSZ"d bytes "
"of memory for target name storage\n", maxPath));
goto exit;
}
if (!CFURLGetFileSystemRepresentation(resolvedRef, FALSE, myTargetName,
maxPath)) {
LOG(4, ("HgfsGetattrResolveAlias: could not convert and copy "
"resolved URL reference into allocated buffer\n"));
goto exit;
}
*targetName = myTargetName;
LOG(4, ("HgfsGetattrResolveAlias: file was an alias\n"));
} else {
*targetName = NULL;
LOG(4, ("HgfsGetattrResolveAlias: file was not an alias\n"));
}
status = 0;
exit:
if (status != 0) {
free(myTargetName);
}
if (resolvedRef != NULL) {
CFRelease(resolvedRef);
}
return status;
#endif
}
/*
*-----------------------------------------------------------------------------
*
* HgfsGetHiddenAttr --
*
* For Mac hosts and Linux hosts, if a guest is Windows we force the "dot",
* files to be treated as hidden too in the Windows client by always setting
* the hidden attribute flag.
* Currently, this flag cannot be removed by Windows clients.
*
* Results:
* None.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static void
HgfsGetHiddenAttr(char const *fileName, // IN: Input filename
HgfsFileAttrInfo *attr) // OUT: Struct to copy into
{
char *baseName;
ASSERT(fileName);
ASSERT(attr);
baseName = strrchr(fileName, DIRSEPC);
if ((baseName != NULL) &&
(baseName[1] == '.') &&
(strcmp(&baseName[1], ".") != 0) &&
(strcmp(&baseName[1], "..") != 0)) {
attr->mask |= HGFS_ATTR_VALID_FLAGS;
attr->flags |= HGFS_ATTR_HIDDEN;
/*
* The request sets the forced flag so the client knows it is simulated
* and is not a real attribute, which can only happen on a Windows server.
* This allows the client to enforce some checks correctly if the flag
* is real or not.
* This replicates SMB behavior see bug 292189.
*/
attr->flags |= HGFS_ATTR_HIDDEN_FORCED;
} else {
Bool isHidden = FALSE;
/*
* Do not propagate any error returned from HgfsGetHiddenXAttr.
* Consider that the file is not hidden if can't get hidden attribute for
* whatever reason; most likely it fails because hidden attribute is not supported
* by the OS or file system.
*/
HgfsGetHiddenXAttr(fileName, &isHidden);
if (isHidden) {
attr->mask |= HGFS_ATTR_VALID_FLAGS;
attr->flags |= HGFS_ATTR_HIDDEN;
}
}
}
/*
*-----------------------------------------------------------------------------
*
* HgfsConvertComponentCase --
*
* Do a case insensitive search of a directory for the specified entry. If
* a matching entry is found, return it in the convertedComponent argument.
*
* Results:
* On Success:
* Returns 0 and the converted component name in the argument convertedComponent.
* The length for the convertedComponent is returned in convertedComponentSize.
*
* On Failure:
* Non-zero errno return, with convertedComponent and convertedComponentSize
* set to NULL and 0 respectively.
*
* Side effects:
* On success, allocated memory is returned in convertedComponent and needs
* to be freed.
*
*-----------------------------------------------------------------------------
*/
static int
HgfsConvertComponentCase(char *currentComponent, // IN
const char *dirPath, // IN
const char **convertedComponent, // OUT
size_t *convertedComponentSize) // OUT
{
struct dirent *dirent;
DIR *dir = NULL;
char *dentryName;
size_t dentryNameLen;
char *myConvertedComponent = NULL;
size_t myConvertedComponentSize;
int ret;
ASSERT(currentComponent);
ASSERT(dirPath);
ASSERT(convertedComponent);
ASSERT(convertedComponentSize);
/* Open the specified directory. */
dir = opendir(dirPath);
if (!dir) {
ret = errno;
goto exit;
}
/*
* Unicode_CompareIgnoreCase crashes with invalid unicode strings,
* validate it before passing it to Unicode_* functions.
*/
if (!Unicode_IsBufferValid(currentComponent, -1, STRING_ENCODING_UTF8)) {
/* Invalid unicode string, return failure. */
ret = EINVAL;
goto exit;
}
/*
* Read all of the directory entries. For each one, convert the name
* to lower case and then compare it to the lower case component.
*/
while ((dirent = readdir(dir))) {
Unicode dentryNameU;
int cmpResult;
dentryName = dirent->d_name;
dentryNameLen = strlen(dentryName);
/*
* Unicode_CompareIgnoreCase crashes with invalid unicode strings,
* validate and convert it appropriately before passing it to Unicode_* functions.
*/
if (!Unicode_IsBufferValid(dentryName, dentryNameLen, STRING_ENCODING_DEFAULT)) {
/* Invalid unicode string, skip the entry. */
continue;
}
dentryNameU = Unicode_Alloc(dentryName, STRING_ENCODING_DEFAULT);
cmpResult = Unicode_CompareIgnoreCase(currentComponent, dentryNameU);
Unicode_Free(dentryNameU);
if (cmpResult == 0) {
/*
* The current directory entry is a case insensitive match to
* the specified component. Malloc and copy the current directory entry.
*/
myConvertedComponentSize = dentryNameLen + 1;
myConvertedComponent = malloc(myConvertedComponentSize);
if (myConvertedComponent == NULL) {
ret = errno;
LOG(4, ("%s: failed to malloc myConvertedComponent.\n", __FUNCTION__));
goto exit;
}
Str_Strcpy(myConvertedComponent, dentryName, myConvertedComponentSize);
/* Success. Cleanup and exit. */
ret = 0;
*convertedComponentSize = myConvertedComponentSize;
*convertedComponent = myConvertedComponent;
goto exit;
}
}
/* We didn't find a match. Failure. */
ret = ENOENT;
exit:
if (dir) {
closedir(dir);
}
if (ret) {
*convertedComponent = NULL;
*convertedComponentSize = 0;
}
return ret;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsConstructConvertedPath --
*
* Expand the passed string and append the converted path.
*
* Results:
* Returns 0 if successful, errno on failure. Note that this
* function cannot return ENOENT.
*
* Side effects:
* Reallocs the path.
*
*-----------------------------------------------------------------------------
*/
static int
HgfsConstructConvertedPath(char **path, // IN/OUT
size_t *pathSize, // IN/OUT
char *convertedPath, // IN
size_t convertedPathSize) // IN
{
char *p;
size_t convertedPathLen = convertedPathSize - 1;
ASSERT(path);
ASSERT(*path);
ASSERT(convertedPath);
ASSERT(pathSize);
p = realloc(*path, *pathSize + convertedPathLen + sizeof (DIRSEPC));
if (!p) {
int error = errno;
LOG(4, ("%s: failed to realloc.\n", __FUNCTION__));
return error;
}
*path = p;
*pathSize += convertedPathLen + sizeof (DIRSEPC);
/* Copy out the converted component to curDir, and free it. */
Str_Strncat(p, *pathSize, DIRSEPS, sizeof (DIRSEPS));
Str_Strncat(p, *pathSize, convertedPath, convertedPathLen);
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsCaseInsensitiveLookup --
*
* Do a case insensitive lookup for fileName. Each component past sharePath is
* looked-up case-insensitively. Expensive!
*
* NOTE:
* shareName is always expected to be a prefix of fileName.
*
* Results:
* Returns 0 if successful and resolved path for fileName is returned in
* convertedFileName with its length in convertedFileNameLength.
* Otherwise returns non-zero errno with convertedFileName and
* convertedFileNameLength set to NULL and 0 respectively.
*
* Side effects:
* On success, allocated memory is returned in convertedFileName and needs
* to be freed.
*
*-----------------------------------------------------------------------------
*/
static int
HgfsCaseInsensitiveLookup(const char *sharePath, // IN
size_t sharePathLength, // IN
char *fileName, // IN
size_t fileNameLength, // IN
char **convertedFileName, // OUT
size_t *convertedFileNameLength) // OUT
{
char *currentComponent;
char *curDir;
char *nextComponent;
int error = ENOENT;
size_t curDirSize;
char *convertedComponent = NULL;
size_t convertedComponentSize = 0;
ASSERT(sharePath);
ASSERT(fileName);
ASSERT(convertedFileName);
ASSERT(fileNameLength >= sharePathLength);
currentComponent = fileName + sharePathLength;
/* Check there is something beyond the share name. */
if (*currentComponent == '\0') {
/*
* The fileName is the same as sharePath. Nothing else to do.
* Dup the string and return.
*/
*convertedFileName = strdup(fileName);
if (!*convertedFileName) {
error = errno;
*convertedFileName = NULL;
*convertedFileNameLength = 0;
LOG(4, ("%s: strdup on fileName failed.\n", __FUNCTION__));
} else {
*convertedFileNameLength = strlen(fileName);
}
return 0;
}
/* Skip a component separator if not in the share path. */
if (*currentComponent == DIRSEPC) {
currentComponent += 1;
}
curDirSize = sharePathLength + 1;
curDir = malloc(curDirSize);
if (!curDir) {
error = errno;
LOG(4, ("%s: failed to allocate for curDir\n", __FUNCTION__));
goto exit;
}
Str_Strcpy(curDir, sharePath, curDirSize);
while (TRUE) {
/* Get the next component. */
nextComponent = strchr(currentComponent, DIRSEPC);
if (nextComponent != NULL) {
*nextComponent = '\0';
}
/*
* Try to match the current component against the one in curDir.
* HgfsConvertComponentCase may return ENOENT. In that case return
* the path case-converted uptil now (curDir) and append to it the
* rest of the unconverted path.
*/
error = HgfsConvertComponentCase(currentComponent, curDir,
(const char **)&convertedComponent,
&convertedComponentSize);
/* Restore the path separator if we removed it earlier. */
if (nextComponent != NULL) {
*nextComponent = DIRSEPC;
}
if (error) {
if (error == ENOENT) {
int ret;
/*
* Copy out the components starting from currentComponent. We do this
* after replacing DIRSEPC, so all the components following
* currentComponent gets copied.
*/
ret = HgfsConstructConvertedPath(&curDir, &curDirSize, currentComponent,
strlen(currentComponent) + 1);
if (ret) {
error = ret;
}
}
if (error != ENOENT) {
free(curDir);
}
break;
}
/* Expand curDir and copy out the converted component. */
error = HgfsConstructConvertedPath(&curDir, &curDirSize, convertedComponent,
convertedComponentSize);
if (error) {
free(curDir);
free(convertedComponent);
break;
}
/* Free the converted component. */
free(convertedComponent);
/* If there is no component after the current one then we are done. */
if (nextComponent == NULL) {
/* Set success. */
error = 0;
break;
}
/*
* Set the current component pointer to point at the start of the next
* component.
*/
currentComponent = nextComponent + 1;
}
/* If the conversion was successful, return the result. */
if (error == 0 || error == ENOENT) {
*convertedFileName = curDir;
*convertedFileNameLength = curDirSize;
}
exit:
if (error && error != ENOENT) {
*convertedFileName = NULL;
*convertedFileNameLength = 0;
}
return error;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerConvertCase --
*
* Converts the fileName to appropriate case depending upon flags.
*
* Results:
* Returns HGFS_NAME_STATUS_COMPLETE if successful and converted
* path for fileName is returned in convertedFileName and it length in
* convertedFileNameLength.
*
* Otherwise returns non-zero integer without affecting fileName with
* convertedFileName and convertedFileNameLength set to NULL and 0
* respectively.
*
* Side effects:
* On success, allocated memory is returned in convertedFileName and needs
* to be freed.
*
*-----------------------------------------------------------------------------
*/
HgfsNameStatus
HgfsServerConvertCase(const char *sharePath, // IN
size_t sharePathLength, // IN
char *fileName, // IN
size_t fileNameLength, // IN
uint32 caseFlags, // IN
char **convertedFileName, // OUT
size_t *convertedFileNameLength) // OUT
{
int error = 0;
HgfsNameStatus nameStatus = HGFS_NAME_STATUS_COMPLETE;
ASSERT(sharePath);
ASSERT(fileName);
ASSERT(convertedFileName);
ASSERT(convertedFileNameLength);
*convertedFileName = NULL;
*convertedFileNameLength = 0;
/*
* Case-insensitive lookup is expensive, do it only if the flag is set
* and file is inaccessible using the case passed to us. We use access(2)
* call to check if the passed case of the file name is correct.
*/
if (caseFlags == HGFS_FILE_NAME_CASE_INSENSITIVE && access(fileName, F_OK) == -1) {
LOG(4, ("%s: Case insensitive lookup, fileName: %s, flags: %u.\n",
__FUNCTION__, fileName, caseFlags));
error = HgfsCaseInsensitiveLookup(sharePath, sharePathLength,
fileName, fileNameLength,
convertedFileName, convertedFileNameLength);
/*
* Success or non-ENOENT error code. HgfsCaseInsensitiveLookup can return ENOENT,
* and its ok to continue if it is ENOENT.
*/
switch (error) {
/*
* Both ENOENT and 0 mean that HgfsCaseInsensitiveLookup
* successfully built the converted name thus we return
* HGFS_NAME_STATUS_COMPLETE in these two cases.
*/
case 0:
case ENOENT:
nameStatus = HGFS_NAME_STATUS_COMPLETE;
break;
case ENOTDIR:
nameStatus = HGFS_NAME_STATUS_NOT_A_DIRECTORY;
break;
default:
nameStatus = HGFS_NAME_STATUS_FAILURE;
break;
}
return nameStatus;
}
*convertedFileName = strdup(fileName);
if (!*convertedFileName) {
nameStatus = HGFS_NAME_STATUS_OUT_OF_MEMORY;
LOG(4, ("%s: strdup on fileName failed.\n", __FUNCTION__));
} else {
*convertedFileNameLength = fileNameLength;
}
return nameStatus;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerCaseConversionRequired --
*
* Determines if the case conversion is required for this platform.
*
* Results:
* TRUE on Linux / Apple.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
Bool
HgfsServerCaseConversionRequired()
{
return TRUE;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsEffectivePermissions --
*
* Get permissions that are in efffect for the current user.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsEffectivePermissions(char *fileName, // IN: Input filename
Bool readOnlyShare, // IN: Share name
uint32 *permissions) // OUT: Effective permissions
{
*permissions = 0;
if (access(fileName, R_OK) == 0) {
*permissions |= HGFS_PERM_READ;
}
if (access(fileName, X_OK) == 0) {
*permissions |= HGFS_PERM_EXEC;
}
if (!readOnlyShare && (access(fileName, W_OK) == 0)) {
*permissions |= HGFS_PERM_WRITE;
}
return 0;
}
#if defined(__APPLE__)
/*
*-----------------------------------------------------------------------------
*
* HgfsConvertStat64ToStat --
*
* Helper function that converts data in stat64 format into stat format.
* It returns creationTime in HGFS platform independent format.
*
* Results:
* None.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static void
HgfsConvertStat64ToStat(const struct stat64 *stats64, // IN: data in stat64 format
struct stat *stats, // OUT: data in stat format
uint64 *creationTime) // OUT: creation time
{
stats->st_dev = stats64->st_dev;
stats->st_ino = stats64->st_ino;
stats->st_mode = stats64->st_mode;
stats->st_nlink = stats64->st_nlink;
stats->st_uid = stats64->st_uid;
stats->st_gid = stats64->st_gid;
stats->st_rdev = stats64->st_rdev;
stats->st_atimespec = stats64->st_atimespec;
stats->st_mtimespec = stats64->st_mtimespec;
stats->st_ctimespec = stats64->st_ctimespec;
stats->st_size = stats64->st_size;
stats->st_blocks = stats64->st_blocks;
stats->st_blksize = stats64->st_blksize;
stats->st_flags = stats64->st_flags;
stats->st_gen = stats64->st_gen;
*creationTime = HgfsConvertTimeSpecToNtTime(&stats64->st_birthtimespec);
}
#else
/*
*-----------------------------------------------------------------------------
*
* HgfsGetCreationTime --
*
* Calculates actual or emulated file creation time from stat structure.
* Definition of stat structure are different on diferent platforms.
* This function hides away all these differences and produces 64 bit value
* which should be reported to the client.
*
* Results:
* Value that should be used as a file creation time stamp.
* The resulting timestamp is in platform independent HGFS format.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static uint64
HgfsGetCreationTime(const struct stat *stats)
{
uint64 creationTime;
/*
* Linux and FreeBSD before v5 doesn't know about creation time; we just use the time
* of last data modification for the creation time.
* FreeBSD 5+ supprots file creation time.
*
* Using mtime when creation time is unavailable to be consistent with SAMBA.
*/
#ifdef __FreeBSD__
/*
* FreeBSD: All supported versions have timestamps with nanosecond resolution.
* FreeBSD 5+ has also file creation time.
*/
# if __IS_FREEBSD_VER__(500043)
creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_birthtimespec);
# else
creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtimespec);
# endif
#elif defined(linux)
/*
* Linux: Glibc 2.3+ has st_Xtim. Glibc 2.1/2.2 has st_Xtime/__unusedX on
* same place (see below). We do not support Glibc 2.0 or older.
*/
# if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 3)
/*
* stat structure is same between glibc 2.3 and older glibcs, just
* these __unused fields are always zero. If we'll use __unused*
* instead of zeroes, we get automatically nanosecond timestamps
* when running on host which provides them.
*/
creationTime = HgfsConvertToNtTime(stats->st_mtime, stats->__unused2);
# else
creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtim);
# endif
#else
/*
* Solaris: No nanosecond timestamps, no file create timestamp.
*/
creationTime = HgfsConvertToNtTime(stats->st_mtime, 0);
#endif
return creationTime;
}
#endif
/*
*-----------------------------------------------------------------------------
*
* HgfsStat --
*
* Wrapper function that invokes stat64 on Mac OS and stat on Linux (where stat64 is
* unavailable).
* Returns filled stat structure and a file creation time. File creation time is
* the birthday time for Mac OS and last write time for Linux (which does not support
* file creation time).
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static int
HgfsStat(const char* fileName, // IN: file name
Bool followLink, // IN: If true then follow symlink
struct stat *stats, // OUT: file attributes
uint64 *creationTime) // OUT: file creation time
{
int error;
#if defined(__APPLE__)
struct stat64 stats64;
if (followLink) {
error = stat64(fileName, &stats64);
} else {
error = lstat64(fileName, &stats64);
}
if (error == 0) {
HgfsConvertStat64ToStat(&stats64, stats, creationTime);
}
#else
if (followLink) {
error = Posix_Stat(fileName, stats);
} else {
error = Posix_Lstat(fileName, stats);
}
*creationTime = HgfsGetCreationTime(stats);
#endif
return error;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsFStat --
*
* Wrapper function that invokes stat64 on Mac OS and stat on Linux (where stat64 is
* unavailable).
* Returns filled stat structure and a file creation time. File creation time is
* the birthday time for Mac OS and last write time for Linux (which does not support
* file creation time).
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static int
HgfsFStat(int fd, // IN: file descriptor
struct stat *stats, // OUT: file attributes
uint64 *creationTime) // OUT: file creation time
{
int error = 0;
#if defined(__APPLE__)
struct stat64 stats64;
error = fstat64(fd, &stats64);
if (error == 0) {
HgfsConvertStat64ToStat(&stats64, stats, creationTime);
}
#else
if (fstat(fd, stats) < 0) {
error = errno;
}
*creationTime = HgfsGetCreationTime(stats);
#endif
return error;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsGetattrFromName --
*
* Performs a stat operation on the given filename, and, if it is a symlink,
* allocates the target filename on behalf of the caller and performs a
* readlink to get it. If not a symlink, the targetName argument is
* untouched. Does necessary translation between Unix file stats and the
* HgfsFileAttrInfo formats.
* NOTE: The function is different from HgfsGetAttrFromId: this function returns
* effectve permissions while HgfsGetAttrFromId does not.
* The reason for this asymmetry is that effective permissions are needed
* to get a new handle. If the file is already opened then
* getting effective permissions does not have any value. However getting
* effective permissions would hurt perfomance and should be avoided.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetattrFromName(char *fileName, // IN/OUT: Input filename
HgfsShareOptions configOptions, // IN: Share config options
char *shareName, // IN: Share name
HgfsFileAttrInfo *attr, // OUT: Struct to copy into
char **targetName) // OUT: Symlink target filename
{
HgfsInternalStatus status = 0;
struct stat stats;
int error;
char *myTargetName = NULL;
uint64 creationTime;
ASSERT(fileName);
ASSERT(attr);
LOG(4, ("HgfsGetattrFromName: getting attrs for \"%s\"\n", fileName));
error = HgfsStat(fileName,
HgfsServerPolicy_IsShareOptionSet(configOptions,
HGFS_SHARE_FOLLOW_SYMLINKS),
&stats,
&creationTime);
if (error) {
status = errno;
LOG(4, ("HgfsGetattrFromName: error stating file: %s\n",
strerror(status)));
goto exit;
}
/*
* Deal with the file type returned from lstat(2). We currently support
* regular files, directories, and symlinks. On Mac OS, we'll additionally
* treat finder aliases as symlinks.
*/
if (S_ISDIR(stats.st_mode)) {
attr->type = HGFS_FILE_TYPE_DIRECTORY;
LOG(4, ("HgfsGetattrFromName: is a directory\n"));
} else if (S_ISLNK(stats.st_mode)) {
attr->type = HGFS_FILE_TYPE_SYMLINK;
LOG(4, ("HgfsGetattrFromName: is a symlink\n"));
/*
* In the case of a symlink, we should populate targetName if the
* caller asked. Use st_size and readlink() to do so.
*/
if (targetName != NULL) {
myTargetName = Posix_ReadLink(fileName);
if (myTargetName == NULL) {
error = errno;
LOG(4, ("HgfsGetattrFromName: readlink returned wrong size\n"));
/*
* Because of an unavoidable race between the lstat(2) and the
* readlink(2), the symlink target may have lengthened and we may
* not have read the entire link. If that happens, just return
* "out of memory".
*/
status = error ? error : ENOMEM;
goto exit;
}
}
} else {
/*
* Now is a good time to check if the file was an alias. If so, we'll
* treat it as a symlink.
*
* XXX: If HgfsGetattrResolveAlias fails, we'll treat the file as a
* regular file. This isn't completely correct (the function may have
* failed because we're out of memory), but it's better than having to
* call LScopyItemInfoForRef for each file, which may negatively affect
* performance. See:
*
* http://lists.apple.com/archives/carbon-development/2001/Nov/msg00007.html
*/
LOG(4, ("HgfsGetattrFromName: NOT a directory or symlink\n"));
if (HgfsGetattrResolveAlias(fileName, &myTargetName)) {
LOG(4, ("HgfsGetattrFromName: could not resolve file aliases\n"));
}
attr->type = HGFS_FILE_TYPE_REGULAR;
if (myTargetName != NULL) {
/*
* At this point the alias target has been successfully resolved. If the alias
* target is inside the same shared folder then convert it to relative path.
* Converting to a relative path produces a symlink that points to the target
* file in the guest OS.
* If the target lies outside the shared folder then treat it the same way as
* if alias has not been resolved.
*/
HgfsNameStatus nameStatus;
size_t sharePathLen;
const char* sharePath;
nameStatus = HgfsServerPolicy_GetSharePath(shareName,
strlen(shareName),
HGFS_OPEN_MODE_READ_ONLY,
&sharePathLen,
&sharePath);
if (nameStatus == HGFS_NAME_STATUS_COMPLETE &&
sharePathLen < strlen(myTargetName) &&
Str_Strncmp(sharePath, myTargetName, sharePathLen) == 0) {
char *relativeName;
relativeName = HgfsBuildRelativePath(fileName, myTargetName);
free(myTargetName);
myTargetName = relativeName;
if (myTargetName != NULL) {
/*
* Let's mangle the permissions and size of the file so that it more
* closely resembles a symlink. The size should be the length of the
* target name (not including the nul-terminator), and the permissions
* should be 777.
*/
stats.st_size = strlen(myTargetName);
stats.st_mode |= ACCESSPERMS;
attr->type = HGFS_FILE_TYPE_SYMLINK;
} else {
LOG(4, ("HgfsGetattrFromName: out of memory\n"));
}
} else {
LOG(4, ("HgfsGetattrFromName: alias target is outside shared folder\n"));
}
}
}
if (myTargetName != NULL && targetName != NULL) {
#if defined(__APPLE__)
/*
* HGFS clients will expect filenames in unicode normal form C
* (precomposed) so Mac hosts must convert from normal form D
* (decomposed).
*/
if (!CodeSet_Utf8FormDToUtf8FormC(myTargetName,
strlen(myTargetName),
targetName,
NULL)) {
LOG(4, ("HgfsGetattrFromName: Unable to normalize form C "
"\"%s\"\n", myTargetName));
status = HgfsConvertFromNameStatus(HGFS_NAME_STATUS_FAILURE);
goto exit;
}
#else
*targetName = myTargetName;
myTargetName = NULL;
#endif
}
HgfsStatToFileAttr(&stats, &creationTime, attr);
/*
* In the case we have a Windows client, force the hidden flag.
* This will be ignored by Linux, Solaris clients.
*/
HgfsGetHiddenAttr(fileName, attr);
/* Get effective permissions if we can */
if (!(S_ISLNK(stats.st_mode))) {
HgfsOpenMode shareMode;
uint32 permissions;
HgfsNameStatus nameStatus;
nameStatus = HgfsServerPolicy_GetShareMode(shareName, strlen(shareName),
&shareMode);
if (nameStatus == HGFS_NAME_STATUS_COMPLETE &&
HgfsEffectivePermissions(fileName,
shareMode == HGFS_OPEN_MODE_READ_ONLY,
&permissions) == 0) {
attr->mask |= HGFS_ATTR_VALID_EFFECTIVE_PERMS;
attr->effectivePerms = permissions;
}
}
exit:
free(myTargetName);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsAccess --
*
* Check is a file with the given name exists and accessible, error code
* otherwise.
* The function does not follow symlinks unless HGFS_SHARE_FOLLOW_SYMLINKS
* flag is specified for the shared folder.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsAccess(char *fileName, // IN: local file path
char *shareName, // IN: Name of the share
size_t shareNameLen) // IN: Length of the share name
{
HgfsFileAttrInfo attr;
HgfsShareOptions configOptions;
HgfsNameStatus nameStatus;
HgfsInternalStatus status;
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(shareName, shareNameLen,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, shareName));
status = ENOENT;
} else {
status = HgfsGetattrFromName(fileName, configOptions, shareName,
&attr, NULL);
}
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsGetattrFromFd --
*
* Performs a stat operation on the given file desc.
* Does necessary translation between Unix file stats and the
* HgfsFileAttrInfo formats.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetattrFromFd(int fd, // IN: file descriptor
HgfsSessionInfo *session, // IN: session info
HgfsFileAttrInfo *attr) // OUT: FileAttrInfo to copy into
{
HgfsInternalStatus status = 0;
struct stat stats;
int error;
HgfsOpenMode shareMode;
HgfsHandle handle = HGFS_INVALID_HANDLE;
char *fileName = NULL;
size_t fileNameLen;
uint64 creationTime;
ASSERT(attr);
ASSERT(session);
LOG(4, ("HgfsGetattrFromFd: getting attrs for %u\n", fd));
error = HgfsFStat(fd, &stats, &creationTime);
if (error) {
LOG(4, ("HgfsGetattrFromFd: error stating file: %s\n", strerror(error)));
status = error;
goto exit;
}
/*
* For now, everything that isn't a directory or symlink is a regular
* file.
*/
if (S_ISDIR(stats.st_mode)) {
attr->type = HGFS_FILE_TYPE_DIRECTORY;
LOG(4, ("HgfsGetattrFromFd: is a directory\n"));
} else if (S_ISLNK(stats.st_mode)) {
attr->type = HGFS_FILE_TYPE_SYMLINK;
LOG(4, ("HgfsGetattrFromFd: is a symlink\n"));
} else {
attr->type = HGFS_FILE_TYPE_REGULAR;
LOG(4, ("HgfsGetattrFromFd: NOT a directory or symlink\n"));
}
HgfsStatToFileAttr(&stats, &creationTime, attr);
/*
* XXX - Correct share mode checking should be fully implemented.
*
* For now, we must ensure that the client only sees read only
* attributes when the share is read only. This allows the client
* to make decisions to fail write/delete operations.
* It is required by clients who use file handles that
* are cached, for setting attributes, renaming and deletion.
*/
if (!HgfsFileDesc2Handle(fd, session, &handle)) {
LOG(4, ("HgfsGetattrFromFd: could not get HGFS handle for fd %u\n",
fd));
status = EBADF;
goto exit;
}
if (!HgfsHandle2ShareMode(handle, session, &shareMode)) {
LOG(4, ("HgfsGetattrFromFd: could not get share mode fd %u\n",
fd));
status = EBADF;
goto exit;
}
if (!HgfsHandle2FileName(handle, session, &fileName, &fileNameLen)) {
LOG(4, ("HgfsGetattrFromFd: could not map cached target file handle %u\n",
handle));
status = EBADF;
goto exit;
}
/*
* In the case we have a Windows client, force the hidden flag.
* This will be ignored by Linux, Solaris clients.
*/
HgfsGetHiddenAttr(fileName, attr);
if (shareMode == HGFS_OPEN_MODE_READ_ONLY) {
/*
* Share does not allow write, so tell the client
* everything is read only.
*/
if (attr->mask & HGFS_ATTR_VALID_OWNER_PERMS) {
attr->ownerPerms &= ~HGFS_PERM_WRITE;
}
if (attr->mask & HGFS_ATTR_VALID_GROUP_PERMS) {
attr->groupPerms &= ~HGFS_PERM_WRITE;
}
if (attr->mask & HGFS_ATTR_VALID_OTHER_PERMS) {
attr->otherPerms &= ~HGFS_PERM_WRITE;
}
}
exit:
free(fileName);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsStatToFileAttr --
*
* Does necessary translation between Unix file stats and the
* HgfsFileAttrInfo formats.
* It expects creationTime to be in platform-independent HGFS format and
* stats in a platform-specific stat format.
*
* Results:
* None.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static void
HgfsStatToFileAttr(struct stat *stats, // IN: stat information
uint64 *creationTime, // IN: file creation time
HgfsFileAttrInfo *attr) // OUT: FileAttrInfo to copy into
{
attr->size = stats->st_size;
attr->creationTime = *creationTime;
#ifdef __FreeBSD__
/*
* FreeBSD: All supported versions have timestamps with nanosecond resolution.
* FreeBSD 5+ has also file creation time.
*/
attr->accessTime = HgfsConvertTimeSpecToNtTime(&stats->st_atimespec);
attr->writeTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtimespec);
attr->attrChangeTime = HgfsConvertTimeSpecToNtTime(&stats->st_ctimespec);
#elif defined(linux)
/*
* Linux: Glibc 2.3+ has st_Xtim. Glibc 2.1/2.2 has st_Xtime/__unusedX on
* same place (see below). We do not support Glibc 2.0 or older.
*/
# if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 3)
/*
* stat structure is same between glibc 2.3 and older glibcs, just
* these __unused fields are always zero. If we'll use __unused*
* instead of zeroes, we get automatically nanosecond timestamps
* when running on host which provides them.
*/
attr->accessTime = HgfsConvertToNtTime(stats->st_atime, stats->__unused1);
attr->writeTime = HgfsConvertToNtTime(stats->st_mtime, stats->__unused2);
attr->attrChangeTime = HgfsConvertToNtTime(stats->st_ctime, stats->__unused3);
# else
attr->accessTime = HgfsConvertTimeSpecToNtTime(&stats->st_atim);
attr->writeTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtim);
attr->attrChangeTime = HgfsConvertTimeSpecToNtTime(&stats->st_ctim);
# endif
#else
/*
* Solaris, Mac OS: No nanosecond timestamps.
*/
attr->accessTime = HgfsConvertToNtTime(stats->st_atime, 0);
attr->writeTime = HgfsConvertToNtTime(stats->st_mtime, 0);
attr->attrChangeTime = HgfsConvertToNtTime(stats->st_ctime, 0);
#endif
attr->specialPerms = (stats->st_mode & (S_ISUID | S_ISGID | S_ISVTX)) >> 9;
attr->ownerPerms = (stats->st_mode & S_IRWXU) >> 6;
attr->groupPerms = (stats->st_mode & S_IRWXG) >> 3;
attr->otherPerms = stats->st_mode & S_IRWXO;
LOG(4, ("HgfsStatToFileAttr: done, permissions %o%o%o%o, size %"FMT64"u\n",
attr->specialPerms, attr->ownerPerms, attr->groupPerms,
attr->otherPerms, attr->size));
#ifdef __FreeBSD__
# if !defined(VM_X86_64) && __FreeBSD_version >= 500043
# define FMTTIMET ""
# else
# define FMTTIMET "l"
# endif
#else
# define FMTTIMET "l"
#endif
LOG(4, ("access: %"FMTTIMET"d/%"FMT64"u \nwrite: %"FMTTIMET"d/%"FMT64"u \n"
"attr: %"FMTTIMET"d/%"FMT64"u\n",
stats->st_atime, attr->accessTime, stats->st_mtime, attr->writeTime,
stats->st_ctime, attr->attrChangeTime));
#undef FMTTIMET
attr->userId = stats->st_uid;
attr->groupId = stats->st_gid;
attr->hostFileId = stats->st_ino;
attr->volumeId = stats->st_dev;
attr->mask = HGFS_ATTR_VALID_TYPE |
HGFS_ATTR_VALID_SIZE |
HGFS_ATTR_VALID_CREATE_TIME |
HGFS_ATTR_VALID_ACCESS_TIME |
HGFS_ATTR_VALID_WRITE_TIME |
HGFS_ATTR_VALID_CHANGE_TIME |
HGFS_ATTR_VALID_SPECIAL_PERMS |
HGFS_ATTR_VALID_OWNER_PERMS |
HGFS_ATTR_VALID_GROUP_PERMS |
HGFS_ATTR_VALID_OTHER_PERMS |
HGFS_ATTR_VALID_USERID |
HGFS_ATTR_VALID_GROUPID |
HGFS_ATTR_VALID_FILEID |
HGFS_ATTR_VALID_VOLID;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetattrMode --
*
* Set the permissions based on stat and attributes.
*
* Results:
* TRUE if permissions have changed.
* FALSE otherwise.
*
* Note that newPermissions is always set.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static Bool
HgfsSetattrMode(struct stat *statBuf, // IN: stat info
HgfsFileAttrInfo *attr, // IN: attrs to set
mode_t *newPermissions) // OUT: new perms
{
Bool permsChanged = FALSE;
ASSERT(statBuf);
ASSERT(attr);
ASSERT(newPermissions);
*newPermissions = ~ALLPERMS;
if (attr->mask & HGFS_ATTR_VALID_SPECIAL_PERMS) {
*newPermissions |= attr->specialPerms << 9;
permsChanged = TRUE;
} else {
*newPermissions |= statBuf->st_mode & (S_ISUID | S_ISGID | S_ISVTX);
}
if (attr->mask & HGFS_ATTR_VALID_OWNER_PERMS) {
*newPermissions |= attr->ownerPerms << 6;
permsChanged = TRUE;
} else {
*newPermissions |= statBuf->st_mode & S_IRWXU;
}
if (attr->mask & HGFS_ATTR_VALID_GROUP_PERMS) {
*newPermissions |= attr->groupPerms << 3;
permsChanged = TRUE;
} else {
*newPermissions |= statBuf->st_mode & S_IRWXG;
}
if (attr->mask & HGFS_ATTR_VALID_OTHER_PERMS) {
*newPermissions |= attr->otherPerms;
permsChanged = TRUE;
} else {
*newPermissions |= statBuf->st_mode & S_IRWXO;
}
return permsChanged;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetattrOwnership --
*
* Set the user and group ID based the attributes.
*
* Results:
* TRUE if ownership has changed.
* FALSE otherwise.
*
* Note that newUid/newGid are always set.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static Bool
HgfsSetattrOwnership(HgfsFileAttrInfo *attr, // IN: attrs to set
uid_t *newUid, // OUT: new user ID
gid_t *newGid) // OUT: new group ID
{
Bool idChanged = FALSE;
ASSERT(attr);
ASSERT(newUid);
ASSERT(newGid);
*newUid = *newGid = -1;
if (attr->mask & HGFS_ATTR_VALID_USERID) {
*newUid = attr->userId;
idChanged = TRUE;
}
if (attr->mask & HGFS_ATTR_VALID_GROUPID) {
*newGid = attr->groupId;
idChanged = TRUE;
}
return idChanged;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetattrTimes --
*
* Set the time stamps based on stat and attributes.
*
* Results:
* Zero on success. accessTime/modTime contain new times.
* Non-zero on failure.
*
* Note that timesChanged is always set.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsSetattrTimes(struct stat *statBuf, // IN: stat info
HgfsFileAttrInfo *attr, // IN: attrs to set
HgfsAttrHint hints, // IN: attr hints
struct timeval *accessTime, // OUT: access time
struct timeval *modTime, // OUT: modification time
Bool *timesChanged) // OUT: times changed
{
HgfsInternalStatus status = 0;
int error;
ASSERT(statBuf);
ASSERT(attr);
ASSERT(accessTime);
ASSERT(modTime);
ASSERT(timesChanged);
*timesChanged = FALSE;
if (attr->mask & (HGFS_ATTR_VALID_ACCESS_TIME |
HGFS_ATTR_VALID_WRITE_TIME)) {
/*
* utime(2) only lets you update both atime and mtime at once, so
* if either one needs updating, first we get the current times
* and call utime with some combination of the current and new
* times. This is a bit racy because someone else could update
* one of them in between, but this seems to be how "touch" does
* things, so we'll go with it. [bac]
*/
if ((attr->mask & (HGFS_ATTR_VALID_ACCESS_TIME |
HGFS_ATTR_VALID_WRITE_TIME))
!= (HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME)) {
/*
* XXX Set also usec from nsec stat fields.
*/
accessTime->tv_sec = statBuf->st_atime;
accessTime->tv_usec = 0;
modTime->tv_sec = statBuf->st_mtime;
modTime->tv_usec = 0;
}
/*
* If times need updating, we either use the guest-provided time or the
* host time. HGFS_ATTR_HINT_SET_x_TIME_ will be set if we should use
* the guest time, and alwaysUseHostTime will be TRUE if the config
* option to always use host time is set.
*/
if (attr->mask & HGFS_ATTR_VALID_ACCESS_TIME) {
if (!alwaysUseHostTime && (hints & HGFS_ATTR_HINT_SET_ACCESS_TIME)) {
/* Use the guest-provided time */
struct timespec ts;
HgfsConvertFromNtTimeNsec(&ts, attr->accessTime);
accessTime->tv_sec = ts.tv_sec;
accessTime->tv_usec = ts.tv_nsec / 1000;
} else {
/* Use the host's time */
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0) {
error = errno;
LOG(4, ("HgfsSetattrTimes: gettimeofday error: %s\n",
strerror(error)));
status = error;
goto exit;
}
accessTime->tv_sec = tv.tv_sec;
accessTime->tv_usec = tv.tv_usec;
}
}
if (attr->mask & HGFS_ATTR_VALID_WRITE_TIME) {
if (!alwaysUseHostTime && (hints & HGFS_ATTR_HINT_SET_WRITE_TIME)) {
struct timespec ts;
HgfsConvertFromNtTimeNsec(&ts, attr->writeTime);
modTime->tv_sec = ts.tv_sec;
modTime->tv_usec = ts.tv_nsec / 1000;
} else {
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0) {
error = errno;
LOG(4, ("HgfsSetattrTimes: gettimeofday error: %s\n",
strerror(error)));
status = error;
goto exit;
}
modTime->tv_sec = tv.tv_sec;
modTime->tv_usec = tv.tv_usec;
}
}
*timesChanged = TRUE;
}
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetattrFromFd --
*
* Handle a Setattr request by file descriptor.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsSetattrFromFd(HgfsHandle file, // IN: file descriptor
HgfsSessionInfo *session, // IN: session info
HgfsFileAttrInfo *attr, // OUT: attrs to set
HgfsAttrHint hints) // IN: attr hints
{
HgfsInternalStatus status = 0, timesStatus;
int error;
struct stat statBuf;
struct timeval times[2];
mode_t newPermissions;
uid_t newUid = -1;
gid_t newGid = -1;
Bool permsChanged = FALSE;
Bool timesChanged = FALSE;
Bool idChanged = FALSE;
int fd;
HgfsServerLock serverLock;
HgfsOpenMode shareMode;
ASSERT(session);
ASSERT(file != HGFS_INVALID_HANDLE);
status = HgfsGetFd(file, session, FALSE, &fd);
if (status != 0) {
LOG(4, ("HgfsSetattrFromFd: Could not get file descriptor\n"));
goto exit;
}
if (!HgfsHandle2ShareMode(file, session, &shareMode)) {
LOG(4, ("HgfsSetattrFromFd: could not get share mode fd %u\n",
fd));
status = EBADF;
goto exit;
}
if (shareMode == HGFS_OPEN_MODE_READ_ONLY) {
status = EACCES;
goto exit;
}
/* We need the old stats so that we can preserve times. */
if (fstat(fd, &statBuf) == -1) {
error = errno;
LOG(4, ("HgfsSetattrFromFd: error stating file %u: %s\n",
fd, strerror(error)));
status = error;
goto exit;
}
/*
* Try to make each requested attribute change. In the event that
* one operation fails, we still attempt to perform any other
* operations that the driver requested. We return success only
* if all operations succeeded.
*/
/*
* Set permissions based on what we got in the packet. If we didn't get
* a particular bit, use the existing permissions. In that case we don't
* toggle permsChanged since it should not influence our decision of
* whether to actually call chmod or not.
*/
permsChanged = HgfsSetattrMode(&statBuf, attr, &newPermissions);
if (permsChanged) {
LOG(4, ("HgfsSetattrFromFd: set mode %o\n", (unsigned)newPermissions));
if (fchmod(fd, newPermissions) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromFd: error chmoding file %u: %s\n",
fd, strerror(error)));
status = error;
}
}
idChanged = HgfsSetattrOwnership(attr, &newUid, &newGid);
if (idChanged) {
LOG(4, ("HgfsSetattrFromFd: set uid %"FMTUID" and gid %"FMTUID"\n",
newUid, newGid));
if (fchown(fd, newUid, newGid) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromFd: error chowning file %u: %s\n",
fd, strerror(error)));
status = error;
}
}
if (attr->mask & HGFS_ATTR_VALID_SIZE) {
/*
* XXX: Truncating the file will trigger an oplock break. The client
* should have predicted this and removed the oplock prior to sending
* the truncate request. At this point, the server must safeguard itself
* against deadlock.
*/
if (!HgfsHandle2ServerLock(file, session, &serverLock)) {
LOG(4, ("HgfsSetattrFromFd: File handle is no longer valid.\n"));
status = EBADF;
} else if (serverLock != HGFS_LOCK_NONE) {
LOG(4, ("HgfsSetattrFromFd: Client attempted to truncate an "
"oplocked file\n"));
status = EBUSY;
} else if (ftruncate(fd, attr->size) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromFd: error truncating file %u: %s\n",
fd, strerror(error)));
status = error;
} else {
LOG(4, ("HgfsSetattrFromFd: set size %"FMT64"u\n", attr->size));
}
}
if (attr->mask & HGFS_ATTR_VALID_FLAGS) {
char *localName;
size_t localNameSize;
if (HgfsHandle2FileName(file, session, &localName, &localNameSize)) {
status = HgfsSetHiddenXAttr(localName, attr->flags & HGFS_ATTR_HIDDEN);
free(localName);
}
}
timesStatus = HgfsSetattrTimes(&statBuf, attr, hints,
×[0], ×[1], ×Changed);
if (timesStatus == 0 && timesChanged) {
uid_t uid;
LOG(4, ("HgfsSetattrFromFd: setting new times\n"));
/*
* If the VMX is either the file owner or running as root, switch to
* superuser briefly to set the files times using futimes. Otherwise
* return an error.
*/
if (!Id_IsSuperUser() && (getuid() != statBuf.st_uid)) {
LOG(4, ("HgfsSetattrFromFd: only owner of file %u or root can call "
"futimes\n", fd));
/* XXX: Linux kernel says both EPERM and EACCES are valid here. */
status = EPERM;
goto exit;
}
uid = Id_BeginSuperUser();
/*
* XXX Newer glibc provide also lutimes() and futimes()
* when we politely ask with -D_GNU_SOURCE -D_BSD_SOURCE
*/
if (futimes(fd, times) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromFd: futimes error on file %u: %s\n",
fd, strerror(error)));
status = error;
}
Id_EndSuperUser(uid);
} else if (timesStatus != 0) {
status = timesStatus;
}
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetattrFromName --
*
* Handle a Setattr request by name.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsSetattrFromName(char *cpName, // IN: Name
size_t cpNameSize, // IN: Name length
HgfsFileAttrInfo *attr, // IN: attrs to set
HgfsAttrHint hints, // IN: attr hints
uint32 caseFlags, // IN: case-sensitivity flags
HgfsSessionInfo *session) // IN: session info
{
HgfsInternalStatus status = 0, timesStatus;
HgfsNameStatus nameStatus;
int error, fd;
char *localName;
struct stat statBuf;
struct timeval times[2];
mode_t newPermissions;
uid_t newUid = -1;
gid_t newGid = -1;
Bool permsChanged = FALSE;
Bool timesChanged = FALSE;
Bool idChanged = FALSE;
HgfsServerLock serverLock;
HgfsShareOptions configOptions;
size_t localNameLen;
HgfsShareInfo shareInfo;
nameStatus = HgfsServerGetShareInfo(cpName,
cpNameSize,
caseFlags,
&shareInfo,
&localName,
&localNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsSetattrFromName: access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
ASSERT(localName);
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(cpName, cpNameSize,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsSetattrFromName: no matching share: %s.\n", cpName));
goto exit;
}
if (!HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS)) {
/*
* If followSymlink option is not set, verify that the pathname isn't a
* symlink. Some of the following syscalls (chmod, for example) will follow
* a link. So we need to verify the final component too. The parent has
* already been verified in HgfsServerGetAccess.
*
* XXX: This is racy. But clients interested in preventing a race should
* have sent us a Setattr packet with a valid HGFS handle.
*/
if (File_IsSymLink(localName)) {
LOG(4, ("HgfsSetattrFromName: pathname contains a symlink\n"));
status = EINVAL;
goto exit_free;
}
}
LOG(4, ("HgfsSetattrFromName: setting attrs for \"%s\"\n", localName));
/* We need the old stats so that we can preserve times. */
if (Posix_Lstat(localName, &statBuf) == -1) {
error = errno;
LOG(4, ("HgfsSetattrFromName: error stating file \"%s\": %s\n",
localName, strerror(error)));
status = error;
goto exit_free;
}
if (!HgfsServerPolicy_CheckMode(HGFS_OPEN_MODE_WRITE_ONLY,
shareInfo.writePermissions,
shareInfo.readPermissions)) {
status = EACCES;
goto exit_free;
}
/*
* Try to make each requested attribute change. In the event that
* one operation fails, we still attempt to perform any other
* operations that the driver requested. We return success only
* if all operations succeeded.
*/
/*
* Set permissions based on what we got in the packet. If we didn't get
* a particular bit, use the existing permissions. In that case we don't
* toggle permsChanged since it should not influence our decision of
* whether to actually call chmod or not.
*/
permsChanged = HgfsSetattrMode(&statBuf, attr, &newPermissions);
if (permsChanged) {
LOG(4, ("HgfsSetattrFromName: set mode %o\n", (unsigned)newPermissions));
if (Posix_Chmod(localName, newPermissions) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromName: error chmoding file \"%s\": %s\n",
localName, strerror(error)));
status = error;
}
}
idChanged = HgfsSetattrOwnership(attr, &newUid, &newGid);
/*
* Chown changes the uid and gid together. If one of them should
* not be changed, we pass in -1.
*/
if (idChanged) {
if (Posix_Lchown(localName, newUid, newGid) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromName: error chowning file \"%s\": %s\n",
localName, strerror(error)));
status = error;
}
}
if (attr->mask & HGFS_ATTR_VALID_SIZE) {
/*
* XXX: Truncating the file will trigger an oplock break. The client
* should have predicted this and removed the oplock prior to sending
* the truncate request. At this point, the server must safeguard itself
* against deadlock.
*/
if (HgfsFileHasServerLock(localName, session, &serverLock, &fd)) {
LOG(4, ("HgfsSetattrFromName: Client attempted to truncate an "
"oplocked file\n"));
status = EBUSY;
} else if (Posix_Truncate(localName, attr->size) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromName: error truncating file \"%s\": %s\n",
localName, strerror(error)));
status = error;
} else {
LOG(4, ("HgfsSetattrFromName: set size %"FMT64"u\n", attr->size));
}
}
if (attr->mask & HGFS_ATTR_VALID_FLAGS) {
status = HgfsSetHiddenXAttr(localName, attr->flags & HGFS_ATTR_HIDDEN);
}
timesStatus = HgfsSetattrTimes(&statBuf, attr, hints,
×[0], ×[1], ×Changed);
if (timesStatus == 0 && timesChanged) {
/*
* XXX Newer glibc provide also lutimes() and futimes()
* when we politely ask with -D_GNU_SOURCE -D_BSD_SOURCE
*/
if (Posix_Utimes(localName, times) < 0) {
error = errno;
LOG(4, ("HgfsSetattrFromName: utimes error on file \"%s\": %s\n",
localName, strerror(error)));
status = error;
}
} else if (timesStatus != 0) {
status = timesStatus;
}
exit_free:
free(localName);
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerScandir --
*
* The cross-platform HGFS server code will call into this function
* in order to populate a list of dents. In the Linux case, we want to avoid
* using scandir(3) because it makes no provisions for not following
* symlinks. Instead, we'll open(2) the directory with O_DIRECTORY and
* O_NOFOLLOW, call getdents(2) directly, then close(2) the directory.
*
* Results:
* Zero on success. numDents contains the number of directory entries found.
* Non-zero on error.
*
* Side effects:
* Memory allocation.
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerScandir(char const *baseDir, // IN: Directory to search in
size_t baseDirLen, // IN: Ignored
Bool followSymlinks, // IN: followSymlinks config option
DirectoryEntry ***dents, // OUT: Array of DirectoryEntrys
int *numDents) // OUT: Number of DirectoryEntrys
{
int fd = -1, result;
DirectoryEntry **myDents = NULL;
int myNumDents = 0;
HgfsInternalStatus status = 0;
int openFlags = O_NONBLOCK | O_RDONLY | O_DIRECTORY | O_NOFOLLOW;
/*
* XXX: glibc uses 8192 (BUFSIZ) when it can't get st_blksize from a stat.
* Should we follow its lead and use stat to get st_blksize?
*/
char buffer[8192];
/* Follow symlinks if config option is set. */
if (followSymlinks) {
openFlags &= ~O_NOFOLLOW;
}
/* We want a directory. No FIFOs. Symlinks only if config option is set. */
result = Posix_Open(baseDir, openFlags);
if (result < 0) {
status = errno;
LOG(4, ("HgfsServerScandir: error in open: %d (%s)\n", status,
strerror(status)));
goto exit;
}
fd = result;
/*
* Rather than read a single dent at a time, batch up multiple dents
* in each call by using a buffer substantially larger than one dent.
*/
while ((result = getdents(fd, (void *)buffer,
sizeof buffer)) > 0) {
size_t offset = 0;
while (offset < result) {
DirectoryEntry *newDent, **newDents;
newDent = (DirectoryEntry *)(buffer + offset);
/* This dent had better fit in the actual space we've got left. */
ASSERT(newDent->d_reclen <= result - offset);
/* Add another dent pointer to the dents array. */
newDents = realloc(myDents, sizeof *myDents * (myNumDents + 1));
if (newDents == NULL) {
status = ENOMEM;
goto exit;
}
myDents = newDents;
/*
* Allocate the new dent and set it up. We do a straight memcpy of
* the entire record to avoid dealing with platform-specific fields.
*/
myDents[myNumDents] = malloc(newDent->d_reclen);
if (myDents[myNumDents] == NULL) {
status = ENOMEM;
goto exit;
}
memcpy(myDents[myNumDents], newDent, newDent->d_reclen);
/*
* Dent is done. Bump the offset to the batched buffer to process the
* next dent within it.
*/
myNumDents++;
offset += newDent->d_reclen;
}
}
if (result == -1) {
status = errno;
LOG(4, ("HgfsServerScandir: error in getdents: %d (%s)\n", status,
strerror(status)));
goto exit;
}
exit:
if (fd != -1 && close(fd) < 0) {
status = errno;
LOG(4, ("HgfsServerScandir: error in close: %d (%s)\n", status,
strerror(status)));
}
/*
* On error, free all allocated dents. On success, set the dents pointer
* given to us by the client.
*/
if (status != 0) {
size_t i;
for (i = 0; i < myNumDents; i++) {
free(myDents[i]);
}
free(myDents);
} else {
*dents = myDents;
*numDents = myNumDents;
}
return status;
}
/*
*----------------------------------------------------------------------
*
* Request Handler Functions
* -------------------------
*
* The functions that follow are all of the same type: they take a
* request packet which came from the driver, process it, and fill out
* a reply packet which is then sent back to the driver. They are
* called by DispatchPacket, which dispatches an incoming packet to
* the correct handler function based on the packet's opcode.
*
* These functions all take the following as input:
*
* - A pointer to a buffer containing the incoming request packet,
* - A pointer to a buffer big enough to hold the outgoing reply packet,
* - A pointer to the size of the incoming packet, packetSize.
*
* After processing the request, the handler functions write the reply
* packet into the output buffer and set the packetSize to be the size
* of the OUTGOING reply packet. The ServerLoop function uses the size
* to send the reply back to the driver.
*
* Note that it is potentially okay for the caller to use the same
* buffer for both input and output; handler functions should make
* sure they are safe w.r.t. this possibility by storing any state
* from the input buffer before they clobber it by potentially writing
* output into the same buffer.
*
* Handler functions should return zero if they successfully processed
* the request, or a negative error if an unrecoverable error
* occurred. Normal errors (e.g. a poorly formed request packet)
* should be handled by sending an error packet back to the driver,
* NOT by returning an error code to the caller, because errors
* returned by handler functions cause the server to terminate.
*
* [bac]
*
*----------------------------------------------------------------------
*/
/*
*-----------------------------------------------------------------------------
*
* HgfsServerOpen --
*
* Handle an Open request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerOpen(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsNameStatus nameStatus;
HgfsInternalStatus status;
int newFd = -1;
HgfsLocalId localId;
HgfsFileOpenInfo openInfo;
char *localName = NULL;
HgfsServerLock serverLock = HGFS_LOCK_NONE;
HgfsShareOptions configOptions;
int followSymlinks;
char *packetOut;
size_t packetOutSize;
HgfsOpenFlags savedOpenFlags = 0;
size_t localNameLen;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackOpenRequest(packetIn, packetSize, &openInfo)) {
status = EPROTO;
goto exit;
}
/* HGFS_OPEN_VALID_FILE_NAME is checked in the unpack function. */
if (!(openInfo.mask & HGFS_OPEN_VALID_MODE)) {
LOG(4, ("HgfsServerOpen: filename or mode not provided\n"));
status = EINVAL;
goto exit;
}
nameStatus = HgfsServerGetShareInfo(openInfo.cpName,
openInfo.cpNameSize,
openInfo.caseFlags,
&openInfo.shareInfo,
&localName,
&localNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerOpen: access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
if (openInfo.mask & HGFS_OPEN_VALID_FLAGS) {
savedOpenFlags = openInfo.flags;
if (!HgfsServerCheckOpenFlagsForShare(&openInfo,
&openInfo.flags)) {
/* Incompatible open mode with share mode. */
status = EACCES;
goto exit;
}
}
ASSERT(localName);
openInfo.utf8Name = localName;
LOG(4, ("HgfsServerOpen: opening \"%s\", mode %u, flags %u, perms "
"%u%u%u%u\n", openInfo.utf8Name,
(openInfo.mask & HGFS_OPEN_VALID_MODE) ? openInfo.mode : 0,
(openInfo.mask & HGFS_OPEN_VALID_FLAGS) ? openInfo.flags : 0,
(openInfo.mask & HGFS_OPEN_VALID_SPECIAL_PERMS) ?
openInfo.specialPerms : 0,
(openInfo.mask & HGFS_OPEN_VALID_OWNER_PERMS) ?
openInfo.ownerPerms : 0,
(openInfo.mask & HGFS_OPEN_VALID_GROUP_PERMS) ?
openInfo.groupPerms : 0,
(openInfo.mask & HGFS_OPEN_VALID_OTHER_PERMS) ?
openInfo.otherPerms : 0));
/*
* XXX: Before opening the file, see if we already have this file opened on
* the server with an oplock on it. If we do, we must fail the new open
* request, otherwise we will trigger an oplock break that the guest cannot
* handle at this time (since the HGFS server is running in the context of
* the vcpu thread), and we'll deadlock.
*
* Until we overcome this limitation via Crosstalk, we will be extra smart
* in the client drivers so as to prevent open requests on handles that
* already have an oplock. And the server will protect itself like so.
*
* XXX: With some extra effort, we could allow a second open for read here,
* since that won't break a shared oplock, but the clients should already
* realize that the second open can be avoided via sharing handles, too.
*/
if (HgfsFileHasServerLock(localName, session, &serverLock, &newFd)) {
LOG (4, ("HgfsServerOpen: Client tried to open new handle for oplocked "
"file %s.\n", localName));
status = EBUSY;
goto exit;
}
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(openInfo.cpName,
openInfo.cpNameSize,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerSearchRead: no matching share: %s.\n", openInfo.cpName));
status = ENOENT;
goto exit;
}
followSymlinks = HgfsServerPolicy_IsShareOptionSet(configOptions,
HGFS_SHARE_FOLLOW_SYMLINKS);
/* See if the name is valid, and if so add it and return the handle. */
status = HgfsValidateOpen(&openInfo, followSymlinks, session, &localId, &newFd);
if (status == 0) {
ASSERT(newFd >= 0);
/*
* Open succeeded, so make new node and return its handle. If we fail,
* it's almost certainly an internal server error.
*/
if (!HgfsCreateAndCacheFileNode(&openInfo, &localId, newFd, FALSE, session)) {
status = HGFS_INTERNAL_STATUS_ERROR;
goto exit;
}
if (HgfsPackOpenReply(packetIn, status, &openInfo, &packetOut, &packetOutSize)) {
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
} else {
status = EPROTO;
}
} else {
/*
* The open failed, if we modified the open flags, force the return
* status to be access denied, not the error for the modified open.
*/
if (openInfo.mask & HGFS_OPEN_VALID_FLAGS &&
savedOpenFlags != openInfo.flags &&
status == ENOENT) {
status = EACCES;
}
}
exit:
free(localName);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerRead --
*
* Handle a Read request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerRead(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsRequest *header = (HgfsRequest *)packetIn;
int fd;
int error;
HgfsInternalStatus status;
uint32 extra;
Bool sequentialOpen;
HgfsHandle file;
uint64 offset;
uint32 requiredSize;
char *payload;
uint32 *replyActualSize;
size_t replySize;
char *packetOut;
ASSERT(packetIn);
ASSERT(session);
if (header->op == HGFS_OP_READ_V3) {
HgfsRequestReadV3 *request =
(HgfsRequestReadV3 *)HGFS_REQ_GET_PAYLOAD_V3(packetIn);
HgfsReplyReadV3 *reply;
file = request->file;
offset = request->offset;
requiredSize = request->requiredSize;
replySize = HGFS_REP_PAYLOAD_SIZE_V3(reply) - 1;
ASSERT(HGFS_LARGE_PACKET_MAX >= replySize);
extra = HGFS_LARGE_PACKET_MAX - replySize;
/*
* requiredSize is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (requiredSize > extra) {
/*
* The client wants to read more bytes than our payload can handle.
* Truncate the request
*/
requiredSize = extra;
}
packetOut = Util_SafeMalloc(replySize + requiredSize);
reply = (HgfsReplyReadV3 *)HGFS_REP_GET_PAYLOAD_V3(packetOut);
payload = reply->payload;
replyActualSize = &reply->actualSize;
reply->reserved = 0;
} else {
HgfsRequestRead *request = (HgfsRequestRead *)packetIn;
HgfsReplyRead *reply;
file = request->file;
offset = request->offset;
requiredSize = request->requiredSize;
replySize = sizeof *reply - 1;
ASSERT(HGFS_PACKET_MAX >= replySize);
extra = HGFS_PACKET_MAX - replySize;
/*
* requiredSize is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (requiredSize > extra) {
/*
* The client wants to read more bytes than our payload can handle.
* Truncate the request
*/
requiredSize = extra;
}
packetOut = Util_SafeMalloc(replySize + requiredSize);
reply = (HgfsReplyRead *)packetOut;
payload = reply->payload;
replyActualSize = &reply->actualSize;
}
LOG(4, ("HgfsServerRead: read fh %u, offset %"FMT64"u, count %u\n",
file, offset, requiredSize));
/* Get the file descriptor from the cache */
status = HgfsGetFd(file, session, FALSE, &fd);
if (status != 0) {
LOG(4, ("HgfsServerRead: Could not get file descriptor\n"));
free(packetOut);
return status;
}
if (!HgfsHandleIsSequentialOpen(file, session, &sequentialOpen)) {
LOG(4, ("HgfsServerRead: Could not get sequenial open status\n"));
free(packetOut);
return EBADF;
}
#if defined(GLIBC_VERSION_21) || defined(__APPLE__)
/* Read from the file. */
if (sequentialOpen) {
error = read(fd, payload, requiredSize);
} else {
error = pread(fd, payload, requiredSize, offset);
}
#else
/*
* Seek to the offset and read from the file. Grab the IO lock to make
* this and the subsequent read atomic.
*/
SyncMutex_Lock(&session->fileIOLock);
if (!sequentialOpen) {
# ifdef linux
{
uint64 res;
# if !defined(VM_X86_64)
error = _llseek(fd, offset >> 32, offset & 0xFFFFFFFF, &res, 0);
# else
error = llseek(fd, offset >> 32, offset & 0xFFFFFFFF, &res, 0);
# endif
}
# else
error = lseek(fd, offset, 0);
# endif
if (error < 0) {
status = errno;
LOG(4, ("HgfsServerRead: could not seek to %"FMT64"u: %s\n",
offset, strerror(status)));
SyncMutex_Unlock(&session->fileIOLock);
goto error;
}
}
error = read(fd, payload, requiredSize);
SyncMutex_Unlock(&session->fileIOLock);
#endif
if (error < 0) {
status = errno;
LOG(4, ("HgfsServerRead: error reading from file: %s\n",
strerror(status)));
goto error;
}
LOG(4, ("HgfsServerRead: read %d bytes\n", error));
*replyActualSize = error;
replySize += error;
/* Send the reply. */
if (!HgfsPackAndSendPacket(packetOut, replySize, 0, header->id, session, 0)) {
status = 0;
goto error;
}
return 0;
error:
free(packetOut);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerWrite --
*
* Handle a Write request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerWrite(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsRequest *header = (HgfsRequest *)packetIn;
uint32 extra;
HgfsInternalStatus status;
int fd;
int error;
Bool sequentialOpen;
HgfsHandle file;
HgfsWriteFlags flags;
uint64 offset;
uint32 requiredSize;
char *payload;
uint32 *actualSize;
size_t replySize;
char *packetOut;
ASSERT(packetIn);
ASSERT(session);
if (header->op == HGFS_OP_WRITE_V3) {
HgfsRequestWriteV3 *request;
HgfsReplyWriteV3 *reply;
replySize = HGFS_REP_PAYLOAD_SIZE_V3(reply);
packetOut = Util_SafeMalloc(replySize);
request = (HgfsRequestWriteV3 *)HGFS_REQ_GET_PAYLOAD_V3(packetIn);
reply = (HgfsReplyWriteV3 *)HGFS_REP_GET_PAYLOAD_V3(packetOut);
/* Enforced by the dispatch function */
ASSERT(packetSize >= HGFS_REQ_PAYLOAD_SIZE_V3(request) - 1);
extra = packetSize - (HGFS_REQ_PAYLOAD_SIZE_V3(request) - 1);
file = request->file;
flags = request->flags;
offset = request->offset;
payload = request->payload;
requiredSize = request->requiredSize;
actualSize = &reply->actualSize;
reply->reserved = 0;
} else {
HgfsRequestWrite *request;
HgfsReplyWrite *reply;
replySize = sizeof *reply;
packetOut = Util_SafeMalloc(replySize);
request = (HgfsRequestWrite *)packetIn;
reply = (HgfsReplyWrite *)packetOut;
/* Enforced by the dispatch function */
ASSERT(packetSize >= sizeof *request - 1);
extra = packetSize - (sizeof *request - 1);
file = request->file;
flags = request->flags;
offset = request->offset;
payload = request->payload;
requiredSize = request->requiredSize;
actualSize = &reply->actualSize;
}
LOG(4, ("HgfsServerWrite: write fh %u, offset %"FMT64"u, count %u, extra %u\n",
file, offset, requiredSize, extra));
/* Get the file desriptor from the cache */
status = HgfsGetFd(file, session, ((flags & HGFS_WRITE_APPEND) ?
TRUE : FALSE),
&fd);
if (status != 0) {
LOG(4, ("HgfsServerWrite: Could not get file descriptor\n"));
free(packetOut);
return status;
}
if (!HgfsHandleIsSequentialOpen(file, session, &sequentialOpen)) {
LOG(4, ("HgfsServerWrite: Could not get sequential open status\n"));
free(packetOut);
return EBADF;
}
/*
* requiredSize is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (requiredSize > extra) {
/*
* The driver wants to write more bytes than there is in its payload.
* Truncate the request
*/
requiredSize = extra;
}
#if defined(GLIBC_VERSION_21) || defined(__APPLE__)
/* Write to the file. */
if (sequentialOpen) {
error = write(fd, payload, requiredSize);
} else {
error = pwrite(fd, payload, requiredSize, offset);
}
#else
/*
* Seek to the offset and write from the file. Grab the IO lock to make
* this and the subsequent write atomic.
*/
SyncMutex_Lock(&session->fileIOLock);
if (!sequentialOpen) {
# ifdef linux
{
uint64 res;
# if !defined(VM_X86_64)
error = _llseek(fd, offset >> 32, offset & 0xFFFFFFFF, &res, 0);
# else
error = llseek(fd, offset >> 32, offset & 0xFFFFFFFF, &res, 0);
# endif
}
# else
error = lseek(fd, offset, 0);
# endif
if (error < 0) {
status = errno;
LOG(4, ("HgfsServerWrite: could not seek to %"FMT64"u: %s\n",
offset, strerror(status)));
SyncMutex_Unlock(&session->fileIOLock);
goto error;
}
}
error = write(fd, payload, requiredSize);
SyncMutex_Unlock(&session->fileIOLock);
#endif
if (error < 0) {
status = errno;
LOG(4, ("HgfsServerWrite: error writing to file: %s\n",
strerror(status)));
goto error;
}
LOG(4, ("HgfsServerWrite: wrote %d bytes\n", error));
*actualSize = error;
status = 0;
if (!HgfsPackAndSendPacket(packetOut, replySize, 0, header->id, session, 0)) {
goto error;
}
return 0;
error:
free(packetOut);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerSearchOpen --
*
* Handle a "Search Open" request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerSearchOpen(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsRequest *header;
HgfsHandle *replySearch;
uint32 extra;
size_t baseDirLen;
char *baseDir;
HgfsHandle handle;
HgfsInternalStatus status;
HgfsNameStatus nameStatus;
char *dirName;
uint32 dirNameLength;
HgfsCaseType caseFlags = HGFS_FILE_NAME_DEFAULT_CASE;
size_t replySize;
char *packetOut;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
header = (HgfsRequest *)packetIn;
if (header->op == HGFS_OP_SEARCH_OPEN_V3) {
HgfsRequestSearchOpenV3 *requestV3;
HgfsReplySearchOpenV3 *replyV3;
replySize = HGFS_REP_PAYLOAD_SIZE_V3(replyV3);
packetOut = Util_SafeMalloc(replySize);
requestV3 = (HgfsRequestSearchOpenV3 *)HGFS_REQ_GET_PAYLOAD_V3(packetIn);
replyV3 = (HgfsReplySearchOpenV3 *)HGFS_REP_GET_PAYLOAD_V3(packetOut);
/* Enforced by the dispatch function */
ASSERT(packetSize >= HGFS_REQ_PAYLOAD_SIZE_V3(requestV3));
extra = packetSize - HGFS_REQ_PAYLOAD_SIZE_V3(requestV3);
caseFlags = requestV3->dirName.caseType;
dirName = requestV3->dirName.name;
dirNameLength = requestV3->dirName.length;
replySearch = &replyV3->search;
replyV3->reserved = 0;
LOG(4, ("HgfsServerSearchOpen: HGFS_OP_SEARCH_OPEN_V3\n"));
} else {
HgfsRequestSearchOpen *request = (HgfsRequestSearchOpen *)packetIn;
replySize = sizeof (HgfsReplySearchOpen);
packetOut = Util_SafeMalloc(replySize);
/* Enforced by the dispatch function */
ASSERT(packetSize >= sizeof *request);
extra = packetSize - sizeof *request;
dirName = request->dirName.name;
dirNameLength = request->dirName.length;
replySearch = &((HgfsReplySearchOpen *)packetOut)->search;
}
/*
* request->dirName.length is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (dirNameLength > extra) {
/* The input packet is smaller than the request */
status = EPROTO;
goto exit;
}
/* It is now safe to read the file name. */
nameStatus = HgfsServerGetShareInfo(dirName,
dirNameLength,
caseFlags,
&shareInfo,
&baseDir,
&baseDirLen);
switch (nameStatus) {
case HGFS_NAME_STATUS_COMPLETE:
{
char *inEnd;
char *next;
int len;
ASSERT(baseDir);
LOG(4, ("HgfsServerSearchOpen: searching in \"%s\", %s.\n", baseDir, dirName));
inEnd = dirName + dirNameLength;
/* Get the first component. */
len = CPName_GetComponent(dirName, inEnd, (char const **) &next);
if (len < 0) {
LOG(4, ("HgfsServerSearchOpen: get first component failed\n"));
status = ENOENT;
goto exit;
}
if (*inEnd != '\0') {
/*
* NT4 clients can send the name without a nul-terminator.
* The space for the nul is included and tested for in the size
* calculations above. Size of structure (includes a single
* character of the name) and the full dirname length.
*/
*inEnd = '\0';
}
LOG(4, ("HgfsServerSearchOpen: dirName: %s.\n", dirName));
status = HgfsServerSearchRealDir(baseDir,
baseDirLen,
dirName,
shareInfo.rootDir,
session,
&handle);
free(baseDir);
/*
* If the directory exists but shared folder is write only
* then return access denied, otherwise preserve the original
* error code.
*/
if (!shareInfo.readPermissions && HGFS_NAME_STATUS_COMPLETE == status) {
status = HGFS_NAME_STATUS_ACCESS_DENIED;
}
if (status != 0) {
LOG(4, ("HgfsServerSearchOpen: couldn't scandir\n"));
goto exit;
}
break;
}
case HGFS_NAME_STATUS_INCOMPLETE_BASE:
/*
* This is the base of our namespace, so enumerate all
* shares. [bac]
*/
LOG(4, ("HgfsServerSearchOpen: opened search on base\n"));
status = HgfsServerSearchVirtualDir(HgfsServerPolicy_GetShares,
HgfsServerPolicy_GetSharesInit,
HgfsServerPolicy_GetSharesCleanup,
DIRECTORY_SEARCH_TYPE_BASE,
session,
&handle);
if (status != 0) {
LOG(4, ("HgfsServerSearchOpen: couldn't enumerate shares\n"));
goto exit;
}
break;
default:
LOG(4, ("HgfsServerSearchOpen: access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
if (DOLOG(4)) {
HgfsServerDumpDents(handle, session);
}
/*
* Return handle to the search object as the reply to the search
* open.
*/
*replySearch = handle;
if (!HgfsPackAndSendPacket(packetOut, replySize, 0, header->id, session, 0)) {
status = 0;
goto exit;
}
return 0;
exit:
free(packetOut);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerSearchRead --
*
* Handle a "Search Read" request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerSearchRead(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
uint32 requestedOffset;
HgfsFileAttrInfo attr;
HgfsInternalStatus status;
HgfsNameStatus nameStatus;
HgfsHandle hgfsSearchHandle;
DirectoryEntry *dent;
HgfsSearch search;
HgfsShareOptions configOptions = 0;
char *packetOut;
size_t packetOutSize;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackSearchReadRequest(packetIn,
packetSize,
&attr,
&hgfsSearchHandle,
&requestedOffset)) {
return EPROTO;
}
LOG(4, ("HgfsServerSearchRead: read search #%u, offset %u\n",
hgfsSearchHandle, requestedOffset));
if (!HgfsGetSearchCopy(hgfsSearchHandle, session, &search)) {
LOG(4, ("HgfsServerSearchRead: handle %u is invalid\n",
hgfsSearchHandle));
return EBADF;
}
/* Get the config options. */
if (search.utf8ShareNameLen != 0) {
nameStatus = HgfsServerPolicy_GetShareOptions(search.utf8ShareName,
search.utf8ShareNameLen,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerSearchRead: no matching share: %s.\n", search.utf8ShareName));
free(search.utf8Dir);
free(search.utf8ShareName);
return ENOENT;
}
}
while ((dent = HgfsGetSearchResult(hgfsSearchHandle, session,
requestedOffset, FALSE)) != NULL) {
unsigned int length;
char *fullName;
char *sharePath;
size_t sharePathLen;
size_t fullNameLen;
size_t entryNameLen;
char *entryName = NULL;
Bool freeEntryName = FALSE;
length = strlen(dent->d_name);
/* Each type of search gets a dent's attributes in a different way. */
switch (search.type) {
case DIRECTORY_SEARCH_TYPE_DIR:
/*
* Construct the UTF8 version of the full path to the file, and call
* HgfsGetattrFromName to get the attributes of the file.
*/
fullNameLen = search.utf8DirLen + 1 + length;
fullName = (char *)malloc(fullNameLen + 1);
if (!fullName) {
LOG(4, ("HgfsServerSearchRead: could not allocate space for "
"\"%s\\%s\"\n", search.utf8Dir, dent->d_name));
free(search.utf8Dir);
free(search.utf8ShareName);
free(dent);
return ENOMEM;
}
memcpy(fullName, search.utf8Dir, search.utf8DirLen);
fullName[search.utf8DirLen] = DIRSEPC;
memcpy(&fullName[search.utf8DirLen + 1], dent->d_name, length + 1);
LOG(4, ("HgfsServerSearchRead: about to stat \"%s\"\n", fullName));
status = HgfsGetattrFromName(fullName, configOptions, search.utf8ShareName,
&attr, NULL);
if (status != 0) {
HgfsOp savedOp = attr.requestType;
LOG(4, ("HgfsServerSearchRead: stat FAILED %s (%d)\n",
fullName, status));
memset(&attr, 0, sizeof attr);
attr.requestType = savedOp;
attr.type = HGFS_FILE_TYPE_REGULAR;
attr.mask = 0;
}
free(fullName);
#if defined(__APPLE__)
/*
* HGFS clients receive names in unicode normal form C,
* (precomposed) so Mac hosts must convert from normal form D
* (decomposed).
*/
if (!CodeSet_Utf8FormDToUtf8FormC((const char *)dent->d_name,
length,
&entryName,
&entryNameLen)) {
LOG(4, ("HgfsServerSearchRead: Unable to normalize form C \"%s\"\n",
dent->d_name));
/* Skip this entry and continue. */
free(dent);
continue;
}
freeEntryName = TRUE;
#else /* defined(__APPLE__) */
entryName = dent->d_name;
entryNameLen = length;
#endif /* defined(__APPLE__) */
break;
case DIRECTORY_SEARCH_TYPE_BASE:
/*
* For a search enumerating all shares, give the default attributes
* for '.' and ".." (which aren't really shares anyway). Each real
* share gets resolved into its full path, and gets its attributes
* via HgfsGetattrFromName.
*/
if (strcmp(dent->d_name, ".") == 0 ||
strcmp(dent->d_name, "..") == 0) {
LOG(4, ("HgfsServerSearchRead: assigning %s default "
"attributes\n", dent->d_name));
HgfsServerGetDefaultDirAttrs(&attr);
} else {
/* Check permission on the share and get the share path */
nameStatus =
HgfsServerPolicy_GetSharePath(dent->d_name,
length,
HGFS_OPEN_MODE_READ_ONLY,
&sharePathLen,
(char const **)&sharePath);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerSearchRead: No such share or access denied\n"));
free(dent);
free(search.utf8Dir);
free(search.utf8ShareName);
return HgfsConvertFromNameStatus(nameStatus);
}
/*
* Server needs to produce list of shares that is consistent with
* the list defined in UI. If a share can't be accessed because of
* problems on the host, the server still enumerates it and
* returns to the client.
*/
status = HgfsGetattrFromName(sharePath, configOptions, dent->d_name,
&attr, NULL);
if (status != 0) {
/*
* The dent no longer exists. Log the event.
*/
LOG(4, ("HgfsServerSearchRead: stat FAILED\n"));
}
}
/*
* No conversion needed on OS X because dent->d_name is the shareName
* that was converted to normal form C in hgfsServerPolicyHost.
*/
entryName = dent->d_name;
entryNameLen = length;
break;
case DIRECTORY_SEARCH_TYPE_OTHER:
/*
* The POSIX implementation of HgfsSearchOpen could not have created
* this kind of search.
*/
NOT_IMPLEMENTED();
break;
default:
NOT_IMPLEMENTED();
break;
}
free(search.utf8Dir);
free(search.utf8ShareName);
LOG(4, ("HgfsServerSearchRead: dent name is \"%s\" len = %"FMTSZ"u\n",
entryName, entryNameLen));
/*
* We need to unescape the name before sending it back to the client
*/
entryNameLen = HgfsEscape_Undo(entryName, entryNameLen + 1);
/*
* XXX: HgfsPackSearchReadReply will error out if the dent we
* give it is too large for the packet. Prior to
* HgfsPackSearchReadReply, we'd skip the dent and return the next
* one with success. Now we return an error. This may be a non-issue
* since what filesystems allow dent lengths as high as 6144 bytes?
*/
status = 0;
if (!HgfsPackSearchReadReply(packetIn, status, entryName, entryNameLen, &attr,
&packetOut, &packetOutSize)) {
status = EPROTO;
}
if (freeEntryName) {
free(entryName);
}
free(dent);
if (status == 0 &&
!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
return status;
}
/* No entry at this offset */
free(search.utf8Dir);
free(search.utf8ShareName);
LOG(4, ("HgfsServerSearchRead: no entry\n"));
status = 0;
if (!HgfsPackSearchReadReply(packetIn, status, NULL, 0, &attr,
&packetOut, &packetOutSize)) {
status = EPROTO;
}
if (status == 0 &&
!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerGetattr --
*
* Handle a Getattr request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerGetattr(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
char *localName;
HgfsAttrHint hints = 0;
HgfsFileAttrInfo attr;
HgfsInternalStatus status = 0;
HgfsNameStatus nameStatus;
char *cpName;
size_t cpNameSize;
char *targetName = NULL;
uint32 targetNameLen;
HgfsHandle file = HGFS_INVALID_HANDLE; /* file handle from driver */
uint32 caseFlags = 0;
HgfsShareOptions configOptions;
char *packetOut;
size_t packetOutSize;
size_t localNameLen;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackGetattrRequest(packetIn,
packetSize,
&attr,
&hints,
&cpName,
&cpNameSize,
&file,
&caseFlags)) {
status = EPROTO;
goto exit;
}
/* Client wants us to reuse an existing handle. */
if (hints & HGFS_ATTR_HINT_USE_FILE_DESC) {
int fd;
status = HgfsGetFd(file, session, FALSE, &fd);
if (status != 0) {
LOG(4, ("HgfsServerGetattr: Could not get file descriptor\n"));
goto exit;
}
status = HgfsGetattrFromFd(fd, session, &attr);
targetNameLen = 0;
} else {
/*
* Depending on whether this file/dir is real or virtual, either
* forge its attributes or look them up in the actual filesystem.
*/
nameStatus = HgfsServerGetShareInfo(cpName,
cpNameSize,
caseFlags,
&shareInfo,
&localName,
&localNameLen);
switch (nameStatus) {
case HGFS_NAME_STATUS_INCOMPLETE_BASE:
/*
* This is the base of our namespace; make up fake status for
* this directory.
*/
LOG(4, ("HgfsServerGetattr: getting attrs for base dir\n"));
HgfsServerGetDefaultDirAttrs(&attr);
break;
case HGFS_NAME_STATUS_COMPLETE:
/* This is a regular lookup; proceed as usual */
ASSERT(localName);
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(cpName, cpNameSize,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerGetattr: no matching share: %s.\n", cpName));
free(localName);
status = ENOENT;
goto exit;
}
status = HgfsGetattrFromName(localName, configOptions, cpName, &attr,
&targetName);
free(localName);
if (status == 0 &&
!HgfsServerPolicy_CheckMode(HGFS_OPEN_MODE_READ_ONLY,
shareInfo.writePermissions,
shareInfo.readPermissions)) {
status = EACCES;
} else if (status != 0) {
/*
* If it is a dangling share server should not return ENOENT
* to the client because it causes confusion: a name that is returned
* by directory enumeration should not produce "name not found"
* error.
* Replace it with a more appropriate error code: no such device.
*/
if (status == ENOENT && HgfsIsShareRoot(cpName, cpNameSize)) {
status = ENXIO;
}
goto exit;
}
break;
default:
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
targetNameLen = targetName ? strlen(targetName) : 0;
}
status = HgfsPackGetattrReply(packetIn, status, &attr, targetName,
targetNameLen, &packetOut, &packetOutSize) ? 0 : EPROTO;
free(targetName);
if (status == 0 &&
!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerSetattr --
*
* Handle a Setattr request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerSetattr(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsInternalStatus status;
HgfsFileAttrInfo attr;
char *cpName;
size_t cpNameSize = 0;
HgfsAttrHint hints = 0;
HgfsHandle file = HGFS_INVALID_HANDLE;
uint32 caseFlags = 0;
char *packetOut;
size_t packetOutSize;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackSetattrRequest(packetIn,
packetSize,
&attr,
&hints,
&cpName,
&cpNameSize,
&file,
&caseFlags)) {
status = EPROTO;
goto exit;
}
if (file != HGFS_INVALID_HANDLE) {
status = HgfsSetattrFromFd(file, session, &attr, hints);
} else {
status = HgfsSetattrFromName(cpName,
cpNameSize,
&attr,
hints,
caseFlags,
session);
}
if (!HgfsPackSetattrReply(packetIn, status, &packetOut, &packetOutSize)) {
status = EPROTO;
goto exit;
}
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
/* We can't send the packet, ignore the error if any. */
}
status = 0;
exit:
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerCreateDir --
*
* Handle a CreateDir request.
*
* Simply converts to the local filename, calls mkdir on the
* file, and returns an appropriate response to the driver.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerCreateDir(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsNameStatus nameStatus;
HgfsCreateDirInfo info;
char *localName;
int error;
mode_t permissions;
char *packetOut;
size_t packetOutSize;
size_t localNameLen;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackCreateDirRequest(packetIn, packetSize, &info)) {
return EPROTO;
}
nameStatus = HgfsServerGetShareInfo(info.cpName,
info.cpNameSize,
info.caseFlags,
&shareInfo,
&localName,
&localNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerCreateDir: access check failed\n"));
return HgfsConvertFromNameStatus(nameStatus);
}
ASSERT(localName);
/*
* For read-only shares we must never attempt to create a directory.
* However the error code must be different depending on the existence
* of the file or directory with the same name.
*/
if (!shareInfo.writePermissions) {
int error = HgfsAccess(localName, info.cpName, info.cpNameSize);
if (error != 0) {
if (error == ENOENT) {
error = EACCES;
}
} else {
error = EEXIST;
}
LOG(4, ("HgfsServerCreateDir: failed access check, error %d\n", error));
free(localName);
return error;
}
/*
* Create mode_t for use in mkdir(). If owner permissions are missing, use
* read/write/execute for the owner permissions. If group or other
* permissions are missing, use the owner permissions.
*
* This sort of makes sense. If the Windows driver wants to make a dir
* read-only, it probably intended for the dir to be 666. Since creating
* a directory requires a valid mode, it's highly unlikely that we'll ever
* be creating a directory without owner permissions.
*/
permissions = ~ALLPERMS;
permissions |= info.mask & HGFS_CREATE_DIR_VALID_SPECIAL_PERMS ?
info.specialPerms << 9 : 0;
permissions |= info.mask & HGFS_CREATE_DIR_VALID_OWNER_PERMS ?
info.ownerPerms << 6 : S_IRWXU;
permissions |= info.mask & HGFS_CREATE_DIR_VALID_GROUP_PERMS ?
info.groupPerms << 3 : (permissions & S_IRWXU) >> 3;
permissions |= info.mask & HGFS_CREATE_DIR_VALID_OTHER_PERMS ?
info.otherPerms : (permissions & S_IRWXU) >> 6;
LOG(4, ("HgfsServerCreateDir: making dir \"%s\", mode %"FMTMODE"\n",
localName, permissions));
error = Posix_Mkdir(localName, permissions);
if ((info.mask & HGFS_CREATE_DIR_VALID_FILE_ATTR) &&
(info.fileAttr & HGFS_ATTR_HIDDEN)) {
/*
* Set hidden attribute when requested.
* Do not fail directory creation if setting hidden attribute fails.
*/
HgfsSetHiddenXAttr(localName, TRUE);
}
free(localName);
if (error) {
error = errno;
LOG(4, ("HgfsServerCreateDir: error: %s\n", strerror(error)));
return error;
}
if (!HgfsPackCreateDirReply(packetIn, 0, &packetOut, &packetOutSize)) {
return EPROTO;
}
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerDeleteFile --
*
* Handle a Delete File request.
*
* Simply converts to the local filename, calls unlink on the
* file, and returns an appropriate response to the driver.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerDeleteFile(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsNameStatus nameStatus;
char *localName;
int error;
HgfsHandle file = HGFS_INVALID_HANDLE;
HgfsDeleteHint hints = 0;
char *cpName;
size_t cpNameSize;
uint32 caseFlags;
char *packetOut;
size_t packetOutSize;
size_t localNameLen;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackDeleteRequest(packetIn,
packetSize,
&cpName,
&cpNameSize,
&hints,
&file,
&caseFlags)) {
return EPROTO;
}
if (hints & HGFS_DELETE_HINT_USE_FILE_DESC) {
if (!HgfsHandle2FileNameMode(file, session, &shareInfo.writePermissions,
&shareInfo.readPermissions, &cpName, &cpNameSize)) {
LOG(4, ("HgfsServerDeleteFile: could not map cached file handle %u\n",
file));
return EBADF;
}
localName = cpName;
} else {
nameStatus = HgfsServerGetShareInfo(cpName,
cpNameSize,
caseFlags,
&shareInfo,
&localName,
&localNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerDeleteFile: access check failed\n"));
return HgfsConvertFromNameStatus(nameStatus);
}
}
ASSERT(localName);
/*
* Deleting a file needs both read and write permssions.
* However the error code must be different depending on the existence
* of the file with the same name.
*/
if (!shareInfo.writePermissions || !shareInfo.readPermissions) {
int error = HgfsAccess(localName, cpName, cpNameSize);
if (error == 0) {
error = EACCES;
}
LOG(4, ("HgfsServerDeleteFile: failed access check, error %d\n", error));
free(localName);
return error;
}
LOG(4, ("HgfsServerDeleteFile: unlinking \"%s\"\n", localName));
error = Posix_Unlink(localName);
free(localName);
if (error) {
error = errno;
LOG(4, ("HgfsServerDeleteFile: error: %s\n", strerror(error)));
return error;
}
if (!HgfsPackDeleteReply(packetIn, 0, &packetOut, &packetOutSize)) {
return EPROTO;
}
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerDeleteDir --
*
* Handle a Delete Dir request.
*
* Simply converts to the local filename, calls rmdir on the
* file, and returns an appropriate response to the driver.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerDeleteDir(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsNameStatus nameStatus;
char *localName = NULL;
int error;
HgfsHandle file = HGFS_INVALID_HANDLE;
HgfsDeleteHint hints = 0;
char *cpName;
size_t cpNameSize;
uint32 caseFlags;
char *packetOut;
size_t packetOutSize;
size_t localNameLen;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackDeleteRequest(packetIn,
packetSize,
&cpName,
&cpNameSize,
&hints,
&file,
&caseFlags)) {
return EPROTO;
}
if (hints & HGFS_DELETE_HINT_USE_FILE_DESC) {
if (!HgfsHandle2FileNameMode(file, session, &shareInfo.writePermissions,
&shareInfo.readPermissions, &cpName, &cpNameSize)) {
LOG(4, ("HgfsServerDeleteDir: could not map cached file handle %u\n",
file));
return EBADF;
}
localName = cpName;
} else {
nameStatus = HgfsServerGetShareInfo(cpName,
cpNameSize,
caseFlags,
&shareInfo,
&localName,
&localNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerDeleteDir: access check failed\n"));
return HgfsConvertFromNameStatus(nameStatus);
}
}
/* Guest OS is not allowed to delete shared folder. */
if (HgfsServerIsSharedFolderOnly(cpName, cpNameSize)){
LOG(4, ("HgfsServerDeleteDir: Cannot delete shared folder\n"));
free(localName);
return EPERM;
}
/*
* Deleting a directory needs both read and write permssions.
* However the error code must be different depending on the existence
* of the file with the same name.
*/
if (!shareInfo.writePermissions || !shareInfo.readPermissions) {
int error = HgfsAccess(localName, cpName, cpNameSize);
if (error == 0) {
error = EACCES;
}
LOG(4, ("HgfsServerDeleteDir: failed access check, error %d\n", error));
free(localName);
return error;
}
ASSERT(localName);
LOG(4, ("HgfsServerDeleteDir: removing \"%s\"\n", localName));
error = Posix_Rmdir(localName);
free(localName);
if (error) {
error = errno;
LOG(4, ("HgfsServerDeleteDir: error: %s\n", strerror(error)));
return error;
}
if (!HgfsPackDeleteReply(packetIn, 0, &packetOut, &packetOutSize)) {
return EPROTO;
}
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
return 0;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerRename --
*
* Handle a Rename request.
*
* Simply converts the new and old names to local filenames, calls
* rename(2), and returns an appropriate response to the driver.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerRename(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsNameStatus nameStatus;
char *localOldName = NULL;
size_t localOldNameLen;
char *localNewName = NULL;
size_t localNewNameLen;
char *cpOldName;
uint32 cpOldNameLen;
char *cpNewName;
uint32 cpNewNameLen;
HgfsHandle srcFile = HGFS_INVALID_HANDLE;
HgfsHandle targetFile = HGFS_INVALID_HANDLE;
HgfsRenameHint hints = 0;
int error;
HgfsInternalStatus status;
Bool sharedFolderOpen = FALSE;
uint32 oldCaseFlags = 0;
uint32 newCaseFlags = 0;
char *packetOut;
size_t packetOutSize;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
if (!HgfsUnpackRenameRequest(packetIn,
packetSize,
&cpOldName,
&cpOldNameLen,
&cpNewName,
&cpNewNameLen,
&hints,
&srcFile,
&targetFile,
&oldCaseFlags,
&newCaseFlags)) {
return EPROTO;
}
if (hints & HGFS_RENAME_HINT_USE_SRCFILE_DESC) {
size_t localOldNameLen;
if (!HgfsHandle2FileNameMode(srcFile, session, &shareInfo.writePermissions,
&shareInfo.readPermissions, &localOldName,
&localOldNameLen)) {
LOG(4, ("HgfsServerDeleteFile: could not map cached source file handle %u\n",
srcFile));
return EBADF;
}
/* Guest OS is not allowed to rename shared folder. */
if (HgfsHandleIsSharedFolderOpen(srcFile, session, &sharedFolderOpen) &&
sharedFolderOpen) {
LOG(4, ("HgfsServerRename: Cannot rename shared folder\n"));
status = EPERM;
goto exit;
}
} else {
nameStatus = HgfsServerGetShareInfo(cpOldName,
cpOldNameLen,
oldCaseFlags,
&shareInfo,
&localOldName,
&localOldNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerRename: old name access check failed\n"));
return HgfsConvertFromNameStatus(nameStatus);
}
ASSERT(localOldName);
/* Guest OS is not allowed to rename shared folder. */
if (HgfsServerIsSharedFolderOnly(cpOldName,
cpOldNameLen)){
LOG(4, ("HgfsServerRename: Cannot rename shared folder\n"));
status = EPERM;
goto exit;
}
/*
* Renaming a file requires both read and write permissions for the original file.
* However the error code must be different depending on the existence
* of the file with the same name.
*/
if (!shareInfo.writePermissions || !shareInfo.readPermissions) {
status = HgfsAccess(localOldName, cpOldName, cpOldNameLen);
if (status == 0) {
status = EACCES;
}
LOG(4, ("HgfsServerRename: failed access check, error %d\n", status));
goto exit;
}
}
if (hints & HGFS_RENAME_HINT_USE_TARGETFILE_DESC) {
size_t localNewNameLen;
if (!HgfsHandle2FileNameMode(targetFile, session, &shareInfo.writePermissions,
&shareInfo.readPermissions, &localNewName,
&localNewNameLen)) {
LOG(4, ("HgfsServerDeleteFile: could not map cached target file handle %u\n",
targetFile));
status = EBADF;
goto exit;
}
/* Guest OS is not allowed to rename shared folder. */
if (HgfsHandleIsSharedFolderOpen(targetFile, session, &sharedFolderOpen) &&
sharedFolderOpen) {
LOG(4, ("HgfsServerRename: Cannot rename shared folder\n"));
status = EPERM;
goto exit;
}
} else {
nameStatus = HgfsServerGetShareInfo(cpNewName,
cpNewNameLen,
newCaseFlags,
&shareInfo,
&localNewName,
&localNewNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerRename: new name access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
}
ASSERT(localNewName);
if (hints & HGFS_RENAME_HINT_NO_REPLACE_EXISTING) {
HgfsFileAttrInfo attr;
HgfsShareOptions configOptions;
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(cpNewName, cpNewNameLen,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerRename: no matching share: %s.\n", cpNewName));
status = ENOENT;
goto exit;
}
/*
* We were asked to avoid replacing an existing file,
* so fail if the target exists.
*/
status = HgfsGetattrFromName(localNewName, configOptions, cpNewName,
&attr, NULL);
if (status == 0) {
/* The target exists, and so must fail the rename. */
LOG(4, ("HgfsServerRename: error: target %s exists\n", localNewName));
status = EEXIST;
goto exit;
}
}
/*
* Renaming a file requires both read and write permssions for the target file.
* However the error code must be different depending on the existence
* of the file with the same name.
*/
if (!shareInfo.writePermissions || !shareInfo.readPermissions) {
status = HgfsAccess(localNewName, cpNewName, cpNewNameLen);
if (status == 0 || status == ENOENT) {
status = EACCES;
}
LOG(4, ("HgfsServerRename: failed access check, error %d\n", status));
goto exit;
}
LOG(4, ("HgfsServerRename: renaming \"%s\" to \"%s\"\n",
localOldName, localNewName));
error = Posix_Rename(localOldName, localNewName);
if (error) {
error = errno;
LOG(4, ("HgfsServerRename: error: %s\n", strerror(error)));
status = error;
goto exit;
}
/*
* Update all file nodes referring to this filename to the new name.
*
* XXX: Note that this operation can fail (out of memory), but we'd like
* the client to see success anyway, because the rename succeeded.
*/
status = 0;
HgfsUpdateNodeNames(localOldName, localNewName, session);
if (!HgfsPackRenameReply(packetIn, status, &packetOut, &packetOutSize)) {
status = EPROTO;
goto exit;
}
if (!HgfsPacketSend(packetOut, packetOutSize, session, 0)) {
free(packetOut);
}
exit:
free(localOldName);
free(localNewName);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerQueryVolume --
*
* Handle a Query Volume request.
*
* Right now we only handle the volume space request. Call Wiper library
* to get the volume information.
* It is possible that shared folders can belong to different volumes on
* the server. If this is the case, default to return the space information
* of the volume that has the least amount of the available space, but it's
* configurable with a config option (tools.hgfs.volumeInfoType). 2 possible
* options, min and max.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerQueryVolume(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsRequest *header;
uint32 extra;
char *utf8Name = NULL;
size_t utf8NameLen;
HgfsHandle handle;
int offset = 0;
uint64 outFreeBytes = 0;
uint64 outTotalBytes = 0;
VolumeInfoType infoType;
DirectoryEntry *dent;
HgfsInternalStatus status;
Bool firstShare = TRUE;
Bool success;
HgfsNameStatus nameStatus;
size_t failed = 0;
size_t shares = 0;
HgfsInternalStatus firstErr = 0;
char *fileName;
uint32 fileNameLength;
uint32 caseFlags = HGFS_FILE_NAME_DEFAULT_CASE;
uint64 *freeBytes;
uint64 *totalBytes;
char *packetOut;
size_t packetOutSize;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
header = (HgfsRequest *)packetIn;
if (header->op == HGFS_OP_QUERY_VOLUME_INFO_V3) {
HgfsRequestQueryVolumeV3 *requestV3 =
(HgfsRequestQueryVolumeV3 *)HGFS_REQ_GET_PAYLOAD_V3(packetIn);
HgfsReplyQueryVolumeV3 *replyV3;
packetOutSize = HGFS_REP_PAYLOAD_SIZE_V3(replyV3);
packetOut = Util_SafeMalloc(packetOutSize);
replyV3 = (HgfsReplyQueryVolumeV3 *)HGFS_REP_GET_PAYLOAD_V3(packetOut);
/*
* We don't yet support file handle for this operation.
* Clients should retry using the file name.
*/
if (requestV3->fileName.flags & HGFS_FILE_NAME_USE_FILE_DESC) {
LOG(4, ("HgfsServerQueryVolume: Doesn't support file handle.\n"));
status = EPARAMETERNOTSUPPORTED;
goto exit;
}
freeBytes = &replyV3->freeBytes;
totalBytes = &replyV3->totalBytes;
replyV3->reserved = 0;
/* Enforced by the dispatch function. */
ASSERT(packetSize >= HGFS_REQ_PAYLOAD_SIZE_V3(requestV3));
extra = packetSize - HGFS_REQ_PAYLOAD_SIZE_V3(requestV3);
caseFlags = requestV3->fileName.caseType;
fileName = requestV3->fileName.name;
fileNameLength = requestV3->fileName.length;
LOG(4, ("HgfsServerQueryVolume: HGFS_OP_QUERY_VOLUME_INFO_V3\n"));
} else {
HgfsRequestQueryVolume *request = (HgfsRequestQueryVolume *)packetIn;
HgfsReplyQueryVolume *reply;
packetOutSize = sizeof *reply;
packetOut = Util_SafeMalloc(packetOutSize);
reply = (HgfsReplyQueryVolume *)packetOut;
freeBytes = &reply->freeBytes;
totalBytes = &reply->totalBytes;
/* Enforced by the dispatch function. */
ASSERT(packetSize >= sizeof *request);
extra = packetSize - sizeof *request;
fileName = request->fileName.name;
fileNameLength = request->fileName.length;
}
/*
* request->fileName.length is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (fileNameLength > extra) {
/* The input packet is smaller than the request. */
status = EPROTO;
goto exit;
}
/* It is now safe to read the file name field. */
nameStatus = HgfsServerGetShareInfo(fileName,
fileNameLength,
caseFlags,
&shareInfo,
&utf8Name,
&utf8NameLen);
switch (nameStatus) {
case HGFS_NAME_STATUS_INCOMPLETE_BASE:
/*
* This is the base of our namespace. Clients can request a
* QueryVolumeInfo on it, on individual shares, or on just about
* any pathname.
*/
LOG(4,("HgfsServerQueryVolume: opened search on base\n"));
status = HgfsServerSearchVirtualDir(HgfsServerPolicy_GetShares,
HgfsServerPolicy_GetSharesInit,
HgfsServerPolicy_GetSharesCleanup,
DIRECTORY_SEARCH_TYPE_BASE,
session,
&handle);
if (status != 0) {
goto exit;
}
/*
* If we're outside the Tools, find out if we're to compute the minimum
* values across all shares, or the maximum values.
*/
infoType = VOLUME_INFO_TYPE_MIN;
#ifndef VMX86_TOOLS
{
char *volumeInfoType = Config_GetString("min",
"tools.hgfs.volumeInfoType");
if (!Str_Strcasecmp(volumeInfoType, "max")) {
infoType = VOLUME_INFO_TYPE_MAX;
}
free(volumeInfoType);
}
#endif
/*
* Now go through all shares and get share paths on the server.
* Then retrieve space info for each share's volume.
*/
offset = 0;
while ((dent = HgfsGetSearchResult(handle, session, offset, TRUE)) != NULL) {
char const *sharePath;
size_t sharePathLen;
uint64 freeBytes = 0;
uint64 totalBytes = 0;
unsigned int length;
length = strlen(dent->d_name);
/*
* Now that the server is passing '.' and ".." around as dents, we
* need to make sure to handle them properly. In particular, they
* should be ignored within QueryVolume, as they're not real shares.
*/
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) {
LOG(4, ("HgfsServerQueryVolume: Skipping fake share %s\n",
dent->d_name));
free(dent);
continue;
}
/*
* The above check ignores '.' and '..' so we do not include them in
* the share count here.
*/
shares++;
/*
* Check permission on the share and get the share path. It is not
* fatal if these do not succeed. Instead we ignore the failures
* (apart from logging them) until we have processed all shares. Only
* then do we check if there were any failures; if all shares failed
* to process then we bail out with an error code.
*/
nameStatus = HgfsServerPolicy_GetSharePath(dent->d_name,
length,
HGFS_OPEN_MODE_READ_ONLY,
&sharePathLen,
&sharePath);
free(dent);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerQueryVolume: No such share or access "
"denied\n"));
if (0 == firstErr) {
firstErr = HgfsConvertFromNameStatus(nameStatus);
}
failed++;
continue;
}
if (!HgfsServerStatFs(sharePath, sharePathLen,
&freeBytes, &totalBytes)) {
LOG(4, ("HgfsServerQueryVolume: error getting volume "
"information\n"));
if (0 == firstErr) {
firstErr = EIO;
}
failed++;
continue;
}
/*
* Pick the drive with amount of space available and return that
* according to different volume info type.
*/
switch (infoType) {
case VOLUME_INFO_TYPE_MIN:
if ((outFreeBytes > freeBytes) || firstShare) {
firstShare = FALSE;
outFreeBytes = freeBytes;
outTotalBytes = totalBytes;
}
break;
case VOLUME_INFO_TYPE_MAX:
if ((outFreeBytes < freeBytes)) {
outFreeBytes = freeBytes;
outTotalBytes = totalBytes;
}
break;
default:
NOT_IMPLEMENTED();
}
}
if (!HgfsRemoveSearch(handle, session)) {
LOG(4, ("HgfsServerQueryVolume: could not close search on base\n"));
}
break;
case HGFS_NAME_STATUS_COMPLETE:
ASSERT(utf8Name);
LOG(4,("HgfsServerQueryVolume: querying path %s\n", utf8Name));
success = HgfsServerStatFs(utf8Name, utf8NameLen,
&outFreeBytes, &outTotalBytes);
free(utf8Name);
if (!success) {
LOG(4, ("HgfsServerQueryVolume: error getting volume information\n"));
status = EIO;
goto exit;
}
break;
default:
LOG(4,("HgfsServerQueryVolume: file access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
*freeBytes = outFreeBytes;
*totalBytes = outTotalBytes;
status = 0;
if (!HgfsPackAndSendPacket(packetOut, packetOutSize, status, header->id,
session, 0)) {
goto exit;
}
return status;
exit:
free(packetOut);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerSymlinkCreate --
*
* Handle a SymlinkCreate request.
*
* Results:
* Zero on success.
* Non-zero on failure.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerSymlinkCreate(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
HgfsRequest *header;
uint32 extra;
char *localSymlinkName = NULL;
char localTargetName[HGFS_PACKET_MAX];
int error;
HgfsNameStatus nameStatus;
uint32 caseFlags = HGFS_FILE_NAME_DEFAULT_CASE;
char *symlinkName;
uint32 symlinkNameLength;
char *targetName;
uint32 targetNameLength;
HgfsShareOptions configOptions;
char *packetOut = NULL;
size_t packetOutSize;
HgfsInternalStatus status = 0;
size_t localSymlinkNameLen;
HgfsShareInfo shareInfo;
ASSERT(packetIn);
ASSERT(session);
header = (HgfsRequest *)packetIn;
if (header->op == HGFS_OP_CREATE_SYMLINK_V3) {
HgfsRequestSymlinkCreateV3 *requestV3;
HgfsReplySymlinkCreateV3 *replyV3;
HgfsFileNameV3 *targetNameP;
requestV3 = (HgfsRequestSymlinkCreateV3 *)HGFS_REQ_GET_PAYLOAD_V3(packetIn);
LOG(4, ("HgfsServerSymlinkCreate: HGFS_OP_CREATE_SYMLINK_V3\n"));
/* Enforced by the dispatch function. */
ASSERT(packetSize >= HGFS_REQ_PAYLOAD_SIZE_V3(requestV3));
extra = packetSize - HGFS_REQ_PAYLOAD_SIZE_V3(requestV3);
caseFlags = requestV3->symlinkName.caseType;
symlinkName = requestV3->symlinkName.name;
symlinkNameLength = requestV3->symlinkName.length;
/*
* targetName starts after symlinkName + the variable length array
* in symlinkName.
*/
targetNameP = (HgfsFileNameV3 *)(symlinkName + 1 + symlinkNameLength);
targetName = targetNameP->name;
targetNameLength = targetNameP->length;
/*
* We don't yet support file handle for this operation.
* Clients should retry using the file name.
*/
if (requestV3->symlinkName.flags & HGFS_FILE_NAME_USE_FILE_DESC ||
targetNameP->flags & HGFS_FILE_NAME_USE_FILE_DESC) {
LOG(4, ("HgfsServerSymlinkCreate: Doesn't support file handle.\n"));
return EPARAMETERNOTSUPPORTED;
}
packetOutSize = HGFS_REP_PAYLOAD_SIZE_V3(replyV3);
packetOut = Util_SafeMalloc(packetOutSize);
replyV3 = (HgfsReplySymlinkCreateV3 *)HGFS_REP_GET_PAYLOAD_V3(packetOut);
replyV3->reserved = 0;
} else {
HgfsRequestSymlinkCreate *request;
HgfsFileName *targetNameP;
request = (HgfsRequestSymlinkCreate *)packetIn;
/* Enforced by the dispatch function. */
ASSERT(packetSize >= sizeof *request);
extra = packetSize - sizeof *request;
symlinkName = request->symlinkName.name;
symlinkNameLength = request->symlinkName.length;
/*
* targetName starts after symlinkName + the variable length array
* in symlinkName.
*/
targetNameP = (HgfsFileName *)(symlinkName + 1 + symlinkNameLength);
targetName = targetNameP->name;
targetNameLength = targetNameP->length;
packetOutSize = sizeof (HgfsReplySymlinkCreate);
packetOut = Util_SafeMalloc(packetOutSize);
}
/*
* request->symlinkName.length is user-provided, so this test must
* be carefully written to prevent wraparounds.
*/
if (symlinkNameLength > extra) {
/* The input packet is smaller than the request */
status = EPROTO;
goto exit;
}
/*
* It is now safe to read the symlink file name and the
* "targetName" field
*/
nameStatus = HgfsServerGetShareInfo(symlinkName,
symlinkNameLength,
caseFlags,
&shareInfo,
&localSymlinkName,
&localSymlinkNameLen);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerSymlinkCreate: symlink name access check failed\n"));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
if (!shareInfo.writePermissions ) {
status = HgfsAccess(localSymlinkName, symlinkName, symlinkNameLength);
if (status != 0) {
if (status == ENOENT) {
status = EACCES;
}
} else {
status = EEXIST;
}
LOG(4, ("HgfsServerCreateDir: failed access check, error %d\n", status));
goto exit;
}
ASSERT(localSymlinkName);
extra -= symlinkNameLength;
/*
* targetNameLength is user-provided, so this test must be carefully
* written to prevent wraparounds.
*/
if (targetNameLength > extra) {
/* The input packet is smaller than the request */
status = EPROTO;
goto exit;
}
/* It is now safe to read the target file name */
/* Get the config options. */
nameStatus = HgfsServerPolicy_GetShareOptions(symlinkName, symlinkNameLength,
&configOptions);
if (nameStatus != HGFS_NAME_STATUS_COMPLETE) {
LOG(4, ("HgfsServerSymlinkCreate: no matching share: %s.\n", symlinkName));
status = HgfsConvertFromNameStatus(nameStatus);
goto exit;
}
/* Convert from CPName-lite to normal and NUL-terminate. */
memcpy(localTargetName, targetName, targetNameLength);
CPNameLite_ConvertFrom(localTargetName, targetNameLength, DIRSEPC);
localTargetName[targetNameLength] = '\0';
/* Prohibit symlink ceation if symlink following is enabled. */
if (HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS)) {
status = EPERM;
goto exit;
}
LOG(4, ("HgfsServerSymlinkCreate: creating \"%s\" linked to \"%s\"\n",
localSymlinkName, localTargetName));
/* XXX: Should make use of targetNameP->flags? */
error = Posix_Symlink(localTargetName, localSymlinkName);
if (error) {
status = errno;
LOG(4, ("HgfsServerSymlinkCreate: error: %s\n", strerror(errno)));
goto exit;
}
status = 0;
if (!HgfsPackAndSendPacket(packetOut, packetOutSize, status, header->id,
session, 0)) {
goto exit;
}
free(localSymlinkName);
return status;
exit:
free(localSymlinkName);
free(packetOut);
return status;
}
/*
*----------------------------------------------------------------------
*
* HgfsServerHasSymlink --
*
* This function determines if any of the intermediate components of the
* fileName makes references outside the actual shared path. We do not
* check for the last component as none of the server operations follow
* symlinks. Also some ops that call us expect to operate on a symlink
* final component.
*
* We use following algorithm. It takes 2 parameters, sharePath and
* fileName, and returns non-zero errno if fileName makes an invalid
* reference. The idea is to resolve both the sharePath and parent
* directory of the fileName. The sharePath is already resolved
* beforehand in HgfsServerPolicyRead. During resolution, we eliminate
* all the ".", "..", and symlinks handled by the realpath(3) libc call.
*
* We use parent because last component could be a symlink or a component
* that doesn't exist. After resolving, we determine if sharePath is a
* prefix of fileName.
*
* Note that realpath(3) behaves differently on GNU and BSD systems.
* Following table lists the difference:
*
* GNU realpath BSD realpath
* ----------------------- -----------------------
*
* "/tmp/existingFile" "/tmp/existingFile" (0) "/tmp/existingFile" (0)
* "/tmp/missingFile" NULL (ENOENT) "/tmp/missingFile" (0)
* "/missingDir/foo" NULL (ENOENT) NULL (ENOENT)
* In /tmp, "" NULL (ENOENT) "/tmp" (0)
* In /tmp, "." "/tmp" (0) "/tmp" (0)
*
* Results:
* HGFS_NAME_STATUS_COMPLETE if the given path has a symlink,
an appropriate name status error otherwise.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
HgfsNameStatus
HgfsServerHasSymlink(const char *fileName, // IN
size_t fileNameLength, // IN
const char *sharePath, // IN
size_t sharePathLength) // IN
{
char *resolvedFileDirPath = NULL;
char *fileDirName = NULL;
HgfsInternalStatus status;
HgfsNameStatus nameStatus = HGFS_NAME_STATUS_COMPLETE;
ASSERT(fileName);
ASSERT(sharePath);
ASSERT(sharePathLength <= fileNameLength);
LOG(4, ("%s: fileName: %s, sharePath: %s#\n", __FUNCTION__, fileName, sharePath));
/*
* Return success if:
* - empty fileName or
* - sharePath is empty (this is for special root share that allows
* access to entire host) or
* - fileName and sharePath are same.
*/
if (fileNameLength == 0 ||
sharePathLength == 0 ||
Str_Strcmp(sharePath, fileName) == 0) {
goto exit;
}
/* Separate out parent directory of the fileName. */
File_GetPathName(fileName, &fileDirName, NULL);
/*
* File_GetPathName may return an empty string to signify the root of the filesystem.
* To simplify subsequent processing, let's convert such empty strings to "/" when
* found. See File_GetPathName header comment for details.
*/
if (strlen(fileDirName) == 0) {
char *p;
p = realloc(fileDirName, sizeof (DIRSEPS));
if (p == NULL) {
nameStatus = HGFS_NAME_STATUS_OUT_OF_MEMORY;
LOG(4, ("%s: failed to realloc fileDirName.\n", __FUNCTION__));
goto exit;
} else {
fileDirName = p;
Str_Strcpy(fileDirName, DIRSEPS, sizeof (DIRSEPS));
}
}
/*
* Resolve parent directory of fileName.
* Use realpath(2) to resolve the parent.
*/
resolvedFileDirPath = Posix_RealPath(fileDirName);
if (resolvedFileDirPath == NULL) {
/* Let's return some meaningful errors if possible. */
status = errno;
switch (status) {
case ENOENT:
nameStatus = HGFS_NAME_STATUS_DOES_NOT_EXIST;
break;
case ENOTDIR:
nameStatus = HGFS_NAME_STATUS_NOT_A_DIRECTORY;
break;
default:
nameStatus = HGFS_NAME_STATUS_FAILURE;
break;
}
LOG(4, ("%s: realpath failed: fileDirName: %s: %s\n",
__FUNCTION__, fileDirName, strerror(errno)));
goto exit;
}
/* Resolved parent should match with the shareName. */
if (Str_Strncmp(sharePath, resolvedFileDirPath, sharePathLength) != 0) {
nameStatus = HGFS_NAME_STATUS_ACCESS_DENIED;
LOG(4, ("%s: resolved parent do not match, parent: %s, resolved: %s#\n",
__FUNCTION__, fileDirName, resolvedFileDirPath));
goto exit;
}
exit:
free(resolvedFileDirPath);
free(fileDirName);
return nameStatus;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsServerServerLockChange --
*
* Called by the client when it wants to either acquire an oplock on a file
* that was previously opened, or when it wants to release/downgrade an
* oplock on a file that was previously oplocked.
*
* Results:
* EOPNOTSUPP, because this is unimplemented.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
HgfsInternalStatus
HgfsServerServerLockChange(char const *packetIn, // IN: incoming packet
size_t packetSize, // IN: size of packet
HgfsSessionInfo *session) // IN: session info
{
return EOPNOTSUPP;
}
#ifdef HGFS_OPLOCKS
/*
*-----------------------------------------------------------------------------
*
* HgfsAckOplockBreak --
*
* Platform-dependent implementation of oplock break acknowledgement.
* This function gets called when the oplock break rpc command is completed.
* The rpc oplock break command (HgfsServerOplockBreak) is in hgfsServer.c
*
* On Linux, we use fcntl() to downgrade the lease. Then we update the node
* cache, free the clientData, and call it a day.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
void
HgfsAckOplockBreak(ServerLockData *lockData, // IN: server lock info
HgfsServerLock replyLock) // IN: client has this lock
{
int fileDesc, newLock;
HgfsServerLock actualLock;
ASSERT(lockData);
fileDesc = lockData->fileDesc;
LOG(4, ("HgfsAckOplockBreak: Acknowledging break on fd %d\n", fileDesc));
/*
* The Linux server supports lock downgrading. We only downgrade to a shared
* lock if our previous call to fcntl() said we could, and if the client
* wants to downgrade to a shared lock. Otherwise, we break altogether.
*/
if (lockData->serverLock == HGFS_LOCK_SHARED &&
replyLock == HGFS_LOCK_SHARED) {
newLock = F_RDLCK;
actualLock = replyLock;
} else {
newLock = F_UNLCK;
actualLock = HGFS_LOCK_NONE;
}
/* Downgrade or acknowledge the break altogether. */
if (fcntl(fileDesc, F_SETLEASE, newLock) == -1) {
int error = errno;
Log("HgfsServer_AckServerOplockBreak: Could not break lease on fd %d: "
"%s\n", fileDesc, strerror(error));
}
/* Cleanup. */
HgfsUpdateNodeServerLock(fileDesc, actualLock);
free(lockData);
}
#endif
/*
*-----------------------------------------------------------------------------
*
* HgfsIsShareRoot --
*
* Checks if the cpName represents the root directory for a share.
* Components in CPName format are separated by NUL characters.
* CPName for the root of a share contains only one component thus
* it does not have any embedded '\0' characters in the name.
*
* Results:
* TRUE if it is the root directory, FALSE otherwise.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static Bool
HgfsIsShareRoot(char const *cpName, // IN: name to test
size_t cpNameSize) // IN: length of the name
{
size_t i;
for (i = 0; i < cpNameSize; i++) {
if (cpName[i] == '\0') {
return FALSE;
}
}
return TRUE;
}
#if defined(__APPLE__)
/*
*-----------------------------------------------------------------------------
*
* HgfsGetHiddenXattr --
*
* For Mac hosts returns true if file has invisible bit set in the FileFinder
* extended attributes.
*
* Results:
* 0 if succeeded getting attribute, error code otherwise otherwise.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetHiddenXAttr(char const *fileName, // IN: File name
Bool *attribute) // OUT: Hidden atribute
{
struct attrlist attrList;
struct FInfoAttrBuf attrBuf;
HgfsInternalStatus err;
ASSERT(fileName);
ASSERT(attribute);
memset(&attrList, 0, sizeof attrList);
attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
attrList.commonattr = ATTR_CMN_OBJTYPE | ATTR_CMN_FNDRINFO;
err = getattrlist(fileName, &attrList, &attrBuf, sizeof attrBuf, 0);
if (err == 0) {
switch (attrBuf.objType) {
case VREG: {
FileInfo *info = (FileInfo*) attrBuf.finderInfo;
uint16 finderFlags = CFSwapInt16BigToHost(info->finderFlags);
*attribute = (finderFlags & kIsInvisible) != 0;
break;
}
case VDIR: {
FolderInfo *info = (FolderInfo*) attrBuf.finderInfo;
uint16 finderFlags = CFSwapInt16BigToHost(info->finderFlags);
*attribute = (finderFlags & kIsInvisible) != 0;
break;
}
default:
LOG(4, ("HgfsGetHiddenXattr: Unrecognized object type %d\n", attrBuf.objType));
err = EINVAL;
}
} else {
LOG(4, ("HgfsGetHiddenXattr: Error %d when getting attributes\n", err));
}
return err;
}
/*
*-----------------------------------------------------------------------------
*
* ChangeInvisibleFlag --
*
* Changes value of the invisible bit in a flags variable to a value defined by
* setFlag parameter.
*
* Results:
* TRUE flag has been changed, FALSE otherwise.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static Bool
ChangeInvisibleFlag(uint16 *flags, // IN: variable that contains flags
Bool setFlag) // IN: new value for the invisible flag
{
Bool changed = FALSE;
/*
* Finder keeps, reports and expects to set flags in big endian format.
* Needs to convert to host endian before using constants
* and then convert back to big endian before saving
*/
uint16 finderFlags = CFSwapInt16BigToHost(*flags);
Bool isInvisible = (finderFlags & kIsInvisible) != 0;
if (setFlag != isInvisible) {
if (setFlag) {
finderFlags |= kIsInvisible;
} else {
finderFlags &= ~kIsInvisible;
}
*flags = CFSwapInt16HostToBig(finderFlags);
changed = TRUE;
}
return changed;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetHiddenXAttr --
*
* Sets new value for the invisible attribute of a file.
*
* Results:
* 0 if succeeded, error code otherwise.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsSetHiddenXAttr(char const *fileName, // IN: path to the file
Bool value) // IN: new value to the invisible attribute
{
HgfsInternalStatus err;
Bool changed = FALSE;
struct attrlist attrList;
struct FInfoAttrBuf attrBuf;
ASSERT(fileName);
memset(&attrList, 0, sizeof attrList);
attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
attrList.commonattr = ATTR_CMN_OBJTYPE | ATTR_CMN_FNDRINFO;
err = getattrlist(fileName, &attrList, &attrBuf, sizeof attrBuf, 0);
if (err == 0) {
switch (attrBuf.objType) {
case VREG: {
FileInfo *info = (FileInfo*) attrBuf.finderInfo;
changed = ChangeInvisibleFlag(&info->finderFlags, value);
break;
}
case VDIR: {
FolderInfo *info = (FolderInfo*) attrBuf.finderInfo;
changed = ChangeInvisibleFlag(&info->finderFlags, value);
break;
}
default:
LOG(4, ("HgfsGetHiddenXattr: Unrecognized object type %d\n", attrBuf.objType));
err = EINVAL;
}
} else {
err = errno;
}
if (changed) {
attrList.commonattr = ATTR_CMN_FNDRINFO;
err = setattrlist(fileName, &attrList, attrBuf.finderInfo,
sizeof attrBuf.finderInfo, 0);
}
return err;
}
#else // __APPLE__
/*
*-----------------------------------------------------------------------------
*
* HgfsGetHiddenXAttr --
*
* Always returns EINVAL since there is no support for invisible files in Linux
* HGFS server.
*
* Results:
* Currently always returns EINVAL. Will return 0 when support for invisible files
* is implemented in Linux server.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsGetHiddenXAttr(char const *fileName, // IN: File name
Bool *attribute) // OUT: Value of the hidden attribute
{
return EINVAL;
}
/*
*-----------------------------------------------------------------------------
*
* HgfsSetHiddenXAttr --
*
* Sets new value for the invisible attribute of a file.
* Currently Linux server does not support invisible or hiddden files thus
* the function fails when a attempt to mark a file as hidden is made.
*
* Results:
* 0 if succeeded, error code otherwise.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static HgfsInternalStatus
HgfsSetHiddenXAttr(char const *fileName, // IN: File name
Bool value) // IN: Value of the attribute to set
{
return value ? EINVAL : 0;
}
#endif // __APPLE__
|