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
|
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package model
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
mrand "math/rand"
"os"
"path/filepath"
"runtime/pprof"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/syncthing/syncthing/lib/build"
"github.com/syncthing/syncthing/lib/config"
"github.com/syncthing/syncthing/lib/db"
"github.com/syncthing/syncthing/lib/db/backend"
"github.com/syncthing/syncthing/lib/events"
"github.com/syncthing/syncthing/lib/fs"
"github.com/syncthing/syncthing/lib/ignore"
"github.com/syncthing/syncthing/lib/osutil"
"github.com/syncthing/syncthing/lib/protocol"
protocolmocks "github.com/syncthing/syncthing/lib/protocol/mocks"
srand "github.com/syncthing/syncthing/lib/rand"
"github.com/syncthing/syncthing/lib/semaphore"
"github.com/syncthing/syncthing/lib/testutil"
"github.com/syncthing/syncthing/lib/versioner"
)
func newState(t testing.TB, cfg config.Configuration) (*testModel, context.CancelFunc) {
wcfg, cancel := newConfigWrapper(cfg)
m := setupModel(t, wcfg)
for _, dev := range cfg.Devices {
m.AddConnection(newFakeConnection(dev.DeviceID, m), protocol.Hello{})
}
return m, cancel
}
func createClusterConfig(remote protocol.DeviceID, ids ...string) *protocol.ClusterConfig {
cc := &protocol.ClusterConfig{
Folders: make([]protocol.Folder, len(ids)),
}
for i, id := range ids {
cc.Folders[i] = protocol.Folder{
ID: id,
Label: id,
}
}
return addFolderDevicesToClusterConfig(cc, remote)
}
func addFolderDevicesToClusterConfig(cc *protocol.ClusterConfig, remote protocol.DeviceID) *protocol.ClusterConfig {
for i := range cc.Folders {
cc.Folders[i].Devices = []protocol.Device{
{ID: myID},
{ID: remote},
}
}
return cc
}
func TestRequest(t *testing.T) {
wrapper, fcfg, cancel := newDefaultCfgWrapper()
ffs := fcfg.Filesystem(nil)
defer cancel()
m := setupModel(t, wrapper)
defer cleanupModel(m)
fd, err := ffs.Create("foo")
if err != nil {
t.Fatal(err)
}
if _, err := fd.Write([]byte("foobar")); err != nil {
t.Fatal(err)
}
fd.Close()
m.ScanFolder("default")
// Existing, shared file
res, err := m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 6})
if err != nil {
t.Fatal(err)
}
bs := res.Data()
if !bytes.Equal(bs, []byte("foobar")) {
t.Errorf("Incorrect data from request: %q", string(bs))
}
// Existing, nonshared file
_, err = m.Request(device2Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 6})
if err == nil {
t.Error("Unexpected nil error on insecure file read")
}
// Nonexistent file
_, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "nonexistent", Size: 6})
if err == nil {
t.Error("Unexpected nil error on insecure file read")
}
// Shared folder, but disallowed file name
_, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "../walk.go", Size: 6})
if err == nil {
t.Error("Unexpected nil error on insecure file read")
}
// Negative size
_, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: -4})
if err == nil {
t.Error("Unexpected nil error on insecure file read")
}
// Larger block than available
_, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 42, Hash: []byte("hash necessary but not checked")})
if err == nil {
t.Error("Unexpected nil error on read past end of file")
}
_, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 42})
if err != nil {
t.Error("Unexpected error when large read should be permitted")
}
}
func genFiles(n int) []protocol.FileInfo {
files := make([]protocol.FileInfo, n)
t := time.Now().Unix()
for i := 0; i < n; i++ {
files[i] = protocol.FileInfo{
Name: fmt.Sprintf("file%d", i),
ModifiedS: t,
Sequence: int64(i + 1),
Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}},
}
}
return files
}
func BenchmarkIndex_10000(b *testing.B) {
benchmarkIndex(b, 10000)
}
func BenchmarkIndex_100(b *testing.B) {
benchmarkIndex(b, 100)
}
func benchmarkIndex(b *testing.B, nfiles int) {
m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
files := genFiles(nfiles)
must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
b.ResetTimer()
for i := 0; i < b.N; i++ {
must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
}
b.ReportAllocs()
}
func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
benchmarkIndexUpdate(b, 10000, 10000)
}
func BenchmarkIndexUpdate_10000_100(b *testing.B) {
benchmarkIndexUpdate(b, 10000, 100)
}
func BenchmarkIndexUpdate_10000_1(b *testing.B) {
benchmarkIndexUpdate(b, 10000, 1)
}
func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
files := genFiles(nfiles)
ufiles := genFiles(nufiles)
must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
b.ResetTimer()
for i := 0; i < b.N; i++ {
must(b, m.IndexUpdate(device1Conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: ufiles}))
}
b.ReportAllocs()
}
func BenchmarkRequestOut(b *testing.B) {
m := setupModel(b, defaultCfgWrapper)
defer cleanupModel(m)
const n = 1000
files := genFiles(n)
fc := newFakeConnection(device1, m)
for _, f := range files {
fc.addFile(f.Name, 0o644, protocol.FileInfoTypeFile, []byte("some data to return"))
}
m.AddConnection(fc, protocol.Hello{})
must(b, m.Index(device1Conn, &protocol.Index{Folder: "default", Files: files}))
b.ResetTimer()
for i := 0; i < b.N; i++ {
data, err := m.RequestGlobal(context.Background(), device1, "default", files[i%n].Name, 0, 0, 32, nil, 0, false)
if err != nil {
b.Error(err)
}
if data == nil {
b.Error("nil data")
}
}
}
func BenchmarkRequestInSingleFile(b *testing.B) {
w, cancel := newConfigWrapper(defaultCfg)
defer cancel()
ffs := w.FolderList()[0].Filesystem(nil)
m := setupModel(b, w)
defer cleanupModel(m)
buf := make([]byte, 128<<10)
srand.Read(buf)
must(b, ffs.MkdirAll("request/for/a/file/in/a/couple/of/dirs", 0o755))
writeFile(b, ffs, "request/for/a/file/in/a/couple/of/dirs/128k", buf)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "request/for/a/file/in/a/couple/of/dirs/128k", Size: 128 << 10}); err != nil {
b.Error(err)
}
}
b.SetBytes(128 << 10)
}
func TestDeviceRename(t *testing.T) {
hello := protocol.Hello{
ClientName: "syncthing",
ClientVersion: "v0.9.4",
}
rawCfg := config.New(device1)
rawCfg.Devices = []config.DeviceConfiguration{
{
DeviceID: device1,
},
}
cfg, cfgCancel := newConfigWrapper(rawCfg)
defer cfgCancel()
m := newModel(t, cfg, myID, nil)
if cfg.Devices()[device1].Name != "" {
t.Errorf("Device already has a name")
}
conn := newFakeConnection(device1, m)
m.AddConnection(conn, hello)
m.ServeBackground()
defer cleanupModel(m)
if cfg.Devices()[device1].Name != "" {
t.Errorf("Device already has a name")
}
m.Closed(conn, protocol.ErrTimeout)
hello.DeviceName = "tester"
m.AddConnection(conn, hello)
if cfg.Devices()[device1].Name != "tester" {
t.Errorf("Device did not get a name")
}
m.Closed(conn, protocol.ErrTimeout)
hello.DeviceName = "tester2"
m.AddConnection(conn, hello)
if cfg.Devices()[device1].Name != "tester" {
t.Errorf("Device name got overwritten")
}
ffs := fs.NewFilesystem(fs.FilesystemTypeFake, srand.String(32)+"?content=true")
path := "someConfigfile"
must(t, saveConfig(ffs, path, cfg.RawCopy()))
cfgw, _, err := loadConfig(ffs, path, myID, events.NoopLogger)
if err != nil {
t.Error(err)
return
}
if cfgw.Devices()[device1].Name != "tester" {
t.Errorf("Device name not saved in config")
}
m.Closed(conn, protocol.ErrTimeout)
waiter, err := cfg.Modify(func(cfg *config.Configuration) {
cfg.Options.OverwriteRemoteDevNames = true
})
must(t, err)
waiter.Wait()
hello.DeviceName = "tester2"
m.AddConnection(conn, hello)
if cfg.Devices()[device1].Name != "tester2" {
t.Errorf("Device name not overwritten")
}
}
// Adjusted copy of the original function for testing purposes
func saveConfig(ffs fs.Filesystem, path string, cfg config.Configuration) error {
fd, err := ffs.Create(path)
if err != nil {
l.Debugln("Create:", err)
return err
}
if err := cfg.WriteXML(osutil.LineEndingsWriter(fd)); err != nil {
l.Debugln("WriteXML:", err)
fd.Close()
return err
}
if err := fd.Close(); err != nil {
l.Debugln("Close:", err)
return err
}
if _, err := ffs.Lstat(path); err != nil {
return err
}
return nil
}
// Adjusted copy of the original function for testing purposes
func loadConfig(ffs fs.Filesystem, path string, myID protocol.DeviceID, evLogger events.Logger) (config.Wrapper, int, error) {
if _, err := ffs.Lstat(path); err != nil {
return nil, 0, err
}
fd, err := ffs.OpenFile(path, fs.OptReadWrite, 0o666)
if err != nil {
return nil, 0, err
}
defer fd.Close()
cfg, originalVersion, err := config.ReadXML(fd, myID)
if err != nil {
return nil, 0, err
}
return config.Wrap(path, cfg, myID, evLogger), originalVersion, nil
}
func TestClusterConfig(t *testing.T) {
cfg := config.New(device1)
cfg.Options.MinHomeDiskFree.Value = 0 // avoids unnecessary free space checks
cfg.Devices = []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
{
DeviceID: device2,
},
}
cfg.Folders = []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata1",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata2",
Paused: true, // should still be included
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder3",
Path: "testdata3",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
// should not be included, does not include device2
},
},
}
wrapper, cancel := newConfigWrapper(cfg)
defer cancel()
m := newModel(t, wrapper, myID, nil)
m.ServeBackground()
defer cleanupModel(m)
cm, _ := m.generateClusterConfig(device2)
if l := len(cm.Folders); l != 2 {
t.Fatalf("Incorrect number of folders %d != 2", l)
}
r := cm.Folders[0]
if r.ID != "folder1" {
t.Errorf("Incorrect folder %q != folder1", r.ID)
}
if l := len(r.Devices); l != 2 {
t.Errorf("Incorrect number of devices %d != 2", l)
}
if id := r.Devices[0].ID; id != device1 {
t.Errorf("Incorrect device ID %s != %s", id, device1)
}
if !r.Devices[0].Introducer {
t.Error("Device1 should be flagged as Introducer")
}
if id := r.Devices[1].ID; id != device2 {
t.Errorf("Incorrect device ID %s != %s", id, device2)
}
if r.Devices[1].Introducer {
t.Error("Device2 should not be flagged as Introducer")
}
r = cm.Folders[1]
if r.ID != "folder2" {
t.Errorf("Incorrect folder %q != folder2", r.ID)
}
if l := len(r.Devices); l != 2 {
t.Errorf("Incorrect number of devices %d != 2", l)
}
if id := r.Devices[0].ID; id != device1 {
t.Errorf("Incorrect device ID %s != %s", id, device1)
}
if !r.Devices[0].Introducer {
t.Error("Device1 should be flagged as Introducer")
}
if id := r.Devices[1].ID; id != device2 {
t.Errorf("Incorrect device ID %s != %s", id, device2)
}
if r.Devices[1].Introducer {
t.Error("Device2 should not be flagged as Introducer")
}
}
func TestIntroducer(t *testing.T) {
var introducedByAnyone protocol.DeviceID
// LocalDeviceID is a magic value meaning don't check introducer
contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
for _, dev := range cfg.Devices {
if dev.DeviceID.Equals(id) {
if introducedBy.Equals(introducedByAnyone) {
return true
}
return dev.IntroducedBy.Equals(introducedBy)
}
}
return false
}
m, cancel := newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
},
},
})
cc := basicClusterConfig(myID, device1, "folder1", "folder2")
cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
ID: device2,
Introducer: true,
SkipIntroductionRemovals: true,
})
cc.Folders[1].Devices = append(cc.Folders[1].Devices, protocol.Device{
ID: device2,
Introducer: true,
SkipIntroductionRemovals: true,
EncryptionPasswordToken: []byte("faketoken"),
})
m.ClusterConfig(device1Conn, cc)
if newDev, ok := m.cfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
t.Error("device 2 missing or wrong flags")
}
if !contains(m.cfg.Folders()["folder1"], device2, device1) {
t.Error("expected folder 1 to have device2 introduced by device 1")
}
for _, devCfg := range m.cfg.Folders()["folder2"].Devices {
if devCfg.DeviceID == device2 {
t.Error("Device was added even though it's untrusted")
}
}
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
},
},
})
cc = basicClusterConfig(myID, device1, "folder2")
cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
ID: device2,
Introducer: true,
SkipIntroductionRemovals: true,
})
m.ClusterConfig(device1Conn, cc)
// Should not get introducer, as it's already unset, and it's an existing device.
if newDev, ok := m.cfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
t.Error("device 2 missing or changed flags")
}
if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
t.Error("expected device 2 to be removed from folder 1")
}
if !contains(m.cfg.Folders()["folder2"], device2, device1) {
t.Error("expected device 2 to be added to folder 2")
}
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
},
})
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
if _, ok := m.cfg.Device(device2); ok {
t.Error("device 2 should have been removed")
}
if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
t.Error("expected device 2 to be removed from folder 1")
}
if contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
t.Error("expected device 2 to be removed from folder 2")
}
// Two cases when removals should not happen
// 1. Introducer flag no longer set on device
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: false,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
},
})
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
if _, ok := m.cfg.Device(device2); !ok {
t.Error("device 2 should not have been removed")
}
if !contains(m.cfg.Folders()["folder1"], device2, device1) {
t.Error("expected device 2 not to be removed from folder 1")
}
if !contains(m.cfg.Folders()["folder2"], device2, device1) {
t.Error("expected device 2 not to be removed from folder 2")
}
// 2. SkipIntroductionRemovals is set
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
SkipIntroductionRemovals: true,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
},
},
})
cc = basicClusterConfig(myID, device1, "folder2")
cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
ID: device2,
Introducer: true,
SkipIntroductionRemovals: true,
})
m.ClusterConfig(device1Conn, cc)
if _, ok := m.cfg.Device(device2); !ok {
t.Error("device 2 should not have been removed")
}
if !contains(m.cfg.Folders()["folder1"], device2, device1) {
t.Error("expected device 2 not to be removed from folder 1")
}
if !contains(m.cfg.Folders()["folder2"], device2, device1) {
t.Error("expected device 2 not to be added to folder 2")
}
// Test device not being removed as it's shared without an introducer.
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2},
},
},
},
})
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
if _, ok := m.cfg.Device(device2); !ok {
t.Error("device 2 should not have been removed")
}
if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
t.Error("expected device 2 to be removed from folder 1")
}
if !contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
t.Error("expected device 2 not to be removed from folder 2")
}
// Test device not being removed as it's shared by a different introducer.
cleanupModel(m)
cancel()
m, cancel = newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
{
DeviceID: device2,
IntroducedBy: device1,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: device1},
},
},
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder2",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
{DeviceID: device2, IntroducedBy: myID},
},
},
},
})
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
if _, ok := m.cfg.Device(device2); !ok {
t.Error("device 2 should not have been removed")
}
if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
t.Error("expected device 2 to be removed from folder 1")
}
if !contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
t.Error("expected device 2 not to be removed from folder 2")
}
}
func TestIssue4897(t *testing.T) {
m, cancel := newState(t, config.Configuration{
Version: config.CurrentVersion,
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
Introducer: true,
},
},
Folders: []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: "testdata",
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
Paused: true,
},
},
})
defer cleanupModel(m)
cancel()
cm, _ := m.generateClusterConfig(device1)
if l := len(cm.Folders); l != 1 {
t.Errorf("Cluster config contains %v folders, expected 1", l)
}
}
// TestIssue5063 is about a panic in connection with modifying config in quick
// succession, related with auto accepted folders. It's unclear what exactly, a
// relevant bit seems to be here:
// PR-comments: https://github.com/syncthing/syncthing/pull/5069/files#r203146546
// Issue: https://github.com/syncthing/syncthing/pull/5509
func TestIssue5063(t *testing.T) {
m, cancel := newState(t, defaultAutoAcceptCfg)
defer cleanupModel(m)
defer cancel()
m.mut.Lock()
for _, c := range m.connections {
conn := c.(*fakeConnection)
conn.CloseCalls(func(_ error) {})
defer m.Closed(c, errStopped) // to unblock deferred m.Stop()
}
m.mut.Unlock()
wg := sync.WaitGroup{}
addAndVerify := func(id string) {
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id)
}
wg.Done()
}
reps := 10
ids := make([]string, reps)
for i := 0; i < reps; i++ {
wg.Add(1)
ids[i] = srand.String(8)
go addAndVerify(ids[i])
}
finished := make(chan struct{})
go func() {
wg.Wait()
close(finished)
}()
select {
case <-finished:
case <-time.After(10 * time.Second):
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
t.Fatal("Timed out before all devices were added")
}
}
func TestAutoAcceptRejected(t *testing.T) {
// Nothing happens if AutoAcceptFolders not set
tcfg := defaultAutoAcceptCfg.Copy()
for i := range tcfg.Devices {
tcfg.Devices[i].AutoAcceptFolders = false
}
m, cancel := newState(t, tcfg)
// defer cleanupModel(m)
defer cancel()
id := srand.String(8)
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if cfg, ok := m.cfg.Folder(id); ok && cfg.SharedWith(device1) {
t.Error("unexpected shared", id)
}
}
func TestAutoAcceptNewFolder(t *testing.T) {
// New folder
m, cancel := newState(t, defaultAutoAcceptCfg)
defer cleanupModel(m)
defer cancel()
id := srand.String(8)
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id)
}
}
func TestAutoAcceptNewFolderFromTwoDevices(t *testing.T) {
m, cancel := newState(t, defaultAutoAcceptCfg)
defer cleanupModel(m)
defer cancel()
id := srand.String(8)
defer os.RemoveAll(id)
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id)
}
if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
t.Error("unexpected expected shared", id)
}
m.ClusterConfig(device2Conn, createClusterConfig(device2, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device2) {
t.Error("expected shared", id)
}
}
func TestAutoAcceptNewFolderFromOnlyOneDevice(t *testing.T) {
modifiedCfg := defaultAutoAcceptCfg.Copy()
modifiedCfg.Devices[2].AutoAcceptFolders = false
m, cancel := newState(t, modifiedCfg)
id := srand.String(8)
defer os.RemoveAll(id)
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id)
}
if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
t.Error("unexpected expected shared", id)
}
m.ClusterConfig(device2Conn, createClusterConfig(device2, id))
if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
t.Error("unexpected shared", id)
}
}
func TestAutoAcceptNewFolderPremutationsNoPanic(t *testing.T) {
if testing.Short() {
t.Skip("short tests only")
}
id := srand.String(8)
label := srand.String(8)
premutations := []protocol.Folder{
{ID: id, Label: id},
{ID: id, Label: label},
{ID: label, Label: id},
{ID: label, Label: label},
}
localFolders := append(premutations, protocol.Folder{})
for _, localFolder := range localFolders {
for _, localFolderPaused := range []bool{false, true} {
for _, dev1folder := range premutations {
for _, dev2folder := range premutations {
cfg := defaultAutoAcceptCfg.Copy()
if localFolder.Label != "" {
fcfg := newFolderConfiguration(defaultCfgWrapper, localFolder.ID, localFolder.Label, config.FilesystemTypeFake, localFolder.ID)
fcfg.Paused = localFolderPaused
cfg.Folders = append(cfg.Folders, fcfg)
}
m, cancel := newState(t, cfg)
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{
Folders: []protocol.Folder{dev1folder},
})
m.ClusterConfig(device2Conn, &protocol.ClusterConfig{
Folders: []protocol.Folder{dev2folder},
})
cleanupModel(m)
cancel()
}
}
}
}
}
func TestAutoAcceptMultipleFolders(t *testing.T) {
// Multiple new folders
id1 := srand.String(8)
defer os.RemoveAll(id1)
id2 := srand.String(8)
defer os.RemoveAll(id2)
m, cancel := newState(t, defaultAutoAcceptCfg)
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, createClusterConfig(device1, id1, id2))
if fcfg, ok := m.cfg.Folder(id1); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id1)
}
if fcfg, ok := m.cfg.Folder(id2); !ok || !fcfg.SharedWith(device1) {
t.Error("expected shared", id2)
}
}
func TestAutoAcceptExistingFolder(t *testing.T) {
// Existing folder
id := srand.String(8)
idOther := srand.String(8) // To check that path does not get changed.
tcfg := defaultAutoAcceptCfg.Copy()
tcfg.Folders = []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: id,
Path: idOther, // To check that path does not get changed.
},
}
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device1) {
t.Error("missing folder, or shared", id)
}
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || fcfg.Path != idOther {
t.Error("missing folder, or unshared, or path changed", id)
}
}
func TestAutoAcceptNewAndExistingFolder(t *testing.T) {
// New and existing folder
id1 := srand.String(8)
id2 := srand.String(8)
tcfg := defaultAutoAcceptCfg.Copy()
tcfg.Folders = []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: id1,
Path: id1, // from previous test case, to verify that path doesn't get changed.
},
}
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
if fcfg, ok := m.cfg.Folder(id1); !ok || fcfg.SharedWith(device1) {
t.Error("missing folder, or shared", id1)
}
m.ClusterConfig(device1Conn, createClusterConfig(device1, id1, id2))
for i, id := range []string{id1, id2} {
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("missing folder, or unshared", i, id)
}
}
}
func TestAutoAcceptAlreadyShared(t *testing.T) {
// Already shared
id := srand.String(8)
tcfg := defaultAutoAcceptCfg.Copy()
tcfg.Folders = []config.FolderConfiguration{
{
FilesystemType: config.FilesystemTypeFake,
ID: id,
Path: id,
Devices: []config.FolderDeviceConfiguration{
{
DeviceID: device1,
},
},
},
}
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("missing folder, or not shared", id)
}
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("missing folder, or not shared", id)
}
}
func TestAutoAcceptNameConflict(t *testing.T) {
ffs := fs.NewFilesystem(fs.FilesystemTypeFake, srand.String(32))
id := srand.String(8)
label := srand.String(8)
ffs.MkdirAll(id, 0o777)
ffs.MkdirAll(label, 0o777)
m, cancel := newState(t, defaultAutoAcceptCfg)
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, &protocol.ClusterConfig{
Folders: []protocol.Folder{
{
ID: id,
Label: label,
},
},
})
if fcfg, ok := m.cfg.Folder(id); ok && fcfg.SharedWith(device1) {
t.Error("unexpected folder", id)
}
}
func TestAutoAcceptPrefersLabel(t *testing.T) {
// Prefers label, falls back to ID.
m, cancel := newState(t, defaultAutoAcceptCfg)
id := srand.String(8)
label := srand.String(8)
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, addFolderDevicesToClusterConfig(&protocol.ClusterConfig{
Folders: []protocol.Folder{
{
ID: id,
Label: label,
},
},
}, device1))
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, label) {
t.Error("expected shared, or wrong path", id, label, fcfg.Path)
}
}
func TestAutoAcceptFallsBackToID(t *testing.T) {
// Prefers label, falls back to ID.
m, cancel := newState(t, defaultAutoAcceptCfg)
ffs := defaultFolderConfig.Filesystem(nil)
id := srand.String(8)
label := srand.String(8)
if err := ffs.MkdirAll(label, 0o777); err != nil {
t.Error(err)
}
defer cleanupModel(m)
defer cancel()
m.ClusterConfig(device1Conn, addFolderDevicesToClusterConfig(&protocol.ClusterConfig{
Folders: []protocol.Folder{
{
ID: id,
Label: label,
},
},
}, device1))
fcfg, ok := m.cfg.Folder(id)
if !ok {
t.Error("folder configuration missing")
}
if !fcfg.SharedWith(device1) {
t.Error("folder is not shared with device1")
}
}
func TestAutoAcceptPausedWhenFolderConfigChanged(t *testing.T) {
// Existing folder
id := srand.String(8)
idOther := srand.String(8) // To check that path does not get changed.
tcfg := defaultAutoAcceptCfg.Copy()
fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", config.FilesystemTypeFake, idOther)
fcfg.Paused = true
// The order of devices here is wrong (cfg.clean() sorts them), which will cause the folder to restart.
// Because of the restart, folder gets removed from m.deviceFolder, which means that generateClusterConfig will not panic.
// This wasn't an issue before, yet keeping the test case to prove that it still isn't.
fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
DeviceID: device1,
})
tcfg.Folders = []config.FolderConfiguration{fcfg}
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("missing folder, or not shared", id)
}
if _, ok := m.folderRunners.Get(id); ok {
t.Fatal("folder running?")
}
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
m.generateClusterConfig(device1)
if fcfg, ok := m.cfg.Folder(id); !ok {
t.Error("missing folder")
} else if fcfg.Path != idOther {
t.Error("folder path changed")
} else {
for _, dev := range fcfg.DeviceIDs() {
if dev == device1 {
return
}
}
t.Error("device missing")
}
if _, ok := m.folderRunners.Get(id); ok {
t.Error("folder started")
}
}
func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
// Existing folder
id := srand.String(8)
idOther := srand.String(8) // To check that path does not get changed.
tcfg := defaultAutoAcceptCfg.Copy()
fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", config.FilesystemTypeFake, idOther)
fcfg.Paused = true
// The new folder is exactly the same as the one constructed by handleAutoAccept, which means
// the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
// to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
// did not have a file set.
fcfg.Devices = append([]config.FolderDeviceConfiguration{
{
DeviceID: device1,
},
}, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
tcfg.Folders = []config.FolderConfiguration{fcfg}
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
t.Error("missing folder, or not shared", id)
}
if _, ok := m.folderRunners.Get(id); ok {
t.Fatal("folder running?")
}
m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
m.generateClusterConfig(device1)
if fcfg, ok := m.cfg.Folder(id); !ok {
t.Error("missing folder")
} else if fcfg.Path != idOther {
t.Error("folder path changed")
} else {
for _, dev := range fcfg.DeviceIDs() {
if dev == device1 {
return
}
}
t.Error("device missing")
}
if _, ok := m.folderRunners.Get(id); ok {
t.Error("folder started")
}
}
func TestAutoAcceptEnc(t *testing.T) {
tcfg := defaultAutoAcceptCfg.Copy()
m, cancel := newState(t, tcfg)
defer cleanupModel(m)
defer cancel()
id := srand.String(8)
defer os.RemoveAll(id)
token := []byte("token")
basicCC := func() *protocol.ClusterConfig {
return &protocol.ClusterConfig{
Folders: []protocol.Folder{{
ID: id,
Label: id,
}},
}
}
// Earlier tests might cause the connection to get closed, thus ClusterConfig
// would panic.
clusterConfig := func(deviceID protocol.DeviceID, cm *protocol.ClusterConfig) {
conn := newFakeConnection(deviceID, m)
m.AddConnection(conn, protocol.Hello{})
m.ClusterConfig(conn, cm)
}
clusterConfig(device1, basicCC())
if _, ok := m.cfg.Folder(id); ok {
t.Fatal("unexpected added")
}
cc := basicCC()
cc.Folders[0].Devices = []protocol.Device{{ID: device1}}
clusterConfig(device1, cc)
if _, ok := m.cfg.Folder(id); ok {
t.Fatal("unexpected added")
}
cc = basicCC()
cc.Folders[0].Devices = []protocol.Device{{ID: myID}}
clusterConfig(device1, cc)
if _, ok := m.cfg.Folder(id); ok {
t.Fatal("unexpected added")
}
// New folder, encrypted -> add as enc
cc = createClusterConfig(device1, id)
cc.Folders[0].Devices[1].EncryptionPasswordToken = token
clusterConfig(device1, cc)
if cfg, ok := m.cfg.Folder(id); !ok {
t.Fatal("unexpected unadded")
} else {
if !cfg.SharedWith(device1) {
t.Fatal("unexpected unshared")
}
if cfg.Type != config.FolderTypeReceiveEncrypted {
t.Fatal("Folder not added as receiveEncrypted")
}
}
// New device, unencrypted on encrypted folder -> reject
clusterConfig(device2, createClusterConfig(device2, id))
if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
t.Fatal("unexpected shared")
}
// New device, encrypted on encrypted folder -> share
cc = createClusterConfig(device2, id)
cc.Folders[0].Devices[1].EncryptionPasswordToken = token
clusterConfig(device2, cc)
if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
t.Fatal("unexpected unshared")
}
// New folder, no encrypted -> add "normal"
id = srand.String(8)
defer os.RemoveAll(id)
clusterConfig(device1, createClusterConfig(device1, id))
if cfg, ok := m.cfg.Folder(id); !ok {
t.Fatal("unexpected unadded")
} else {
if !cfg.SharedWith(device1) {
t.Fatal("unexpected unshared")
}
if cfg.Type != config.FolderTypeSendReceive {
t.Fatal("Folder not added as send-receive")
}
}
// New device, encrypted on unencrypted folder -> reject
cc = createClusterConfig(device2, id)
cc.Folders[0].Devices[1].EncryptionPasswordToken = token
clusterConfig(device2, cc)
if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
t.Fatal("unexpected shared")
}
// New device, unencrypted on unencrypted folder -> share
clusterConfig(device2, createClusterConfig(device2, id))
if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
t.Fatal("unexpected unshared")
}
}
func changeIgnores(t *testing.T, m *testModel, expected []string) {
arrEqual := func(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
ignores, _, err := m.LoadIgnores("default")
if err != nil {
t.Error(err)
}
if !arrEqual(ignores, expected) {
t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
}
ignores = append(ignores, "pox")
err = m.SetIgnores("default", ignores)
if err != nil {
t.Error(err)
}
ignores2, _, err := m.LoadIgnores("default")
if err != nil {
t.Error(err)
}
if !arrEqual(ignores, ignores2) {
t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
}
if build.IsDarwin {
// see above
time.Sleep(time.Second)
} else {
time.Sleep(time.Millisecond)
}
err = m.SetIgnores("default", expected)
if err != nil {
t.Error(err)
}
ignores, _, err = m.LoadIgnores("default")
if err != nil {
t.Error(err)
}
if !arrEqual(ignores, expected) {
t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
}
}
func TestIgnores(t *testing.T) {
w, cancel := newConfigWrapper(defaultCfg)
defer cancel()
ffs := w.FolderList()[0].Filesystem(nil)
m := setupModel(t, w)
defer cleanupModel(m)
// Assure a clean start state
must(t, ffs.MkdirAll(config.DefaultMarkerName, 0o644))
writeFile(t, ffs, ".stignore", []byte(".*\nquux\n"))
folderIgnoresAlwaysReload(t, m, defaultFolderConfig)
// Make sure the initial scan has finished (ScanFolders is blocking)
m.ScanFolders()
expected := []string{
".*",
"quux",
}
changeIgnores(t, m, expected)
_, _, err := m.LoadIgnores("doesnotexist")
if err == nil {
t.Error("No error")
}
err = m.SetIgnores("doesnotexist", expected)
if err == nil {
t.Error("No error")
}
// Invalid path, treated like no patterns at all.
fcfg := config.FolderConfiguration{
ID: "fresh", Path: "XXX",
FilesystemType: config.FilesystemTypeFake,
}
ignores := ignore.New(fcfg.Filesystem(nil), ignore.WithCache(m.cfg.Options().CacheIgnoredFiles))
m.mut.Lock()
m.folderCfgs[fcfg.ID] = fcfg
m.folderIgnores[fcfg.ID] = ignores
m.mut.Unlock()
_, _, err = m.LoadIgnores("fresh")
if err != nil {
t.Error("Got error for inexistent folder path")
}
// Repeat tests with paused folder
pausedDefaultFolderConfig := defaultFolderConfig
pausedDefaultFolderConfig.Paused = true
m.restartFolder(defaultFolderConfig, pausedDefaultFolderConfig, false)
// Here folder initialization is not an issue as a paused folder isn't
// added to the model and thus there is no initial scan happening.
changeIgnores(t, m, expected)
// Make sure no .stignore file is considered valid
defer func() {
must(t, ffs.Rename(".stignore.bak", ".stignore"))
}()
must(t, ffs.Rename(".stignore", ".stignore.bak"))
changeIgnores(t, m, []string{})
}
func TestEmptyIgnores(t *testing.T) {
w, cancel := newConfigWrapper(defaultCfg)
defer cancel()
ffs := w.FolderList()[0].Filesystem(nil)
m := setupModel(t, w)
defer cleanupModel(m)
if err := m.SetIgnores("default", []string{}); err != nil {
t.Error(err)
}
if _, err := ffs.Stat(".stignore"); err == nil {
t.Error(".stignore was created despite being empty")
}
if err := m.SetIgnores("default", []string{".*", "quux"}); err != nil {
t.Error(err)
}
if _, err := ffs.Stat(".stignore"); os.IsNotExist(err) {
t.Error(".stignore does not exist")
}
if err := m.SetIgnores("default", []string{}); err != nil {
t.Error(err)
}
if _, err := ffs.Stat(".stignore"); err == nil {
t.Error(".stignore should have been deleted because it is empty")
}
}
func waitForState(t *testing.T, sub events.Subscription, folder, expected string) {
t.Helper()
timeout := time.After(5 * time.Second)
var err string
for {
select {
case ev := <-sub.C():
data := ev.Data.(map[string]interface{})
if data["folder"].(string) == folder {
if data["error"] == nil {
err = ""
} else {
err = data["error"].(string)
}
if err == expected {
return
} else {
t.Error(ev)
}
}
case <-timeout:
t.Fatalf("Timed out waiting for status: %s, current status: %v", expected, err)
}
}
}
func TestROScanRecovery(t *testing.T) {
fcfg := config.FolderConfiguration{
FilesystemType: config.FilesystemTypeFake,
ID: "default",
Path: srand.String(32),
Type: config.FolderTypeSendOnly,
RescanIntervalS: 1,
MarkerName: config.DefaultMarkerName,
}
cfg, cancel := newConfigWrapper(config.Configuration{
Version: config.CurrentVersion,
Folders: []config.FolderConfiguration{fcfg},
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
},
},
})
defer cancel()
m := newModel(t, cfg, myID, nil)
set := newFileSet(t, "default", m.db)
set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
{Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
})
ffs := fcfg.Filesystem(nil)
// Remove marker to generate an error
ffs.Remove(fcfg.MarkerName)
sub := m.evLogger.Subscribe(events.StateChanged)
defer sub.Unsubscribe()
m.ServeBackground()
defer cleanupModel(m)
waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
fd, err := ffs.Create(config.DefaultMarkerName)
if err != nil {
t.Fatal(err)
}
fd.Close()
waitForState(t, sub, "default", "")
}
func TestRWScanRecovery(t *testing.T) {
fcfg := config.FolderConfiguration{
FilesystemType: config.FilesystemTypeFake,
ID: "default",
Path: srand.String(32),
Type: config.FolderTypeSendReceive,
RescanIntervalS: 1,
MarkerName: config.DefaultMarkerName,
}
cfg, cancel := newConfigWrapper(config.Configuration{
Version: config.CurrentVersion,
Folders: []config.FolderConfiguration{fcfg},
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
},
},
})
defer cancel()
m := newModel(t, cfg, myID, nil)
set := newFileSet(t, "default", m.db)
set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
{Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
})
ffs := fcfg.Filesystem(nil)
// Generate error
if err := ffs.Remove(config.DefaultMarkerName); err != nil {
t.Fatal(err)
}
sub := m.evLogger.Subscribe(events.StateChanged)
defer sub.Unsubscribe()
m.ServeBackground()
defer cleanupModel(m)
waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
fd, err := ffs.Create(config.DefaultMarkerName)
if err != nil {
t.Error(err)
}
fd.Close()
waitForState(t, sub, "default", "")
}
func TestGlobalDirectoryTree(t *testing.T) {
m, conn, fcfg, wCancel := setupModelWithConnection(t)
defer wCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
b := func(isfile bool, path ...string) protocol.FileInfo {
typ := protocol.FileInfoTypeDirectory
var blocks []protocol.BlockInfo
if isfile {
typ = protocol.FileInfoTypeFile
blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
}
return protocol.FileInfo{
Name: filepath.Join(path...),
Type: typ,
ModifiedS: 0x666,
Blocks: blocks,
Size: 0xa,
}
}
f := func(name string) *TreeEntry {
return &TreeEntry{
Name: name,
ModTime: time.Unix(0x666, 0),
Size: 0xa,
Type: protocol.FileInfoTypeFile.String(),
}
}
d := func(name string, entries ...*TreeEntry) *TreeEntry {
return &TreeEntry{
Name: name,
ModTime: time.Unix(0x666, 0),
Size: 128,
Type: protocol.FileInfoTypeDirectory.String(),
Children: entries,
}
}
testdata := []protocol.FileInfo{
b(false, "another"),
b(false, "another", "directory"),
b(true, "another", "directory", "afile"),
b(false, "another", "directory", "with"),
b(false, "another", "directory", "with", "a"),
b(true, "another", "directory", "with", "a", "file"),
b(true, "another", "directory", "with", "file"),
b(true, "another", "file"),
b(false, "other"),
b(false, "other", "rand"),
b(false, "other", "random"),
b(false, "other", "random", "dir"),
b(false, "other", "random", "dirx"),
b(false, "other", "randomx"),
b(false, "some"),
b(false, "some", "directory"),
b(false, "some", "directory", "with"),
b(false, "some", "directory", "with", "a"),
b(true, "some", "directory", "with", "a", "file"),
b(true, "zzrootfile"),
}
expectedResult := []*TreeEntry{
d("another",
d("directory",
f("afile"),
d("with",
d("a",
f("file"),
),
f("file"),
),
),
f("file"),
),
d("other",
d("rand"),
d("random",
d("dir"),
d("dirx"),
),
d("randomx"),
),
d("some",
d("directory",
d("with",
d("a",
f("file"),
),
),
),
),
f("zzrootfile"),
}
mm := func(data interface{}) string {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
must(t, m.Index(conn, &protocol.Index{Folder: "default", Files: testdata}))
result, _ := m.GlobalDirectoryTree("default", "", -1, false)
if mm(result) != mm(expectedResult) {
t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(expectedResult))
}
result, _ = m.GlobalDirectoryTree("default", "another", -1, false)
if mm(result) != mm(findByName(expectedResult, "another").Children) {
t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(findByName(expectedResult, "another").Children))
}
result, _ = m.GlobalDirectoryTree("default", "", 0, false)
currentResult := []*TreeEntry{
d("another"),
d("other"),
d("some"),
f("zzrootfile"),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "", 1, false)
currentResult = []*TreeEntry{
d("another",
d("directory"),
f("file"),
),
d("other",
d("rand"),
d("random"),
d("randomx"),
),
d("some",
d("directory"),
),
f("zzrootfile"),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "", -1, true)
currentResult = []*TreeEntry{
d("another",
d("directory",
d("with",
d("a"),
),
),
),
d("other",
d("rand"),
d("random",
d("dir"),
d("dirx"),
),
d("randomx"),
),
d("some",
d("directory",
d("with",
d("a"),
),
),
),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "", 1, true)
currentResult = []*TreeEntry{
d("another",
d("directory"),
),
d("other",
d("rand"),
d("random"),
d("randomx"),
),
d("some",
d("directory"),
),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "another", 0, false)
currentResult = []*TreeEntry{
d("directory"),
f("file"),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "some/directory", 0, false)
currentResult = []*TreeEntry{
d("with"),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "some/directory", 1, false)
currentResult = []*TreeEntry{
d("with",
d("a"),
),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "some/directory", 2, false)
currentResult = []*TreeEntry{
d("with",
d("a",
f("file"),
),
),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
result, _ = m.GlobalDirectoryTree("default", "another", -1, true)
currentResult = []*TreeEntry{
d("directory",
d("with",
d("a"),
),
),
}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
// No prefix matching!
result, _ = m.GlobalDirectoryTree("default", "som", -1, false)
currentResult = []*TreeEntry{}
if mm(result) != mm(currentResult) {
t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
}
}
func genDeepFiles(n, d int) []protocol.FileInfo {
mrand.Seed(int64(n))
files := make([]protocol.FileInfo, n)
t := time.Now().Unix()
for i := 0; i < n; i++ {
path := ""
for i := 0; i <= d; i++ {
path = filepath.Join(path, strconv.Itoa(mrand.Int()))
}
sofar := ""
for _, path := range filepath.SplitList(path) {
sofar = filepath.Join(sofar, path)
files[i] = protocol.FileInfo{
Name: sofar,
}
i++
}
files[i].ModifiedS = t
files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
}
return files
}
func BenchmarkTree_10000_50(b *testing.B) {
benchmarkTree(b, 10000, 50)
}
func BenchmarkTree_100_50(b *testing.B) {
benchmarkTree(b, 100, 50)
}
func BenchmarkTree_100_10(b *testing.B) {
benchmarkTree(b, 100, 10)
}
func benchmarkTree(b *testing.B, n1, n2 int) {
m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
m.ScanFolder(fcfg.ID)
files := genDeepFiles(n1, n2)
must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
b.ResetTimer()
for i := 0; i < b.N; i++ {
m.GlobalDirectoryTree(fcfg.ID, "", -1, false)
}
b.ReportAllocs()
}
func TestIssue3028(t *testing.T) {
w, cancel := newConfigWrapper(defaultCfg)
defer cancel()
ffs := w.FolderList()[0].Filesystem(nil)
m := setupModel(t, w)
defer cleanupModel(m)
// Create two files that we'll delete, one with a name that is a prefix of the other.
writeFile(t, ffs, "testrm", []byte("Hello"))
writeFile(t, ffs, "testrm2", []byte("Hello"))
// Scan, and get a count of how many files are there now
m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
locorigfiles := localSize(t, m, "default").Files
globorigfiles := globalSize(t, m, "default").Files
// Delete
must(t, ffs.Remove("testrm"))
must(t, ffs.Remove("testrm2"))
// Verify that the number of files decreased by two and the number of
// deleted files increases by two
m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
loc := localSize(t, m, "default")
glob := globalSize(t, m, "default")
if loc.Files != locorigfiles-2 {
t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
}
if glob.Files != globorigfiles-2 {
t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
}
if loc.Deleted != 2 {
t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
}
if glob.Deleted != 2 {
t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
}
}
func TestIssue4357(t *testing.T) {
cfg := defaultCfgWrapper.RawCopy()
// Create a separate wrapper not to pollute other tests.
wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
defer cancel()
m := newModel(t, wrapper, myID, nil)
m.ServeBackground()
defer cleanupModel(m)
// Force the model to wire itself and add the folders
replace(t, wrapper, cfg)
if _, ok := m.folderCfgs["default"]; !ok {
t.Error("Folder should be running")
}
newCfg := wrapper.RawCopy()
newCfg.Folders[0].Paused = true
replace(t, wrapper, newCfg)
if _, ok := m.folderCfgs["default"]; ok {
t.Error("Folder should not be running")
}
if _, ok := m.cfg.Folder("default"); !ok {
t.Error("should still have folder in config")
}
replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
if _, ok := m.cfg.Folder("default"); ok {
t.Error("should not have folder in config")
}
// Add the folder back, should be running
replace(t, wrapper, cfg)
if _, ok := m.folderCfgs["default"]; !ok {
t.Error("Folder should be running")
}
if _, ok := m.cfg.Folder("default"); !ok {
t.Error("should still have folder in config")
}
// Should not panic when removing a running folder.
replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
if _, ok := m.folderCfgs["default"]; ok {
t.Error("Folder should not be running")
}
if _, ok := m.cfg.Folder("default"); ok {
t.Error("should not have folder in config")
}
}
func TestIndexesForUnknownDevicesDropped(t *testing.T) {
t.Skip()
m := newModel(t, defaultCfgWrapper, myID, nil)
files := newFileSet(t, "default", m.db)
files.Drop(device1)
files.Update(device1, genFiles(1))
files.Drop(device2)
files.Update(device2, genFiles(1))
if len(files.ListDevices()) != 2 {
t.Error("expected two devices")
}
m.newFolder(defaultFolderConfig, false)
defer cleanupModel(m)
// Remote sequence is cached, hence need to recreated.
files = newFileSet(t, "default", m.db)
if l := len(files.ListDevices()); l != 1 {
t.Errorf("Expected one device got %v", l)
}
}
func TestSharedWithClearedOnDisconnect(t *testing.T) {
wcfg, cancel := newConfigWrapper(defaultCfg)
defer cancel()
addDevice2(t, wcfg, wcfg.FolderList()[0])
m := setupModel(t, wcfg)
defer cleanupModel(m)
conn1 := newFakeConnection(device1, m)
m.AddConnection(conn1, protocol.Hello{})
conn2 := newFakeConnection(device2, m)
m.AddConnection(conn2, protocol.Hello{})
m.ClusterConfig(conn1, &protocol.ClusterConfig{
Folders: []protocol.Folder{
{
ID: "default",
Devices: []protocol.Device{
{ID: myID},
{ID: device1},
{ID: device2},
},
},
},
})
m.ClusterConfig(conn2, &protocol.ClusterConfig{
Folders: []protocol.Folder{
{
ID: "default",
Devices: []protocol.Device{
{ID: myID},
{ID: device1},
{ID: device2},
},
},
},
})
if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
t.Error("not shared with device1")
}
if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
t.Error("not shared with device2")
}
select {
case <-conn2.Closed():
t.Error("conn already closed")
default:
}
if _, err := wcfg.RemoveDevice(device2); err != nil {
t.Error(err)
}
time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
fcfg, ok := m.cfg.Folder("default")
if !ok {
t.Fatal("default folder missing")
}
if !fcfg.SharedWith(device1) {
t.Error("not shared with device1")
}
if fcfg.SharedWith(device2) {
t.Error("shared with device2")
}
for _, dev := range fcfg.Devices {
if dev.DeviceID == device2 {
t.Error("still there")
}
}
select {
case <-conn2.Closed():
default:
t.Error("connection not closed")
}
if _, ok := wcfg.Devices()[device2]; ok {
t.Error("device still in config")
}
if _, ok := m.deviceConnIDs[device2]; ok {
t.Error("conn not missing")
}
if _, ok := m.helloMessages[device2]; ok {
t.Error("hello not missing")
}
if _, ok := m.deviceDownloads[device2]; ok {
t.Error("downloads not missing")
}
}
func TestIssue3804(t *testing.T) {
m := setupModel(t, defaultCfgWrapper)
defer cleanupModel(m)
// Subdirs ending in slash should be accepted
if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
t.Error("Unexpected error:", err)
}
}
func TestIssue3829(t *testing.T) {
m := setupModel(t, defaultCfgWrapper)
defer cleanupModel(m)
// Empty subdirs should be accepted
if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
t.Error("Unexpected error:", err)
}
}
// TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
func TestIssue4573(t *testing.T) {
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
testFs := fcfg.Filesystem(nil)
defer os.RemoveAll(testFs.URI())
must(t, testFs.MkdirAll("inaccessible", 0o755))
defer testFs.Chmod("inaccessible", 0o777)
file := filepath.Join("inaccessible", "a")
fd, err := testFs.Create(file)
must(t, err)
fd.Close()
m := setupModel(t, w)
defer cleanupModel(m)
must(t, testFs.Chmod("inaccessible", 0o000))
m.ScanFolder("default")
if file, ok := m.testCurrentFolderFile("default", file); !ok {
t.Fatalf("File missing in db")
} else if file.Deleted {
t.Errorf("Inaccessible file has been marked as deleted.")
}
}
// TestInternalScan checks whether various fs operations are correctly represented
// in the db after scanning.
func TestInternalScan(t *testing.T) {
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
testFs := fcfg.Filesystem(nil)
defer os.RemoveAll(testFs.URI())
testCases := map[string]func(protocol.FileInfo) bool{
"removeDir": func(f protocol.FileInfo) bool {
return !f.Deleted
},
"dirToFile": func(f protocol.FileInfo) bool {
return f.Deleted || f.IsDirectory()
},
}
baseDirs := []string{"dirToFile", "removeDir"}
for _, dir := range baseDirs {
sub := filepath.Join(dir, "subDir")
for _, dir := range []string{dir, sub} {
if err := testFs.MkdirAll(dir, 0o775); err != nil {
t.Fatalf("%v: %v", dir, err)
}
}
testCases[sub] = func(f protocol.FileInfo) bool {
return !f.Deleted
}
for _, dir := range []string{dir, sub} {
file := filepath.Join(dir, "a")
fd, err := testFs.Create(file)
must(t, err)
fd.Close()
testCases[file] = func(f protocol.FileInfo) bool {
return !f.Deleted
}
}
}
m := setupModel(t, w)
defer cleanupModel(m)
for _, dir := range baseDirs {
must(t, testFs.RemoveAll(dir))
}
fd, err := testFs.Create("dirToFile")
must(t, err)
fd.Close()
m.ScanFolder("default")
for path, cond := range testCases {
if f, ok := m.testCurrentFolderFile("default", path); !ok {
t.Fatalf("%v missing in db", path)
} else if cond(f) {
t.Errorf("Incorrect db entry for %v", path)
}
}
}
func TestCustomMarkerName(t *testing.T) {
fcfg := newFolderConfig()
fcfg.ID = "default"
fcfg.RescanIntervalS = 1
fcfg.MarkerName = "myfile"
cfg, cancel := newConfigWrapper(config.Configuration{
Version: config.CurrentVersion,
Folders: []config.FolderConfiguration{fcfg},
Devices: []config.DeviceConfiguration{
{
DeviceID: device1,
},
},
})
defer cancel()
ffs := fcfg.Filesystem(nil)
m := newModel(t, cfg, myID, nil)
set := newFileSet(t, "default", m.db)
set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
{Name: "dummyfile"},
})
if err := ffs.Remove(config.DefaultMarkerName); err != nil {
t.Fatal(err)
}
sub := m.evLogger.Subscribe(events.StateChanged)
defer sub.Unsubscribe()
m.ServeBackground()
defer cleanupModel(m)
waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
fd, _ := ffs.Create("myfile")
fd.Close()
waitForState(t, sub, "default", "")
}
func TestRemoveDirWithContent(t *testing.T) {
m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
defer wcfgCancel()
tfs := fcfg.Filesystem(nil)
defer cleanupModelAndRemoveDir(m, tfs.URI())
tfs.MkdirAll("dirwith", 0o755)
content := filepath.Join("dirwith", "content")
fd, err := tfs.Create(content)
must(t, err)
fd.Close()
must(t, m.ScanFolder(fcfg.ID))
dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
if !ok {
t.Fatalf("Can't get dir \"dirwith\" after initial scan")
}
dir.Deleted = true
dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
file, ok := m.testCurrentFolderFile(fcfg.ID, content)
if !ok {
t.Fatalf("Can't get file \"%v\" after initial scan", content)
}
file.Deleted = true
file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{dir, file}}))
// Is there something we could trigger on instead of just waiting?
timeout := time.NewTimer(5 * time.Second)
for {
dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
if !ok {
t.Fatalf("Can't get dir \"dirwith\" after index update")
}
file, ok := m.testCurrentFolderFile(fcfg.ID, content)
if !ok {
t.Fatalf("Can't get file \"%v\" after index update", content)
}
if dir.Deleted && file.Deleted {
return
}
select {
case <-timeout.C:
if !dir.Deleted && !file.Deleted {
t.Errorf("Neither the dir nor its content was deleted before timing out.")
} else if !dir.Deleted {
t.Errorf("The dir was not deleted before timing out.")
} else {
t.Errorf("The content of the dir was not deleted before timing out.")
}
return
default:
time.Sleep(100 * time.Millisecond)
}
}
}
func TestIssue4475(t *testing.T) {
m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
defer wcfgCancel()
defer cleanupModel(m)
testFs := fcfg.Filesystem(nil)
// Scenario: Dir is deleted locally and before syncing/index exchange
// happens, a file is create in that dir on the remote.
// This should result in the directory being recreated and added to the
// db locally.
must(t, testFs.MkdirAll("delDir", 0o755))
m.ScanFolder("default")
if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
t.Fatal("not shared with device1")
}
fileName := filepath.Join("delDir", "file")
conn.addFile(fileName, 0o644, protocol.FileInfoTypeFile, nil)
conn.sendIndexUpdate()
// Is there something we could trigger on instead of just waiting?
timeout := time.NewTimer(5 * time.Second)
created := false
for {
if !created {
if _, ok := m.testCurrentFolderFile("default", fileName); ok {
created = true
}
} else {
dir, ok := m.testCurrentFolderFile("default", "delDir")
if !ok {
t.Fatalf("can't get dir from db")
}
if !dir.Deleted {
return
}
}
select {
case <-timeout.C:
if created {
t.Errorf("Timed out before file from remote was created")
} else {
t.Errorf("Timed out before directory was resurrected in db")
}
return
default:
time.Sleep(100 * time.Millisecond)
}
}
}
func TestVersionRestore(t *testing.T) {
t.Skip("incompatible with fakefs")
// We create a bunch of files which we restore
// In each file, we write the filename as the content
// We verify that the content matches at the expected filenames
// after the restore operation.
fcfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", config.FilesystemTypeFake, srand.String(32))
fcfg.Versioning.Type = "simple"
fcfg.FSWatcherEnabled = false
filesystem := fcfg.Filesystem(nil)
rawConfig := config.Configuration{
Version: config.CurrentVersion,
Folders: []config.FolderConfiguration{fcfg},
}
cfg, cancel := newConfigWrapper(rawConfig)
defer cancel()
m := setupModel(t, cfg)
defer cleanupModel(m)
m.ScanFolder("default")
sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20180101-010101", time.Local)
if err != nil {
t.Fatal(err)
}
for _, file := range []string{
// Versions directory
".stversions/file~20171210-040404.txt", // will be restored
".stversions/existing~20171210-040404", // exists, should expect to be archived.
".stversions/something~20171210-040404", // will become directory, hence error
".stversions/dir/file~20171210-040404.txt",
".stversions/dir/file~20171210-040405.txt",
".stversions/dir/file~20171210-040406.txt",
".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
".stversions/dir/cat", // untagged which was used by trashcan, supported
// "file.txt" will be restored
"existing",
"something/file", // Becomes directory
"dir/file.txt",
"dir/existing.txt",
} {
if build.IsWindows {
file = filepath.FromSlash(file)
}
dir := filepath.Dir(file)
must(t, filesystem.MkdirAll(dir, 0o755))
if fd, err := filesystem.Create(file); err != nil {
t.Fatal(err)
} else if _, err := fd.Write([]byte(file)); err != nil {
t.Fatal(err)
} else if err := fd.Close(); err != nil {
t.Fatal(err)
} else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
t.Fatal(err)
}
}
versions, err := m.GetFolderVersions("default")
must(t, err)
expectedVersions := map[string]int{
"file.txt": 1,
"existing": 1,
"something": 1,
"dir/file.txt": 3,
"dir/existing.txt": 1,
"very/very/deep/one.txt": 1,
"dir/cat": 1,
}
for name, vers := range versions {
cnt, ok := expectedVersions[name]
if !ok {
t.Errorf("unexpected %s", name)
}
if len(vers) != cnt {
t.Errorf("%s: %d != %d", name, cnt, len(vers))
}
// Delete, so we can check if we didn't hit something we expect afterwards.
delete(expectedVersions, name)
}
for name := range expectedVersions {
t.Errorf("not found expected %s", name)
}
// Restoring non existing folder fails.
_, err = m.RestoreFolderVersions("does not exist", nil)
if err == nil {
t.Errorf("expected an error")
}
makeTime := func(s string) time.Time {
tm, err := time.ParseInLocation(versioner.TimeFormat, s, time.Local)
if err != nil {
t.Error(err)
}
return tm.Truncate(time.Second)
}
restore := map[string]time.Time{
"file.txt": makeTime("20171210-040404"),
"existing": makeTime("20171210-040404"),
"something": makeTime("20171210-040404"),
"dir/file.txt": makeTime("20171210-040406"),
"dir/existing.txt": makeTime("20171210-040406"),
"very/very/deep/one.txt": makeTime("20171210-040406"),
}
beforeRestore := time.Now().Truncate(time.Second)
ferr, err := m.RestoreFolderVersions("default", restore)
must(t, err)
if err, ok := ferr["something"]; len(ferr) > 1 || !ok || !errors.Is(err, versioner.ErrDirectory) {
t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
}
// Failed items are not expected to be restored.
// Remove them from expectations
for name := range ferr {
delete(restore, name)
}
// Check that content of files matches to the version they've been restored.
for file, version := range restore {
if build.IsWindows {
file = filepath.FromSlash(file)
}
tag := version.In(time.Local).Truncate(time.Second).Format(versioner.TimeFormat)
taggedName := filepath.Join(versioner.DefaultPath, versioner.TagFilename(file, tag))
fd, err := filesystem.Open(file)
if err != nil {
t.Error(err)
}
defer fd.Close()
content, err := io.ReadAll(fd)
if err != nil {
t.Error(err)
}
if !bytes.Equal(content, []byte(taggedName)) {
t.Errorf("%s: %s != %s", file, string(content), taggedName)
}
}
// Simple versioner uses now for timestamp generation, so we can check
// if existing stuff was correctly archived as we restored (oppose to deleteD), and version time as after beforeRestore
expectArchived := map[string]struct{}{
"existing": {},
"dir/file.txt": {},
"dir/existing.txt": {},
}
allFileVersions, err := m.GetFolderVersions("default")
must(t, err)
for file, versions := range allFileVersions {
key := file
if build.IsWindows {
file = filepath.FromSlash(file)
}
for _, version := range versions {
if version.VersionTime.Equal(beforeRestore) || version.VersionTime.After(beforeRestore) {
fd, err := filesystem.Open(versioner.DefaultPath + "/" + versioner.TagFilename(file, version.VersionTime.Format(versioner.TimeFormat)))
must(t, err)
defer fd.Close()
content, err := io.ReadAll(fd)
if err != nil {
t.Error(err)
}
// Even if they are at the archived path, content should have the non
// archived name.
if !bytes.Equal(content, []byte(file)) {
t.Errorf("%s (%s): %s != %s", file, fd.Name(), string(content), file)
}
_, ok := expectArchived[key]
if !ok {
t.Error("unexpected archived file with future timestamp", file, version.VersionTime)
}
delete(expectArchived, key)
}
}
}
if len(expectArchived) != 0 {
t.Fatal("missed some archived files", expectArchived)
}
}
func TestPausedFolders(t *testing.T) {
// Create a separate wrapper not to pollute other tests.
wrapper, cancel := newConfigWrapper(defaultCfgWrapper.RawCopy())
defer cancel()
m := setupModel(t, wrapper)
defer cleanupModel(m)
if err := m.ScanFolder("default"); err != nil {
t.Error(err)
}
pausedConfig := wrapper.RawCopy()
pausedConfig.Folders[0].Paused = true
replace(t, wrapper, pausedConfig)
if err := m.ScanFolder("default"); err != ErrFolderPaused {
t.Errorf("Expected folder paused error, received: %v", err)
}
if err := m.ScanFolder("nonexistent"); err != ErrFolderMissing {
t.Errorf("Expected missing folder error, received: %v", err)
}
}
func TestIssue4094(t *testing.T) {
// Create a separate wrapper not to pollute other tests.
wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
defer cancel()
m := newModel(t, wrapper, myID, nil)
m.ServeBackground()
defer cleanupModel(m)
// Force the model to wire itself and add the folders
folderPath := "nonexistent"
cfg := defaultCfgWrapper.RawCopy()
fcfg := config.FolderConfiguration{
FilesystemType: config.FilesystemTypeFake,
ID: "folder1",
Path: folderPath,
Paused: true,
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
}
cfg.Folders = []config.FolderConfiguration{fcfg}
replace(t, wrapper, cfg)
if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
t.Fatalf("failed setting ignores: %v", err)
}
if _, err := fcfg.Filesystem(nil).Lstat(".stignore"); err != nil {
t.Fatalf("failed stating .stignore: %v", err)
}
}
func TestIssue4903(t *testing.T) {
wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
defer cancel()
m := setupModel(t, wrapper)
defer cleanupModel(m)
// Force the model to wire itself and add the folders
folderPath := "nonexistent"
cfg := defaultCfgWrapper.RawCopy()
fcfg := config.FolderConfiguration{
ID: "folder1",
Path: folderPath,
Paused: true,
Devices: []config.FolderDeviceConfiguration{
{DeviceID: device1},
},
}
cfg.Folders = []config.FolderConfiguration{fcfg}
replace(t, wrapper, cfg)
if err := fcfg.CheckPath(); err != config.ErrPathMissing {
t.Fatalf("expected path missing error, got: %v, debug: %s", err, fcfg.CheckPath())
}
if _, err := fcfg.Filesystem(nil).Lstat("."); !fs.IsNotExist(err) {
t.Fatalf("Expected missing path error, got: %v", err)
}
}
func TestIssue5002(t *testing.T) {
// recheckFile should not panic when given an index equal to the number of blocks
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
ffs := fcfg.Filesystem(nil)
fd, err := ffs.Create("foo")
must(t, err)
_, err = fd.Write([]byte("foobar"))
must(t, err)
fd.Close()
m := setupModel(t, w)
defer cleanupModel(m)
if err := m.ScanFolder("default"); err != nil {
t.Error(err)
}
file, ok := m.testCurrentFolderFile("default", "foo")
if !ok {
t.Fatal("test file should exist")
}
blockSize := int32(file.BlockSize())
m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size-int64(blockSize), []byte{1, 2, 3, 4}, 0)
m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size, []byte{1, 2, 3, 4}, 0) // panic
m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size+int64(blockSize), []byte{1, 2, 3, 4}, 0)
}
func TestParentOfUnignored(t *testing.T) {
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
ffs := fcfg.Filesystem(nil)
must(t, ffs.Mkdir("bar", 0o755))
must(t, ffs.Mkdir("baz", 0o755))
must(t, ffs.Mkdir("baz/quux", 0o755))
m := setupModel(t, w)
defer cleanupModel(m)
m.SetIgnores("default", []string{"!quux", "*"})
m.ScanFolder("default")
if bar, ok := m.testCurrentFolderFile("default", "bar"); !ok {
t.Error(`Directory "bar" missing in db`)
} else if !bar.IsIgnored() {
t.Error(`Directory "bar" is not ignored`)
}
if baz, ok := m.testCurrentFolderFile("default", "baz"); !ok {
t.Error(`Directory "baz" missing in db`)
} else if baz.IsIgnored() {
t.Error(`Directory "baz" is ignored`)
}
}
// TestFolderRestartZombies reproduces issue 5233, where multiple concurrent folder
// restarts would leave more than one folder runner alive.
func TestFolderRestartZombies(t *testing.T) {
wrapper, cancel := newConfigWrapper(defaultCfg.Copy())
defer cancel()
waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
cfg.Options.RawMaxFolderConcurrency = -1
_, i, _ := cfg.Folder("default")
cfg.Folders[i].FilesystemType = config.FilesystemTypeFake
})
must(t, err)
waiter.Wait()
folderCfg, _ := wrapper.Folder("default")
m := setupModel(t, wrapper)
defer cleanupModel(m)
// Make sure the folder is up and running, because we want to count it.
m.ScanFolder("default")
// Check how many running folders we have running before the test.
if r := m.foldersRunning.Load(); r != 1 {
t.Error("Expected one running folder, not", r)
}
// Run a few parallel configuration changers for one second. Each waits
// for the commit to complete, but there are many of them.
var wg sync.WaitGroup
for i := 0; i < 25; i++ {
wg.Add(1)
go func() {
defer wg.Done()
t0 := time.Now()
for time.Since(t0) < time.Second {
fcfg := folderCfg.Copy()
fcfg.MaxConflicts = mrand.Int() // safe change that should cause a folder restart
setFolder(t, wrapper, fcfg)
}
}()
}
// Wait for the above to complete and check how many folders we have
// running now. It should not have increased.
wg.Wait()
// Make sure the folder is up and running, because we want to count it.
m.ScanFolder("default")
if r := m.foldersRunning.Load(); r != 1 {
t.Error("Expected one running folder, not", r)
}
}
func TestRequestLimit(t *testing.T) {
wrapper, fcfg, cancel := newDefaultCfgWrapper()
ffs := fcfg.Filesystem(nil)
file := "tmpfile"
fd, err := ffs.Create(file)
must(t, err)
fd.Close()
defer cancel()
waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
_, i, _ := cfg.Device(device1)
cfg.Devices[i].MaxRequestKiB = 1
})
must(t, err)
waiter.Wait()
m, conn := setupModelWithConnectionFromWrapper(t, wrapper)
defer cleanupModel(m)
m.ScanFolder("default")
befReq := time.Now()
first, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
if err != nil {
t.Fatalf("First request failed: %v", err)
}
reqDur := time.Since(befReq)
returned := make(chan struct{})
go func() {
second, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
if err != nil {
t.Errorf("Second request failed: %v", err)
}
close(returned)
second.Close()
}()
time.Sleep(10 * reqDur)
select {
case <-returned:
t.Fatalf("Second request returned before first was done")
default:
}
first.Close()
select {
case <-returned:
case <-time.After(time.Second):
t.Fatalf("Second request did not return after first was done")
}
}
// TestConnCloseOnRestart checks that there is no deadlock when calling Close
// on a protocol connection that has a blocking reader (blocking writer can't
// be done as the test requires clusterconfigs to go through).
func TestConnCloseOnRestart(t *testing.T) {
oldCloseTimeout := protocol.CloseTimeout
protocol.CloseTimeout = 100 * time.Millisecond
defer func() {
protocol.CloseTimeout = oldCloseTimeout
}()
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
m := setupModel(t, w)
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
br := &testutil.BlockingRW{}
nw := &testutil.NoopRW{}
ci := &protocolmocks.ConnectionInfo{}
ci.ConnectionIDReturns(srand.String(16))
m.AddConnection(protocol.NewConnection(device1, br, nw, testutil.NoopCloser{}, m, ci, protocol.CompressionNever, nil, m.keyGen), protocol.Hello{})
m.mut.RLock()
if len(m.closed) != 1 {
t.Fatalf("Expected just one conn (len(m.closed) == %v)", len(m.closed))
}
var closed chan struct{}
for _, c := range m.closed {
closed = c
}
m.mut.RUnlock()
waiter, err := w.RemoveDevice(device1)
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
waiter.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("Timed out before config took effect")
}
select {
case <-closed:
case <-time.After(5 * time.Second):
t.Fatal("Timed out before connection was closed")
}
}
func TestModTimeWindow(t *testing.T) {
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
tfs := modtimeTruncatingFS{
trunc: 0,
Filesystem: fcfg.Filesystem(nil),
}
// fcfg.RawModTimeWindowS = 2
setFolder(t, w, fcfg)
m := setupModel(t, w)
defer cleanupModelAndRemoveDir(m, tfs.URI())
name := "foo"
fd, err := tfs.Create(name)
must(t, err)
stat, err := fd.Stat()
must(t, err)
modTime := stat.ModTime()
fd.Close()
m.ScanFolders()
// Get current version
fi, ok := m.testCurrentFolderFile("default", name)
if !ok {
t.Fatal("File missing")
}
v := fi.Version
// Change the filesystem to only return modtimes to the closest two
// seconds, like FAT.
tfs.trunc = 2 * time.Second
// Scan again
m.ScanFolders()
// No change due to within window
fi, _ = m.testCurrentFolderFile("default", name)
if !fi.Version.Equal(v) {
t.Fatalf("Got version %v, expected %v", fi.Version, v)
}
// Update to be outside window
err = tfs.Chtimes(name, time.Now(), modTime.Add(2*time.Second))
must(t, err)
m.ScanFolders()
// Version should have updated
fi, _ = m.testCurrentFolderFile("default", name)
if fi.Version.Compare(v) != protocol.Greater {
t.Fatalf("Got result %v, expected %v", fi.Version.Compare(v), protocol.Greater)
}
}
func TestDevicePause(t *testing.T) {
m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
sub := m.evLogger.Subscribe(events.DevicePaused)
defer sub.Unsubscribe()
m.mut.RLock()
var closed chan struct{}
for _, c := range m.closed {
closed = c
}
m.mut.RUnlock()
pauseDevice(t, m.cfg, device1, true)
timeout := time.NewTimer(5 * time.Second)
select {
case <-sub.C():
select {
case <-closed:
case <-timeout.C:
t.Fatal("Timed out before connection was closed")
}
case <-timeout.C:
t.Fatal("Timed out before device was paused")
}
}
func TestDeviceWasSeen(t *testing.T) {
m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
m.deviceWasSeen(device1)
stats, err := m.DeviceStatistics()
if err != nil {
t.Error("Unexpected error:", err)
}
entry := stats[device1]
if time.Since(entry.LastSeen) > time.Second {
t.Error("device should have been seen now")
}
}
func TestNewLimitedRequestResponse(t *testing.T) {
l0 := semaphore.New(0)
l1 := semaphore.New(1024)
l2 := (*semaphore.Semaphore)(nil)
// Should take 500 bytes from any non-unlimited non-nil limiters.
res := newLimitedRequestResponse(500, l0, l1, l2)
if l1.Available() != 1024-500 {
t.Error("should have taken bytes from limited limiter")
}
// Closing the result should return the bytes.
res.Close()
// Try to take 1024 bytes to make sure the bytes were returned.
done := make(chan struct{})
go func() {
l1.Take(1024)
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Error("Bytes weren't returned in a timely fashion")
}
}
func TestSummaryPausedNoError(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
pauseFolder(t, wcfg, fcfg.ID, true)
m := setupModel(t, wcfg)
defer cleanupModel(m)
fss := NewFolderSummaryService(wcfg, m, myID, events.NoopLogger)
if _, err := fss.Summary(fcfg.ID); err != nil {
t.Error("Expected no error getting a summary for a paused folder:", err)
}
}
func TestFolderAPIErrors(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
pauseFolder(t, wcfg, fcfg.ID, true)
m := setupModel(t, wcfg)
defer cleanupModel(m)
methods := []func(folder string) error{
m.ScanFolder,
func(folder string) error {
return m.ScanFolderSubdirs(folder, nil)
},
func(folder string) error {
_, err := m.GetFolderVersions(folder)
return err
},
func(folder string) error {
_, err := m.RestoreFolderVersions(folder, nil)
return err
},
}
for i, method := range methods {
if err := method(fcfg.ID); err != ErrFolderPaused {
t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderPaused, err, i)
}
if err := method("notexisting"); err != ErrFolderMissing {
t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderMissing, err, i)
}
}
}
func TestRenameSequenceOrder(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
numFiles := 20
ffs := fcfg.Filesystem(nil)
for i := 0; i < numFiles; i++ {
v := fmt.Sprintf("%d", i)
writeFile(t, ffs, v, []byte(v))
}
m.ScanFolders()
count := 0
snap := dbSnapshot(t, m, "default")
snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
count++
return true
})
snap.Release()
if count != numFiles {
t.Errorf("Unexpected count: %d != %d", count, numFiles)
}
// Modify all the files, other than the ones we expect to rename
for i := 0; i < numFiles; i++ {
if i == 3 || i == 17 || i == 16 || i == 4 {
continue
}
v := fmt.Sprintf("%d", i)
writeFile(t, ffs, v, []byte(v+"-new"))
}
// Rename
must(t, ffs.Rename("3", "17"))
must(t, ffs.Rename("16", "4"))
// Scan
m.ScanFolders()
// Verify sequence of a appearing is followed by c disappearing.
snap = dbSnapshot(t, m, "default")
defer snap.Release()
var firstExpectedSequence int64
var secondExpectedSequence int64
failed := false
snap.WithHaveSequence(0, func(i protocol.FileInfo) bool {
t.Log(i)
if i.FileName() == "17" {
firstExpectedSequence = i.SequenceNo() + 1
}
if i.FileName() == "4" {
secondExpectedSequence = i.SequenceNo() + 1
}
if i.FileName() == "3" {
failed = i.SequenceNo() != firstExpectedSequence || failed
}
if i.FileName() == "16" {
failed = i.SequenceNo() != secondExpectedSequence || failed
}
return true
})
if failed {
t.Fail()
}
}
func TestRenameSameFile(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
ffs := fcfg.Filesystem(nil)
writeFile(t, ffs, "file", []byte("file"))
m.ScanFolders()
count := 0
snap := dbSnapshot(t, m, "default")
snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
count++
return true
})
snap.Release()
if count != 1 {
t.Errorf("Unexpected count: %d != %d", count, 1)
}
must(t, ffs.Rename("file", "file1"))
must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file0"))
must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file2"))
must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file3"))
must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file4"))
m.ScanFolders()
snap = dbSnapshot(t, m, "default")
defer snap.Release()
prevSeq := int64(0)
seen := false
snap.WithHaveSequence(0, func(i protocol.FileInfo) bool {
if i.SequenceNo() <= prevSeq {
t.Fatalf("non-increasing sequences: %d <= %d", i.SequenceNo(), prevSeq)
}
if i.FileName() == "file" {
if seen {
t.Fatal("already seen file")
}
seen = true
}
prevSeq = i.SequenceNo()
return true
})
}
func TestRenameEmptyFile(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
ffs := fcfg.Filesystem(nil)
writeFile(t, ffs, "file", []byte("data"))
writeFile(t, ffs, "empty", nil)
m.ScanFolders()
snap := dbSnapshot(t, m, "default")
defer snap.Release()
empty, eok := snap.Get(protocol.LocalDeviceID, "empty")
if !eok {
t.Fatal("failed to find empty file")
}
file, fok := snap.Get(protocol.LocalDeviceID, "file")
if !fok {
t.Fatal("failed to find non-empty file")
}
count := 0
snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileInfo) bool {
count++
return true
})
if count != 0 {
t.Fatalf("Found %d entries for empty file, expected 0", count)
}
count = 0
snap.WithBlocksHash(file.BlocksHash, func(_ protocol.FileInfo) bool {
count++
return true
})
if count != 1 {
t.Fatalf("Found %d entries for non-empty file, expected 1", count)
}
must(t, ffs.Rename("file", "new-file"))
must(t, ffs.Rename("empty", "new-empty"))
// Scan
m.ScanFolders()
snap = dbSnapshot(t, m, "default")
defer snap.Release()
count = 0
snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileInfo) bool {
count++
return true
})
if count != 0 {
t.Fatalf("Found %d entries for empty file, expected 0", count)
}
count = 0
snap.WithBlocksHash(file.BlocksHash, func(i protocol.FileInfo) bool {
count++
if i.FileName() != "new-file" {
t.Fatalf("unexpected file name %s, expected new-file", i.FileName())
}
return true
})
if count != 1 {
t.Fatalf("Found %d entries for non-empty file, expected 1", count)
}
}
func TestBlockListMap(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
ffs := fcfg.Filesystem(nil)
writeFile(t, ffs, "one", []byte("content"))
writeFile(t, ffs, "two", []byte("content"))
writeFile(t, ffs, "three", []byte("content"))
writeFile(t, ffs, "four", []byte("content"))
writeFile(t, ffs, "five", []byte("content"))
m.ScanFolders()
snap := dbSnapshot(t, m, "default")
defer snap.Release()
fi, ok := snap.Get(protocol.LocalDeviceID, "one")
if !ok {
t.Error("failed to find existing file")
}
var paths []string
snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileInfo) bool {
paths = append(paths, fi.FileName())
return true
})
snap.Release()
expected := []string{"one", "two", "three", "four", "five"}
if !equalStringsInAnyOrder(paths, expected) {
t.Errorf("expected %q got %q", expected, paths)
}
// Fudge the files around
// Remove
must(t, ffs.Remove("one"))
// Modify
must(t, ffs.Remove("two"))
writeFile(t, ffs, "two", []byte("mew-content"))
// Rename
must(t, ffs.Rename("three", "new-three"))
// Change type
must(t, ffs.Remove("four"))
must(t, ffs.Mkdir("four", 0o644))
m.ScanFolders()
// Check we're left with 2 of the 5
snap = dbSnapshot(t, m, "default")
defer snap.Release()
paths = paths[:0]
snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileInfo) bool {
paths = append(paths, fi.FileName())
return true
})
snap.Release()
expected = []string{"new-three", "five"}
if !equalStringsInAnyOrder(paths, expected) {
t.Errorf("expected %q got %q", expected, paths)
}
}
func TestScanRenameCaseOnly(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
ffs := fcfg.Filesystem(nil)
name := "foo"
writeFile(t, ffs, name, []byte("contents"))
m.ScanFolders()
snap := dbSnapshot(t, m, fcfg.ID)
defer snap.Release()
found := false
snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
if found {
t.Fatal("got more than one file")
}
if i.FileName() != name {
t.Fatalf("got file %v, expected %v", i.FileName(), name)
}
found = true
return true
})
snap.Release()
upper := strings.ToUpper(name)
must(t, ffs.Rename(name, upper))
m.ScanFolders()
snap = dbSnapshot(t, m, fcfg.ID)
defer snap.Release()
found = false
snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
if i.FileName() == name {
if i.IsDeleted() {
return true
}
t.Fatal("renamed file not deleted")
}
if i.FileName() != upper {
t.Fatalf("got file %v, expected %v", i.FileName(), upper)
}
if found {
t.Fatal("got more than the expected files")
}
found = true
return true
})
}
func TestClusterConfigOnFolderAdd(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, false, true, nil, func(wrapper config.Wrapper) {
fcfg := newFolderConfig()
fcfg.ID = "second"
fcfg.Label = "second"
fcfg.Devices = []config.FolderDeviceConfiguration{{
DeviceID: device2,
IntroducedBy: protocol.EmptyDeviceID,
}}
setFolder(t, wrapper, fcfg)
})
}
func TestClusterConfigOnFolderShare(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, true, true, nil, func(cfg config.Wrapper) {
fcfg := cfg.FolderList()[0]
fcfg.Devices = []config.FolderDeviceConfiguration{{
DeviceID: device2,
IntroducedBy: protocol.EmptyDeviceID,
}}
setFolder(t, cfg, fcfg)
})
}
func TestClusterConfigOnFolderUnshare(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
fcfg := cfg.FolderList()[0]
fcfg.Devices = nil
setFolder(t, cfg, fcfg)
})
}
func TestClusterConfigOnFolderRemove(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
rcfg := cfg.RawCopy()
rcfg.Folders = nil
replace(t, cfg, rcfg)
})
}
func TestClusterConfigOnFolderPause(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
})
}
func TestClusterConfigOnFolderUnpause(t *testing.T) {
testConfigChangeTriggersClusterConfigs(t, true, false, func(cfg config.Wrapper) {
pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
}, func(cfg config.Wrapper) {
pauseFolder(t, cfg, cfg.FolderList()[0].ID, false)
})
}
func TestAddFolderCompletion(t *testing.T) {
// Empty folders are always 100% complete.
comp := newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderValid)
comp.add(newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderPaused))
if comp.CompletionPct != 100 {
t.Error(comp.CompletionPct)
}
// Completion is of the whole
comp = newFolderCompletion(db.Counts{Bytes: 100}, db.Counts{}, 0, remoteFolderValid) // 100% complete
comp.add(newFolderCompletion(db.Counts{Bytes: 400}, db.Counts{Bytes: 50}, 0, remoteFolderValid)) // 82.5% complete
if comp.CompletionPct != 90 { // 100 * (1 - 50/500)
t.Error(comp.CompletionPct)
}
}
func TestScanDeletedROChangedOnSR(t *testing.T) {
m, conn, fcfg, wCancel := setupModelWithConnection(t)
ffs := fcfg.Filesystem(nil)
defer wCancel()
defer cleanupModelAndRemoveDir(m, ffs.URI())
fcfg.Type = config.FolderTypeReceiveOnly
setFolder(t, m.cfg, fcfg)
name := "foo"
writeFile(t, ffs, name, []byte(name))
m.ScanFolders()
file, ok := m.testCurrentFolderFile(fcfg.ID, name)
if !ok {
t.Fatal("file missing in db")
}
// A remote must have the file, otherwise the deletion below is
// automatically resolved as not a ro-changed item.
must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{file}}))
must(t, ffs.Remove(name))
m.ScanFolders()
if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 1 {
t.Fatal("expected one receive only changed deleted item")
}
fcfg.Type = config.FolderTypeSendReceive
setFolder(t, m.cfg, fcfg)
m.ScanFolders()
if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 0 {
t.Fatal("expected no receive only changed deleted item")
}
if localSize(t, m, fcfg.ID).Deleted != 1 {
t.Fatal("expected one local deleted item")
}
}
func testConfigChangeTriggersClusterConfigs(t *testing.T, expectFirst, expectSecond bool, pre func(config.Wrapper), fn func(config.Wrapper)) {
t.Helper()
wcfg, _, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
m := setupModel(t, wcfg)
defer cleanupModel(m)
setDevice(t, wcfg, newDeviceConfiguration(wcfg.DefaultDevice(), device2, "device2"))
if pre != nil {
pre(wcfg)
}
cc1 := make(chan struct{}, 1)
cc2 := make(chan struct{}, 1)
fc1 := newFakeConnection(device1, m)
fc1.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
cc1 <- struct{}{}
})
fc2 := newFakeConnection(device2, m)
fc2.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
cc2 <- struct{}{}
})
m.AddConnection(fc1, protocol.Hello{})
m.AddConnection(fc2, protocol.Hello{})
m.promoteConnections()
// Initial CCs
select {
case <-cc1:
default:
t.Fatal("missing initial CC from device1")
}
select {
case <-cc2:
default:
t.Fatal("missing initial CC from device2")
}
t.Log("Applying config change")
fn(wcfg)
timeout := time.NewTimer(time.Second)
if expectFirst {
select {
case <-cc1:
case <-timeout.C:
t.Errorf("timed out before receiving cluste rconfig for first device")
}
}
if expectSecond {
select {
case <-cc2:
case <-timeout.C:
t.Errorf("timed out before receiving cluste rconfig for second device")
}
}
}
// The end result of the tested scenario is that the global version entry has an
// empty version vector and is not deleted, while everything is actually deleted.
// That then causes these files to be considered as needed, while they are not.
// https://github.com/syncthing/syncthing/issues/6961
func TestIssue6961(t *testing.T) {
wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
defer wcfgCancel()
tfs := fcfg.Filesystem(nil)
waiter, err := wcfg.Modify(func(cfg *config.Configuration) {
cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device2, "device2"))
fcfg.Type = config.FolderTypeReceiveOnly
fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
cfg.SetFolder(fcfg)
})
must(t, err)
waiter.Wait()
// Always recalc/repair when opening a fileset.
m := newModel(t, wcfg, myID, nil)
m.db.Close()
m.db, err = db.NewLowlevel(backend.OpenMemory(), m.evLogger, db.WithRecheckInterval(time.Millisecond))
if err != nil {
t.Fatal(err)
}
m.ServeBackground()
defer cleanupModelAndRemoveDir(m, tfs.URI())
conn1 := addFakeConn(m, device1, fcfg.ID)
conn2 := addFakeConn(m, device2, fcfg.ID)
m.ScanFolders()
name := "foo"
version := protocol.Vector{}.Update(device1.Short())
// Remote, valid and existing file
must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, Version: version, Sequence: 1}}}))
// Remote, invalid (receive-only) and existing file
must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, RawInvalid: true, Sequence: 1}}}))
// Create a local file
if fd, err := tfs.OpenFile(name, fs.OptCreate, 0o666); err != nil {
t.Fatal(err)
} else {
fd.Close()
}
if info, err := tfs.Lstat(name); err != nil {
t.Fatal(err)
} else {
l.Infoln("intest", info.Mode)
}
m.ScanFolders()
// Get rid of valid global
waiter, err = wcfg.RemoveDevice(device1)
if err != nil {
t.Fatal(err)
}
waiter.Wait()
// Delete the local file
must(t, tfs.Remove(name))
m.ScanFolders()
// Drop the remote index, add some other file.
must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: "bar", RawInvalid: true, Sequence: 1}}}))
// Pause and unpause folder to create new db.FileSet and thus recalculate everything
pauseFolder(t, wcfg, fcfg.ID, true)
pauseFolder(t, wcfg, fcfg.ID, false)
if comp := m.testCompletion(device2, fcfg.ID); comp.NeedDeletes != 0 {
t.Error("Expected 0 needed deletes, got", comp.NeedDeletes)
} else {
t.Log(comp)
}
}
func TestCompletionEmptyGlobal(t *testing.T) {
m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
defer wcfgCancel()
defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
files := []protocol.FileInfo{{Name: "foo", Version: protocol.Vector{}.Update(myID.Short()), Sequence: 1}}
m.mut.Lock()
m.folderFiles[fcfg.ID].Update(protocol.LocalDeviceID, files)
m.mut.Unlock()
files[0].Deleted = true
files[0].Version = files[0].Version.Update(device1.Short())
must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
comp := m.testCompletion(protocol.LocalDeviceID, fcfg.ID)
if comp.CompletionPct != 95 {
t.Error("Expected completion of 95%, got", comp.CompletionPct)
}
}
func TestNeedMetaAfterIndexReset(t *testing.T) {
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
addDevice2(t, w, fcfg)
m := setupModel(t, w)
defer cleanupModelAndRemoveDir(m, fcfg.Path)
conn1 := addFakeConn(m, device1, fcfg.ID)
conn2 := addFakeConn(m, device2, fcfg.ID)
var seq int64 = 1
files := []protocol.FileInfo{{Name: "foo", Size: 10, Version: protocol.Vector{}.Update(device1.Short()), Sequence: seq}}
// Start with two remotes having one file, then both deleting it, then
// only one adding it again.
must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: files}))
seq++
files[0].SetDeleted(device2.Short())
files[0].Sequence = seq
must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
must(t, m.IndexUpdate(conn2, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
seq++
files[0].Deleted = false
files[0].Size = 20
files[0].Version = files[0].Version.Update(device1.Short())
files[0].Sequence = seq
must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
t.Error("Expected one needed item for device2, got", comp.NeedItems)
}
// Pretend we had an index reset on device 1
must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
t.Error("Expected one needed item for device2, got", comp.NeedItems)
}
}
func TestCcCheckEncryption(t *testing.T) {
if testing.Short() {
t.Skip("skipping on short testing - generating encryption tokens is slow")
}
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
m := setupModel(t, w)
m.cancel()
defer cleanupModel(m)
pw := "foo"
token := protocol.PasswordToken(m.keyGen, fcfg.ID, pw)
m.folderEncryptionPasswordTokens[fcfg.ID] = token
testCases := []struct {
tokenRemote, tokenLocal []byte
isEncryptedRemote, isEncryptedLocal bool
expectedErr error
}{
{
tokenRemote: token,
tokenLocal: token,
expectedErr: errEncryptionInvConfigRemote,
},
{
isEncryptedRemote: true,
isEncryptedLocal: true,
expectedErr: errEncryptionInvConfigLocal,
},
{
tokenRemote: token,
tokenLocal: nil,
isEncryptedRemote: false,
isEncryptedLocal: false,
expectedErr: errEncryptionNotEncryptedLocal,
},
{
tokenRemote: token,
tokenLocal: nil,
isEncryptedRemote: true,
isEncryptedLocal: false,
expectedErr: nil,
},
{
tokenRemote: token,
tokenLocal: nil,
isEncryptedRemote: false,
isEncryptedLocal: true,
expectedErr: nil,
},
{
tokenRemote: nil,
tokenLocal: token,
isEncryptedRemote: true,
isEncryptedLocal: false,
expectedErr: nil,
},
{
tokenRemote: nil,
tokenLocal: token,
isEncryptedRemote: false,
isEncryptedLocal: true,
expectedErr: nil,
},
{
tokenRemote: nil,
tokenLocal: token,
isEncryptedRemote: false,
isEncryptedLocal: false,
expectedErr: errEncryptionNotEncryptedLocal,
},
{
tokenRemote: nil,
tokenLocal: nil,
isEncryptedRemote: true,
isEncryptedLocal: false,
expectedErr: errEncryptionPlainForRemoteEncrypted,
},
{
tokenRemote: nil,
tokenLocal: nil,
isEncryptedRemote: false,
isEncryptedLocal: true,
expectedErr: errEncryptionPlainForReceiveEncrypted,
},
{
tokenRemote: nil,
tokenLocal: nil,
isEncryptedRemote: false,
isEncryptedLocal: false,
expectedErr: nil,
},
}
for i, tc := range testCases {
tfcfg := fcfg.Copy()
if tc.isEncryptedLocal {
tfcfg.Type = config.FolderTypeReceiveEncrypted
m.folderEncryptionPasswordTokens[fcfg.ID] = token
}
dcfg := config.FolderDeviceConfiguration{DeviceID: device1}
if tc.isEncryptedRemote {
dcfg.EncryptionPassword = pw
}
deviceInfos := &clusterConfigDeviceInfo{
remote: protocol.Device{ID: device1, EncryptionPasswordToken: tc.tokenRemote},
local: protocol.Device{ID: myID, EncryptionPasswordToken: tc.tokenLocal},
}
err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
if err != tc.expectedErr {
t.Errorf("Testcase %v: Expected error %v, got %v", i, tc.expectedErr, err)
}
if tc.expectedErr == nil {
err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, true)
if tc.isEncryptedRemote || tc.isEncryptedLocal {
if err != nil {
t.Errorf("Testcase %v: Expected no error, got %v", i, err)
}
} else {
if err != errEncryptionNotEncryptedUntrusted {
t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionNotEncryptedUntrusted, err)
}
}
}
if err != nil || (!tc.isEncryptedRemote && !tc.isEncryptedLocal) {
continue
}
if tc.isEncryptedLocal {
m.folderEncryptionPasswordTokens[fcfg.ID] = []byte("notAMatch")
} else {
dcfg.EncryptionPassword = "notAMatch"
}
err = m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
if err != errEncryptionPassword {
t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionPassword, err)
}
}
}
func TestCCFolderNotRunning(t *testing.T) {
// Create the folder, but don't start it.
w, fcfg, wCancel := newDefaultCfgWrapper()
defer wCancel()
tfs := fcfg.Filesystem(nil)
m := newModel(t, w, myID, nil)
defer cleanupModelAndRemoveDir(m, tfs.URI())
// A connection can happen before all the folders are started.
cc, _ := m.generateClusterConfig(device1)
if l := len(cc.Folders); l != 1 {
t.Fatalf("Expected 1 folder in CC, got %v", l)
}
folder := cc.Folders[0]
if id := folder.ID; id != fcfg.ID {
t.Fatalf("Expected folder %v, got %v", fcfg.ID, id)
}
if l := len(folder.Devices); l != 2 {
t.Fatalf("Expected 2 devices in CC, got %v", l)
}
local := folder.Devices[1]
if local.ID != myID {
local = folder.Devices[0]
}
if !folder.Paused && local.IndexID == 0 {
t.Errorf("Folder isn't paused, but index-id is zero")
}
}
func TestPendingFolder(t *testing.T) {
w, _, wCancel := newDefaultCfgWrapper()
defer wCancel()
m := setupModel(t, w)
defer cleanupModel(m)
setDevice(t, w, config.DeviceConfiguration{DeviceID: device2})
pfolder := "default"
of := db.ObservedFolder{
Time: time.Now().Truncate(time.Second),
Label: pfolder,
}
if err := m.db.AddOrUpdatePendingFolder(pfolder, of, device2); err != nil {
t.Fatal(err)
}
deviceFolders, err := m.PendingFolders(protocol.EmptyDeviceID)
if err != nil {
t.Fatal(err)
} else if pf, ok := deviceFolders[pfolder]; !ok {
t.Errorf("folder %v not pending", pfolder)
} else if _, ok := pf.OfferedBy[device2]; !ok {
t.Errorf("folder %v not pending for device %v", pfolder, device2)
} else if len(pf.OfferedBy) > 1 {
t.Errorf("folder %v pending for too many devices %v", pfolder, pf.OfferedBy)
}
device3, err := protocol.DeviceIDFromString("AIBAEAQ-CAIBAEC-AQCAIBA-EAQCAIA-BAEAQCA-IBAEAQC-CAIBAEA-QCAIBA7")
if err != nil {
t.Fatal(err)
}
setDevice(t, w, config.DeviceConfiguration{DeviceID: device3})
if err := m.db.AddOrUpdatePendingFolder(pfolder, of, device3); err != nil {
t.Fatal(err)
}
deviceFolders, err = m.PendingFolders(device2)
if err != nil {
t.Fatal(err)
} else if pf, ok := deviceFolders[pfolder]; !ok {
t.Errorf("folder %v not pending when filtered", pfolder)
} else if _, ok := pf.OfferedBy[device2]; !ok {
t.Errorf("folder %v not pending for device %v when filtered", pfolder, device2)
} else if _, ok := pf.OfferedBy[device3]; ok {
t.Errorf("folder %v pending for device %v, but not filtered out", pfolder, device3)
}
waiter, err := w.RemoveDevice(device3)
if err != nil {
t.Fatal(err)
}
waiter.Wait()
deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
if err != nil {
t.Fatal(err)
} else if pf, ok := deviceFolders[pfolder]; !ok {
t.Errorf("folder %v not pending", pfolder)
} else if _, ok := pf.OfferedBy[device3]; ok {
t.Errorf("folder %v pending for removed device %v", pfolder, device3)
}
waiter, err = w.RemoveFolder(pfolder)
if err != nil {
t.Fatal(err)
}
waiter.Wait()
deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
if err != nil {
t.Fatal(err)
} else if _, ok := deviceFolders[pfolder]; ok {
t.Errorf("folder %v still pending after local removal", pfolder)
}
}
func TestDeletedNotLocallyChangedReceiveOnly(t *testing.T) {
deletedNotLocallyChanged(t, config.FolderTypeReceiveOnly)
}
func TestDeletedNotLocallyChangedReceiveEncrypted(t *testing.T) {
deletedNotLocallyChanged(t, config.FolderTypeReceiveEncrypted)
}
func deletedNotLocallyChanged(t *testing.T, ft config.FolderType) {
w, fcfg, wCancel := newDefaultCfgWrapper()
tfs := fcfg.Filesystem(nil)
fcfg.Type = ft
setFolder(t, w, fcfg)
defer wCancel()
m := setupModel(t, w)
defer cleanupModelAndRemoveDir(m, tfs.URI())
name := "foo"
writeFile(t, tfs, name, nil)
must(t, m.ScanFolder(fcfg.ID))
fi, ok, err := m.CurrentFolderFile(fcfg.ID, name)
must(t, err)
if !ok {
t.Fatal("File hasn't been added")
}
if !fi.IsReceiveOnlyChanged() {
t.Fatal("File isn't receive-only-changed")
}
must(t, tfs.Remove(name))
must(t, m.ScanFolder(fcfg.ID))
_, ok, err = m.CurrentFolderFile(fcfg.ID, name)
must(t, err)
if ok {
t.Error("Expected file to be removed from db")
}
}
func equalStringsInAnyOrder(a, b []string) bool {
if len(a) != len(b) {
return false
}
sort.Strings(a)
sort.Strings(b)
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// modtimeTruncatingFS is a FileSystem that returns modification times only
// to the closest two `trunc` interval.
type modtimeTruncatingFS struct {
trunc time.Duration
fs.Filesystem
}
func (f modtimeTruncatingFS) Lstat(name string) (fs.FileInfo, error) {
fmt.Println("lstat", name)
info, err := f.Filesystem.Lstat(name)
return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
}
func (f modtimeTruncatingFS) Stat(name string) (fs.FileInfo, error) {
fmt.Println("stat", name)
info, err := f.Filesystem.Stat(name)
return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
}
func (f modtimeTruncatingFS) Walk(root string, walkFn fs.WalkFunc) error {
return f.Filesystem.Walk(root, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return walkFn(path, nil, err)
}
fmt.Println("walk", info.Name())
return walkFn(path, modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, nil)
})
}
type modtimeTruncatingFileInfo struct {
trunc time.Duration
fs.FileInfo
}
func (fi modtimeTruncatingFileInfo) ModTime() time.Time {
return fi.FileInfo.ModTime().Truncate(fi.trunc)
}
|