1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291
|
/* index.c -- Routines for dealing with the index file in the imapd
*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sysexits.h>
#include <syslog.h>
#include <ctype.h>
#include <stdlib.h>
#ifdef USE_HTTPD
/* For iCalendar indexing */
#include <libical/ical.h>
#include "vcard_support.h"
#endif
#include "acl.h"
#include "annotate.h"
#include "append.h"
#include "assert.h"
#include "backend.h"
#include "charset.h"
#include "conversations.h"
#include "dlist.h"
#include "hash.h"
#include "hashu64.h"
#include "http_client.h"
#include "jmap_util.h"
#include "global.h"
#include "times.h"
#include "imapd.h"
#include "lsort.h"
#include "mailbox.h"
#include "map.h"
#include "message.h"
#include "msgrecord.h"
#include "parseaddr.h"
#include "search_engines.h"
#include "search_query.h"
#include "seen.h"
#include "statuscache.h"
#include "strhash.h"
#include "user.h"
#include "util.h"
#include "xstats.h"
#include "ptrarray.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
#include "index.h"
#include "sync_log.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
EXPORTED unsigned client_capa;
static struct extractor_ctx *index_text_extractor = NULL;
/* Forward declarations */
static void index_refresh_locked(struct index_state *state);
static void index_tellexists(struct index_state *state);
static int index_lock(struct index_state *state, int readonly);
static void index_unlock(struct index_state *state);
struct index_modified_flags {
int added_flags;
bit32 added_system_flags;
bit32 added_user_flags[MAX_USER_FLAGS/32];
int removed_flags;
bit32 removed_system_flags;
bit32 removed_user_flags[MAX_USER_FLAGS/32];
};
static int index_writeseen(struct index_state *state);
static void index_fetchmsg(struct index_state *state,
const struct buf *msg,
unsigned offset, unsigned size,
unsigned start_octet, unsigned octet_count);
static int index_fetchsection(struct index_state *state, const char *resp,
const struct buf *msg,
char *section, struct body *body, unsigned size,
unsigned start_octet, unsigned octet_count);
static void index_fetchfsection(struct index_state *state,
const char *msg_base, unsigned long msg_size,
struct fieldlist *fsection,
struct body *body,
unsigned start_octet, unsigned octet_count);
static char *index_readheader(const char *msg_base, unsigned long msg_size,
unsigned offset, unsigned size);
static void index_fetchheader(struct index_state *state,
const char *msg_base, unsigned long msg_size,
unsigned size,
const strarray_t *headers,
const strarray_t *headers_not);
static void index_fetchcacheheader(struct index_state *state, struct index_record *record,
const strarray_t *headers, unsigned start_octet,
unsigned octet_count);
static void index_listflags(struct index_state *state);
static void index_fetchflags(struct index_state *state, uint32_t msgno);
static int index_copysetup(struct index_state *state, uint32_t msgno,
struct copyargs *copyargs);
static int index_storeflag(struct index_state *state,
struct index_modified_flags *modified_flags,
uint32_t msgno, msgrecord_t *msgrec,
struct storeargs *storeargs);
static int index_store_annotation(struct index_state *state, uint32_t msgno,
msgrecord_t *mrw, struct storeargs *storeargs,
int *dirty);
static int index_fetchreply(struct index_state *state, uint32_t msgno,
const struct fetchargs *fetchargs);
static void index_printflags(struct index_state *state, uint32_t msgno,
int usinguid, int printmodseq);
static char *get_localpart_addr(const char *header);
static char *get_displayname(const char *header);
static char *index_extract_subject(const char *subj, size_t len, int *is_refwd);
static char *_index_extract_subject(char *s, int *is_refwd);
static void index_get_ids(MsgData *msgdata,
char *envtokens[], const char *headers, unsigned size);
static int index_sort_compare(MsgData *md1, MsgData *md2,
const struct sortcrit *call_data);
static void *index_thread_getnext(Thread *thread);
static void index_thread_setnext(Thread *thread, Thread *next);
static int index_thread_compare(Thread *t1, Thread *t2,
const struct sortcrit *call_data);
static void index_thread_orderedsubj(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid);
static void index_thread_sort(Thread *root, const struct sortcrit *sortcrit);
static void index_thread_print(struct index_state *state,
Thread *threads, int usinguid);
static void index_thread_references(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid);
static void index_thread_refs(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid);
static seqset_t *_parse_sequence(struct index_state *state,
const char *sequence, int usinguid);
static void massage_header(char *hdr);
/* NOTE: Make sure these are listed in CAPABILITY_STRING */
static const struct thread_algorithm thread_algs[] = {
{ "ORDEREDSUBJECT", index_thread_orderedsubj },
{ "REFERENCES", index_thread_references },
{ "REFS", index_thread_refs },
{ NULL, NULL }
};
EXPORTED int index_reload_record(struct index_state *state,
uint32_t msgno,
struct index_record *record)
{
struct index_map *im = &state->map[msgno-1];
int r = 0;
int i;
memset(record, 0, sizeof(struct index_record));
if (!im->recno) {
/* doh, gotta just fill in what we know */
record->uid = im->uid;
}
else {
record->recno = im->recno;
record->uid = im->uid;
r = mailbox_reload_index_record_dirty(state->mailbox, record);
}
/* NOTE: we have released the cyrus.index lock at this point, but are
* still holding the mailbox name relock. This means nobody can rewrite
* the file under us - so the offsets are still guaranteed to be correct,
* and all the immutable fields are unchanged. That said, we can get a
* read of a partially updated record which contains an invalid checksum
* due to incomplete concurrent changes to mutable fields. That's why we
* used the _dirty API which ignores checksums.
* but other errors are still bad */
if (r) return r;
/* better be! */
assert(record->uid == im->uid);
/* restore mutable fields */
record->modseq = im->modseq;
record->system_flags = im->system_flags;
record->internal_flags = im->internal_flags;
record->cache_offset = im->cache_offset;
for (i = 0; i < MAX_USER_FLAGS/32; i++)
record->user_flags[i] = im->user_flags[i];
return 0;
}
static int index_rewrite_record(struct index_state *state,
uint32_t msgno,
struct index_record *record,
int silent)
{
struct index_map *im = &state->map[msgno-1];
int i;
assert(record->uid == im->uid);
if (!silent) {
int r = mailbox_rewrite_index_record(state->mailbox, record);
if (r) return r;
}
/* update tracking of mutable fields */
im->modseq = record->modseq;
im->system_flags = record->system_flags;
im->internal_flags = record->internal_flags;
im->cache_offset = record->cache_offset;
for (i = 0; i < MAX_USER_FLAGS/32; i++)
im->user_flags[i] = record->user_flags[i];
return 0;
}
EXPORTED void index_release(struct index_state *state)
{
if (!state) return;
message_unref(&state->m);
if (state->mailbox) {
mailbox_close(&state->mailbox);
state->mailbox = NULL; /* should be done by close anyway */
}
}
static struct sortcrit *the_sortcrit;
/*
* A mailbox is about to be closed.
*/
EXPORTED void index_close(struct index_state **stateptr)
{
unsigned i;
struct index_state *state = *stateptr;
if (!state) return;
index_release(state);
free(state->map);
free(state->mboxname);
free(state->userid);
for (i = 0; i < MAX_USER_FLAGS; i++)
free(state->flagname[i]);
free(state);
*stateptr = NULL;
}
/*
* A new mailbox has been selected and already opened, map it into
* memory and do the initial CHECK.
*/
EXPORTED int index_open_mailbox(struct mailbox *mailbox, struct index_init *init,
struct index_state **stateptr)
{
int r;
struct index_state *state = xzmalloc(sizeof(struct index_state));
state->mailbox = mailbox;
state->mboxname = xstrdup(mailbox_name(mailbox));
if (init) {
state->authstate = init->authstate;
state->examining = init->examine_mode;
state->out = init->out;
state->userid = xstrdupnull(init->userid);
state->want_dav = init->want_dav;
state->want_mbtype = init->want_mbtype;
state->want_expunged = init->want_expunged;
state->myrights = cyrus_acl_myrights(init->authstate,
mailbox_acl(state->mailbox));
if (state->examining)
state->myrights &= ~ACL_READ_WRITE;
state->internalseen = mailbox_internal_seen(state->mailbox,
state->userid);
}
if (mbtype_isa(mailbox_mbtype(state->mailbox)) != MBTYPE_EMAIL) {
if (state->want_dav) {
/* User logged in using imapmagicplus token "dav" */
}
else if (mbtype_isa(mailbox_mbtype(state->mailbox)) == state->want_mbtype) {
/* Caller explicitly asks for this NONIMAP type */
}
else {
r = IMAP_MAILBOX_BADTYPE;
goto fail;
}
}
/* initialise the index_state */
index_refresh_locked(state);
/* have to get the vanished list while we're still locked */
if (init)
init->vanishedlist = index_vanished(state, &init->vanished);
index_unlock(state);
*stateptr = state;
return 0;
fail:
free(state->mboxname);
free(state->userid);
free(state);
return r;
}
/*
* A new mailbox has been selected, map it into memory and do the
* initial CHECK.
*/
EXPORTED int index_open(const char *name, struct index_init *init,
struct index_state **stateptr)
{
int r;
struct mailbox *mailbox = NULL;
r = init && init->examine_mode ? mailbox_open_irl(name, &mailbox) :
mailbox_open_iwl(name, &mailbox);
if (r) return r;
r = index_open_mailbox(mailbox, init, stateptr);
if (r) mailbox_close(&mailbox);
return r;
}
EXPORTED int index_expunge(struct index_state *state, char *sequence,
int need_deleted)
{
int r;
uint32_t msgno;
struct index_map *im;
seqset_t *seq = NULL;
struct index_record record;
int numexpunged = 0;
struct mboxevent *mboxevent = NULL;
modseq_t oldmodseq;
r = index_lock(state, /*readonly*/0);
if (r) return r;
/* XXX - check if not mailbox->i.deleted count and need_deleted */
seq = _parse_sequence(state, sequence, 1);
mboxevent = mboxevent_new(EVENT_MESSAGE_EXPUNGE);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (im->internal_flags & FLAG_INTERNAL_EXPUNGED)
continue; /* already expunged */
if (need_deleted && !(im->system_flags & FLAG_DELETED))
continue; /* no \Deleted flag */
/* if there is a sequence list, check it */
if (sequence && !seqset_ismember(seq, im->uid))
continue; /* not in the list */
/* load first once we know we have to process this one */
if (index_reload_record(state, msgno, &record))
continue;
oldmodseq = im->modseq;
if (!im->isseen) {
if (state->numunseen)
state->numunseen--;
else
syslog(LOG_ERR, "IOERROR: numunseen underflow in expunge: %s %u",
state->mboxname, im->uid);
im->isseen = 1;
}
if (im->isrecent) {
if (state->numrecent)
state->numrecent--;
else
syslog(LOG_ERR, "IOERROR: numrecent underflow in expunge: %s %u",
state->mboxname, im->uid);
im->isrecent = 0;
}
/* set the flags */
record.system_flags |= FLAG_DELETED;
record.internal_flags |= FLAG_INTERNAL_EXPUNGED;
numexpunged++;
state->num_expunged++;
r = index_rewrite_record(state, msgno, &record, /*silent*/0);
if (r) break;
/* avoid telling again (equivalent to STORE FLAGS.SILENT) */
if (im->told_modseq == oldmodseq)
im->told_modseq = im->modseq;
mboxevent_extract_record(mboxevent, state->mailbox, &record);
}
seqset_free(&seq);
mboxevent_extract_mailbox(mboxevent, state->mailbox);
mboxevent_set_access(mboxevent, NULL, NULL, state->userid, mailbox_name(state->mailbox), 1);
mboxevent_set_numunseen(mboxevent, state->mailbox, state->numunseen);
/* unlock before responding */
index_unlock(state);
if (!r && (numexpunged > 0)) {
syslog(LOG_NOTICE, "Expunged %d messages from %s",
numexpunged, state->mboxname);
/* send the MessageExpunge event notification for "immediate", "default"
* and "delayed" expunge */
mboxevent_notify(&mboxevent);
}
mboxevent_free(&mboxevent);
return r;
}
static char *index_buildseen(struct index_state *state, const char *oldseenuids)
{
seqset_t *outlist;
uint32_t msgno;
unsigned oldmax;
struct index_map *im;
char *out;
outlist = seqset_init(0, SEQ_MERGE);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
seqset_add(outlist, im->uid, im->isseen);
}
/* there may be future already seen UIDs that this process isn't
* allowed to know about, but we can't blat them either! This is
* a massive pain... */
oldmax = seq_lastnum(oldseenuids);
if (oldmax > state->last_uid) {
seqset_t *seq = seqset_parse(oldseenuids, NULL, oldmax);
uint32_t uid;
/* for each future UID, copy the state in the old seenuids */
for (uid = state->last_uid + 1; uid <= oldmax; uid++)
seqset_add(outlist, uid, seqset_ismember(seq, uid));
seqset_free(&seq);
}
out = seqset_cstring(outlist);
seqset_free(&outlist);
return out;
}
static int index_writeseen(struct index_state *state)
{
int r;
struct seen *seendb = NULL;
struct seendata oldsd = SEENDATA_INITIALIZER;
struct seendata sd = SEENDATA_INITIALIZER;
struct mailbox *mailbox = state->mailbox;
const char *userid = (mailbox->i.options & OPT_IMAP_SHAREDSEEN) ? "anyone" : state->userid;
if (!state->seen_dirty)
return 0;
state->seen_dirty = 0;
/* only examining, can't write any changes */
if (state->examining)
return 0;
/* always dirty the mailbox, we may just be updating recent counts which doesn't bump the
* modseq because Recent is all sorts of evil */
mailbox_index_dirty(mailbox);
/* already handled! Just update the header fields */
if (state->internalseen) {
mailbox->i.recenttime = time(0);
if (mailbox->i.recentuid < state->last_uid)
mailbox->i.recentuid = state->last_uid;
return 0;
}
r = seen_open(userid, SEEN_CREATE, &seendb);
if (r) return r;
r = seen_lockread(seendb, mailbox_uniqueid(mailbox), &oldsd);
if (r) {
oldsd.lastread = 0;
oldsd.lastuid = 0;
oldsd.lastchange = 0;
oldsd.seenuids = xstrdup("");
}
/* fields of interest... */
sd.lastuid = oldsd.lastuid;
sd.seenuids = index_buildseen(state, oldsd.seenuids);
if (!sd.seenuids) sd.seenuids = xstrdup("");
/* make comparison only catch some changes */
sd.lastread = oldsd.lastread;
sd.lastchange = oldsd.lastchange;
/* update \Recent lowmark */
if (sd.lastuid < state->last_uid)
sd.lastuid = state->last_uid;
/* only commit if interesting fields have changed */
if (!seen_compare(&sd, &oldsd)) {
sd.lastread = time(NULL);
sd.lastchange = mailbox->i.last_appenddate;
r = seen_write(seendb, mailbox_uniqueid(mailbox), &sd);
}
seen_close(&seendb);
seen_freedata(&oldsd);
seen_freedata(&sd);
return r;
}
/* caller must free the list with seqset_free() when done */
static seqset_t *_readseen(struct index_state *state, unsigned *recentuid)
{
struct mailbox *mailbox = state->mailbox;
seqset_t *seenlist = NULL;
/* Obtain seen information */
if (state->internalseen) {
*recentuid = mailbox->i.recentuid;
}
else if (state->userid) {
struct seen *seendb = NULL;
struct seendata sd = SEENDATA_INITIALIZER;
const char *userid = (mailbox->i.options & OPT_IMAP_SHAREDSEEN) ? "anyone" : state->userid;
int r;
r = seen_open(userid, SEEN_CREATE, &seendb);
if (!r) r = seen_read(seendb, mailbox_uniqueid(mailbox), &sd);
seen_close(&seendb);
/* handle no seen DB gracefully */
if (r) {
*recentuid = mailbox->i.last_uid;
prot_printf(state->out, "* OK (seen state failure) %s: %s\r\n",
error_message(IMAP_NO_CHECKPRESERVE), error_message(r));
syslog(LOG_ERR, "Could not open seen state for %s (%s)",
userid, error_message(r));
}
else {
*recentuid = sd.lastuid;
seenlist = seqset_parse(sd.seenuids, NULL, *recentuid);
seen_freedata(&sd);
}
}
else {
*recentuid = mailbox->i.last_uid; /* nothing is recent! */
}
return seenlist;
}
static void index_refresh_locked(struct index_state *state)
{
struct mailbox *mailbox = state->mailbox;
const message_t *msg;
uint32_t msgno = 1;
uint32_t firstnotseen = 0;
uint32_t numrecent = 0;
uint32_t numunseen = 0;
uint32_t num_expunged = 0;
uint32_t recentuid = 0;
modseq_t delayed_modseq = 0;
struct index_map *im;
uint32_t need_records;
seqset_t *seenlist;
int i;
/* need to start by having enough space for the entire index state
* before telling of any expunges (which happens after this refresh
* if the command allows it). In the update case, where there's
* already a map, we have to theoretically fit the number that existed
* last time plus however many new records might be unEXPUNGEd on the
* end */
need_records = state->want_expunged ? mailbox->i.num_records : mailbox->i.exists;
if (state->last_uid) {
need_records = state->exists + (mailbox->i.last_uid - state->last_uid);
}
/* make sure we have space */
if (need_records >= state->mapsize) {
state->mapsize = (need_records | 0xff) + 1; /* round up 1-256 */
state->map = xrealloc(state->map,
state->mapsize * sizeof(struct index_map));
}
seenlist = _readseen(state, &recentuid);
/* walk through all records */
struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_UNLINKED);
while ((msg = mailbox_iter_step(iter))) {
const struct index_record *record = msg_record(msg);
im = &state->map[msgno-1];
while (msgno <= state->exists && im->uid < record->uid) {
/* NOTE: this same logic is repeated below for messages
* past the end of recno (repack removing the trailing
* records). Make sure to keep them in sync */
if (!(im->internal_flags & FLAG_INTERNAL_EXPUNGED)) {
/* we don't even know the modseq of when it was wiped,
* but we can be sure it's since the last given highestmodseq,
* so simulate the lowest possible value. This is fine for
* our told_modseq logic, and doesn't have to be exact because
* QRESYNC/CONDSTORE clients will see deletedmodseq and fall
* back to the inefficient codepath anyway */
im->modseq = state->highestmodseq + 1;
}
if (!delayed_modseq || im->modseq < delayed_modseq)
delayed_modseq = im->modseq - 1;
im->recno = 0;
/* simulate expunged flag so we get an EXPUNGE response and
* tell about unlinked so we don't get IO errors trying to
* find the file */
im->internal_flags |= FLAG_INTERNAL_EXPUNGED |
FLAG_INTERNAL_UNLINKED;
im = &state->map[msgno++];
/* this one is expunged */
num_expunged++;
}
/* expunged record not in map, can skip immediately. It's
* never been told to this connection, so it doesn't need to
* get its own msgno */
if (!state->want_expunged
&& (msgno > state->exists || record->uid < im->uid)
&& (record->internal_flags & FLAG_INTERNAL_EXPUNGED))
continue;
/* make sure our UID map is consistent */
if (msgno <= state->exists) {
assert(im->uid == record->uid);
}
else {
memset(im, 0, sizeof(struct index_map));
im->uid = record->uid;
}
/* copy all mutable fields */
im->recno = record->recno;
im->modseq = record->modseq;
im->system_flags = record->system_flags;
im->internal_flags = record->internal_flags;
im->cache_offset = record->cache_offset;
for (i = 0; i < MAX_USER_FLAGS/32; i++)
im->user_flags[i] = record->user_flags[i];
/* re-calculate seen flags */
if (state->internalseen)
im->isseen = (im->system_flags & FLAG_SEEN) ? 1 : 0;
else
im->isseen = seqset_ismember(seenlist, im->uid) ? 1 : 0;
/* for expunged records, just track the modseq */
if (im->internal_flags & FLAG_INTERNAL_EXPUNGED) {
num_expunged++;
/* http://www.rfc-editor.org/errata_search.php?rfc=5162
* Errata ID: 1809 - if there are expunged records we
* aren't telling about, need to make the highestmodseq
* be one lower so the client can safely resync */
if (!delayed_modseq || im->modseq < delayed_modseq)
delayed_modseq = im->modseq - 1;
}
else {
if (msgno > state->exists) {
/* don't auto-tell new records */
im->told_modseq = im->modseq;
if (im->uid > recentuid) {
/* mark recent if it's newly being added to the index and also
* greater than the recentuid - ensures only one session gets
* the \Recent flag for any one message */
im->isrecent = 1;
state->seen_dirty = 1;
}
else
im->isrecent = 0;
}
/* track select values */
if (!im->isseen) {
numunseen++;
if (!firstnotseen)
firstnotseen = msgno;
}
if (im->isrecent) {
numrecent++;
}
}
/* make sure we don't overflow the memory we mapped */
if (msgno > state->mapsize) {
char buf[2048];
sprintf(buf, "Exists wrong %u %u %u %u", msgno,
state->mapsize, mailbox->i.exists, mailbox->i.num_records);
fatal(buf, EX_IOERR);
}
msgno++;
}
mailbox_iter_done(&iter);
/* may be trailing records which need to be considered for
* delayed_modseq purposes, and to get the count right for
* later expunge processing */
im = &state->map[msgno-1];
while (msgno <= state->exists) {
/* this is the same logic as the block above in the main loop,
* see comments up there, and make sure the blocks are kept
* in sync! */
if (!(im->internal_flags & FLAG_INTERNAL_EXPUNGED))
im->modseq = state->highestmodseq + 1;
if (!delayed_modseq || im->modseq < delayed_modseq)
delayed_modseq = im->modseq - 1;
im->recno = 0;
im->internal_flags |= FLAG_INTERNAL_EXPUNGED | FLAG_INTERNAL_UNLINKED;
im = &state->map[msgno++];
num_expunged++;
}
seqset_free(&seenlist);
/* update the header tracking data */
state->oldexists = state->exists; /* we last knew about this many */
state->exists = msgno - 1; /* we actually got this many */
state->delayed_modseq = delayed_modseq;
state->oldhighestmodseq = state->highestmodseq;
state->highestmodseq = mailbox->i.highestmodseq;
state->generation = mailbox->i.generation_no;
state->uidvalidity = mailbox->i.uidvalidity;
state->last_uid = mailbox->i.last_uid;
state->num_records = mailbox->i.num_records;
state->num_expunged = num_expunged;
state->firstnotseen = firstnotseen;
state->numunseen = numunseen;
state->numrecent = numrecent;
}
EXPORTED modseq_t index_highestmodseq(struct index_state *state)
{
if (state->delayed_modseq)
return state->delayed_modseq;
return state->highestmodseq;
}
EXPORTED void index_select(struct index_state *state, struct index_init *init)
{
index_tellexists(state);
/* always print flags */
index_checkflags(state, 1, 1);
if (state->firstnotseen)
prot_printf(state->out, "* OK [UNSEEN %u] Ok\r\n",
state->firstnotseen);
prot_printf(state->out, "* OK [UIDVALIDITY %u] Ok\r\n",
state->mailbox->i.uidvalidity);
prot_printf(state->out, "* OK [UIDNEXT %lu] Ok\r\n",
state->last_uid + 1);
/* RFC 7162 */
prot_printf(state->out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "] Ok\r\n",
state->highestmodseq);
/* RFC 8474 */
prot_printf(state->out, "* OK [MAILBOXID (%s)] Ok\r\n",
mailbox_uniqueid(state->mailbox));
/* RFC 4467 */
prot_printf(state->out, "* OK [URLMECH INTERNAL] Ok\r\n");
/*
* RFC 5257. Note that we must report a maximum size for annotations
* but we don't enforce any such limit, so pick a "large" number.
*/
prot_printf(state->out, "* OK [ANNOTATIONS %u] Ok\r\n", 64*1024);
if (init->vanishedlist) {
char *vanished;
const char *sequence = NULL;
seqset_t *seq = NULL;
struct index_map *im;
uint32_t msgno;
/* QRESYNC response:
* UID FETCH seq FLAGS (CHANGEDSINCE modseq VANISHED)
*/
vanished = seqset_cstring(init->vanishedlist);
if (vanished) {
prot_printf(state->out, "* VANISHED (EARLIER) %s\r\n", vanished);
free(vanished);
}
sequence = init->vanished.sequence;
if (sequence) seq = _parse_sequence(state, sequence, 1);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (sequence && !seqset_ismember(seq, im->uid))
continue;
if (im->modseq <= init->vanished.modseq)
continue;
index_printflags(state, msgno, 1, 0);
}
seqset_free(&seq);
}
}
/*
* Check for and report updates
*/
EXPORTED int index_check(struct index_state *state, int usinguid, int printuid)
{
int r;
if (!state) return 0;
/* we don't write any records in here, but we want to write the recentuid if
* there were new emails delivered... */
r = index_lock(state, /*readonly*/0);
/* Check for deleted mailbox */
if (r == IMAP_MAILBOX_NONEXISTENT) {
/* Mailbox has been (re)moved */
if (config_getswitch(IMAPOPT_DISCONNECT_ON_VANISHED_MAILBOX)) {
syslog(LOG_WARNING,
"Mailbox %s has been (re)moved out from under client",
state->mboxname);
mailbox_close(&state->mailbox);
fatal("Mailbox has been (re)moved", EX_IOERR);
}
if (state->exists && (client_capa & CAPA_QRESYNC)) {
/* XXX - is it OK to just expand to entire possible range? */
prot_printf(state->out, "* VANISHED 1:%lu\r\n", state->last_uid);
}
else {
int exists;
for (exists = state->exists; exists > 0; exists--) {
prot_printf(state->out, "* 1 EXPUNGE\r\n");
}
}
state->exists = 0;
return IMAP_MAILBOX_NONEXISTENT;
}
if (r) return r;
index_tellchanges(state, usinguid, printuid, 0);
index_unlock(state);
return r;
}
/*
* Perform UID FETCH (VANISHED) on a sequence.
*/
seqset_t *index_vanished(struct index_state *state,
struct vanished_params *params)
{
struct mailbox *mailbox = state->mailbox;
seqset_t *outlist;
seqset_t *seq;
/* check uidvalidity match */
if (params->uidvalidity_is_max) {
if (params->uidvalidity < mailbox->i.uidvalidity) return NULL;
}
else {
if (params->uidvalidity != mailbox->i.uidvalidity) return NULL;
}
/* No recently expunged messages */
if (params->modseq >= state->highestmodseq) return NULL;
outlist = seqset_init(0, SEQ_SPARSE);
seq = _parse_sequence(state, params->sequence, 1);
/* XXX - use match_seq and match_uid */
if (params->modseq >= mailbox->i.deletedmodseq) {
const message_t *msg;
/* all records are significant */
/* List only expunged UIDs with MODSEQ > requested */
struct mailbox_iter *iter = mailbox_iter_init(mailbox, params->modseq, 0);
while ((msg = mailbox_iter_step(iter))) {
const struct index_record *record = msg_record(msg);
if (!(record->internal_flags & FLAG_INTERNAL_EXPUNGED))
continue;
if (!params->sequence || seqset_ismember(seq, record->uid))
seqset_add(outlist, record->uid, 1);
}
mailbox_iter_done(&iter);
}
else {
unsigned prevuid = 0;
seqset_t *msgnolist;
seqset_t *uidlist;
uint32_t msgno;
unsigned uid;
syslog(LOG_NOTICE, "inefficient qresync ("
MODSEQ_FMT " > " MODSEQ_FMT ") %s",
mailbox->i.deletedmodseq, params->modseq,
mailbox_name(mailbox));
/* use the sequence to uid mapping provided by the client to
* skip over any initial matches - see RFC 5162 section 3.1 */
if (params->match_seq && params->match_uid) {
msgnolist = _parse_sequence(state, params->match_seq, 0);
uidlist = _parse_sequence(state, params->match_uid, 1);
while ((msgno = seqset_getnext(msgnolist)) != 0) {
uid = seqset_getnext(uidlist);
/* first non-match, we'll start here */
if (state->map[msgno-1].uid != uid)
break;
/* ok, they matched - so we can start after here */
prevuid = uid;
}
seqset_free(&msgnolist);
seqset_free(&uidlist);
}
const message_t *msg;
struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_EXPUNGED);
mailbox_iter_startuid(iter, prevuid);
/* possible efficiency improvement - use "seq_getnext" on seq
* to avoid incrementing through every single number for prevuid.
* Only really an issue if there's a giant block of thousands of
* expunged messages. Only likely to be seen in the wild if
* last_uid winds up being bumped up a few million by a bug... */
/* for the rest of the mailbox, we're just going to have to assume
* every record in the requested range which DOESN'T exist has been
* expunged, so build a complete sequence */
while ((msg = mailbox_iter_step(iter))) {
const struct index_record *record = msg_record(msg);
while (++prevuid < record->uid) {
if (!params->sequence || seqset_ismember(seq, prevuid))
seqset_add(outlist, prevuid, 1);
}
prevuid = record->uid;
}
mailbox_iter_done(&iter);
/* include the space past the final record up to last_uid as well */
while (++prevuid <= mailbox->i.last_uid) {
if (!params->sequence || seqset_ismember(seq, prevuid))
seqset_add(outlist, prevuid, 1);
}
}
seqset_free(&seq);
return outlist;
}
static int _fetch_setseen(struct index_state *state,
struct mboxevent *mboxevent,
uint32_t msgno)
{
struct index_map *im = &state->map[msgno-1];
struct index_record record;
int r;
/* already seen */
if (im->isseen)
return 0;
/* no rights to change it */
if (!(state->myrights & ACL_SETSEEN))
return 0;
r = index_reload_record(state, msgno, &record);
if (r) return r;
/* track changes internally */
if (state->numunseen)
state->numunseen--;
else
syslog(LOG_ERR, "IOERROR: unseen underflow on setseen: %s %u",
state->mboxname, im->uid);
state->seen_dirty = 1;
im->isseen = 1;
/* also store in the record if it's internal seen */
if (state->internalseen)
record.system_flags |= FLAG_SEEN;
/* need to bump modseq anyway, so always rewrite it */
r = index_rewrite_record(state, msgno, &record, /*silent*/0);
if (r) return r;
mboxevent_extract_record(mboxevent, state->mailbox, &record);
/* RFC 2060 says:
* The \Seen flag is implicitly set; if this causes
* the flags to change they SHOULD be included as part
* of the FETCH responses. This is handled later by
* always including flags if the modseq has changed.
*/
return 0;
}
/* seq can be NULL - means "ALL" */
EXPORTED void index_fetchresponses(struct index_state *state,
seqset_t *seq,
int usinguid,
const struct fetchargs *fetchargs,
int *fetchedsomething)
{
uint32_t msgno, start, end;
struct index_map *im;
int fetched = 0;
annotate_db_t *annot_db = NULL;
/* Keep an open reference on the per-mailbox db to avoid
* doing too many slow database opens during the fetch */
if ((fetchargs->fetchitems & FETCH_ANNOTATION))
annotate_getdb(state->mailbox, &annot_db);
start = 1;
end = state->exists;
/* if we haven't told exists and we're fetching something past the end of the
* old size, we need to tell exists now...
* https://github.com/cyrusimap/cyrus-imapd/issues/1967
*/
if (state->exists != state->oldexists) index_tellexists(state);
/* if the modseq hasn't changed then there will be no unsolicited updates
* to send, so we only need to scan messages inside the sequence range.
* https://github.com/cyrusimap/cyrus-imapd/issues/1971
*/
if (state->oldhighestmodseq == state->highestmodseq) {
/* compress the search range down if a sequence was given */
if (seq) {
unsigned first = seqset_first(seq);
unsigned last = seqset_last(seq);
if (usinguid) {
if (first > 1)
start = index_finduid(state, first);
if (first == last)
end = start;
else if (last < state->last_uid)
end = index_finduid(state, last);
}
else {
start = first;
end = last;
}
}
}
/* make sure we didn't go outside the range! */
if (start < 1) start = 1;
if (end > state->exists) end = state->exists;
for (msgno = start; msgno <= end; msgno++) {
im = &state->map[msgno-1];
if (seq && !seqset_ismember(seq, usinguid ? im->uid : msgno)) {
if (im->told_modseq !=0 && im->modseq > im->told_modseq)
index_printflags(state, msgno, usinguid, 0);
continue;
}
if (index_fetchreply(state, msgno, fetchargs))
break;
fetched = 1;
}
/* Update oldhighestmodseq, ensuring we don't have unsolicited updates */
state->oldhighestmodseq = state->highestmodseq;
if (fetchedsomething) *fetchedsomething = fetched;
annotate_putdb(&annot_db);
}
/*
* Perform a FETCH-related command on a sequence.
* Fetchedsomething argument is 0 if nothing was fetched, 1 if something was
* fetched. (A fetch command that fetches nothing is not a valid fetch
* command.)
*/
EXPORTED int index_fetch(struct index_state *state,
const char *sequence,
int usinguid,
const struct fetchargs *fetchargs,
int *fetchedsomething)
{
seqset_t *seq;
seqset_t *vanishedlist = NULL;
struct index_map *im;
uint32_t msgno;
int r;
struct mboxevent *mboxevent = NULL;
r = index_lock(state, /*readonly*/0); // can't be readonly because of FETCH_SETSEEN
if (r) return r;
seq = _parse_sequence(state, sequence, usinguid);
/* set the \Seen flag if necessary - while we still have the lock */
if (fetchargs->fetchitems & FETCH_SETSEEN && !state->examining && state->myrights & ACL_SETSEEN) {
mboxevent = mboxevent_new(EVENT_MESSAGE_READ);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (!seqset_ismember(seq, usinguid ? im->uid : msgno))
continue;
r = _fetch_setseen(state, mboxevent, msgno);
if (r) break;
}
mboxevent_extract_mailbox(mboxevent, state->mailbox);
mboxevent_set_access(mboxevent, NULL, NULL, state->userid, mailbox_name(state->mailbox), 1);
mboxevent_set_numunseen(mboxevent, state->mailbox,
state->numunseen);
}
if (fetchargs->vanished) {
struct vanished_params v;
v.sequence = sequence;
v.uidvalidity = state->mailbox->i.uidvalidity;
v.modseq = fetchargs->changedsince;
v.match_seq = fetchargs->match_seq;
v.match_uid = fetchargs->match_uid;
/* XXX - return error unless usinguid? */
vanishedlist = index_vanished(state, &v);
}
index_unlock(state);
/* send MessageRead event notification for successfully rewritten records */
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
index_checkflags(state, 1, 0);
if (seqset_first(vanishedlist)) {
char *vanished = seqset_cstring(vanishedlist);
prot_printf(state->out, "* VANISHED (EARLIER) %s\r\n", vanished);
free(vanished);
}
seqset_free(&vanishedlist);
index_fetchresponses(state, seq, usinguid, fetchargs, fetchedsomething);
seqset_free(&seq);
index_tellchanges(state, usinguid, usinguid, 0);
return r;
}
/*
* Perform a STORE command on a sequence
*/
EXPORTED int index_store(struct index_state *state, char *sequence,
struct storeargs *storeargs)
{
struct mailbox *mailbox;
int i, r = 0;
uint32_t msgno;
int userflag;
seqset_t *seq;
struct index_map *im;
const strarray_t *flags = &storeargs->flags;
struct mboxevent *mboxevents = NULL;
struct mboxevent *flagsset = NULL, *flagsclear = NULL;
struct index_modified_flags modified_flags;
struct index_record record;
if (storeargs->operation == STORE_ADD_FLAGS
|| storeargs->operation == STORE_REMOVE_FLAGS)
{
int did_limit_flags = 0;
/* Quoth RFC 4314:
* STORE operation SHOULD NOT fail if the user has rights to modify
* at least one flag specified in the STORE, as the tagged NO
* response to a STORE command is not handled very well by deployed
* clients.
*/
if (storeargs->seen && !(state->myrights & ACL_SETSEEN)) {
syslog(LOG_DEBUG, "%s: no permission to alter \\Seen, removing from set",
__func__);
storeargs->seen = 0;
did_limit_flags = 1;
}
if ((storeargs->system_flags & FLAG_DELETED)
&& !(state->myrights & ACL_DELETEMSG))
{
syslog(LOG_DEBUG, "%s: no permission to alter \\Deleted, removing from set",
__func__);
storeargs->system_flags &= ~FLAG_DELETED;
did_limit_flags = 1;
}
if (((storeargs->system_flags & ~FLAG_DELETED) || flags->count)
&& !(state->myrights & ACL_WRITE))
{
syslog(LOG_DEBUG, "%s: no permission to alter other flags, removing from set",
__func__);
storeargs->system_flags &= FLAG_DELETED; /* turn off everything BUT deleted */
strarray_truncate(&storeargs->flags, 0);
did_limit_flags = 1;
}
if (did_limit_flags
&& !storeargs->seen
&& !storeargs->system_flags
&& !flags->count)
{
syslog(LOG_DEBUG, "%s: no permitted flags left, rejecting", __func__);
return IMAP_PERMISSION_DENIED;
}
}
else {
if ((storeargs->seen && !(state->myrights & ACL_SETSEEN)) ||
((storeargs->system_flags & FLAG_DELETED) &&
!(state->myrights & ACL_DELETEMSG)) ||
(((storeargs->system_flags & ~FLAG_DELETED) || flags->count) &&
!(state->myrights & ACL_WRITE))) {
return IMAP_PERMISSION_DENIED;
}
}
r = index_lock(state, /*readonly*/0);
if (r) return r;
mailbox = state->mailbox;
seq = _parse_sequence(state, sequence, storeargs->usinguid);
for (i = 0; i < flags->count ; i++) {
r = mailbox_user_flag(mailbox, flags->data[i], &userflag, 1);
if (r) goto out;
storeargs->user_flags[userflag/32] |= 1<<(userflag&31);
}
storeargs->update_time = time((time_t *)0);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (!seqset_ismember(seq, storeargs->usinguid ? im->uid : msgno))
continue;
/* if it's expunged already, skip it now */
if ((im->internal_flags & FLAG_INTERNAL_EXPUNGED))
continue;
/* if it's changed already, skip it now */
if (im->modseq > storeargs->unchangedsince) {
if (!storeargs->modified) {
uint32_t maxval = (storeargs->usinguid ?
state->last_uid : state->exists);
storeargs->modified = seqset_init(maxval, SEQ_SPARSE);
}
seqset_add(storeargs->modified,
(storeargs->usinguid ? im->uid : msgno),
/*ismember*/1);
continue;
}
/* TODO(rsto): we need to keep index_reload_record here until we
* can make sure that the index map doesn't contain uncommitted
* changes for this msgno. See the comments in index_reload_record
* on how it releases the cyrus.index lock in the middle of action */
r = index_reload_record(state, msgno, &record);
if (r) goto out;
msgrecord_t *msgrec = msgrecord_from_index_record(state->mailbox, &record);
switch (storeargs->operation) {
case STORE_ADD_FLAGS:
case STORE_REMOVE_FLAGS:
case STORE_REPLACE_FLAGS:
r = index_storeflag(state, &modified_flags, msgno, msgrec, storeargs);
if (r) goto doneloop;
// nothing to do?
if (!(modified_flags.added_flags | modified_flags.removed_flags))
goto doneloop;
r = msgrecord_rewrite(msgrec);
if (r) goto doneloop;
if (modified_flags.added_flags) {
if (flagsset == NULL)
flagsset = mboxevent_enqueue(EVENT_FLAGS_SET, &mboxevents);
mboxevent_add_flags(flagsset, mailbox->h.flagname,
modified_flags.added_system_flags,
modified_flags.added_user_flags);
mboxevent_extract_msgrecord(flagsset, msgrec);
}
if (modified_flags.removed_flags) {
if (flagsclear == NULL)
flagsclear = mboxevent_enqueue(EVENT_FLAGS_CLEAR, &mboxevents);
mboxevent_add_flags(flagsclear, mailbox->h.flagname,
modified_flags.removed_system_flags,
modified_flags.removed_user_flags);
mboxevent_extract_msgrecord(flagsclear, msgrec);
}
break;
case STORE_ANNOTATION: {
int dirty = 0;
r = index_store_annotation(state, msgno, msgrec, storeargs, &dirty);
if (r) goto doneloop;
if (!dirty) goto doneloop;
// rewrite message
r = msgrecord_rewrite(msgrec);
if (r) goto doneloop;
// XXX mboxevents?
break;
}
default:
r = IMAP_INTERNAL;
break;
}
if (r) goto doneloop;
/* msgrecord_rewrite already took care of rewriting the index_record,
* but we want to stay up to date of the changes in the index_map.
* Pass the silent flag to index_rewrite_record. */
r = msgrecord_get_index_record(msgrec, &record);
if (r) goto doneloop;
r = index_rewrite_record(state, msgno, &record, /*silent*/1);
doneloop:
msgrecord_unref(&msgrec);
if (r) goto out;
}
/* let mboxevent_notify split FlagsSet into MessageRead, MessageTrash
* and FlagsSet events */
mboxevent_extract_mailbox(flagsset, mailbox);
mboxevent_set_numunseen(flagsset, mailbox, state->numunseen);
mboxevent_set_access(flagsset, NULL, NULL, state->userid, mailbox_name(state->mailbox), 1);
mboxevent_extract_mailbox(flagsclear, mailbox);
mboxevent_set_access(flagsclear, NULL, NULL, state->userid, mailbox_name(state->mailbox), 1);
mboxevent_set_numunseen(flagsclear, mailbox, state->numunseen);
mboxevent_notify(&mboxevents);
out:
mboxevent_freequeue(&mboxevents);
if (storeargs->operation == STORE_ANNOTATION && r)
annotate_state_abort(&mailbox->annot_state);
seqset_free(&seq);
index_unlock(state);
index_tellchanges(state, storeargs->usinguid, storeargs->usinguid,
(storeargs->unchangedsince != ~0ULL));
return r;
}
static void prefetch_messages(struct index_state *state,
seqset_t *seq,
int usinguid)
{
struct mailbox *mailbox = state->mailbox;
struct index_map *im;
uint32_t msgno;
const char *fname;
struct index_record record;
syslog(LOG_ERR, "Prefetching initial parts of messages");
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (!seqset_ismember(seq, usinguid ? im->uid : msgno))
continue;
if (index_reload_record(state, msgno, &record))
continue;
fname = mailbox_record_fname(mailbox, &record);
if (!fname)
continue;
warmup_file(fname, 0, 16384);
}
}
/*
* Perform the XRUNANNOTATOR command which runs the
* annotator callout for each message in the given sequence.
*/
EXPORTED int index_run_annotator(struct index_state *state,
const char *sequence, int usinguid,
struct namespace *namespace, int isadmin)
{
struct index_record record;
seqset_t *seq = NULL;
struct index_map *im;
uint32_t msgno;
struct appendstate as;
msgrecord_t *msgrec = NULL;
int r = 0;
/* We do the acl check here rather than in append_setup_mbox()
* to account for the EXAMINE command where state->myrights has
* fewer rights than the ACL actually grants */
if (!(state->myrights & (ACL_WRITE|ACL_ANNOTATEMSG)))
return IMAP_PERMISSION_DENIED;
if (!config_getstring(IMAPOPT_ANNOTATION_CALLOUT))
return 0;
r = index_lock(state, /*readonly*/0);
if (r) return r;
r = append_setup_mbox(&as, state->mailbox,
state->userid, state->authstate,
0, NULL, namespace, isadmin, 0);
if (r) goto out;
seq = _parse_sequence(state, sequence, usinguid);
if (!seq) goto out;
prefetch_messages(state, seq, usinguid);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (!seqset_ismember(seq, usinguid ? im->uid : msgno))
continue;
/* if it's expunged already, skip it now */
if ((im->internal_flags & FLAG_INTERNAL_EXPUNGED))
continue;
r = index_reload_record(state, msgno, &record);
if (r) goto out;
msgrec = msgrecord_from_index_record(state->mailbox, &record);
r = append_run_annotator(&as, msgrec);
if (r) goto out;
/* msgrecord_rewrite already took care of rewriting the index_record,
* but we want to stay up to date of the changes in the index_map.
* Pass the silent flag to index_rewrite_record. */
r = msgrecord_get_index_record(msgrec, &record);
if (r) goto out;
r = index_rewrite_record(state, msgno, &record, /*silent*/1);
if (r) goto out;
msgrecord_unref(&msgrec);
}
out:
seqset_free(&seq);
if (msgrec) msgrecord_unref(&msgrec);
if (!r) {
r = append_commit(&as);
}
else {
append_abort(&as);
}
index_unlock(state);
index_tellchanges(state, usinguid, usinguid, 1);
return r;
}
EXPORTED int index_warmup(struct mboxlist_entry *mbentry,
unsigned int warmup_flags,
seqset_t *uids)
{
const char *fname = NULL;
char *userid = NULL;
char *tofree1 = NULL;
char *tofree2 = NULL;
unsigned int uid;
strarray_t files = STRARRAY_INITIALIZER;
int i;
int r = 0;
if (warmup_flags & WARMUP_INDEX) {
fname = mbentry_metapath(mbentry, META_INDEX, 0);
r = warmup_file(fname, 0, 0);
if (r) goto out;
}
if (warmup_flags & WARMUP_CONVERSATIONS) {
if (config_getswitch(IMAPOPT_CONVERSATIONS)) {
fname = tofree1 = conversations_getmboxpath(mbentry->name);
r = warmup_file(fname, 0, 0);
if (r) goto out;
}
}
if (warmup_flags & WARMUP_ANNOTATIONS) {
fname = mbentry_metapath(mbentry, META_ANNOTATIONS, 0);
r = warmup_file(fname, 0, 0);
if (r) goto out;
}
if (warmup_flags & WARMUP_SEARCH) {
userid = mboxname_to_userid(mbentry->name);
r = search_list_files(userid, &files);
if (r) goto out;
for (i = 0 ; i < files.count ; i++) {
fname = strarray_nth(&files, i);
r = warmup_file(fname, 0, 0);
if (r) goto out;
}
}
while ((uid = seqset_getnext(uids))) {
fname = mbentry_datapath(mbentry, uid);
r = warmup_file(fname, 0, 0);
if (r) goto out;
}
out:
if (r == ENOENT || r == ENOSYS)
r = 0;
if (r)
syslog(LOG_ERR, "IOERROR: unable to warmup file %s: %s",
fname, error_message(r));
free(userid);
free(tofree1);
free(tofree2);
strarray_fini(&files);
return r;
}
static void build_query(search_builder_t *bx,
search_expr_t *e,
int remove,
int *nmatchesp)
{
search_expr_t *child;
int bop = -1;
switch (e->op) {
case SEOP_NOT:
bop = SEARCH_OP_NOT;
break;
case SEOP_AND:
bop = SEARCH_OP_AND;
break;
case SEOP_OR:
bop = SEARCH_OP_OR;
break;
case SEOP_FUZZYMATCH:
if (e->attr && e->attr->part >= 0) {
bx->match(bx, e->attr->part, e->value.s);
(*nmatchesp)++;
if (remove && e->attr->part != SEARCH_PART_HEADERS) {
/*
* We're relying on the search engine to correctly
* find matching messages, so we don't need to
* keep this node in the expression tree anymore.
* Rather than remove it we neuter it.
*/
search_expr_neutralise(e);
}
}
return;
default:
return;
}
if (e->children) {
assert(bop != -1);
bx->begin_boolean(bx, bop);
for (child = e->children ; child ; child = child->next)
build_query(bx, child, remove, nmatchesp);
bx->end_boolean(bx, bop);
}
}
static int index_prefilter_messages(unsigned* msg_list,
struct index_state *state,
struct searchargs *searchargs __attribute((unused)))
{
unsigned int msgno;
xstats_inc(SEARCH_TRIVIAL);
/* Just put in all possible messages. This falls back to Cyrus' default
* search. */
for (msgno = 1; msgno <= state->exists; msgno++)
msg_list[msgno-1] = msgno;
return state->exists;
}
static int index_scan_work(const char *s, unsigned long len,
const char *match, unsigned long min)
{
while (len > min) {
if (!strncasecmp(s, match, min)) return(1);
s++;
len--;
}
return(0);
}
/*
* Guts of the SCAN command, lifted from _index_search()
*
* Returns 1 if we get a hit, otherwise returns 0.
*/
EXPORTED int index_scan(struct index_state *state, const char *contents)
{
unsigned *msgno_list;
uint32_t msgno;
int n = 0;
int listindex;
int listcount;
struct searchargs searchargs;
unsigned long length;
struct mailbox *mailbox = state->mailbox;
charset_t ascii = charset_lookupname("US-ASCII");
if (!(contents && contents[0])) return(0);
if (index_check(state, 0, 0))
return 0;
if (state->exists <= 0) return 0;
length = strlen(contents);
memset(&searchargs, 0, sizeof(struct searchargs));
searchargs.root = search_expr_new(NULL, SEOP_MATCH);
searchargs.root->attr = search_attr_find("text");
/* Use US-ASCII to emulate fgrep */
searchargs.root->value.s = charset_convert(contents, ascii, charset_flags);
search_expr_internalise(state, searchargs.root);
msgno_list = (unsigned *) xmalloc(state->exists * sizeof(unsigned));
listcount = index_prefilter_messages(msgno_list, state, &searchargs);
for (listindex = 0; !n && listindex < listcount; listindex++) {
if (!(listindex % 128) && cmd_cancelled(/*insearch*/1))
break;
struct buf buf = BUF_INITIALIZER;
struct index_record record;
msgno = msgno_list[listindex];
if (index_reload_record(state, msgno, &record))
continue;
if (mailbox_map_record(mailbox, &record, &buf))
continue;
n += index_scan_work(buf.s, buf.len, contents, length);
buf_free(&buf);
}
charset_free(&ascii);
search_expr_free(searchargs.root);
free(msgno_list);
return n;
}
EXPORTED uint32_t index_getuid(struct index_state *state, uint32_t msgno)
{
assert(msgno <= state->exists);
return state->map[msgno-1].uid;
}
/* 'uid_list' is malloc'd string representing the hits from searchargs;
returns number of hits */
EXPORTED int index_getuidsequence(struct index_state *state,
struct searchargs *searchargs,
unsigned **uid_list)
{
search_query_t *query = NULL;
search_folder_t *folder = NULL;
int r;
int n = 0;
query = search_query_new(state, searchargs);
r = search_query_run(query);
if (r) goto out;
folder = search_query_find_folder(query, index_mboxname(state));
if (!folder) goto out;
n = search_folder_get_array(folder, uid_list);
out:
search_query_free(query);
return n;
}
static int index_lock(struct index_state *state, int readonly)
{
int r;
if (state->mailbox) {
if (state->examining || readonly) {
r = mailbox_lock_index(state->mailbox, LOCK_SHARED);
if (r) return r;
}
else {
r = mailbox_lock_index(state->mailbox, LOCK_EXCLUSIVE);
if (r) return r;
}
}
else {
if (state->examining || readonly) {
r = mailbox_open_irl(state->mboxname, &state->mailbox);
if (r) return r;
}
else {
r = mailbox_open_iwl(state->mboxname, &state->mailbox);
if (r) return r;
}
}
/* if the UIDVALIDITY has changed, treat as a delete */
if (state->mailbox->i.uidvalidity != state->uidvalidity) {
mailbox_close(&state->mailbox);
return IMAP_MAILBOX_NONEXISTENT;
}
/* if highestmodseq has changed or file is repacked, read updates */
if (state->highestmodseq != state->mailbox->i.highestmodseq
|| state->generation != state->mailbox->i.generation_no)
index_refresh_locked(state);
return 0;
}
EXPORTED int index_status(struct index_state *state, struct statusdata *sdata)
{
int r = index_lock(state, /*readonly*/1);
if (r) return r;
status_fill_mailbox(state->mailbox, sdata);
status_fill_seen(state->userid, sdata, state->numrecent, state->numunseen);
index_unlock(state);
return 0;
}
EXPORTED int index_refresh(struct index_state *state)
{
int r;
r = index_lock(state, /*readonly*/1); /* calls index_refresh_locked */
if (r) return r;
index_unlock(state);
return 0;
}
static void index_unlock(struct index_state *state)
{
// only update seen if we've got a writelocked mailbox
if (mailbox_index_islocked(state->mailbox, 1))
index_writeseen(state); // XXX: errors?
/* grab the latest modseq */
state->highestmodseq = state->mailbox->i.highestmodseq;
if (state->mailbox->i.dirty) {
struct statusdata sdata = STATUSDATA_INIT;
status_fill_mailbox(state->mailbox, &sdata);
// we zero out recent data for everyone else
status_fill_seen(state->userid, &sdata, /*recent*/0, state->numunseen);
mailbox_unlock_index(state->mailbox, &sdata);
}
else {
mailbox_unlock_index(state->mailbox, NULL);
}
}
/*
* RFC 4551 says:
* If client specifies a MODSEQ criterion in a SEARCH command
* and the server returns a non-empty SEARCH result, the server
* MUST also append (to the end of the untagged SEARCH response)
* the highest mod-sequence for all messages being returned.
*/
static int needs_modseq(const struct searchargs *searchargs,
const struct sortcrit *sortcrit)
{
int i;
if (search_expr_uses_attr(searchargs->root, "modseq"))
return 1;
if (sortcrit) {
for (i = 0 ; sortcrit[i].key != SORT_SEQUENCE ; i++)
if (sortcrit[i].key == SORT_MODSEQ)
return 1;
}
return 0;
}
static void begin_esearch_response(struct index_state *state,
struct searchargs *searchargs,
int usinguid, search_folder_t *folder,
int nmsg)
{
/*
* Implement RFC 4731 return options.
*/
prot_printf(state->out, "* ESEARCH");
if (searchargs->tag) {
prot_printf(state->out, " (TAG \"%s\")", searchargs->tag);
}
/* RFC 4731: 3.1
* An extended UID SEARCH command MUST cause an ESEARCH response with
* the UID indicator present. */
if (usinguid) prot_printf(state->out, " UID");
if (searchargs->returnopts & SEARCH_RETURN_COUNT) {
prot_printf(state->out, " COUNT %u", nmsg);
}
if (nmsg) {
if (searchargs->returnopts & SEARCH_RETURN_MIN) {
prot_printf(state->out, " MIN %u", search_folder_get_min(folder));
}
if (searchargs->returnopts & SEARCH_RETURN_MAX) {
prot_printf(state->out, " MAX %u", search_folder_get_max(folder));
}
}
}
static void esearch_modseq_response(struct index_state *state,
struct searchargs *searchargs,
search_folder_t *folder,
modseq_t highestmodseq)
{
if (!highestmodseq) return;
// restrict modseq to the returned items only
if (searchargs->returnopts == SEARCH_RETURN_MIN) {
highestmodseq = search_folder_get_first_modseq(folder);
}
if (searchargs->returnopts == SEARCH_RETURN_MAX) {
highestmodseq = search_folder_get_last_modseq(folder);
}
if (searchargs->returnopts == (SEARCH_RETURN_MIN|SEARCH_RETURN_MAX)) {
/* special case min and max should be greatest of the two */
uint64_t last = search_folder_get_last_modseq(folder);
highestmodseq = search_folder_get_first_modseq(folder);
if (last > highestmodseq) highestmodseq = last;
}
if (highestmodseq)
prot_printf(state->out, " MODSEQ " MODSEQ_FMT, highestmodseq);
}
/*
* Performs a SEARCH command.
* This is a wrapper around the search_query API which simply prints the results.
*/
EXPORTED int index_search(struct index_state *state,
struct searchargs *searchargs,
int usinguid)
{
search_query_t *query = NULL;
search_folder_t *folder;
int nmsg = 0;
int i;
modseq_t highestmodseq = 0;
int r;
/* update the index */
if (index_check(state, 0, 0))
return 0;
highestmodseq = needs_modseq(searchargs, NULL);
query = search_query_new(state, searchargs);
r = search_query_run(query);
if (r) goto out; /* search failed */
folder = search_query_find_folder(query, index_mboxname(state));
if (folder) {
if (!usinguid)
search_folder_use_msn(folder, state);
if (highestmodseq)
highestmodseq = search_folder_get_highest_modseq(folder);
nmsg = search_folder_get_count(folder);
}
else
nmsg = 0;
if (searchargs->returnopts) {
begin_esearch_response(state, searchargs, usinguid, folder, nmsg);
if (nmsg) {
if (searchargs->returnopts & SEARCH_RETURN_ALL) {
seqset_t *seq = search_folder_get_seqset(folder);
if (seqset_first(seq)) {
char *str = seqset_cstring(seq);
prot_printf(state->out, " ALL %s", str);
free(str);
}
seqset_free(&seq);
}
if (searchargs->returnopts & SEARCH_RETURN_RELEVANCY) {
prot_printf(state->out, " RELEVANCY (");
for (i = 0; i < nmsg; i++) {
if (i) prot_putc(' ', state->out);
/* for now all messages have relevancy=100 */
prot_printf(state->out, "%u", 100);
}
prot_printf(state->out, ")");
}
esearch_modseq_response(state, searchargs, folder, highestmodseq);
}
}
else {
prot_printf(state->out, "* SEARCH");
if (nmsg) {
search_folder_foreach(folder, i) {
prot_printf(state->out, " %u", i);
}
}
if (highestmodseq)
prot_printf(state->out, " (MODSEQ " MODSEQ_FMT ")", highestmodseq);
}
prot_printf(state->out, "\r\n");
out:
search_query_free(query);
return nmsg;
}
/*
* Performs a SORT command
*/
EXPORTED int index_sort(struct index_state *state,
const struct sortcrit *sortcrit,
struct searchargs *searchargs, int usinguid)
{
int i;
int nmsg = 0;
modseq_t highestmodseq = 0;
search_query_t *query = NULL;
search_folder_t *folder = NULL;
int r;
/* update the index */
if (index_check(state, 0, 0))
return 0;
highestmodseq = needs_modseq(searchargs, NULL);
/* Search for messages based on the given criteria */
query = search_query_new(state, searchargs);
query->sortcrit = sortcrit;
r = search_query_run(query);
if (r) goto out; /* search failed */
folder = search_query_find_folder(query, index_mboxname(state));
if (folder) {
if (highestmodseq)
highestmodseq = search_folder_get_highest_modseq(folder);
nmsg = search_folder_get_count(folder);
}
if (searchargs->returnopts) {
begin_esearch_response(state, searchargs, usinguid, folder, nmsg);
if (nmsg) {
if (searchargs->returnopts & SEARCH_RETURN_ALL) {
seqset_t *seq = seqset_init(0, SEQ_SPARSE);
for (i = 0 ; i < query->merged_msgdata.count ; i++) {
MsgData *md = ptrarray_nth(&query->merged_msgdata, i);
seqset_add(seq, usinguid ? md->uid : md->msgno, 1);
}
if (seqset_first(seq)) {
char *str = seqset_cstring(seq);
prot_printf(state->out, " ALL %s", str);
free(str);
}
seqset_free(&seq);
}
if (searchargs->returnopts & SEARCH_RETURN_RELEVANCY) {
prot_printf(state->out, " RELEVANCY (");
for (i = 0; i < nmsg; i++) {
if (i) prot_putc(' ', state->out);
/* for now all messages have relevancy=100 */
prot_printf(state->out, "%u", 100);
}
prot_printf(state->out, ")");
}
esearch_modseq_response(state, searchargs, folder, highestmodseq);
}
}
else {
prot_printf(state->out, "* SORT");
if (nmsg) {
/* Output the sorted messages */
for (i = 0 ; i < query->merged_msgdata.count ; i++) {
MsgData *md = ptrarray_nth(&query->merged_msgdata, i);
prot_printf(state->out, " %u",
(usinguid ? md->uid : md->msgno));
}
}
if (highestmodseq)
prot_printf(state->out, " (MODSEQ " MODSEQ_FMT ")", highestmodseq);
}
prot_printf(state->out, "\r\n");
out:
search_query_free(query);
return nmsg;
}
#define UNPREDICTABLE (-1)
static int search_predict_total(struct index_state *state,
struct conversations_state *cstate,
const struct searchargs *searchargs,
int conversations,
modseq_t *xconvmodseqp)
{
conv_status_t convstatus = CONV_STATUS_INIT;
uint32_t exists;
if (conversations) {
conversation_getstatus(cstate,
CONV_FOLDER_KEY_MBOX(cstate, state->mailbox),
&convstatus);
/* always grab xconvmodseq, so we report a growing
* highestmodseq to all callers */
if (xconvmodseqp) *xconvmodseqp = convstatus.threadmodseq;
exists = convstatus.threadexists;
}
else {
if (xconvmodseqp) *xconvmodseqp = state->highestmodseq;
/* we may be in xconvupdates, where expunged are present */
exists = state->exists - state->num_expunged;
}
switch (search_expr_get_countability(searchargs->root)) {
case SEC_EXISTS:
return exists;
case SEC_EXISTS|SEC_NOT:
return 0;
/* we don't try to optimise searches on \Recent */
case SEC_SEEN:
assert(state->exists >= state->numunseen);
return state->exists - state->numunseen;
case SEC_SEEN|SEC_NOT:
return state->numunseen;
case SEC_CONVSEEN:
assert(conversations);
assert(convstatus.threadexists >= convstatus.threadunseen);
return convstatus.threadexists - convstatus.threadunseen;
case SEC_CONVSEEN|SEC_NOT:
assert(conversations);
return convstatus.threadunseen;
default:
return UNPREDICTABLE;
}
}
/*
* Performs a XCONVSORT command
*/
EXPORTED int index_convsort(struct index_state *state,
struct sortcrit *sortcrit,
struct searchargs *searchargs,
const struct windowargs *windowargs)
{
MsgData **msgdata = NULL;
unsigned int mi;
modseq_t xconvmodseq = 0;
int i;
hashu64_table seen_cids = HASHU64_TABLE_INITIALIZER;
uint32_t pos = 0;
int found_anchor = 0;
uint32_t anchor_pos = 0;
uint32_t first_pos = 0;
unsigned int ninwindow = 0;
ptrarray_t results = PTRARRAY_INITIALIZER;
int total = 0;
int r = 0;
struct conversations_state *cstate = NULL;
assert(windowargs);
assert(!windowargs->changedsince);
assert(!windowargs->upto);
/* Check the client didn't specify MULTIANCHOR. */
if (windowargs->anchor && windowargs->anchorfolder)
return IMAP_PROTOCOL_BAD_PARAMETERS;
/* make sure \Deleted messages are expunged. Will also lock the
* mailbox state and read any new information */
r = index_expunge(state, NULL, 1);
if (r) return r;
if (windowargs->conversations) {
cstate = conversations_get_mbox(index_mboxname(state));
if (!cstate)
return IMAP_INTERNAL;
}
search_expr_internalise(state, searchargs->root);
/* this works both with and without conversations */
total = search_predict_total(state, cstate, searchargs,
windowargs->conversations,
&xconvmodseq);
/* not going to match anything? bonus */
if (!total)
goto out;
construct_hashu64_table(&seen_cids, state->exists/4+4, 0);
/* Create/load the msgdata array.
* load data for ALL messages always. We sort before searching so
* we can take advantage of the window arguments to stop searching
* early */
msgdata = index_msgdata_load(state, NULL, state->exists, sortcrit,
windowargs->anchor, &found_anchor);
if (windowargs->anchor && !found_anchor) {
r = IMAP_ANCHOR_NOT_FOUND;
goto out;
}
/* Sort the messages based on the given criteria */
index_msgdata_sort(msgdata, state->exists, sortcrit);
/* One pass through the message list */
for (mi = 0 ; mi < state->exists ; mi++) {
MsgData *msg = msgdata[mi];
struct index_map *im = &state->map[msg->msgno-1];
/* can happen if we didn't "tellchanges" yet */
if (im->internal_flags & FLAG_INTERNAL_EXPUNGED)
continue;
/* run the search program against all messages */
if (!index_search_evaluate(state, searchargs->root, msg->msgno))
continue;
/* figure out whether this message is an exemplar */
if (windowargs->conversations) {
/* in conversations mode => only the first message seen
* with each unique CID is an exemplar */
if (hashu64_lookup(msg->cid, &seen_cids))
continue;
hashu64_insert(msg->cid, (void *)1, &seen_cids);
}
/* else not in conversations mode => all messages are exemplars */
pos++;
if (!anchor_pos &&
windowargs->anchor == msg->uid) {
/* we've found the anchor's position, rejoice! */
anchor_pos = pos;
}
if (windowargs->anchor) {
if (!anchor_pos)
continue;
if (pos < anchor_pos + windowargs->offset)
continue;
}
else if (windowargs->position) {
if (pos < windowargs->position)
continue;
}
if (windowargs->limit &&
++ninwindow > windowargs->limit) {
if (total == UNPREDICTABLE) {
/* the total was not predictable, so we need to keep
* going over the whole list to count it */
continue;
}
break;
}
if (!first_pos)
first_pos = pos;
ptrarray_append(&results, msg);
}
if (total == UNPREDICTABLE) {
/* the total was not predictable prima facie */
total = pos;
}
if (windowargs->anchor && !anchor_pos) {
/* the anchor was present but not an exemplar */
assert(results.count == 0);
r = IMAP_ANCHOR_NOT_FOUND;
goto out;
}
/* Print the resulting list */
/* Yes, we could use a seqset here, but apparently the most common
* sort order seen in the field is reverse date, which is basically
* the worst case for seqset. So we don't bother */
if (results.count) {
prot_printf(state->out, "* SORT"); /* uids */
for (i = 0 ; i < results.count ; i++) {
MsgData *msg = results.data[i];
prot_printf(state->out, " %u", msg->uid);
}
prot_printf(state->out, "\r\n");
}
out:
if (!r) {
if (first_pos)
prot_printf(state->out, "* OK [POSITION %u]\r\n", first_pos);
prot_printf(state->out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "]\r\n",
MAX(xconvmodseq, state->mailbox->i.highestmodseq));
prot_printf(state->out, "* OK [UIDVALIDITY %u]\r\n",
state->mailbox->i.uidvalidity);
prot_printf(state->out, "* OK [UIDNEXT %u]\r\n",
state->mailbox->i.last_uid + 1);
prot_printf(state->out, "* OK [TOTAL %u]\r\n",
total);
}
/* free all our temporary data */
index_msgdata_free(msgdata, state->exists);
ptrarray_fini(&results);
free_hashu64_table(&seen_cids, NULL);
return r;
}
/*
* Performs a XCONVMULTISORT command
*/
EXPORTED int index_convmultisort(struct index_state *state,
struct sortcrit *sortcrit,
struct searchargs *searchargs,
const struct windowargs *windowargs)
{
int mi;
int fi;
int i;
hashu64_table seen_cids = HASHU64_TABLE_INITIALIZER;
uint32_t pos = 0;
uint32_t anchor_pos = 0;
uint32_t first_pos = 0;
unsigned int ninwindow = 0;
/* array of (arrays of msgdata* with the same CID) */
ptrarray_t results = PTRARRAY_INITIALIZER;
/* Used as a placeholder which provides a non-NULL entry in the
* seen_cids hashtable for conversations which are outside the
* specified window. */
ptrarray_t dummy_response;
int total = UNPREDICTABLE;
int r = 0;
struct mboxname_counters counters;
search_query_t *query = NULL;
search_folder_t *folder = NULL;
search_folder_t *anchor_folder = NULL;
assert(windowargs);
assert(!windowargs->changedsince);
assert(!windowargs->upto);
/* Client needs to have specified MULTIANCHOR which includes
* the folder name instead of just ANCHOR. Check that here
* 'cos it's easier than doing so during parsing */
if (windowargs->anchor && !windowargs->anchorfolder)
return IMAP_PROTOCOL_BAD_PARAMETERS;
/* make sure folder still exists and map in data */
r = index_refresh(state);
if (r) return r;
r = mboxname_read_counters(index_mboxname(state), &counters);
if (r) return r;
query = search_query_new(state, searchargs);
query->multiple = 1;
query->need_ids = 1;
query->need_expunge = 1;
query->sortcrit = sortcrit;
r = search_query_run(query);
if (r) return r;
if (windowargs->anchorfolder) {
anchor_folder = search_query_find_folder(query, windowargs->anchorfolder);
if (!anchor_folder) {
r = IMAP_ANCHOR_NOT_FOUND;
goto out;
}
}
/* going to need to do conversation-level breakdown */
if (windowargs->conversations)
construct_hashu64_table(&seen_cids, query->merged_msgdata.count/4+4, 0);
/* no need */
else
total = query->merged_msgdata.count;
/* Another pass through the merged message list */
for (mi = 0 ; mi < query->merged_msgdata.count ; mi++) {
MsgData *md = ptrarray_nth(&query->merged_msgdata, mi);
ptrarray_t *response = NULL;
/* figure out whether this message is an exemplar */
if (windowargs->conversations) {
response = hashu64_lookup(md->cid, &seen_cids);
/* in conversations mode => only the first message seen
* with each unique CID is an exemplar */
if (response) {
if (response != &dummy_response)
ptrarray_append(response, md);
continue;
}
hashu64_insert(md->cid, &dummy_response, &seen_cids);
}
/* else not in conversations mode => all messages are exemplars */
pos++;
if (!anchor_pos &&
windowargs->anchor == md->uid &&
anchor_folder == md->folder) {
/* we've found the anchor's position, rejoice! */
anchor_pos = pos;
}
if (windowargs->anchor) {
if (!anchor_pos)
continue;
if (pos < anchor_pos + windowargs->offset)
continue;
}
else if (windowargs->position) {
if (pos < windowargs->position)
continue;
}
if (windowargs->limit &&
++ninwindow > windowargs->limit) {
if (total == UNPREDICTABLE) {
/* the total was not predictable, so we need to keep
* going over the whole list to count it */
continue;
}
break;
}
if (!first_pos)
first_pos = pos;
/* the message is the exemplar of a conversation which is inside
* the specified window, so record a non-dummy seen_cids entry
* and a results entry */
response = ptrarray_new();
ptrarray_push(response, md);
ptrarray_push(&results, response);
if (windowargs->conversations) {
hashu64_insert(md->cid, response, &seen_cids);
}
}
if (total == UNPREDICTABLE) {
/* the total was not predictable prima facie */
total = pos;
}
if (windowargs->anchor && !anchor_pos) {
/* the anchor was not found */
assert(results.count == 0);
r = IMAP_ANCHOR_NOT_FOUND;
goto out;
}
/* Print the resulting list */
xstats_add(SEARCH_RESULT, results.count);
if (results.count) {
/* The untagged response would be XCONVMULTISORT but
* Mail::IMAPTalk has an undocumented hack whereby any untagged
* response matching /sort/i is assumed to be a sequence of
* numeric uids. Meh. */
prot_printf(state->out, "* XCONVMULTI (");
for (fi = 0 ; fi < query->folders_by_id.count ; fi++) {
folder = ptrarray_nth(&query->folders_by_id, fi);
char *extname = mboxname_to_external(folder->mboxname, searchargs->namespace, searchargs->userid);
if (fi)
prot_printf(state->out, " ");
prot_printf(state->out, "(");
prot_printstring(state->out, extname);
prot_printf(state->out, " %u)", folder->uidvalidity);
free(extname);
}
prot_printf(state->out, ") (");
for (i = 0 ; i < results.count ; i++) {
ptrarray_t *response = ptrarray_nth(&results, i);
int j;
if (i)
prot_printf(state->out, " ");
for (j = 0; j < response->count; j++) {
MsgData *md = ptrarray_nth(response, j);
if (!j)
prot_printf(state->out, "(%s" , conversation_id_encode(md->cid));
prot_printf(state->out, " (%u %u)", md->folder->id, md->uid);
}
prot_printf(state->out, ")");
}
prot_printf(state->out, ")\r\n");
}
out:
if (!r) {
if (first_pos)
prot_printf(state->out, "* OK [POSITION %u]\r\n", first_pos);
prot_printf(state->out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "]\r\n",
counters.mailmodseq);
#if 0
prot_printf(state->out, "* OK [UIDNEXT %u]\r\n",
state->mailbox->i.last_uid + 1);
#endif
prot_printf(state->out, "* OK [TOTAL %u]\r\n",
total);
}
/* free all our temporary data */
free_hashu64_table(&seen_cids, NULL);
for (i = 0 ; i < results.count ; i++) {
ptrarray_t *response = ptrarray_nth(&results, i);
ptrarray_free(response);
}
ptrarray_fini(&results);
search_query_free(query);
return r;
}
struct snippet_rock {
struct protstream *out;
struct namespace *namespace;
const char *userid;
};
static int emit_snippet(struct mailbox *mailbox, uint32_t uid,
int part, const char *partid __attribute__((unused)),
const char *snippet, void *rock)
{
struct snippet_rock *sr = (struct snippet_rock *)rock;
const char *partname = search_part_as_string(part);
if (!partname) return 0;
char *extname = mboxname_to_external(mailbox_name(mailbox), sr->namespace, sr->userid);
prot_printf(sr->out, "* SNIPPET ");
prot_printstring(sr->out, extname);
prot_printf(sr->out, " %u %u %s ", mailbox->i.uidvalidity, uid, partname);
prot_printstring(sr->out, snippet);
prot_printf(sr->out, "\r\n");
free(extname);
return 0;
}
EXPORTED int index_snippets(struct index_state *state,
const struct snippetargs *snippetargs,
struct searchargs *searchargs)
{
void *intquery = NULL;
search_builder_t *bx = NULL;
search_text_receiver_t *rx = NULL;
struct mailbox *mailbox = NULL;
int i;
int r = 0;
int nmatches = 0;
struct snippet_rock srock;
/* reload index */
r = index_refresh(state);
if (r) return r;
bx = search_begin_search(state->mailbox, SEARCH_MULTIPLE);
if (!bx) {
r = IMAP_INTERNAL;
goto out;
}
build_query(bx, searchargs->root, 0, &nmatches);
if (!bx->get_internalised) goto out;
intquery = bx->get_internalised(bx);
search_end_search(bx);
if (!intquery) goto out;
srock.out = state->out;
srock.namespace = searchargs->namespace;
srock.userid = searchargs->userid;
rx = search_begin_snippets(intquery, 0/*verbose*/, &default_snippet_markup,
emit_snippet, &srock);
if (!rx) goto out;
for ( ; snippetargs ; snippetargs = snippetargs->next) {
mailbox = NULL;
if (!strcmp(snippetargs->mboxname, index_mboxname(state))) {
mailbox = state->mailbox;
}
else {
r = mailbox_open_irl(snippetargs->mboxname, &mailbox);
if (r) goto out;
mailbox_unlock_index(mailbox, NULL);
}
if (snippetargs->uidvalidity &&
snippetargs->uidvalidity != mailbox->i.uidvalidity) {
r = IMAP_NOTFOUND;
goto out;
}
r = rx->begin_mailbox(rx, mailbox, /*incremental*/0);
for (i = 0 ; i < snippetargs->uids.count ; i++) {
uint32_t uid = snippetargs->uids.data[i];
struct index_record record;
/* It's OK to do a dirty read, because we only care about
* the UID of the message */
r = mailbox_find_index_record(mailbox, uid, &record);
if (r == IMAP_MAILBOX_CHECKSUM) r = 0;
if (r) continue;
if (state->m) message_set_from_record(mailbox, &record, state->m);
else state->m = message_new_from_record(mailbox, &record);
index_getsearchtext(state->m, NULL, rx, INDEX_GETSEARCHTEXT_SNIPPET);
}
r = rx->end_mailbox(rx, mailbox);
if (r) goto out;
if (mailbox != state->mailbox)
mailbox_close(&mailbox);
}
out:
if (rx) search_end_snippets(rx);
if (intquery) search_free_internalised(intquery);
if (mailbox != state->mailbox)
mailbox_close(&mailbox);
return r;
}
static modseq_t get_modseq_of(MsgData *msg,
struct conversations_state *cstate)
{
modseq_t modseq = 0;
if (cstate) {
conversation_get_modseq(cstate, msg->cid, &modseq);
/* TODO: error handling dammit */
} else {
modseq = msg->modseq;
}
return modseq;
}
/*
* Performs a XCONVUPDATES command
*/
EXPORTED int index_convupdates(struct index_state *state,
struct sortcrit *sortcrit,
struct searchargs *searchargs,
const struct windowargs *windowargs)
{
MsgData **msgdata = NULL;
modseq_t xconvmodseq = 0;
unsigned int mi;
int i;
hashu64_table seen_cids = HASHU64_TABLE_INITIALIZER;
hashu64_table old_seen_cids = HASHU64_TABLE_INITIALIZER;
int32_t pos = 0;
uint32_t upto_pos = 0;
ptrarray_t added = PTRARRAY_INITIALIZER;
ptrarray_t removed = PTRARRAY_INITIALIZER;
ptrarray_t changed = PTRARRAY_INITIALIZER;
int total = 0;
struct conversations_state *cstate = NULL;
int is_mutable = search_is_mutable(sortcrit, searchargs->root);
int r = 0;
assert(windowargs);
assert(windowargs->changedsince);
assert(windowargs->offset == 0);
assert(!windowargs->position);
/* make sure \Deleted messages are expunged. Will also lock the
* mailbox state and read any new information */
r = index_expunge(state, NULL, 1);
if (r) return r;
if (windowargs->conversations) {
cstate = conversations_get_mbox(index_mboxname(state));
if (!cstate)
return IMAP_INTERNAL;
}
search_expr_internalise(state, searchargs->root);
total = search_predict_total(state, cstate, searchargs,
windowargs->conversations,
&xconvmodseq);
/* If there are no current and no expunged messages, we won't
* have any results at all and can short circuit the main loop;
* note that is a righter criterion than for XCONVSORT. */
if (!total && !state->exists)
goto out;
construct_hashu64_table(&seen_cids, state->exists/4+4, 0);
construct_hashu64_table(&old_seen_cids, state->exists/4+4, 0);
/* Create/load the msgdata array
* initial list - load data for ALL messages always */
msgdata = index_msgdata_load(state, NULL, state->exists, sortcrit, 0, NULL);
/* Sort the messages based on the given criteria */
index_msgdata_sort(msgdata, state->exists, sortcrit);
/* Discover exemplars */
for (mi = 0 ; mi < state->exists ; mi++) {
MsgData *msg = msgdata[mi];
struct index_map *im = &state->map[msg->msgno-1];
int was_old_exemplar = 0;
int is_new_exemplar = 0;
int is_deleted = 0;
int is_new = 0;
int was_deleted = 0;
int is_changed = 0;
int in_search = 0;
in_search = index_search_evaluate(state, searchargs->root, msg->msgno);
is_deleted = !!(im->internal_flags & FLAG_INTERNAL_EXPUNGED);
is_new = (im->uid >= windowargs->uidnext);
was_deleted = is_deleted && (im->modseq <= windowargs->modseq);
/* is this message a current exemplar? */
if (!is_deleted &&
in_search &&
(!windowargs->conversations || !hashu64_lookup(msg->cid, &seen_cids))) {
is_new_exemplar = 1;
pos++;
if (windowargs->conversations)
hashu64_insert(msg->cid, (void *)1, &seen_cids);
}
/* optimisation for when the total is
* not known but we've hit 'upto' */
if (upto_pos)
continue;
modseq_t modseq = get_modseq_of(msg, cstate);
is_changed = (modseq > windowargs->modseq);
/* was this message an old exemplar, or in the case of mutable
* searches, possible an old exemplar? */
if (!is_new &&
!was_deleted &&
(in_search || (is_mutable && is_changed)) &&
(!windowargs->conversations || !hashu64_lookup(msg->cid, &old_seen_cids))) {
was_old_exemplar = 1;
if (windowargs->conversations)
hashu64_insert(msg->cid, (void *)1, &old_seen_cids);
}
if (was_old_exemplar && !is_new_exemplar) {
ptrarray_push(&removed, msg);
} else if (!was_old_exemplar && is_new_exemplar) {
msg->msgno = pos; /* hacky: reuse ->msgno for pos */
ptrarray_push(&added, msg);
} else if (was_old_exemplar && is_new_exemplar) {
if (is_changed) {
ptrarray_push(&changed, msg);
if (is_mutable) {
/* is the search is mutable, we're in a whole world of
* uncertainty about the client's state, so we just
* report the exemplar in all three lists and let the
* client sort it out. */
ptrarray_push(&removed, msg);
msg->msgno = pos; /* hacky: reuse ->msgno for pos */
ptrarray_push(&added, msg);
}
}
}
/* if this is the last message the client cares about ('upto')
* then we can break early...unless its a mutable search or
* we need to keep going to calculate an accurate total */
if (!is_mutable &&
!upto_pos &&
msg->uid == windowargs->upto) {
if (total != UNPREDICTABLE)
break;
upto_pos = pos;
}
}
/* unlike 'anchor', the case of not finding 'upto' is not an error */
if (total == UNPREDICTABLE) {
/* the total was not predictable prima facie */
total = pos;
}
/* Print the resulting lists */
if (added.count) {
prot_printf(state->out, "* ADDED"); /* (uid pos) tuples */
for (i = 0 ; i < added.count ; i++) {
MsgData *msg = added.data[i];
prot_printf(state->out, " (%u %u)",
msg->uid, msg->msgno);
}
prot_printf(state->out, "\r\n");
}
if (removed.count) {
prot_printf(state->out, "* REMOVED"); /* uids */
for (i = 0 ; i < removed.count ; i++) {
MsgData *msg = removed.data[i];
prot_printf(state->out, " %u", msg->uid);
}
prot_printf(state->out, "\r\n");
}
if (changed.count) {
prot_printf(state->out, "* CHANGED"); /* cids or uids */
for (i = 0 ; i < changed.count ; i++) {
MsgData *msg = changed.data[i];
if (windowargs->conversations)
prot_printf(state->out, " %s",
conversation_id_encode(msg->cid));
else
prot_printf(state->out, " %u", msg->uid);
}
prot_printf(state->out, "\r\n");
}
out:
if (!r) {
prot_printf(state->out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "]\r\n",
MAX(xconvmodseq, state->mailbox->i.highestmodseq));
prot_printf(state->out, "* OK [UIDVALIDITY %u]\r\n",
state->mailbox->i.uidvalidity);
prot_printf(state->out, "* OK [UIDNEXT %u]\r\n",
state->mailbox->i.last_uid + 1);
prot_printf(state->out, "* OK [TOTAL %u]\r\n",
total);
}
/* free all our temporary data */
index_msgdata_free(msgdata, state->exists);
ptrarray_fini(&added);
ptrarray_fini(&removed);
ptrarray_fini(&changed);
free_hashu64_table(&seen_cids, NULL);
free_hashu64_table(&old_seen_cids, NULL);
return r;
}
/*
* Performs a THREAD command
*/
EXPORTED int index_thread(struct index_state *state, int algorithm,
struct searchargs *searchargs, int usinguid)
{
search_query_t *query = NULL;
search_folder_t *folder;
unsigned *msgno_list;
int nmsg = 0;
clock_t start;
modseq_t highestmodseq = 0;
int r;
/* update the index */
if (index_check(state, 0, 0))
return 0;
highestmodseq = needs_modseq(searchargs, NULL);
if(CONFIG_TIMING_VERBOSE)
start = clock();
/* Search for messages based on the given criteria */
query = search_query_new(state, searchargs);
r = search_query_run(query);
if (r) goto out; /* search failed */
folder = search_query_find_folder(query, index_mboxname(state));
if (folder) {
search_folder_use_msn(folder, state);
if (highestmodseq)
highestmodseq = search_folder_get_highest_modseq(folder);
nmsg = search_folder_get_array(folder, &msgno_list);
}
if (nmsg) {
/* Thread messages using given algorithm */
(*thread_algs[algorithm].threader)(state, msgno_list, nmsg, usinguid);
free(msgno_list);
if (highestmodseq)
prot_printf(state->out, " (MODSEQ " MODSEQ_FMT ")", highestmodseq);
}
/* print an empty untagged response */
else
index_thread_print(state, NULL, usinguid);
prot_printf(state->out, "\r\n");
if (CONFIG_TIMING_VERBOSE) {
/* debug */
syslog(LOG_DEBUG, "THREAD %s processing time: %d msg in %f sec",
thread_algs[algorithm].alg_name, nmsg,
(clock() - start) / (double) CLOCKS_PER_SEC);
}
out:
search_query_free(query);
return nmsg;
}
/*
* Performs a COPY command
*/
EXPORTED int
index_copy(struct index_state *state,
char *sequence,
int usinguid,
char *name,
char **copyuidp,
int nolink,
struct namespace *namespace,
int isadmin,
int ismove,
int ignorequota)
{
struct copyargs copyargs;
int i;
quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER;
quota_t *qptr = NULL;
int r;
struct appendstate appendstate;
uint32_t msgno, checkval;
long docopyuid;
seqset_t *seq;
struct mailbox *srcmailbox = NULL;
struct mailbox *destmailbox = NULL;
struct index_map *im;
int is_same_user;
ptrarray_t *msgrecs = NULL;
*copyuidp = NULL;
memset(©args, 0, sizeof(struct copyargs));
/* let's just see how common this is... */
if (!strcmp(index_mboxname(state), name))
syslog(LOG_NOTICE, "same mailbox copy %s (%s)", name, sequence);
is_same_user = mboxname_same_userid(index_mboxname(state), name);
if (is_same_user < 0)
return is_same_user;
r = index_check(state, usinguid, usinguid);
if (r) return r;
srcmailbox = state->mailbox;
seq = _parse_sequence(state, sequence, usinguid);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
checkval = usinguid ? im->uid : msgno;
if (!seqset_ismember(seq, checkval))
continue;
index_copysetup(state, msgno, ©args);
}
seqset_free(&seq);
if (copyargs.nummsg == 0) {
r = IMAP_NO_NOSUCHMSG;
goto done;
}
r = mailbox_open_iwl(name, &destmailbox);
if (r) goto done;
/* make sure copying into this mailbox is enabled */
r = insert_into_mailbox_allowed(destmailbox);
if (r) goto done;
/* if using conversations, a COPY is the same email, so there's no extra usage */
int checkquota = !ismove && !config_getswitch(IMAPOPT_QUOTA_USE_CONVERSATIONS);
/* not moving or different quota root - need to check quota */
if (checkquota || strcmpsafe(mailbox_quotaroot(srcmailbox), mailbox_quotaroot(destmailbox))) {
for (i = 0; i < copyargs.nummsg; i++)
qdiffs[QUOTA_STORAGE] += copyargs.records[i].size;
qdiffs[QUOTA_MESSAGE] = copyargs.nummsg;
qptr = qdiffs;
}
r = append_setup_mbox(&appendstate, destmailbox, state->userid,
state->authstate, ACL_INSERT,
ignorequota ? NULL : qptr, namespace, isadmin,
ismove ? EVENT_MESSAGE_MOVE : EVENT_MESSAGE_COPY);
if (r) goto done;
docopyuid = (appendstate.myrights & ACL_READ);
msgrecs = ptrarray_new();
for (i = 0; i < copyargs.nummsg; i++) {
msgrecord_t *mr = msgrecord_from_index_record(srcmailbox, ©args.records[i]);
ptrarray_append(msgrecs, mr);
}
r = append_copy(srcmailbox, &appendstate, msgrecs, nolink, is_same_user);
if (r) {
append_abort(&appendstate);
goto done;
}
r = append_commit(&appendstate);
if (r) goto done;
/* unlock first so we don't hold the lock while expunging
* the source */
mailbox_unlock_index(destmailbox, NULL);
if (docopyuid || ismove) {
char *source;
seqset_t *seq;
unsigned uidvalidity = destmailbox->i.uidvalidity;
seq = seqset_init(0, SEQ_SPARSE);
for (i = 0; i < copyargs.nummsg; i++)
seqset_add(seq, copyargs.records[i].uid, 1);
source = seqset_cstring(seq);
/* remove the source messages */
if (ismove)
r = index_expunge(state, source, 0);
if (docopyuid) {
*copyuidp = xmalloc(strlen(source) + 50);
if (appendstate.nummsg == 1)
sprintf(*copyuidp, "%u %s %u", uidvalidity, source,
appendstate.baseuid);
else
sprintf(*copyuidp, "%u %s %u:%u", uidvalidity, source,
appendstate.baseuid,
appendstate.baseuid + appendstate.nummsg - 1);
}
free(source);
seqset_free(&seq);
}
if (!r) {
/* we log the first name to get GUID-copy magic */
sync_log_mailbox_double(index_mboxname(state), name);
/* also want to log an append here, to make sure squatter notices */
sync_log_append(name);
}
done:
free(copyargs.records);
mailbox_close(&destmailbox);
if (msgrecs) {
for (i = 0; i < msgrecs->count; i++) {
msgrecord_t *mr = ptrarray_nth(msgrecs, i);
msgrecord_unref(&mr);
}
ptrarray_free(msgrecs);
}
return r;
}
/*
* Helper function to multiappend a message to remote mailbox
*/
static int index_appendremote(struct index_state *state, uint32_t msgno,
struct protstream *pout)
{
struct mailbox *mailbox = state->mailbox;
struct buf buf = BUF_INITIALIZER;
unsigned flag, flagmask = 0;
char datebuf[RFC3501_DATETIME_MAX+1];
char sepchar = '(';
struct index_record record;
int r;
r = index_reload_record(state, msgno, &record);
if (r) return r;
/* Open the message file */
if (mailbox_map_record(mailbox, &record, &buf))
return IMAP_NO_MSGGONE;
/* start the individual append */
prot_printf(pout, " ");
/* add system flags */
if (record.system_flags & FLAG_ANSWERED) {
prot_printf(pout, "%c\\Answered", sepchar);
sepchar = ' ';
}
if (record.system_flags & FLAG_FLAGGED) {
prot_printf(pout, "%c\\Flagged", sepchar);
sepchar = ' ';
}
if (record.system_flags & FLAG_DRAFT) {
prot_printf(pout, "%c\\Draft", sepchar);
sepchar = ' ';
}
if (record.system_flags & FLAG_DELETED) {
prot_printf(pout, "%c\\Deleted", sepchar);
sepchar = ' ';
}
if (record.system_flags & FLAG_SEEN) {
prot_printf(pout, "%c\\Seen", sepchar);
sepchar = ' ';
}
/* add user flags */
for (flag = 0; flag < MAX_USER_FLAGS; flag++) {
if ((flag & 31) == 0) {
flagmask = record.user_flags[flag/32];
}
if (state->flagname[flag] && (flagmask & (1<<(flag & 31)))) {
prot_printf(pout, "%c%s", sepchar, state->flagname[flag]);
sepchar = ' ';
}
}
/* add internal date */
time_to_rfc3501(record.internaldate, datebuf, sizeof(datebuf));
prot_printf(pout, ") \"%s\" ", datebuf);
/* message literal */
index_fetchmsg(state, &buf, 0, record.size, 0, 0);
/* close the message file */
buf_free(&buf);
return 0;
}
/*
* Performs a COPY command from a local mailbox to a remote mailbox
*/
EXPORTED int index_copy_remote(struct index_state *state, char *sequence,
int usinguid, struct protstream *pout)
{
uint32_t msgno;
seqset_t *seq;
struct index_map *im;
int r;
r = index_check(state, usinguid, usinguid);
if (r) return r;
seq = _parse_sequence(state, sequence, usinguid);
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
if (!seqset_ismember(seq, usinguid ? im->uid : msgno))
continue;
index_appendremote(state, msgno, pout);
}
seqset_free(&seq);
return 0;
}
/*
* Returns the msgno of the message with UID 'uid'.
* If no message with UID 'uid', returns the message with
* the highest UID not greater than 'uid'.
*/
EXPORTED uint32_t index_finduid(struct index_state *state, uint32_t uid)
{
unsigned low = 1;
unsigned high = state->exists;
unsigned mid;
unsigned miduid;
while (low <= high) {
mid = (high - low)/2 + low;
miduid = index_getuid(state, mid);
if (miduid == uid)
return mid;
else if (miduid > uid)
high = mid - 1;
else
low = mid + 1;
}
return high;
}
/* Helper function to determine domain of data */
enum {
DOMAIN_7BIT = 0,
DOMAIN_8BIT,
DOMAIN_BINARY
};
static int data_domain(const char *p, size_t n)
{
int r = DOMAIN_7BIT;
while (n--) {
if (!*p) return DOMAIN_BINARY;
if (*p & 0x80) r = DOMAIN_8BIT;
p++;
}
return r;
}
/*
* Helper function to fetch data from a message file. Writes a
* quoted-string or literal containing data from 'msg_base', which is
* of size 'msg_size', starting at 'offset' and containing 'size'
* octets. If 'octet_count' is nonzero, the data is
* further constrained by 'start_octet' and 'octet_count' as per the
* IMAP command PARTIAL.
*/
void index_fetchmsg(struct index_state *state, const struct buf *msg,
unsigned offset,
unsigned size, /* this is the correct size for a news message after
having LF translated to CRLF */
unsigned start_octet, unsigned octet_count)
{
unsigned n, domain;
/* If no data, output NIL */
if (!msg || !msg->s) {
prot_printf(state->out, "NIL");
return;
}
/* partial fetch: adjust 'size' */
if (octet_count) {
if (size <= start_octet) {
size = 0;
}
else {
size -= start_octet;
}
if (size > octet_count) size = octet_count;
}
/* If zero-length data, output empty quoted string */
if (size == 0) {
prot_printf(state->out, "\"\"");
return;
}
/* Seek over PARTIAL constraint */
offset += start_octet;
n = size;
if (offset + size > msg->len) {
if (msg->len > offset) {
n = msg->len - offset;
}
else {
prot_printf(state->out, "\"\"");
return;
}
}
/* Get domain of the data */
domain = data_domain(msg->s + offset, n);
if (domain == DOMAIN_BINARY) {
/* Write size of literal8 */
prot_printf(state->out, "~{%u}\r\n", size);
} else {
/* Write size of literal */
prot_printf(state->out, "{%u}\r\n", size);
}
/* Non-text literal -- tell the protstream about it */
if (domain != DOMAIN_7BIT) prot_data_boundary(state->out);
prot_write(state->out, msg->s + offset, n);
while (n++ < size) {
/* File too short, resynch client.
*
* This can only happen if the reported size of the part
* is incorrect and would push us past EOF.
*/
(void)prot_putc(' ', state->out);
}
/* End of non-text literal -- tell the protstream about it */
if (domain != DOMAIN_7BIT) prot_data_boundary(state->out);
}
static int body_is_rfc822(struct body *body)
{
return body &&
!strcasecmpsafe(body->type, "MESSAGE") &&
!strcasecmpsafe(body->subtype, "RFC822");
}
static struct body *find_part(struct body *body, int32_t part)
{
if (body_is_rfc822(body))
body = body->subpart;
else if (!body->numparts)
return NULL;
if (body->numparts) {
/* A multipart */
if (part >= body->numparts + 1)
return NULL;
body = body->subpart + part - 1;
}
else {
/* Every message has at least one part number. */
if (part > 1)
return NULL;
}
return body;
}
/*
* Helper function to fetch a body section
*/
static int index_fetchsection(struct index_state *state, const char *resp,
const struct buf *inmsg,
char *section, struct body *body, unsigned size,
unsigned start_octet, unsigned octet_count)
{
const char *p;
unsigned offset = 0;
char *decbuf = NULL;
struct buf msg = BUF_INITIALIZER;
struct body *top = body;
int wantheader = 0;
int32_t mimenum = 0;
int r;
p = section;
buf_init_ro(&msg, inmsg->s, inmsg->len);
/* Special-case BODY[] */
if (*p == ']') {
if (strstr(resp, "BINARY.SIZE")) {
prot_printf(state->out, "%s%u", resp, size);
} else {
prot_printf(state->out, "%s", resp);
index_fetchmsg(state, &msg, 0, size,
start_octet, octet_count);
}
return 0;
}
/*
section = "[" [section-spec] "]"
section-msgtext = "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list /
"TEXT"
; top-level or MESSAGE/RFC822 part
section-part = nz-number *("." nz-number)
; body part nesting
section-spec = section-msgtext / (section-part ["." section-text])
section-text = section-msgtext / "MIME"
; text other than actual body part (headers, etc.)
*/
while (*p != ']') {
switch (*p) {
case 'H':
if (!body_is_rfc822(body)) goto badpart;
body = body->subpart;
p += 6;
wantheader = 1;
goto emitpart;
case 'T':
if (!body_is_rfc822(body)) goto badpart;
body = body->subpart;
p += 4;
goto emitpart;
case 'M':
if (body == top) goto badpart;
p += 4;
wantheader = 1;
goto emitpart;
default:
mimenum = 0;
r = parseint32(p, &p, &mimenum);
if (*p == '.') p++;
if (r || !mimenum) goto badpart;
body = find_part(body, mimenum);
if (!body) goto badpart;
break;
}
}
emitpart:
if (*p != ']') goto badpart;
if (wantheader) {
offset = body->header_offset;
size = body->header_size;
}
else {
offset = body->content_offset;
size = body->content_size;
}
if (msg.s && !wantheader && (p = strstr(resp, "BINARY"))) {
/* BINARY or BINARY.SIZE */
int encoding = body->charset_enc & 0xff;
size_t newsize;
/* check that the offset isn't corrupt */
if (offset + size > msg.len) {
syslog(LOG_ERR, "invalid part offset in %s", index_mboxname(state));
return IMAP_IOERROR;
}
msg.s = (char *)charset_decode_mimebody(msg.s + offset, size, encoding,
&decbuf, &newsize);
if (!msg.s) {
/* failed to decode */
if (decbuf) free(decbuf);
return IMAP_NO_UNKNOWN_CTE;
}
else if (p[6] == '.') {
/* BINARY.SIZE */
prot_printf(state->out, "%s%zd", resp, newsize);
if (decbuf) free(decbuf);
return 0;
}
else {
/* BINARY */
offset = 0;
size = newsize;
msg.len = newsize;
}
}
/* Output body part */
prot_printf(state->out, "%s", resp);
index_fetchmsg(state, &msg, offset, size,
start_octet, octet_count);
if (decbuf) free(decbuf);
return 0;
badpart:
if (strstr(resp, "BINARY.SIZE"))
prot_printf(state->out, "%s0", resp);
else
prot_printf(state->out, "%sNIL", resp);
return 0;
}
/*
* Helper function to fetch a HEADER.FIELDS[.NOT] body section
*/
static void index_fetchfsection(struct index_state *state,
const char *msg_base,
unsigned long msg_size,
struct fieldlist *fsection,
struct body *body,
unsigned start_octet, unsigned octet_count)
{
const char *p;
int32_t mimenum = 0;
int fields_not = 0;
const char *crlf = "\r\n";
unsigned crlf_start = 0;
unsigned crlf_size = 2;
char *buf;
unsigned size;
int r;
/* If no data, output null quoted string */
if (!msg_base) {
prot_printf(state->out, "\"\"");
return;
}
p = fsection->section;
while (*p != 'H') {
r = parseint32(p, &p, &mimenum);
if (*p == '.') p++;
if (r || !mimenum) goto badpart;
body = find_part(body, mimenum);
if (!body) goto badpart;
}
if (body_is_rfc822(body)) body = body->subpart;
if (!body->header_size) goto badpart;
if (p[13]) fields_not++; /* Check for "." after "HEADER.FIELDS" */
buf = index_readheader(msg_base, msg_size,
body->header_offset,
body->header_size);
if (fields_not) {
message_pruneheader(buf, 0, fsection->fields);
}
else {
message_pruneheader(buf, fsection->fields, 0);
}
size = strlen(buf);
/* partial fetch: adjust 'size' */
if (octet_count) {
if (size <= start_octet) {
crlf_start = start_octet - size;
size = 0;
start_octet = 0;
if (crlf_size <= crlf_start) {
crlf_size = 0;
}
else {
crlf_size -= crlf_start;
}
}
else {
size -= start_octet;
}
if (size > octet_count) {
size = octet_count;
crlf_size = 0;
}
else if (size + crlf_size > octet_count) {
crlf_size = octet_count - size;
}
}
/* If no data, output null quoted string */
if (size + crlf_size == 0) {
prot_printf(state->out, "\"\"");
return;
}
/* Write literal */
prot_printf(state->out, "{%u}\r\n", size + crlf_size);
prot_write(state->out, buf + start_octet, size);
prot_write(state->out, crlf + crlf_start, crlf_size);
return;
badpart:
prot_printf(state->out, "NIL");
}
/*
* Helper function to read a header section into a static buffer
*/
static char *index_readheader(const char *msg_base, unsigned long msg_size,
unsigned offset, unsigned size)
{
static struct buf buf = BUF_INITIALIZER;
if (offset + size > msg_size) {
/* Message file is too short, truncate request */
if (offset < msg_size) {
size = msg_size - offset;
}
else {
size = 0;
}
}
buf_reset(&buf);
buf_appendmap(&buf, msg_base+offset, size);
return (char *)buf_cstring(&buf);
}
/*
* Handle a FETCH RFC822.HEADER.LINES or RFC822.HEADER.LINES.NOT
* that can't use the cacheheaders in cyrus.cache
*/
static void index_fetchheader(struct index_state *state,
const char *msg_base,
unsigned long msg_size,
unsigned size,
const strarray_t *headers,
const strarray_t *headers_not)
{
char *buf;
/* If no data, output null quoted string */
if (!msg_base) {
prot_printf(state->out, "\"\"");
return;
}
buf = index_readheader(msg_base, msg_size, 0, size);
message_pruneheader(buf, headers, headers_not);
size = strlen(buf);
prot_printf(state->out, "{%u}\r\n%s\r\n", size+2, buf);
}
/*
* Handle a FETCH RFC822.HEADER.LINES that can use the
* cacheheaders in cyrus.cache
*/
static void
index_fetchcacheheader(struct index_state *state, struct index_record *record,
const strarray_t *headers, unsigned start_octet,
unsigned octet_count)
{
static struct buf buf = BUF_INITIALIZER;
unsigned size;
const char *crlf = "\r\n";
unsigned crlf_start = 0;
unsigned crlf_size = 2;
struct mailbox *mailbox = state->mailbox;
if (mailbox_cacherecord(mailbox, record)) {
/* bogus cache record */
prot_printf(state->out, "\"\"");
return;
}
buf_setmap(&buf, cacheitem_base(record, CACHE_HEADERS),
cacheitem_size(record, CACHE_HEADERS));
buf_cstring(&buf);
message_pruneheader(buf.s, headers, 0);
size = strlen(buf.s); /* not buf.len, it has been pruned */
/* partial fetch: adjust 'size' */
if (octet_count) {
if (size <= start_octet) {
crlf_start = start_octet - size;
size = 0;
start_octet = 0;
if (crlf_size <= crlf_start) {
crlf_size = 0;
}
else {
crlf_size -= crlf_start;
}
}
else {
size -= start_octet;
}
if (size > octet_count) {
size = octet_count;
crlf_size = 0;
}
else if (size + crlf_size > octet_count) {
crlf_size = octet_count - size;
}
}
if (size + crlf_size == 0) {
prot_printf(state->out, "\"\"");
}
else {
prot_printf(state->out, "{%u}\r\n", size + crlf_size);
prot_write(state->out, buf.s + start_octet, size);
prot_write(state->out, crlf + crlf_start, crlf_size);
}
}
/*
* Send a * FLAGS response.
*/
static void index_listflags(struct index_state *state)
{
unsigned i;
int cancreate = 0;
char sepchar = '(';
prot_printf(state->out, "* FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen");
for (i = 0; i < MAX_USER_FLAGS; i++) {
if (state->flagname[i]) {
prot_printf(state->out, " %s", state->flagname[i]);
}
else cancreate++;
}
prot_printf(state->out, ")\r\n* OK [PERMANENTFLAGS ");
if (!state->examining) {
if (state->myrights & ACL_WRITE) {
prot_printf(state->out, "%c\\Answered \\Flagged \\Draft", sepchar);
sepchar = ' ';
}
if (state->myrights & ACL_DELETEMSG) {
prot_printf(state->out, "%c\\Deleted", sepchar);
sepchar = ' ';
}
if (state->myrights & ACL_SETSEEN) {
prot_printf(state->out, "%c\\Seen", sepchar);
sepchar = ' ';
}
if (state->myrights & ACL_WRITE) {
for (i = 0; i < MAX_USER_FLAGS; i++) {
if (state->flagname[i]) {
prot_printf(state->out, " %s", state->flagname[i]);
}
}
if (cancreate) {
prot_printf(state->out, " \\*");
}
}
}
if (sepchar == '(') prot_printf(state->out, "(");
prot_printf(state->out, ")] Ok\r\n");
}
EXPORTED void index_checkflags(struct index_state *state, int print, int dirty)
{
struct mailbox *mailbox = state->mailbox;
unsigned i;
for (i = 0; i < MAX_USER_FLAGS; i++) {
/* both empty */
if (!mailbox->h.flagname[i] && !state->flagname[i])
continue;
/* both same */
if (mailbox->h.flagname[i] && state->flagname[i] &&
!strcmp(mailbox->h.flagname[i], state->flagname[i]))
continue;
/* ok, got something to change! */
if (state->flagname[i])
free(state->flagname[i]);
if (mailbox->h.flagname[i])
state->flagname[i] = xstrdup(mailbox->h.flagname[i]);
else
state->flagname[i] = NULL;
dirty = 1;
}
if (dirty && print)
index_listflags(state);
}
static void index_tellexpunge(struct index_state *state)
{
unsigned oldmsgno;
uint32_t msgno = 1;
seqset_t *vanishedlist;
struct index_map *im;
unsigned exists = state->exists;
// if we want expunged, we can't tell them!
if (state->want_expunged) return;
vanishedlist = seqset_init(0, SEQ_SPARSE);
for (oldmsgno = 1; oldmsgno <= exists; oldmsgno++) {
im = &state->map[oldmsgno-1];
/* inform about expunges */
if (im->internal_flags & FLAG_INTERNAL_EXPUNGED) {
state->exists--;
state->num_expunged--;
/* they never knew about this one, skip */
if (msgno > state->oldexists)
continue;
state->oldexists--;
if ((client_capa & CAPA_QRESYNC))
seqset_add(vanishedlist, im->uid, 1);
else
prot_printf(state->out, "* %u EXPUNGE\r\n", msgno);
continue;
}
/* copy back if necessary (after first expunge) */
if (msgno < oldmsgno)
state->map[msgno-1] = *im;
msgno++;
}
/* report all vanished if we're doing it this way */
if (seqset_first(vanishedlist)) {
char *vanished = seqset_cstring(vanishedlist);
prot_printf(state->out, "* VANISHED %s\r\n", vanished);
free(vanished);
}
seqset_free(&vanishedlist);
/* highestmodseq can now come forward to real-time */
state->delayed_modseq = 0;
}
static void index_tellexists(struct index_state *state)
{
prot_printf(state->out, "* %u EXISTS\r\n", state->exists);
prot_printf(state->out, "* %u RECENT\r\n", state->numrecent);
state->oldexists = state->exists;
}
EXPORTED void index_tellchanges(struct index_state *state, int canexpunge,
int printuid, int printmodseq)
{
uint32_t msgno;
struct index_map *im;
/* must call tellexpunge before tellexists, because tellexpunge changes
* the size of oldexists to mention expunges, and tellexists will reset
* oldexists. If we do these out of order, we will tell the user about
* expunges of messages they never saw, which would be wrong */
if (canexpunge) index_tellexpunge(state);
if (state->oldexists != state->exists) index_tellexists(state);
if (state->oldhighestmodseq == state->highestmodseq) return;
index_checkflags(state, 1, 0);
/* print any changed message flags */
for (msgno = 1; msgno <= state->exists; msgno++) {
im = &state->map[msgno-1];
/* report if it's changed since last told */
if (im->modseq > im->told_modseq)
index_printflags(state, msgno, printuid, printmodseq);
}
}
struct fetch_annotation_rock {
struct protstream *pout;
const char *sep;
};
static void fetch_annotation_response(const char *mboxname
__attribute__((unused)),
uint32_t uid
__attribute__((unused)),
const char *entry,
struct attvaluelist *attvalues,
void *rock)
{
char sep2 = '(';
struct attvaluelist *l;
struct fetch_annotation_rock *frock = rock;
prot_printf(frock->pout, "%s", frock->sep);
prot_printastring(frock->pout, entry);
prot_putc(' ', frock->pout);
for (l = attvalues ; l ; l = l->next) {
prot_putc(sep2, frock->pout);
sep2 = ' ';
prot_printastring(frock->pout, l->attrib);
prot_putc(' ', frock->pout);
prot_printmap(frock->pout, l->value.s, l->value.len);
}
prot_putc(')', frock->pout);
frock->sep = " ";
}
/*
* Helper function to send FETCH data for the ANNOTATION
* fetch item.
*/
static int index_fetchannotations(struct index_state *state,
uint32_t msgno,
const struct fetchargs *fetchargs)
{
annotate_state_t *astate = NULL;
struct fetch_annotation_rock rock;
int r = 0;
r = mailbox_get_annotate_state(state->mailbox,
state->map[msgno-1].uid,
&astate);
if (r) return r;
annotate_state_set_auth(astate, fetchargs->isadmin,
fetchargs->userid, fetchargs->authstate);
memset(&rock, 0, sizeof(rock));
rock.pout = state->out;
rock.sep = "";
r = annotate_state_fetch(astate,
&fetchargs->entries, &fetchargs->attribs,
fetch_annotation_response, &rock);
return r;
}
struct fetch_mailbox_rock {
struct index_state *state;
int sep;
int wantname;
const struct fetchargs *fetchargs;
};
static int fetch_mailbox_cb(const conv_guidrec_t *rec, void *rock)
{
static const int needrights = ACL_READ|ACL_LOOKUP;
struct fetch_mailbox_rock *fmb_rock = (struct fetch_mailbox_rock *) rock;
mbentry_t *mbentry = NULL;
int myrights = 0;
struct mailbox *mailbox = NULL;
msgrecord_t *msgrecord = NULL;
char *extname = NULL;
int r = 0;
assert(fmb_rock->state != NULL);
assert(fmb_rock->fetchargs != NULL);
/* convdb has flags: skip if flag deleted or flag internal expunged */
if (rec->version >= 1) {
if ((rec->system_flags & FLAG_DELETED)
|| (rec->internal_flags & FLAG_INTERNAL_EXPUNGED))
goto done;
}
/* make sure we have appropriate rights */
r = conv_guidrec_mbentry(rec, &mbentry);
if (r) goto done;
myrights = cyrus_acl_myrights(fmb_rock->state->authstate, mbentry->acl);
if ((myrights & needrights) != needrights)
goto done;
/* convdb does not have flags: grab them from message record */
if (rec->version == 0) {
uint32_t system_flags, internal_flags;
r = mailbox_open_irl(mbentry->name, &mailbox);
if (r) goto done;
r = msgrecord_find(mailbox, rec->uid, &msgrecord);
if (r) goto done;
r = msgrecord_get_systemflags(msgrecord, &system_flags);
if (!r) r = msgrecord_get_internalflags(msgrecord, &internal_flags);
if (r) goto done;
if ((system_flags & FLAG_DELETED)
|| (internal_flags & FLAG_INTERNAL_EXPUNGED))
goto done;
}
if (fmb_rock->wantname) {
extname = mboxname_to_external(mbentry->name,
fmb_rock->fetchargs->namespace,
fmb_rock->fetchargs->userid);
}
if (fmb_rock->sep)
prot_putc(fmb_rock->sep, fmb_rock->state->out);
prot_printf(fmb_rock->state->out, "%s",
fmb_rock->wantname ? extname : mbentry->uniqueid);
fmb_rock->sep = ' ';
done:
if (extname) free(extname);
if (msgrecord) msgrecord_unref(&msgrecord);
if (mailbox) mailbox_close(&mailbox);
if (mbentry) mboxlist_entry_free(&mbentry);
return r;
}
/*
* Helper function to send FETCH data for the MAILBOXES
* fetch item.
*/
static int index_fetchmailboxes(struct index_state *state,
uint32_t msgno,
const struct fetchargs *fetchargs)
{
struct fetch_mailbox_rock rock = { state, 0, /*wantname*/ 1, fetchargs};
struct index_record record;
int r;
if (!fetchargs->convstate) return 0;
r = index_reload_record(state, msgno, &record);
if (r) return r;
return conversations_guid_foreach(fetchargs->convstate,
message_guid_encode(&record.guid),
&fetch_mailbox_cb,
&rock);
}
/*
* Helper function to send FETCH data for the MAILBOXIDS
* fetch item.
*/
static int index_fetchmailboxids(struct index_state *state,
uint32_t msgno,
const struct fetchargs *fetchargs)
{
struct fetch_mailbox_rock rock = { state, 0, /*wantname*/ 0, fetchargs};
struct index_record record;
int r;
if (!fetchargs->convstate) return 0;
r = index_reload_record(state, msgno, &record);
if (r) return r;
return conversations_guid_foreach(fetchargs->convstate,
message_guid_encode(&record.guid),
&fetch_mailbox_cb,
&rock);
}
/*
* Helper function to send * FETCH (FLAGS data.
* Does not send the terminating close paren or CRLF.
* Also sends preceeding * FLAGS if necessary.
*/
static void index_fetchflags(struct index_state *state,
uint32_t msgno)
{
int sepchar = '(';
unsigned flag;
bit32 flagmask = 0;
struct index_map *im = &state->map[msgno-1];
prot_printf(state->out, "* %u FETCH (FLAGS ", msgno);
if (im->isrecent) {
prot_printf(state->out, "%c\\Recent", sepchar);
sepchar = ' ';
}
if (im->system_flags & FLAG_ANSWERED) {
prot_printf(state->out, "%c\\Answered", sepchar);
sepchar = ' ';
}
if (im->system_flags & FLAG_FLAGGED) {
prot_printf(state->out, "%c\\Flagged", sepchar);
sepchar = ' ';
}
if (im->system_flags & FLAG_DRAFT) {
prot_printf(state->out, "%c\\Draft", sepchar);
sepchar = ' ';
}
if (im->system_flags & FLAG_DELETED) {
prot_printf(state->out, "%c\\Deleted", sepchar);
sepchar = ' ';
}
if (state->want_expunged && (im->internal_flags & FLAG_INTERNAL_EXPUNGED)) {
prot_printf(state->out, "%c\\Expunged", sepchar);
sepchar = ' ';
}
if (im->isseen) {
prot_printf(state->out, "%c\\Seen", sepchar);
sepchar = ' ';
}
for (flag = 0; flag < VECTOR_SIZE(state->flagname); flag++) {
if ((flag & 31) == 0) {
flagmask = im->user_flags[flag/32];
}
if (state->flagname[flag] && (flagmask & (1<<(flag & 31)))) {
prot_printf(state->out, "%c%s", sepchar, state->flagname[flag]);
sepchar = ' ';
}
}
if (sepchar == '(') (void)prot_putc('(', state->out);
(void)prot_putc(')', state->out);
im->told_modseq = im->modseq;
}
static void index_printflags(struct index_state *state,
uint32_t msgno, int usinguid,
int printmodseq)
{
struct index_map *im = &state->map[msgno-1];
index_fetchflags(state, msgno);
/* http://www.rfc-editor.org/errata_search.php?rfc=5162
* Errata ID: 1807 - MUST send UID and MODSEQ to all
* untagged FETCH unsolicited responses */
if (usinguid || (client_capa & CAPA_QRESYNC))
prot_printf(state->out, " UID %u", im->uid);
if (printmodseq || (client_capa & CAPA_CONDSTORE))
prot_printf(state->out, " MODSEQ (" MODSEQ_FMT ")", im->modseq);
prot_printf(state->out, ")\r\n");
}
/* interface message_read_bodystructure which makes sure the cache record
* exists and adds the MESSAGE/RFC822 wrapper to make fetch BODY[*]
* work consistently */
static void loadbody(struct mailbox *mailbox, struct index_record *record,
struct body **bodyp)
{
if (*bodyp) return;
if (mailbox_cacherecord(mailbox, record)) return;
struct body *body = xzmalloc(sizeof(struct body));
message_read_bodystructure(record, &body->subpart);
body->type = xstrdup("MESSAGE");
body->subtype = xstrdup("RFC822");
body->header_offset = 0;
body->header_size = 0;
body->content_offset = 0;
body->content_offset = record->size;
*bodyp = body;
}
/*
* Helper function to send requested * FETCH data for a message
*/
static int index_fetchreply(struct index_state *state, uint32_t msgno,
const struct fetchargs *fetchargs)
{
struct mailbox *mailbox = state->mailbox;
int fetchitems = fetchargs->fetchitems;
struct buf buf = BUF_INITIALIZER;
struct octetinfo *oi = NULL;
int sepchar = '(';
int started = 0;
struct section *section;
struct fieldlist *fsection;
char respbuf[100];
int r = 0;
struct index_map *im = &state->map[msgno-1];
struct index_record record;
struct body *body = NULL;
/* Check the modseq against changedsince */
if (fetchargs->changedsince && im->modseq <= fetchargs->changedsince)
return 0;
/* skip missing records entirely */
if (!im->recno)
return 0;
r = index_reload_record(state, msgno, &record);
if (r) {
prot_printf(state->out, "* OK ");
prot_printf(state->out, error_message(IMAP_NO_MSGGONE), msgno);
prot_printf(state->out, "\r\n");
return 0;
}
/* Check against the CID list filter */
if (fetchargs->cidhash) {
const char *key = conversation_id_encode(record.cid);
if (!hash_lookup(key, fetchargs->cidhash))
return 0;
}
/* Open the message file if we're going to need it */
if ((fetchitems & (FETCH_HEADER|FETCH_TEXT|FETCH_SHA1|FETCH_RFC822)) ||
fetchargs->cache_atleast > record.cache_version ||
fetchargs->binsections || fetchargs->sizesections ||
fetchargs->bodysections) {
if (mailbox_map_record(mailbox, &record, &buf)) {
prot_printf(state->out, "* OK ");
prot_printf(state->out, error_message(IMAP_NO_MSGGONE), msgno);
prot_printf(state->out, "\r\n");
return 0;
}
}
int ischanged = im->told_modseq < record.modseq;
/* display flags if asked _OR_ if they've changed */
if (fetchitems & FETCH_FLAGS || ischanged) {
index_fetchflags(state, msgno);
sepchar = ' ';
}
else if ((fetchitems & ~FETCH_SETSEEN) || fetchargs->fsections ||
fetchargs->headers.count || fetchargs->headers_not.count) {
/* these fetch items will always succeed, so start the response */
prot_printf(state->out, "* %u FETCH ", msgno);
started = 1;
}
if (fetchitems & FETCH_UID || (ischanged && (client_capa & CAPA_QRESYNC))) {
prot_printf(state->out, "%cUID %u", sepchar, record.uid);
sepchar = ' ';
}
if (fetchitems & FETCH_GUID) {
prot_printf(state->out, "%cDIGEST.SHA1 %s", sepchar,
message_guid_encode(&record.guid));
sepchar = ' ';
}
if (fetchitems & FETCH_INTERNALDATE) {
time_t msgdate = record.internaldate;
char datebuf[RFC3501_DATETIME_MAX+1];
time_to_rfc3501(msgdate, datebuf, sizeof(datebuf));
prot_printf(state->out, "%cINTERNALDATE \"%s\"",
sepchar, datebuf);
sepchar = ' ';
}
if (fetchitems & FETCH_LASTUPDATED) {
time_t msgdate = record.last_updated;
char datebuf[RFC3501_DATETIME_MAX+1];
time_to_rfc3501(msgdate, datebuf, sizeof(datebuf));
prot_printf(state->out, "%cLASTUPDATED \"%s\"",
sepchar, datebuf);
sepchar = ' ';
}
if (fetchitems & FETCH_MODSEQ || (ischanged && (client_capa & CAPA_CONDSTORE))) {
prot_printf(state->out, "%cMODSEQ (" MODSEQ_FMT ")",
sepchar, record.modseq);
sepchar = ' ';
}
if (fetchitems & FETCH_SIZE) {
prot_printf(state->out, "%cRFC822.SIZE %u",
sepchar, record.size);
sepchar = ' ';
}
if ((fetchitems & FETCH_ANNOTATION)) {
prot_printf(state->out, "%cANNOTATION (", sepchar);
r = index_fetchannotations(state, msgno, fetchargs);
r = 0;
prot_printf(state->out, ")");
sepchar = ' ';
}
if (fetchitems & FETCH_PREVIEW) {
prot_printf(state->out, "%cPREVIEW ", sepchar);
const char *annot = config_getstring(IMAPOPT_JMAP_PREVIEW_ANNOT);
if (annot && !strncmp(annot, "/shared/", 8)) {
struct buf previewbuf = BUF_INITIALIZER;
annotatemore_msg_lookup(mailbox, record.uid, annot+7,
/*userid*/"", &previewbuf);
if (buf_len(&previewbuf) > 256)
buf_truncate(&previewbuf, 256); // XXX - utf8 chars
prot_printastring(state->out, buf_cstring(&previewbuf));
buf_free(&previewbuf);
}
else {
prot_puts(state->out, "NIL");
}
sepchar = ' ';
}
if (fetchitems & FETCH_FILESIZE) {
unsigned int msg_size = buf.len;
if (!buf.s) {
const char *fname = mailbox_record_fname(mailbox, &record);
struct stat sbuf;
/* Find the size of the message file */
if (stat(fname, &sbuf) == -1)
syslog(LOG_ERR, "IOERROR: stat on %s: %m", fname);
else
msg_size = sbuf.st_size;
}
prot_printf(state->out, "%cRFC822.FILESIZE %lu", sepchar,
(long unsigned)msg_size);
sepchar = ' ';
}
if (fetchitems & FETCH_SHA1) {
struct message_guid tmpguid;
message_guid_generate(&tmpguid, buf.s, buf.len);
prot_printf(state->out, "%cRFC822.SHA1 %s", sepchar, message_guid_encode(&tmpguid));
sepchar = ' ';
}
if (fetchitems & FETCH_EMAILID) {
char emailid[26];
emailid[0] = 'M';
memcpy(emailid+1, message_guid_encode(&record.guid), 24);
emailid[25] = '\0';
prot_printf(state->out, "%cEMAILID (%s)", sepchar, emailid);
sepchar = ' ';
}
if ((fetchitems & FETCH_CID) &&
config_getswitch(IMAPOPT_CONVERSATIONS)) {
struct buf buf = BUF_INITIALIZER;
if (!record.cid)
buf_appendcstr(&buf, "NIL");
else
buf_printf(&buf, CONV_FMT, record.cid);
prot_printf(state->out, "%cCID %s", sepchar, buf_cstring(&buf));
buf_free(&buf);
sepchar = ' ';
}
if ((fetchitems & FETCH_THREADID)) {
char threadid[18];
if (!record.cid) {
threadid[0] = 'N';
threadid[1] = 'I';
threadid[2] = 'L';
threadid[3] = '\0';
}
else {
threadid[0] = 'T';
memcpy(threadid+1, conversation_id_encode(record.cid), 16);
threadid[17] = '\0';
}
prot_printf(state->out, "%cTHREADID (%s)", sepchar, threadid);
sepchar = ' ';
}
if (fetchitems & FETCH_SAVEDATE) {
time_t msgdate = record.savedate;
char datebuf[RFC3501_DATETIME_MAX+1];
// handle internaldate
if (!msgdate) msgdate = record.internaldate;
time_to_rfc3501(msgdate, datebuf, sizeof(datebuf));
prot_printf(state->out, "%cSAVEDATE \"%s\"",
sepchar, datebuf);
sepchar = ' ';
}
if (fetchitems & FETCH_CREATEDMODSEQ) {
prot_printf(state->out, "%cCREATEDMODSEQ (" MODSEQ_FMT ")",
sepchar, record.createdmodseq);
sepchar = ' ';
}
if ((fetchitems & FETCH_BASECID) &&
config_getswitch(IMAPOPT_CONVERSATIONS)) {
mailbox_read_basecid(mailbox, &record);
struct buf buf = BUF_INITIALIZER;
if (!record.basecid)
buf_appendcstr(&buf, "NIL");
else
buf_printf(&buf, CONV_FMT, record.basecid);
prot_printf(state->out, "%cBASECID %s", sepchar, buf_cstring(&buf));
buf_free(&buf);
sepchar = ' ';
}
if ((fetchitems & FETCH_FOLDER)) {
char *extname = mboxname_to_external(index_mboxname(state),
fetchargs->namespace, fetchargs->userid);
prot_printf(state->out, "%cFOLDER ", sepchar);
prot_printastring(state->out, extname);
sepchar = ' ';
free(extname);
}
if ((fetchitems & FETCH_UIDVALIDITY)) {
prot_printf(state->out, "%cUIDVALIDITY %u", sepchar,
state->mailbox->i.uidvalidity);
sepchar = ' ';
}
if (config_getswitch(IMAPOPT_CONVERSATIONS)) {
if (fetchitems & FETCH_MAILBOXES) {
prot_printf(state->out, "%cMAILBOXES (", sepchar);
r = index_fetchmailboxes(state, msgno, fetchargs);
r = 0;
prot_printf(state->out, ")");
sepchar = ' ';
}
if (fetchitems & FETCH_MAILBOXIDS) {
prot_printf(state->out, "%cMAILBOXIDS (", sepchar);
r = index_fetchmailboxids(state, msgno, fetchargs);
r = 0;
prot_printf(state->out, ")");
sepchar = ' ';
}
}
if (fetchitems & FETCH_ENVELOPE) {
if (!mailbox_cacherecord(mailbox, &record)) {
prot_printf(state->out, "%cENVELOPE ", sepchar);
sepchar = ' ';
prot_putbuf(state->out, cacheitem_buf(&record, CACHE_ENVELOPE));
}
}
if (fetchitems & FETCH_BODYSTRUCTURE) {
if (!mailbox_cacherecord(mailbox, &record)) {
prot_printf(state->out, "%cBODYSTRUCTURE ", sepchar);
sepchar = ' ';
prot_putbuf(state->out, cacheitem_buf(&record, CACHE_BODYSTRUCTURE));
}
}
if (fetchitems & FETCH_BODY) {
if (!mailbox_cacherecord(mailbox, &record)) {
prot_printf(state->out, "%cBODY ", sepchar);
sepchar = ' ';
prot_putbuf(state->out, cacheitem_buf(&record, CACHE_BODY));
}
}
if (fetchitems & FETCH_HEADER) {
prot_printf(state->out, "%cRFC822.HEADER ", sepchar);
sepchar = ' ';
index_fetchmsg(state, &buf, 0,
record.header_size,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : 0,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : 0);
}
else if (fetchargs->headers.count || fetchargs->headers_not.count) {
prot_printf(state->out, "%cRFC822.HEADER ", sepchar);
sepchar = ' ';
if (fetchargs->cache_atleast > record.cache_version) {
index_fetchheader(state, buf.s, buf.len,
record.header_size,
&fetchargs->headers, &fetchargs->headers_not);
} else {
index_fetchcacheheader(state, &record, &fetchargs->headers, 0, 0);
}
}
if (fetchitems & FETCH_TEXT) {
prot_printf(state->out, "%cRFC822.TEXT ", sepchar);
sepchar = ' ';
index_fetchmsg(state, &buf,
record.header_size, record.size - record.header_size,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : 0,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : 0);
}
if (fetchitems & FETCH_RFC822) {
prot_printf(state->out, "%cRFC822 ", sepchar);
sepchar = ' ';
index_fetchmsg(state, &buf, 0, record.size,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : 0,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : 0);
}
for (fsection = fetchargs->fsections; fsection; fsection = fsection->next) {
int i;
prot_printf(state->out, "%cBODY[%s ", sepchar, fsection->section);
sepchar = '(';
for (i = 0 ; i < fsection->fields->count ; i++) {
(void)prot_putc(sepchar, state->out);
sepchar = ' ';
prot_printastring(state->out, fsection->fields->data[i]);
}
(void)prot_putc(')', state->out);
sepchar = ' ';
oi = (struct octetinfo *)fsection->rock;
prot_printf(state->out, "%s ", fsection->trail);
if (fetchargs->cache_atleast > record.cache_version) {
loadbody(mailbox, &record, &body);
if (body) {
index_fetchfsection(state, buf.s, buf.len,
fsection,
body,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : oi->start_octet,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : oi->octet_count);
} else {
prot_printf(state->out, "NIL");
}
}
else {
index_fetchcacheheader(state, &record, fsection->fields,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : oi->start_octet,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : oi->octet_count);
}
}
for (section = fetchargs->bodysections; section; section = section->next) {
respbuf[0] = 0;
if (sepchar == '(' && !started) {
/* we haven't output a fetch item yet, so start the response */
snprintf(respbuf, sizeof(respbuf), "* %u FETCH ", msgno);
}
snprintf(respbuf+strlen(respbuf), sizeof(respbuf)-strlen(respbuf),
"%cBODY[%s ", sepchar, section->name);
oi = §ion->octetinfo;
loadbody(mailbox, &record, &body);
if (body) {
r = index_fetchsection(state, respbuf, &buf,
section->name, body, record.size,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : oi->start_octet,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : oi->octet_count);
if (!r) sepchar = ' ';
}
}
for (section = fetchargs->binsections; section; section = section->next) {
respbuf[0] = 0;
if (sepchar == '(' && !started) {
/* we haven't output a fetch item yet, so start the response */
snprintf(respbuf, sizeof(respbuf), "* %u FETCH ", msgno);
}
snprintf(respbuf+strlen(respbuf), sizeof(respbuf)-strlen(respbuf),
"%cBINARY[%s ", sepchar, section->name);
loadbody(mailbox, &record, &body);
if (body) {
oi = §ion->octetinfo;
r = index_fetchsection(state, respbuf, &buf,
section->name, body, record.size,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->start_octet : oi->start_octet,
(fetchitems & FETCH_IS_PARTIAL) ?
fetchargs->octet_count : oi->octet_count);
if (!r) sepchar = ' ';
}
}
for (section = fetchargs->sizesections; section; section = section->next) {
respbuf[0] = 0;
if (sepchar == '(' && !started) {
/* we haven't output a fetch item yet, so start the response */
snprintf(respbuf, sizeof(respbuf), "* %u FETCH ", msgno);
}
snprintf(respbuf+strlen(respbuf), sizeof(respbuf)-strlen(respbuf),
"%cBINARY.SIZE[%s ", sepchar, section->name);
loadbody(mailbox, &record, &body);
if (body) {
r = index_fetchsection(state, respbuf, &buf,
section->name, body, record.size,
fetchargs->start_octet, fetchargs->octet_count);
if (!r) sepchar = ' ';
}
}
if (sepchar != '(') {
/* finsh the response if we have one */
prot_printf(state->out, ")\r\n");
}
buf_free(&buf);
if (body) {
message_free_body(body);
free(body);
}
return r;
}
/*
* Fetch the text data associated with an IMAP URL.
*
* If outsize is NULL, the data will be output as a literal (URLFETCH),
* otherwise just the data will be output (CATENATE), and its size returned
* in *outsize.
*
* This is an amalgamation of index_fetchreply(), index_fetchsection()
* and index_fetchmsg().
*/
EXPORTED int index_urlfetch(struct index_state *state, uint32_t msgno,
unsigned params, const char *section,
unsigned long start_octet, unsigned long octet_count,
struct protstream *pout, size_t maxsize, unsigned long *outsize)
{
/* dumbass eM_Client sends this:
* A4 APPEND "INBOX.Junk Mail" () "14-Jul-2013 17:01:02 +0000"
* CATENATE (URL "/INBOX/;uid=83118/;section=TEXT.MIME"
* URL "/INBOX/;uid=83118/;section=TEXT")
*
* genius. I can sort of see how TEXT.MIME kinda == "HEADER",
* so there we go */
static char text_mime[] = "HEADER";
struct buf buf = BUF_INITIALIZER;
int domain = DOMAIN_7BIT;
const char *data;
size_t size;
int32_t wantheader = 0;
unsigned long n;
int r = 0;
char *decbuf = NULL;
struct index_record record;
struct body *top = NULL, *body = NULL;
size_t section_offset, section_size;
r = index_lock(state, /*readonly*/1); // XXX: do we need to stay locked for this entire function?
if (r) return r;
struct mailbox *mailbox = state->mailbox;
if (!strcasecmpsafe(section, "TEXT.MIME"))
section = text_mime;
if (outsize) *outsize = 0;
r = index_reload_record(state, msgno, &record);
if (r) goto done;
loadbody(mailbox, &record, &body);
if (!body) goto done;
top = body;
/* Open the message file */
if (mailbox_map_record(mailbox, &record, &buf)) {
r = IMAP_NO_MSGGONE;
goto done;
}
data = buf.s;
size = buf.len;
int is_binary = params & URLFETCH_BINARY;
/* Special-case BODY[] */
if (!section || !*section) {
/* whole message, no further parsing */
}
else {
const char *p = ucase((char *) section);
int32_t mimenum = 0;
while (*p) {
switch(*p) {
case 'H':
if (is_binary) goto badpart;
if (!body_is_rfc822(body)) goto badpart;
body = body->subpart;
p += 6;
wantheader = 1;
goto getoffset;
case 'T':
if (is_binary) goto badpart;
if (!body_is_rfc822(body)) goto badpart;
body = body->subpart;
p += 4;
goto getoffset;
case 'M':
if (is_binary) goto badpart;
if (top == body) goto badpart;
p += 4;
wantheader = 1;
goto getoffset;
default:
mimenum = 0;
r = parseint32(p, &p, &mimenum);
if (*p == '.') p++;
if (r || !mimenum) goto badpart;
body = find_part(body, mimenum);
if (!body) goto badpart;
break;
}
}
getoffset:
if (*p) goto badpart;
section_offset = wantheader ? body->header_offset : body->content_offset;
section_size = wantheader ? body->header_size : body->content_size;
if (section_offset + section_size < section_offset
|| section_offset + section_size > size) {
r = IMAP_INTERNAL;
goto done;
}
data += section_offset;
size = section_size;
}
if (is_binary) {
int encoding = body->charset_enc & 0xff;
data = charset_decode_mimebody(data, size, encoding,
&decbuf, &size);
/* update the encoding of this part per RFC 5524:3.2 */
if (data && encoding) {
domain = data_domain(data, size);
free(body->encoding);
switch (domain) {
case DOMAIN_BINARY:
body->encoding = xstrdup("BINARY");
break;
case DOMAIN_8BIT:
body->encoding = xstrdup("8BIT");
break;
default:
body->encoding = NULL; // will output 7BIT
break;
}
body->content_size = size;
body->content_lines = 0;
}
}
if (params & URLFETCH_BODYPARTSTRUCTURE) {
struct buf buf = BUF_INITIALIZER;
message_write_body(&buf, body, 1);
prot_puts(pout, " (BODYPARTSTRUCTURE ");
if (buf_len(&buf))
prot_putbuf(pout, &buf);
else
prot_puts(pout, "NIL");
prot_puts(pout, ")");
buf_free(&buf);
}
if (params & URLFETCH_BODY) {
prot_printf(pout, " (BODY");
}
else if (params & URLFETCH_BINARY) {
prot_printf(pout, " (BINARY");
if (!data) {
/* failed to decode */
prot_printf(pout, " NIL)");
r = 0;
goto done;
}
}
else if (params) {
r = 0;
goto done;
}
/* Handle PARTIAL request */
n = octet_count ? octet_count : size;
/* Sanity check the requested size */
if (start_octet > size) {
start_octet = size;
n = 0;
}
else if (start_octet + n < start_octet || start_octet + n > size) {
n = size - start_octet;
}
if (n > maxsize) {
r = IMAP_MESSAGE_TOO_LARGE;
goto done;
}
if (outsize) {
/* Return size (CATENATE) */
*outsize = n;
} else {
domain = data_domain(data + start_octet, n);
if (domain == DOMAIN_BINARY) {
/* Write size of literal8 */
prot_printf(pout, " ~{%lu}\r\n", n);
} else {
/* Write size of literal */
prot_printf(pout, " {%lu}\r\n", n);
}
}
/* Non-text literal -- tell the protstream about it */
if (domain != DOMAIN_7BIT) prot_data_boundary(pout);
if (n) prot_write(pout, data + start_octet, n);
/* End of non-text literal -- tell the protstream about it */
if (domain != DOMAIN_7BIT) prot_data_boundary(pout);
/* Complete extended URLFETCH response */
if (params) prot_printf(pout, ")");
r = 0;
done:
/* Close the message file */
index_unlock(state);
buf_free(&buf);
if (top) {
message_free_body(top);
free(top);
}
if (decbuf) free(decbuf);
return r;
badpart:
r = IMAP_PROTOCOL_BAD_PARAMETERS;
goto done;
}
/*
* Helper function to perform a STORE command for flags.
*/
static int index_storeflag(struct index_state *state,
struct index_modified_flags *modified_flags,
uint32_t msgno, msgrecord_t *msgrec,
struct storeargs *storeargs)
{
uint32_t old, new, keep;
unsigned i;
int dirty = 0;
modseq_t oldmodseq;
struct index_map *im = &state->map[msgno-1];
int seen_dirty = 0;
int r;
memset(modified_flags, 0, sizeof(struct index_modified_flags));
oldmodseq = im->modseq;
/* Change \Seen flag. This gets done on the index first and will only be
copied into the record later if internalseen is set */
if (state->myrights & ACL_SETSEEN) {
old = im->isseen ? 1 : 0;
new = old;
if (storeargs->operation == STORE_REPLACE_FLAGS)
new = storeargs->seen ? 1 : 0;
else if (storeargs->seen)
new = (storeargs->operation == STORE_ADD_FLAGS) ? 1 : 0;
if (new != old) {
if (state->numunseen || new < old)
state->numunseen += (old - new);
else
syslog(LOG_ERR, "IOERROR: numunseen underflow in storeflag: %s %u",
state->mboxname, im->uid);
im->isseen = new;
state->seen_dirty = 1;
dirty++;
seen_dirty = 1;
}
}
uint32_t system_flags;
uint32_t internal_flags;
uint32_t user_flags[MAX_USER_FLAGS/32];
r = msgrecord_get_systemflags(msgrec, &system_flags);
if (r) return r;
r = msgrecord_get_internalflags(msgrec, &internal_flags);
if (r) return r;
r = msgrecord_get_userflags(msgrec, user_flags);
if (r) return r;
keep = internal_flags;
old = system_flags & FLAGS_SYSTEM;
new = storeargs->system_flags & FLAGS_SYSTEM;
/* all other updates happen directly to the record */
if (storeargs->operation == STORE_REPLACE_FLAGS) {
if (!(state->myrights & ACL_WRITE)) {
/* ACL_DELETE handled in index_store() */
if ((old & FLAG_DELETED) != (new & FLAG_DELETED)) {
dirty++;
system_flags = (old & ~FLAG_DELETED) | (new & FLAG_DELETED);
}
}
else {
if (!(state->myrights & ACL_DELETEMSG)) {
if ((old & ~FLAG_DELETED) != (new & ~FLAG_DELETED)) {
dirty++;
system_flags = (old & FLAG_DELETED) | (new & ~FLAG_DELETED);
}
}
else {
if (old != new) {
dirty++;
system_flags = new;
}
}
for (i = 0; i < (MAX_USER_FLAGS/32); i++) {
if (user_flags[i] != storeargs->user_flags[i]) {
uint32_t changed;
dirty++;
changed = ~user_flags[i] & storeargs->user_flags[i];
if (changed) {
modified_flags->added_user_flags[i] = changed;
modified_flags->added_flags++;
}
changed = user_flags[i] & ~storeargs->user_flags[i];
if (changed) {
modified_flags->removed_user_flags[i] = changed;
modified_flags->removed_flags++;
}
user_flags[i] = storeargs->user_flags[i];
}
}
}
}
else if (storeargs->operation == STORE_ADD_FLAGS) {
uint32_t added;
if (~old & new) {
dirty++;
system_flags = old | new;
}
for (i = 0; i < (MAX_USER_FLAGS/32); i++) {
added = ~user_flags[i] & storeargs->user_flags[i];
if (added) {
dirty++;
user_flags[i] |= storeargs->user_flags[i];
modified_flags->added_user_flags[i] = added;
modified_flags->added_flags++;
}
}
}
else { /* STORE_REMOVE_FLAGS */
uint32_t removed;
if (old & new) {
dirty++;
system_flags &= ~storeargs->system_flags;
}
for (i = 0; i < (MAX_USER_FLAGS/32); i++) {
removed = user_flags[i] & storeargs->user_flags[i];
if (removed) {
dirty++;
user_flags[i] &= ~storeargs->user_flags[i];
modified_flags->removed_user_flags[i] = removed;
modified_flags->removed_flags++;
}
}
}
/* RFC 4551:
* 3.8. Additional Quality-of-Implementation Issues
*
* Server implementations should follow the following rule, which
* applies to any successfully completed STORE/UID STORE (with and
* without UNCHANGEDSINCE modifier), as well as to a FETCH command that
* implicitly sets \Seen flag:
*
* Adding the flag when it is already present or removing when it is
* not present SHOULD NOT change the mod-sequence.
*
* This will prevent spurious client synchronization requests.
*/
if (!dirty) return 0;
if (state->internalseen) {
/* copy the seen flag from the index */
if (im->isseen)
system_flags |= FLAG_SEEN;
else
system_flags &= ~FLAG_SEEN;
}
/* add back the internal tracking flags */
system_flags |= keep;
modified_flags->added_system_flags = ~old & system_flags & FLAGS_SYSTEM;
if (modified_flags->added_system_flags)
modified_flags->added_flags++;
modified_flags->removed_system_flags = old & ~system_flags & FLAGS_SYSTEM;
if (modified_flags->removed_system_flags)
modified_flags->removed_flags++;
r = msgrecord_set_systemflags(msgrec, system_flags);
if (r) return r;
r = msgrecord_set_internalflags(msgrec, internal_flags);
if (r) return r;
r = msgrecord_set_userflags(msgrec, user_flags);
if (r) return r;
// patch back in seen state for non-internal-seen
if (seen_dirty && !state->internalseen) {
if (im->isseen) {
modified_flags->added_system_flags |= FLAG_SEEN;
modified_flags->added_flags++;
}
else {
modified_flags->removed_system_flags |= FLAG_SEEN;
modified_flags->removed_flags++;
}
}
/* if it's silent and unchanged, update the seen value, but
* not if qresync is enabled - RFC 4551 says that the MODSEQ
* must always been told, and we prefer just to tell flags
* as well in this case, it's simpler and not much more
* bandwidth */
if (!(client_capa & CAPA_CONDSTORE) && storeargs->silent && im->told_modseq == oldmodseq)
im->told_modseq = im->modseq;
return 0;
}
/*
* Helper function to perform a STORE command for annotations
*/
static int index_store_annotation(struct index_state *state,
uint32_t msgno,
msgrecord_t *msgrec,
struct storeargs *storeargs,
int *dirty)
{
modseq_t oldmodseq;
struct index_record *record;
struct index_map *im = &state->map[msgno-1];
int r;
r = msgrecord_get_index_record_rw(msgrec, &record);
if (r) goto out;
r = index_reload_record(state, msgno, record);
if (r) goto out;
oldmodseq = record->modseq;
r = msgrecord_annot_set_auth(msgrec, storeargs->isadmin, storeargs->userid,
storeargs->authstate);
if (r) goto out;
r = msgrecord_annot_writeall(msgrec, storeargs->entryatts);
if (r) goto out;
/* It would be nice if the annotate layer told us whether it
* actually made a change to the database, but it doesn't, so
* we have to assume the message is dirty */
*dirty = 1;
r = index_rewrite_record(state, msgno, record, /*silent*/1);
if (r) goto out;
/* if it's silent and unchanged, update the seen value */
if (!(client_capa & CAPA_CONDSTORE) && storeargs->silent && im->told_modseq == oldmodseq)
im->told_modseq = im->modseq;
out:
return r;
}
/*
* Evaluate a searchargs structure on a msgno
*/
EXPORTED int index_search_evaluate(struct index_state *state,
const search_expr_t *e,
uint32_t msgno)
{
struct index_map *im = &state->map[msgno-1];
struct index_record record;
int always = search_expr_always_same(e);
if (always < 0) return 0;
if (always > 0) return 1;
// failure to load is an error!
int r = index_reload_record(state, msgno, &record);
if (r) return 0;
xstats_inc(SEARCH_EVALUATE);
int flags = (im->isrecent ? MESSAGE_RECENT : 0)
| (im->isseen ? MESSAGE_SEEN : 0);
if (state->m) message_set_from_index(state->mailbox, &record, msgno, flags, state->m);
else state->m = message_new_from_index(state->mailbox, &record, msgno, flags);
int match = search_expr_evaluate(state->m, e);
return match;
}
struct extractor_ctx {
struct protstream *clientin;
char *hostname;
char *path;
struct backend *be;
};
struct getsearchtext_rock
{
search_text_receiver_t *receiver;
int indexed_headers;
int charset_flags;
const strarray_t *partids;
int snippet_iteration; /* 0..no snippet, 1..first run, 2..second run */
struct extractor_ctx *ext;
strarray_t striphtml; /* strip HTML from these plain text body part ids */
uint8_t indexlevel;
int flags;
};
static void stuff_part(search_text_receiver_t *receiver,
int part, const struct buf *buf)
{
// don't try to index a zero length part
if (!buf_len(buf)) return;
if (part == SEARCH_PART_HEADERS &&
!config_getswitch(IMAPOPT_SEARCH_INDEX_HEADERS))
return;
receiver->begin_part(receiver, part);
receiver->append_text(receiver, buf);
receiver->end_part(receiver, part);
}
static int extract_cb(const struct buf *text, void *rock)
{
struct getsearchtext_rock *str = (struct getsearchtext_rock *)rock;
return str->receiver->append_text(str->receiver, text);
}
#ifdef USE_HTTPD
static int extract_icalbuf(struct buf *raw, charset_t charset, int encoding,
struct getsearchtext_rock *str)
{
icalcomponent *comp = NULL, *ical = NULL;
const char *s;
int r = 0;
struct buf buf = BUF_INITIALIZER;
/* Parse the message into an iCalendar object */
const struct buf *icalbuf = NULL;
if (encoding || strcasecmp(charset_canon_name(charset), "utf-8")) {
char *tmp = charset_to_utf8(buf_cstring(raw), buf_len(raw), charset, encoding);
if (!tmp) return 0; /* could be a bogus header - ignore */
buf_initm(&buf, tmp, strlen(tmp));
icalbuf = &buf;
}
else {
icalbuf = raw;
}
ical = icalparser_parse_string(buf_cstring(icalbuf));
buf_reset(&buf);
if (!ical) {
r = IMAP_INTERNAL;
goto done;
}
for (comp = icalcomponent_get_first_real_component(ical);
comp;
comp = icalcomponent_get_next_component(ical, icalcomponent_isa(comp))) {
icalproperty *prop;
icalparameter *param;
/* description */
if ((s = icalcomponent_get_description(comp))) {
buf_setcstr(&buf, s);
charset_t utf8 = charset_lookupname("utf-8");
str->receiver->begin_part(str->receiver, SEARCH_PART_BODY);
charset_extract(extract_cb, str, &buf, utf8, 0, "calendar",
str->charset_flags);
str->receiver->end_part(str->receiver, SEARCH_PART_BODY);
charset_free(&utf8);
buf_reset(&buf);
}
/* summary */
if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
if ((s = icalproperty_get_summary(prop))) {
buf_setcstr(&buf, s);
stuff_part(str->receiver, SEARCH_PART_SUBJECT, &buf);
buf_reset(&buf);
}
}
/* organizer */
if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
if ((s = icalproperty_get_organizer(prop))) {
if (!strncasecmp(s, "mailto:", 7)) {
s += 7;
}
param = icalproperty_get_first_parameter(prop, ICAL_CN_PARAMETER);
if (param) {
buf_printf(&buf, "\"%s\" <%s>", icalparameter_get_cn(param), s);
} else {
buf_setcstr(&buf, s);
}
stuff_part(str->receiver, SEARCH_PART_FROM, &buf);
buf_reset(&buf);
}
}
/* attendees */
for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
prop;
prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
if ((s = icalproperty_get_attendee(prop))) {
if (!strncasecmp(s, "mailto:", 7)) {
s += 7;
}
param = icalproperty_get_first_parameter(prop, ICAL_CN_PARAMETER);
if (buf.len) {
buf_appendcstr(&buf, ", ");
}
if (param) {
buf_printf(&buf, "\"%s\" <%s>", icalparameter_get_cn(param), s);
} else {
buf_appendcstr(&buf, s);
}
}
}
if (buf.len) {
stuff_part(str->receiver, SEARCH_PART_TO, &buf);
buf_reset(&buf);
}
/* location */
if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
if ((s = icalproperty_get_location(prop))) {
buf_setcstr(&buf, s);
stuff_part(str->receiver, SEARCH_PART_LOCATION, &buf);
buf_reset(&buf);
}
}
}
done:
if (ical) icalcomponent_free(ical);
buf_free(&buf);
return r;
}
static void _add_vcard_singlval(struct vparse_card *card, const char *key, struct buf *buf)
{
struct vparse_entry *entry;
for (entry = card->properties; entry; entry = entry->next) {
if (strcasecmp(entry->name, key)) continue;
const char *val = entry->v.value;
if (val && val[0]) {
if (buf_len(buf)) buf_putc(buf, ' ');
buf_appendcstr(buf, val);
}
}
}
static void _add_vcard_multival(struct vparse_card *card, const char *key, struct buf *buf)
{
struct vparse_entry *entry;
for (entry = card->properties; entry; entry = entry->next) {
if (strcasecmp(entry->name, key)) continue;
const strarray_t *sa = entry->v.values;
int i;
for (i = 0; i < strarray_size(sa); i++) {
const char *val = strarray_nth(sa, i);
if (val && val[0]) {
if (buf_len(buf)) buf_putc(buf, ' ');
buf_appendcstr(buf, val);
}
}
}
}
static int extract_vcardbuf(struct buf *raw, charset_t charset, int encoding,
struct getsearchtext_rock *str)
{
struct vparse_card *vcard = NULL;
int r = 0;
struct buf buf = BUF_INITIALIZER;
/* Parse the message into a vcard object */
const struct buf *vcardbuf = NULL;
if (encoding || strcasecmp(charset_canon_name(charset), "utf-8")) {
char *tmp = charset_to_utf8(buf_cstring(raw), buf_len(raw), charset, encoding);
if (!tmp) return 0; /* could be a bogus header - ignore */
buf_initm(&buf, tmp, strlen(tmp));
vcardbuf = &buf;
}
else {
vcardbuf = raw;
}
vcard = vcard_parse_string(buf_cstring(vcardbuf));
if (!vcard || !vcard->objects) {
r = IMAP_INTERNAL;
goto done;
}
buf_reset(&buf);
// these are all the things that we think might be interesting
_add_vcard_singlval(vcard->objects, "fn", &buf);
_add_vcard_singlval(vcard->objects, "email", &buf);
_add_vcard_singlval(vcard->objects, "tel", &buf);
_add_vcard_singlval(vcard->objects, "url", &buf);
_add_vcard_singlval(vcard->objects, "impp", &buf);
_add_vcard_singlval(vcard->objects, "x-social-profile", &buf);
_add_vcard_singlval(vcard->objects, "x-fm-online-other", &buf);
_add_vcard_singlval(vcard->objects, "nickname", &buf);
_add_vcard_singlval(vcard->objects, "note", &buf);
_add_vcard_multival(vcard->objects, "n", &buf);
_add_vcard_multival(vcard->objects, "org", &buf);
_add_vcard_multival(vcard->objects, "adr", &buf);
if (buf.len) {
charset_t utf8 = charset_lookupname("utf-8");
str->receiver->begin_part(str->receiver, SEARCH_PART_BODY);
charset_extract(extract_cb, str, &buf, utf8, 0, "vcard",
str->charset_flags);
str->receiver->end_part(str->receiver, SEARCH_PART_BODY);
charset_free(&utf8);
buf_reset(&buf);
}
done:
if (vcard) vparse_free_card(vcard);
buf_free(&buf);
return r;
}
#endif /* USE_HTTPD */
#define IDLE_TIMEOUT (5 * 60) /* 5 min */
static int login(struct backend *s __attribute__((unused)),
const char *userid __attribute__((unused)),
sasl_callback_t *cb __attribute__((unused)),
const char **status __attribute__((unused)),
int noauth __attribute__((unused)))
{
return 0;
}
static int ping(struct backend *s __attribute__((unused)),
const char *userid __attribute__((unused)))
{
return 0;
}
static int logout(struct backend *s __attribute__((unused)))
{
return 0;
}
static void extractor_disconnect(struct extractor_ctx *ext)
{
if (!ext) return;
struct backend *be = ext->be;
syslog(LOG_DEBUG, "extractor_disconnect(%p)", be);
if (!be || (be->sock == -1)) {
/* already disconnected */
return;
}
/* need to logout of server */
backend_disconnect(be);
/* remove the timeout */
if (be->timeout) prot_removewaitevent(be->clientin, be->timeout);
be->timeout = NULL;
be->clientin = NULL;
}
static struct prot_waitevent *
extractor_timeout(struct protstream *s __attribute__((unused)),
struct prot_waitevent *ev __attribute__((unused)),
void *rock)
{
struct extractor_ctx *ext = rock;
syslog(LOG_DEBUG, "extractor_timeout(%p)", ext);
/* too long since we last used the extractor - disconnect */
extractor_disconnect(ext);
return NULL;
}
static struct protocol_t http =
{ "http", "HTTP", TYPE_SPEC, { .spec = { &login, &ping, &logout } } };
static int extractor_connect(struct extractor_ctx *ext)
{
struct backend *be;
time_t now = time(NULL);
syslog(LOG_DEBUG, "extractor_connect()");
be = ext->be;
if (be && be->sock != -1) {
// extend the timeout
if (be->timeout) be->timeout->mark = now + IDLE_TIMEOUT;
return 0;
}
// clean up any existing connection
extractor_disconnect(ext);
be = ext->be = backend_connect(be, ext->hostname,
&http, NULL, NULL, NULL, -1);
if (!be) {
syslog(LOG_ERR, "extract_connect: failed to connect to %s",
ext->hostname);
return IMAP_IOERROR;
}
if (ext->clientin) {
/* add a default timeout */
be->clientin = ext->clientin;
be->timeout = prot_addwaitevent(ext->clientin,
now + IDLE_TIMEOUT,
extractor_timeout, ext);
}
return 0;
}
static int extract_attachment(const char *type, const char *subtype,
const struct param *type_params,
const struct buf *data, int encoding,
const struct message_guid *content_guid,
struct getsearchtext_rock *str)
{
struct backend *be;
struct buf decbuf = BUF_INITIALIZER;
struct buf buf = BUF_INITIALIZER;
hdrcache_t hdrs = NULL;
struct body_t body = { 0, 0, 0, 0, 0, BUF_INITIALIZER };
const char *guidstr, *errstr = NULL;
size_t hostlen;
const char **hdr, *p;
int r = 0;
if (!index_text_extractor) {
/* This is a legitimate case for sieve and lmtpd (so we don't need
* to spam the logs! */
syslog(LOG_DEBUG, "%s: ignoring uninitialized extractor",
__func__);
return 0;
}
if (message_guid_isnull(content_guid)) {
syslog(LOG_DEBUG, "extract_attachment: ignoring null guid for %s/%s",
type ? type : "<null>", subtype ? subtype : "<null>");
return 0;
}
struct extractor_ctx *ext = str->ext = index_text_extractor;
r = extractor_connect(ext);
if (r) return r;
be = ext->be;
hostlen = strcspn(ext->hostname, "/");
guidstr = message_guid_encode(content_guid);
/* try to fetch previously extracted text */
unsigned statuscode = 0;
prot_printf(be->out,
"GET %s/%s %s\r\n"
"Host: %.*s\r\n"
"User-Agent: Cyrus/%s\r\n"
"Connection: Keep-Alive\r\n"
"Keep-Alive: timeout=%u\r\n"
"Accept: text/plain\r\n"
"X-Truncate-Length: " SIZE_T_FMT "\r\n"
"\r\n",
ext->path, guidstr, HTTP_VERSION,
(int) hostlen, be->hostname, CYRUS_VERSION,
IDLE_TIMEOUT, config_search_maxsize);
prot_flush(be->out);
/* Read GET response */
do {
r = http_read_response(be, METH_GET,
&statuscode, &hdrs, &body, &errstr);
if (r) {
syslog(LOG_ERR,
"extract_attachment: failed to read response for GET %s/%s",
ext->path, guidstr);
statuscode = 599;
}
} while (statuscode < 200);
syslog(LOG_DEBUG, "extract_attachment: GET %s/%s: got status %u",
ext->path, guidstr, statuscode);
if (statuscode == 200) goto gotdata;
// otherwise we're going to try three times to PUT this request to the server!
/* Decode data */
if (encoding) {
if (charset_decode(&decbuf, buf_base(data), buf_len(data), encoding)) {
syslog(LOG_ERR, "extract_attachment: failed to decode data");
r = IMAP_IOERROR;
goto done;
}
data = &decbuf;
}
/* Build list of Content-Type parameters */
const struct param *param;
for (param = type_params; param && param->attribute; param = param->next) {
/* Ignore all but select parameters */
if (strcmp(param->attribute, "charset")) {
continue;
}
buf_putc(&buf, ';');
buf_appendcstr(&buf, param->attribute);
if (param->value) {
buf_putc(&buf, '=');
buf_appendcstr(&buf, param->value);
}
}
int retry;
for (retry = 0; retry < 3; retry++) {
if (retry) {
// second and third time around, sleep and reconnect
sleep(retry);
extractor_disconnect(ext);
r = extractor_connect(ext);
if (r) continue;
be = ext->be;
}
/* Send attachment to service for text extraction */
prot_printf(be->out,
"PUT %s/%s %s\r\n"
"Host: %.*s\r\n"
"User-Agent: Cyrus/%s\r\n"
"Connection: Keep-Alive\r\n"
"Keep-Alive: timeout=%u\r\n"
"Accept: text/plain\r\n"
"Content-Type: %s/%s%s\r\n"
"Content-Length: " SIZE_T_FMT "\r\n"
"X-Truncate-Length: " SIZE_T_FMT "\r\n"
"\r\n",
ext->path, guidstr, HTTP_VERSION,
(int) hostlen, be->hostname, CYRUS_VERSION, IDLE_TIMEOUT,
type, subtype, buf_cstring(&buf), buf_len(data),
config_search_maxsize);
prot_putbuf(be->out, data);
prot_flush(be->out);
/* Read PUT response */
body.flags = 0;
do {
r = http_read_response(be, METH_PUT,
&statuscode, &hdrs, &body, &errstr);
if (r) {
syslog(LOG_ERR,
"extract_attachment: failed to read response for PUT %s/%s",
ext->path, guidstr);
statuscode = 599;
}
} while (statuscode < 200);
syslog(LOG_DEBUG, "extract_attachment: PUT %s/%s: got status %u",
ext->path, guidstr, statuscode);
if (statuscode == 200 || statuscode == 201) {
// we got a result, yay
goto gotdata;
}
if (statuscode >= 400 && statuscode <= 499) {
/* indexer can't extract this for some reason, never try again */
goto done;
}
/* any other status code is an error */
syslog(LOG_ERR, "extract GOT STATUSCODE %d with timeout %d: %s", statuscode, IDLE_TIMEOUT, errstr);
}
// dropped out of the loop? Then we failed!
r = IMAP_IOERROR;
goto done;
gotdata:
/* Abide by server's timeout, if any */
if ((hdr = spool_getheader(hdrs, "Keep-Alive")) &&
(p = strstr(hdr[0], "timeout="))) {
int timeout = atoi(p+8);
if (be->timeout) be->timeout->mark = time(NULL) + timeout;
}
/* Append extracted text */
if (buf_len(&body.payload)) {
str->receiver->begin_part(str->receiver, SEARCH_PART_ATTACHMENTBODY);
str->receiver->append_text(str->receiver, &body.payload);
str->receiver->end_part(str->receiver, SEARCH_PART_ATTACHMENTBODY);
}
done:
spool_free_hdrcache(hdrs);
buf_free(&body.payload);
buf_free(&buf);
buf_free(&decbuf);
return r;
}
EXPORTED void index_text_extractor_init(struct protstream *clientin)
{
const char *exturl =
config_getstring(IMAPOPT_SEARCH_ATTACHMENT_EXTRACTOR_URL);
if (!exturl) return;
syslog(LOG_DEBUG, "extractor_init(%p)", clientin);
char scheme[6], server[100], path[256], *p;
unsigned https, port;
/* Parse URL (cheesy parser without having to use libxml2) */
int n = sscanf(exturl, "%5[^:]://%99[^/]%255[^\n]",
scheme, server, path);
if (n != 3 ||
strncmp(lcase(scheme), "http", 4) || (scheme[4] && scheme[4] != 's')) {
syslog(LOG_ERR,
"extract_attachment: unexpected non-HTTP URL %s", exturl);
return;
}
/* Normalize URL parts */
https = (scheme[4] == 's');
if (*(p = path + strlen(path) - 1) == '/') *p = '\0';
if ((p = strrchr(server, ':'))) {
*p++ = '\0';
port = atoi(p);
}
else port = https ? 443 : 80;
/* Build servername, port, and options */
struct buf buf = BUF_INITIALIZER;
buf_printf(&buf, "%s:%u%s/noauth", server, port, https ? "/tls" : "");
index_text_extractor = xzmalloc(sizeof(struct extractor_ctx));
index_text_extractor->clientin = clientin;
index_text_extractor->path = xstrdup(path);
index_text_extractor->hostname = buf_release(&buf);
}
EXPORTED void index_text_extractor_destroy(void)
{
struct extractor_ctx *ext = index_text_extractor;
syslog(LOG_DEBUG, "extractor_destroy(%p)", ext);
if (!ext) return;
extractor_disconnect(ext);
free(ext->be);
free(ext->hostname);
free(ext->path);
free(ext);
index_text_extractor = NULL;
}
static int getsearchtext_cb(int isbody, charset_t charset, int encoding,
const char *type, const char *subtype,
const struct param *type_params __attribute__((unused)),
const char *disposition,
const struct param *disposition_params,
const struct message_guid *content_guid,
const char *partid,
struct buf *data,
void *rock)
{
struct getsearchtext_rock *str = (struct getsearchtext_rock *)rock;
char *q;
struct buf text = BUF_INITIALIZER;
int r = 0;
if (isbody && partid && str->partids && strarray_find(str->partids, partid, 0) < 0) {
/* Skip part */
return 0;
}
if (str->receiver->begin_bodypart) {
str->receiver->begin_bodypart(str->receiver,
partid, content_guid, type, subtype);
}
if (!isbody) {
if (str->snippet_iteration >= 2) goto done;
if (!str->indexed_headers) {
/* Only index the headers of the top message */
q = charset_decode_mimeheader(buf_cstring(data), str->charset_flags);
buf_init_ro_cstr(&text, q);
stuff_part(str->receiver, SEARCH_PART_HEADERS, &text);
free(q);
buf_free(&text);
str->indexed_headers = 1;
}
/* Index attachment file names */
const struct param *param;
if (disposition && !strcmp(disposition, "ATTACHMENT")) {
/* Look for "Content-Disposition: attachment;filename=" header */
for (param = disposition_params; param; param = param->next) {
if (!strcmp(param->attribute, "FILENAME")) {
char *tmp = charset_decode_mimeheader(param->value, str->charset_flags);
buf_init_ro_cstr(&text, tmp);
stuff_part(str->receiver, SEARCH_PART_ATTACHMENTNAME, &text);
buf_free(&text);
free(tmp);
}
else if (!strcmp(param->attribute, "FILENAME*")) {
char *xval = charset_parse_mimexvalue(param->value, NULL);
if (!xval) xval = xstrdup(param->value);
if (xval) {
char *tmp = charset_decode_mimeheader(xval, str->charset_flags|CHARSET_MIME_UTF8);
buf_init_ro_cstr(&text, tmp);
stuff_part(str->receiver, SEARCH_PART_ATTACHMENTNAME, &text);
buf_free(&text);
free(tmp);
free(xval);
}
}
}
}
for(param = type_params; param; param = param->next) {
/* Look for "Content-Type: foo;name=" header */
if (strcmp(param->attribute, "NAME"))
continue;
char *tmp = charset_decode_mimeheader(param->value, str->charset_flags);
buf_init_ro_cstr(&text, tmp);
stuff_part(str->receiver, SEARCH_PART_ATTACHMENTNAME, &text);
buf_free(&text);
free(tmp);
}
}
else if (buf_len(data) > 50 && !memcmp(data->s, "-----BEGIN PGP MESSAGE-----", 27)) {
/* PGP encrypted body part - we don't want to index this,
* it's a ton of random base64 noise */
}
else if (isbody && !strcmp(type, "TEXT") && strcmpsafe(subtype, "RTF")) {
if (str->snippet_iteration >= 2) goto done;
if (!strcmp(subtype, "CALENDAR")) {
#ifdef USE_HTTPD
extract_icalbuf(data, charset, encoding, str);
#endif /* USE_HTTPD */
}
else if (!strcmp(subtype, "VCARD")) {
#ifdef USE_HTTPD
extract_vcardbuf(data, charset, encoding, str);
#endif /* USE_HTTPD */
}
else {
/* body-like */
int mycharset_flags = str->charset_flags;
const char *mysubtype = subtype;
if (!strcmpsafe(subtype, "PLAIN") && partid &&
strarray_find(&str->striphtml, partid, 0) >= 0) {
/* Strip any HTML tags from plain text before indexing */
mycharset_flags &= ~(CHARSET_SKIPHTML|CHARSET_KEEPHTML);
mysubtype = "HTML";
}
str->receiver->begin_part(str->receiver, SEARCH_PART_BODY);
charset_extract(extract_cb, str, data, charset, encoding, mysubtype,
mycharset_flags);
str->receiver->end_part(str->receiver, SEARCH_PART_BODY);
}
}
else if (isbody && (!strcmp(type, "APPLICATION") || !strcmp(type, "TEXT"))) {
#ifdef USE_HTTPD
// application/ics is an alias for text/icalendar
if (!strcmp(subtype, "ICS")) {
extract_icalbuf(data, charset, encoding, str);
goto done;
}
#endif /* USE_HTTPD */
// these are encrypted fields which aren't worth indexing
if (!strcmp(subtype, "PKCS7-MIME")) goto done;
if (!strcmp(subtype, "PKCS7-ENCRYPTED")) goto done;
if (!strcmp(subtype, "PKCS7-SIGNATURE")) goto done;
if (!strcmp(subtype, "PGP-SIGNATURE")) goto done;
if (!strcmp(subtype, "PGP-KEYS")) goto done;
if (!strcmp(subtype, "PGP-ENCRYPTED")) goto done;
/* Ignore attachments in first snippet generation pass */
if (str->snippet_iteration == 1) goto done;
/* Only generate snippets from named attachment parts */
if (str->snippet_iteration >= 2 && !str->partids) goto done;
if (!config_getstring(IMAPOPT_SEARCH_ATTACHMENT_EXTRACTOR_URL)) {
/* Message has attachment, but no extractor is configured */
str->indexlevel = 1;
goto done;
}
r = extract_attachment(type, subtype, type_params, data, encoding,
content_guid, str);
if (r) {
syslog(LOG_ERR, "IOERROR index: can't extract attachment %s (%s/%s): %s",
message_guid_encode(content_guid),
type, subtype, error_message(r));
if (str->flags & INDEX_GETSEARCHTEXT_PARTIALS) {
/* mark message as partially indexed and continue */
str->indexlevel |= SEARCH_INDEXLEVEL_PARTIAL;
r = 0;
}
}
}
done:
if (str->receiver->end_bodypart) {
str->receiver->end_bodypart(str->receiver);
}
return r;
}
static int find_striphtml_parts(message_t *msg, strarray_t *striphtml)
{
const struct body *root;
int r = message_get_cachebody(msg, &root);
if (r) return r;
ptrarray_t submsgs = PTRARRAY_INITIALIZER;
ptrarray_t work = PTRARRAY_INITIALIZER;
/* Add top-level message and find all rfc822 messages */
ptrarray_push(&submsgs, (void*)root);
ptrarray_push(&work, (void*) root);
const struct body *body;
while ((body = ptrarray_pop(&work))) {
if (!strcmpsafe(body->type, "MESSAGE") &&
!strcmpsafe(body->subtype, "RFC822")) {
ptrarray_push(&submsgs, (void*)body);
}
int i;
for (i = 0; i < body->numparts; i++) {
ptrarray_push(&work, body->subpart + i);
}
}
/* Process top-level and each embedded message separately */
while ((root = ptrarray_pop(&submsgs))) {
/* Check if submsg has any HTML part */
int has_htmlpart = 0;
int i;
for (i = 0; i < root->numparts; i++) {
ptrarray_push(&work, root->subpart + i);
}
while ((body = ptrarray_pop(&work))) {
if (!strcmpsafe(body->type, "TEXT") &&
!strcmpsafe(body->subtype, "HTML") &&
(!body->disposition || !strcmp(body->disposition, "INLINE"))) {
has_htmlpart = 1;
break;
}
else if (!strcmpsafe(body->type, "MESSAGE") &&
!strcmpsafe(body->subtype, "RFC822")) {
continue;
}
else if (body->numparts) {
for (i = 0; i < body->numparts; i++) {
ptrarray_push(&work, body->subpart + i);
}
}
}
if (!has_htmlpart) continue;
/* Keep track of plain text body part ids that
* coexist with HTML bodies in the same submsg */
for (i = 0; i < root->numparts; i++) {
ptrarray_push(&work, root->subpart + i);
}
while ((body = ptrarray_pop(&work))) {
if (!strcmpsafe(body->type, "TEXT") &&
!strcmpsafe(body->subtype, "PLAIN")) {
if (body->part_id) {
strarray_push(striphtml, body->part_id);
}
}
else if (!strcmpsafe(body->type, "MESSAGE") &&
!strcmpsafe(body->subtype, "RFC822")) {
continue;
}
else if (body->numparts) {
int i;
for (i = 0; i < body->numparts; i++) {
ptrarray_push(&work, body->subpart + i);
}
}
}
}
ptrarray_fini(&submsgs);
ptrarray_fini(&work);
return 0;
}
EXPORTED int index_getsearchtext(message_t *msg, const strarray_t *partids,
search_text_receiver_t *receiver,
int flags)
{
struct getsearchtext_rock str;
struct buf buf = BUF_INITIALIZER;
int format = MESSAGE_SEARCH;
strarray_t types = STRARRAY_INITIALIZER;
const char *type = NULL, *subtype = NULL;
int i;
int r;
/* Determine Content-Type */
r = message_get_type(msg, &type);
if (r) return r;
r = message_get_subtype(msg, &subtype);
if (r) return r;
/* Set up search receiver */
r = receiver->begin_message(receiver, msg);
if (r) return r;
memset(&str, 0, sizeof(struct getsearchtext_rock));
str.receiver = receiver;
str.indexed_headers = 0;
str.charset_flags = charset_flags;
str.partids = partids;
str.snippet_iteration = 0;
str.flags = flags;
str.indexlevel = SEARCH_INDEXLEVEL_ATTACH; // may get downgraded in callback
/* Search receiver can override text conversion */
if (receiver->index_charset_flags) {
str.charset_flags = receiver->index_charset_flags(str.charset_flags);
}
if (flags & INDEX_GETSEARCHTEXT_SNIPPET) {
str.charset_flags |= CHARSET_KEEPCASE;
format = MESSAGE_SNIPPET;
}
/* Search receiver can override message field conversion */
if (receiver->index_message_format) {
format = receiver->index_message_format(format,
flags & INDEX_GETSEARCHTEXT_SNIPPET);
}
/* Extract headers */
if (!message_get_field(msg, "From", format, &buf))
stuff_part(receiver, SEARCH_PART_FROM, &buf);
if (!message_get_field(msg, "To", format, &buf))
stuff_part(receiver, SEARCH_PART_TO, &buf);
if (!message_get_field(msg, "Cc", format, &buf))
stuff_part(receiver, SEARCH_PART_CC, &buf);
if (!message_get_field(msg, "Bcc", format, &buf))
stuff_part(receiver, SEARCH_PART_BCC, &buf);
if (!message_get_field(msg, "Subject", format, &buf))
stuff_part(receiver, SEARCH_PART_SUBJECT, &buf);
if (!message_get_field(msg, "List-Id", format, &buf))
stuff_part(receiver, SEARCH_PART_LISTID, &buf);
if (!message_get_field(msg, "Mailing-List", format, &buf))
stuff_part(receiver, SEARCH_PART_LISTID, &buf);
if (!message_get_field(msg, "Mailing-List", format, &buf))
stuff_part(receiver, SEARCH_PART_LISTID, &buf);
if (!message_get_deliveredto(msg, &buf))
stuff_part(receiver, SEARCH_PART_DELIVEREDTO, &buf);
if (!message_get_priority(msg, &buf))
stuff_part(receiver, SEARCH_PART_PRIORITY, &buf);
if (!message_get_leaf_types(msg, &types) && types.count) {
for (i = 0 ; i < types.count ; i+= 2) {
receiver->begin_part(receiver, SEARCH_PART_TYPE);
buf_setcstr(&buf, types.data[i]);
buf_putc(&buf, '/');
buf_appendcstr(&buf, types.data[i+1]);
receiver->append_text(receiver, &buf);
receiver->end_part(receiver, SEARCH_PART_TYPE);
}
}
/* Determine when to strip HTML from plain text */
find_striphtml_parts(msg, &str.striphtml);
/* Generate snippets in two passes. */
if (flags & INDEX_GETSEARCHTEXT_SNIPPET) {
str.snippet_iteration = 1; /* first pass */
}
/* Traverse bodies */
r = message_foreach_section(msg, getsearchtext_cb, &str);
if (!r && str.snippet_iteration) {
if (receiver->flush) {
r = receiver->flush(receiver);
}
if (!r) {
str.snippet_iteration = 2;
r = message_foreach_section(msg, getsearchtext_cb, &str);
}
if (r == IMAP_OK_COMPLETED) r = 0;
}
if (r) goto done;
/* Finalize message. */
r = receiver->end_message(receiver, str.indexlevel);
if (r == IMAP_OK_COMPLETED) r = 0;
/* Log erroneous or partially indexed message */
if (r || (str.indexlevel & SEARCH_INDEXLEVEL_PARTIAL)) {
struct mailbox *mailbox = msg_mailbox(msg);
uint32_t uid = 0;
message_get_uid(msg, &uid);
const char *mboxname = mailbox ? mailbox_name(mailbox) : "";
if (r) {
xsyslog(LOG_ERR, "IOERROR: failed to index msg",
"mailbox=<%s> uid=<%d> r=<%s>",
mboxname, uid, error_message(r));
}
else {
xsyslog(LOG_ERR, "IOERROR: partially indexed msg",
"mailbox=<%s> uid=<%d>", mboxname, uid);
}
}
done:
buf_free(&buf);
strarray_fini(&types);
strarray_fini(&str.striphtml);
return r;
}
/*
* Helper function to set up arguments to append_copy()
*/
#define COPYARGSGROW 30
static int index_copysetup(struct index_state *state, uint32_t msgno,
struct copyargs *copyargs)
{
struct index_map *im = &state->map[msgno-1];
int r;
if (copyargs->nummsg == copyargs->msgalloc) {
copyargs->msgalloc += COPYARGSGROW;
copyargs->records = (struct index_record *)
xrealloc((char *)copyargs->records,
copyargs->msgalloc * sizeof(struct index_record));
}
r = index_reload_record(state, msgno, ©args->records[copyargs->nummsg]);
if (r) return r;
/* seen is per user - embed it in the record */
if (im->isseen)
copyargs->records[copyargs->nummsg].system_flags |= FLAG_SEEN;
else
copyargs->records[copyargs->nummsg].system_flags &= ~FLAG_SEEN;
if (state->want_expunged && (im->internal_flags & FLAG_INTERNAL_EXPUNGED)) {
copyargs->records[copyargs->nummsg].system_flags &= ~FLAG_DELETED;
copyargs->records[copyargs->nummsg].internal_flags &= ~FLAG_INTERNAL_EXPUNGED;
}
copyargs->nummsg++;
return 0;
}
/*
* Creates a list, and optionally also an array of pointers to, of msgdata.
*
* We fill these structs with the processed info that will be needed
* by the specified sort criteria.
*/
MsgData **index_msgdata_load(struct index_state *state,
unsigned *msgno_list, int n,
const struct sortcrit *sortcrit,
unsigned int anchor, int *found_anchor)
{
MsgData **ptrs, *md, *cur;
int i, j;
char *tmpenv;
char *envtokens[NUMENVTOKENS];
int did_cache, did_env, did_conv;
int label;
struct mailbox *mailbox = state->mailbox;
struct index_record record;
struct conversations_state *cstate = NULL;
conversation_t conv = CONVERSATION_INIT;
int *preload = NULL;
if (!n) return NULL;
/* create an array of MsgData */
ptrs = (MsgData **) xzmalloc(n * sizeof(MsgData *) + n * sizeof(MsgData));
md = (MsgData *)(ptrs + n);
xstats_add(MSGDATA_LOAD, n);
if (found_anchor)
*found_anchor = 0;
/* set mailbox level states */
for (j = 0; sortcrit[j].key; j++); // count how many we need
if (j) preload = xzmalloc(j * sizeof(int));
for (j = 0; sortcrit[j].key; j++) {
label = sortcrit[j].key;
switch(label) {
case SORT_SAVEDATE:
#ifdef WITH_JMAP
case SORT_SNOOZEDUNTIL:
#endif
preload[j] = !strcmpnull(mailbox_uniqueid(mailbox), sortcrit[j].args.mailbox.id);
break;
case SORT_HASCONVFLAG:
preload[j] = -1;
if (!cstate) cstate = conversations_get_mbox(index_mboxname(state));
assert(cstate);
if (cstate->counted_flags)
preload[j] = strarray_find_case(cstate->counted_flags, sortcrit[j].args.flag.name, 0);
break;
default:
break;
}
}
for (i = 0 ; i < n ; i++) {
cur = &md[i];
ptrs[i] = cur;
/* set msgno */
cur->msgno = (msgno_list ? msgno_list[i] : (unsigned)(i+1));
if (index_reload_record(state, cur->msgno, &record))
continue;
cur->uid = record.uid;
cur->cid = record.cid;
cur->system_flags = record.system_flags;
cur->internal_flags = record.internal_flags;
message_guid_copy(&cur->guid, &record.guid);
if (found_anchor && record.uid == anchor)
*found_anchor = 1;
/* useful for convupdates */
cur->modseq = record.modseq;
did_cache = did_env = did_conv = 0;
tmpenv = NULL;
for (j = 0; sortcrit[j].key; j++) {
label = sortcrit[j].key;
if ((label == SORT_CC ||
label == SORT_FROM || label == SORT_SUBJECT ||
label == SORT_TO || label == LOAD_IDS ||
label == SORT_DISPLAYFROM || label == SORT_DISPLAYTO ||
label == SORT_SPAMSCORE) &&
!did_cache) {
/* fetch cached info */
if (mailbox_cacherecord(mailbox, &record))
continue; /* can't do this with a broken cache */
did_cache++;
}
if ((label == LOAD_IDS) && !did_env) {
/* no point if we don't have enough data */
if (cacheitem_size(&record, CACHE_ENVELOPE) <= 2)
continue;
/* make a working copy of envelope -- strip outer ()'s */
/* +1 -> skip the leading paren */
/* -2 -> don't include the size of the outer parens */
tmpenv = xstrndup(cacheitem_base(&record, CACHE_ENVELOPE) + 1,
cacheitem_size(&record, CACHE_ENVELOPE) - 2);
/* parse envelope into tokens */
parse_cached_envelope(tmpenv, envtokens,
VECTOR_SIZE(envtokens));
did_env++;
}
if ((label == SORT_HASCONVFLAG || label == SORT_CONVMODSEQ ||
label == SORT_CONVEXISTS || label == SORT_CONVSIZE) && !did_conv) {
if (!cstate) cstate = conversations_get_mbox(index_mboxname(state));
assert(cstate);
if (conversation_load_advanced(cstate, record.cid, &conv, /*flags*/0))
continue;
// useful to have for mutable sorts
cur->convmodseq = conv.modseq;
did_conv++;
}
switch (label) {
case SORT_CC:
cur->cc = get_localpart_addr(cacheitem_base(&record, CACHE_CC));
break;
case SORT_DATE:
cur->sentdate = record.gmtime;
/* fall through */
case SORT_ARRIVAL:
cur->internaldate = record.internaldate;
break;
case SORT_FROM:
cur->from = get_localpart_addr(cacheitem_base(&record, CACHE_FROM));
break;
case SORT_MODSEQ:
/* already copied above */
break;
case SORT_CREATEDMODSEQ:
cur->createdmodseq = record.createdmodseq;
break;
case SORT_SIZE:
cur->size = record.size;
break;
case SORT_SUBJECT:
cur->xsubj = index_extract_subject(cacheitem_base(&record, CACHE_SUBJECT),
cacheitem_size(&record, CACHE_SUBJECT),
&cur->is_refwd);
cur->xsubj_hash = strhash(cur->xsubj);
break;
case SORT_TO:
cur->to = get_localpart_addr(cacheitem_base(&record, CACHE_TO));
break;
case SORT_ANNOTATION: {
struct buf value = BUF_INITIALIZER;
annotatemore_msg_lookup(state->mailbox,
record.uid,
sortcrit[j].args.annot.entry,
sortcrit[j].args.annot.userid,
&value);
/* buf_release() never returns NULL, so if the lookup
* fails for any reason we just get an empty string here */
strarray_appendm(&cur->annot, buf_release(&value));
break;
}
case SORT_SAVEDATE:
if (preload[j]) {
cur->savedate = record.savedate;
}
else {
/* If not in mailboxId, we use receivedAt */
cur->internaldate = record.internaldate;
}
break;
case SORT_SNOOZEDUNTIL:
#ifdef WITH_JMAP
if (preload[j] && (record.internal_flags & FLAG_INTERNAL_SNOOZED)) {
/* SAVEDATE == snoozed#until */
cur->savedate = record.savedate;
if (!cur->savedate) {
/* Try fetching snoozed#until directly */
json_t *snoozed =
jmap_fetch_snoozed(mailbox_name(mailbox), record.uid);
if (snoozed) {
time_from_iso8601(
json_string_value(json_object_get(snoozed,
"until")),
&cur->savedate);
json_decref(snoozed);
}
}
}
#endif
if (!cur->savedate) {
/* If not snoozed in mailboxId, we use receivedAt */
cur->internaldate = record.internaldate;
}
break;
case LOAD_IDS:
index_get_ids(cur, envtokens, cacheitem_base(&record, CACHE_HEADERS),
cacheitem_size(&record, CACHE_HEADERS));
break;
case SORT_DISPLAYFROM:
cur->displayfrom = get_displayname(
cacheitem_base(&record, CACHE_FROM));
break;
case SORT_DISPLAYTO:
cur->displayto = get_displayname(
cacheitem_base(&record, CACHE_TO));
break;
case SORT_SPAMSCORE: {
const char *score = index_getheader(state, cur->msgno, "X-Spam-score");
/* multiply by 100 to give an integer score */
cur->spamscore = (int)((atof(score) * 100) + 0.5);
break;
}
case SORT_HASFLAG: {
const char *name = sortcrit[j].args.flag.name;
if (mailbox_record_hasflag(mailbox, &record, name))
cur->hasflag |= (1<<j);
break;
}
case SORT_HASCONVFLAG: {
int idx = preload[j];
/* flag exists in the conversation at all */
if (idx >= 0 && conv.counts[idx] > 0 && j < 31)
cur->hasflag |= (1<<j);
break;
}
case SORT_CONVEXISTS:
cur->convexists = conv.exists;
break;
case SORT_CONVSIZE:
cur->convsize = conv.size;
break;
case SORT_CONVMODSEQ:
cur->convmodseq = conv.modseq;
break;
case SORT_RELEVANCY:
/* for now all messages have relevancy=100 */
break;
}
}
free(tmpenv);
conversation_fini(&conv);
}
free(preload);
return ptrs;
}
static char *get_localpart_addr(const char *header)
{
struct address *addr = NULL;
char *ret = NULL;
parseaddr_list(header, &addr);
if (!addr) return NULL;
if (addr->mailbox)
ret = xstrdup(addr->mailbox);
parseaddr_free(addr);
return ret;
}
/*
* Get the 'display-name' of an address from a header
*/
static char *get_displayname(const char *header)
{
struct address *addr = NULL;
char *ret = NULL;
char *p;
parseaddr_list(header, &addr);
if (!addr) return NULL;
if (addr->name && addr->name[0]) {
/* pure RFC 5255 compatible "searchform" conversion */
ret = charset_utf8_to_searchform(addr->name, /*flags*/0);
}
else if (addr->domain && addr->mailbox) {
ret = strconcat(addr->mailbox, "@", addr->domain, (char *)NULL);
/* gotta uppercase mailbox/domain */
for (p = ret; *p; p++)
*p = toupper(*p);
}
else if (addr->mailbox) {
ret = xstrdup(addr->mailbox);
/* gotta uppercase mailbox/domain */
for (p = ret; *p; p++)
*p = toupper(*p);
}
parseaddr_free(addr);
return ret;
}
/*
* Extract base subject from subject header
*
* This is a wrapper around _index_extract_subject() which preps the
* subj NSTRING and checks for Netscape "[Fwd: ]".
*/
static char *index_extract_subject(const char *subj, size_t len, int *is_refwd)
{
char *rawbuf, *buf, *s, *base;
/* parse the subj NSTRING and make a working copy */
if (!strcmp(subj, "NIL")) { /* NIL? */
return xstrdup(""); /* yes, return empty */
} else if (*subj == '"') { /* quoted? */
rawbuf = xstrndup(subj + 1, len - 2); /* yes, strip quotes */
} else {
s = strchr(subj, '}') + 3; /* literal, skip { }\r\n */
rawbuf = xstrndup(s, len - (s - subj));
}
buf = charset_parse_mimeheader(rawbuf, charset_flags);
free(rawbuf);
for (s = buf;;) {
base = _index_extract_subject(s, is_refwd);
/* If we have a Netscape "[Fwd: ...]", extract the contents */
if (!strncasecmp(base, "[fwd:", 5) &&
base[strlen(base) - 1] == ']') {
/* inc refwd counter */
*is_refwd += 1;
/* trim "]" */
base[strlen(base) - 1] = '\0';
/* trim "[fwd:" */
s = base + 5;
}
else /* otherwise, we're done */
break;
}
base = xstrdup(base);
free(buf);
for (s = base; *s; s++) {
*s = toupper(*s);
}
return base;
}
/*
* Guts of subject extraction.
*
* Takes a subject string and returns a pointer to the base.
*/
static char *_index_extract_subject(char *s, int *is_refwd)
{
char *base, *x;
/* trim trailer
*
* start at the end of the string and work towards the front,
* resetting the end of the string as we go.
*/
for (x = s + strlen(s) - 1; x >= s;) {
if (Uisspace(*x)) { /* whitespace? */
*x = '\0'; /* yes, trim it */
x--; /* skip past it */
}
else if (x - s >= 4 &&
!strncasecmp(x-4, "(fwd)", 5)) { /* "(fwd)"? */
*(x-4) = '\0'; /* yes, trim it */
x -= 5; /* skip past it */
*is_refwd += 1; /* inc refwd counter */
}
else
break; /* we're done */
}
/* trim leader
*
* start at the head of the string and work towards the end,
* skipping over stuff we don't care about.
*/
for (base = s; base;) {
if (Uisspace(*base)) base++; /* whitespace? */
/* possible refwd */
else if ((!strncasecmp(base, "re", 2) && /* "re"? */
(x = base + 2)) || /* yes, skip past it */
(!strncasecmp(base, "fwd", 3) && /* "fwd"? */
(x = base + 3)) || /* yes, skip past it */
(!strncasecmp(base, "fw", 2) && /* "fw"? */
(x = base + 2))) { /* yes, skip past it */
int count = 0; /* init counter */
while (Uisspace(*x)) x++; /* skip whitespace */
if (*x == '[') { /* start of blob? */
for (x++; x;) { /* yes, get count */
if (!*x) { /* end of subj, quit */
x = NULL;
break;
}
else if (*x == ']') { /* end of blob, done */
break;
/* if we have a digit, and we're still
counting, keep building the count */
} else if (cyrus_isdigit((int) *x) && count != -1) {
count = count * 10 + *x - '0';
if (count < 0) { /* overflow */
count = -1; /* abort counting */
}
} else { /* no digit, */
count = -1; /* abort counting */
}
x++;
}
if (x) /* end of blob? */
x++; /* yes, skip past it */
else
break; /* no, we're done */
}
while (Uisspace(*x)) x++; /* skip whitespace */
if (*x == ':') { /* ending colon? */
base = x + 1; /* yes, skip past it */
*is_refwd += (count > 0 ? count : 1); /* inc refwd counter
by count or 1 */
}
else
break; /* no, we're done */
}
#if 0 /* do nested blobs - wait for decision on this */
else if (*base == '[') { /* start of blob? */
int count = 1; /* yes, */
x = base + 1; /* find end of blob */
while (count) { /* find matching ']' */
if (!*x) { /* end of subj, quit */
x = NULL;
break;
}
else if (*x == '[') /* new open */
count++; /* inc counter */
else if (*x == ']') /* close */
count--; /* dec counter */
x++;
}
if (!x) /* blob didn't close */
break; /* so quit */
else if (*x) /* end of subj? */
base = x; /* no, skip blob */
#else
else if (*base == '[' && /* start of blob? */
(x = strpbrk(base+1, "[]")) && /* yes, end of blob */
*x == ']') { /* (w/o nesting)? */
if (*(x+1)) /* yes, end of subj? */
base = x + 1; /* no, skip blob */
#endif
else
break; /* yes, return blob */
}
else
break; /* we're done */
}
return base;
}
/* Get message-id, and references/in-reply-to */
void index_get_ids(MsgData *msgdata, char *envtokens[], const char *headers,
unsigned size)
{
static struct buf buf;
strarray_t refhdr = STRARRAY_INITIALIZER;
char *refstr, *ref, *in_reply_to;
buf_reset(&buf);
/* get msgid */
msgdata->msgid = find_msgid(envtokens[ENV_MSGID], NULL);
/* if we don't have one, create one */
if (!msgdata->msgid) {
buf_printf(&buf, "<Empty-ID: %u>", msgdata->msgno);
msgdata->msgid = xstrdup(buf.s);
buf_reset(&buf);
}
/* Copy headers to the buffer */
buf_appendmap(&buf, headers, size);
buf_cstring(&buf);
/* grab the References header */
strarray_append(&refhdr, "references");
message_pruneheader(buf.s, &refhdr, 0);
strarray_fini(&refhdr);
if (buf.s) {
/* allocate some space for refs */
/* find references */
refstr = buf.s;
massage_header(refstr);
while ((ref = find_msgid(refstr, &refstr)) != NULL)
strarray_appendm(&msgdata->ref, ref);
}
/* if we have no references, try in-reply-to */
if (!msgdata->ref.count) {
/* get in-reply-to id */
in_reply_to = find_msgid(envtokens[ENV_INREPLYTO], NULL);
/* if we have an in-reply-to id, make it the ref */
if (in_reply_to)
strarray_appendm(&msgdata->ref, in_reply_to);
}
}
/*
* Function for comparing two integers.
*/
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int numcmp(modseq_t n1, modseq_t n2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int numcmp(modseq_t n1, modseq_t n2)
{
if (n1 < n2) return -1;
if (n1 > n2) return 1;
return 0;
}
/*
* Comparison function for sorting message lists.
*/
static int index_sort_compare(MsgData *md1, MsgData *md2,
const struct sortcrit *sortcrit)
{
int reverse, ret = 0, i = 0, ann = 0;
do {
/* determine sort order from reverse flag bit */
reverse = sortcrit[i].flags & SORT_REVERSE;
switch (sortcrit[i].key) {
case SORT_SEQUENCE:
ret = numcmp(md1->msgno, md2->msgno);
break;
case SORT_ARRIVAL:
ret = numcmp(md1->internaldate, md2->internaldate);
break;
case SORT_CC:
ret = strcmpsafe(md1->cc, md2->cc);
break;
case SORT_DATE: {
time_t d1 = md1->sentdate ? md1->sentdate : md1->internaldate;
time_t d2 = md2->sentdate ? md2->sentdate : md2->internaldate;
ret = numcmp(d1, d2);
break;
}
case SORT_SNOOZEDUNTIL:
case SORT_SAVEDATE: {
time_t d1 = md1->savedate ? md1->savedate : md1->internaldate;
time_t d2 = md2->savedate ? md2->savedate : md2->internaldate;
ret = numcmp(d1, d2);
break;
}
case SORT_FROM:
ret = strcmpsafe(md1->from, md2->from);
break;
case SORT_SIZE:
ret = numcmp(md1->size, md2->size);
break;
case SORT_SUBJECT:
ret = strcmpsafe(md1->xsubj, md2->xsubj);
break;
case SORT_TO:
ret = strcmpsafe(md1->to, md2->to);
break;
case SORT_ANNOTATION:
ret = strcmpsafe(md1->annot.data[ann], md2->annot.data[ann]);
ann++;
break;
case SORT_MODSEQ:
ret = numcmp(md1->modseq, md2->modseq);
break;
case SORT_CREATEDMODSEQ:
ret = numcmp(md1->createdmodseq, md2->createdmodseq);
break;
case SORT_DISPLAYFROM:
ret = strcmpsafe(md1->displayfrom, md2->displayfrom);
break;
case SORT_DISPLAYTO:
ret = strcmpsafe(md1->displayto, md2->displayto);
break;
case SORT_UID:
ret = numcmp(md1->uid, md2->uid);
break;
case SORT_CONVMODSEQ:
ret = numcmp(md1->convmodseq, md2->convmodseq);
break;
case SORT_CONVEXISTS:
ret = numcmp(md1->convexists, md2->convexists);
break;
case SORT_CONVSIZE:
ret = numcmp(md1->convsize, md2->convsize);
break;
case SORT_SPAMSCORE:
ret = numcmp(md1->spamscore, md2->spamscore);
break;
case SORT_HASFLAG:
case SORT_HASCONVFLAG:
if (i < 31)
ret = numcmp(md1->hasflag & (1<<i),
md2->hasflag & (1<<i));
break;
case SORT_FOLDER:
if (md1->folder && md2->folder)
ret = strcmpsafe(md1->folder->mboxname, md2->folder->mboxname);
break;
case SORT_RELEVANCY:
ret = 0; /* for now all messages have relevancy=100 */
break;
case SORT_GUID:
ret = message_guid_cmp(&md1->guid, &md2->guid);
break;
}
} while (!ret && sortcrit[i++].key != SORT_SEQUENCE);
// must be multi-folder with the same UID! tiebreaker is GUID
if (!ret) return message_guid_cmp(&md1->guid, &md2->guid);
return (reverse ? -ret : ret);
}
static int sortcrit_is_uid(const struct sortcrit *sortcrit)
{
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int sortcrit_is_reverse_uid(const struct sortcrit *sortcrit)
{
if (!(sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int sortcrit_is_modseq(const struct sortcrit *sortcrit)
{
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_MODSEQ)) return 0;
sortcrit++;
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int sortcrit_is_arrival(const struct sortcrit *sortcrit)
{
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_ARRIVAL)) return 0;
sortcrit++;
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int sortcrit_is_reverse_arrival(const struct sortcrit *sortcrit)
{
if (!(sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_ARRIVAL)) return 0;
sortcrit++;
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int sortcrit_is_reverse_flagged(const struct sortcrit *sortcrit)
{
if (!(sortcrit->flags & SORT_REVERSE)) return 0;
// both HASFLAG and HASCONVFLAG have the same representation internally
if (!(sortcrit->key == SORT_HASFLAG ||
sortcrit->key == SORT_HASCONVFLAG)) return 0;
sortcrit++;
if (!(sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_ARRIVAL)) return 0;
sortcrit++;
if ((sortcrit->flags & SORT_REVERSE)) return 0;
if (!(sortcrit->key == SORT_SEQUENCE)) return 0;
return 1;
}
static int index_sort_compare_generic_qsort(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
return index_sort_compare(md1, md2, the_sortcrit);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_uid(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_uid(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md1->uid - md2->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_reverse_uid(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_reverse_uid(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md2->uid - md1->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_modseq(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_modseq(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md1->modseq - md2->modseq;
if (ret) return ret;
ret = md1->uid - md2->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_arrival(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_arrival(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md1->internaldate - md2->internaldate;
if (ret) return ret;
ret = md1->createdmodseq - md2->createdmodseq;
if (ret) return ret;
ret = md1->uid - md2->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_reverse_arrival(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_reverse_arrival(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md2->internaldate - md1->internaldate;
if (ret) return ret;
ret = md2->createdmodseq - md1->createdmodseq;
if (ret) return ret;
ret = md1->uid - md2->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
#ifdef HAVE_DECLARE_OPTIMIZE
static inline int index_sort_compare_reverse_flagged(const void *v1, const void *v2)
__attribute__((pure, always_inline, optimize("-O3")));
#endif
static int index_sort_compare_reverse_flagged(const void *v1, const void *v2)
{
MsgData *md1 = *(MsgData **)v1;
MsgData *md2 = *(MsgData **)v2;
int ret;
ret = md2->hasflag - md1->hasflag;
if (ret) return ret;
ret = md2->internaldate - md1->internaldate;
if (ret) return ret;
ret = md2->createdmodseq - md1->createdmodseq;
if (ret) return ret;
ret = md1->uid - md2->uid;
if (ret) return ret;
return message_guid_cmp(&md1->guid, &md2->guid);
}
void index_msgdata_sort(MsgData **msgdata, int n, const struct sortcrit *sortcrit)
{
if (sortcrit_is_uid(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_uid);
}
else if (sortcrit_is_reverse_uid(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_reverse_uid);
}
else if (sortcrit_is_modseq(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_modseq);
}
else if (sortcrit_is_arrival(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_arrival);
}
else if (sortcrit_is_reverse_arrival(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_reverse_arrival);
}
else if (sortcrit_is_reverse_flagged(sortcrit)) {
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_reverse_flagged);
}
else {
char *tmp = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "GENERICSORT: %s", tmp);
free(tmp);
the_sortcrit = (struct sortcrit *)sortcrit;
qsort(msgdata, n, sizeof(MsgData *), index_sort_compare_generic_qsort);
}
}
/*
* Free an array of MsgData* as built by index_msgdata_load()
*/
void index_msgdata_free(MsgData **msgdata, unsigned int n)
{
unsigned int i;
if (!msgdata)
return;
for (i = 0 ; i < n ; i++) {
MsgData *md = msgdata[i];
if (!md) continue;
free(md->cc);
free(md->from);
free(md->to);
free(md->displayfrom);
free(md->displayto);
free(md->xsubj);
free(md->msgid);
free(md->listid);
free(md->contenttype);
strarray_fini(&md->ref);
strarray_fini(&md->annot);
}
free(msgdata);
}
/*
* Getnext function for sorting thread lists.
*/
static void *index_thread_getnext(Thread *thread)
{
return thread->next;
}
/*
* Setnext function for sorting thread lists.
*/
static void index_thread_setnext(Thread *thread, Thread *next)
{
thread->next = next;
}
/*
* Comparison function for sorting threads.
*/
static int index_thread_compare(Thread *t1, Thread *t2,
const struct sortcrit *call_data)
{
MsgData *md1, *md2;
/* if the container is empty, use the first child's container */
md1 = t1->msgdata ? t1->msgdata : t1->child->msgdata;
md2 = t2->msgdata ? t2->msgdata : t2->child->msgdata;
return index_sort_compare(md1, md2, call_data);
}
/*
* Sort a list of threads.
*/
static void index_thread_sort(Thread *root,
const struct sortcrit *sortcrit)
{
Thread *child;
/* sort the grandchildren */
child = root->child;
while (child) {
/* if the child has children, sort them */
if (child->child)
index_thread_sort(child, sortcrit);
child = child->next;
}
/* sort the children */
root->child = lsort(root->child,
(void * (*)(void*)) index_thread_getnext,
(void (*)(void*,void*)) index_thread_setnext,
(int (*)(void*,void*,void*)) index_thread_compare,
(void *)sortcrit);
}
/*
* Thread a list of messages using the ORDEREDSUBJECT algorithm.
*/
static void index_thread_orderedsubj(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid)
{
MsgData **msgdata;
unsigned int mi;
static const struct sortcrit sortcrit[] =
{{ SORT_SUBJECT, 0, {{NULL, NULL}} },
{ SORT_DATE, 0, {{NULL, NULL}} },
{ SORT_SEQUENCE, 0, {{NULL, NULL}} }};
unsigned psubj_hash = 0;
char *psubj;
Thread *head, *newnode, *cur, *parent, *last;
/* Create/load the msgdata array */
msgdata = index_msgdata_load(state, msgno_list, nmsg, sortcrit, 0, NULL);
/* Sort messages by subject and date */
index_msgdata_sort(msgdata, nmsg, sortcrit);
/* create an array of Thread to use as nodes of thread tree
*
* we will be building threads under a dummy head,
* so we need (nmsg + 1) nodes
*/
head = (Thread *) xzmalloc((nmsg + 1) * sizeof(Thread));
newnode = head + 1; /* set next newnode to the second
one in the array (skip the head) */
parent = head; /* parent is the head node */
psubj = NULL; /* no previous subject */
cur = NULL; /* no current thread */
last = NULL; /* no last child */
for (mi = 0 ; mi < nmsg ; mi++) {
MsgData *msg = msgdata[mi];
newnode->msgdata = msg;
/* if no previous subj, or
current subj = prev subj (subjs have same hash, and
the strings are equal), then add message to current thread */
if (!psubj ||
(msg->xsubj_hash == psubj_hash &&
!strcmp(msg->xsubj, psubj))) {
/* if no children, create first child */
if (!parent->child) {
last = parent->child = newnode;
if (!cur) /* first thread */
parent = cur = parent->child;
}
/* otherwise, add to siblings */
else {
last->next = newnode;
last = last->next;
}
}
/* otherwise, create a new thread */
else {
cur->next = newnode; /* create and start a new thread */
parent = cur = cur->next; /* now work with the new thread */
}
psubj_hash = msg->xsubj_hash;
psubj = msg->xsubj;
newnode++;
}
/* Sort threads by date */
index_thread_sort(head, sortcrit+1);
/* Output the threaded messages */
index_thread_print(state, head, usinguid);
/* free the thread array */
free(head);
/* free the msgdata array */
index_msgdata_free(msgdata, nmsg);
}
/*
* Guts of thread printing. Recurses over children when necessary.
*
* Frees contents of msgdata as a side effect.
*/
static void _index_thread_print(struct index_state *state,
Thread *thread, int usinguid)
{
Thread *child;
/* for each thread... */
while (thread) {
/* start the thread */
prot_printf(state->out, "(");
/* if we have a message, print its identifier
* (do nothing for empty containers)
*/
if (thread->msgdata && thread->msgdata->uid) {
prot_printf(state->out, "%u",
usinguid ? thread->msgdata->uid :
thread->msgdata->msgno);
/* if we have a child, print the parent-child separator */
if (thread->child) prot_printf(state->out, " ");
}
/* for each child, grandchild, etc... */
child = thread->child;
while (child) {
/* if the child has siblings, print new branch and break */
if (child->next) {
_index_thread_print(state, child, usinguid);
break;
}
/* otherwise print the only child */
else {
prot_printf(state->out, "%u",
usinguid ? child->msgdata->uid :
child->msgdata->msgno);
/* if we have a child, print the parent-child separator */
if (child->child) prot_printf(state->out, " ");
child = child->child;
}
}
/* end the thread */
prot_printf(state->out, ")");
thread = thread->next;
}
}
/*
* Print a list of threads.
*
* This is a wrapper around _index_thread_print() which simply prints the
* start and end of the untagged thread response.
*/
static void index_thread_print(struct index_state *state,
Thread *thread, int usinguid)
{
prot_printf(state->out, "* THREAD");
if (thread) {
prot_printf(state->out, " ");
_index_thread_print(state, thread->child, usinguid);
}
}
/*
* Find threading algorithm for given arg.
* Returns index into thread_algs[], or -1 if not found.
*/
EXPORTED int find_thread_algorithm(char *arg)
{
int alg;
ucase(arg);
for (alg = 0; thread_algs[alg].alg_name; alg++) {
if (!strcmp(arg, thread_algs[alg].alg_name))
return alg;
}
return -1;
}
/*
* The following code is an interpretation of JWZ's description
* and pseudo-code in http://www.jwz.org/doc/threading.html.
*
* It has been modified to match the THREAD=REFERENCES algorithm.
*/
/*
* Determines if child is a descendent of parent.
*
* Returns 1 if yes, 0 otherwise.
*/
static int thread_is_descendent(Thread *parent, Thread *child)
{
Thread *kid;
/* self */
if (parent == child)
return 1;
/* search each child's descendents */
for (kid = parent->child; kid; kid = kid->next) {
if (thread_is_descendent(kid, child))
return 1;
}
return 0;
}
/*
* Links child into parent's children.
*/
static void thread_adopt_child(Thread *parent, Thread *child)
{
child->parent = parent;
child->next = parent->child;
parent->child = child;
}
/*
* Unlinks child from it's parent's children.
*/
static void thread_orphan_child(Thread *child)
{
Thread *prev, *cur;
/* sanity check -- make sure child is actually a child of parent */
for (prev = NULL, cur = child->parent->child;
cur != child && cur != NULL; prev = cur, cur = cur->next);
if (!cur) {
/* uh oh! couldn't find the child in it's parent's children
* we should probably return NO to thread command
*/
return;
}
/* unlink child */
if (!prev) /* first child */
child->parent->child = child->next;
else
prev->next = child->next;
child->parent = child->next = NULL;
}
/*
* Link messages together using message-id and references.
*/
static void ref_link_messages(MsgData **msgdata, unsigned int nmsg,
Thread **newnode, struct hash_table *id_table)
{
Thread *cur, *parent, *ref;
unsigned int mi;
int dup_count = 0;
char buf[100];
int i;
/* for each message... */
for (mi = 0 ; mi < nmsg ; mi++) {
MsgData *msg = msgdata[mi];
/* fill the containers with msgdata
*
* if we already have a container, use it
*/
if ((cur = (Thread *) hash_lookup(msg->msgid, id_table))) {
/* If this container is not empty, then we have a duplicate
* Message-ID. Make this one unique so that we don't stomp
* on the old one.
*/
if (cur->msgdata) {
snprintf(buf, sizeof(buf), "-dup%d", dup_count++);
msg->msgid =
(char *) xrealloc(msg->msgid,
strlen(msg->msgid) + strlen(buf) + 1);
strcat(msg->msgid, buf);
/* clear cur so that we create a new container */
cur = NULL;
}
else
cur->msgdata = msg;
}
/* otherwise, make and index a new container */
if (!cur) {
cur = *newnode;
cur->msgdata = msg;
hash_insert(msg->msgid, cur, id_table);
(*newnode)++;
}
/* Step 1.A */
for (i = 0, parent = NULL; i < msg->ref.count; i++) {
/* if we don't already have a container for the reference,
* make and index a new (empty) container
*/
if (!(ref = (Thread *) hash_lookup(msg->ref.data[i], id_table))) {
ref = *newnode;
hash_insert(msg->ref.data[i], ref, id_table);
(*newnode)++;
}
/* link the references together as parent-child iff:
* - we won't change existing links, AND
* - we won't create a loop
*/
if (!ref->parent &&
parent && !thread_is_descendent(ref, parent)) {
thread_adopt_child(parent, ref);
}
parent = ref;
}
/* Step 1.B
*
* if we have a parent already, it is probably bogus (the result
* of a truncated references field), so unlink from it because
* we now have the actual parent
*/
if (cur->parent) thread_orphan_child(cur);
/* make the last reference the parent of our message iff:
* - we won't create a loop
*/
if (parent && !thread_is_descendent(cur, parent))
thread_adopt_child(parent, cur);
}
}
/*
* Gather orphan messages under the root node.
*/
static void ref_gather_orphans(const char *key __attribute__((unused)),
void *data, void *rock)
{
Thread *node = (Thread *)data;
struct rootset *rootset = (struct rootset *)rock;
/* we only care about nodes without parents */
if (!node->parent) {
if (node->next) {
/* uh oh! a node without a parent should not have a sibling
* we should probably return NO to thread command
*/
return;
}
/* add this node to root's children */
node->next = rootset->root->child;
rootset->root->child = node;
rootset->nroot++;
}
}
/*
* Prune tree of empty containers.
*/
static void ref_prune_tree(Thread *parent)
{
Thread *cur, *prev, *next, *child;
for (prev = NULL, cur = parent->child, next = cur->next;
cur;
prev = cur, cur = next, next = (cur ? cur->next : NULL)) {
retry:
/* if we have an empty container with no children, delete it */
if (!cur->msgdata && !cur->child) {
if (!prev) /* first child */
parent->child = cur->next;
else
prev->next = cur->next;
/* we just removed cur from our list,
* so we need to keep the same prev for the next pass
*/
cur = prev;
}
/* if we have an empty container with children, AND
* we're not at the root OR we only have one child,
* then remove the container but promote its children to this level
* (splice them into the current child list)
*/
else if (!cur->msgdata && cur->child &&
(cur->parent || !cur->child->next)) {
/* move cur's children into cur's place (start the splice) */
if (!prev) /* first child */
parent->child = cur->child;
else
prev->next = cur->child;
/* make cur's parent the new parent of cur's children
* (they're moving in with grandma!)
*/
child = cur->child;
do {
child->parent = cur->parent;
} while (child->next && (child = child->next));
/* make the cur's last child point to cur's next sibling
* (finish the splice)
*/
child->next = cur->next;
/* we just replaced cur with it's children
* so make it's first child the next node to process
*/
next = cur->child;
/* make cur childless and siblingless */
cur->child = cur->next = NULL;
/* we just removed cur from our list,
* so we need to keep the same prev for the next pass
*/
cur = prev;
}
/* if we have a message with children, prune it's children */
else if (cur->child) {
ref_prune_tree(cur);
if (!cur->msgdata && !cur->child) {
/* Did we end up with a completely empty node here?
* Go back and prune it too. See Bug 3784. */
goto retry;
}
}
}
}
/*
* Sort the messages in the root set by date.
*/
static void ref_sort_root(Thread *root)
{
Thread *cur;
static const struct sortcrit sortcrit[] =
{{ SORT_DATE, 0, {{NULL, NULL}} },
{ SORT_SEQUENCE, 0, {{NULL, NULL}} }};
cur = root->child;
while (cur) {
/* if the message is a dummy, sort its children */
if (!cur->msgdata) {
cur->child = lsort(cur->child,
(void * (*)(void*)) index_thread_getnext,
(void (*)(void*,void*)) index_thread_setnext,
(int (*)(void*,void*,void*)) index_thread_compare,
(void *)sortcrit);
}
cur = cur->next;
}
/* sort the root set */
root->child = lsort(root->child,
(void * (*)(void*)) index_thread_getnext,
(void (*)(void*,void*)) index_thread_setnext,
(int (*)(void*,void*,void*)) index_thread_compare,
(void *)sortcrit);
}
/*
* Group threads with same subject.
*/
static void ref_group_subjects(Thread *root, unsigned nroot, Thread **newnode)
{
Thread *cur, *old, *prev, *next, *child;
struct hash_table subj_table;
char *subj;
/* Step 5.A: create a subj_table with one bucket for every possible
* subject in the root set
*/
construct_hash_table(&subj_table, nroot, 1);
/* Step 5.B: populate the table with a container for each subject
* at the root
*/
for (cur = root->child; cur; cur = cur->next) {
/* Step 5.B.i: find subject of the thread
*
* if the container is not empty, use it's subject
*/
if (cur->msgdata)
subj = cur->msgdata->xsubj;
/* otherwise, use the subject of it's first child */
else
subj = cur->child->msgdata->xsubj;
/* Step 5.B.ii: if subject is empty, skip it */
if (!strlen(subj)) continue;
/* Step 5.B.iii: lookup this subject in the table */
old = (Thread *) hash_lookup(subj, &subj_table);
/* Step 5.B.iv: insert the current container into the table iff:
* - this subject is not in the table, OR
* - this container is empty AND the one in the table is not
* (the empty one is more interesting as a root), OR
* - the container in the table is a re/fwd AND this one is not
* (the non-re/fwd is the more interesting of the two)
*/
if (!old ||
(!cur->msgdata && old->msgdata) ||
(old->msgdata && old->msgdata->is_refwd &&
cur->msgdata && !cur->msgdata->is_refwd)) {
hash_insert(subj, cur, &subj_table);
}
}
/* 5.C - group containers with the same subject together */
for (prev = NULL, cur = root->child, next = cur->next;
cur;
prev = cur, cur = next, next = (next ? next->next : NULL)) {
/* Step 5.C.i: find subject of the thread
*
* if container is not empty, use it's subject
*/
if (cur->msgdata)
subj = cur->msgdata->xsubj;
/* otherwise, use the subject of it's first child */
else
subj = cur->child->msgdata->xsubj;
/* Step 5.C.ii: if subject is empty, skip it */
if (!strlen(subj)) continue;
/* Step 5.C.iii: lookup this subject in the table */
old = (Thread *) hash_lookup(subj, &subj_table);
/* Step 5.C.iv: if we found ourselves, skip it */
if (!old || old == cur) continue;
/* ok, we already have a container which contains our current subject,
* so pull this container out of the root set, because we are going to
* merge this node with another one
*/
if (!prev) /* we're at the root */
root->child = cur->next;
else
prev->next = cur->next;
cur->next = NULL;
/* if both containers are dummies, append cur's children to old's */
if (!old->msgdata && !cur->msgdata) {
/* find old's last child */
for (child = old->child; child->next; child = child->next);
/* append cur's children to old's children list */
child->next = cur->child;
/* make old the parent of cur's children */
for (child = cur->child; child; child = child->next)
child->parent = old;
/* make cur childless */
cur->child = NULL;
}
/* if:
* - old container is empty, OR
* - the current message is a re/fwd AND the old one is not,
* make the current container a child of the old one
*
* Note: we don't have to worry about the reverse cases
* because step 5.B guarantees that they won't happen
*/
else if (!old->msgdata ||
(cur->msgdata && cur->msgdata->is_refwd &&
!old->msgdata->is_refwd)) {
thread_adopt_child(old, cur);
}
/* if both messages are re/fwds OR neither are re/fwds,
* then make them both children of a new dummy container
* (we don't want to assume any parent-child relationship between them)
*
* perhaps we can create a parent-child relationship
* between re/fwds by counting the number of re/fwds
*
* Note: we need the hash table to still point to old,
* so we must make old the dummy and make the contents of the
* new container a copy of old's original contents
*/
else {
Thread *new = (*newnode)++;
/* make new a copy of old (except parent and next) */
new->msgdata = old->msgdata;
new->child = old->child;
new->next = NULL;
/* make new the parent of it's newly adopted children */
for (child = new->child; child; child = child->next)
child->parent = new;
/* make old the parent of cur and new */
cur->parent = old;
new->parent = old;
/* empty old and make it have two children (cur and new) */
old->msgdata = NULL;
old->child = cur;
cur->next = new;
}
/* we just removed cur from our list,
* so we need to keep the same prev for the next pass
*/
cur = prev;
}
free_hash_table(&subj_table, NULL);
}
/*
* Guts of thread searching. Recurses over children when necessary.
*/
static int _index_thread_search(struct index_state *state,
Thread *thread, int (*searchproc) (MsgData *))
{
Thread *child;
/* test the head node */
if (thread->msgdata && searchproc(thread->msgdata)) return 1;
/* test the children recursively */
child = thread->child;
while (child) {
if (_index_thread_search(state, child, searchproc)) return 1;
child = child->next;
}
/* if we get here, we struck out */
return 0;
}
/*
* Search a thread to see if it contains a message which matches searchproc().
*
* This is a wrapper around _index_thread_search() which iterates through
* each thread and removes any which fail the searchproc().
*/
static void index_thread_search(struct index_state *state,
Thread *root, int (*searchproc) (MsgData *))
{
Thread *cur, *prev, *next;
for (prev = NULL, cur = root->child, next = cur->next;
cur;
prev = cur, cur= next, next = (cur ? cur->next : NULL)) {
if (!_index_thread_search(state, cur, searchproc)) {
/* unlink the thread from the list */
if (!prev) /* first thread */
root->child = cur->next;
else
prev->next = cur->next;
/* we just removed cur from our list,
* so we need to keep the same prev for the next pass
*/
cur = prev;
}
}
}
/*
* Guts of the REFERENCES algorithms. Behavior is tweaked with loadcrit[],
* threadproc(), searchproc() and sortcrit[].
*/
static void _index_thread_ref(struct index_state *state, unsigned *msgno_list,
unsigned int nmsg,
const struct sortcrit loadcrit[],
MsgData **(*threadproc) (struct rootset *, Thread **),
int (*searchproc) (MsgData *),
const struct sortcrit sortcrit[], int usinguid)
{
MsgData **msgdata, **thrdata = NULL;
unsigned int mi;
int tref, nnode;
Thread *newnode;
struct hash_table id_table;
struct rootset rootset;
/* Create/load the msgdata array */
msgdata = index_msgdata_load(state, msgno_list, nmsg, loadcrit, 0, NULL);
/* calculate the sum of the number of references for all messages */
for (mi = 0, tref = 0 ; mi < nmsg ; mi++)
tref += msgdata[mi]->ref.count;
/* create an array of Thread to use as nodes of thread tree (including
* empty containers)
*
* - We will be building threads under a dummy root, so we need at least
* (nmsg + 1) nodes.
* - We also will need containers for references to non-existent messages.
* To make sure we have enough, we will take the worst case and
* use the sum of the number of references for all messages.
* - Finally, we will need containers to group threads with the same
* subject together. To make sure we have enough, we will take the
* worst case which will be half of the number of messages.
*
* This is overkill, but it is the only way to make sure we have enough
* ahead of time. If we tried to use xrealloc(), the array might be moved,
* and our parent/child/next pointers will no longer be correct
* (been there, done that).
*/
nnode = (int) (1.5 * nmsg + 1 + tref);
rootset.root = (Thread *) xmalloc(nnode * sizeof(Thread));
memset(rootset.root, 0, nnode * sizeof(Thread));
newnode = rootset.root + 1; /* set next newnode to the second
one in the array (skip the root) */
/* Step 0: create an id_table with one bucket for every possible
* message-id and reference (nmsg + tref)
*/
construct_hash_table(&id_table, nmsg + tref, 1);
/* Step 1: link messages together */
ref_link_messages(msgdata, nmsg, &newnode, &id_table);
/* Step 2: find the root set (gather all of the orphan messages) */
rootset.nroot = 0;
hash_enumerate(&id_table, ref_gather_orphans, &rootset);
/* discard id_table */
free_hash_table(&id_table, NULL);
/* Step 3: prune tree of empty containers - get our deposit back :^) */
ref_prune_tree(rootset.root);
/* Steps 4/5: algorithm-specific thread processing */
if (threadproc) thrdata = threadproc(&rootset, &newnode);
/* Optionally search threads (to be used by REFERENCES derivatives) */
if (searchproc) index_thread_search(state, rootset.root, searchproc);
/* Step 6: sort threads */
if (sortcrit) index_thread_sort(rootset.root, sortcrit);
/* Output the threaded messages */
index_thread_print(state, rootset.root, usinguid);
/* free the thread array */
free(rootset.root);
/* free the msgdata array */
index_msgdata_free(msgdata, nmsg);
index_msgdata_free(thrdata, rootset.nroot);
}
/*
* Thread a list of messages using the REFERENCES algorithm.
*/
static MsgData **references_thread_proc(struct rootset *rootset,
Thread **newnode)
{
/* Step 4: sort the root set */
ref_sort_root(rootset->root);
/* Step 5: group root set by subject */
ref_group_subjects(rootset->root, rootset->nroot, newnode);
return NULL;
}
static void index_thread_references(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid)
{
static const struct sortcrit loadcrit[] =
{{ LOAD_IDS, 0, {{NULL,NULL}} },
{ SORT_SUBJECT, 0, {{NULL,NULL}} },
{ SORT_DATE, 0, {{NULL,NULL}} },
{ SORT_SEQUENCE, 0, {{NULL,NULL}} }};
static const struct sortcrit sortcrit[] =
{{ SORT_DATE, 0, {{NULL,NULL}} },
{ SORT_SEQUENCE, 0, {{NULL,NULL}} }};
_index_thread_ref(state, msgno_list, nmsg, loadcrit,
references_thread_proc, NULL, sortcrit, usinguid);
}
/* Find most recent internaldate of all messages in thread */
static void find_most_recent(Thread *thread, MsgData *recent)
{
Thread *child;
/* test the head node */
if (thread->msgdata->internaldate > recent->internaldate)
recent->internaldate = thread->msgdata->internaldate;
/* test the children recursively */
child = thread->child;
while (child) {
find_most_recent(child, recent);
child = child->next;
}
}
/*
* Tag the root of each thread with the most recent internaldate of all
* messages in the thread. The actual sorting will be done by the calling
* function, but we leverage the fact that sorting by sentdate will fallback
* to internaldate if sentdate == 0.
*/
static MsgData **refs_thread_proc(struct rootset *rootset,
Thread **newnode __attribute((unused)))
{
MsgData **ptrs, *md;
Thread *cur;
int i = 0;
/* Create an array of MsgData for dummy roots */
ptrs = (MsgData **) xzmalloc(rootset->nroot *
(sizeof(MsgData *) + sizeof(MsgData)));
md = (MsgData *)(ptrs + rootset->nroot);
/* Find most recent internaldate in each thread */
cur = rootset->root->child;
while (cur) {
/* If the message is a dummy, assign it MsgData for sorting */
if (!cur->msgdata) {
cur->msgdata = ptrs[i] = &md[i];
i++;
cur->msgdata->internaldate = cur->child->msgdata->internaldate;
}
cur->msgdata->sentdate = 0; /* force date sort to use internaldate */
find_most_recent(cur, cur->msgdata);
cur = cur->next;
}
return ptrs;
}
/*
* Thread a list of messages using the REFS algorithm.
*/
static void index_thread_refs(struct index_state *state,
unsigned *msgno_list, unsigned int nmsg,
int usinguid)
{
static const struct sortcrit loadcrit[] =
{{ LOAD_IDS, 0, {{NULL,NULL}} },
{ SORT_DATE, 0, {{NULL,NULL}} },
{ SORT_ARRIVAL, 0, {{NULL,NULL}} },
{ SORT_SEQUENCE, 0, {{NULL,NULL}} }};
static const struct sortcrit sortcrit[] =
{{ SORT_DATE, 0, {{NULL,NULL}} },
{ SORT_ARRIVAL, 0, {{NULL,NULL}} },
{ SORT_SEQUENCE, 0, {{NULL,NULL}} }};
_index_thread_ref(state, msgno_list, nmsg, loadcrit,
refs_thread_proc, NULL, sortcrit, usinguid);
}
/*
* NNTP specific stuff.
*/
EXPORTED char *index_get_msgid(struct index_state *state,
uint32_t msgno)
{
struct mailbox *mailbox = state->mailbox;
struct index_record record;
if (index_reload_record(state, msgno, &record))
return NULL;
return mailbox_cache_get_env(mailbox, &record, ENV_MSGID);
}
static void massage_header(char *hdr)
{
int n = 0;
char *p, c;
for (p = hdr; *p; p++) {
if (*p == ' ' || *p == '\t' || *p == '\r') {
if (!n || *(p+1) == '\n') {
/* no leading or trailing whitespace */
continue;
}
/* replace with space */
c = ' ';
}
else if (*p == '\n') {
if (*(p+1) == ' ' || *(p+1) == '\t') {
/* folded header */
continue;
}
/* end of header */
break;
}
else
c = *p;
hdr[n++] = c;
}
hdr[n] = '\0';
}
EXPORTED extern struct nntp_overview *index_overview(struct index_state *state,
uint32_t msgno)
{
static struct nntp_overview over;
static char *env = NULL, *from = NULL, *hdr = NULL;
static int envsize = 0, fromsize = 0, hdrsize = 0;
int size;
char *envtokens[NUMENVTOKENS];
struct address addr = { NULL, NULL, NULL, NULL, NULL, NULL, 0 };
strarray_t refhdr = STRARRAY_INITIALIZER;
struct mailbox *mailbox = state->mailbox;
struct index_record record;
/* flush any previous data */
memset(&over, 0, sizeof(struct nntp_overview));
if (index_reload_record(state, msgno, &record))
return NULL;
if (mailbox_cacherecord(mailbox, &record))
return NULL; /* upper layers can cope! */
/* make a working copy of envelope; strip outer ()'s */
/* -2 -> don't include the size of the outer parens */
/* +1 -> leave space for NUL */
size = cacheitem_size(&record, CACHE_ENVELOPE) - 2 + 1;
if (envsize < size) {
envsize = size;
env = xrealloc(env, envsize);
}
/* +1 -> skip the leading paren */
strlcpy(env, cacheitem_base(&record, CACHE_ENVELOPE) + 1, size);
/* make a working copy of headers */
size = cacheitem_size(&record, CACHE_HEADERS);
if (hdrsize < size+2) {
hdrsize = size+100;
hdr = xrealloc(hdr, hdrsize);
}
memcpy(hdr, cacheitem_base(&record, CACHE_HEADERS), size);
hdr[size] = '\0';
parse_cached_envelope(env, envtokens, VECTOR_SIZE(envtokens));
over.uid = record.uid;
over.bytes = record.size;
over.lines = index_getlines(state, msgno);
over.date = envtokens[ENV_DATE];
over.msgid = envtokens[ENV_MSGID];
/* massage subject */
if ((over.subj = envtokens[ENV_SUBJECT]))
massage_header(over.subj);
/* build original From: header */
if (envtokens[ENV_FROM]) /* paranoia */
message_parse_env_address(envtokens[ENV_FROM], &addr);
if (addr.mailbox && addr.domain) { /* paranoia */
/* +3 -> add space for quotes and space */
/* +4 -> add space for < @ > NUL */
size = (addr.name ? strlen(addr.name) + 3 : 0) +
strlen(addr.mailbox) + strlen(addr.domain) + 4;
if (fromsize < size) {
fromsize = size;
from = xrealloc(from, fromsize);
}
from[0] = '\0';
if (addr.name) sprintf(from, "\"%s\" ", addr.name);
snprintf(from + strlen(from), fromsize - strlen(from),
"<%s@%s>", addr.mailbox, addr.domain);
over.from = from;
}
/* massage references */
strarray_append(&refhdr, "references");
message_pruneheader(hdr, &refhdr, 0);
strarray_fini(&refhdr);
if (*hdr) {
over.ref = hdr + 11; /* skip over header name */
massage_header(over.ref);
}
return &over;
}
EXPORTED extern char *index_getheader(struct index_state *state,
uint32_t msgno, char *hdr)
{
static struct buf staticbuf = BUF_INITIALIZER;
strarray_t headers = STRARRAY_INITIALIZER;
struct mailbox *mailbox = state->mailbox;
struct index_record record;
char *buf;
if (index_reload_record(state, msgno, &record))
return NULL;
/* see if the header is cached */
if (mailbox_cached_header(hdr) != BIT32_MAX &&
!mailbox_cacherecord(mailbox, &record)) {
buf_copy(&staticbuf, cacheitem_buf(&record, CACHE_HEADERS));
}
else {
/* uncached header */
struct buf msgbuf = BUF_INITIALIZER;
if (mailbox_map_record(mailbox, &record, &msgbuf))
return NULL;
buf_setcstr(&staticbuf, index_readheader(msgbuf.s, msgbuf.len, 0, record.header_size));
buf_free(&msgbuf);
}
buf_cstring(&staticbuf);
strarray_append(&headers, hdr);
message_pruneheader(staticbuf.s, &headers, NULL);
strarray_fini(&headers);
buf = staticbuf.s;
if (*buf) {
buf += strlen(hdr) + 1; /* skip header: */
massage_header(buf);
}
return buf;
}
EXPORTED extern unsigned long index_getsize(struct index_state *state,
uint32_t msgno)
{
struct index_record record;
if (index_reload_record(state, msgno, &record))
return 0;
return record.size;
}
EXPORTED extern unsigned long index_getlines(struct index_state *state,
uint32_t msgno)
{
struct index_record record;
struct body *body = NULL;
unsigned long lines = 0;
if (index_reload_record(state, msgno, &record))
return 0;
if (mailbox_cacherecord(state->mailbox, &record))
return 0;
message_read_bodystructure(&record, &body);
if (!body) return 0;
lines = body->content_lines;
message_free_body(body);
free(body);
return lines;
}
EXPORTED const char *index_mboxname(const struct index_state *state)
{
if (!state) return NULL;
return state->mboxname;
}
EXPORTED int index_hasrights(const struct index_state *state, int rights)
{
return state->myrights & rights;
}
/*
* Parse a sequence into an array of sorted & merged ranges.
*/
static seqset_t *_parse_sequence(struct index_state *state,
const char *sequence, int usinguid)
{
unsigned maxval;
/* Per RFC 3501, seq-number ABNF:
"*" represents the largest number in use.
In the case of message sequence numbers,
it is the number of messages in a non-empty mailbox.
In the case of unique identifiers,
it is the unique identifier of the last message in the mailbox
or, if the mailbox is empty, the mailbox's current UIDNEXT value.
*/
if (usinguid) {
if (state->exists) maxval = index_getuid(state, state->exists);
else maxval = state->last_uid + 1;
}
else maxval = state->exists;
return seqset_parse(sequence, NULL, maxval);
}
/*
* Create a new search program.
*/
EXPORTED struct searchargs *new_searchargs(const char *tag, int state,
struct namespace *namespace,
const char *userid,
struct auth_state *authstate,
int isadmin)
{
struct searchargs *sa;
sa = (struct searchargs *)xzmalloc(sizeof(struct searchargs));
sa->tag = tag;
sa->state = state;
/* default charset is US-ASCII */
sa->charset = charset_lookupname("US-ASCII");
sa->namespace = namespace;
sa->userid = userid;
sa->authstate = authstate;
sa->isadmin = isadmin;
return sa;
}
/*
* Free the searchargs 's'
*/
EXPORTED void freesearchargs(struct searchargs *s)
{
if (!s) return;
charset_free(&s->charset);
search_expr_free(s->root);
free(s);
}
EXPORTED char *sortcrit_as_string(const struct sortcrit *sortcrit)
{
struct buf b = BUF_INITIALIZER;
static const char * const key_names[] = {
"SEQUENCE", "ARRIVAL", "CC", "DATE",
"DISPLAYFROM", "DISPLAYTO", "FROM",
"SIZE", "SUBJECT", "TO", "ANNOTATION",
"MODSEQ", "UID", "HASFLAG", "CONVMODSEQ",
"CONVEXISTS", "CONVSIZE", "HASCONVFLAG",
"FOLDER", "RELEVANCY", "SPAMSCORE", "GUID",
"EMAILID", "THREADID", "SAVEDATE", "SNOOZEDUNTIL"
};
do {
if (b.len)
buf_putc(&b, ' ');
if (sortcrit->flags & SORT_REVERSE)
buf_appendcstr(&b, "REVERSE ");
if (sortcrit->key < VECTOR_SIZE(key_names))
buf_appendcstr(&b, key_names[sortcrit->key]);
else
buf_printf(&b, "UNKNOWN%u", sortcrit->key);
switch (sortcrit->key) {
case SORT_ANNOTATION:
buf_printf(&b, " \"%s\" \"%s\"",
sortcrit->args.annot.entry,
*sortcrit->args.annot.userid ?
"value.priv" : "value.shared");
break;
}
sortcrit++;
} while (sortcrit->key);
return buf_release(&b);
}
/*
* Free an array of sortcrit
*/
EXPORTED void freesortcrit(struct sortcrit *s)
{
int i = 0;
if (!s) return;
do {
switch (s[i].key) {
case SORT_ANNOTATION:
free(s[i].args.annot.entry);
free(s[i].args.annot.userid);
break;
case SORT_HASFLAG:
case SORT_HASCONVFLAG:
free(s[i].args.flag.name);
break;
case SORT_SAVEDATE:
case SORT_SNOOZEDUNTIL:
free(s[i].args.mailbox.id);
break;
}
i++;
} while (s[i].key != SORT_SEQUENCE);
free(s);
}
EXPORTED int insert_into_mailbox_allowed(struct mailbox *mailbox)
{
int r = 0;
/* prohibit inserting into \Snoozed mailbox */
if (mailbox->i.options & OPT_IMAP_HAS_ALARMS) {
struct buf attrib = BUF_INITIALIZER;
char *userid = mboxname_to_userid(mailbox_name(mailbox));
r = annotatemore_lookup(mailbox_name(mailbox), "/specialuse", userid, &attrib);
free(userid);
if (!r && buf_len(&attrib)) {
strarray_t *specialuse =
strarray_split(buf_cstring(&attrib), NULL, 0);
if (strarray_find(specialuse, "\\Snoozed", 0) >= 0) {
r = IMAP_MAILBOX_NOTSUPPORTED;
}
strarray_free(specialuse);
}
buf_free(&attrib);
}
return r;
}
|