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
//-
// Copyright (c) 2023, 2024, Jason Lingle
//
// This file is part of Crymap.
//
// Crymap is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// Crymap is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// Crymap. If not, see <http://www.gnu.org/licenses/>.
use std::convert::TryFrom;
use std::fmt::Write as _;
use std::fs;
use std::io;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::Duration;
use log::error;
use rusqlite::OptionalExtension as _;
use super::{sqlite_xex_vfs::XexVfs, types::*};
use crate::{
account::model::*,
support::{
error::Error, log_prefix::LogPrefix, mailbox_paths::parse_mailbox_path,
safe_name::is_safe_name, small_bitset::SmallBitset,
},
};
/// A connection to the encrypted `meta.sqlite.xex` database.
pub struct Connection {
path: PathBuf,
cxn: rusqlite::Connection,
#[cfg(test)]
override_savedate: Option<UnixTimestamp>,
}
static MIGRATIONS: &[&str] = &[include_str!("metadb.v1.sql")];
impl Connection {
pub fn new(
log_prefix: &LogPrefix,
path: PathBuf,
xex: &XexVfs,
) -> Result<Self, Error> {
let mut cxn = rusqlite::Connection::open_with_flags_and_vfs(
&path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
| rusqlite::OpenFlags::SQLITE_OPEN_CREATE
| rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
xex.name(),
)?;
// Set the database mode to what we want. There's a `modeof` query
// parm, but instead of actually taking a mode, it takes a *file path*
// and copies that file's mode, so this is the saner option. SQLite
// will copy the mode of the database file when it creates the journal
// file, and as long as all processes do the chmod before any
// transactions, this will always have the desired effect.
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
cxn.pragma_update(None, "foreign_keys", true)?;
// NB Changing this to WAL has implications for the backup process.
cxn.pragma_update(None, "journal_mode", "PERSIST")?;
cxn.pragma_update(None, "journal_size_limit", 1024 * 1024)?;
cxn.busy_timeout(Duration::from_secs(10))?;
super::db_migrations::apply_migrations(
log_prefix, &mut cxn, "meta", MIGRATIONS,
)?;
Ok(Self {
cxn,
path,
#[cfg(test)]
override_savedate: None,
})
}
/// Creates a mailbox with the given name, parent, and special use.
///
/// On success, returns the ID of the created mailbox.
#[cfg(test)]
pub fn create_mailbox(
&mut self,
parent: MailboxId,
name: &str,
special_use: Option<MailboxAttribute>,
) -> Result<MailboxId, Error> {
let txn = self.cxn.write_tx()?;
let id = create_mailbox(&txn, parent, name, special_use)?;
txn.commit()?;
Ok(id)
}
/// Atomically creates all the mailboxes necessary to make `path` exist.
///
/// `special_use` applies only to the final child. Returns the ID of the
/// final child.
///
/// Unlike other parts of the database layer, this implementation *does*
/// validate name safety of the path, since it is the only thing that
/// actually parses it. However, it does not validate that the call is not
/// creating a child of INBOX.
///
/// This still returns `MailboxExists` if `path` already refers to an
/// existing mailbox.
pub fn create_mailbox_hierarchy(
&mut self,
path: &str,
special_use: Option<MailboxAttribute>,
) -> Result<MailboxId, Error> {
let txn = self.cxn.write_tx()?;
let (parent, child_name) = create_parent_hierarchy(&txn, path)?;
let id = create_mailbox(&txn, parent, child_name, special_use)?;
txn.commit()?;
Ok(id)
}
/// Finds the ID of the mailbox with the given path, or returns
/// `Error::NxMailbox` if it does not exist.
///
/// This will never return `MailboxId::ROOT`. If `path` has no components,
/// it returns `Error::NxMailbox`.
pub fn find_mailbox(&mut self, path: &str) -> Result<MailboxId, Error> {
self.cxn.enable_write(false)?;
let mut id = MailboxId::ROOT;
for part in parse_mailbox_path(path) {
id = look_up_mailbox(&self.cxn, id, part)?
.ok_or(Error::NxMailbox)?;
}
if MailboxId::ROOT == id {
return Err(Error::NxMailbox);
}
Ok(id)
}
/// Finds the ID of the immediate parent mailbox of the given path,
/// returning the ID and the name of the would-be child under that parent.
/// `path` itself need not refer to an existing mailbox; only the parent
/// must exist.
///
/// This can return `MailboxId::ROOT` if `path` names a top-level mailbox,
/// but if `path` has no components, it will return `NxMailbox`.
#[cfg(test)]
pub fn find_mailbox_parent<'a>(
&mut self,
path: &'a str,
) -> Result<(MailboxId, &'a str), Error> {
self.cxn.enable_write(false)?;
let mut parent = MailboxId::ROOT;
let mut it = parse_mailbox_path(path).peekable();
while let Some(part) = it.next() {
if it.peek().is_none() {
return Ok((parent, part));
}
parent = look_up_mailbox(&self.cxn, parent, part)?
.ok_or(Error::NxMailbox)?;
}
Err(Error::NxMailbox)
}
/// Fetches the mailbox with the given ID.
pub fn fetch_mailbox(&mut self, id: MailboxId) -> Result<Mailbox, Error> {
self.cxn.enable_write(false)?;
self.cxn
.query_row(
"SELECT * FROM `mailbox` WHERE `id` = ?",
(id,),
Mailbox::from_row,
)
.optional()?
.ok_or(Error::NxMailbox)
}
/// Retrieves all mailboxes currently in the account, excluding the root.
pub fn fetch_all_mailboxes(&mut self) -> Result<Vec<Mailbox>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare("SELECT * FROM `mailbox` WHERE `id` != 0")?
.query_map((), from_row)?
.collect::<Result<Vec<Mailbox>, _>>()
.map_err(Into::into)
}
/// Moves and renames `mailbox_id` to have name `new_name` and be placed
/// under `new_parent`.
#[cfg(test)]
pub fn move_mailbox(
&mut self,
mailbox_id: MailboxId,
new_parent: MailboxId,
new_name: &str,
) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
move_mailbox(&txn, mailbox_id, new_parent, new_name)?;
txn.commit()?;
Ok(())
}
/// Moves and renames `mailbox_id` to be at `new_path`, implicitly creating
/// any new mailboxes required.
///
/// Like `create_mailbox_hierarchy`, this does validate that all names are
/// safe, but does not validate that the destination is not inside the
/// INBOX.
pub fn move_mailbox_into_hierarchy(
&mut self,
mailbox_id: MailboxId,
new_path: &str,
) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
let (new_parent, new_name) = create_parent_hierarchy(&txn, new_path)?;
move_mailbox(&txn, mailbox_id, new_parent, new_name)?;
txn.commit()?;
Ok(())
}
/// Deletes the mailbox with the given ID.
///
/// All messages and expungement records are removed from the mailbox. If
/// the mailbox has inferiors, it is marked `\Noselect`. Otherwise, it is
/// deleted entirely.
///
/// Returns `NxMailbox` if the mailbox does not exist. Returns
/// `MailboxHasInferiors` if it exists, is already `\Noselect`, and still
/// has inferiors.
pub fn delete_mailbox(&mut self, id: MailboxId) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
let selectable = txn
.query_row(
"SELECT `selectable` FROM `mailbox` \
WHERE `id` = ?",
(id,),
from_single::<bool>,
)
.optional()?
.ok_or(Error::NxMailbox)?;
let has_inferiors = 0
!= txn.query_row(
"SELECT COUNT(*) FROM `mailbox` \
WHERE `parent_id` = ?",
(id,),
from_single::<i64>,
)?;
if !selectable && has_inferiors {
// Nothing further we can do.
return Err(Error::MailboxHasInferiors);
}
// Remove external references to the mailbox.
txn.execute(
"DELETE FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ?",
(id,),
)?;
txn.execute(
"DELETE FROM `mailbox_message` \
WHERE `mailbox_id` = ?",
(id,),
)?;
txn.execute(
"DELETE FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ?",
(id,),
)?;
// Remove the mailbox entirely if it has no inferiors; otherwise, just
// make it \Noselect.
if has_inferiors {
txn.execute(
"UPDATE `mailbox` SET `selectable` = 0 \
WHERE `id` = ?",
(id,),
)?;
} else {
txn.execute("DELETE FROM `mailbox` WHERE `id` = ?", (id,))?;
}
txn.commit()?;
Ok(())
}
/// Adds `path` as a new subscription.
///
/// No normalisation is applied to `path`; this is the responsibility of
/// the API layer of the state-storage system.
///
/// If the subscription already exists, does nothing.
pub fn add_subscription(&mut self, path: &str) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn.execute(
"INSERT OR IGNORE INTO `subscription` (`path`) VALUES (?)",
(path,),
)?;
Ok(())
}
/// Removes the subscription identified by `path`.
///
/// If no such subscription exists, does nothing.
pub fn rm_subscription(&mut self, path: &str) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn
.execute("DELETE FROM `subscription` WHERE `path` = ?", (path,))?;
Ok(())
}
/// Returns all subscriptions in the account.
///
/// Unsubscribed parents of subscribed mailboxes are not represented here.
/// Their existence must be inferred from the results.
pub fn fetch_all_subscriptions(&mut self) -> Result<Vec<String>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare("SELECT `path` FROM `subscription`")?
.query_map((), from_single)?
.collect::<Result<Vec<_>, _>>()
.map_err(Into::into)
}
/// Finds the ID of the given flag, if it exists. Returns `None` without
/// modifying the database otherwise.
#[cfg(test)]
pub fn look_up_flag_id(
&mut self,
flag: &Flag,
) -> Result<Option<FlagId>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare_cached("SELECT `id` FROM `flag` WHERE `flag` = ?")?
.query_row((flag,), from_single)
.optional()
.map_err(Into::into)
}
/// Interns `flag` into the database.
///
/// If `flag` is already defined, the database is not modified and the
/// existing ID is returned. Otherwise, `flag` is added to the database and
/// its new ID is returned.
pub fn intern_flag(&mut self, flag: &Flag) -> Result<FlagId, Error> {
let txn = self.cxn.write_tx()?;
let flag_id = intern_flag(&txn, flag)?;
txn.commit()?;
Ok(flag_id)
}
/// Retrieves all flags that currently exist in the account.
#[cfg(test)]
pub fn fetch_all_flags(&mut self) -> Result<Vec<(FlagId, Flag)>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare("SELECT `id`, `flag` FROM `flag` ORDER BY `id`")?
.query_map((), from_row)?
.collect::<Result<_, _>>()
.map_err(Into::into)
}
/// Interns each `path` as a message.
///
/// Any created message is initially orphaned, so if the message is not
/// eventually added to a mailbox, it will be deleted instead of being
/// dropped into `INBOX`.
pub fn intern_messages_as_orphans(
&mut self,
paths: &mut dyn Iterator<Item = &str>,
) -> Result<Vec<MessageId>, Error> {
let txn = self.cxn.write_tx()?;
let ret = paths
.map(|path| intern_message_as_orphan(&txn, path))
.collect::<Result<Vec<_>, _>>()?;
txn.commit()?;
Ok(ret)
}
/// Returns whether `path` is currently a known message.
pub fn is_known_message(&self, path: &str) -> Result<bool, Error> {
get_message_by_path(&self.cxn, path).map(|e| e.is_some())
}
/// Returns a summary of the messages known to the database.
///
/// The table returned holds the sum of the `summary_increment` values for
/// all known messages grouped by their `summary_bucket`, with
/// `summary_bucket` being the index.
pub fn summarise_messages(&self) -> Result<Box<[u64; 256]>, Error> {
let mut result = Box::new([0u64; 256]);
for entry in self
.cxn
.prepare(
"SELECT `summary_bucket`, SUM(`summary_increment`) \
FROM `message` GROUP BY `summary_bucket`",
)?
.query_map((), from_row::<(usize, u64)>)?
{
let (group, sum) = entry?;
if let Some(dst) = result.get_mut(group) {
*dst = sum;
}
}
Ok(result)
}
/// Fetches the ID and path of every message which is currently orphaned
/// (i.e. not referenced by any mailbox) and which has a `last_activity`
/// time less than `last_activity_before`.
pub fn fetch_orphaned_messages(
&mut self,
last_activity_before: UnixTimestamp,
) -> Result<Vec<(MessageId, String)>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare(
"SELECT `id`, `path` FROM `message` \
WHERE `refcount` = 0 AND `last_activity` < ?",
)?
.query_map((last_activity_before,), from_row)?
.collect::<Result<_, _>>()
.map_err(Into::into)
}
/// Removes the message with the given ID from the database.
///
/// If there is no such message, or it is not orphaned, this silently does
/// nothing.
pub fn forget_message(
&mut self,
message_id: MessageId,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn
.prepare_cached(
"DELETE FROM `message` WHERE `id` = ? AND `refcount` = 0",
)?
.execute((message_id,))?;
Ok(())
}
/// Fetches the on-access data for the given message.
pub fn access_message(
&mut self,
message_id: MessageId,
) -> Result<MessageAccessData, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare_cached(
"SELECT `path`, `session_key`, `rfc822_size` \
FROM `message` WHERE `id` = ?",
)?
.query_row((message_id,), from_row)
.optional()?
.ok_or(Error::ExpungedMessage)
}
/// Updates the cached data for the given message.
///
/// If the message no longer exists, the call silently does nothing.
pub fn cache_message_data(
&mut self,
message_id: MessageId,
session_key: SessionKey,
rfc822_size: u64,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn
.prepare_cached(
"UPDATE `message` SET `session_key` = ?2, `rfc822_size` = ?3 \
WHERE `id` = ?1",
)?
.execute((message_id, session_key, rfc822_size))?;
Ok(())
}
/// Append already-interned messages into the given mailbox, with the given
/// initial flags if requested.
///
/// Returns the UID of the first message so inserted. (If there are no
/// messages, this will be a UID of a non-existent message.) Each message
/// is assigned a UID 1 greater than the previous.
pub fn append_mailbox_messages(
&mut self,
mailbox_id: MailboxId,
messages: &mut dyn Iterator<Item = (MessageId, Option<&SmallBitset>)>,
) -> Result<Uid, Error> {
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, mailbox_id)?;
let uid = append_mailbox_messages(
&txn,
mailbox_id,
savedate,
&mut messages.map(Ok),
)?;
txn.commit()?;
Ok(uid)
}
/// Atomically interns messages by path and then adds them to the given
/// mailbox with the set per-message flags.
pub fn intern_and_append_mailbox_messages(
&mut self,
mailbox_id: MailboxId,
messages: &mut dyn Iterator<Item = (&str, Option<&SmallBitset>)>,
) -> Result<Uid, Error> {
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, mailbox_id)?;
let mut messages = messages.map(|(path, flags)| {
intern_message_as_orphan(&txn, path).map(|id| (id, flags))
});
let uid =
append_mailbox_messages(&txn, mailbox_id, savedate, &mut messages)?;
txn.commit()?;
Ok(uid)
}
/// Atomically interns a message by path and adds it to the given mailbox,
/// but only if the message was not already interned.
///
/// Returns whether anything was recovered.
pub fn recover_message_into_mailbox(
&mut self,
mailbox_id: MailboxId,
path: &str,
flags: Option<&SmallBitset>,
) -> Result<bool, Error> {
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
if get_message_by_path(&txn, path)?.is_some() {
return Ok(false);
}
require_selectable_mailbox(&txn, mailbox_id)?;
let message_id = intern_message_as_orphan(&txn, path)?;
append_mailbox_messages(
&txn,
mailbox_id,
savedate,
&mut std::iter::once(Ok((message_id, flags))),
)?;
txn.commit()?;
Ok(true)
}
/// Copy the messages represented by `src_uids` (which must be sorted
/// ascending) from `src_mailbox_id` into `dst_mailbox_id`.
///
/// Returns the parallel ranges of messages that were actually copied.
pub fn copy_mailbox_messages(
&mut self,
src_mailbox_id: MailboxId,
src_uids: &mut dyn Iterator<Item = Uid>,
dst_mailbox_id: MailboxId,
) -> Result<CopyResponse, Error> {
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, src_mailbox_id)?;
require_selectable_mailbox(&txn, dst_mailbox_id)?;
let response = copy_mailbox_messages(
&txn,
src_mailbox_id,
src_uids,
dst_mailbox_id,
savedate,
)?;
txn.commit()?;
Ok(response)
}
/// Move the messages represented by `src_uids` (which must be sorted
/// ascending) from `src_mailbox_id` into `dst_mailbox_id`.
///
/// Returns the parallel ranges of messages that were actually copied.
pub fn move_mailbox_messages(
&mut self,
src_mailbox_id: MailboxId,
mut src_uids: impl Iterator<Item = Uid> + Clone,
dst_mailbox_id: MailboxId,
) -> Result<CopyResponse, Error> {
if src_mailbox_id == dst_mailbox_id {
return Err(Error::MoveIntoSelf);
}
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, src_mailbox_id)?;
require_selectable_mailbox(&txn, dst_mailbox_id)?;
let response = copy_mailbox_messages(
&txn,
src_mailbox_id,
&mut src_uids.clone(),
dst_mailbox_id,
savedate,
)?;
expunge_mailbox_messages(&txn, src_mailbox_id, &mut src_uids)?;
txn.commit()?;
Ok(response)
}
/// Atomically create a mailbox at `dst_path` with no special use, then
/// move the entire contents of `src_mailbox_id` into it.
///
/// `dst_path` is validated for special names but not for whether it
/// implies a descendent of the INBOX`. There is only an implicit-hierarchy
/// version of this function since it is only used for the lunatic special
/// case that invokes it.
///
/// This implements the special `RENAME INBOX` case.
pub fn move_all_mailbox_messages_into_create_hierarchy(
&mut self,
src_mailbox_id: MailboxId,
dst_path: &str,
) -> Result<MailboxId, Error> {
let savedate = self.savedate();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, src_mailbox_id)?;
let (dst_parent_id, dst_name) =
create_parent_hierarchy(&txn, dst_path)?;
let dst_mailbox_id =
create_mailbox(&txn, dst_parent_id, dst_name, None)?;
let src_uids = txn
.prepare(
"SELECT `uid` FROM `mailbox_message` \
WHERE `mailbox_id` = ? ORDER BY `uid`",
)?
.query_map((src_mailbox_id,), from_single::<Uid>)?
.collect::<Result<Vec<Uid>, _>>()?;
copy_mailbox_messages(
&txn,
src_mailbox_id,
&mut src_uids.iter().copied(),
dst_mailbox_id,
savedate,
)?;
expunge_mailbox_messages(
&txn,
src_mailbox_id,
&mut src_uids.into_iter(),
)?;
txn.commit()?;
Ok(dst_mailbox_id)
}
/// Expunges the given messages by UID from the mailbox.
///
/// This does not consider whether or not the messages have the `\Deleted`
/// flag. UIDs not present in the mailbox are silently ignored.
pub fn expunge_mailbox_messages(
&mut self,
mailbox_id: MailboxId,
messages: &mut dyn Iterator<Item = Uid>,
) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, mailbox_id)?;
if expunge_mailbox_messages(&txn, mailbox_id, messages)? > 0 {
txn.commit()?;
}
Ok(())
}
/// Fetch the messages in the given mailbox which were expunged after the
/// given modseq and pass the given filter.
///
/// The UIDs are returned in ascending order.
///
/// This corresponds to QRESYNC's `UID FETCH VANISHED CHANGEDSINCE modseq`.
pub fn fetch_vanished_mailbox_messages(
&mut self,
mailbox_id: MailboxId,
after_modseq: Modseq,
filter: &mut dyn FnMut(Uid) -> bool,
) -> Result<Vec<Uid>, Error> {
let txn = self.cxn.read_tx()?;
let mut ret = txn
.prepare(
"SELECT `uid` FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ? AND `expunged_modseq` > ?",
)?
.query_map((mailbox_id, after_modseq), from_single::<Uid>)?
.filter(|r| match *r {
Ok(uid) => filter(uid),
Err(_) => true,
})
.collect::<Result<Vec<Uid>, _>>()?;
ret.sort_unstable();
Ok(ret)
}
/// Modifies the flags of the given sequence of messages in a mailbox.
///
/// If `remove_listed` is true, flags found in `flags` are unset.
/// Otherwise, flags found in `flags` are set.
///
/// If `remove_unlisted` is `true`, flags not found in `flags` are unset.
///
/// Messages where `flags_modseq > unchanged_since` are skipped.
///
/// Returns a `Vec` of results parallel to `messages` which indicates what
/// happened to each message.
///
/// If no messages were changed, no modseq is allocated for the operation.
pub fn modify_mailbox_message_flags(
&mut self,
mailbox_id: MailboxId,
flags: &SmallBitset,
remove_listed: bool,
remove_unlisted: bool,
unchanged_since: Modseq,
messages: &mut dyn Iterator<Item = Uid>,
) -> Result<Vec<StoreResult>, Error> {
debug_assert!(!remove_listed || !remove_unlisted);
let mut results = Vec::<StoreResult>::new();
let txn = self.cxn.write_tx()?;
require_selectable_mailbox(&txn, mailbox_id)?;
let modseq = new_modseq(&txn, mailbox_id)?;
{
// For the near flags, we can fuse the unchanged_since check,
// modification check, all addition/removal, and updating
// `flags_modseq` into one operation per message.
//
// The near flags statement will:
// - Return no rows if the message is expunged or the
// unchanged_since condition fails.
// - Return a value other than `modseq` if the condition passes but
// the change is a no-op.
// - Return `modseq` if the condition passes and the change makes a
// difference.
let mut update_near_flags = if 0 == flags.near_bits() {
if remove_unlisted {
Some(txn.prepare(
"UPDATE `mailbox_message` \
SET `near_flags` = 0, `flags_modseq` = \
CASE `near_flags` \
WHEN 0 THEN `flags_modseq` \
ELSE ?4 END \
WHERE `mailbox_id` = ?1 AND `uid` = ?2 \
AND `flags_modseq` <= ?3 \
RETURNING `flags_modseq`",
)?)
} else {
None
}
} else {
let mut or_flags = 0i64;
let mut nand_flags = 0i64;
if remove_listed {
nand_flags |= flags.near_bits() as i64;
} else {
or_flags |= flags.near_bits() as i64;
}
if remove_unlisted {
nand_flags |= !flags.near_bits() as i64;
}
let flags_expr =
format!("((`near_flags` | {or_flags}) & ~ {nand_flags})");
Some(txn.prepare(&format!(
"UPDATE `mailbox_message` \
SET `near_flags` = {flags_expr}, `flags_modseq` = \
CASE `near_flags` \
WHEN {flags_expr} THEN `flags_modseq` \
ELSE ?4 END \
WHERE `mailbox_id` = ?1 AND `uid` = ?2 \
AND `flags_modseq` <= ?3 \
RETURNING `flags_modseq`",
))?)
};
// For the far flags, we need separate steps for add/remove, and
// also need to do the modseq check and update manually.
let mut add_far_flags = if !flags.has_far() || remove_listed {
None
} else {
let mut query =
"INSERT OR IGNORE INTO `mailbox_message_far_flag` \
(`mailbox_id`, `uid`, `flag_id`) VALUES"
.to_owned();
for (i, far_flag) in flags.iter_far().enumerate() {
if 0 != i {
query.push(',');
}
let _ = write!(query, " (?1, ?2, {far_flag})");
}
Some(txn.prepare(&query)?)
};
let mut rm_far_flags = if remove_unlisted {
if flags.has_far() {
let mut query = "DELETE FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` = ? \
AND `flag_id` NOT IN ("
.to_owned();
for (i, far_flag) in flags.iter_far().enumerate() {
if 0 != i {
query.push(',');
}
let _ = write!(query, "{far_flag}");
}
query.push(')');
Some(txn.prepare(&query)?)
} else {
Some(txn.prepare(
"DELETE FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` = ?",
)?)
}
} else if remove_listed {
let mut query = "DELETE FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` = ? \
AND `flag_id` IN ("
.to_owned();
for (i, far_flag) in flags.iter_far().enumerate() {
if 0 != i {
query.push(',');
}
let _ = write!(query, "{far_flag}");
}
query.push(')');
Some(txn.prepare(&query)?)
} else {
None
};
let mut is_updatable =
if add_far_flags.is_some() || rm_far_flags.is_some() {
Some(txn.prepare(
"SELECT 1 FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` = ? \
AND `flags_modseq` <= ?",
)?)
} else {
None
};
let mut update_flags_modseq =
if add_far_flags.is_some() || rm_far_flags.is_some() {
Some(txn.prepare(
"UPDATE `mailbox_message` \
SET `flags_modseq` = ?3 \
WHERE `mailbox_id` = ?1 AND `uid` = ?2",
)?)
} else {
None
};
for uid in messages {
let mut modified_with_modseq_update = false;
let mut modified_without_modseq_update = false;
if let Some(ref mut is_updatable) = is_updatable {
if !is_updatable.exists((
mailbox_id,
uid,
unchanged_since,
))? {
results.push(StoreResult::PreconditionsFailed);
continue;
}
}
if let Some(ref mut update_near_flags) = update_near_flags {
match update_near_flags
.query_row(
(mailbox_id, uid, unchanged_since, modseq),
from_single::<Modseq>,
)
.optional()?
{
None => {
results.push(StoreResult::PreconditionsFailed);
continue;
},
Some(m) => modified_with_modseq_update |= m == modseq,
}
}
if let Some(ref mut rm_far_flags) = rm_far_flags {
modified_without_modseq_update |=
0 != rm_far_flags.execute((mailbox_id, uid))?;
}
if let Some(ref mut add_far_flags) = add_far_flags {
modified_without_modseq_update |=
0 != add_far_flags.execute((mailbox_id, uid))?;
}
if let Some(ref mut update_flags_modseq) = update_flags_modseq {
if modified_without_modseq_update
&& !modified_with_modseq_update
{
update_flags_modseq
.execute((mailbox_id, uid, modseq))?;
}
}
if modified_with_modseq_update || modified_without_modseq_update
{
results.push(StoreResult::Modified);
} else {
results.push(StoreResult::Nop);
}
}
}
if results.contains(&StoreResult::Modified) {
txn.commit()?;
}
Ok(results)
}
/// Directly fetches the raw data for the given message.
#[cfg(test)]
fn fetch_raw_message(
&mut self,
message_id: MessageId,
) -> Result<RawMessage, Error> {
self.cxn.enable_write(false)?;
self.cxn
.query_row(
"SELECT * FROM `message` WHERE `id` = ?",
(message_id,),
from_row,
)
.optional()?
.ok_or(Error::NxMessage)
}
/// Directly fetches the raw data for the given mailbox message.
#[cfg(test)]
fn fetch_raw_mailbox_message(
&mut self,
mailbox_id: MailboxId,
uid: Uid,
) -> Result<RawMailboxMessage, Error> {
self.cxn.enable_write(false)?;
self.cxn
.query_row(
"SELECT * FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` = ?",
(mailbox_id, uid),
from_row,
)
.optional()?
.ok_or(Error::NxMessage)
}
/// Fetches the flags bitset for the given mailbox message.
///
/// This is only useful for tests, as the real IMAP code needs to manage
/// flags at a snapshot level.
#[cfg(test)]
fn fetch_mailbox_message_flags(
&mut self,
mailbox_id: MailboxId,
uid: Uid,
) -> Result<SmallBitset, Error> {
let txn = self.cxn.read_tx()?;
let near = txn
.query_row(
"SELECT `near_flags` FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` = ?",
(mailbox_id, uid),
from_single::<i64>,
)
.optional()?
.ok_or(Error::NxMessage)?;
let mut bitset = SmallBitset::new_with_near(near as u64);
for flag in txn
.prepare(
"SELECT `flag_id` FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` = ?",
)?
.query_map((mailbox_id, uid), from_single::<usize>)?
{
bitset.insert(flag?);
}
Ok(bitset)
}
/// Fetches the `Modseq` at which a mailbox message was expunged (if there
/// is such a record).
///
/// This is only useful for tests. Real code needs to query the table for a
/// range; additionally, this lookup is inefficient as there is no index on
/// the key it uses.
#[cfg(test)]
fn fetch_mailbox_message_expunge_modseq(
&mut self,
mailbox_id: MailboxId,
uid: Uid,
) -> Result<Option<Modseq>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.query_row(
"SELECT `expunged_modseq` FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ? AND `uid` = ?",
(mailbox_id, uid),
from_single,
)
.optional()
.map_err(Into::into)
}
/// Zero the `last_activity` field of the given message.
#[cfg(test)]
fn zero_message_last_activity(
&mut self,
message_id: MessageId,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn.execute(
"UPDATE `message` SET `last_activity` = 0 WHERE `id` = ?",
(message_id,),
)?;
Ok(())
}
/// Fetches the initial snapshot state for a mailbox (as in `SELECT` or
/// `EXAMINE`).
///
/// `writable` controls whether the `recent_uid` field gets updated.
pub fn select(
&mut self,
mailbox_id: MailboxId,
writable: bool,
qresync: Option<&QresyncRequest>,
) -> Result<InitialSnapshot, Error> {
let txn = if writable {
self.cxn.write_tx()?
} else {
self.cxn.read_tx()?
};
let status = selectable_mailbox_status(&txn, mailbox_id)?;
let flags = txn
.prepare("SELECT `id`, `flag` FROM `flag` ORDER BY `id`")?
.query_map((), from_row::<(FlagId, Flag)>)?
.collect::<Result<Vec<_>, _>>()?;
let messages = fetch_initial_messages(
&txn,
mailbox_id,
Uid::MIN,
status.recent_uid,
)?;
if writable && status.recent_uid != status.next_uid {
txn.execute(
"UPDATE `mailbox` SET `recent_uid` = `next_uid` \
WHERE `id` = ?",
(mailbox_id,),
)?;
}
let uid_validity = mailbox_id.as_uid_validity()?;
let qresync_response = if let Some(qresync) =
qresync.filter(|q| q.uid_validity == uid_validity)
{
// Note that this code deliberately never looks at
// `mapping_reference`: because we remember all expungements, the
// case where we would use it never occurs.
//
// Comparisons against `resync_from` are `>` and not `>=` since the
// client implies that it knows the state at `modseq ==
// resync_from`.
let accept_uid = |uid: Uid| -> bool {
qresync.known_uids.as_ref().is_none_or(|k| k.contains(uid))
};
let mut expunged = SeqRange::<Uid>::new();
for uid in txn
.prepare(
"SELECT `uid` FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ? AND `expunged_modseq` > ? \
ORDER BY `uid`",
)?
.query_map(
(mailbox_id, qresync.resync_from),
from_single::<Uid>,
)?
{
let uid = uid?;
if accept_uid(uid) {
expunged.append(uid);
}
}
let changed = txn
.prepare(
// `flags_modseq` is always >= `append_modseq`, so we only
// need to query one of them.
"SELECT `uid` FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `flags_modseq` > ? \
ORDER BY `uid`",
)?
.query_map(
(mailbox_id, qresync.resync_from),
from_single::<Uid>,
)?
.filter_map(|res| match res {
Ok(uid) if !accept_uid(uid) => None,
res => Some(res),
})
.collect::<Result<Vec<Uid>, _>>()?;
Some(QresyncResponse { expunged, changed })
} else {
None
};
txn.commit()?;
Ok(InitialSnapshot {
flags,
messages,
next_uid: status.next_uid,
max_modseq: status.max_modseq,
qresync: qresync_response,
})
}
/// Performs a "mini poll", discovering a subset of updated data which is
/// safe to report after the cursed non-UID `FETCH`, `STORE`, and `SEARCH`
/// commands.
///
/// `max_known_flag` is the maximum flag ID currently in the snapshot. Any
/// new flags beyond this ID will be discovered and returned.
///
/// `max_known_uid` is the maximum UID of any message in the snapshot. No
/// information on newer messages will be returned.
///
/// `snapshot_modseq` is the current nominal modseq of the snapshot. It is
/// used to determine whether any expunges have happened after the
/// snapshot. `mini_poll` will compute an updated value for the snapshot
/// modseq.
///
/// `max_message_modseq` is the maximum modseq of any message currently in
/// the snapshot. It may be greater than or less than `snapshot_modseq`.
/// It is used to discover changes to flags on known messages.
pub fn mini_poll(
&mut self,
mailbox_id: MailboxId,
max_known_flag: FlagId,
max_known_uid: Option<Uid>,
snapshot_modseq: Modseq,
max_message_modseq: Modseq,
) -> Result<MiniPoll, Error> {
let txn = self.cxn.read_tx()?;
let status = selectable_mailbox_status(&txn, mailbox_id)?;
if snapshot_modseq == status.max_modseq {
// Short-circuit since we know nothing has changed. (There could
// potentially be new flags, but we don't need to discover them
// until any message is modified to reference them.)
return Ok(MiniPoll {
new_flags: Vec::new(),
updated_messages: Vec::new(),
snapshot_modseq,
diverged: false,
has_pending_expunge: false,
});
}
let new_flags = poll_new_flags(&txn, max_known_flag)?;
let updated_messages = poll_updated_messages(
&txn,
mailbox_id,
max_known_uid,
max_message_modseq,
)?;
// If there are expunge or append events which occurred after the
// snapshot, we need to ensure we do not report a modseq >= those
// events.
let delayed_expunge_modseq = txn
.prepare_cached(
"SELECT MIN(`expunged_modseq`) - 1 \
FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ? AND `expunged_modseq` > ?",
)?
.query_row(
(mailbox_id, snapshot_modseq),
from_single::<Option<Modseq>>,
)?;
let delayed_append_modseq = txn
.prepare_cached(
"SELECT MIN(`append_modseq`) - 1 \
FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` > ?",
)?
.query_row(
(
mailbox_id,
max_known_uid.map(|uid| uid.0.get()).unwrap_or(0),
),
from_single::<Option<Modseq>>,
)?;
let new_snapshot_modseq = delayed_expunge_modseq
.unwrap_or(status.max_modseq)
.min(delayed_append_modseq.unwrap_or(status.max_modseq));
let diverged = txn
.prepare_cached(
"SELECT `max_modseq` != ?2 FROM `mailbox` WHERE `id` = ?1",
)?
.query_row(
(mailbox_id, new_snapshot_modseq),
from_single::<bool>,
)?;
Ok(MiniPoll {
new_flags,
updated_messages,
snapshot_modseq: new_snapshot_modseq,
diverged,
has_pending_expunge: delayed_expunge_modseq.is_some(),
})
}
/// Performs a full poll, fetching all data needed to bring a snapshot up
/// to date with the database.
///
/// `writable` indicates whether the mailbox is opened in a writable mode.
/// If `false`, `recent_uid` will not be updated.
///
/// `max_known_flag` is the maximum flag ID currently in the snapshot. Any
/// new flags beyond this ID will be discovered and returned.
///
/// `max_known_uid` is the maximum UID of any message in the snapshot, used
/// to differentiate between already-known and new messages.
///
/// `snapshot_modseq` is the current nominal modseq of the snapshot. It is
/// used to discover new expunge events.
///
/// `max_message_modseq` is the maximum modseq of any message currently in
/// the snapshot. It may be greater than or less than `snapshot_modseq`.
/// (The "greater" case only occurs after `mini_poll` allowed the true
/// state to diverge from reality.) It is used to discover changes to flags
/// on known messages. This is only really here so that a `mini_poll`
/// followed by `full_poll` does not repeat flags changes.
pub fn full_poll(
&mut self,
mailbox_id: MailboxId,
writable: bool,
max_known_flag: FlagId,
max_known_uid: Option<Uid>,
snapshot_modseq: Modseq,
max_message_modseq: Modseq,
) -> Result<FullPoll, Error> {
let txn = if writable {
self.cxn.write_tx()?
} else {
self.cxn.read_tx()?
};
let status = selectable_mailbox_status(&txn, mailbox_id)?;
if snapshot_modseq == status.max_modseq {
// Short-circuit since we know nothing has changed. (There could
// potentially be new flags, but we don't need to discover them
// until any message is modified to reference them.)
return Ok(FullPoll {
new_flags: Vec::new(),
updated_messages: Vec::new(),
new_messages: Vec::new(),
expunged: Vec::new(),
snapshot_modseq,
next_uid: status.next_uid,
});
}
let new_flags = poll_new_flags(&txn, max_known_flag)?;
let updated_messages = poll_updated_messages(
&txn,
mailbox_id,
max_known_uid,
max_message_modseq,
)?;
let new_messages = if let Some(min_uid) =
max_known_uid.map_or(Some(Uid::MIN), Uid::next)
{
fetch_initial_messages(
&txn,
mailbox_id,
min_uid,
status.recent_uid,
)?
} else {
Vec::new()
};
let expunged = txn
.prepare_cached(
"SELECT `uid` FROM `mailbox_message_expungement` \
WHERE `mailbox_id` = ? AND `expunged_modseq` > ? \
ORDER BY `uid` ",
)?
.query_map((mailbox_id, snapshot_modseq), from_single::<Uid>)?
.collect::<Result<Vec<_>, _>>()?;
if writable && status.next_uid != status.recent_uid {
txn.execute(
"UPDATE `mailbox` SET `recent_uid` = `next_uid` WHERE `id` = ?",
(mailbox_id,),
)?;
}
txn.commit()?;
Ok(FullPoll {
new_flags,
updated_messages,
new_messages,
expunged,
snapshot_modseq: status.max_modseq,
next_uid: status.next_uid,
})
}
/// Runs the V1-to-V2 migration process.
///
/// If the migration has already been performed according to the database,
/// this does nothing and simply returns. Otherwise, `callback` is invoked.
/// The callback is given its own callback to which it passes migration
/// information as it discovers it.
///
/// An exclusive lock is held on the database for the duration of the
/// operation.
pub fn migrate_v1_to_v2(
&mut self,
callback: &mut dyn FnMut(
&mut dyn FnMut(V1MigrationEvent<'_>) -> Result<(), Error>,
) -> Result<(), Error>,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
let txn = self.cxn.transaction_with_behavior(
rusqlite::TransactionBehavior::Exclusive,
)?;
if 0 == txn.execute(
"INSERT OR IGNORE INTO `maintenance` (`name`) \
VALUES ('v1-to-v2-migration')",
(),
)? {
return Ok(());
}
let mut current_flag_ids = Vec::<FlagId>::new();
let mut current_mailbox = None::<MailboxId>;
callback(&mut |evt| {
match evt {
V1MigrationEvent::Mailbox {
path,
special_use,
flags,
} => {
let (parent_id, child_name) =
create_parent_hierarchy(&txn, path)?;
current_mailbox =
look_up_mailbox(&txn, parent_id, child_name)?;
if current_mailbox.is_none() {
current_mailbox = Some(create_mailbox(
&txn,
parent_id,
child_name,
special_use,
)?);
}
current_flag_ids.clear();
for flag in flags {
current_flag_ids.push(intern_flag(&txn, flag)?);
}
},
V1MigrationEvent::Message {
path,
flags,
savedate,
} => {
let mailbox_id =
current_mailbox.expect("Message event before Mailbox");
let message_id = intern_message_as_orphan(&txn, path)?;
let translated_flags = flags
.iter()
.map(|ix| current_flag_ids[ix].0)
.collect::<SmallBitset>();
append_mailbox_messages(
&txn,
mailbox_id,
savedate,
&mut std::iter::once(Ok((
message_id,
Some(&translated_flags),
))),
)?;
},
V1MigrationEvent::Subscription { path } => {
txn.execute(
"INSERT OR IGNORE INTO `subscription` (`path`) \
VALUES (?)",
(path,),
)?;
},
}
Ok(())
})?;
txn.commit()?;
Ok(())
}
/// See if the given maintenance should be started.
pub fn start_maintenance(
&mut self,
name: &str,
if_not_since: UnixTimestamp,
) -> Result<bool, Error> {
let txn = self.cxn.write_tx()?;
if txn
.prepare(
"SELECT 1 FROM `maintenance` \
WHERE `name` = ? AND `last_started` >= ?",
)?
.exists((name, if_not_since))?
{
return Ok(false);
}
txn.execute(
"INSERT OR REPLACE INTO `maintenance` (`name`, `last_started`) \
VALUES (?, ?)",
(name, UnixTimestamp::now()),
)?;
txn.commit()?;
Ok(true)
}
#[cfg(test)]
pub fn clear_maintenance(&mut self, name: &str) -> Result<(), Error> {
self.cxn
.execute("DELETE FROM `maintenance` WHERE `name` = ?", (name,))?;
Ok(())
}
/// Creates a backup copy of the database.
///
/// The backup is staged in the `tmp` directory and ultimately placed at
/// `out`. `out` will never be overwritten.
pub fn back_up(&mut self, tmp: &Path, out: &Path) -> Result<(), Error> {
// We do the backup by starting a read transaction and then doing a
// plain file copy. This is faster and far operationally simpler than
// going through SQLite's backup API (which would need to decrypt and
// re-encrypt XEX). It also addresses the fact that the XEX VFS layer
// will use different keys for different file names; the expectation is
// that one of these backups can be renamed back to METADB_NAME and be
// expected to work.
let txn = self.cxn.read_tx()?;
let journal_mode = txn.query_row(
"SELECT `journal_mode` FROM `pragma_journal_mode`",
(),
from_single::<String>,
)?;
// Doing a plain file copy makes this incompatible with WAL mode.
if journal_mode.eq_ignore_ascii_case("WAL") {
error!("can't back up database because it is in WAL mode");
return Err(Error::CorruptFileLayout);
}
let mut tmpfile = tempfile::NamedTempFile::new_in(tmp)?;
let mut infile = fs::File::open(&self.path)?;
io::copy(&mut infile, &mut tmpfile)?;
tmpfile.as_file_mut().sync_all()?;
tmpfile
.persist_noclobber(out)
.map_err(|e| Error::Io(e.error))?;
// Explicitly ensure that the transaction is carried to here.
let _ = txn.rollback();
Ok(())
}
/// Fetches the message spool information for the given message, if any.
pub fn fetch_message_spool(
&mut self,
id: MessageId,
) -> Result<Option<MessageSpool>, Error> {
let txn = self.cxn.read_tx()?;
let message_spool = txn
.query_row(
"SELECT * FROM `message_spool` WHERE `message_id` = ?",
(id,),
from_row::<MessageSpool>,
)
.optional()?;
let Some(mut message_spool) = message_spool else {
return Ok(None);
};
message_spool.destinations = txn
.prepare(
"SELECT `destination` FROM `message_spool_destination` \
WHERE `message_id` = ?",
)?
.query_map((id,), from_single::<String>)?
.collect::<Result<Vec<_>, _>>()?;
Ok(Some(message_spool))
}
/// Inserts the given message spool entry.
pub fn insert_message_spool(
&mut self,
spool: &MessageSpool,
) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
txn.execute(
"INSERT INTO `message_spool` \
(`message_id`, `transfer`, `mail_from`, `expires`) \
VALUES (?, ?, ?, ?)",
(
spool.message_id,
spool.transfer,
&spool.mail_from,
spool.expires,
),
)?;
let mut insert_destination = txn.prepare(
"INSERT INTO `message_spool_destination` \
(`message_id`, `destination`) \
VALUES (?, ?)",
)?;
for destination in &spool.destinations {
insert_destination.execute((spool.message_id, destination))?;
}
drop(insert_destination);
txn.commit()?;
Ok(())
}
/// Removes any message spool entries which expired before the given
/// timestamp.
pub fn delete_expired_message_spools(
&mut self,
now: UnixTimestamp,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn.execute(
"DELETE FROM `message_spool` WHERE `expires` <= ?",
(now,),
)?;
Ok(())
}
/// Removes all the listed destinations from the mail spool entry for the
/// given message.
///
/// If there are no remaining destinations after this operation, the mail
/// spool entry is removed entirely.
pub fn delete_message_spool_destinations(
&mut self,
message_id: MessageId,
destinations: &mut dyn Iterator<Item = &str>,
) -> Result<(), Error> {
let txn = self.cxn.write_tx()?;
let mut delete_destination = txn.prepare(
"DELETE FROM `message_spool_destination` \
WHERE `message_id` = ? AND `destination` = ?",
)?;
for destination in destinations {
delete_destination.execute((message_id, destination))?;
}
drop(delete_destination);
if !txn
.prepare(
"SELECT 1 FROM `message_spool_destination` \
WHERE `message_id` = ?",
)?
.exists((message_id,))?
{
txn.execute(
"DELETE FROM `message_spool` \
WHERE `message_id` = ?",
(message_id,),
)?;
}
txn.commit()?;
Ok(())
}
/// Fetches the current foreign SMTP TLS status for the given domain, if
/// any.
pub fn fetch_foreign_smtp_tls_status(
&mut self,
domain: &str,
) -> Result<Option<ForeignSmtpTlsStatus>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.query_row(
"SELECT * FROM `foreign_smtp_tls_status` \
WHERE `domain` = ?",
(domain,),
from_row,
)
.optional()
.map_err(Into::into)
}
/// Fetch all SMTP TLS stati.
pub fn fetch_all_foreign_smtp_tls_stati(
&mut self,
) -> Result<Vec<ForeignSmtpTlsStatus>, Error> {
self.cxn.enable_write(false)?;
self.cxn
.prepare("SELECT * FROM `foreign_smtp_tls_status`")?
.query_map((), from_row)?
.collect::<Result<Vec<_>, _>>()
.map_err(Into::into)
}
/// Inserts or updates the foreign SMTP TLS status for `status.domain`.
pub fn put_foreign_smtp_tls_status(
&mut self,
status: &ForeignSmtpTlsStatus,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn.execute(
"INSERT OR REPLACE INTO `foreign_smtp_tls_status` \
(`domain`, `starttls`, `valid_certificate`, `tls_version`) \
VALUES (?, ?, ?, ?)",
(
&status.domain,
status.starttls,
status.valid_certificate,
status.tls_version,
),
)?;
Ok(())
}
/// Deletes the foreign SMTP TLS status for the given domain.
pub fn delete_foreign_smtp_tls_status(
&mut self,
domain: &str,
) -> Result<(), Error> {
self.cxn.enable_write(true)?;
self.cxn.execute(
"DELETE FROM `foreign_smtp_tls_status` \
WHERE `domain` = ?",
(domain,),
)?;
Ok(())
}
#[cfg(not(test))]
fn savedate(&self) -> UnixTimestamp {
UnixTimestamp::now()
}
#[cfg(test)]
fn savedate(&self) -> UnixTimestamp {
self.override_savedate.unwrap_or_else(UnixTimestamp::now)
}
}
trait ConnectionExt {
fn read_tx(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>>;
fn write_tx(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>>;
fn enable_write(&mut self, enabled: bool) -> rusqlite::Result<()>;
}
impl ConnectionExt for rusqlite::Connection {
fn read_tx(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>> {
self.enable_write(false)?;
self.transaction_with_behavior(rusqlite::TransactionBehavior::Deferred)
}
fn write_tx(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>> {
self.enable_write(true)?;
self.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
}
#[cfg(debug_assertions)]
fn enable_write(&mut self, enabled: bool) -> rusqlite::Result<()> {
// PRAGMA doesn't actually support templates, so switch the whole query
// string based on `enabled`.
self.execute(
if enabled {
"PRAGMA query_only = false"
} else {
"PRAGMA query_only = true"
},
(),
)?;
Ok(())
}
#[cfg(not(debug_assertions))]
fn enable_write(&mut self, _: bool) -> rusqlite::Result<()> {
Ok(())
}
}
fn intern_flag(
txn: &rusqlite::Connection,
flag: &Flag,
) -> Result<FlagId, Error> {
if let Some(existing) = txn
.prepare_cached("SELECT `id` FROM `flag` WHERE `flag` = ?")?
.query_row((flag,), from_single)
.optional()?
{
return Ok(existing);
}
txn.execute("INSERT INTO `flag` (`flag`) VALUES (?)", (flag,))?;
let flag_id = usize::try_from(txn.last_insert_rowid())
.map_err(|_| Error::MailboxFull)?;
Ok(FlagId(flag_id))
}
fn create_mailbox(
txn: &rusqlite::Connection,
parent: MailboxId,
name: &str,
special_use: Option<MailboxAttribute>,
) -> Result<MailboxId, Error> {
if 0 == txn.query_row(
"SELECT COUNT(*) FROM `mailbox` WHERE `id` = ?",
(parent,),
from_single::<i64>,
)? {
return Err(Error::NxMailbox);
}
if 0 != txn.query_row(
"SELECT COUNT(*) FROM `mailbox` \
WHERE `parent_id` = ? AND `name` = ?",
(parent, name),
from_single::<i64>,
)? {
return Err(Error::MailboxExists);
}
txn.execute(
"INSERT INTO `mailbox` (`parent_id`, `name`, `special_use`)\
VALUES (?, ?, ?)",
(parent, name, special_use),
)?;
let Ok(mailbox_id) = u32::try_from(txn.last_insert_rowid()) else {
return Err(Error::MailboxIdOutOfRange);
};
Ok(MailboxId(mailbox_id))
}
/// Creates any mailboxes needed so that `path` can be represented as a
/// `parent_id` and `child_name` pair.
///
/// This validates that all elements of the path are safe names, including the
/// final one.
fn create_parent_hierarchy<'a>(
txn: &rusqlite::Connection,
path: &'a str,
) -> Result<(MailboxId, &'a str), Error> {
let mut parent = MailboxId::ROOT;
let mut parts = parse_mailbox_path(path).peekable();
while let Some(part) = parts.next() {
if !is_safe_name(part) {
return Err(Error::UnsafeName);
}
if parts.peek().is_none() {
return Ok((parent, part));
}
if let Some(id) = look_up_mailbox(txn, parent, part)? {
parent = id;
} else {
parent = create_mailbox(txn, parent, part, None)?;
}
}
// We only get here if path is empty.
Err(Error::UnsafeName)
}
fn look_up_mailbox(
txn: &rusqlite::Connection,
parent_id: MailboxId,
name: &str,
) -> Result<Option<MailboxId>, Error> {
txn.prepare_cached(
"SELECT `id` FROM `mailbox` WHERE `parent_id` = ? AND `name` = ?",
)?
.query_row((parent_id, name), from_single)
.optional()
.map_err(Into::into)
}
fn move_mailbox(
txn: &rusqlite::Connection,
mailbox_id: MailboxId,
new_parent: MailboxId,
new_name: &str,
) -> Result<(), Error> {
// Fetch the current information about the mailbox to ensure it still
// exists and to check whether the rename is a noop.
let (current_parent, current_name) = txn
.query_row(
"SELECT `parent_id`, `name` FROM `mailbox` \
WHERE `id` = ?",
(mailbox_id,),
from_row::<(MailboxId, String)>,
)
.optional()?
.ok_or(Error::NxMailbox)?;
if new_parent == current_parent && new_name == current_name {
return Err(Error::RenameToSelf);
}
// Walk up the tree and ensure `new_parent` is not a descendent of
// `mailbox`. This also handles verifying that the new parent actually
// exists.
let mut ancestor = new_parent;
while MailboxId::ROOT != ancestor {
if ancestor == mailbox_id {
return Err(Error::RenameIntoSelf);
}
ancestor = txn
.query_row(
"SELECT `parent_id` FROM `mailbox` WHERE `id` = ?",
(ancestor,),
from_single,
)
.optional()?
.ok_or(Error::NxMailbox)?;
}
// Ensure the new name is not already in use.
if 0 != txn.query_row(
"SELECT COUNT(*) FROM `mailbox` \
WHERE `parent_id` = ? AND `name` = ?",
(new_parent, new_name),
from_single::<i64>,
)? {
return Err(Error::MailboxExists);
}
// Everything looks sensible; go ahead with the rename.
txn.execute(
"UPDATE `mailbox` SET `parent_id` = ?, `name` = ? \
WHERE `id` = ?",
(new_parent, new_name, mailbox_id),
)?;
Ok(())
}
fn get_message_by_path(
cxn: &rusqlite::Connection,
path: &str,
) -> Result<Option<MessageId>, Error> {
cxn.prepare_cached("SELECT `id` FROM `message` WHERE `path` = ?")?
.query_row((path,), from_single)
.optional()
.map_err(Into::into)
}
/// Computes the `summary_bucket` and `summary_increment` values for the given
/// message path.
pub fn message_summary_values(path: &str) -> (u8, u16) {
// FNV hash
let mut hash = 2166136261u32;
for &byte in path.as_bytes() {
hash = hash.wrapping_mul(16777619);
hash ^= u32::from(byte);
}
(hash as u8, ((hash >> 8) as u16).max(1))
}
fn intern_message_as_orphan(
cxn: &rusqlite::Connection,
path: &str,
) -> Result<MessageId, Error> {
if let Some(existing) = get_message_by_path(cxn, path)? {
return Ok(existing);
}
let (summary_bucket, summary_increment) = message_summary_values(path);
cxn.prepare_cached(
"INSERT INTO `message` (`path`, `summary_bucket`, `summary_increment`) \
VALUES (?, ?, ?)")?
.execute((path, summary_bucket, summary_increment))?;
Ok(MessageId(cxn.last_insert_rowid()))
}
fn append_mailbox_messages(
cxn: &rusqlite::Connection,
mailbox_id: MailboxId,
savedate: UnixTimestamp,
messages: &mut dyn Iterator<
Item = Result<(MessageId, Option<&SmallBitset>), Error>,
>,
) -> Result<Uid, Error> {
let modseq = new_modseq(cxn, mailbox_id)?;
// Read the UID for the first new message out of the database.
let first_uid = selectable_mailbox_status(cxn, mailbox_id)?.next_uid;
let mut next_uid = first_uid;
let mut mailbox_message_insert = cxn.prepare_cached(
"INSERT INTO `mailbox_message` ( \
`mailbox_id`, `uid`, `message_id`, `near_flags`, \
`savedate`, `append_modseq`, `flags_modseq` \
) VALUES (?, ?, ?, ?, ?, ?, ?)",
)?;
let mut mailbox_message_far_flag_insert = cxn.prepare_cached(
"INSERT INTO `mailbox_message_far_flag` (\
`mailbox_id`, `uid`, `flag_id` \
) VALUES (?, ?, ?)",
)?;
for message in messages {
let (message_id, flags) = message?;
let uid = next_uid;
next_uid = next_uid.next().ok_or(Error::MailboxFull)?;
mailbox_message_insert.execute((
mailbox_id,
uid,
message_id,
flags.map_or(0, |f| f.near_bits() as i64),
savedate,
modseq,
modseq,
))?;
if let Some(flags) = flags {
if flags.has_far() {
for far_flag in flags.iter_far() {
mailbox_message_far_flag_insert.execute((
mailbox_id,
uid,
FlagId(far_flag),
))?;
}
}
}
}
if next_uid > first_uid {
cxn.execute(
"UPDATE `mailbox` SET `next_uid` = ? WHERE `id` = ?",
(next_uid, mailbox_id),
)?;
}
Ok(first_uid)
}
/// Copy the messages represented by `src_uids` (which must be sorted
/// ascending) from `src_mailbox_id` into `dst_mailbox_id`.
///
/// Returns the parallel ranges of messages that were actually copied.
fn copy_mailbox_messages(
txn: &rusqlite::Connection,
src_mailbox_id: MailboxId,
src_uids: &mut dyn Iterator<Item = Uid>,
dst_mailbox_id: MailboxId,
savedate: UnixTimestamp,
) -> Result<CopyResponse, Error> {
let mut response = CopyResponse {
uid_validity: dst_mailbox_id.as_uid_validity()?,
from_uids: SeqRange::new(),
to_uids: SeqRange::new(),
};
let dst_modseq = new_modseq(txn, dst_mailbox_id)?;
let mut next_uid = selectable_mailbox_status(txn, dst_mailbox_id)?.next_uid;
let mut copy_message = txn.prepare(
"INSERT INTO `mailbox_message` ( \
`mailbox_id`, `uid`, `message_id`, `near_flags`, \
`savedate`, `append_modseq`, `flags_modseq` \
) \
SELECT ?3, ?4, `message_id`, `near_flags`, ?5, ?6, ?6 \
FROM `mailbox_message` \
WHERE `mailbox_id` = ?1 AND `uid` = ?2",
)?;
let mut copy_far_flags = txn.prepare(
"INSERT INTO `mailbox_message_far_flag` ( \
`mailbox_id`, `uid`, `flag_id` \
) \
SELECT ?3, ?4, `flag_id` \
FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ?1 AND `uid` = ?2",
)?;
for src_uid in src_uids {
let dst_uid = next_uid;
if 0 == copy_message.execute((
src_mailbox_id,
src_uid,
dst_mailbox_id,
dst_uid,
savedate,
dst_modseq,
))? {
continue;
}
copy_far_flags.execute((
src_mailbox_id,
src_uid,
dst_mailbox_id,
dst_uid,
))?;
response.from_uids.append(src_uid);
response.to_uids.append(dst_uid);
next_uid = next_uid.next().ok_or(Error::MailboxFull)?;
}
if !response.from_uids.is_empty() {
txn.execute(
"UPDATE `mailbox` SET `next_uid` = ? WHERE `id` = ?",
(next_uid, dst_mailbox_id),
)?;
}
Ok(response)
}
/// Expunges the given messages from the given mailbox.
///
/// Non-existent messages are silently skipped.
fn expunge_mailbox_messages(
txn: &rusqlite::Connection,
mailbox_id: MailboxId,
messages: &mut dyn Iterator<Item = Uid>,
) -> Result<u32, Error> {
let modseq = new_modseq(txn, mailbox_id)?;
let mut delete_from_mailbox_message_far_flag = txn.prepare(
"DELETE FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` = ?",
)?;
let mut delete_from_mailbox_message = txn.prepare(
"DELETE FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` = ?",
)?;
let mut insert_mailbox_message_expungement = txn.prepare(
"INSERT INTO `mailbox_message_expungement` \
(`mailbox_id`, `uid`, `expunged_modseq`) \
VALUES (?, ?, ?)",
)?;
let mut count = 0;
for uid in messages {
delete_from_mailbox_message_far_flag.execute((mailbox_id, uid))?;
if delete_from_mailbox_message.execute((mailbox_id, uid))? > 0 {
insert_mailbox_message_expungement
.execute((mailbox_id, uid, modseq))?;
count += 1;
}
}
Ok(count)
}
/// Fetches the `InitialMessageStatus` for every message in `mailbox_id` whose
/// UID is at least `min_uid`.
///
/// `recent_uid` is used to determine the value of the `recent` field.
fn fetch_initial_messages(
txn: &rusqlite::Connection,
mailbox_id: MailboxId,
min_uid: Uid,
recent_uid: Uid,
) -> Result<Vec<InitialMessageStatus>, Error> {
let mut messages = txn
.prepare_cached(
"SELECT `uid`, `message_id`, `near_flags`,
MAX(`flags_modseq`, `append_modseq`), `savedate` \
FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` >= ? \
ORDER BY `uid`",
)?
.query_map(
(mailbox_id, min_uid),
from_row::<(Uid, MessageId, i64, Modseq, UnixTimestamp)>,
)?
.map(|res| {
res.map(|(uid, id, near_flags, modseq, savedate)| {
InitialMessageStatus {
uid,
id,
savedate,
flags: SmallBitset::new_with_near(near_flags as u64),
last_modified: modseq,
recent: uid >= recent_uid,
}
})
})
.collect::<Result<Vec<_>, _>>()?;
if !messages.is_empty() {
let mut msg_it = messages.iter_mut().peekable();
for far_flag in txn
.prepare_cached(
"SELECT `uid`, `flag_id` \
FROM `mailbox_message_far_flag` \
WHERE `mailbox_id` = ? AND `uid` >= ? \
ORDER BY `uid`",
)?
.query_map((mailbox_id, min_uid), from_row::<(Uid, FlagId)>)?
{
let (uid, FlagId(flag_id)) = far_flag?;
while msg_it.peek().unwrap().uid < uid {
msg_it.next();
}
let msg = msg_it.peek_mut().unwrap();
debug_assert_eq!(uid, msg.uid);
msg.flags.insert(flag_id);
}
}
Ok(messages)
}
/// Poll for flags added with an ID greater than `max_known_flag`.
fn poll_new_flags(
txn: &rusqlite::Connection,
max_known_flag: FlagId,
) -> Result<Vec<(FlagId, Flag)>, Error> {
txn.prepare_cached(
"SELECT `id`, `flag` FROM `flag` WHERE `id` > ? ORDER BY `id`",
)?
.query_map((max_known_flag,), from_row::<(FlagId, Flag)>)?
.collect::<Result<Vec<_>, _>>()
.map_err(Into::into)
}
/// Poll for updates to messages with a UID less than or equal to
/// `max_known_uid` and which have been modified after `max_message_modseq`.
fn poll_updated_messages(
txn: &rusqlite::Connection,
mailbox_id: MailboxId,
max_known_uid: Option<Uid>,
max_message_modseq: Modseq,
) -> Result<Vec<UpdatedMessageStatus>, Error> {
let Some(max_known_uid) = max_known_uid else {
return Ok(Vec::new());
};
let mut messages = txn
.prepare_cached(
"SELECT `uid`, `near_flags`, `flags_modseq` \
FROM `mailbox_message` \
WHERE `mailbox_id` = ? AND `uid` <= ? \
AND `flags_modseq` > ? \
ORDER BY `uid`",
)?
.query_map(
(mailbox_id, max_known_uid, max_message_modseq),
from_row::<(Uid, i64, Modseq)>,
)?
.map(|res| {
res.map(|(uid, near_flags, modseq)| UpdatedMessageStatus {
uid,
flags: SmallBitset::new_with_near(near_flags as u64),
last_modified: modseq,
})
})
.collect::<Result<Vec<_>, _>>()?;
if !messages.is_empty() {
let mut msg_it = messages.iter_mut().peekable();
for far_flag in txn
.prepare_cached(
"SELECT `mm`.`uid`, `mmff`.`flag_id` \
FROM `mailbox_message` `mm` \
JOIN `mailbox_message_far_flag` `mmff` \
ON `mm`.`mailbox_id` = `mmff`.`mailbox_id` \
AND `mm`.`uid` = `mmff`.`uid` \
WHERE `mm`.`mailbox_id` = ? \
AND `mm`.`uid` <= ? \
AND `mm`.`flags_modseq` > ? \
ORDER BY `mm`.`uid`",
)?
.query_map(
(mailbox_id, max_known_uid, max_message_modseq),
from_row::<(Uid, FlagId)>,
)?
{
let (uid, FlagId(flag_id)) = far_flag?;
while msg_it.peek().unwrap().uid < uid {
msg_it.next();
}
let msg = msg_it.peek_mut().unwrap();
debug_assert_eq!(uid, msg.uid);
msg.flags.insert(flag_id);
}
}
Ok(messages)
}
/// Ensures that `id` represents an extant and selectable mailbox.
fn require_selectable_mailbox(
cxn: &rusqlite::Connection,
id: MailboxId,
) -> Result<(), Error> {
match cxn
.prepare_cached("SELECT `selectable` FROM `mailbox` WHERE `id` = ?")?
.query_row((id,), from_single)
.optional()?
{
None => Err(Error::NxMailbox),
Some(false) => Err(Error::MailboxUnselectable),
Some(true) => Ok(()),
}
}
fn selectable_mailbox_status(
cxn: &rusqlite::Connection,
mailbox_id: MailboxId,
) -> Result<MailboxStatus, Error> {
let status = cxn
.prepare_cached(
"SELECT `selectable`, `next_uid`, `recent_uid`, `max_modseq` \
FROM `mailbox` WHERE `id` = ?",
)?
.query_row((mailbox_id,), from_row::<MailboxStatus>)
.optional()?
.ok_or(Error::NxMailbox)?;
if !status.selectable {
return Err(Error::MailboxUnselectable);
}
Ok(status)
}
/// Allocates a new `Modseq` for a change within the given mailbox.
fn new_modseq(
cxn: &rusqlite::Connection,
id: MailboxId,
) -> Result<Modseq, Error> {
let max_modseq = cxn.prepare_cached(
"SELECT `max_modseq` FROM `mailbox` WHERE `id` = ? AND `selectable`",
)?
.query_row((id,), from_single::<Modseq>)
.optional()?
.ok_or(Error::NxMailbox)?;
let this_modseq = max_modseq.next().ok_or(Error::MailboxFull)?;
cxn.prepare_cached("UPDATE `mailbox` SET `max_modseq` = ? WHERE `id` = ?")?
.execute((this_modseq, id))?;
Ok(this_modseq)
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use chrono::prelude::*;
use tempfile::TempDir;
use super::*;
use crate::crypt::master_key::MasterKey;
struct Fixture {
_tmpdir: TempDir,
cxn: Connection,
savedate: UnixTimestamp,
}
impl Fixture {
fn new() -> Self {
let savedate =
UnixTimestamp(DateTime::from_timestamp(12345, 0).unwrap());
let tmpdir = TempDir::new().unwrap();
let master_key = Arc::new(MasterKey::new());
let xex = XexVfs::new(master_key).unwrap();
let mut cxn = Connection::new(
&LogPrefix::new("test".to_owned()),
tmpdir.path().join("meta.sqlite.xex"),
&xex,
)
.unwrap();
cxn.override_savedate = Some(savedate);
Self {
_tmpdir: tmpdir,
cxn,
savedate,
}
}
}
#[test]
fn test_mailbox_crud() {
let mut fixture = Fixture::new();
// Creation
let foo_id = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "foo", None)
.unwrap();
assert_eq!(MailboxId(1), foo_id);
let foobar_id =
fixture.cxn.create_mailbox(foo_id, "bar", None).unwrap();
let baz_id = fixture
.cxn
.create_mailbox(
MailboxId::ROOT,
"baz",
Some(MailboxAttribute::Important),
)
.unwrap();
assert_matches!(
Err(Error::MailboxExists),
fixture.cxn.create_mailbox(MailboxId::ROOT, "foo", None),
);
assert_matches!(
Err(Error::MailboxExists),
fixture.cxn.create_mailbox(foo_id, "bar", None),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.create_mailbox(MailboxId(999), "quux", None),
);
// Retrieval
let mut mailboxes = fixture
.cxn
.fetch_all_mailboxes()
.unwrap()
.into_iter()
.map(|mb| (mb.name, mb.parent_id, mb.special_use))
.collect::<Vec<_>>();
mailboxes.sort();
assert_eq!(
vec![
("bar".to_owned(), foo_id, None),
(
"baz".to_owned(),
MailboxId::ROOT,
Some(MailboxAttribute::Important)
),
("foo".to_owned(), MailboxId::ROOT, None),
],
mailboxes
);
let mut foobar = fixture.cxn.fetch_mailbox(foobar_id).unwrap();
assert_eq!("bar", foobar.name);
assert_eq!(foo_id, foobar.parent_id);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.fetch_mailbox(MailboxId(999)),
);
// Path resolution
assert_eq!(foo_id, fixture.cxn.find_mailbox("foo").unwrap());
assert_eq!(foobar_id, fixture.cxn.find_mailbox("foo/bar").unwrap());
assert_eq!(baz_id, fixture.cxn.find_mailbox("baz").unwrap());
assert_matches!(Err(Error::NxMailbox), fixture.cxn.find_mailbox(""));
assert_matches!(Err(Error::NxMailbox), fixture.cxn.find_mailbox("bar"));
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.find_mailbox("foo/baz"),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.find_mailbox("foo/bar/baz"),
);
assert_eq!(
(MailboxId::ROOT, "quux"),
fixture.cxn.find_mailbox_parent("quux").unwrap(),
);
assert_eq!(
(MailboxId::ROOT, "foo"),
fixture.cxn.find_mailbox_parent("foo").unwrap(),
);
assert_eq!(
(MailboxId::ROOT, "INBOX"),
fixture.cxn.find_mailbox_parent("InBoX").unwrap(),
);
assert_eq!(
(foo_id, "quux"),
fixture.cxn.find_mailbox_parent("foo/quux").unwrap(),
);
assert_eq!(
(foobar_id, "quux"),
fixture.cxn.find_mailbox_parent("foo/bar/quux").unwrap(),
);
assert_eq!(
(foo_id, "InBoX"),
fixture.cxn.find_mailbox_parent("//foo/InBoX").unwrap(),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.find_mailbox_parent(""),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.find_mailbox_parent("foo/bar/baz/quux"),
);
// Renaming
fixture
.cxn
.move_mailbox(foobar_id, foo_id, "foobar")
.unwrap();
foobar = fixture.cxn.fetch_mailbox(foobar_id).unwrap();
assert_eq!("foobar", foobar.name);
assert_eq!(foo_id, foobar.parent_id);
fixture
.cxn
.move_mailbox(foobar_id, baz_id, "foobar")
.unwrap();
foobar = fixture.cxn.fetch_mailbox(foobar_id).unwrap();
assert_eq!("foobar", foobar.name);
assert_eq!(baz_id, foobar.parent_id);
fixture.cxn.move_mailbox(foobar_id, foo_id, "bar").unwrap();
foobar = fixture.cxn.fetch_mailbox(foobar_id).unwrap();
assert_eq!("bar", foobar.name);
assert_eq!(foo_id, foobar.parent_id);
assert_matches!(
Err(Error::RenameToSelf),
fixture.cxn.move_mailbox(foobar_id, foo_id, "bar"),
);
assert_matches!(
Err(Error::RenameIntoSelf),
fixture.cxn.move_mailbox(foo_id, foobar_id, "plugh"),
);
assert_matches!(
Err(Error::RenameIntoSelf),
fixture.cxn.move_mailbox(foo_id, foo_id, "foo"),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.move_mailbox(MailboxId(999), foo_id, "plugh"),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.move_mailbox(foo_id, MailboxId(999), "plugh"),
);
assert_matches!(
Err(Error::MailboxExists),
fixture.cxn.move_mailbox(baz_id, MailboxId::ROOT, "foo"),
);
// Deletion. Deleting messages and whatnot isn't tested here, but this
// at least checks that the queries are syntactically valid.
let mut foo = fixture.cxn.fetch_mailbox(foo_id).unwrap();
assert!(foo.selectable);
fixture.cxn.delete_mailbox(foo_id).unwrap();
foo = fixture.cxn.fetch_mailbox(foo_id).unwrap();
assert!(!foo.selectable);
assert_matches!(
Err(Error::MailboxHasInferiors),
fixture.cxn.delete_mailbox(foo_id),
);
fixture.cxn.delete_mailbox(foobar_id).unwrap();
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.fetch_mailbox(foobar_id),
);
fixture.cxn.delete_mailbox(foo_id).unwrap();
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.fetch_mailbox(foo_id),
);
}
#[test]
fn test_create_mailbox_hierarchy() {
let mut fixture = Fixture::new();
let baz_id = fixture
.cxn
.create_mailbox_hierarchy(
"foo/bar/baz",
Some(MailboxAttribute::Important),
)
.unwrap();
let qux_id = fixture
.cxn
.create_mailbox_hierarchy("foo/bar/qux", None)
.unwrap();
let fum_id = fixture.cxn.create_mailbox_hierarchy("fum", None).unwrap();
let mailboxes = fixture.cxn.fetch_all_mailboxes().unwrap();
assert_eq!(5, mailboxes.len());
for mailbox in &mailboxes {
if baz_id == mailbox.id {
assert_eq!(
Some(MailboxAttribute::Important),
mailbox.special_use
);
} else {
assert_eq!(None, mailbox.special_use);
}
}
assert_eq!(baz_id, fixture.cxn.find_mailbox("foo/bar/baz").unwrap());
assert_eq!(qux_id, fixture.cxn.find_mailbox("foo/bar/qux").unwrap());
assert_eq!(fum_id, fixture.cxn.find_mailbox("fum").unwrap());
assert_matches!(
Err(Error::UnsafeName),
fixture.cxn.create_mailbox_hierarchy("", None),
);
assert_matches!(
Err(Error::UnsafeName),
fixture.cxn.create_mailbox_hierarchy("f%o", None),
);
assert_matches!(
Err(Error::UnsafeName),
fixture.cxn.create_mailbox_hierarchy("foo/b%r", None),
);
assert_matches!(
Err(Error::MailboxExists),
fixture.cxn.create_mailbox_hierarchy("foo/bar", None),
);
}
#[test]
fn test_subscription_crud() {
let mut fixture = Fixture::new();
fixture.cxn.add_subscription("foo").unwrap();
fixture.cxn.add_subscription("bar").unwrap();
fixture.cxn.add_subscription("foo").unwrap();
fn sorted(mut v: Vec<String>) -> Vec<String> {
v.sort();
v
}
assert_eq!(
vec!["bar".to_owned(), "foo".to_owned()],
sorted(fixture.cxn.fetch_all_subscriptions().unwrap(),),
);
fixture.cxn.rm_subscription("foo").unwrap();
fixture.cxn.rm_subscription("quux").unwrap();
assert_eq!(
vec!["bar".to_owned()],
fixture.cxn.fetch_all_subscriptions().unwrap(),
);
}
#[test]
fn test_flag_interning() {
let mut fixture = Fixture::new();
let keyword = Flag::Keyword("Keyword".to_owned());
let keyword_lower = Flag::Keyword("keyword".to_owned());
assert_eq!(None, fixture.cxn.look_up_flag_id(&keyword).unwrap());
assert_eq!(FlagId(5), fixture.cxn.intern_flag(&keyword).unwrap());
assert_eq!(
Some(FlagId(5)),
fixture.cxn.look_up_flag_id(&keyword).unwrap(),
);
assert_eq!(FlagId(5), fixture.cxn.intern_flag(&keyword).unwrap());
assert_eq!(FlagId(5), fixture.cxn.intern_flag(&keyword_lower).unwrap());
assert_eq!(
Some(FlagId(5)),
fixture.cxn.look_up_flag_id(&keyword_lower).unwrap(),
);
assert!(fixture
.cxn
.fetch_all_flags()
.unwrap()
.contains(&(FlagId(5), keyword.clone())));
}
#[test]
fn test_message_crud() {
let mut fixture = Fixture::new();
// Create a bunch of flags. Some will be near flags, others far flags.
let flags = (0..100)
.map(|f| {
fixture
.cxn
.intern_flag(&Flag::Keyword(format!("flag{f}")))
.unwrap()
})
.collect::<Vec<FlagId>>();
let unselectable_id = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "unselectable", None)
.unwrap();
let child_id = fixture
.cxn
.create_mailbox(unselectable_id, "child", None)
.unwrap();
// Insert a couple messages into `unselectable`, give one of them a far
// flag, and expunge the other. This will add entries to all the
// mailbox-specific sub-tables, which we can then validate were removed
// when we delete `unselectable` (making it \Noselect rather than
// actually removing it).
let us_uid_flag = fixture
.cxn
.intern_and_append_mailbox_messages(
unselectable_id,
&mut [("foo", None), ("bar", None)].iter().copied(),
)
.unwrap();
assert_eq!(Uid::u(1), us_uid_flag);
let us_flag_flags = SmallBitset::from(vec![flags[99].0]);
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
unselectable_id,
&us_flag_flags,
false,
false,
Modseq::MAX,
&mut [us_uid_flag].iter().copied(),
)
.unwrap(),
);
let us_flag_mboxmsg = fixture
.cxn
.fetch_raw_mailbox_message(unselectable_id, us_uid_flag)
.unwrap();
// The flag we set should be a far flag.
assert_eq!(0, us_flag_mboxmsg.near_flags);
assert_eq!(Modseq::of(2), us_flag_mboxmsg.append_modseq);
assert_eq!(Modseq::of(3), us_flag_mboxmsg.flags_modseq);
// Ensure the flags are what we think. Since we eliminated the
// possibility of the flag being a near flag above, success implies a
// far flag entry.
assert_eq!(
us_flag_flags,
fixture
.cxn
.fetch_mailbox_message_flags(unselectable_id, us_uid_flag)
.unwrap(),
);
let us_uid_expunge = us_uid_flag.next().unwrap();
fixture
.cxn
.expunge_mailbox_messages(
unselectable_id,
&mut [us_uid_expunge].iter().copied(),
)
.unwrap();
// Validate that it has in fact been expunged.
assert_matches!(
Err(Error::NxMessage),
fixture
.cxn
.fetch_raw_mailbox_message(unselectable_id, us_uid_expunge),
);
assert_eq!(
Some(Modseq::of(4)),
fixture
.cxn
.fetch_mailbox_message_expunge_modseq(
unselectable_id,
us_uid_expunge
)
.unwrap(),
);
assert_eq!(
vec![us_uid_expunge],
fixture
.cxn
.fetch_vanished_mailbox_messages(
unselectable_id,
Modseq::of(3),
&mut |u| us_uid_expunge == u,
)
.unwrap(),
);
assert_eq!(
Vec::<Uid>::new(),
fixture
.cxn
.fetch_vanished_mailbox_messages(
unselectable_id,
Modseq::of(4),
&mut |u| us_uid_expunge == u,
)
.unwrap(),
);
assert_eq!(
Vec::<Uid>::new(),
fixture
.cxn
.fetch_vanished_mailbox_messages(
unselectable_id,
Modseq::of(3),
&mut |_| false,
)
.unwrap(),
);
let mut unselectable =
fixture.cxn.fetch_mailbox(unselectable_id).unwrap();
assert_eq!(Uid::u(3), unselectable.next_uid);
// Delete `unselectable`, making it `\Noselect`.
fixture.cxn.delete_mailbox(unselectable_id).unwrap();
unselectable = fixture.cxn.fetch_mailbox(unselectable_id).unwrap();
assert!(!unselectable.selectable);
assert_matches!(
Err(Error::NxMessage),
fixture
.cxn
.fetch_raw_mailbox_message(unselectable_id, us_uid_flag),
);
assert_eq!(
None,
fixture
.cxn
.fetch_mailbox_message_expunge_modseq(
unselectable_id,
us_uid_expunge
)
.unwrap()
);
// Now we can test all the expected failure modes of the message CRUD
// operations.
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.append_mailbox_messages(
unselectable_id,
&mut [(us_flag_mboxmsg.message_id, None)].iter().copied(),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.append_mailbox_messages(
MailboxId(999),
&mut [(us_flag_mboxmsg.message_id, None)].iter().copied(),
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.intern_and_append_mailbox_messages(
unselectable_id,
&mut [("foo", None)].iter().copied(),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.intern_and_append_mailbox_messages(
MailboxId(999),
&mut [("foo", None)].iter().copied(),
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.expunge_mailbox_messages(
unselectable_id,
&mut [us_uid_flag].iter().copied(),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.expunge_mailbox_messages(
MailboxId(999),
&mut [us_uid_flag].iter().copied(),
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.modify_mailbox_message_flags(
unselectable_id,
&SmallBitset::new(),
false,
false,
Modseq::MAX,
&mut [us_uid_flag].iter().copied(),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.modify_mailbox_message_flags(
MailboxId(999),
&SmallBitset::new(),
false,
false,
Modseq::MAX,
&mut [us_uid_flag].iter().copied(),
),
);
// Add a message to child by the two-step process, inserting them with
// initial flags (both near and far).
let child_init_flags = SmallBitset::from(vec![flags[0].0, flags[99].0]);
let child_msg_ids = fixture
.cxn
.intern_messages_as_orphans(
&mut ["foo", "bar", "baz"].iter().copied(),
)
.unwrap();
let child_msg_uid123 = fixture
.cxn
.append_mailbox_messages(
child_id,
&mut child_msg_ids
.iter()
.map(|&id| (id, Some(&child_init_flags))),
)
.unwrap();
let child_msg_uid4 = fixture
.cxn
.intern_and_append_mailbox_messages(
child_id,
&mut [("foo", Some(&child_init_flags))].iter().copied(),
)
.unwrap();
assert_eq!(Uid::u(1), child_msg_uid123);
assert_eq!(Uid::u(4), child_msg_uid4);
let child_mboxmsg1 = fixture
.cxn
.fetch_raw_mailbox_message(child_id, child_msg_uid123)
.unwrap();
let child_mboxmsg4 = fixture
.cxn
.fetch_raw_mailbox_message(child_id, child_msg_uid4)
.unwrap();
// Because messages 1 and 4 both have path "foo", they both have the
// same underlying message ID.
assert_eq!(child_mboxmsg1.message_id, child_mboxmsg4.message_id);
// Ensure all the flags were set properly.
assert_eq!(
child_init_flags,
fixture
.cxn
.fetch_mailbox_message_flags(child_id, child_msg_uid123)
.unwrap(),
);
assert_eq!(
child_init_flags,
fixture
.cxn
.fetch_mailbox_message_flags(
child_id,
child_msg_uid123.next().unwrap()
)
.unwrap(),
);
assert_eq!(
child_init_flags,
fixture
.cxn
.fetch_mailbox_message_flags(child_id, child_msg_uid4)
.unwrap(),
);
// Brute-force various operations with every flag we've defined
// combining with known near- and far-flags to exercise every path in
// modify_mailbox_message_flags and check the boundary conditions.
for &FlagId(flag) in &flags[1..99] {
let uid = child_msg_uid123;
// Clear the flags left over from prior code.
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::new(),
false,
true,
Modseq::MAX,
&mut [uid].iter().copied(),
)
.unwrap();
macro_rules! read_modseq {
() => {
fixture
.cxn
.fetch_raw_mailbox_message(child_id, uid)
.unwrap()
.flags_modseq
};
}
macro_rules! read_flags {
() => {
fixture
.cxn
.fetch_mailbox_message_flags(child_id, uid)
.unwrap()
};
}
let start_modseq = read_modseq!();
// Set *just* the flag in question. This covers the fused update
// case where all conditions pass for near flags and the insertion
// case for far flags.
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![flag]),
false,
true,
start_modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
let mut modseq = read_modseq!();
assert!(modseq > start_modseq);
assert_eq!(SmallBitset::from(vec![flag]), read_flags!());
// Try clearing the flag, setting a near flag, setting a far flag,
// and clearing all flags with the old modseq. Nothing should
// happen. This covers the inline modseq case for near flags and
// the manual check for far flags.
for (flags, remove_listed, remove_unlisted) in vec![
(vec![flag], true, false),
(vec![flags[0].0], true, false),
(vec![flags[99].0], true, false),
(vec![], false, true),
] {
assert_eq!(
vec![StoreResult::PreconditionsFailed],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(flags),
remove_listed,
remove_unlisted,
start_modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
assert_eq!(modseq, read_modseq!());
assert_eq!(SmallBitset::from(vec![flag]), read_flags!());
}
// Setting the flag when it's already set does nothing, and the
// value of remove_unlisted changes nothing since there are no
// other flags. This partially covers the no-op check for near
// flags and fully covers the no-op checks for far flag insertion
// and bulk far flag removal.
for &remove_unlisted in &[false, true] {
assert_eq!(
vec![StoreResult::Nop],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![flag]),
false,
remove_unlisted,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
assert_eq!(modseq, read_modseq!());
assert_eq!(SmallBitset::from(vec![flag]), read_flags!());
}
// Toggling other flags leaves this one alone.
for &other_flag in &[flags[0].0, flags[99].0] {
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![other_flag]),
false,
false,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
"flag={flag}, other_flag={other_flag}",
);
let mut new_modseq = read_modseq!();
assert!(new_modseq > modseq);
modseq = new_modseq;
assert_eq!(
SmallBitset::from(vec![other_flag, flag]),
read_flags!(),
);
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![other_flag]),
true,
false,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
new_modseq = read_modseq!();
assert!(new_modseq > modseq);
modseq = new_modseq;
assert_eq!(SmallBitset::from(vec![flag]), read_flags!(),);
}
// Clearing another flag by remove_unlisted while re-setting the
// flag in question is detected as a change. This covers no-op
// detection for specific far flag removal and further tests the
// no-op detection for near flags.
for &other_flag in &[flags[0].0, flags[99].0] {
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![other_flag]),
false,
false,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
let mut new_modseq = read_modseq!();
assert!(new_modseq > modseq);
modseq = new_modseq;
assert_eq!(
SmallBitset::from(vec![other_flag, flag]),
read_flags!(),
);
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![flag]),
false,
true,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
new_modseq = read_modseq!();
assert!(new_modseq > modseq);
modseq = new_modseq;
assert_eq!(SmallBitset::from(vec![flag]), read_flags!(),);
}
// Clearing this flag when it's already clear is a no-op, even when
// other flags are present.
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![flags[0].0, flags[99].0]),
false,
true,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
let new_modseq = read_modseq!();
assert!(new_modseq > modseq);
modseq = new_modseq;
assert_eq!(
SmallBitset::from(vec![flags[0].0, flags[99].0]),
read_flags!(),
);
assert_eq!(
vec![StoreResult::Nop],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&SmallBitset::from(vec![flag]),
true,
false,
modseq,
&mut [uid].iter().copied(),
)
.unwrap(),
);
assert_eq!(modseq, read_modseq!());
assert_eq!(
SmallBitset::from(vec![flags[0].0, flags[99].0]),
read_flags!(),
);
}
// Set all the flags on a couple messages to ensure that mailbox
// deletion and message expungement handle the far flags.
let all_flags =
SmallBitset::from(flags.iter().map(|f| f.0).collect::<Vec<_>>());
assert_eq!(
vec![StoreResult::Modified; 3],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&all_flags,
false,
false,
Modseq::MAX,
&mut [
child_msg_uid123,
child_msg_uid123.next().unwrap(),
child_msg_uid4
]
.iter()
.copied(),
)
.unwrap(),
);
// Verify bulk-deletion of many flags. This is mainly a concern
// regarding syntax of dynamically-generated SQL.
assert_eq!(
vec![StoreResult::Modified],
fixture
.cxn
.modify_mailbox_message_flags(
child_id,
&all_flags,
true,
false,
Modseq::MAX,
&mut [child_msg_uid4].iter().copied(),
)
.unwrap(),
);
// Expunge a message with many flags. Also ensure that last_activity
// gets updated when expunged.
fixture
.cxn
.zero_message_last_activity(child_msg_ids[0])
.unwrap();
fixture
.cxn
.expunge_mailbox_messages(
child_id,
&mut [child_msg_uid123].iter().copied(),
)
.unwrap();
assert_ne!(
UnixTimestamp::zero(),
fixture
.cxn
.fetch_raw_message(child_msg_ids[0])
.unwrap()
.last_activity,
);
// Now we can verify that deleting everything works.
fixture.cxn.delete_mailbox(child_id).unwrap();
fixture.cxn.delete_mailbox(unselectable_id).unwrap();
assert!(fixture.cxn.fetch_all_mailboxes().unwrap().is_empty());
}
#[test]
fn test_message_copy_move() {
let mut fixture = Fixture::new();
let messages = fixture
.cxn
.intern_messages_as_orphans(
&mut ["a", "b", "c", "d", "e", "f"].iter().copied(),
)
.unwrap();
let copy_src = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "copy-src", None)
.unwrap();
let copy_dst = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "copy-dst", None)
.unwrap();
let move_dst = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "move-dst", None)
.unwrap();
let flags = (0..100)
.map(|id| {
fixture
.cxn
.intern_flag(&Flag::Keyword(format!("f{id}")))
.unwrap()
})
.collect::<Vec<_>>();
let all_flags_bitset = SmallBitset::from(
flags.iter().map(|&FlagId(ix)| ix).collect::<Vec<_>>(),
);
let msg1_uid = fixture
.cxn
.append_mailbox_messages(
copy_src,
&mut [
(messages[0], None),
(messages[1], None),
(messages[2], Some(&all_flags_bitset)),
(messages[3], None),
(messages[4], None),
]
.iter()
.copied(),
)
.unwrap();
assert_eq!(Uid::u(1), msg1_uid);
fixture
.cxn
.expunge_mailbox_messages(
copy_src,
&mut [Uid::u(4)].iter().copied(),
)
.unwrap();
// Also add an initial message to move_dst so that the copy part of the
// move produces slightly different results.
fixture
.cxn
.append_mailbox_messages(
move_dst,
&mut [(messages[5], None)].iter().copied(),
)
.unwrap();
let mut resp = fixture
.cxn
.copy_mailbox_messages(
copy_src,
&mut [Uid::u(1), Uid::u(3), Uid::u(4), Uid::u(5)]
.iter()
.copied(),
copy_dst,
)
.unwrap();
assert_eq!(
CopyResponse {
uid_validity: copy_dst.as_uid_validity().unwrap(),
from_uids: vec![Uid::u(1), Uid::u(3), Uid::u(5)].into(),
to_uids: vec![Uid::u(1), Uid::u(2), Uid::u(3)].into(),
},
resp,
);
resp = fixture
.cxn
.move_mailbox_messages(
copy_src,
[Uid::u(1), Uid::u(3), Uid::u(4), Uid::u(5)].iter().copied(),
move_dst,
)
.unwrap();
assert_eq!(
CopyResponse {
uid_validity: move_dst.as_uid_validity().unwrap(),
from_uids: vec![Uid::u(1), Uid::u(3), Uid::u(5)].into(),
to_uids: vec![Uid::u(2), Uid::u(3), Uid::u(4)].into(),
},
resp,
);
let mut selected = fixture.cxn.select(copy_src, false, None).unwrap();
// Only the one message we didn't move remains.
assert_eq!(
vec![InitialMessageStatus {
uid: Uid::u(2),
id: messages[1],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},],
selected.messages,
);
// 1 = init, 2 = append, 3 = expunge, 4 = move
assert_eq!(Modseq::of(4), selected.max_modseq);
selected = fixture.cxn.select(copy_dst, false, None).unwrap();
assert_eq!(
vec![
InitialMessageStatus {
uid: Uid::u(1),
id: messages[0],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(2),
id: messages[2],
flags: all_flags_bitset.clone(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(3),
id: messages[4],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
],
selected.messages,
);
selected = fixture.cxn.select(move_dst, false, None).unwrap();
assert_eq!(
vec![
InitialMessageStatus {
uid: Uid::u(1),
id: messages[5],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(2),
id: messages[0],
flags: SmallBitset::new(),
last_modified: Modseq::of(3),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(3),
id: messages[2],
flags: all_flags_bitset.clone(),
last_modified: Modseq::of(3),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(4),
id: messages[4],
flags: SmallBitset::new(),
last_modified: Modseq::of(3),
recent: true,
savedate: fixture.savedate,
},
],
selected.messages,
);
// Expunge a message from move_dst to create a UID hole.
fixture
.cxn
.expunge_mailbox_messages(
move_dst,
&mut [Uid::u(2)].iter().copied(),
)
.unwrap();
let rename_move_dst = fixture
.cxn
.move_all_mailbox_messages_into_create_hierarchy(
move_dst,
"rename-dst",
)
.unwrap();
selected = fixture.cxn.select(move_dst, false, None).unwrap();
assert!(selected.messages.is_empty());
selected = fixture.cxn.select(rename_move_dst, false, None).unwrap();
assert_eq!(
vec![
InitialMessageStatus {
uid: Uid::u(1),
id: messages[5],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(2),
id: messages[2],
flags: all_flags_bitset.clone(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(3),
id: messages[4],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
],
selected.messages,
);
// Copying with dst == src is allowed.
resp = fixture
.cxn
.copy_mailbox_messages(
rename_move_dst,
&mut [Uid::u(2)].iter().copied(),
rename_move_dst,
)
.unwrap();
assert_eq!(
CopyResponse {
uid_validity: rename_move_dst.as_uid_validity().unwrap(),
from_uids: vec![Uid::u(2)].into(),
to_uids: vec![Uid::u(4)].into(),
},
resp,
);
selected = fixture.cxn.select(rename_move_dst, false, None).unwrap();
assert_eq!(
vec![
InitialMessageStatus {
uid: Uid::u(1),
id: messages[5],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(2),
id: messages[2],
flags: all_flags_bitset.clone(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(3),
id: messages[4],
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: Uid::u(4),
id: messages[2],
flags: all_flags_bitset.clone(),
last_modified: Modseq::of(3),
recent: true,
savedate: fixture.savedate,
},
],
selected.messages,
);
let unselectable = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "unselectable", None)
.unwrap();
fixture
.cxn
.create_mailbox(unselectable, "plugh", None)
.unwrap();
fixture.cxn.delete_mailbox(unselectable).unwrap();
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.copy_mailbox_messages(
MailboxId(999),
&mut std::iter::empty(),
copy_dst,
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.copy_mailbox_messages(
copy_src,
&mut std::iter::empty(),
MailboxId(999),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.move_mailbox_messages(
MailboxId(999),
std::iter::empty(),
move_dst,
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.move_mailbox_messages(
copy_src,
std::iter::empty(),
MailboxId(999),
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.move_all_mailbox_messages_into_create_hierarchy(
MailboxId(999),
"other",
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.copy_mailbox_messages(
unselectable,
&mut std::iter::empty(),
copy_dst,
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.copy_mailbox_messages(
copy_src,
&mut std::iter::empty(),
unselectable,
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.move_mailbox_messages(
unselectable,
std::iter::empty(),
move_dst,
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.move_mailbox_messages(
copy_src,
std::iter::empty(),
unselectable,
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.move_all_mailbox_messages_into_create_hierarchy(
unselectable,
"other",
),
);
assert_matches!(
Err(Error::MoveIntoSelf),
fixture.cxn.move_mailbox_messages(
move_dst,
std::iter::empty(),
move_dst,
),
);
}
#[test]
fn test_message_cache_data() {
let mut fixture = Fixture::new();
let message_id = fixture
.cxn
.intern_messages_as_orphans(&mut ["foo"].iter().copied())
.unwrap()[0];
assert_eq!(
MessageAccessData {
path: "foo".to_owned(),
session_key: None,
rfc822_size: None,
},
fixture.cxn.access_message(message_id).unwrap(),
);
fixture
.cxn
.cache_message_data(
message_id,
SessionKey([3; crate::crypt::AES_BLOCK]),
1234,
)
.unwrap();
assert_eq!(
MessageAccessData {
path: "foo".to_owned(),
session_key: Some(SessionKey([3; crate::crypt::AES_BLOCK])),
rfc822_size: Some(1234),
},
fixture.cxn.access_message(message_id).unwrap(),
);
assert_matches!(
Err(Error::ExpungedMessage),
fixture.cxn.access_message(MessageId(-1)),
);
fixture
.cxn
.cache_message_data(
MessageId(-1),
SessionKey([3; crate::crypt::AES_BLOCK]),
1234,
)
.unwrap();
}
#[test]
fn test_orphaned_messages() {
let mut fixture = Fixture::new();
let inbox = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "INBOX", None)
.unwrap();
let messages = fixture
.cxn
.intern_messages_as_orphans(
&mut ["a", "b", "c", "d", "e", "f"].iter().copied(),
)
.unwrap();
for &message in &messages[3..] {
fixture.cxn.zero_message_last_activity(message).unwrap();
}
fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(messages[0], None), (messages[3], None)].iter().copied(),
)
.unwrap();
assert_eq!(
vec![(messages[4], "e".to_owned()), (messages[5], "f".to_owned()),],
fixture
.cxn
.fetch_orphaned_messages(UnixTimestamp(
DateTime::from_timestamp(42, 0).unwrap()
))
.unwrap(),
);
for &message in &messages {
fixture.cxn.forget_message(message).unwrap();
}
fixture.cxn.forget_message(MessageId(999)).unwrap();
for (ix, &message) in messages.iter().enumerate() {
assert_eq!(
0 == ix || 3 == ix,
fixture.cxn.fetch_raw_message(message).is_ok(),
"for index {ix}",
);
}
}
#[test]
fn test_select() {
let mut fixture = Fixture::new();
let inbox = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "INBOX", None)
.unwrap();
let message_id = fixture
.cxn
.intern_messages_as_orphans(&mut ["foo"].iter().copied())
.unwrap()[0];
let mut init_state = fixture.cxn.select(inbox, true, None).unwrap();
assert!(init_state.messages.is_empty());
assert_eq!(Uid::MIN, init_state.next_uid);
assert_eq!(Modseq::MIN, init_state.max_modseq);
assert!(init_state.qresync.is_none());
let msg1_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let msg2_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
// Read-only select: We'll get \Recent flags, but the next session will
// also see them.
init_state = fixture.cxn.select(inbox, false, None).unwrap();
assert_eq!(
vec![
InitialMessageStatus {
uid: msg1_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: Modseq::of(2),
recent: true,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: msg2_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: Modseq::of(3),
recent: true,
savedate: fixture.savedate,
},
],
init_state.messages,
);
assert_eq!(Uid::u(3), init_state.next_uid);
assert_eq!(Modseq::of(3), init_state.max_modseq);
init_state = fixture.cxn.select(inbox, true, None).unwrap();
assert!(init_state.messages.iter().all(|m| m.recent));
// Since we did a RW select, the next will not see anything as recent.
init_state = fixture.cxn.select(inbox, true, None).unwrap();
assert!(init_state.messages.iter().all(|m| !m.recent));
// Add a third message. Another select will then see that message alone
// as recent.
let msg3_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
init_state = fixture.cxn.select(inbox, true, None).unwrap();
assert!(!init_state.messages[0].recent);
assert!(!init_state.messages[1].recent);
assert!(init_state.messages[2].recent);
let before_msg_flags = init_state.max_modseq;
// Add a bunch of flags to messages 1 and 3, then verify we get all of
// them when selecting.
let flags = (0..100)
.map(|id| {
fixture
.cxn
.intern_flag(&Flag::Keyword(format!("f{id}")))
.unwrap()
})
.collect::<Vec<_>>();
let all_flags_bitset = SmallBitset::from(
flags.iter().map(|&FlagId(ix)| ix).collect::<Vec<_>>(),
);
fixture
.cxn
.modify_mailbox_message_flags(
inbox,
&all_flags_bitset,
false,
false,
Modseq::MAX,
&mut [msg1_uid, msg3_uid].iter().copied(),
)
.unwrap();
init_state = fixture.cxn.select(inbox, false, None).unwrap();
assert_eq!(all_flags_bitset, init_state.messages[0].flags);
assert_eq!(SmallBitset::new(), init_state.messages[1].flags);
assert_eq!(all_flags_bitset, init_state.messages[2].flags);
let after_msg_flags = init_state.max_modseq;
let msg4_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let msg5_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
// Expunge a couple messages separately for the qresync tests.
fixture
.cxn
.expunge_mailbox_messages(inbox, &mut [msg4_uid].iter().copied())
.unwrap();
let before_expunge_2 =
fixture.cxn.fetch_mailbox(inbox).unwrap().max_modseq;
fixture
.cxn
.expunge_mailbox_messages(inbox, &mut [msg2_uid].iter().copied())
.unwrap();
let latest_modseq =
fixture.cxn.fetch_mailbox(inbox).unwrap().max_modseq;
// Qresync against the latest modseq returns nothing.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: latest_modseq,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![].into(),
changed: vec![],
}),
init_state.qresync,
);
assert!(init_state.qresync.as_ref().unwrap().expunged.is_empty());
assert!(init_state.qresync.as_ref().unwrap().changed.is_empty());
// Qresync with the wrong UID validity returns no response at all.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32 + 1,
resync_from: Modseq::MIN,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert!(init_state.qresync.is_none());
// Qresync from the init modseq returns all extant UIDs and both
// expunges (even though the UIDs for those expunges weren't known at
// that time).
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: Modseq::MIN,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![msg2_uid, msg4_uid].into(),
changed: vec![msg1_uid, msg3_uid, msg5_uid],
}),
init_state.qresync,
);
// If we specify a known UID range, we only get updates for things in
// that range.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: Modseq::MIN,
known_uids: Some(SeqRange::range(msg1_uid, msg3_uid)),
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![msg2_uid].into(),
changed: vec![msg1_uid, msg3_uid],
}),
init_state.qresync,
);
// Fetching with resync_from = before_msg_flags, we'll get told about
// msg1 and msg3 because of the flags change, even though they already
// existed.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: before_msg_flags,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![msg2_uid, msg4_uid].into(),
changed: vec![msg1_uid, msg3_uid, msg5_uid],
}),
init_state.qresync,
);
// But with resync_from = after_msg_flags, there were no further
// updates to 1 and 3, so we don't see those.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: after_msg_flags,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![msg2_uid, msg4_uid].into(),
changed: vec![msg5_uid],
}),
init_state.qresync,
);
// With resync_from = before_expunge_2, the only change is the
// expungement of message 2.
init_state = fixture
.cxn
.select(
inbox,
false,
Some(&QresyncRequest {
uid_validity: inbox.0 as u32,
resync_from: before_expunge_2,
known_uids: None,
mapping_reference: None,
}),
)
.unwrap();
assert_eq!(
Some(QresyncResponse {
expunged: vec![msg2_uid].into(),
changed: vec![],
}),
init_state.qresync,
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.select(MailboxId(999), false, None),
);
let unselectable = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "unselectable", None)
.unwrap();
fixture
.cxn
.create_mailbox(unselectable, "child", None)
.unwrap();
fixture.cxn.delete_mailbox(unselectable).unwrap();
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.select(unselectable, false, None),
);
}
#[test]
fn test_poll() {
let mut fixture = Fixture::new();
let inbox = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "INBOX", None)
.unwrap();
macro_rules! read_modseq {
() => {
fixture.cxn.fetch_mailbox(inbox).unwrap().max_modseq
};
}
let message_id = fixture
.cxn
.intern_messages_as_orphans(&mut ["foo"].iter().copied())
.unwrap()[0];
let msg1_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let after_insert_msg1 = read_modseq!();
let msg2_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let msg3_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let baseline_modseq = read_modseq!();
let msg4_uid = fixture
.cxn
.append_mailbox_messages(
inbox,
&mut [(message_id, None)].iter().copied(),
)
.unwrap();
let after_insert_msg4 = read_modseq!();
fixture
.cxn
.expunge_mailbox_messages(inbox, &mut [msg2_uid].iter().copied())
.unwrap();
let after_expunge_msg2 = read_modseq!();
let flags = (0..100)
.map(|id| {
fixture
.cxn
.intern_flag(&Flag::Keyword(format!("f{id}")))
.unwrap()
})
.collect::<Vec<_>>();
let all_flags_bitset = SmallBitset::from(
flags.iter().map(|&FlagId(ix)| ix).collect::<Vec<_>>(),
);
fixture
.cxn
.modify_mailbox_message_flags(
inbox,
&all_flags_bitset,
false,
false,
Modseq::MAX,
&mut [msg3_uid].iter().copied(),
)
.unwrap();
let after_msg3_flags = read_modseq!();
// Mini poll from baseline_modseq --- we learn about message 3's new
// flags but nothing else. The snapshot is marked as divergent and the
// snapshot modseq remains at baseline_modseq.
let mut mini_poll = fixture
.cxn
.mini_poll(
inbox,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
baseline_modseq,
)
.unwrap();
assert_eq!(
MiniPoll {
new_flags: vec![],
updated_messages: vec![UpdatedMessageStatus {
uid: msg3_uid,
last_modified: after_msg3_flags,
flags: all_flags_bitset.clone(),
},],
snapshot_modseq: baseline_modseq,
diverged: true,
has_pending_expunge: true,
},
mini_poll,
);
// With the same parameters, a full poll discovers the new message and
// the expungement.
let mut full_poll = fixture
.cxn
.full_poll(
inbox,
false,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
baseline_modseq,
)
.unwrap();
assert_eq!(
FullPoll {
new_flags: vec![],
updated_messages: vec![UpdatedMessageStatus {
uid: msg3_uid,
last_modified: after_msg3_flags,
flags: all_flags_bitset.clone(),
},],
new_messages: vec![InitialMessageStatus {
uid: msg4_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: after_insert_msg4,
recent: true,
savedate: fixture.savedate,
},],
expunged: vec![msg2_uid],
snapshot_modseq: after_msg3_flags,
next_uid: Uid::u(5),
},
full_poll,
);
// Repeating the poll gives msg4 as recent again since the previous was
// read-only.
full_poll = fixture
.cxn
.full_poll(
inbox,
true,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
baseline_modseq,
)
.unwrap();
assert!(full_poll.new_messages[0].recent);
// But since that last one was RW, another discovery will not see it as
// recent.
full_poll = fixture
.cxn
.full_poll(
inbox,
true,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
baseline_modseq,
)
.unwrap();
assert!(!full_poll.new_messages[0].recent);
// Continuing the same sequence: max_message_modseq is now
// after_msg3_flags, but the snapshot is otherwise the same. We get no
// new information for mini_poll.
mini_poll = fixture
.cxn
.mini_poll(
inbox,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
after_msg3_flags,
)
.unwrap();
assert_eq!(
MiniPoll {
new_flags: vec![],
updated_messages: vec![],
snapshot_modseq: baseline_modseq,
diverged: true,
has_pending_expunge: true,
},
mini_poll,
);
// For full_poll, this is essentially continuing from the first
// mini_poll. We discover the new message and the expungement.
full_poll = fixture
.cxn
.full_poll(
inbox,
true,
*flags.last().unwrap(),
Some(msg3_uid),
baseline_modseq,
after_msg3_flags,
)
.unwrap();
assert_eq!(
FullPoll {
new_flags: vec![],
updated_messages: vec![],
new_messages: vec![InitialMessageStatus {
uid: msg4_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: after_insert_msg4,
recent: false,
savedate: fixture.savedate,
},],
expunged: vec![msg2_uid],
snapshot_modseq: after_msg3_flags,
next_uid: Uid::u(5),
},
full_poll,
);
// Mini poll from after_insert_msg4: this is the same as the baseline
// case, except that it's now an expunge blocking advancement of the
// snapshot modseq.
mini_poll = fixture
.cxn
.mini_poll(
inbox,
*flags.last().unwrap(),
Some(msg4_uid),
after_insert_msg4,
after_insert_msg4,
)
.unwrap();
assert_eq!(
MiniPoll {
new_flags: vec![],
updated_messages: vec![UpdatedMessageStatus {
uid: msg3_uid,
last_modified: after_msg3_flags,
flags: all_flags_bitset.clone(),
},],
snapshot_modseq: after_insert_msg4,
diverged: true,
has_pending_expunge: true,
},
mini_poll,
);
// Mini poll from after_expunge_msg2: since there's only flag changes
// beyond, the whole snapshot advances and is not divergent.
mini_poll = fixture
.cxn
.mini_poll(
inbox,
*flags.last().unwrap(),
Some(msg4_uid),
after_expunge_msg2,
after_expunge_msg2,
)
.unwrap();
assert_eq!(
MiniPoll {
new_flags: vec![],
updated_messages: vec![UpdatedMessageStatus {
uid: msg3_uid,
last_modified: after_msg3_flags,
flags: all_flags_bitset.clone(),
},],
snapshot_modseq: after_msg3_flags,
diverged: false,
has_pending_expunge: false,
},
mini_poll,
);
// Mini-polling from the primordial state returns no data.
mini_poll = fixture
.cxn
.mini_poll(
inbox,
*flags.last().unwrap(),
None,
Modseq::MIN,
Modseq::MIN,
)
.unwrap();
assert_eq!(
MiniPoll {
new_flags: vec![],
updated_messages: vec![],
snapshot_modseq: Modseq::MIN,
diverged: true,
has_pending_expunge: true,
},
mini_poll,
);
// Full-polling from the primordial state returns all data.
full_poll = fixture
.cxn
.full_poll(
inbox,
true,
*flags.last().unwrap(),
None,
Modseq::MIN,
Modseq::MIN,
)
.unwrap();
assert_eq!(
FullPoll {
new_flags: vec![],
updated_messages: vec![],
new_messages: vec![
InitialMessageStatus {
uid: msg1_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: after_insert_msg1,
recent: false,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: msg3_uid,
id: message_id,
flags: all_flags_bitset.clone(),
last_modified: after_msg3_flags,
recent: false,
savedate: fixture.savedate,
},
InitialMessageStatus {
uid: msg4_uid,
id: message_id,
flags: SmallBitset::new(),
last_modified: after_insert_msg4,
recent: false,
savedate: fixture.savedate,
},
],
expunged: vec![msg2_uid],
snapshot_modseq: after_msg3_flags,
next_uid: Uid::u(5),
},
full_poll,
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.mini_poll(
MailboxId(999),
FlagId(0),
None,
Modseq::MIN,
Modseq::MIN,
),
);
assert_matches!(
Err(Error::NxMailbox),
fixture.cxn.full_poll(
MailboxId(999),
true,
FlagId(0),
None,
Modseq::MIN,
Modseq::MIN,
),
);
let unselectable = fixture
.cxn
.create_mailbox(MailboxId::ROOT, "unselectable", None)
.unwrap();
fixture
.cxn
.create_mailbox(unselectable, "child", None)
.unwrap();
fixture.cxn.delete_mailbox(unselectable).unwrap();
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.mini_poll(
unselectable,
FlagId(0),
None,
Modseq::MIN,
Modseq::MIN,
),
);
assert_matches!(
Err(Error::MailboxUnselectable),
fixture.cxn.full_poll(
unselectable,
true,
FlagId(0),
None,
Modseq::MIN,
Modseq::MIN,
),
);
}
#[test]
fn message_spool_crud() {
let mut fixture = Fixture::new();
let message_id = fixture
.cxn
.intern_messages_as_orphans(&mut ["foo"].iter().copied())
.unwrap()[0];
let orphaned_thresh =
UnixTimestamp(Utc::now() + Duration::from_secs(60));
// Initially orphaned
assert!(!fixture
.cxn
.fetch_orphaned_messages(orphaned_thresh)
.unwrap()
.is_empty());
assert_eq!(None, fixture.cxn.fetch_message_spool(message_id).unwrap());
let mut message_spool = MessageSpool {
message_id,
transfer: SmtpTransfer::SevenBit,
expires: UnixTimestamp(DateTime::from_timestamp(42, 0).unwrap()),
mail_from: "foo@example.com".to_owned(),
destinations: vec![
"bar@example.net".to_owned(),
"baz@example.net".to_owned(),
],
};
fixture.cxn.insert_message_spool(&message_spool).unwrap();
// Being in the spool prevents it from being classified as an orphan.
assert!(fixture
.cxn
.fetch_orphaned_messages(orphaned_thresh)
.unwrap()
.is_empty());
assert_eq!(
message_spool,
fixture
.cxn
.fetch_message_spool(message_id)
.unwrap()
.unwrap(),
);
fixture
.cxn
.delete_message_spool_destinations(
message_id,
&mut std::iter::once("baz@example.net"),
)
.unwrap();
message_spool.destinations.remove(1);
assert_eq!(
message_spool,
fixture
.cxn
.fetch_message_spool(message_id)
.unwrap()
.unwrap(),
);
fixture
.cxn
.delete_message_spool_destinations(
message_id,
&mut std::iter::once("bar@example.net"),
)
.unwrap();
assert_eq!(None, fixture.cxn.fetch_message_spool(message_id).unwrap(),);
// Now the message is an orphan since the message spool was deleted.
assert!(!fixture
.cxn
.fetch_orphaned_messages(orphaned_thresh)
.unwrap()
.is_empty());
fixture.cxn.insert_message_spool(&message_spool).unwrap();
assert_eq!(
message_spool,
fixture
.cxn
.fetch_message_spool(message_id)
.unwrap()
.unwrap(),
);
fixture
.cxn
.delete_expired_message_spools(UnixTimestamp(
DateTime::from_timestamp(1, 0).unwrap(),
))
.unwrap();
assert_eq!(
message_spool,
fixture
.cxn
.fetch_message_spool(message_id)
.unwrap()
.unwrap(),
);
fixture
.cxn
.delete_expired_message_spools(UnixTimestamp(
DateTime::from_timestamp(100, 0).unwrap(),
))
.unwrap();
assert_eq!(None, fixture.cxn.fetch_message_spool(message_id).unwrap(),);
}
#[test]
fn tls_status_crud() {
let mut fixture = Fixture::new();
assert_eq!(
None,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.com")
.unwrap()
);
let mut example_com = ForeignSmtpTlsStatus {
domain: "example.com".to_owned(),
starttls: false,
valid_certificate: false,
tls_version: None,
};
let example_net = ForeignSmtpTlsStatus {
domain: "example.net".to_owned(),
starttls: true,
valid_certificate: true,
tls_version: Some(TlsVersion::Ssl3),
};
fixture
.cxn
.put_foreign_smtp_tls_status(&example_com)
.unwrap();
fixture
.cxn
.put_foreign_smtp_tls_status(&example_net)
.unwrap();
assert_eq!(
example_com,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.com")
.unwrap()
.unwrap(),
);
assert_eq!(
example_net,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.net")
.unwrap()
.unwrap(),
);
example_com.starttls = true;
for tls_version in [
TlsVersion::Tls10,
TlsVersion::Tls11,
TlsVersion::Tls12,
TlsVersion::Tls13,
] {
example_com.tls_version = Some(tls_version);
fixture
.cxn
.put_foreign_smtp_tls_status(&example_com)
.unwrap();
assert_eq!(
example_com,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.com")
.unwrap()
.unwrap(),
);
}
fixture
.cxn
.delete_foreign_smtp_tls_status("example.com")
.unwrap();
assert_eq!(
None,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.com")
.unwrap(),
);
assert_eq!(
example_net,
fixture
.cxn
.fetch_foreign_smtp_tls_status("example.net")
.unwrap()
.unwrap(),
);
}
}