summaryrefslogtreecommitdiff
path: root/src/syncevo/SyncContext.cpp
blob: a0344fa366004fe680e9b6aecd372cbea69b6a90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
/*
 * Copyright (C) 2005-2009 Patrick Ohly <patrick.ohly@gmx.de>
 * Copyright (C) 2009 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
#include <dlfcn.h>

#include <syncevo/SyncContext.h>
#include <syncevo/SyncSource.h>
#include <syncevo/util.h>
#include <syncevo/SuspendFlags.h>
#include <syncevo/ThreadSupport.h>

#include <syncevo/SafeConfigNode.h>
#include <syncevo/IniConfigNode.h>

#include <syncevo/LogStdout.h>
#include <syncevo/TransportAgent.h>
#include <syncevo/CurlTransportAgent.h>
#include <syncevo/SoupTransportAgent.h>
#include <syncevo/ObexTransportAgent.h>
#include <syncevo/LocalTransportAgent.h>

#include <list>
#include <memory>
#include <vector>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <ctime>
using namespace std;

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/bind.hpp>
#include <boost/utility.hpp>

#include <sys/stat.h>
#include <sys/wait.h>
#include <pwd.h>
#include <unistd.h>
#include <signal.h>
#include <dirent.h>
#include <errno.h>
#include <pthread.h>
#include <signal.h>

#include <synthesis/enginemodulebridge.h>
#include <synthesis/SDK_util.h>
#include <synthesis/san.h>

#include "test.h"

#include <syncevo/declarations.h>
SE_BEGIN_CXX

SyncContext *SyncContext::m_activeContext;

static const char *LogfileBasename = "syncevolution-log";

SyncContext::SyncContext()
{
    init();
}

SyncContext::SyncContext(const string &server,
                         bool doLogging) :
    SyncConfig(server),
    m_server(server)
{
    init();
    m_doLogging = doLogging;
}

SyncContext::SyncContext(const string &client,
                         const string &server,
                         const string &rootPath,
                         const boost::shared_ptr<TransportAgent> &agent,
                         bool doLogging) :
    SyncConfig(client,
               boost::shared_ptr<ConfigTree>(),
               rootPath),
    m_server(client),
    m_localClientRootPath(rootPath),
    m_agent(agent)
{
    init();
    initLocalSync(server);
    m_doLogging = doLogging;
}

void SyncContext::initLocalSync(const string &config)
{
    m_localSync = true;
    string tmp;
    splitConfigString(config, tmp, m_localPeerContext);
    m_localPeerContext.insert(0, "@");
}

void SyncContext::init()
{
    m_doLogging = false;
    m_quiet = false;
    m_dryrun = false;
    m_localSync = false;
    m_serverMode = false;
    m_serverAlerted = false;
    m_configNeeded = true;
    m_firstSourceAccess = true;
    m_remoteInitiated = false;
    m_sourceListPtr = NULL;
}

SyncContext::~SyncContext()
{
}

/**
 * Utility code for parsing and comparing
 * log dir names. Also a binary predicate for
 * sorting them.
 */
class LogDirNames {
public:
    // internal prefix for backup directory name: "SyncEvolution-"
    static const char* const DIR_PREFIX;

    /**
     * Compare two directory by its creation time encoded
     * in the directory name sort them in ascending order
     */
    bool operator() (const string &str1, const string &str2) {
        string iDirPath1, iStr1;
        string iDirPath2, iStr2;
        parseLogDir(str1, iDirPath1, iStr1);
        parseLogDir(str2, iDirPath2, iStr2);
        string dirPrefix1, peerName1, dateTime1;
        parseDirName(iStr1, dirPrefix1, peerName1, dateTime1);
        string dirPrefix2, peerName2, dateTime2;
        parseDirName(iStr2, dirPrefix2, peerName2, dateTime2);
        return dateTime1 < dateTime2;
    }

    /**
     * extract backup directory name from a full backup path
     * for example, a full path "/home/xxx/.cache/syncevolution/default/funambol-2009-12-08-14-05"
     * is parsed as "/home/xxx/.cache/syncevolution/default" and "funambol-2009-12-08-14-05"
     */
    static void parseLogDir(const string &fullpath, string &dirPath, string &dirName) {
        string iFullpath = boost::trim_right_copy_if(fullpath, boost::is_any_of("/"));
        size_t off = iFullpath.find_last_of('/');
        if(off != iFullpath.npos) {
            dirPath = iFullpath.substr(0, off);
            dirName = iFullpath.substr(off+1);
        } else {
            dirPath = "";
            dirName = iFullpath;
        }
    }

    // escape '-' and '_' for peer name 
    static string escapePeer(const string &prefix) {
        string escaped = prefix;
        boost::replace_all(escaped, "_", "__");
        boost::replace_all(escaped, "-", "_+");
        return escaped;
    }

    // un-escape '_+' and '__' for peer name 
    static string unescapePeer(const string &escaped) {
        string prefix = escaped;
        boost::replace_all(prefix, "_+", "-");
        boost::replace_all(prefix, "__", "_");
        return prefix;
    }

    /**
     * parse a directory name into dirPrefix(empty or DIR_PREFIX), peerName, dateTime.
     * peerName must be unescaped by the caller to get the real string.
     * If directory name is in the format of '[DIR_PREFIX]-peer[@context]-year-month-day-hour-min'
     * then parsing is sucessful and these 3 strings are correctly set and true is returned. 
     * Otherwise, false is returned. 
     * Here we don't check whether the dir name is matching peer name
     */
    static bool parseDirName(const string &dir, string &dirPrefix, string &config, string &dateTime) {
        string iDir = dir;
        if (!boost::starts_with(iDir, DIR_PREFIX)) {
            dirPrefix = "";
        } else {
            dirPrefix = DIR_PREFIX;
            boost::erase_first(iDir, DIR_PREFIX);
        }
        size_t off = iDir.find('-');
        if (off != iDir.npos) {
            config = iDir.substr(0, off);
            dateTime = iDir.substr(off);
            // m_prefix doesn't contain peer name or it equals with dirPrefix plus peerName
            return checkDirName(dateTime);
        }
        return false;
    }

    // check the dir name is conforming to what format we write
    static bool checkDirName(const string& value) {
        const char* str = value.c_str();
        /** need check whether string after prefix is a valid date-time we wrote, format
         * should be -YYYY-MM-DD-HH-MM and optional sequence number */
        static char table[] = {'-','9','9','9','9', //year
                               '-','1','9', //month
                               '-','3','9', //date
                               '-','2','9', //hour
                               '-','5','9'  //minute
        };
        for(size_t i = 0; i < sizeof(table)/sizeof(table[0]) && *str; i++,str++) {
            switch(table[i]) {
                case '-':
                    if(*str != '-')
                        return false;
                    break;
                case '1':
                    if(*str < '0' || *str > '1')
                        return false;
                    break;
                case '2':
                    if(*str < '0' || *str > '2')
                        return false;
                    break;
                case '3':
                    if(*str < '0' || *str > '3')
                        return false;
                    break;
                case '5':
                    if(*str < '0' || *str > '5')
                        return false;
                    break;
                case '9':
                    if(*str < '0' || *str > '9')
                        return false;
                    break;
                default:
                    return false;
            };
        }
        return true;
    }
};

class LogDir;

/**
 * Helper class for LogDir: acts as proxy for logging into
 * the LogDir's reports and log file.
 */
class LogDirLogger : public Logger
{
    Logger::Handle m_parentLogger;     /**< the logger which was active before we started to intercept messages */
    boost::weak_ptr<LogDir> m_logdir;  /**< grants access to report and Synthesis engine */

public:
    LogDirLogger(const boost::weak_ptr<LogDir> &logdir);
    virtual void remove() throw ();
    virtual void messagev(const MessageOptions &options,
                          const char *format,
                          va_list args);
};

// This class owns the logging directory. It is responsible
// for redirecting output at the start and end of sync (even
// in case of exceptions thrown!).
class LogDir : private boost::noncopyable, private LogDirNames {
    SyncContext &m_client;
    string m_logdir;         /**< configured backup root dir */
    int m_maxlogdirs;        /**< number of backup dirs to preserve, 0 if unlimited */
    string m_prefix;         /**< common prefix of backup dirs */
    string m_path;           /**< path to current logging and backup dir */
    string m_logfile;        /**< Path to log file there, empty if not writing one.
                                  The file is no longer written by this class, nor
                                  does it control the basename of it. Writing the
                                  log file is enabled by the XML configuration that
                                  we prepare for the Synthesis engine; the base name
                                  of the file is hard-coded in the engine. Despite
                                  that this class still is the central point to ask
                                  for the name of the log file. */
    boost::scoped_ptr<SafeConfigNode> m_info;  /**< key/value representation of sync information */

    // Access to m_report and m_client must be thread-safe as soon as
    // LogDirLogger is active, because they are shared between main
    // thread and any thread which might log errors.
    friend class LogDirLogger;
    bool m_readonly;         /**< m_info is not to be written to */
    SyncReport *m_report;    /**< record start/end times here */

    boost::weak_ptr<LogDir> m_self;
    PushLogger<LogDirLogger> m_logger; /**< active logger */

    LogDir(SyncContext &client) : m_client(client), m_info(NULL), m_readonly(false), m_report(NULL)
    {
        // Set default log directory. This will be overwritten with a user-specified
        // location later on, if one was selected by the user. SyncEvolution >= 0.9 alpha
        // and < 0.9 beta 2 used XDG_DATA_HOME because the logs and data base dumps
        // were not considered "non-essential data files". Because XDG_DATA_HOME is
        // searched for .desktop files and creating large amounts of other files there
        // slows down that search, the default was changed to XDG_CACHE_DIR.
        //
        // To migrate old installations seamlessly, this code here renames the old
        // default directory to the new one. Errors (like not found) are silently ignored.
        mkdir_p(SubstEnvironment("${XDG_CACHE_HOME}").c_str());
        rename(SubstEnvironment("${XDG_DATA_HOME}/applications/syncevolution").c_str(),
               SubstEnvironment("${XDG_CACHE_HOME}/syncevolution").c_str());

        string path = m_client.getLogDir();
        if (path.empty()) {
            path = "${XDG_CACHE_HOME}/syncevolution";
        }
        setLogdir(path);
    }

public:
    static boost::shared_ptr<LogDir> create(SyncContext &client)
    {
        boost::shared_ptr<LogDir> logdir(new LogDir(client));
        logdir->m_self = logdir;
        return logdir;
    }

    /**
     * Finds previous log directories for context. Reports errors via exceptions.
     *
     * @retval dirs       vector of full path names, oldest first
     */
    void previousLogdirs(vector<string> &dirs) {
        dirs.clear();
        getLogdirs(dirs);
    }

    /**
     * Finds previous log directory. Returns empty string if anything went wrong.
     *
     * @param path        path to configured backup directy, NULL if defaulting to /tmp, "none" if not creating log file
     * @return full path of previous log directory, empty string if not found
     */
    string previousLogdir() throw() {
        try {
            vector<string> dirs;
            previousLogdirs(dirs);
            return dirs.empty() ? "" : dirs.back();
        } catch (...) {
            Exception::handle();
            return "";
        }
    }

    /**
     * Set log dir and base name used for searching and creating sessions.
     * Default if not called is the getLogDir() value of the context.
     *
     * @param logdir     "none" to disable sessions, "" for default, may contain ${}
     *                   for environment variables
     */
    void setLogdir(const string &logdir) {
        if (logdir.empty()) {
            return;
        }
        m_logdir = SubstEnvironment(logdir);
        m_logdir = boost::trim_right_copy_if(m_logdir, boost::is_any_of("/"));
        if (m_logdir == "none") {
            return;
        }

        // the config name has been normalized
        string peer = m_client.getConfigName();

        // escape "_" and "-" the peer name
        peer = escapePeer(peer);

        if (boost::iends_with(m_logdir, "syncevolution")) {
            // use just the server name as prefix
            m_prefix = peer;
        } else {
            // SyncEvolution-<server>-<yyyy>-<mm>-<dd>-<hh>-<mm>
            m_prefix = DIR_PREFIX;
            m_prefix += peer;
        }
    }

    /**
     * access existing log directory to extract status information
     */
    void openLogdir(const string &dir) {
        boost::shared_ptr<ConfigNode> filenode(new IniFileConfigNode(dir, "status.ini", true));
        m_info.reset(new SafeConfigNode(filenode));
        m_info->setMode(false);
        m_readonly = true;
    }
    /*
     * get the corresponding peer name encoded in the logging dir name.
     * The dir name must match the format(see startSession). Otherwise,
     * empty string is returned.
     */
    string getPeerNameFromLogdir(const string &dir) {
        // extract the dir name from the fullpath
        string iDirPath, iDirName;
        parseLogDir(dir, iDirPath, iDirName);
        // extract the peer name from the dir name
        string dirPrefix, peerName, dateTime;
        if(parseDirName(iDirName, dirPrefix, peerName, dateTime)) {
            return unescapePeer(peerName);
        }
        return "";
    }

    /**
     * read sync report for session selected with openLogdir()
     */
    void readReport(SyncReport &report) {
        report.clear();
        if (!m_info) {
            return;
        }
        *m_info >> report;
    }

    /**
     * write sync report for current session
     */
    void writeReport(SyncReport &report) {
        if (m_info) {
            *m_info << report;

            /* write in slightly different format and flush at the end */
            writeTimestamp("start", report.getStart(), false);
            writeTimestamp("end", report.getEnd(), true);
        }
    }

    enum SessionMode {
        SESSION_USE_PATH,      /**< write directly into path, don't create and manage subdirectories */
        SESSION_READ_ONLY,     /**< access an existing session directory identified with path */
        SESSION_CREATE         /**< create a new session directory inside the given path */
    };

    // setup log directory and redirect logging into it
    // @param path        path to configured backup directy, empty for using default, "none" if not creating log file
    // @param mode        determines how path is interpreted and which session is accessed
    // @param maxlogdirs  number of backup dirs to preserve in path, 0 if unlimited
    // @param logLevel    0 = default, 1 = ERROR, 2 = INFO, 3 = DEBUG
    // @param report      record information about session here (may be NULL)
    void startSession(const string &path, SessionMode mode, int maxlogdirs, int logLevel, SyncReport *report) {
        m_maxlogdirs = maxlogdirs;
        m_report = report;
        m_logfile = "";
        if (boost::iequals(path, "none")) {
            m_path = "";
        } else {
            setLogdir(path);
            if (mode == SESSION_CREATE) {
                // create unique directory name in the given directory
                time_t ts = time(NULL);
                struct tm tmbuffer;
                struct tm *tm = localtime_r(&ts, &tmbuffer);
                if (!tm) {
                    SE_THROW("localtime_r() failed");
                }
                stringstream base;
                base << "-"
                     << setfill('0')
                     << setw(4) << tm->tm_year + 1900 << "-"
                     << setw(2) << tm->tm_mon + 1 << "-"
                     << setw(2) << tm->tm_mday << "-"
                     << setw(2) << tm->tm_hour << "-"
                     << setw(2) << tm->tm_min;
                // If other sessions, regardless of which peer, have
                // the same date and time, then append a sequence
                // number to ensure correct sorting. Solve this by
                // finding the maximum sequence number for any kind of
                // date time. Backwards running clocks or changing the
                // local time will still screw our ordering, though.
                typedef std::map<string, int> SeqMap_t;
                SeqMap_t dateTimes2Seq;
                if (isDir(m_logdir)) {
                    ReadDir dir(m_logdir);
                    BOOST_FOREACH(const string &entry, dir) {
                        string dirPrefix, peerName, dateTime;
                        if (parseDirName(entry, dirPrefix, peerName, dateTime)) {
                            // dateTime = -2010-01-31-12-00[-rev]
                            size_t off = 0;
                            for (int i = 0; off != dateTime.npos && i < 5; i++) {
                                off = dateTime.find('-', off + 1);
                            }
                            int sequence;
                            if (off != dateTime.npos) {
                                sequence = dateTime[off + 1] - 'a';
                                dateTime.resize(off);
                            } else {
                                sequence = -1;
                            }
                            pair <SeqMap_t::iterator, bool> entry = dateTimes2Seq.insert(make_pair(dateTime, sequence));
                            if (sequence > entry.first->second) {
                                entry.first->second = sequence;
                            }
                        }
                    }
                }
                stringstream path;
                path << base.str();
                SeqMap_t::iterator it = dateTimes2Seq.find(path.str());
                if (it != dateTimes2Seq.end()) {
                    path << "-" << (char)('a' + it->second + 1);
                }
                m_path = m_logdir + "/";
                m_path += m_prefix;
                m_path += path.str();
                mkdir_p(m_path);
            } else {
                m_path = m_logdir;
                if (mkdir(m_path.c_str(), S_IRWXU) &&
                    errno != EEXIST) {
                    SE_LOG_DEBUG(NULL, "%s: %s", m_path.c_str(), strerror(errno));
                    SyncContext::throwError(m_path, errno);
                }
            }
            m_logfile = m_path + "/" + LogfileBasename + ".html";
        }

        // update log level of default logger and our own replacement
        Logger::Level level;
        switch (logLevel) {
        case 0:
            // default for console output
            level = Logger::INFO;
            break;
        case 1:
            level = Logger::ERROR;
            break;
        case 2:
            level = Logger::INFO;
            break;
        default:
            if (m_logfile.empty() || getenv("SYNCEVOLUTION_DEBUG")) {
                // no log file or user wants to see everything:
                // print all information to the console
                level = Logger::DEBUG;
            } else {
                // have log file: avoid excessive output to the console,
                // full information is in the log file
                level = Logger::INFO;
            }
            break;
        }
        if (mode != SESSION_USE_PATH) {
            Logger::instance().setLevel(level);
        }
        boost::shared_ptr<Logger> logger(new LogDirLogger(m_self));
        logger->setLevel(level);
        m_logger.reset(logger);

        time_t start = time(NULL);
        if (m_report) {
            m_report->setStart(start);
        }
        m_readonly = mode == SESSION_READ_ONLY;
        if (!m_path.empty()) {
            boost::shared_ptr<ConfigNode> filenode(new IniFileConfigNode(m_path, "status.ini", m_readonly));
            m_info.reset(new SafeConfigNode(filenode));
            m_info->setMode(false);
            if (mode != SESSION_READ_ONLY) {
                // Create a status.ini which contains an error.
                // Will be overwritten later on, unless we crash.
                m_info->setProperty("status", STATUS_DIED_PREMATURELY);
                m_info->setProperty("error", InitStateString("synchronization process died prematurely", true));
                writeTimestamp("start", start);
            }
        }
    }

    /** sets a fixed directory for database files without redirecting logging */
    void setPath(const string &path) { m_path = path; }

    // return log directory, empty if not enabled
    const string &getLogdir() {
        return m_path;
    }

    // return log file, empty if not enabled
    const string &getLogfile() {
        return m_logfile;
    }

    /**
     * remove backup dir(s) if exceeding limit
     *
     * Assign a priority to each session dir, with lower
     * meaning "less important". Then sort by priority and (if
     * equal) creation time (aka index) in ascending
     * order. The sessions at the beginning of the sorted
     * vector are then removed first.
     *
     * DUMPS = any kind of database dump was made
     * ERROR = session failed
     * CHANGES = local data modified since previous dump (based on dumps
     *           of the current peer, for simplicity reasons),
     *           dump created for the first time,
     *           changes made during sync (detected with dumps and statistics)
     *
     * The goal is to preserve as many database dumps as possible
     * and ideally those where something happened.
     *
     * Some criteria veto the removal of a session:
     * - it is the only one holding a dump of a specific source
     * - it is the last session
     */
    void expire() {
        if (m_logdir.size() && m_maxlogdirs > 0 ) {
            vector<string> dirs;
            getLogdirs(dirs);

            /** stores priority and index in "dirs"; after sorting, delete from the start */
            vector< pair<Priority, size_t> > victims;
            /** maps from source name to list of information about dump, oldest first */
            typedef map< string, list<DumpInfo> > Dumps_t;
            Dumps_t dumps;
            for (size_t i = 0;
                 i < dirs.size();
                 i++) {
                bool changes = false;
                bool havedumps = false;
                bool errors = false;

                LogDir logdir(m_client);
                logdir.openLogdir(dirs[i]);
                SyncReport report;
                logdir.readReport(report);
                SyncMLStatus status = report.getStatus();
                if (status != STATUS_OK && status != STATUS_HTTP_OK) {
                    errors = true;
                }
                BOOST_FOREACH(SyncReport::SourceReport_t source, report) {
                    string &sourcename = source.first;
                    SyncSourceReport &sourcereport = source.second;
                    list<DumpInfo> &dumplist = dumps[sourcename];
                    if (sourcereport.m_backupBefore.isAvailable() ||
                        sourcereport.m_backupAfter.isAvailable()) {
                        // yes, we have backup dumps
                        havedumps = true;

                        DumpInfo info(i,
                                      sourcereport.m_backupBefore.getNumItems(),
                                      sourcereport.m_backupAfter.getNumItems());

                        // now check for changes, if none found yet
                        if (!changes) {
                            if (dumplist.empty()) {
                                // new backup dump
                                changes = true;
                            } else {
                                DumpInfo &previous = dumplist.back();
                                changes =
                                    // item count changed -> items changed
                                    previous.m_itemsDumpedAfter != info.m_itemsDumpedBefore ||
                                    sourcereport.wasChanged(SyncSourceReport::ITEM_LOCAL) ||
                                    sourcereport.wasChanged(SyncSourceReport::ITEM_REMOTE) ||
                                    haveDifferentContent(sourcename,
                                                         dirs[previous.m_dirIndex], "after",
                                                         dirs[i], "before");
                            }
                        }

                        dumplist.push_back(info);
                    }
                }
                Priority pri =
                    havedumps ?
                    (changes ?
                     HAS_DUMPS_WITH_CHANGES :
                     errors ?
                     HAS_DUMPS_NO_CHANGES_WITH_ERRORS :
                     HAS_DUMPS_NO_CHANGES) :
                    (changes ?
                     NO_DUMPS_WITH_CHANGES :
                     errors ?
                     NO_DUMPS_WITH_ERRORS :
                     NO_DUMPS_NO_ERRORS);
                victims.push_back(make_pair(pri, i));
            }
            sort(victims.begin(), victims.end());

            int deleted = 0;
            for (size_t e = 0;
                 e < victims.size() && (int)dirs.size() - deleted > m_maxlogdirs;
                 ++e) {
                size_t index = victims[e].second;
                string &path = dirs[index];
                // preserve latest session
                if (index != dirs.size() - 1) {
                    bool mustkeep = false;
                    // also check whether it holds the only backup of a source
                    BOOST_FOREACH(Dumps_t::value_type dump, dumps) {
                        if (dump.second.size() == 1 &&
                            dump.second.front().m_dirIndex == index) {
                            mustkeep = true;
                            break;
                        }
                    }
                    if (!mustkeep) {
                        SE_LOG_DEBUG(NULL, "removing %s", path.c_str());
                        rm_r(path);
                        ++deleted;
                    }
                }
            }
        }
    }

    // finalize session
    void endSession()
    {
        time_t end = time(NULL);
        if (m_report) {
            m_report->setEnd(end);
        }
        if (m_info) {
            if (!m_readonly) {
                writeTimestamp("end", end);
                if (m_report) {
                    RecMutex::Guard guard = Logger::lock();
                    writeReport(*m_report);
                }
                m_info->flush();
            }
            m_info.reset();
        }
    }

    // Remove redirection of logging.
    void restore() {
        m_logger.reset();
    }

    ~LogDir() {
        restore();
    }


#if 0
    /**
     * A quick check for level = SHOW text dumps whether the text dump
     * starts with the [ERROR] prefix; used to detect error messages
     * from forked process which go through this instance but are not
     * already tagged as error messages and thus would not show up as
     * "first error" in sync reports.
     *
     * Example for the problem:
     * [ERROR] onConnect not implemented                [from child process]
     * [ERROR] child process quit with return code 1    [from parent]
     * ...
     * Changes applied during synchronization:
     * ...
     * First ERROR encountered: child process quit with return code 1
     */
    static bool isErrorString(const char *format,
                              va_list args)
    {
        const char *text;
        if (!strcmp(format, "%s")) {
            va_list argscopy;
            va_copy(argscopy, args);
            text = va_arg(argscopy, const char *);
            va_end(argscopy);
        } else {
            text = format;
        }
        return boost::starts_with(text, "[ERROR");
    }
#endif

    /**
     * Compare two database dumps just based on their inodes.
     * @return true    if inodes differ
     */
    static bool haveDifferentContent(const string &sourceName,
                                     const string &firstDir,
                                     const string &firstSuffix,
                                     const string &secondDir,
                                     const string &secondSuffix)
    {
        string first = firstDir + "/" + sourceName + "." + firstSuffix;
        string second = secondDir + "/" + sourceName + "." + secondSuffix;
        ReadDir firstContent(first);
        ReadDir secondContent(second);
        set<ino_t> firstInodes;
        BOOST_FOREACH(const string &name, firstContent) {
            struct stat buf;
            string fullpath = first + "/" + name;
            if (stat(fullpath.c_str(), &buf)) {
                SyncContext::throwError(fullpath, errno);
            }
            firstInodes.insert(buf.st_ino);
        }
        BOOST_FOREACH(const string &name, secondContent) {
            struct stat buf;
            string fullpath = second + "/" + name;
            if (stat(fullpath.c_str(), &buf)) {
                SyncContext::throwError(fullpath, errno);
            }
            set<ino_t>::iterator it = firstInodes.find(buf.st_ino);
            if (it == firstInodes.end()) {
                // second dir has different file
                return true;
            } else {
                firstInodes.erase(it);
            }
        }
        if (!firstInodes.empty()) {
            // first dir has different file
            return true;
        }
        // exact match of inodes
        return false;
    }

private:
    enum Priority {
        NO_DUMPS_NO_ERRORS,
        NO_DUMPS_WITH_ERRORS,
        NO_DUMPS_WITH_CHANGES,
        HAS_DUMPS_NO_CHANGES,
        HAS_DUMPS_NO_CHANGES_WITH_ERRORS,
        HAS_DUMPS_WITH_CHANGES
    };

    struct DumpInfo {
        size_t m_dirIndex;
        int m_itemsDumpedBefore;
        int m_itemsDumpedAfter;
        DumpInfo(size_t dirIndex,
                 int itemsDumpedBefore,
                 int itemsDumpedAfter) :
            m_dirIndex(dirIndex),
            m_itemsDumpedBefore(itemsDumpedBefore),
            m_itemsDumpedAfter(itemsDumpedAfter)
        {}
    };

    /** 
     * Find all entries in a given directory, return as sorted array of full paths in ascending order.
     * If m_prefix doesn't contain peer name information, then all log dirs for different peers in the
     * logdir are returned.
     */
    void getLogdirs(vector<string> &dirs) {
        if (m_logdir != "none" && !isDir(m_logdir)) {
            return;
        }
        string peer = m_client.getConfigName();
        string peerName, context;
        SyncConfig::splitConfigString(peer, peerName, context);

        ReadDir dir(m_logdir);
        BOOST_FOREACH(const string &entry, dir) {
            string tmpDirPrefix, tmpPeer, tmpDateTime;
            // if directory name could not be parsed, ignore it
            if(parseDirName(entry, tmpDirPrefix, tmpPeer, tmpDateTime)) {
                if(!peerName.empty() && (m_prefix == (tmpDirPrefix + tmpPeer))) {
                    // if peer name exists, match the logs for the given peer
                    dirs.push_back(m_logdir + "/" + entry);
                } else if(peerName.empty()) {
                    // if no peer name and only context, match for all logs under the given context
                    string tmpName, tmpContext;
                    SyncConfig::splitConfigString(unescapePeer(tmpPeer), tmpName, tmpContext);
                    if( context == tmpContext && boost::starts_with(m_prefix, tmpDirPrefix)) {
                        dirs.push_back(m_logdir + "/" + entry);
                    }
                }
            }
        }
        // sort vector in ascending order
        // if no peer name
        if(peerName.empty()){
            sort(dirs.begin(), dirs.end(), LogDirNames());
        } else {
            sort(dirs.begin(), dirs.end());
        }
    }

    // store time stamp in session info
    void writeTimestamp(const string &key, time_t val, bool flush = true) {
        if (m_info) {
            char buffer[160];
            struct tm tmbuffer, *tm;
            // be nice and store a human-readable date in addition the seconds since the epoch
            tm = localtime_r(&val, &tmbuffer);
            if (tm) {
                strftime(buffer, sizeof(buffer), "%s, %Y-%m-%d %H:%M:%S %z", tm);
            } else {
                // Less suitable fallback. Won't work correctly for 32
                // bit long beyond 2038.
                sprintf(buffer, "%lu", (long unsigned)val);
            }
            m_info->setProperty(key, buffer);
            if (flush) {
                m_info->flush();
            }
        }
    }
};

LogDirLogger::LogDirLogger(const boost::weak_ptr<LogDir> &logdir) :
    m_parentLogger(Logger::instance()),
    m_logdir(logdir)
{
}

void LogDirLogger::remove() throw ()
{
    // Forget reference to LogDir. This prevents accessing it in
    // future messagev() calls.
    RecMutex::Guard guard = Logger::lock();
    m_logdir.reset();
}

void LogDirLogger::messagev(const MessageOptions &options,
                            const char *format,
                            va_list args)
{
    // Protects ordering of log messages and access to shared
    // variables like m_report and m_engine.
    RecMutex::Guard guard = Logger::lock();

    // always to parent first (usually stdout):
    // if the parent is a LogRedirect instance, then
    // it'll flush its own output first, which ensures
    // that the new output comes later (as desired)
    va_list argscopy;
    va_copy(argscopy, args);
    m_parentLogger.messagev(options, format, argscopy);
    va_end(argscopy);

    boost::shared_ptr<LogDir> logdir = m_logdir.lock();
    if (logdir) {
        if (logdir->m_report &&
            options.m_level <= ERROR &&
            logdir->m_report->getError().empty()) {
            va_list argscopy;
            va_copy(argscopy, args);
            string error = StringPrintfV(format, argscopy);
            va_end(argscopy);

            logdir->m_report->setError(error);
        }

        if (logdir->m_client.getEngine().get()) {
            va_list argscopy;
            va_copy(argscopy, args);
            // once to Synthesis log, with full debugging
            logdir->m_client.getEngine().doDebug(options.m_level,
                                                 options.m_prefix ? options.m_prefix->c_str() : NULL,
                                                 options.m_file,
                                                 options.m_line,
                                                 options.m_function,
                                                 format,
                                                 argscopy);
            va_end(argscopy);
        }
    }
}


const char* const LogDirNames::DIR_PREFIX = "SyncEvolution-";

/**
 * This class owns the sync sources. For historic reasons (required
 * by Funambol) SyncSource instances are stored as plain pointers
 * deleted by this class. Virtual sync sources were added later
 * and are stored as shared pointers which are freed automatically.
 * It is possible to iterate over the two classes of sources
 * separately.
 *
 * The SourceList ensures that all sources (normal and virtual) have
 * a valid and unique integer ID as needed for Synthesis. Traditionally
 * this used to be a simple hash of the source name (which is unique
 * by design), without checking for hash collisions. Now the ID is assigned
 * the first time a source is added here and doesn't have one yet.
 * For backward compatibility (the ID is stored in the .synthesis dir),
 * the same Hash() value is tested first. Assuming that there were no
 * hash conflicts, the same IDs will be generated as before.
 *
 * Together with a logdir, the SourceList
 * handles writing of per-sync files as well as the final report.
 * It is not stateless. The expectation is that it is instantiated
 * together with a SyncContext for one particular operation (sync
 * session, status check, restore). In contrast to a SyncContext,
 * this class has to be recreated for another operation.
 *
 * When running as client, only the active sources get added. They can
 * be dumped one after the other before running a sync.
 *
 * As a server, all sources get added, regardless whether they are
 * active. This implies that at least their "type" must be valid. Then
 * later when a client really starts using them, they are opened() and
 * database dumps are made.
 *
 * Virtual datastores are stored here when they get initialized
 * together with the normal sources by the user of SourceList.
 *
 * 
 */
class SourceList : private vector<SyncSource *> {
    typedef vector<SyncSource *> inherited;

public:
    enum LogLevel {
        LOGGING_QUIET,    /**< avoid all extra output */
        LOGGING_SUMMARY,  /**< sync report, but no database comparison */
        LOGGING_FULL      /**< everything */
    };

    typedef std::vector< boost::shared_ptr<VirtualSyncSource> > VirtualSyncSources_t;

    /** reading our set of virtual sources is okay, modifying it is not */
    const VirtualSyncSources_t &getVirtualSources() { return m_virtualSources; }
    void addSource(const boost::shared_ptr<VirtualSyncSource> &source) { checkSource(source.get()); m_virtualSources.push_back(source); }

    using inherited::iterator;
    using inherited::const_iterator;
    using inherited::empty;
    using inherited::begin;
    using inherited::end;
    using inherited::rbegin;
    using inherited::rend;

    /** transfers ownership (historic reasons for storing plain pointer...) */
    void addSource(cxxptr<SyncSource> &source) { checkSource(source); push_back(source.release()); }

private:
    VirtualSyncSources_t m_virtualSources; /**< all configured virtual data sources (aka Synthesis <superdatastore>) */
    boost::shared_ptr<LogDir> m_logdir;     /**< our logging directory */
    SyncContext &m_client; /**< the context in which we were instantiated */
    set<string> m_prepared;   /**< remember for which source we dumped databases successfully */
    string m_intro;      /**< remembers the dumpLocalChanges() intro and only prints it again
                            when different from last dumpLocalChanges() call */
    bool m_doLogging;    /**< true iff the normal logdir handling is enabled
                            (creating and expiring directoties, before/after comparison) */
    bool m_reportTodo;   /**< true if syncDone() shall print a final report */
    LogLevel m_logLevel; /**< chooses how much information is printed */
    string m_previousLogdir; /**< remember previous log dir before creating the new one */

    /** create name in current (if set) or previous logdir */
    string databaseName(SyncSource &source, const string suffix, string logdir = "") {
        if (!logdir.size()) {
            logdir = m_logdir->getLogdir();
        }
        return logdir + "/" +
            source.getName() + "." + suffix;
    }

    /** ensure that Synthesis ID is set and unique */
    void checkSource(SyncSource *source) {
        if (source->getSynthesisID()) {
            return;
        }
        int id = Hash(source->getName()) % INT_MAX;
        while (true) {
            // avoid negative values
            if (id < 0) {
                id = -id;
            }
            // avoid zero, it means unset
            if (!id) {
                id = 1;
            }
            // check for collisions
            bool collision = false;
            BOOST_FOREACH(const string &other, m_client.getSyncSources()) {
                boost::shared_ptr<PersistentSyncSourceConfig> sc(m_client.getSyncSourceConfig(other));
                int other_id = sc->getSynthesisID();
                if (other_id == id) {
                    ++id;
                    collision = true;
                    break;
                }
            }
            if (!collision) {
                source->setSynthesisID(id);
                return;
            }
        }
    }

public:
    /** allow iterating over sources */
    const inherited *getSourceSet() const { return this; }

    LogLevel getLogLevel() const { return m_logLevel; }
    void setLogLevel(LogLevel logLevel) { m_logLevel = logLevel; }

    /**
     * Dump into files with a certain suffix, optionally store report
     * in member of SyncSourceReport. Remembers which sources were
     * dumped before a sync and only dumps those again afterward.
     *
     * @param suffix        "before/after/current" - before sync, after sync, during status check
     * @param excludeSource when not empty, only dump that source
     */
    void dumpDatabases(const string &suffix,
                       BackupReport SyncSourceReport::*report,
                       const string &excludeSource = "") {
        // Identify all logdirs of current context, of any peer.  Used
        // to search for previous backups of each source, if
        // necessary.
        SyncContext context(m_client.getContextName());
        boost::shared_ptr<LogDir> logdir(LogDir::create(context));
        vector<string> dirs;
        logdir->previousLogdirs(dirs);

        BOOST_FOREACH(SyncSource *source, *this) {
            if ((!excludeSource.empty() && excludeSource != source->getName()) ||
                (suffix == "after" && m_prepared.find(source->getName()) == m_prepared.end())) {
                continue;
            }

            string dir = databaseName(*source, suffix);
            boost::shared_ptr<ConfigNode> node = ConfigNode::createFileNode(dir + ".ini");
            SE_LOG_DEBUG(NULL, "creating %s", dir.c_str());
            rm_r(dir);
            BackupReport dummy;
            if (source->getOperations().m_backupData) {
                SyncSource::Operations::ConstBackupInfo oldBackup;
                // Now look for a backup of the current source,
                // starting with the most recent one.
                for (vector<string>::const_reverse_iterator it = dirs.rbegin();
                     it != dirs.rend();
                     ++it) {
                    const string &sessiondir = *it;
                    string oldBackupDir;
                    SyncSource::Operations::BackupInfo::Mode mode =
                        SyncSource::Operations::BackupInfo::BACKUP_AFTER;
                    oldBackupDir = databaseName(*source, "after", sessiondir);
                    if (!isDir(oldBackupDir)) {
                        mode = SyncSource::Operations::BackupInfo::BACKUP_BEFORE;
                        oldBackupDir = databaseName(*source, "before", sessiondir);
                        if (!isDir(oldBackupDir)) {
                            // try next session
                            continue;
                        }
                    }

                    oldBackup.m_mode = mode;
                    oldBackup.m_dirname = oldBackupDir;
                    oldBackup.m_node = ConfigNode::createFileNode(oldBackupDir + ".ini");
                    break;
                }
                mkdir_p(dir);
                SyncSource::Operations::BackupInfo newBackup(suffix == "before" ?
                                                             SyncSource::Operations::BackupInfo::BACKUP_BEFORE :
                                                             suffix == "after" ?
                                                             SyncSource::Operations::BackupInfo::BACKUP_AFTER :
                                                             SyncSource::Operations::BackupInfo::BACKUP_OTHER,
                                                             dir, node);
                source->getOperations().m_backupData(oldBackup, newBackup,
                                                     report ? source->*report : dummy);
                SE_LOG_DEBUG(NULL, "%s created", dir.c_str());

                // remember that we have dumped at the beginning of a sync
                if (suffix == "before") {
                    m_prepared.insert(source->getName());
                }
            }
        }
    }

    void restoreDatabase(SyncSource &source, const string &suffix, bool dryrun, SyncSourceReport &report)
    {
        string dir = databaseName(source, suffix);
        boost::shared_ptr<ConfigNode> node = ConfigNode::createFileNode(dir + ".ini");
        if (!node->exists()) {
            SyncContext::throwError(dir + ": no such database backup found");
        }
        if (source.getOperations().m_restoreData) {
            source.getOperations().m_restoreData(SyncSource::Operations::ConstBackupInfo(SyncSource::Operations::BackupInfo::BACKUP_OTHER, dir, node),
                                                 dryrun, report);
        }
    }

    SourceList(SyncContext &client, bool doLogging) :
        m_logdir(LogDir::create(client)),
        m_client(client),
        m_doLogging(doLogging),
        m_reportTodo(true),
        m_logLevel(LOGGING_FULL)
    {
    }
    
    // call as soon as logdir settings are known
    void startSession(const string &logDirPath, int maxlogdirs, int logLevel, SyncReport *report) {
        m_logdir->setLogdir(logDirPath);
        m_previousLogdir = m_logdir->previousLogdir();
        if (m_doLogging) {
            m_logdir->startSession(logDirPath, LogDir::SESSION_CREATE, maxlogdirs, logLevel, report);
        } else {
            // Run debug session without paying attention to
            // the normal logdir handling. The log level here
            // refers to stdout. The log file will be as complete
            // as possible.
            m_logdir->startSession(logDirPath, LogDir::SESSION_USE_PATH, 0, 1, report);
        }
    }

    /** read-only access to existing session, identified in logDirPath */
    void accessSession(const string &logDirPath) {
        m_logdir->setLogdir(logDirPath);
        m_previousLogdir = m_logdir->previousLogdir();
        m_logdir->startSession(logDirPath, LogDir::SESSION_READ_ONLY, 0, 0, NULL);
    }


    /** return log directory, empty if not enabled */
    const string &getLogdir() {
        return m_logdir->getLogdir();
    }

    /** return previous log dir found in startSession() */
    const string &getPrevLogdir() const { return m_previousLogdir; }

    /** set directory for database files without actually redirecting the logging */
    void setPath(const string &path) { m_logdir->setPath(path); }

    /**
     * If possible (directory to compare against available) and enabled,
     * then dump changes applied locally.
     *
     * @param oldSession     directory to compare against; "" searches in sessions of current peer
     *                       as selected by context for the lastest one involving each source
     * @param oldSuffix      suffix of old database dump: usually "after"
     * @param currentSuffix  the current database dump suffix: "current"
     *                       when not doing a sync, otherwise "before"
     * @param excludeSource  when not empty, only dump that source
     */
    bool dumpLocalChanges(const string &oldSession,
                          const string &oldSuffix, const string &newSuffix,
                          const string &excludeSource,
                          const string &intro = "Local data changes to be applied remotely during synchronization:\n",
                          const string &config = "CLIENT_TEST_LEFT_NAME='after last sync' CLIENT_TEST_RIGHT_NAME='current data' CLIENT_TEST_REMOVED='removed since last sync' CLIENT_TEST_ADDED='added since last sync'") {
        if (m_logLevel <= LOGGING_SUMMARY) {
            return false;
        }

        vector<string> dirs;
        if (oldSession.empty()) {
            m_logdir->previousLogdirs(dirs);
        }

        BOOST_FOREACH(SyncSource *source, *this) {
            if ((!excludeSource.empty() && excludeSource != source->getName()) ||
                (newSuffix == "after" && m_prepared.find(source->getName()) == m_prepared.end())) {
                continue;
            }

            // dump only if not done before or changed
            if (m_intro != intro) {
                SE_LOG_SHOW(NULL, "%s", intro.c_str());
                m_intro = intro;
            }

            string oldDir;
            if (oldSession.empty()) {
                // Now look for the latest session involving the current source,
                // starting with the most recent one.
                for (vector<string>::const_reverse_iterator it = dirs.rbegin();
                     it != dirs.rend();
                     ++it) {
                    const string &sessiondir = *it;
                    boost::shared_ptr<LogDir> oldsession(LogDir::create(m_client));
                    oldsession->openLogdir(sessiondir);
                    SyncReport report;
                    oldsession->readReport(report);
                    if (report.find(source->getName()) != report.end())  {
                        // source was active in that session, use dump
                        // made there
                        oldDir = databaseName(*source, oldSuffix, sessiondir);
                        break;
                    }
                }
            } else {
                oldDir = databaseName(*source, oldSuffix, oldSession);
            }
            string newDir = databaseName(*source, newSuffix);
            SE_LOG_SHOW(NULL, "*** %s ***", source->getDisplayName().c_str());
            string cmd = string("env CLIENT_TEST_COMPARISON_FAILED=10 " + config + " synccompare '" ) +
                oldDir + "' '" + newDir + "'";
            int ret = Execute(cmd, EXECUTE_NO_STDERR);
            switch (ret == -1 ? ret :
                    WIFEXITED(ret) ? WEXITSTATUS(ret) :
                    -1) {
            case 0:
                SE_LOG_SHOW(NULL, "no changes");
                break;
            case 10:
                break;
            default:
                SE_LOG_SHOW(NULL, "Comparison was impossible.");
                break;
            }
        }
        SE_LOG_SHOW(NULL, "\n");
        return true;
    }

    // call when all sync sources are ready to dump
    // pre-sync databases
    // @param sourceName   limit preparation to that source
    void syncPrepare(const string &sourceName) {
        if (m_prepared.find(sourceName) != m_prepared.end()) {
            // data dump was already done (can happen when running multiple
            // SyncML sessions)
            return;
        }

        if (m_logdir->getLogfile().size() &&
            m_doLogging &&
            (m_client.getDumpData() || m_client.getPrintChanges())) {
            // dump initial databases
            SE_LOG_INFO(NULL, "creating complete data backup of source %s before sync (%s)",
                        sourceName.c_str(),
                        (m_client.getDumpData() && m_client.getPrintChanges()) ? "enabled with dumpData and needed for printChanges" :
                        m_client.getDumpData() ? "because it was enabled with dumpData" :
                        m_client.getPrintChanges() ? "needed for printChanges" :
                        "???");
            dumpDatabases("before", &SyncSourceReport::m_backupBefore, sourceName);
            if (m_client.getPrintChanges()) {
                // compare against the old "after" database dump
                dumpLocalChanges("", "after", "before", sourceName,
                                 StringPrintf("%s data changes to be applied during synchronization:\n",
                                              m_client.isLocalSync() ? m_client.getContextName().c_str() : "Local"));
            }
        }
    }

    // call at the end of a sync with success == true
    // if all went well to print report
    void syncDone(SyncMLStatus status, SyncReport *report) {
        // record status - failures from now only affect post-processing
        // and thus do no longer change that result
        if (report) {
            report->setStatus(status == 0 ? STATUS_HTTP_OK : status);
        }

        // dump database after sync if explicitly enabled or
        // needed for comparison;
        // in the latter case only if dumping it at the beginning completed
        if (m_doLogging &&
            (m_client.getDumpData() ||
             (m_client.getPrintChanges() && m_reportTodo && !m_prepared.empty()))) {
            try {
                SE_LOG_INFO(NULL, "creating complete data backup after sync (%s)",
                            (m_client.getDumpData() && m_client.getPrintChanges()) ? "enabled with dumpData and needed for printChanges" :
                            m_client.getDumpData() ? "because it was enabled with dumpData" :
                            m_client.getPrintChanges() ? "needed for printChanges" :
                            "???");
                dumpDatabases("after", &SyncSourceReport::m_backupAfter);
            } catch (...) {
                Exception::handle();
                // not exactly sure what the problem was, but don't
                // try it again
                m_prepared.clear();
            }
        }

        if (m_doLogging) {
            if (m_reportTodo && !m_prepared.empty() && report) {
                // update report with more recent information about m_backupAfter
                updateSyncReport(*report);
            }

            // ensure that stderr is seen again
            m_logdir->restore();

            // write out session status
            m_logdir->endSession();

            if (m_reportTodo) {
                // haven't looked at result of sync yet;
                // don't do it again
                m_reportTodo = false;

                string logfile = m_logdir->getLogfile();
                if (status == STATUS_OK) {
                    SE_LOG_SHOW(NULL, "\nSynchronization successful.");
                } else if (logfile.size()) {
                    SE_LOG_SHOW(NULL, "\nSynchronization failed, see %s for details.",
                                logfile.c_str());
                } else {
                    SE_LOG_SHOW(NULL, "\nSynchronization failed.");
                }

                // pretty-print report
                if (m_logLevel > LOGGING_QUIET) {
                    std::string procname = Logger::getProcessName();
                    SE_LOG_SHOW(NULL, "\nChanges applied during synchronization%s%s%s:",
                                procname.empty() ? "" : " (",
                                procname.c_str(),
                                procname.empty() ? "" : ")");
                }
                if (m_logLevel > LOGGING_QUIET && report) {
                    ostringstream out;
                    out << *report;
                    std::string slowSync = report->slowSyncExplanation(m_client.getPeer());
                    if (!slowSync.empty()) {
                        out << endl << slowSync;
                    }
                    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
                }

                // compare databases?
                if (m_client.getPrintChanges()) {
                    dumpLocalChanges(m_logdir->getLogdir(),
                                     "before", "after", "",
                                     StringPrintf("\nData modified %s during synchronization:\n",
                                                  m_client.isLocalSync() ? m_client.getContextName().c_str() : "locally"),
                                     "CLIENT_TEST_LEFT_NAME='before sync' CLIENT_TEST_RIGHT_NAME='after sync' CLIENT_TEST_REMOVED='removed during sync' CLIENT_TEST_ADDED='added during sync'");
                }

                // now remove some old logdirs
                m_logdir->expire();
            }
        } else {
            // finish debug session
            m_logdir->restore();
            m_logdir->endSession();
        }
    }

    /** copies information about sources into sync report */
    void updateSyncReport(SyncReport &report) {
        BOOST_FOREACH(SyncSource *source, *this) {
            report.addSyncSourceReport(source->getName(), *source);
        }
    }

    /** returns names of active sources */
    set<string> getSources() {
        set<string> res;

        BOOST_FOREACH(SyncSource *source, *this) {
            res.insert(source->getName());
        }
        return res;
    }
   
    ~SourceList() {
        // free sync sources
        BOOST_FOREACH(SyncSource *source, *this) {
            delete source;
        }
    }

    /** find sync source by name (both normal and virtual sources) */
    SyncSource *operator [] (const string &name) {
        BOOST_FOREACH(SyncSource *source, *this) {
            if (name == source->getName()) {
                return source;
            }
        }
        BOOST_FOREACH(boost::shared_ptr<VirtualSyncSource> &source, m_virtualSources) {
            if (name == source->getName()) {
                return source.get();
            }
        }
        return NULL;
    }

    /** find by XML <dbtypeid> (the ID used by Synthesis to identify sources in progress events) */
    SyncSource *lookupBySynthesisID(int synthesisid) {
        BOOST_FOREACH(SyncSource *source, *this) {
            if (source->getSynthesisID() == synthesisid) {
                return source;
            }
        }
        BOOST_FOREACH(boost::shared_ptr<VirtualSyncSource> &source, m_virtualSources) {
            if (source->getSynthesisID() == synthesisid) {
                return source.get();
            }
        }
        return NULL;
    }
};

void unref(SourceList *sourceList)
{
    delete sourceList;
}

UserInterface &SyncContext::getUserInterfaceNonNull()
{
    if (m_userInterface) {
        return *m_userInterface;
    } else {
        static class DummyUserInterface : public UserInterface
        {
        public:
            virtual std::string askPassword(const std::string &passwordName, const std::string &descr, const ConfigPasswordKey &key) { return ""; }

            virtual bool savePassword(const std::string &passwordName, const std::string &password, const ConfigPasswordKey &key) { return false; }

            virtual void readStdin(std::string &content) { content.clear(); }
        } dummy;

        return dummy;
    }
}

void SyncContext::requestAnotherSync()
{
    if (m_activeContext &&
        m_activeContext->m_engine.get() &&
        m_activeContext->m_session) {
        SharedKey sessionKey =
            m_activeContext->m_engine.OpenSessionKey(m_activeContext->m_session);
        m_activeContext->m_engine.SetInt32Value(sessionKey,
                                                "restartsync",
                                                true);
    }
}

const std::vector<SyncSource *> *SyncContext::getSources() const
{
    return m_sourceListPtr ?
        m_sourceListPtr->getSourceSet() :
        NULL;
}

string SyncContext::getUsedSyncURL() {
    vector<string> urls = getSyncURL();
    BOOST_FOREACH (string url, urls) {
        if (boost::starts_with(url, "http://") ||
                boost::starts_with(url, "https://")) {
#ifdef ENABLE_LIBSOUP
            return url;
#elif defined(ENABLE_LIBCURL)
            return url;
#endif
        } else if (url.find("obex-bt://") ==0) {
#ifdef ENABLE_BLUETOOTH
            return url;
#endif
        } else if (boost::starts_with(url, "local://")) {
            return url;
        }
    }
    return "";
}

static void CancelTransport(TransportAgent *agent, SuspendFlags &flags)
{
    if (flags.getState() == SuspendFlags::ABORT) {
        SE_LOG_DEBUG(NULL, "CancelTransport: cancelling because of SuspendFlags::ABORT");
        agent->cancel();
    }
}

/**
 * common initialization for all kinds of transports, to be called
 * before using them
 */
static void InitializeTransport(const boost::shared_ptr<TransportAgent> &agent,
                                int timeout)
{
    agent->setTimeout(timeout);

    // Automatically call cancel() when we an abort request
    // is detected. Relies of automatic connection management
    // to disconnect when agent is deconstructed.
    SuspendFlags &flags(SuspendFlags::getSuspendFlags());
    flags.m_stateChanged.connect(SuspendFlags::StateChanged_t::slot_type(CancelTransport, agent.get(), _1).track(agent));
}

boost::shared_ptr<TransportAgent> SyncContext::createTransportAgent(void *gmainloop)
{
    string url = getUsedSyncURL();
    m_retryInterval = getRetryInterval();
    m_retryDuration = getRetryDuration();
    int timeout = m_serverMode ? m_retryDuration : min(m_retryInterval, m_retryDuration);

    if (m_localSync) {
        string peer = url.substr(strlen("local://"));
        boost::shared_ptr<LocalTransportAgent> agent(LocalTransportAgent::create(this, peer, gmainloop));
        InitializeTransport(agent, timeout);
        agent->start();
        return agent;
    } else if (boost::starts_with(url, "http://") ||
        boost::starts_with(url, "https://")) {
#ifdef ENABLE_LIBSOUP
        boost::shared_ptr<SoupTransportAgent> agent(new SoupTransportAgent(static_cast<GMainLoop *>(gmainloop)));
        agent->setConfig(*this);
        InitializeTransport(agent, timeout);
        return agent;
#elif defined(ENABLE_LIBCURL)
        boost::shared_ptr<CurlTransportAgent> agent(new CurlTransportAgent());
        agent->setConfig(*this);
        InitializeTransport(agent, timeout);
        return agent;
#endif
    } else if (url.find("obex-bt://") ==0) {
#ifdef ENABLE_BLUETOOTH
        std::string btUrl = url.substr (strlen ("obex-bt://"), std::string::npos);
        boost::shared_ptr<ObexTransportAgent> agent(new ObexTransportAgent(ObexTransportAgent::OBEX_BLUETOOTH,
                                                                           static_cast<GMainLoop *>(gmainloop)));
        agent->setURL (btUrl);
        InitializeTransport(agent, timeout);
        // this will block already
        agent->connect();
        return agent;
#endif
    }

    SE_THROW("unsupported transport type is specified in the configuration");
}

void SyncContext::displayServerMessage(const string &message)
{
    SE_LOG_INFO(NULL, "message from server: %s", message.c_str());
}

void SyncContext::displaySyncProgress(sysync::TProgressEventEnum type,
                                              int32_t extra1, int32_t extra2, int32_t extra3)
{
    
}

void SyncContext::displaySourceProgress(sysync::TProgressEventEnum type,
                                                SyncSource &source,
                                                int32_t extra1, int32_t extra2, int32_t extra3)
{
    switch(type) {
    case sysync::PEV_PREPARING:
        /* preparing (e.g. preflight in some clients), extra1=progress, extra2=total */
        /* extra2 might be zero */
        /*
         * At the moment, preparing items doesn't do any real work.
         * Printing this progress just increases the output and slows
         * us down. Disabled.
         */
        if (true || source.getFinalSyncMode() == SYNC_NONE) {
            // not active, suppress output
        } else if (extra2) {
            SE_LOG_INFO(NULL, "%s: preparing %d/%d",
                        source.getDisplayName().c_str(), extra1, extra2);
        } else {
            SE_LOG_INFO(NULL, "%s: preparing %d",
                        source.getDisplayName().c_str(), extra1);
        }
        break;
    case sysync::PEV_DELETING:
        /* deleting (zapping datastore), extra1=progress, extra2=total */
        if (extra2) {
            SE_LOG_INFO(NULL, "%s: deleting %d/%d",
                        source.getDisplayName().c_str(), extra1, extra2);
        } else {
            SE_LOG_INFO(NULL, "%s: deleting %d",
                        source.getDisplayName().c_str(), extra1);
        }
        break;
    case sysync::PEV_ALERTED: {
        /* datastore alerted (extra1=0 for normal, 1 for slow, 2 for first time slow, 
           extra2=1 for resumed session,
           extra3 0=twoway, 1=fromserver, 2=fromclient */
        // -1 is used for alerting a restore from backup. Synthesis won't use this
        bool peerIsClient = getPeerIsClient();
        if (extra1 != -1) {
            SE_LOG_INFO(NULL, "%s: %s %s sync%s (%s)",
                        source.getDisplayName().c_str(),
                        extra2 ? "resuming" : "starting",
                        extra1 == 0 ? "normal" :
                        extra1 == 1 ? "slow" :
                        extra1 == 2 ? "first time" :
                        "unknown",
                        extra3 == 0 ? ", two-way" :
                        extra3 == 1 ? " from server" :
                        extra3 == 2 ? " from client" :
                        ", unknown direction",
                        peerIsClient ? "peer is client" : "peer is server");
         
            SimpleSyncMode mode = SIMPLE_SYNC_NONE;
            SyncMode sync = StringToSyncMode(source.getSync());
            switch (extra1) {
            case 0:
                switch (extra3) {
                case 0:
                    mode = SIMPLE_SYNC_TWO_WAY;
                    if (m_serverMode &&
                        m_serverAlerted) {
                        if (sync == SYNC_ONE_WAY_FROM_SERVER ||
                            sync == SYNC_ONE_WAY_FROM_LOCAL) {
                            // As in the slow/refresh-from-server case below,
                            // pretending to do a two-way incremental sync
                            // is a correct way of executing the requested
                            // one-way sync, as long as the client doesn't
                            // send any of its own changes. The Synthesis
                            // engine does that.
                            mode = SIMPLE_SYNC_ONE_WAY_FROM_LOCAL;
                        } else if (sync == SYNC_LOCAL_CACHE_SLOW ||
                                   sync == SYNC_LOCAL_CACHE_INCREMENTAL) {
                            mode = SIMPLE_SYNC_LOCAL_CACHE_INCREMENTAL;
                        }
                    }
                    break;
                case 1:
                    mode = peerIsClient ? SIMPLE_SYNC_ONE_WAY_FROM_LOCAL : SIMPLE_SYNC_ONE_WAY_FROM_REMOTE;
                    break;
                case 2:
                    mode = peerIsClient ? SIMPLE_SYNC_ONE_WAY_FROM_REMOTE : SIMPLE_SYNC_ONE_WAY_FROM_LOCAL;
                    break;
                }
                break;
            case 1:
            case 2:
                switch (extra3) {
                case 0:
                    mode = SIMPLE_SYNC_SLOW;
                    if (m_serverMode &&
                        m_serverAlerted) {
                        if (sync == SYNC_REFRESH_FROM_SERVER ||
                            sync == SYNC_REFRESH_FROM_LOCAL) {
                            // We run as server and told the client to refresh
                            // its data. A slow sync is how some clients (the
                            // Synthesis engine included) execute that sync mode;
                            // let's be optimistic and assume that the client
                            // did as it was told and deleted its data.
                            mode = SIMPLE_SYNC_REFRESH_FROM_LOCAL;
                        } else if (sync == SYNC_LOCAL_CACHE_SLOW ||
                                   sync == SYNC_LOCAL_CACHE_INCREMENTAL) {
                            mode = SIMPLE_SYNC_LOCAL_CACHE_SLOW;
                        }
                    }
                    break;
                case 1:
                    mode = peerIsClient ? SIMPLE_SYNC_REFRESH_FROM_LOCAL : SIMPLE_SYNC_REFRESH_FROM_REMOTE;
                    break;
                case 2:
                    mode = peerIsClient ? SIMPLE_SYNC_REFRESH_FROM_REMOTE : SIMPLE_SYNC_REFRESH_FROM_LOCAL;
                    break;
                }
                break;
            }
            if (source.getFinalSyncMode() == SYNC_NONE) {
                source.recordFinalSyncMode(SyncMode(mode));
                source.recordFirstSync(extra1 == 2);
                source.recordResumeSync(extra2 == 1);
            } else if (SyncMode(mode) != SYNC_NONE) {
                // may happen when the source is used in multiple
                // SyncML sessions; only remember the initial sync
                // mode in that case and count all following syncs
                // (they should only finish the work of the initial
                // one)
                source.recordRestart();
            }
        } else {
            SE_LOG_INFO(NULL, "%s: restore from backup", source.getDisplayName().c_str());
            source.recordFinalSyncMode(SYNC_RESTORE_FROM_BACKUP);
        }
        break;
    }
    case sysync::PEV_SYNCSTART:
        /* sync started */
        SE_LOG_INFO(NULL, "%s: started",
                    source.getDisplayName().c_str());
        break;
    case sysync::PEV_ITEMRECEIVED:
        /* item received, extra1=current item count,
           extra2=number of expected changes (if >= 0) */
        if (source.getFinalSyncMode() == SYNC_NONE) {
        } else if (extra2 > 0) {
            SE_LOG_INFO(NULL, "%s: received %d/%d",
                        source.getDisplayName().c_str(), extra1, extra2);
        } else {
            SE_LOG_INFO(NULL, "%s: received %d",
                        source.getDisplayName().c_str(), extra1);
        }
        break;
    case sysync::PEV_ITEMSENT:
        /* item sent,     extra1=current item count,
           extra2=number of expected items to be sent (if >=0) */
        if (source.getFinalSyncMode() == SYNC_NONE) {
        } else if (extra2 > 0) {
            SE_LOG_INFO(NULL, "%s: sent %d/%d",
                        source.getDisplayName().c_str(), extra1, extra2);
        } else {
            SE_LOG_INFO(NULL, "%s: sent %d",
                        source.getDisplayName().c_str(), extra1);
        }
        break;
    case sysync::PEV_ITEMPROCESSED:
        /* item locally processed,               extra1=# added, 
           extra2=# updated,
           extra3=# deleted */
        if (source.getFinalSyncMode() == SYNC_NONE) {
        } else if (source.getFinalSyncMode() != SYNC_NONE) {
            SE_LOG_INFO(NULL, "%s: added %d, updated %d, removed %d",
                        source.getDisplayName().c_str(), extra1, extra2, extra3);
        }
        break;
    case sysync::PEV_SYNCEND:
        /* sync finished, probably with error in extra1 (0=ok),
           syncmode in extra2 (0=normal, 1=slow, 2=first time), 
           extra3=1 for resumed session) */
        if (source.getFinalSyncMode() == SYNC_NONE) {
            SE_LOG_INFO(NULL, "%s: inactive", source.getDisplayName().c_str());
        } else if(source.getFinalSyncMode() == SYNC_RESTORE_FROM_BACKUP) {
            SE_LOG_INFO(NULL, "%s: restore done %s", 
                        source.getDisplayName().c_str(),
                        extra1 ? "unsuccessfully" : "successfully" );
        } else {
            SE_LOG_INFO(NULL, "%s: %s%s sync done %s",
                        source.getDisplayName().c_str(),
                        extra3 ? "resumed " : "",
                        extra2 == 0 ? "normal" :
                        extra2 == 1 ? "slow" :
                        extra2 == 2 ? "first time" :
                        "unknown",
                        extra1 ? "unsuccessfully" : "successfully");
        }
        switch (extra1) {
        case 401:
            // TODO: reset cached password
            SE_LOG_INFO(NULL, "authorization failed, check username '%s' and password", getSyncUsername().c_str());
            break;
        case 403:
            SE_LOG_INFO(source.getDisplayName(), "log in succeeded, but server refuses access - contact server operator");
            break;
        case 407:
            SE_LOG_INFO(NULL, "proxy authorization failed, check proxy username and password");
            break;
        case 404:
            SE_LOG_INFO(source.getDisplayName(), "server database not found, check URI '%s'", source.getURINonEmpty().c_str());
            break;
        case 0:
            break;
        case sysync::LOCERR_DATASTORE_ABORT:
            // this can mean only one thing in SyncEvolution: unexpected slow sync
            extra1 = STATUS_UNEXPECTED_SLOW_SYNC;
            // no break!
        default:
            // Printing unknown status codes here is of somewhat questionable value,
            // because even "good" sources will get a bad status when the overall
            // session turns bad. We also don't have good explanations for the
            // status here.
            SE_LOG_ERROR(source.getDisplayName(), "%s", Status2String(SyncMLStatus(extra1)).c_str());
            break;
        }
        source.recordStatus(SyncMLStatus(extra1));
        break;
    case sysync::PEV_DSSTATS_L:
        /* datastore statistics for local       (extra1=# added, 
           extra2=# updated,
           extra3=# deleted) */
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_ADDED,
                           SyncSource::ITEM_TOTAL,
                           extra1);
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_UPDATED,
                           SyncSource::ITEM_TOTAL,
                           extra2);
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_REMOVED,
                           SyncSource::ITEM_TOTAL,
                           // Synthesis engine doesn't count locally
                           // deleted items during
                           // refresh-from-server/client. That's a matter of
                           // taste. In SyncEvolution we'd like these
                           // items to show up, so add it here.
                           (source.getFinalSyncMode() == (m_serverMode ? SYNC_REFRESH_FROM_CLIENT : SYNC_REFRESH_FROM_SERVER) ||
                            source.getFinalSyncMode() == SYNC_REFRESH_FROM_REMOTE) ?
                           source.getNumDeleted() :
                           extra3);
        break;
    case sysync::PEV_DSSTATS_R:
        /* datastore statistics for remote      (extra1=# added, 
           extra2=# updated,
           extra3=# deleted) */
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ADDED,
                           SyncSource::ITEM_TOTAL,
                           extra1);
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_UPDATED,
                           SyncSource::ITEM_TOTAL,
                           extra2);
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_REMOVED,
                           SyncSource::ITEM_TOTAL,
                           extra3);
        break;
    case sysync::PEV_DSSTATS_E:
        /* datastore statistics for local/remote rejects (extra1=# locally rejected, 
           extra2=# remotely rejected) */
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_REJECT,
                           extra1);
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_REJECT,
                           extra2);
        break;
    case sysync::PEV_DSSTATS_S:
        /* datastore statistics for server slowsync  (extra1=# slowsync matches) */
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_MATCH,
                           extra1);
        break;
    case sysync::PEV_DSSTATS_C:
        /* datastore statistics for server conflicts (extra1=# server won,
           extra2=# client won,
           extra3=# duplicated) */
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_CONFLICT_SERVER_WON,
                           extra1);
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_CONFLICT_CLIENT_WON,
                           extra2);
        source.setItemStat(SyncSource::ITEM_REMOTE,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_CONFLICT_DUPLICATED,
                           extra3);
        break;
    case sysync::PEV_DSSTATS_D:
        /* datastore statistics for data   volume    (extra1=outgoing bytes,
           extra2=incoming bytes) */
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_SENT_BYTES,
                           extra1);
        source.setItemStat(SyncSource::ITEM_LOCAL,
                           SyncSource::ITEM_ANY,
                           SyncSource::ITEM_RECEIVED_BYTES,
                           extra2);
        break;
    default:
        SE_LOG_DEBUG(NULL, "%s: progress event %d, extra %d/%d/%d",
                     source.getDisplayName().c_str(),
                     type, extra1, extra2, extra3);
    }
}

void SyncContext::throwError(const string &error)
{
    throwError(SyncMLStatus(STATUS_FATAL + sysync::LOCAL_STATUS_CODE), error);
}

void SyncContext::throwError(SyncMLStatus status, const string &error)
{
#ifdef IPHONE
    /*
     * Catching the runtime_exception fails due to a toolchain problem,
     * so do the error handling now and abort: because there is just
     * one sync source this is probably the only thing that can be done.
     * Still, it's not nice on the server...
     */
    fatalError(NULL, error.c_str());
#else
    SE_THROW_EXCEPTION_STATUS(StatusException, error, status);
#endif
}

void SyncContext::throwError(const string &action, int error)
{
    std::string what = action + ": " + strerror(error);
    // be as specific if we can be: relevant for the file backend,
    // which is expected to return STATUS_NOT_FOUND == 404 for "file
    // not found"
    if (error == ENOENT) {
        throwError(STATUS_NOT_FOUND, what);
    } else {
        throwError(what);
    }
}

void SyncContext::fatalError(void *object, const char *error)
{
    SE_LOG_ERROR(NULL, "%s", error);
    if (m_activeContext && m_activeContext->m_sourceListPtr) {
        m_activeContext->m_sourceListPtr->syncDone(STATUS_FATAL, NULL);
    }
    exit(1);
}

/*
 * There have been segfaults inside glib in the background
 * thread which ran the second event loop. Disabled it again,
 * even though the synchronous EDS API calls will block then
 * when EDS dies.
 */
#if 0 && defined(HAVE_GLIB) && defined(HAVE_EDS)
# define RUN_GLIB_LOOP
#endif

#ifdef RUN_GLIB_LOOP
static void *mainLoopThread(void *)
{
    // The test framework uses SIGALRM for timeouts.
    // Block the signal here because a) the signal handler
    // prints a stack back trace when called and we are not
    // interessted in the background thread's stack and b)
    // it seems to have confused glib/libebook enough to
    // access invalid memory and segfault when it gets the SIGALRM.
    sigset_t blocked;
    sigemptyset(&blocked);
    sigaddset(&blocked, SIGALRM);
    pthread_sigmask(SIG_BLOCK, &blocked, NULL);

    GMainLoop *mainloop = g_main_loop_new(NULL, TRUE);
    if (mainloop) {
        g_main_loop_run(mainloop);
        g_main_loop_unref(mainloop);
    }
    return NULL;
}
#endif

void SyncContext::startLoopThread()
{
#ifdef RUN_GLIB_LOOP
    // when using Evolution we must have a running main loop,
    // otherwise loss of connection won't be reported to us
    static pthread_t loopthread;
    static bool loopthreadrunning;
    if (!loopthreadrunning) {
        loopthreadrunning = !pthread_create(&loopthread, NULL, mainLoopThread, NULL);
    }
#endif
}

SyncSource *SyncContext::findSource(const std::string &name)
{
    if (!m_activeContext || !m_activeContext->m_sourceListPtr) {
        return NULL;
    }
    const char *realname = strrchr(name.c_str(), m_findSourceSeparator);
    if (realname) {
        realname++;
    } else {
        realname = name.c_str();
    }
    return (*m_activeContext->m_sourceListPtr)[realname];
}

SyncContext *SyncContext::findContext(const char *sessionName)
{
    return m_activeContext;
}

void SyncContext::initSources(SourceList &sourceList)
{
    list<string> configuredSources = getSyncSources();
    map<string, string> subSources;

    // Disambiguate source names because we have multiple with the same
    // name active?
    string contextName;
    if (m_localSync) {
        contextName = getContextName();
    }

    // Phase 1, check all virtual sync soruces
    BOOST_FOREACH(const string &name, configuredSources) {
        boost::shared_ptr<PersistentSyncSourceConfig> sc(getSyncSourceConfig(name));
        SyncSourceNodes source = getSyncSourceNodes (name);
        std::string sync = sc->getSync();
        SyncMode mode = StringToSyncMode(sync);
        if (mode != SYNC_NONE) {
            SourceType sourceType = SyncSource::getSourceType(source);
            if (sourceType.m_backend == "virtual") {
                //This is a virtual sync source, check and enable the referenced
                //sub syncsources here
                SyncSourceParams params(name, source, boost::shared_ptr<SyncConfig>(this, SyncConfigNOP()), contextName);
                boost::shared_ptr<VirtualSyncSource> vSource = boost::shared_ptr<VirtualSyncSource> (new VirtualSyncSource (params));
                std::vector<std::string> mappedSources = vSource->getMappedSources();
                BOOST_FOREACH (std::string source, mappedSources) {
                    //check whether the mapped source is really available
                    boost::shared_ptr<PersistentSyncSourceConfig> source_config 
                        = getSyncSourceConfig(source);
                    if (!source_config || !source_config->exists()) {
                        throwError(StringPrintf("Virtual data source \"%s\" references a nonexistent datasource \"%s\".", name.c_str(), source.c_str()));
                    }
                    pair< map<string, string>::iterator, bool > res = subSources.insert(make_pair(source, name));
                    if (!res.second) {
                        throwError(StringPrintf("Data source \"%s\" included in the virtual sources \"%s\" and \"%s\". It can only be included in one virtual source at a time.",
                                                source.c_str(), res.first->second.c_str(), name.c_str()));
                    }

                }
                FilterConfigNode::ConfigFilter vFilter;
                vFilter["sync"] = sync;
                if (!m_serverMode) {
                    // must set special URI for clients so that
                    // engine knows about superdatastore and its
                    // URI
                    vFilter["uri"] = string("<") + vSource->getName() + ">" + vSource->getURINonEmpty();
                }
                BOOST_FOREACH (std::string source, mappedSources) {
                    setConfigFilter (false, source, vFilter);
                }
                sourceList.addSource(vSource);
            }
        }
    }

    BOOST_FOREACH(const string &name, configuredSources) {
        boost::shared_ptr<PersistentSyncSourceConfig> sc(getSyncSourceConfig(name));

        SyncSourceNodes source = getSyncSourceNodes (name);
        if (!sc->isDisabled()) {
            SourceType sourceType = SyncSource::getSourceType(source);
            if (sourceType.m_backend != "virtual") {
                SyncSourceParams params(name,
                                        source,
                                        boost::shared_ptr<SyncConfig>(this, SyncConfigNOP()),
                                        contextName);
                cxxptr<SyncSource> syncSource(SyncSource::createSource(params));
                if (!syncSource) {
                    throwError(name + ": type unknown" );
                }
                if (subSources.find(name) != subSources.end()) {
                    syncSource->recordVirtualSource(subSources[name]);
                }
                sourceList.addSource(syncSource);
            }
        } else {
            // the Synthesis engine is never going to see this source,
            // therefore we have to mark it as 100% complete and
            // "done"
            class DummySyncSource source(name, contextName);
            source.recordFinalSyncMode(SYNC_NONE);
            displaySourceProgress(sysync::PEV_PREPARING,
                                  source,
                                  0, 0, 0);
            displaySourceProgress(sysync::PEV_ITEMPROCESSED,
                                  source,
                                  0, 0, 0);
            displaySourceProgress(sysync::PEV_ITEMRECEIVED,
                                  source,
                                  0, 0, 0);
            displaySourceProgress(sysync::PEV_ITEMSENT,
                                  source,
                                  0, 0, 0);
            displaySourceProgress(sysync::PEV_SYNCEND,
                                  source,
                                  0, 0, 0);
        }
    }
}

void SyncContext::startSourceAccess(SyncSource *source)
{
    if(m_firstSourceAccess) {
        syncSuccessStart();
        m_firstSourceAccess = false;
    }
    if (m_serverMode) {
        // source is active in sync, now open it
        source->open();
    }
    // database dumping is delayed in both client and server
    m_sourceListPtr->syncPrepare(source->getName());
}

// XML configuration converted to C string constants
extern "C" {
    // including all known fragments for a client
    extern const char *SyncEvolutionXMLClient;
    // the remote rules for a client
    extern const char *SyncEvolutionXMLClientRules;
}

/**
 * helper class which scans directories for
 * XML config files
 */
class XMLFiles
{
public:
    enum Category {
        MAIN,           /**< files directly under searched directories */
        DATATYPES,      /**< inside datatypes and datatypes/<mode> */
        SCRIPTING,      /**< inside scripting and scripting/<mode> */
        REMOTERULES,    /**< inside remoterules and remoterules/<mode> */
        MAX_CATEGORY
    };

    /** search file system for XML config fragments */
    void scan(const string &mode);
    /** datatypes, scripts and rules concatenated, empty if none found */
    string get(Category category);
    /** main file, typically "syncevolution.xml", empty if not found */
    string get(const string &file);

    static const string m_syncevolutionXML;

private:
    /* base name as sort key + full file path, iterating is done in lexical order */
    StringMap m_files[MAX_CATEGORY];

    /**
     * scan a specific directory for main files directly inside it
     * and inside datatypes, scripting, remoterules;
     * it is not an error when it does not exist or is not a directory
     */
    void scanRoot(const string &mode, const string &dir);

    /**
     * scan a datatypes/scripting/remoterules sub directory,
     * including the <mode> sub-directory
     */
    void scanFragments(const string &mode, const string &dir, Category category);

    /**
     * add all .xml files to the right hash, overwriting old entries
     */
    void addFragments(const string &dir, Category category);
};

const string XMLFiles::m_syncevolutionXML("syncevolution.xml");

void XMLFiles::scan(const string &mode)
{
    const char *dir = getenv("SYNCEVOLUTION_XML_CONFIG_DIR");
    /*
     * read either one or the other, so that testing can run without
     * accidentally reading installed files
     */
    if (dir) {
        scanRoot(mode, dir);
    } else {
        scanRoot(mode, XML_CONFIG_DIR);
        scanRoot(mode, SubstEnvironment("${XDG_CONFIG_HOME}/syncevolution-xml"));
    }
}

void XMLFiles::scanRoot(const string &mode, const string &dir)
{
    addFragments(dir, MAIN);
    scanFragments(mode, dir + "/scripting", SCRIPTING);
    scanFragments(mode, dir + "/datatypes", DATATYPES);
    scanFragments(mode, dir + "/remoterules", REMOTERULES);
}

void XMLFiles::scanFragments(const string &mode, const string &dir, Category category)
{
    addFragments(dir, category);
    addFragments(dir + "/" + mode, category);
}

void XMLFiles::addFragments(const string &dir, Category category)
{
    if (!isDir(dir)) {
        return;
    }
    ReadDir content(dir);
    BOOST_FOREACH(const string &file, content) {
        if (boost::ends_with(file, ".xml")) {
            m_files[category][file] = dir + "/" + file;
        }
    }
}

string XMLFiles::get(Category category)
{
    string res;

    BOOST_FOREACH(const StringPair &entry, m_files[category]) {
        string content;
        ReadFile(entry.second, content);
        res += content;
    }
    return res;
}

string XMLFiles::get(const string &file)
{
    string res;
    StringMap::const_iterator entry = m_files[MAIN].find(file);
    if (entry != m_files[MAIN].end()) {
        ReadFile(entry->second, res);
    }
    return res;
}

static void substTag(string &xml, const string &tagname, const string &replacement, bool replaceElement = false)
{
    string tag;
    size_t index;

    tag.reserve(tagname.size() + 3);
    tag += "<";
    tag += tagname;
    tag += "/>";

    index = xml.find(tag);
    if (index != xml.npos) {
        string tmp;
        tmp.reserve(tagname.size() * 2 + 2 + 3 + replacement.size());
        if (!replaceElement) {
            tmp += "<";
            tmp += tagname;
            tmp += ">";
        }
        tmp += replacement;
        if (!replaceElement) {
            tmp += "</";
            tmp += tagname;
            tmp += ">";
        }
        xml.replace(index, tag.size(), tmp);
    }
}

static void substTag(string &xml, const string &tagname, const char *replacement, bool replaceElement = false)
{
    substTag(xml, tagname, std::string(replacement), replaceElement);
}

template <class T> void substTag(string &xml, const string &tagname, const T replacement, bool replaceElement = false)
{
    stringstream str;
    str << replacement;
    substTag(xml, tagname, str.str(), replaceElement);
}

void SyncContext::getConfigTemplateXML(const string &mode,
                                       string &xml,
                                       string &rules,
                                       string &configname)
{
    XMLFiles files;

    files.scan(mode);
    xml = files.get(files.m_syncevolutionXML);
    if (xml.empty()) {
        if (mode != "client") {
            SE_THROW(files.m_syncevolutionXML + " not found");
        }
        configname = "builtin XML configuration";
        xml = SyncEvolutionXMLClient;
        rules = SyncEvolutionXMLClientRules;
    } else {
        configname = "XML configuration files";
        rules = files.get(XMLFiles::REMOTERULES);
        substTag(xml, "datatypes",
                 files.get(XMLFiles::DATATYPES) +
                 "    <fieldlists/>\n    <profiles/>\n    <datatypedefs/>\n");
        substTag(xml, "scripting", files.get(XMLFiles::SCRIPTING));
    }
}

void SyncContext::getConfigXML(string &xml, string &configname)
{
    string rules;
    getConfigTemplateXML(m_serverMode ? "server" : "client",
                         xml,
                         rules,
                         configname);

    string tag;
    size_t index;
    unsigned long hash = 0;


    std::set<std::string> flags = getSyncMLFlags();
    bool noctcap = flags.find("noctcap") != flags.end();
    bool norestart = flags.find("norestart") != flags.end();
    const char *sessioninitscript =
        "    <sessioninitscript><![CDATA[\n"
        "      // these variables are possibly modified by rule scripts\n"
        "      TIMESTAMP mindate; // earliest date remote party can handle\n"
        "      INTEGER retransfer_body; // if set to true, body is re-sent to client when message is moved from outbox to sent\n"
        "      mindate=EMPTY; // no limit by default\n"
        "      retransfer_body=FALSE; // normally, do not retransfer email body (and attachments) when moving items to sent box\n"
        "      INTEGER delayedabort;\n"
        "      delayedabort = FALSE;\n"
        "      INTEGER alarmTimeToUTC;\n"
        "      alarmTimeToUTC = FALSE;\n"
        "      INTEGER addInternetEmail;\n"
        "      addInternetEmail = FALSE;\n"
        "      INTEGER stripUID;\n"
        "      stripUID = FALSE;\n"
        "    ]]></sessioninitscript>\n";

    ostringstream clientorserver;
    if (m_serverMode) {
        clientorserver <<
            "  <server type='plugin'>\n"
            "    <plugin_module>SyncEvolution</plugin_module>\n"
            "    <plugin_sessionauth>yes</plugin_sessionauth>\n"
            "    <plugin_deviceadmin>yes</plugin_deviceadmin>\n";

        InitState<unsigned int> configrequestmaxtime = getRequestMaxTime();
        unsigned int requestmaxtime;
        if (configrequestmaxtime.wasSet()) {
            // Explicitly set, use it regardless of the kind of sync.
            // We allow this even if thread support was not available,
            // because if a user enables it explicitly, it's probably
            // for a good reason (= failing client), in which case
            // risking multithreading issues is preferable.
            requestmaxtime = configrequestmaxtime.get();
        } else if (m_remoteInitiated || m_localSync) {
            // We initiated the sync (local sync, Bluetooth). The client
            // should not time out, so there is no need for intermediate
            // message sending.
            //
            // To avoid potential problems and get a single log file,
            // avoid it and multithreading by default.
            requestmaxtime = 0;
        } else {
            // We were contacted by an HTTP client. Reply to client
            // not later than 120 seconds while storage initializes
            // in a background thread.
#ifdef HAVE_THREAD_SUPPORT
            requestmaxtime = 120; // default in seconds
#else
            requestmaxtime = 0;
#endif
        }
        if (requestmaxtime) {
            clientorserver <<
                "    <multithread>yes</multithread>\n"
                "    <requestmaxtime>" << requestmaxtime << "</requestmaxtime>\n";
        } else {
            clientorserver <<
                "    <multithread>no</multithread>\n";
        }

        clientorserver <<
            "\n" <<
            sessioninitscript <<
            "    <sessiontimeout>300</sessiontimeout>\n"
            "\n";
        //do not send respuri if over bluetooth
        if (boost::starts_with (getUsedSyncURL(), "obex-bt://")) {
            clientorserver << "    <sendrespuri>no</sendrespuri>\n"
            "\n";
        }
        clientorserver << "    <syncmodeextensions>" << (norestart ? "no" : "yes" ) << "</syncmodeextensions>\n";
        if (noctcap) {
            clientorserver << "    <showctcapproperties>no</showctcapproperties>\n"
            "\n";
        }
        clientorserver<<"    <defaultauth/>\n"
            "\n"
            "    <datastore/>\n"
            "\n"
            "    <remoterules/>\n"
            "  </server>\n";
    } else {
        clientorserver <<
            "  <client type='plugin'>\n"
            "    <binfilespath>$(binfilepath)</binfilespath>\n"
            "    <multithread>no</multithread>\n"
            "    <defaultauth/>\n";
        if (getRefreshSync()) {
            clientorserver <<
                "    <preferslowsync>no</preferslowsync>\n";
        }
        clientorserver <<
            "\n" ;

         string syncMLVersion (getSyncMLVersion());
         if (!syncMLVersion.empty()) {
             clientorserver << "<defaultsyncmlversion>"
                 <<syncMLVersion.c_str()<<"</defaultsyncmlversion>\n";
         }

         clientorserver << "    <syncmodeextensions>" << (norestart ? "no" : "yes" ) << "</syncmodeextensions>\n";
         if (noctcap) {
             clientorserver << "    <showctcapproperties>no</showctcapproperties>\n"
                 "\n";
         }

         clientorserver << sessioninitscript <<
            // SyncEvolution has traditionally not folded long lines in
            // vCard.  Testing showed that servers still have problems with
            // it, so avoid it by default
            "    <donotfoldcontent>yes</donotfoldcontent>\n"
            "\n"
            "    <fakedeviceid/>\n"
            "\n"
            "    <datastore/>\n"
            "\n"
            "    <remoterules/>\n"
            "  </client>\n";
    }
    substTag(xml,
             "clientorserver",
             clientorserver.str(),
             true);

    tag = "<debug/>";
    index = xml.find(tag);
    if (index != xml.npos) {
        stringstream debug;
        bool logging = !m_sourceListPtr->getLogdir().empty();
        int loglevel = getLogLevel();

        debug <<
            "  <debug>\n"
            // logpath is a config variable set by SyncContext::doSync()
            "    <logpath>$(logpath)</logpath>\n"
            "    <filename>" <<
            LogfileBasename << "</filename>" <<
            "    <logflushmode>flush</logflushmode>\n"
            "    <logformat>html</logformat>\n"
            "    <folding>auto</folding>\n"
            "    <timestamp>yes</timestamp>\n"
            "    <timestampall>yes</timestampall>\n"
            "    <timedsessionlognames>no</timedsessionlognames>\n"
            "    <subthreadmode>separate</subthreadmode>\n"
            "    <logsessionstoglobal>yes</logsessionstoglobal>\n"
            "    <singlegloballog>yes</singlegloballog>\n";
        if (logging) {
            debug <<
                "    <sessionlogs>yes</sessionlogs>\n"
                "    <globallogs>yes</globallogs>\n";
            debug << "<msgdump>" << (loglevel >= 5 ? "yes" : "no") << "</msgdump>\n";
            debug << "<xmltranslate>" << (loglevel >= 4 ? "yes" : "no") << "</xmltranslate>\n";
            if (loglevel >= 3) {
                debug <<
                    "    <sourcelink>doxygen</sourcelink>\n"
                    "    <enable option=\"all\"/>\n"
                    "    <enable option=\"userdata\"/>\n"
                    "    <enable option=\"scripts\"/>\n"
                    "    <enable option=\"exotic\"/>\n";
            }
        } else {
            debug <<
                "    <sessionlogs>no</sessionlogs>\n"
                "    <globallogs>no</globallogs>\n"
                "    <msgdump>no</msgdump>\n"
                "    <xmltranslate>no</xmltranslate>\n"
                "    <disable option=\"all\"/>";
        }
        debug <<
            "  </debug>\n";

        xml.replace(index, tag.size(), debug.str());
    }

    XMLConfigFragments fragments;
    tag = "<datastore/>";
    index = xml.find(tag);
    if (index != xml.npos) {
        stringstream datastores;

        BOOST_FOREACH(SyncSource *source, *m_sourceListPtr) {
            string fragment;
            source->getDatastoreXML(fragment, fragments);
            string name;

            // Make sure that sub-datastores do not interfere with the global URI namespace
            // by adding a <superdatastore>/ prefix. That way we can have a "calendar"
            // alias for "calendar+todo" without conflicting with the underlying
            // "calendar", which will be called "calendar+todo/calendar" in the XML config.
            name = source->getVirtualSource();
            if (!name.empty()) {
                name += m_findSourceSeparator;
            }
            name += source->getName();

            datastores << "    <datastore name='" << name << "' type='plugin'>\n" <<
                "      <dbtypeid>" << source->getSynthesisID() << "</dbtypeid>\n" <<
                fragment;

            datastores << "      <resumesupport>on</resumesupport>\n";
            if (source->getOperations().m_writeBlob) {
                // BLOB support is essential for caching partially received items.
                datastores << "      <resumeitemsupport>on</resumeitemsupport>\n";
            }

            SyncMode mode = StringToSyncMode(source->getSync());
            if (source->getForceSlowSync()) {
                // we *want* a slow sync, but couldn't tell the client -> force it server-side
                datastores << "      <alertscript> FORCESLOWSYNC(); </alertscript>\n";
            } else if (mode == SYNC_LOCAL_CACHE_SLOW ||
                       mode == SYNC_LOCAL_CACHE_INCREMENTAL) {
                if (!m_serverMode) {
                    SE_THROW("sync modes 'local-cache-*' are only supported on the server side");
                }
                datastores << "      <alertscript>SETREFRESHONLY(1); SETCACHEDATA(1);</alertscript>\n";
                // datastores << "      <datastoreinitscript>REFRESHONLY(); CACHEDATA(); SLOWSYNC(); ALERTCODE();</datastoreinitscript>\n";
            } else if (mode != SYNC_SLOW &&
                       // slow-sync detection not implemented when running as server,
                       // not even when initiating the sync (direct sync with phone)
                       !m_serverMode &&
                       // is implemented as "delete local data" + "slow sync",
                       // so a slow sync is acceptable in this case
                       mode != SYNC_REFRESH_FROM_SERVER &&
                       mode != SYNC_REFRESH_FROM_REMOTE &&
                       // The forceSlow should be disabled if the sync session is
                       // initiated by a remote peer (eg. Server Alerted Sync)
                       !m_remoteInitiated &&
                       getPreventSlowSync() &&
                       (!source->getOperations().m_isEmpty ||    // check is only relevant if we have local data;
                        !source->getOperations().m_isEmpty())) { // if we cannot check, assume we have data
                // We are not expecting a slow sync => refuse to execute one.
                // This is the client check for this, server must be handled
                // differently (TODO, MB #2416).
                datastores <<
                    "      <datastoreinitscript><![CDATA[\n"
                    "           if (SLOWSYNC() && ALERTCODE() != 203) {\n" // SLOWSYNC() is true for acceptable refresh-from-client, check for that
                    "              DEBUGMESSAGE(\"slow sync not expected by SyncEvolution, disabling datastore\");\n"
                    "              ABORTDATASTORE(" << sysync::LOCERR_DATASTORE_ABORT << ");\n"
                    "              // tell UI to abort instead of sending the next message\n"
                    "              SETSESSIONVAR(\"delayedabort\", 1);\n"
                    "           }\n"
                    "      ]]></datastoreinitscript>\n";
            }

            if (m_serverMode && !m_localSync) {
                string uri = source->getURI();
                if (!uri.empty()) {
                    datastores << " <alias name='" << uri << "'/>";
                }
            }

            datastores << "    </datastore>\n\n";
        }

        /*If there is super datastore, add it here*/
        //TODO generate specific superdatastore contents (MB #8753)
        //Now only works for synthesis built-in events+tasks
        BOOST_FOREACH (boost::shared_ptr<VirtualSyncSource> vSource, m_sourceListPtr->getVirtualSources()) {
            std::string superType = vSource->getSourceType().m_format;
            std::string evoSyncSource = vSource->getDatabaseID();
            std::vector<std::string> mappedSources = unescapeJoinedString (evoSyncSource, ',');

            // always check for a consistent config
            SourceType sourceType = vSource->getSourceType();
            BOOST_FOREACH (std::string source, mappedSources) {
                //check the data type
                SyncSource *subSource = (*m_sourceListPtr)[source];
                SourceType subType = subSource->getSourceType();

                //If there is no format explictly selected in sub SyncSource, we
                //have no way to determine whether it works with the format
                //specific in the virtual SyncSource, thus no warning in this
                //case.
                if (!subType.m_format.empty() && (
                    sourceType.m_format != subType.m_format ||
                    sourceType.m_forceFormat != subType.m_forceFormat)) {
                    SE_LOG_WARNING(NULL, 
                                   "Virtual data source \"%s\" and sub data source \"%s\" have different data format. Will use the format in virtual data source.",
                                   vSource->getDisplayName().c_str(), source.c_str());
                }
            }

            if (mappedSources.size() !=2) {
                vSource->throwError ("virtual data source currently only supports events+tasks combinations");
            } 

            string name = vSource->getName();
            datastores << "    <superdatastore name= '" << name << "'> \n";
            datastores << "      <contains datastore = '" << name << m_findSourceSeparator << mappedSources[0] <<"'>\n"
                << "        <dispatchfilter>F.ISEVENT:=1</dispatchfilter>\n"
                << "        <guidprefix>e</guidprefix>\n"
                << "      </contains>\n"
                << "\n      <contains datastore = '" << name << m_findSourceSeparator << mappedSources[1] <<"'>\n"
                << "        <dispatchfilter>F.ISEVENT:=0</dispatchfilter>\n"
                << "        <guidprefix>t</guidprefix>\n"
                <<"      </contains>\n" ;

            if (m_serverMode && !m_localSync) {
                string uri = vSource->getURI();
                if (!uri.empty()) {
                    datastores << " <alias name='" << uri << "'/>";
                }
            }

            if (vSource->getForceSlowSync()) {
                // we *want* a slow sync, but couldn't tell the client -> force it server-side
                datastores << "      <alertscript> FORCESLOWSYNC(); </alertscript>\n";
            }

            std::string typesupport;
            typesupport = vSource->getDataTypeSupport();
            datastores << "      <typesupport>\n"
                << typesupport 
                << "      </typesupport>\n";
            datastores <<"\n    </superdatastore>";
        }

        if (datastores.str().empty()) {
            // Add dummy datastore, the engine needs it. sync()
            // checks that we have a valid configuration if it is
            // really needed.
#if 0
            datastores << "<datastore name=\"____dummy____\" type=\"plugin\">"
                "<plugin_module>SyncEvolution</plugin_module>"
                "<fieldmap fieldlist=\"contacts\"/>"
                "<typesupport>"
                "<use datatype=\"vCard30\"/>"
                "</typesupport>"
                "</datastore>";
#endif
        }
        xml.replace(index, tag.size(), datastores.str());
    }

    substTag(xml, "fieldlists", fragments.m_fieldlists.join(), true);
    substTag(xml, "profiles", fragments.m_profiles.join(), true);
    substTag(xml, "datatypedefs", fragments.m_datatypes.join(), true);
    substTag(xml, "remoterules",
             rules +
             fragments.m_remoterules.join(),
             true);

    if (m_serverMode) {
        // TODO: set the device ID for an OBEX server
    } else {
        substTag(xml, "fakedeviceid", getDevID());
    }
    substTag(xml, "model", getMod());
    substTag(xml, "manufacturer", getMan());
    substTag(xml, "hardwareversion", getHwv());
    // abuse (?) the firmware version to store the SyncEvolution version number
    substTag(xml, "firmwareversion", getSwv());
    substTag(xml, "devicetype", getDevType());
    substTag(xml, "maxmsgsize", std::max(getMaxMsgSize().get(), 10000ul));
    substTag(xml, "maxobjsize", std::max(getMaxObjSize().get(), 1024u));
    if (m_serverMode) {
        const string user = getSyncUsername();
        const string password = getSyncPassword();

        /*
         * Do not check username/pwd if this local sync or over
         * bluetooth transport. Need credentials for checking.
         */
        if (!m_localSync &&
            !boost::starts_with(getUsedSyncURL(), "obex-bt") &&
            (!user.empty() || !password.empty())) {
            // require authentication with the configured password
            substTag(xml, "defaultauth",
                     "<requestedauth>md5</requestedauth>\n"
                     "<requiredauth>basic</requiredauth>\n"
                     "<autononce>yes</autononce>\n",
                     true);
        } else {
            // no authentication required
            substTag(xml, "defaultauth",
                     "<logininitscript>return TRUE</logininitscript>\n"
                     "<requestedauth>none</requestedauth>\n"
                     "<requiredauth>none</requiredauth>\n"
                     "<autononce>yes</autononce>\n",
                     true);
        }
    } else {
        substTag(xml, "defaultauth", getClientAuthType());
    }

    // if the hash code is changed, that means the content of the
    // config has changed, save the new hash and regen the configdate
    hash = Hash(xml.c_str());
    if (getHashCode() != hash) {
        setConfigDate();
        setHashCode(hash);
        flush();
    }
    substTag(xml, "configdate", getConfigDate().c_str());
}

SharedEngine SyncContext::createEngine()
{
    SharedEngine engine(new sysync::TEngineModuleBridge);

    // This instance of the engine is used outside of the sync session
    // itself for logging. doSync() then reinitializes it with a full
    // datastore configuration.
    engine.Connect(m_serverMode ?
#ifdef ENABLE_SYNCML_LINKED
                   // use Synthesis client or server engine that we were linked against
                   "[server:]" : "[]",
#else
                   // load engine dynamically
                   "server:libsynthesis.so.0" : "libsynthesis.so.0",
#endif
                   0,
                   sysync::DBG_PLUGIN_NONE|
                   sysync::DBG_PLUGIN_INT|
                   sysync::DBG_PLUGIN_DB|
                   sysync::DBG_PLUGIN_EXOT);

    SharedKey configvars = engine.OpenKeyByPath(SharedKey(), "/configvars");
    string logdir;
    if (m_sourceListPtr) {
        logdir = m_sourceListPtr->getLogdir();
    }
    engine.SetStrValue(configvars, "defout_path",
                       logdir.size() ? logdir : "/dev/null");
    engine.SetStrValue(configvars, "conferrpath", "console");
    engine.SetStrValue(configvars, "binfilepath", getSynthesisDatadir().c_str());
    configvars.reset();

    return engine;
}

namespace {
    void GnutlsLogFunction(int level, const char *str)
    {
        SE_LOG_DEBUG("GNUTLS", "level %d: %s", level, str);
    }
}

void SyncContext::initServer(const std::string &sessionID,
                             SharedBuffer data,
                             const std::string &messageType)
{
    m_serverMode = true;
    m_sessionID = sessionID;
    m_initialMessage = data;
    m_initialMessageType = messageType;
    
}

struct SyncContext::SyncMLMessageInfo
SyncContext::analyzeSyncMLMessage(const char *data, size_t len,
                                  const std::string &messageType)
{
    SyncContext sync;
    SourceList sourceList(sync, false);
    sourceList.setLogLevel(SourceList::LOGGING_SUMMARY);
    sync.m_sourceListPtr = &sourceList;
    SwapContext syncSentinel(&sync);
    sync.initServer("", SharedBuffer(), "");
    SwapEngine swapengine(sync);
    sync.initEngine(false);

    sysync::TEngineProgressInfo progressInfo;
    sysync::uInt16 stepCmd = sysync::STEPCMD_GOTDATA;
    SharedSession session = sync.m_engine.OpenSession(sync.m_sessionID);
    SessionSentinel sessionSentinel(sync, session);

    sync.m_engine.WriteSyncMLBuffer(session, data, len);
    SharedKey sessionKey = sync.m_engine.OpenSessionKey(session);
    sync.m_engine.SetStrValue(sessionKey,
                              "contenttype",
                              messageType);

    // analyze main loop: runs until SessionStep() signals reply or error.
    // Will call our SynthesisDBPlugin callbacks, most importantly
    // SyncEvolution_Session_CheckDevice(), which records the device ID
    // for us.
    do {
        sync.m_engine.SessionStep(session, stepCmd, &progressInfo);
        switch (stepCmd) {
        case sysync::STEPCMD_OK:
        case sysync::STEPCMD_PROGRESS:
            stepCmd = sysync::STEPCMD_STEP;
            break;
        default:
            // whatever it is, cannot proceed
            break;
        }
    } while (stepCmd == sysync::STEPCMD_STEP);

    SyncMLMessageInfo info;
    info.m_deviceID = sync.getSyncDeviceID();
    return info;
}

void SyncContext::initEngine(bool logXML)
{
    string xml, configname;
    getConfigXML(xml, configname);
    try {
        m_engine.InitEngineXML(xml.c_str());
    } catch (const BadSynthesisResult &ex) {
        SE_LOG_ERROR(NULL,
                     "internal error, invalid XML configuration (%s):\n%s",
                     m_sourceListPtr && !m_sourceListPtr->empty() ?
                     "with datastores" :
                     "without datastores",
                     xml.c_str());
        throw;
    }
    if (logXML &&
        getLogLevel() >= 5) {
        SE_LOG_DEV(NULL, "Full XML configuration:\n%s", xml.c_str());
    }
}

// This is just the declaration. The actual function pointer instance
// is inside libsynthesis, which, for historic purposes, doesn't define
// it in its header files (yet).
extern "C" int (*SySync_ConsolePrintf)(FILE *stream, const char *format, ...);

static int nopPrintf(FILE *stream, const char *format, ...) { return 0; }

extern "C"
{
    extern int (*SySync_CondTimedWait)(pthread_cond_t *cond, pthread_mutex_t *mutex, bool &aTerminated, long aMilliSecondsToWait);
}

#ifdef HAVE_GLIB
static gboolean timeout(gpointer data)
{
    // Call me again...
    return true;
}

static int CondTimedWaitGLib(pthread_cond_t * /* cond */, pthread_mutex_t *mutex,
                             bool &terminated, long milliSecondsToWait)
{
    int result = 0;

    // return abstime ? pthread_cond_timedwait(cond, mutex, abstime) : pthread_cond_wait(cond, mutex);
    try {
        pthread_mutex_unlock(mutex);

        SE_LOG_DEBUG(NULL, "wait for background thread: %lds", milliSecondsToWait);
        SuspendFlags &flags = SuspendFlags::getSuspendFlags();

        Timespec now = Timespec::system();
        Timespec wait(milliSecondsToWait / 1000, milliSecondsToWait % 1000);
        Timespec deadline = now + wait;

        // We don't need to react to thread shutdown immediately (only
        // called once per sync), so a relatively long check interval of
        // one second is okay.
        GLibEvent id(g_timeout_add_seconds(1, timeout, NULL), "timeout");

        while (true) {
            // Thread has terminated?
            pthread_mutex_lock(mutex);
            if (terminated) {
                pthread_mutex_unlock(mutex);
                SE_LOG_DEBUG(NULL, "background thread completed");
                break;
            }
            pthread_mutex_unlock(mutex);

            // Abort? Ignore when waiting for final thread shutdown, because
            // in that case we just get called again.
            if (milliSecondsToWait > 0 && flags.isAborted()) {
                SE_LOG_DEBUG(NULL, "give up waiting for background thread, aborted");
                // Signal error. libsynthesis then assumes that the thread still
                // runs and enters its parallel message sending, which eventually
                // returns control to us.
                result = 1;
                break;
            }

            // Timeout?
            if (milliSecondsToWait > 0 && deadline <= Timespec::system()) {
                SE_LOG_DEBUG(NULL, "give up waiting for background thread, timeout");
                result = 1;
                break;
            }

            // Check event loop with blocking. We'll return after one
            // second.
            g_main_context_iteration(NULL, true);
        }
    } catch (...) {
        Exception::handle(HANDLE_EXCEPTION_FATAL);
    }

    pthread_mutex_lock(mutex);
    return result;
}

#endif

void SyncContext::initMain(const char *appname)
{
#if defined(HAVE_GLIB)
    // this is required when using glib directly or indirectly
    g_type_init();
    g_thread_init(NULL);
    g_set_prgname(appname);

    // redirect glib logging into our own logging
    g_log_set_default_handler(Logger::glogFunc, NULL);

    // Only the main thread may use the default GMainContext.
    // Anything else is unsafe, see https://mail.gnome.org/archives/gtk-list/2013-April/msg00040.html
    // util.cpp:Sleep() checks this and uses the default context
    // when called by the main thread, otherwise falls back to
    // select().
    g_main_context_acquire(NULL);

    SySync_CondTimedWait = CondTimedWaitGLib;
#endif
    if (atoi(getEnv("SYNCEVOLUTION_DEBUG", "0")) > 3) {
        SySync_ConsolePrintf = Logger::sysyncPrintf;
    } else {
        SySync_ConsolePrintf = nopPrintf;
    }

    // invoke optional init parts, for example KDE KApplication init
    // in KDE backend
    GetInitMainSignal()(appname);

    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &sa, NULL);

    // Initializing a potential use of EDS early is necessary for
    // libsynthesis when compiled with
    // --enable-evolution-compatibility: in that mode libical will
    // only be found by libsynthesis after EDSAbiWrapperInit()
    // pulls it into the process by loading libecal.
    EDSAbiWrapperInit();

    if (const char *gnutlsdbg = getenv("SYNCEVOLUTION_GNUTLS_DEBUG")) {
        // Enable libgnutls debugging without creating a hard dependency on it,
        // because we don't call it directly and might not even be linked against
        // it. Therefore check for the relevant symbols via dlsym().
        void (*set_log_level)(int);
        typedef void (*LogFunc_t)(int level, const char *str);
        void (*set_log_function)(LogFunc_t func);
        
        set_log_level = (typeof(set_log_level))dlsym(RTLD_DEFAULT, "gnutls_global_set_log_level");
        set_log_function = (typeof(set_log_function))dlsym(RTLD_DEFAULT, "gnutls_global_set_log_function");

        if (set_log_level && set_log_function) {
            set_log_level(atoi(gnutlsdbg));
            set_log_function(GnutlsLogFunction);
        } else {
            SE_LOG_ERROR(NULL, "SYNCEVOLUTION_GNUTLS_DEBUG debugging not possible, log functions not found");
        }
    }
}

SyncContext::InitMainSignal &SyncContext::GetInitMainSignal()
{
    static InitMainSignal initMainSignal;
    return initMainSignal;
}

static bool IsStableRelease =
#ifdef SYNCEVOLUTION_STABLE_RELEASE
                   true
#else
                   false
#endif
                   ;
bool SyncContext::isStableRelease()
{
    return IsStableRelease;
}
void SyncContext::setStableRelease(bool isStableRelease)
{
    IsStableRelease = isStableRelease;
}

void SyncContext::checkConfig(const std::string &operation) const
{
    std::string peer, context;
    splitConfigString(m_server, peer, context);
    if (isConfigNeeded() &&
        (!exists() || peer.empty())) {
        if (peer.empty()) {
            SE_LOG_INFO(NULL, "Configuration \"%s\" does not refer to a sync peer.", m_server.c_str());
        } else {
            SE_LOG_INFO(NULL, "Configuration \"%s\" does not exist.", m_server.c_str());
        }
        throwError(StringPrintf("Cannot proceed with %s without a configuration.", operation.c_str()));
    }
}

SyncMLStatus SyncContext::sync(SyncReport *report)
{
    SyncMLStatus status = STATUS_OK;

    checkConfig("sync");

    // redirect logging as soon as possible
    SourceList sourceList(*this, m_doLogging);
    sourceList.setLogLevel(m_quiet ? SourceList::LOGGING_QUIET :
                           getPrintChanges() ? SourceList::LOGGING_FULL :
                           SourceList::LOGGING_SUMMARY);

    // careful about scope, this is needed for writing the
    // report below
    SyncReport buffer;

    SwapContext syncSentinel(this);
    try {
        m_sourceListPtr = &sourceList;
        string url = getUsedSyncURL();
        if (boost::starts_with(url, "local://")) {
            initLocalSync(url.substr(strlen("local://")));
        }

        if (!report) {
            report = &buffer;
        }
        report->clear();
        if (m_localSync) {
            report->setRemoteName(m_localPeerContext);
            report->setLocalName(getContextName());
        }

        // let derived classes override settings, like the log dir
        prepare();

        // choose log directory
        sourceList.startSession(getLogDir(),
                                getMaxLogDirs(),
                                getLogLevel(),
                                report);

        /* Must detect server or client session before creating the
         * underlying SynthesisEngine 
         * */
        if ( getPeerIsClient()) {
            m_serverMode = true;
        } else if (m_localSync && !m_agent) {
            throwError("configuration error, syncURL = local can only be used in combination with peerIsClient = 1");
        }

        // create a Synthesis engine, used purely for logging purposes
        // at this time
        SwapEngine swapengine(*this);
        initEngine(false);

        try {
            // dump some summary information at the beginning of the log
            SE_LOG_DEV(NULL, "SyncML server account: %s", getSyncUsername().c_str());
            SE_LOG_DEV(NULL, "client: SyncEvolution %s for %s", getSwv().c_str(), getDevType().c_str());
            SE_LOG_DEV(NULL, "device ID: %s", getDevID().c_str());
            SE_LOG_DEV(NULL, "%s", EDSAbiWrapperDebug());
            SE_LOG_DEV(NULL, "%s", SyncSource::backendsDebug().c_str());

            // ensure that config can be modified (might have to be migrated first)
            prepareConfigForWrite();

            // instantiate backends, but do not open them yet
            initSources(sourceList);
            if (sourceList.empty()) {
                throwError("no sources active, check configuration");
            }

            // request all config properties once: throwing exceptions
            // now is okay, whereas later it would lead to leaks in the
            // not exception safe client library
            SyncConfig dummy;
            set<string> activeSources = sourceList.getSources();
            dummy.copy(*this, &activeSources);

            // start background thread if not running yet:
            // necessary to catch problems with Evolution backend
            startLoopThread();

            // ask for passwords now
            /* iterator over all sync and source properties instead of checking
             * some specified passwords.
             */
            ConfigPropertyRegistry& registry = SyncConfig::getRegistry();
            BOOST_FOREACH(const ConfigProperty *prop, registry) {
                SE_LOG_DEBUG(NULL, "checking sync password %s", prop->getMainName().c_str());
                prop->checkPassword(getUserInterfaceNonNull(), m_server, *getProperties());
            }
            BOOST_FOREACH(SyncSource *source, sourceList) {
                ConfigPropertyRegistry& registry = SyncSourceConfig::getRegistry();
                BOOST_FOREACH(const ConfigProperty *prop, registry) {
                    SE_LOG_DEBUG(NULL, "checking source %s password %s",
                                 source->getName().c_str(),
                                 prop->getMainName().c_str());
                    prop->checkPassword(getUserInterfaceNonNull(), m_server, *getProperties(),
                                        source->getName(), source->getProperties());
                }
            }

            // open each source - failing now is still safe
            // in clients; in servers we wait until the source
            // is really needed
            BOOST_FOREACH(SyncSource *source, sourceList) {
                if (m_serverMode) {
                    source->enableServerMode();
                } else {
                    source->open();
                }

                // request callback when starting to use source
                source->getOperations().m_startDataRead.getPreSignal().connect(boost::bind(&SyncContext::startSourceAccess, this, source));
            }

            // ready to go
            status = doSync();
        } catch (...) {
            // handle the exception here while the engine (and logging!) is still alive
            Exception::handle(&status);
            goto report;
        }
    } catch (...) {
        Exception::handle(&status);
    }

 report:
    if (status == SyncMLStatus(sysync::LOCERR_DATASTORE_ABORT)) {
        // this can mean only one thing in SyncEvolution: unexpected slow sync
        status = STATUS_UNEXPECTED_SLOW_SYNC;
    }
                            

    try {
        // Print final report before cleaning up.
        // Status was okay only if all sources succeeded.
        // When a source or the overall sync was successful,
        // but some items failed, we report a "partial failure"
        // status.
        BOOST_FOREACH(SyncSource *source, sourceList) {
            if (source->getStatus() == STATUS_OK &&
                (source->getItemStat(SyncSource::ITEM_LOCAL,
                                     SyncSource::ITEM_ANY,
                                     SyncSource::ITEM_REJECT) ||
                 source->getItemStat(SyncSource::ITEM_REMOTE,
                                     SyncSource::ITEM_ANY,
                                     SyncSource::ITEM_REJECT))) {
                source->recordStatus(STATUS_PARTIAL_FAILURE);
            }
            if (source->getStatus() != STATUS_OK &&
                status == STATUS_OK) {
                status = source->getStatus();
                break;
            }
        }

        // Also take into account result of client side in local sync,
        // if any existed. A non-success status code in the client's report
        // was already propagated to the parent via a TransportStatusException
        // in LocalTransportAgent::checkChildReport(). What we can do here
        // is updating the individual's sources status.
        if (m_localSync && m_agent && getPeerIsClient()) {
            boost::shared_ptr<LocalTransportAgent> agent = boost::static_pointer_cast<LocalTransportAgent>(m_agent);
            SyncReport childReport;
            agent->getClientSyncReport(childReport);
            BOOST_FOREACH(SyncSource *source, sourceList) {
                const SyncSourceReport *childSourceReport = childReport.findSyncSourceReport(source->getURINonEmpty());
                if (childSourceReport) {
                    SyncMLStatus parentSourceStatus = source->getStatus();
                    SyncMLStatus childSourceStatus = childSourceReport->getStatus();
                    // child source had an error *and*
                    // parent error is either unspecific (USERABORT) or
                    // is a remote error (HTTP error range)
                    if (childSourceStatus != STATUS_OK && childSourceStatus != STATUS_HTTP_OK &&
                        (parentSourceStatus == SyncMLStatus(sysync::LOCERR_USERABORT) ||
                         parentSourceStatus < SyncMLStatus(sysync::LOCAL_STATUS_CODE))) {
                        source->recordStatus(childSourceStatus);
                    }
                }
            }
        }

        sourceList.updateSyncReport(*report);
        sourceList.syncDone(status, report);
    } catch(...) {
        Exception::handle(&status);
    }

    m_agent.reset();
    m_sourceListPtr = NULL;
    return status;
}

bool SyncContext::sendSAN(uint16_t version) 
{
    sysync::SanPackage san;
    bool legacy = version < 12;
    /* Should be nonce sent by the server in the preceeding sync session */
    string nonce = "SyncEvolution";
    string uauthb64 = san.B64_H (getSyncUsername(), getSyncPassword());
    /* Client is expected to conduct the sync in the backgroud */
    sysync::UI_Mode mode = sysync::UI_not_specified;

    uint16_t sessionId = 1;
    string serverId = getRemoteIdentifier();
    if(serverId.empty()) {
        serverId = getDevID();
    }
    SE_LOG_DEBUG(NULL, "starting SAN %u auth %s nonce %s session %u server %s",
                 version,
                 uauthb64.c_str(),
                 nonce.c_str(),
                 sessionId,
                 serverId.c_str());
    san.PreparePackage( uauthb64, nonce, version, mode, 
            sysync::Initiator_Server, sessionId, serverId);

    san.CreateEmptyNotificationBody();
    bool hasSource = false;
     
    std::set<std::string> dataSources = m_sourceListPtr->getSources();

    /* For each virtual datasoruce, generate the SAN accoring to it and ignoring
     * sub datasource in the later phase*/
    BOOST_FOREACH (boost::shared_ptr<VirtualSyncSource> vSource, m_sourceListPtr->getVirtualSources()) {
            std::string evoSyncSource = vSource->getDatabaseID();
            std::string sync = vSource->getSync();
            SANSyncMode mode = AlertSyncMode(StringToSyncMode(sync, true), getPeerIsClient());
            std::vector<std::string> mappedSources = unescapeJoinedString (evoSyncSource, ',');
            BOOST_FOREACH (std::string source, mappedSources) {
                dataSources.erase (source);
                if (mode == SA_SLOW) {
                    // We force a source which the client is not expected to use into slow mode.
                    // Shouldn't we rather reject attempts to synchronize it?
                    (*m_sourceListPtr)[source]->setForceSlowSync(true);
                }
            }
            dataSources.insert (vSource->getName());
    }

    SANSyncMode syncMode = SA_INVALID;
    vector<pair <string, string> > alertedSources;

    /* For each source to be notified do the following: */
    BOOST_FOREACH (string name, dataSources) {
        boost::shared_ptr<PersistentSyncSourceConfig> sc(getSyncSourceConfig(name));
        string sync = sc->getSync();
        SANSyncMode mode = AlertSyncMode(StringToSyncMode(sync, true), getPeerIsClient());
        if (mode == SA_SLOW) {
            (*m_sourceListPtr)[name]->setForceSlowSync(true);
            mode = SA_TWO_WAY;
        }
        if (mode < SA_FIRST || mode > SA_LAST) {
            SE_LOG_DEV(NULL, "Ignoring data source %s with an invalid sync mode", name.c_str());
            continue;
        }
        syncMode = mode;
        hasSource = true;
        string uri = sc->getURINonEmpty();

        SourceType sourceType = sc->getSourceType();
        /*If the type is not set by user explictly, let's use backend default
         * value*/
        if(sourceType.m_format.empty()) {
            sourceType.m_format = (*m_sourceListPtr)[name]->getPeerMimeType();
        }
        if (!legacy) {
            /*If user did not use force type, we will always use the older type as
             * this is what most phones support*/
            int contentTypeB = StringToContentType (sourceType.m_format, sourceType.m_forceFormat);
            if (contentTypeB == WSPCTC_UNKNOWN) {
                contentTypeB = 0;
                SE_LOG_DEBUG(NULL, "Unknown datasource mimetype, use 0 as default");
            }
            SE_LOG_DEBUG(NULL, "SAN source %s uri %s type %u mode %d",
                         name.c_str(),
                         uri.c_str(),
                         contentTypeB,
                         mode);
            if ( san.AddSync(mode, (uInt32) contentTypeB, uri.c_str())) {
                SE_LOG_ERROR(NULL, "SAN: adding server alerted sync element failed");
            };
        } else {
            string mimetype = GetLegacyMIMEType(sourceType.m_format, sourceType.m_forceFormat);
            SE_LOG_DEBUG(NULL, "SAN source %s uri %s type %s",
                         name.c_str(),
                         uri.c_str(),
                         mimetype.c_str());
            alertedSources.push_back(std::make_pair(mimetype, uri));
        }
    }

    if (!hasSource) {
        SE_THROW ("No source enabled for server alerted sync!");
    }

    /* Generate the SAN Package */
    void *buffer;
    size_t sanSize;
    if (!legacy) {
        if (san.GetPackage(buffer, sanSize)){
            SE_LOG_ERROR(NULL, "SAN package generating failed");
            return false;
        }
        //TODO log the binary SAN content
    } else {
        SE_LOG_DEBUG(NULL, "SAN with overall sync mode %d", syncMode);
        if (san.GetPackageLegacy(buffer, sanSize, alertedSources, syncMode, getWBXML())){
            SE_LOG_ERROR(NULL, "SAN package generating failed");
            return false;
        }
        //SE_LOG_DEBUG(NULL, "SAN package content: %s", (char*)buffer);
    }

    m_agent = createTransportAgent();
    SE_LOG_INFO(NULL, "Server sending SAN");
    m_serverAlerted = true;
    m_agent->setContentType(!legacy ? 
                           TransportAgent::m_contentTypeServerAlertedNotificationDS
                           : (getWBXML() ? TransportAgent::m_contentTypeSyncWBXML :
                            TransportAgent::m_contentTypeSyncML));
    m_agent->send(reinterpret_cast <char *> (buffer), sanSize);
    //change content type
    m_agent->setContentType(getWBXML() ? TransportAgent::m_contentTypeSyncWBXML :
                            TransportAgent::m_contentTypeSyncML);

    TransportAgent::Status status;
    do {
        status = m_agent->wait();
    } while(status == TransportAgent::ACTIVE);
    if (status == TransportAgent::GOT_REPLY) {
        const char *reply;
        size_t replyLen;
        string contentType;
        m_agent->getReply (reply, replyLen, contentType);

        //sanity check for the reply 
        if (contentType.empty() || 
            contentType.find(TransportAgent::m_contentTypeSyncML) != contentType.npos ||
            contentType.find(TransportAgent::m_contentTypeSyncWBXML) != contentType.npos) {
            SharedBuffer request (reply, replyLen);
            //TODO should generate more reasonable sessionId here
            string sessionId ="";
            initServer (sessionId, request, contentType);
            return true;
        }
    }
    return false;
}

static string Step2String(sysync::uInt16 stepcmd)
{
    switch (stepcmd) {
    case sysync::STEPCMD_CLIENTSTART: return "STEPCMD_CLIENTSTART";
    case sysync::STEPCMD_CLIENTAUTOSTART: return "STEPCMD_CLIENTAUTOSTART";
    case sysync::STEPCMD_STEP: return "STEPCMD_STEP";
    case sysync::STEPCMD_GOTDATA: return "STEPCMD_GOTDATA";
    case sysync::STEPCMD_SENTDATA: return "STEPCMD_SENTDATA";
    case sysync::STEPCMD_SUSPEND: return "STEPCMD_SUSPEND";
    case sysync::STEPCMD_ABORT: return "STEPCMD_ABORT";
    case sysync::STEPCMD_TRANSPFAIL: return "STEPCMD_TRANSPFAIL";
    case sysync::STEPCMD_TIMEOUT: return "STEPCMD_TIMEOUT";
    case sysync::STEPCMD_SAN_CHECK: return "STEPCMD_SAN_CHECK";
    case sysync::STEPCMD_AUTOSYNC_CHECK: return "STEPCMD_AUTOSYNC_CHECK";
    case sysync::STEPCMD_OK: return "STEPCMD_OK";
    case sysync::STEPCMD_PROGRESS: return "STEPCMD_PROGRESS";
    case sysync::STEPCMD_ERROR: return "STEPCMD_ERROR";
    case sysync::STEPCMD_SENDDATA: return "STEPCMD_SENDDATA";
    case sysync::STEPCMD_NEEDDATA: return "STEPCMD_NEEDDATA";
    case sysync::STEPCMD_RESENDDATA: return "STEPCMD_RESENDDATA";
    case sysync::STEPCMD_DONE: return "STEPCMD_DONE";
    case sysync::STEPCMD_RESTART: return "STEPCMD_RESTART";
    case sysync::STEPCMD_NEEDSYNC: return "STEPCMD_NEEDSYNC";
    default: return StringPrintf("STEPCMD %d", stepcmd);
    }
}

SyncMLStatus SyncContext::doSync()
{
    boost::shared_ptr<SuspendFlags::Guard> signalGuard;
    // install signal handlers unless this was explicitly disabled
    bool catchSignals = getenv("SYNCEVOLUTION_NO_SYNC_SIGNALS") == NULL;
    if (catchSignals) {
        SE_LOG_DEBUG(NULL, "sync is starting, catch signals");
        signalGuard = SuspendFlags::getSuspendFlags().activate();
    }

    // delay the sync for debugging purposes
    SE_LOG_DEBUG(NULL, "ready to sync");
    const char *delay = getenv("SYNCEVOLUTION_SYNC_DELAY");
    if (delay) {
        Sleep(atoi(delay));
    }

    SuspendFlags &flags = SuspendFlags::getSuspendFlags();
    if (!flags.isNormal()) {
        return (SyncMLStatus)sysync::LOCERR_USERABORT;
    }

    SyncMLStatus status = STATUS_OK;
    std::string s;

    if (m_serverMode &&
        !m_initialMessage.size() &&
        !m_localSync) {
        //This is a server alerted sync !
        string sanFormat (getSyncMLVersion());
        uint16_t version = 12;
        if (boost::iequals (sanFormat, "1.2") ||
            sanFormat == "") {
            version = 12;
        } else if (boost::iequals (sanFormat, "1.1")) {
            version = 11;
        } else {
            version = 10;
        }

        bool status = true;
        try {
            status = sendSAN (version);
        } catch (TransportException e) {
            if (!sanFormat.empty()){
                throw;
            }
            status = false;
            //by pass the exception if we will try again with legacy SANFormat
        }

        if (!flags.isNormal()) {
            return (SyncMLStatus)sysync::LOCERR_USERABORT;
        }

        if (! status) {
            if (sanFormat.empty()) {
                SE_LOG_DEBUG(NULL, "Server Alerted Sync init with SANFormat %d failed, trying with legacy format", version);
                version = 11;
                if (!sendSAN (version)) {
                    // return a proper error code 
                    throwError ("Server Alerted Sync init failed");
                }
            } else {
                // return a proper error code 
                throwError ("Server Alerted Sync init failed");
            }
        }
    }

    if (!flags.isNormal()) {
        return (SyncMLStatus)sysync::LOCERR_USERABORT;
    }

    // re-init engine with all sources configured
    string xml, configname;
    initEngine(true);

    SharedKey targets;
    SharedKey target;
    if (m_serverMode) {
        // Server engine has no profiles. All settings have be done
        // via the XML configuration or function parameters (session ID
        // in OpenSession()).
    } else {
        // check the settings status (MUST BE DONE TO MAKE SETTINGS READY)
        SharedKey profiles = m_engine.OpenKeyByPath(SharedKey(), "/profiles");
        m_engine.GetStrValue(profiles, "settingsstatus");
        // allow creating new settings when existing settings are not up/downgradeable
        m_engine.SetStrValue(profiles, "overwrite",  "1");
        // check status again
        m_engine.GetStrValue(profiles, "settingsstatus");
    
        // open first profile
        SharedKey profile;
        profile = m_engine.OpenSubkey(profiles, sysync::KEYVAL_ID_FIRST, true);
        if (!profile) {
            // no profile exists  yet, create default profile
            profile = m_engine.OpenSubkey(profiles, sysync::KEYVAL_ID_NEW_DEFAULT);
        }
         
        m_engine.SetStrValue(profile, "serverURI", getUsedSyncURL());
        m_engine.SetStrValue(profile, "serverUser", getSyncUsername());
        m_engine.SetStrValue(profile, "serverPassword", getSyncPassword());
        m_engine.SetInt32Value(profile, "encoding",
                               getWBXML() ? 1 /* WBXML */ : 2 /* XML */);

        // Iterate over all data stores in the XML config
        // and match them with sync sources.
        // TODO: let sync sources provide their own
        // XML snippets (inside <client> and inside <datatypes>).
        targets = m_engine.OpenKeyByPath(profile, "targets");

        for(target = m_engine.OpenSubkey(targets, sysync::KEYVAL_ID_FIRST, true);
            target;
            target = m_engine.OpenSubkey(targets, sysync::KEYVAL_ID_NEXT, true)) {
            s = m_engine.GetStrValue(target, "dbname");
            SyncSource *source = findSource(s);
            if (source) {
                m_engine.SetInt32Value(target, "enabled", 1);
                int slow = 0;
                int direction = 0;
                string sync = source->getSync();
                // this code only runs when we are the client,
                // take that into account for the "from-local/remote" modes
                SimpleSyncMode mode = SimplifySyncMode(StringToSyncMode(sync), false);
                if (mode == SIMPLE_SYNC_SLOW) {
                    slow = 1;
                    direction = 0;
                } else if (mode == SIMPLE_SYNC_TWO_WAY) {
                    slow = 0;
                    direction = 0;
                } else if (mode == SIMPLE_SYNC_REFRESH_FROM_REMOTE) {
                    slow = 1;
                    direction = 1;
                } else if (mode == SIMPLE_SYNC_REFRESH_FROM_LOCAL) {
                    slow = 1;
                    direction = 2;
                } else if (mode == SIMPLE_SYNC_ONE_WAY_FROM_REMOTE) {
                    slow = 0;
                    direction = 1;
                } else if (mode == SIMPLE_SYNC_ONE_WAY_FROM_LOCAL) {
                    slow = 0;
                    direction = 2;
                } else {
                    source->throwError(string("invalid sync mode: ") + sync);
                }
                m_engine.SetInt32Value(target, "forceslow", slow);
                m_engine.SetInt32Value(target, "syncmode", direction);

                string uri = source->getURINonEmpty();
                m_engine.SetStrValue(target, "remotepath", uri);
            } else {
                m_engine.SetInt32Value(target, "enabled", 0);
            }
        }

        // Close all keys so that engine can flush the modified config.
        // Otherwise the session reads the unmodified values from the
        // created files while the updated values are still in memory.
        target.reset();
        targets.reset();
        profile.reset();
        profiles.reset();

        // reopen profile keys
        profiles = m_engine.OpenKeyByPath(SharedKey(), "/profiles");
        m_engine.GetStrValue(profiles, "settingsstatus");
        profile = m_engine.OpenSubkey(profiles, sysync::KEYVAL_ID_FIRST);
        targets = m_engine.OpenKeyByPath(profile, "targets");
    }

    m_retries = 0;

    //Create the transport agent if not already created
    if(!m_agent) {
        m_agent = createTransportAgent();
    }

    // server in local sync initiates sync by passing data to forked process
    if (m_serverMode && m_localSync) {
        m_serverAlerted = true;
    }

    sysync::TEngineProgressInfo progressInfo;
    sysync::uInt16 stepCmd = 
        (m_localSync && m_serverMode) ? sysync::STEPCMD_NEEDDATA :
        m_serverMode ?
        sysync::STEPCMD_GOTDATA :
        sysync::STEPCMD_CLIENTSTART;
    SharedSession session = m_engine.OpenSession(m_sessionID);
    SharedBuffer sendBuffer;
    SessionSentinel sessionSentinel(*this, session);

    if (m_serverMode && !m_localSync) {
        m_engine.WriteSyncMLBuffer(session,
                                   m_initialMessage.get(),
                                   m_initialMessage.size());
        SharedKey sessionKey = m_engine.OpenSessionKey(session);
        m_engine.SetStrValue(sessionKey,
                             "contenttype",
                             m_initialMessageType);
        m_initialMessage.reset();

        // TODO: set "sendrespuri" session key to control
        // whether the generated messages contain a respURI
        // (not needed for OBEX)
    }

    // Sync main loop: runs until SessionStep() signals end or error.
    // Exceptions are caught and lead to a call of SessionStep() with
    // parameter STEPCMD_ABORT -> abort session as soon as possible.
    bool aborting = false;
    int suspending = 0; 
    Timespec sendStart, resendStart;
    int requestNum = 0;
    sysync::uInt16 previousStepCmd = stepCmd;
    do {
        try {
            // check for suspend, if so, modify step command for next step
            // Since the suspend will actually be committed until it is
            // sending out a message, we can safely delay the suspend to
            // GOTDATA state.
            // After exception occurs, stepCmd will be set to abort to force
            // aborting, must avoid to change it back to suspend cmd.
            if (flags.isSuspended() && stepCmd == sysync::STEPCMD_GOTDATA) {
                SE_LOG_DEBUG(NULL, "suspending before SessionStep() in STEPCMD_GOTDATA as requested by user");
                stepCmd = sysync::STEPCMD_SUSPEND;
            }

            // Aborting is useful while waiting for a reply and before
            // sending a message (which will just lead to us waiting
            // for the reply, but possibly after doing some slow network
            // IO for setting up the message send).
            //
            // While processing a message we let the engine run, because
            // that is a) likely to be done soon and b) may reduce the
            // breakage caused by aborting a running sync.
            //
            // This check here covers the "waiting for reply" case.
            if ((stepCmd == sysync::STEPCMD_RESENDDATA ||
                 stepCmd == sysync::STEPCMD_SENTDATA ||
                 stepCmd == sysync::STEPCMD_NEEDDATA) &&
                flags.isAborted()) {
                SE_LOG_DEBUG(NULL, "aborting before SessionStep() in %s as requested by script",
                             Step2String(stepCmd).c_str());
                stepCmd = sysync::STEPCMD_ABORT;
            }

            // take next step, but don't abort twice: instead
            // let engine contine with its shutdown
            if (stepCmd == sysync::STEPCMD_ABORT) {
                if (aborting) {
                    SE_LOG_DEBUG(NULL, "engine already notified of abort request, reverting to %s",
                                 Step2String(previousStepCmd).c_str());
                    stepCmd = previousStepCmd;
                } else {
                    aborting = true;
                }
            }
            // same for suspending
            if (stepCmd == sysync::STEPCMD_SUSPEND) {
                if (suspending) {
                    SE_LOG_DEBUG(NULL, "engine already notified of suspend request, reverting to %s",
                                 Step2String(previousStepCmd).c_str());
                    stepCmd = previousStepCmd;
                    suspending++;
                } else {
                    suspending++; 
                }
            }

            if (stepCmd == sysync::STEPCMD_NEEDDATA) {
                // Engine already notified. Don't call it twice
                // with this state, because it doesn't know how
                // to handle this. Skip the SessionStep() call
                // and wait for response.
            } else {
                if (getLogLevel() > 4) {
                    SE_LOG_DEBUG(NULL, "before SessionStep: %s", Step2String(stepCmd).c_str());
                }
                m_engine.SessionStep(session, stepCmd, &progressInfo);
                if (getLogLevel() > 4) {
                    SE_LOG_DEBUG(NULL, "after SessionStep: %s", Step2String(stepCmd).c_str());
                }
                reportStepCmd(stepCmd);
            }

            if (stepCmd == sysync::STEPCMD_SENDDATA &&
                checkForScriptAbort(session)) {
                SE_LOG_DEBUG(NULL, "aborting after SessionStep() in STEPCMD_SENDDATA as requested by script");

                // Catch outgoing message and abort if requested by script.
                // Report which sources are affected, based on their status code.
                set<string> sources;
                BOOST_FOREACH(SyncSource *source, *m_sourceListPtr) {
                    if (source->getStatus() == STATUS_UNEXPECTED_SLOW_SYNC) {
                        string name = source->getVirtualSource();
                        if (name.empty()) {
                            name = source->getName();
                        }
                        sources.insert(name);
                    }
                }
                string explanation = SyncReport::slowSyncExplanation(m_server,
                                                                     sources);
                if (!explanation.empty()) {
                    string sourceparam = boost::join(sources, " ");
                    SE_LOG_ERROR(NULL,
                                 "Aborting because of unexpected slow sync for source(s): %s",
                                 sourceparam.c_str());
                    SE_LOG_INFO(NULL, "%s", explanation.c_str());
                } else {
                    // we should not get here, but if we do, at least log something
                    SE_LOG_ERROR(NULL, "aborting as requested by script");
                }
                stepCmd = sysync::STEPCMD_ABORT;
                continue;
            } else if (stepCmd == sysync::STEPCMD_SENDDATA &&
                       flags.isAborted()) {
                // Catch outgoing message and abort if requested by user.
                SE_LOG_DEBUG(NULL, "aborting after SessionStep() in STEPCMD_SENDDATA as requested by user");
                stepCmd = sysync::STEPCMD_ABORT;
                continue;
            } else if (suspending == 1) {
                //During suspention we actually insert a STEPCMD_SUSPEND cmd
                //Should restore to the original step here
                stepCmd = previousStepCmd;
                continue;
            }

            switch (stepCmd) {
            case sysync::STEPCMD_OK:
                // no progress info, call step again
                stepCmd = sysync::STEPCMD_STEP;
                break;
            case sysync::STEPCMD_PROGRESS:
                // new progress info to show
                // Check special case of interactive display alert
                if (progressInfo.eventtype == sysync::PEV_DISPLAY100) {
                    // alert 100 received from remote, message text is in
                    // SessionKey's "displayalert" field
                    SharedKey sessionKey = m_engine.OpenSessionKey(session);
                    // get message from server to display
                    s = m_engine.GetStrValue(sessionKey,
                                             "displayalert");
                    displayServerMessage(s);
                } else {
                    switch (progressInfo.targetID) {
                    case sysync::KEYVAL_ID_UNKNOWN:
                    case 0 /* used with PEV_SESSIONSTART?! */:
                        displaySyncProgress(sysync::TProgressEventEnum(progressInfo.eventtype),
                                            progressInfo.extra1,
                                            progressInfo.extra2,
                                            progressInfo.extra3);
                        if (progressInfo.eventtype == sysync::PEV_SESSIONEND &&
                            !status) {
                            // remember sync result
                            status = SyncMLStatus(progressInfo.extra1);
                        }
                        break;
                    default: {
                        // specific for a certain sync source:
                        // find it...
                        SyncSource *source = m_sourceListPtr->lookupBySynthesisID(progressInfo.targetID);
                        if (source) {
                            displaySourceProgress(sysync::TProgressEventEnum(progressInfo.eventtype),
                                                  *source,
                                                  progressInfo.extra1,
                                                  progressInfo.extra2,
                                                  progressInfo.extra3);
                        } else {
                            throwError(std::string("unknown target ") + s);
                        }
                        target.reset();
                        break;
                    }
                    }
                }
                stepCmd = sysync::STEPCMD_STEP;
                break;
            case sysync::STEPCMD_ERROR:
                // error, terminate (should not happen, as status is
                // already checked above)
                break;
            case sysync::STEPCMD_RESTART:
                // make sure connection is closed and will be re-opened for next request
                // tbd: close communication channel if still open to make sure it is
                //       re-opened for the next request
                stepCmd = sysync::STEPCMD_STEP;
                m_retries = 0;
                break;
            case sysync::STEPCMD_SENDDATA: {
                // send data to remote

                SharedKey sessionKey = m_engine.OpenSessionKey(session);
                if (m_serverMode) {
                    m_agent->setURL("");
                } else {
                    // use OpenSessionKey() and GetValue() to retrieve "connectURI"
                    // and "contenttype" to be used to send data to the server
                    s = m_engine.GetStrValue(sessionKey,
                                             "connectURI");
                    m_agent->setURL(s);
                }
                s = m_engine.GetStrValue(sessionKey,
                                         "contenttype");
                m_agent->setContentType(s);
                sessionKey.reset();

                sendStart = resendStart = Timespec::monotonic();
                requestNum ++;
                // use GetSyncMLBuffer()/RetSyncMLBuffer() to access the data to be
                // sent or have it copied into caller's buffer using
                // ReadSyncMLBuffer(), then send it to the server
                sendBuffer = m_engine.GetSyncMLBuffer(session, true);
                m_agent->send(sendBuffer.get(), sendBuffer.size());
                stepCmd = sysync::STEPCMD_SENTDATA; // we have sent the data
                break;
            }
            case sysync::STEPCMD_RESENDDATA: {
                SE_LOG_INFO(NULL, "resend previous message, retry #%d", m_retries);
                resendStart = Timespec::monotonic();
                /* We are resending previous message, just read from the
                 * previous buffer */
                m_agent->send(sendBuffer.get(), sendBuffer.size());
                stepCmd = sysync::STEPCMD_SENTDATA; // we have sent the data
                break;
            }
            case sysync::STEPCMD_NEEDDATA:
                if (!sendStart) {
                    // no message sent yet, record start of wait for data
                    sendStart = Timespec::monotonic();
                }
                switch (m_agent->wait()) {
                case TransportAgent::ACTIVE:
                    // Still sending the data?! Don't change anything,
                    // skip SessionStep() above.
                    break;
               
                case TransportAgent::TIME_OUT: {
                    double duration = (Timespec::monotonic() - sendStart).duration();
                    // HTTP SyncML servers cannot resend a HTTP POST
                    // reply.  Other server transports could in theory
                    // resend, but don't have the necessary D-Bus APIs
                    // (MB #6370).
                    // Same if() as below for FAILED.
                    if (m_serverMode ||
                        !m_retryInterval || duration >= m_retryDuration || requestNum == 1) {
                        SE_LOG_INFO(NULL,
                                    "Transport giving up after %d retries and %ld:%02ldmin",
                                    m_retries,
                                    (long)duration / 60,
                                    (long)duration % 60);
                        SE_THROW_EXCEPTION(TransportException, "timeout, retry period exceeded");
                    }else {
                        // Timeout must have been due to retryInterval having passed, resend
                        // immediately.
                        m_retries ++;
                        stepCmd = sysync::STEPCMD_RESENDDATA;
                    }
                    break;
                    }
                case TransportAgent::GOT_REPLY: {
                    const char *reply;
                    size_t replylen;
                    string contentType;
                    m_agent->getReply(reply, replylen, contentType);

                    // sanity check for reply: if known at all, it must be either XML or WBXML
                    if (contentType.empty() ||
                        contentType.find("application/vnd.syncml+wbxml") != contentType.npos ||
                        contentType.find("application/vnd.syncml+xml") != contentType.npos) {
                        // put answer received earlier into SyncML engine's buffer
                        m_retries = 0;
                        sendBuffer.reset();
                        m_engine.WriteSyncMLBuffer(session,
                                                   reply,
                                                   replylen);
                        if (m_serverMode) {
                            SharedKey sessionKey = m_engine.OpenSessionKey(session);
                            m_engine.SetStrValue(sessionKey,
                                                 "contenttype",
                                                 contentType);
                        }
                        stepCmd = sysync::STEPCMD_GOTDATA; // we have received response data
                        break;
                    } else {
                        SE_LOG_DEBUG(NULL, "unexpected content type '%s' in reply, %d bytes:\n%.*s",
                                     contentType.c_str(), (int)replylen, (int)replylen, reply);
                        SE_LOG_ERROR(NULL, "unexpected reply from server; might be a temporary problem, try again later");
                      } //fall through to network failure case
                }
                /* If this is a network error, it usually failed quickly, retry
                 * immediately has likely no effect. Manually sleep here to wait a while
                 * before retry. Sleep time will be calculated so that the
                 * message sending interval equals m_retryInterval.
                 */
                case TransportAgent::FAILED: {
                    // Send might have failed because of abort or
                    // suspend request.
                    if (flags.isSuspended()) {
                        SE_LOG_DEBUG(NULL, "suspending after TransportAgent::FAILED as requested by user");
                        stepCmd = sysync::STEPCMD_SUSPEND;
                        break;
                    } else if (flags.isAborted()) {
                        SE_LOG_DEBUG(NULL, "aborting after TransportAgent::FAILED as requested by user");
                        stepCmd = sysync::STEPCMD_ABORT;
                        break;
                    }

                    Timespec curTime = Timespec::monotonic();
                    double duration = (curTime - sendStart).duration();
                    double resendDelay = m_retryInterval - (curTime - resendStart).duration();
                    if (resendDelay < 0) {
                        resendDelay = 0;
                    }
                    // Similar if() as above for TIME_OUT. In addition, we must check that
                    // the next resend won't happen after the retryDuration, because then
                    // we might as well give up now immediately.
                    if (m_serverMode ||
                        !m_retryInterval || duration + resendDelay >= m_retryDuration || requestNum == 1) {
                        SE_LOG_INFO(NULL,
                                    "Transport giving up after %d retries and %ld:%02ldmin",
                                    m_retries,
                                    (long)duration / 60,
                                    (long)duration % 60);
                        SE_THROW_EXCEPTION(TransportException, "transport failed, retry period exceeded");
                    } else {
                        // Resend after having ensured that the retryInterval is over.
                        if (resendDelay > 0) {
                            if (Sleep(resendDelay) > 0) {
                                if (flags.isSuspended()) {
                                    SE_LOG_DEBUG(NULL, "suspending after premature exit from sleep() caused by user suspend");
                                    stepCmd = sysync::STEPCMD_SUSPEND;
                                } else {
                                    SE_LOG_DEBUG(NULL, "aborting after premature exit from sleep() caused by user abort");
                                    stepCmd = sysync::STEPCMD_ABORT;
                                }
                                break;
                            } 
                        }

                        m_retries ++;
                        stepCmd = sysync::STEPCMD_RESENDDATA;
                    }
                    break;
                }
                case TransportAgent::CANCELED:
                    // Send might have failed because of abort or
                    // suspend request.
                    if (flags.isSuspended()) {
                        SE_LOG_DEBUG(NULL, "suspending after TransportAgent::CANCELED as requested by user");
                        stepCmd = sysync::STEPCMD_SUSPEND;
                        break;
                    } else if (flags.isAborted()) {
                        SE_LOG_DEBUG(NULL, "aborting after TransportAgent::CANCELED as requested by user");
                        stepCmd = sysync::STEPCMD_ABORT;
                        break;
                    }
                    // not sure exactly why it is canceled
                    SE_THROW_EXCEPTION_STATUS(BadSynthesisResult,
                                              "transport canceled",
                                              sysync::LOCERR_USERABORT);
                    break;
                default:
                    stepCmd = sysync::STEPCMD_TRANSPFAIL; // communication with server failed
                    break;
                }
            }

            // Don't tell engine to abort when it already did.
            if (aborting && stepCmd == sysync::STEPCMD_ABORT) {
                stepCmd = sysync::STEPCMD_DONE;
            }

            previousStepCmd = stepCmd;
            // loop until session done or aborted with error
        } catch (const BadSynthesisResult &result) {
            if (result.result() == sysync::LOCERR_USERABORT && aborting) {
                SE_LOG_INFO(NULL, "Aborted as requested.");
                stepCmd = sysync::STEPCMD_DONE;
            } else if (result.result() == sysync::LOCERR_USERSUSPEND && suspending) {
                SE_LOG_INFO(NULL, "Suspended as requested.");
                stepCmd = sysync::STEPCMD_DONE;
            } else if (aborting) {
                // aborting very early can lead to results different from LOCERR_USERABORT
                // => don't treat this as error
                SE_LOG_INFO(NULL, "Aborted with unexpected result (%d)",
                            static_cast<int>(result.result()));
                stepCmd = sysync::STEPCMD_DONE;
            } else {
                Exception::handle(&status);
                SE_LOG_DEBUG(NULL, "aborting after catching fatal error");
                // Don't tell engine to abort when it already did.
                stepCmd = aborting ? sysync::STEPCMD_DONE : sysync::STEPCMD_ABORT;
            }
        } catch (...) {
            Exception::handle(&status);
            SE_LOG_DEBUG(NULL, "aborting after catching fatal error");
            // Don't tell engine to abort when it already did.
            stepCmd = aborting ? sysync::STEPCMD_DONE : sysync::STEPCMD_ABORT;
        }
    } while (stepCmd != sysync::STEPCMD_DONE && stepCmd != sysync::STEPCMD_ERROR);

    // If we get here without error, then close down connection normally.
    // Otherwise destruct the agent without further communication.
    if (!status && !flags.isAborted()) {
        try {
            m_agent->shutdown();
            // TODO: implement timeout for peers which fail to respond
            while (!flags.isAborted() &&
                   m_agent->wait(true) == TransportAgent::ACTIVE) {
                // TODO: allow aborting the sync here
            }
        } catch (...) {
            status = handleException();
        }
    }

    return status;
}

string SyncContext::getSynthesisDatadir()
{
    if (isEphemeral() && m_sourceListPtr) {
        return m_sourceListPtr->getLogdir() + "/synthesis";
    } else if (m_localSync && !m_serverMode) {
        return m_localClientRootPath + "/.synthesis";
    } else {
        return getRootPath() + "/.synthesis";
    }
}

SyncMLStatus SyncContext::handleException()
{
    SyncMLStatus res = Exception::handle();
    return res;
}

void SyncContext::status()
{
    checkConfig("status check");

    SourceList sourceList(*this, false);
    initSources(sourceList);
    BOOST_FOREACH(SyncSource *source, sourceList) {
        ConfigPropertyRegistry& registry = SyncSourceConfig::getRegistry();
        BOOST_FOREACH(const ConfigProperty *prop, registry) {
            prop->checkPassword(getUserInterfaceNonNull(), m_server, *getProperties(),
                                source->getName(), source->getProperties());
        }
    }
    BOOST_FOREACH(SyncSource *source, sourceList) {
        source->open();
    }

    SyncReport changes;
    checkSourceChanges(sourceList, changes);

    stringstream out;
    changes.prettyPrint(out,
                        SyncReport::WITHOUT_SERVER|
                        SyncReport::WITHOUT_CONFLICTS|
                        SyncReport::WITHOUT_REJECTS|
                        SyncReport::WITH_TOTAL);
    SE_LOG_INFO(NULL, "Local item changes:\n%s",
                out.str().c_str());

    sourceList.accessSession(getLogDir());
    Logger::instance().setLevel(Logger::INFO);
    string prevLogdir = sourceList.getPrevLogdir();
    bool found = access(prevLogdir.c_str(), R_OK|X_OK) == 0;

    if (found) {
        if (!m_quiet && getPrintChanges()) {
            try {
                sourceList.setPath(prevLogdir);
                sourceList.dumpDatabases("current", NULL);
                sourceList.dumpLocalChanges("", "after", "current", "");
            } catch(...) {
                Exception::handle();
            }
        }
    } else {
        SE_LOG_SHOW(NULL, "Previous log directory not found.");
        if (getLogDir().empty()) {
            SE_LOG_SHOW(NULL, "Enable the 'logdir' option and synchronize to use this feature.");
        }
    }
}

void SyncContext::checkStatus(SyncReport &report)
{
    checkConfig("status check");

    SourceList sourceList(*this, false);
    initSources(sourceList);
    BOOST_FOREACH(SyncSource *source, sourceList) {
        ConfigPropertyRegistry& registry = SyncSourceConfig::getRegistry();
        BOOST_FOREACH(const ConfigProperty *prop, registry) {
            prop->checkPassword(getUserInterfaceNonNull(), m_server, *getProperties(),
                                source->getName(), source->getProperties());
        }
    }
    BOOST_FOREACH(SyncSource *source, sourceList) {
        source->open();
    }

    checkSourceChanges(sourceList, report);
}

static void logRestoreReport(const SyncReport &report, bool dryrun)
{
    if (!report.empty()) {
        stringstream out;
        report.prettyPrint(out, SyncReport::WITHOUT_SERVER|SyncReport::WITHOUT_CONFLICTS|SyncReport::WITH_TOTAL);
        SE_LOG_INFO(NULL, "Item changes %s applied locally during restore:\n%s",
                    dryrun ? "to be" : "that were",
                    out.str().c_str());
        SE_LOG_INFO(NULL, "The same incremental changes will be applied to the server during the next sync.");
        SE_LOG_INFO(NULL, "Use -sync refresh-from-client to replace the complete data on the server.");
    }
}

void SyncContext::checkSourceChanges(SourceList &sourceList, SyncReport &changes)
{
    changes.setStart(time(NULL));
    BOOST_FOREACH(SyncSource *source, sourceList) {
        SyncSourceReport local;
        if (source->getOperations().m_checkStatus) {
            source->getOperations().m_checkStatus(local);
        } else {
            // no information available
            local.setItemStat(SyncSourceReport::ITEM_LOCAL,
                              SyncSourceReport::ITEM_ADDED,
                              SyncSourceReport::ITEM_TOTAL,
                              -1);
            local.setItemStat(SyncSourceReport::ITEM_LOCAL,
                              SyncSourceReport::ITEM_UPDATED,
                              SyncSourceReport::ITEM_TOTAL,
                              -1);
            local.setItemStat(SyncSourceReport::ITEM_LOCAL,
                              SyncSourceReport::ITEM_REMOVED,
                              SyncSourceReport::ITEM_TOTAL,
                              -1);
            local.setItemStat(SyncSourceReport::ITEM_LOCAL,
                              SyncSourceReport::ITEM_ANY,
                              SyncSourceReport::ITEM_TOTAL,
                              -1);
        }
        changes.addSyncSourceReport(source->getName(), local);
    }
    changes.setEnd(time(NULL));
}

bool SyncContext::checkForScriptAbort(SharedSession session)
{
    try {
        SharedKey sessionKey = m_engine.OpenSessionKey(session);
        SharedKey contextKey = m_engine.OpenKeyByPath(sessionKey, "/sessionvars");
        bool abort = m_engine.GetInt32Value(contextKey, "delayedabort");
        return abort;
    } catch (NoSuchKey) {
        // this is necessary because the session might already have
        // been closed, which removes the variable
        return false;
    } catch (BadSynthesisResult) {
        return false;
    }
}

void SyncContext::restore(const string &dirname, RestoreDatabase database)
{
    checkConfig("restore");

    SourceList sourceList(*this, false);
    sourceList.accessSession(dirname.c_str());
    Logger::instance().setLevel(Logger::INFO);
    initSources(sourceList);
    BOOST_FOREACH(SyncSource *source, sourceList) {
        ConfigPropertyRegistry& registry = SyncSourceConfig::getRegistry();
        BOOST_FOREACH(const ConfigProperty *prop, registry) {
            prop->checkPassword(getUserInterfaceNonNull(), m_server, *getProperties(),
                                source->getName(), source->getProperties());
        }
    }

    string datadump = database == DATABASE_BEFORE_SYNC ? "before" : "after";

    BOOST_FOREACH(SyncSource *source, sourceList) {
        // fake a source alert event
        displaySourceProgress(sysync::PEV_ALERTED, *source, -1, 0, 0);
        source->open();
    }

    if (!m_quiet && getPrintChanges()) {
        sourceList.dumpDatabases("current", NULL);
        sourceList.dumpLocalChanges(dirname, "current", datadump, "",
                                    "Data changes to be applied locally during restore:\n",
                                    "CLIENT_TEST_LEFT_NAME='current data' "
                                    "CLIENT_TEST_REMOVED='after restore' " 
                                    "CLIENT_TEST_REMOVED='to be removed' "
                                    "CLIENT_TEST_ADDED='to be added'");
    }

    SyncReport report;
    try {
        BOOST_FOREACH(SyncSource *source, sourceList) {
            SyncSourceReport sourcereport;
            try {
                displaySourceProgress(sysync::PEV_SYNCSTART, *source, 0, 0, 0);
                sourceList.restoreDatabase(*source,
                                           datadump,
                                           m_dryrun,
                                           sourcereport);
                displaySourceProgress(sysync::PEV_SYNCEND, *source, 0, 0, 0);
                report.addSyncSourceReport(source->getName(), sourcereport);
            } catch (...) {
                sourcereport.recordStatus(STATUS_FATAL);
                report.addSyncSourceReport(source->getName(), sourcereport);
                throw;
            }
        }
    } catch (...) {
        logRestoreReport(report, m_dryrun);
        throw;
    }
    logRestoreReport(report, m_dryrun);
}

void SyncContext::getSessions(vector<string> &dirs)
{
    LogDir::create(*this)->previousLogdirs(dirs);
}

string SyncContext::readSessionInfo(const string &dir, SyncReport &report)
{
    boost::shared_ptr<LogDir> logging(LogDir::create(*this));
    logging->openLogdir(dir);
    logging->readReport(report);
    return logging->getPeerNameFromLogdir(dir);
}

#ifdef ENABLE_UNIT_TESTS
/**
 * This class works LogDirTest as scratch directory.
 * LogDirTest/[file_event|file_contact]_[one|two|empty] contain different
 * sets of items for use in a FileSyncSource.
 *
 * With that setup and a fake SyncContext it is possible to simulate
 * sessions and test the resulting logdirs.
 */
class LogDirTest : public CppUnit::TestFixture, private SyncContext, public Logger
{
public:
    LogDirTest() :
        SyncContext("nosuchconfig@nosuchcontext"),
        m_maxLogDirs(10)
    {
        // suppress output by redirecting into m_out
        addLogger(boost::shared_ptr<Logger>(this, NopDestructor()));
    }

    ~LogDirTest() {
        removeLogger(this);
    }

    void setUp() {
        static const char *vcard_1 =
            "BEGIN:VCARD\n"
            "VERSION:2.1\n"
            "TITLE:tester\n"
            "FN:John Doe\n"
            "N:Doe;John;;;\n"
            "X-MOZILLA-HTML:FALSE\n"
            "TEL;TYPE=WORK;TYPE=VOICE:business 1\n"
            "EMAIL:john.doe@work.com\n"
            "X-AIM:AIM JOHN\n"
            "END:VCARD\n";
        static const char *vcard_2 =
            "BEGIN:VCARD\n"
            "VERSION:2.1\n"
            "TITLE:developer\n"
            "FN:John Doe\n"
            "N:Doe;John;;;\n"
            "X-MOZILLA-HTML:TRUE\n"
            "BDAY:2006-01-08\n"
            "END:VCARD\n";
        static const char *ical_1 =
            "BEGIN:VCALENDAR\n"
            "PRODID:-//Ximian//NONSGML Evolution Calendar//EN\n"
            "VERSION:2.0\n"
            "METHOD:PUBLISH\n"
            "BEGIN:VEVENT\n"
            "SUMMARY:phone meeting\n"
            "DTEND:20060406T163000Z\n"
            "DTSTART:20060406T160000Z\n"
            "UID:1234567890!@#$%^&*()<>@dummy\n"
            "DTSTAMP:20060406T211449Z\n"
            "LAST-MODIFIED:20060409T213201\n"
            "CREATED:20060409T213201\n"
            "LOCATION:calling from home\n"
            "DESCRIPTION:let's talk\n"
            "CLASS:PUBLIC\n"
            "TRANSP:OPAQUE\n"
            "SEQUENCE:1\n"
            "BEGIN:VALARM\n"
            "DESCRIPTION:alarm\n"
            "ACTION:DISPLAY\n"
            "TRIGGER;VALUE=DURATION;RELATED=START:-PT15M\n"
            "END:VALARM\n"
            "END:VEVENT\n"
            "END:VCALENDAR\n";
        static const char *ical_2 =
            "BEGIN:VCALENDAR\n"
            "PRODID:-//Ximian//NONSGML Evolution Calendar//EN\n"
            "VERSION:2.0\n"
            "METHOD:PUBLISH\n"
            "BEGIN:VEVENT\n"
            "SUMMARY:phone meeting\n"
            "DTEND:20060406T163000Z\n"
            "DTSTART:20060406T160000Z\n"
            "UID:1234567890!@#$%^&*()<>@dummy\n"
            "DTSTAMP:20060406T211449Z\n"
            "LAST-MODIFIED:20060409T213201\n"
            "CREATED:20060409T213201\n"
            "LOCATION:my office\n"
            "CATEGORIES:WORK\n"
            "DESCRIPTION:what the heck\\, let's even shout a bit\n"
            "CLASS:PUBLIC\n"
            "TRANSP:OPAQUE\n"
            "SEQUENCE:1\n"
            "END:VEVENT\n"
            "END:VCALENDAR\n";
        rm_r("LogDirTest");
        dump("file_event.one", "1", ical_1);
        dump("file_event.two", "1", ical_1);
        dump("file_event.two", "2", ical_2);
        mkdir_p(getLogData() + "/file_event.empty");
        dump("file_contact.one", "1", vcard_1);
        dump("file_contact.two", "1", vcard_1);
        dump("file_contact.two", "2", vcard_2);
        mkdir_p(getLogData() + "/file_contact.empty");

        mkdir_p(getLogDir());
        m_maxLogDirs = 0;
        m_out.clear();
        m_out.str("");
    }

private:

    string getLogData() { return "LogDirTest/data"; }
    virtual InitStateString getLogDir() const { return "LogDirTest/cache/syncevolution"; }
    int m_maxLogDirs;

    ostringstream m_out;

    void dump(const char *dir, const char *file, const char *data) {
        string name = getLogData();
        name += "/";
        name += dir;
        mkdir_p(name);
        name += "/";
        name += file;
        ofstream out(name.c_str());
        out << data;
    }

    /** capture output produced while test ran */
    void messagev(const MessageOptions &options,
                  const char *format,
                  va_list args)
    {
        std::string str = StringPrintfV(format, args);
        m_out << '[' << levelToStr(options.m_level) << ']' << str;
        if (!boost::ends_with(str, "\n")) {
            m_out << std::endl;
        }
    }

    CPPUNIT_TEST_SUITE(LogDirTest);
    CPPUNIT_TEST(testQuickCompare);
    CPPUNIT_TEST(testSessionNoChanges);
    CPPUNIT_TEST(testSessionChanges);
    CPPUNIT_TEST(testMultipleSessions);
    CPPUNIT_TEST(testExpire);
    CPPUNIT_TEST_SUITE_END();

    /**
     * Simulate a session involving one or more sources.
     *
     * @param changeServer   pretend that peer got changed
     * @param status         result of session
     * @param varargs        sourcename ("file_event"),
     *                       statebefore (NULL for no dump, or suffix like "_one"),
     *                       stateafter (NULL for same as before), ..., NULL
     * @return logdir created for the session
     */
    string session(bool changeServer, SyncMLStatus status, ...) {
        Logger::Level level = Logger::instance().getLevel();
        SourceList list(*this, true);
        list.setLogLevel(SourceList::LOGGING_QUIET);
        SyncReport report;
        list.startSession("", m_maxLogDirs, 0, &report);
        va_list ap;
        va_start(ap, status);
        while (true) {
            const char *sourcename = va_arg(ap, const char *);
            if (!sourcename) {
                break;
            }
            const char *type = NULL;
            if (!strcmp(sourcename, "file_event")) {
                type = "file:text/calendar:2.0";
            } else if (!strcmp(sourcename, "file_contact")) {
                type = "file:text/vcard:3.0";
            }
            CPPUNIT_ASSERT(type);
            string datadir = getLogData() + "/";
            cxxptr<SyncSource> source(SyncSource::createTestingSource(sourcename, type, true,
                                                                      (string("file://") + datadir).c_str()));
            datadir += sourcename;
            datadir += "_1";
            source->open();
            if (changeServer) {
                // fake one added item on server
                source->setItemStat(SyncSourceReport::ITEM_REMOTE,
                                    SyncSourceReport::ITEM_ADDED,
                                    SyncSourceReport::ITEM_TOTAL,
                                    1);
            }
            list.addSource(source);
            const char *before = va_arg(ap, const char *);
            const char *after = va_arg(ap, const char *);
            if (before) {
                // do a "before" dump after directing the source towards the desired data
                rm_r(datadir);
                CPPUNIT_ASSERT_EQUAL(0, symlink((string(sourcename) + before).c_str(),
                                                datadir.c_str()));
                list.syncPrepare(sourcename);
                if (after) {
                    rm_r(datadir);
                    CPPUNIT_ASSERT_EQUAL(0, symlink((string(sourcename) + after).c_str(),
                                                    datadir.c_str()));
                }
            }
        }
        list.syncDone(status, &report);

        Logger::instance().setLevel(level);
        return list.getLogdir();
    }

    typedef vector<string> Sessions_t;
    // full paths to all sessions, sorted
    Sessions_t listSessions() {
        Sessions_t sessions;
        string logdir = getLogDir();
        ReadDir dirs(logdir);
        BOOST_FOREACH(const string &dir, dirs) {
            sessions.push_back(logdir + "/" + dir);
        }
        sort(sessions.begin(), sessions.end());
        return sessions;
    }

    void testQuickCompare() {
        // identical dirs => identical files
        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_event",
                                                     getLogData(), "empty",
                                                     getLogData(), "empty"));
        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_event",
                                                     getLogData(), "one",
                                                     getLogData(), "one"));
        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_event",
                                                     getLogData(), "two",
                                                     getLogData(), "two"));
        // some files shared
        CPPUNIT_ASSERT(!system("cp -l -r LogDirTest/data/file_event.two LogDirTest/data/file_event.copy && rm LogDirTest/data/file_event.copy/2"));
        CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_event",
                                                    getLogData(), "two",
                                                    getLogData(), "copy"));
        CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_event",
                                                    getLogData(), "copy",
                                                    getLogData(), "one"));
    }

    void testSessionNoChanges() {
        ScopedEnvChange config("XDG_CONFIG_HOME", "LogDirTest/config");
        ScopedEnvChange cache("XDG_CACHE_HOME", "LogDirTest/cache");

        // simple session with no changes
        string dir = session(false, STATUS_OK, "file_event", ".one", ".one", (char *)0);
        Sessions_t sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)1, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dir, sessions[0]);
        IniFileConfigNode status(dir, "status.ini", true);
        CPPUNIT_ASSERT(status.exists());
        CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__event-backup-before").get());
        CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__event-backup-after").get());
        CPPUNIT_ASSERT_EQUAL(string("200"), status.readProperty("status").get());
        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_event",
                                                     dir, "before",
                                                     dir, "after"));
    }

    void testSessionChanges() {
        ScopedEnvChange config("XDG_CONFIG_HOME", "LogDirTest/config");
        ScopedEnvChange cache("XDG_CACHE_HOME", "LogDirTest/cache");

        // session with local changes
        string dir = session(false, STATUS_OK, "file_event", ".one", ".two", (char *)0);
        Sessions_t sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)1, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dir, sessions[0]);
        IniFileConfigNode status(dir, "status.ini", true);
        CPPUNIT_ASSERT(status.exists());
        CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__event-backup-before").get());
        CPPUNIT_ASSERT_EQUAL(string("2"), status.readProperty("source-file__event-backup-after").get());
        CPPUNIT_ASSERT_EQUAL(string("200"), status.readProperty("status").get());
        CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_event",
                                                    dir, "before",
                                                    dir, "after"));
    }

    void testMultipleSessions() {
        ScopedEnvChange config("XDG_CONFIG_HOME", "LogDirTest/config");
        ScopedEnvChange cache("XDG_CACHE_HOME", "LogDirTest/cache");

        // two sessions, starting with 1 item, adding 1 during the sync, then
        // removing it again during the second
        string dir = session(false, STATUS_OK,
                             "file_event", ".one", ".two",
                             "file_contact", ".one", ".two",
                             (char *)0);
        {
            Sessions_t sessions = listSessions();
            CPPUNIT_ASSERT_EQUAL((size_t)1, sessions.size());
            CPPUNIT_ASSERT_EQUAL(dir, sessions[0]);
            IniFileConfigNode status(dir, "status.ini", true);
            CPPUNIT_ASSERT(status.exists());
            CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__event-backup-before").get());
            CPPUNIT_ASSERT_EQUAL(string("2"), status.readProperty("source-file__event-backup-after").get());
            CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__contact-backup-before").get());
            CPPUNIT_ASSERT_EQUAL(string("2"), status.readProperty("source-file__contact-backup-after").get());
            CPPUNIT_ASSERT_EQUAL(string("200"), status.readProperty("status").get());
            CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_event",
                                                        dir, "before",
                                                        dir, "after"));
            CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_contact",
                                                        dir, "before",
                                                        dir, "after"));
        }

        string seconddir = session(false, STATUS_OK,
                                   "file_event", ".two", ".one",
                                   "file_contact", ".two", ".one",
                                   (char *)0);
        {
            Sessions_t sessions = listSessions();
            CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
            CPPUNIT_ASSERT_EQUAL(dir, sessions[0]);
            CPPUNIT_ASSERT_EQUAL(seconddir, sessions[1]);
            IniFileConfigNode status(seconddir, "status.ini", true);
            CPPUNIT_ASSERT(status.exists());
            CPPUNIT_ASSERT_EQUAL(string("2"), status.readProperty("source-file__event-backup-before").get());
            CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__event-backup-after").get());
            CPPUNIT_ASSERT_EQUAL(string("2"), status.readProperty("source-file__contact-backup-before").get());
            CPPUNIT_ASSERT_EQUAL(string("1"), status.readProperty("source-file__contact-backup-after").get());
            CPPUNIT_ASSERT_EQUAL(string("200"), status.readProperty("status").get());
            CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_event",
                                                        seconddir, "before",
                                                        seconddir, "after"));
            CPPUNIT_ASSERT(LogDir::haveDifferentContent("file_contact",
                                                        seconddir, "before",
                                                        seconddir, "after"));
        }

        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_event",
                                                     dir, "after",
                                                     seconddir, "before"));
        CPPUNIT_ASSERT(!LogDir::haveDifferentContent("file_contact",
                                                     dir, "after",
                                                     seconddir, "before"));
    }

    void testExpire() {
        ScopedEnvChange config("XDG_CONFIG_HOME", "LogDirTest/config");
        ScopedEnvChange cache("XDG_CACHE_HOME", "LogDirTest/cache");

        string dirs[5];
        Sessions_t sessions;

        m_maxLogDirs = 1;

        // The latest session always must be preserved, even if it
        // is normally considered less important (no error in this case).
        dirs[0] = session(false, STATUS_FATAL, (char *)0);
        dirs[0] = session(false, STATUS_OK, (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)1, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);

        // all things being equal, then expire the oldest session,
        // leaving us with two here
        m_maxLogDirs = 2;
        dirs[0] = session(false, STATUS_OK, (char *)0);
        dirs[1] = session(false, STATUS_OK, (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);

        // When syncing first file_event, then file_contact, both sessions
        // must be preserved despite m_maxLogDirs = 1, otherwise
        // we would loose the only existent backup of file_event.
        dirs[0] = session(false, STATUS_OK, "file_event", ".two", ".one", (char *)0);
        dirs[1] = session(false, STATUS_OK, "file_contact", ".two", ".one", (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);

        // after synchronizing both, we can expire both the old sessions
        m_maxLogDirs = 1;
        dirs[0] = session(false, STATUS_OK,
                          "file_event", ".two", ".one",
                          "file_contact", ".two", ".one",
                          (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)1, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);

        // when doing multiple failed syncs without dumps, keep the sessions
        // which have database dumps
        m_maxLogDirs = 2;
        dirs[1] = session(false, STATUS_FATAL, (char *)0);
        dirs[1] = session(false, STATUS_FATAL, (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);

        // when doing syncs which don't change data, keep the sessions which
        // did change something: keep oldest backup because it created the
        // backups for the first time
        dirs[1] = session(false, STATUS_OK,
                          "file_event", ".one", ".one",
                          "file_contact", ".one", ".one",
                          (char *)0);
        dirs[1] = session(false, STATUS_OK,
                          "file_event", ".one", ".one",
                          "file_contact", ".one", ".one",
                          (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);

        // when making a change in each sync, we end up with the two
        // most recent sessions eventually: first change server,
        // then local
        dirs[1] = session(true, STATUS_OK,
                          "file_event", ".one", ".one",
                          "file_contact", ".one", ".one",
                          (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);
        dirs[0] = dirs[1];
        dirs[1] = session(false, STATUS_OK,
                          "file_event", ".one", ".two",
                          "file_contact", ".one", ".two",
                          (char *)0);
        sessions = listSessions();
        CPPUNIT_ASSERT_EQUAL((size_t)2, sessions.size());
        CPPUNIT_ASSERT_EQUAL(dirs[0], sessions[0]);
        CPPUNIT_ASSERT_EQUAL(dirs[1], sessions[1]);
    }
};
SYNCEVOLUTION_TEST_SUITE_REGISTRATION(LogDirTest);
#endif // ENABLE_UNIT_TESTS

SE_END_CXX