1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
|
/**
* @File localengineds.cpp
*
* @Author Lukas Zeller (luz@synthesis.ch)
*
* @brief TLocalEngineDS
* Abstraction of the local datastore - interface class to the
* sync engine.
*
* Copyright (c) 2001-2009 by Synthesis AG (www.synthesis.ch)
*
* @Date 2005-09-15 : luz : created from localdatastore
*/
// includes
#include "prefix_file.h"
#include "sysync.h"
#include "localengineds.h"
#include "syncappbase.h"
#include "scriptcontext.h"
#include "superdatastore.h"
#include "syncagent.h"
using namespace sysync;
namespace sysync {
#ifdef SYDEBUG
cAppCharP const LocalDSStateNames[numDSStates] = {
"idle",
"client_initialized",
"admin_ready",
"client_sent_alert",
"server_alerted",
"server_answered_alert",
"client_alert_statused",
"client_alerted",
"sync_mode_stable",
"data_access_started",
"sync_set_ready",
"client_sync_gen_started",
"server_seen_client_mods",
"server_sync_gen_started",
"sync_gen_done",
"data_access_done",
"client_maps_sent",
"admin_done",
"completed"
};
#endif
#ifdef OBJECT_FILTERING
// add a new expression to an existing filter
static void addToFilter(const char *aNewFilter, string &aFilter, bool aORChain=false)
{
if (aNewFilter && *aNewFilter) {
// just assign if current filter expression is empty
if (aFilter.empty())
aFilter = aNewFilter;
else {
// construct new filter
string newFilter;
StringObjPrintf(newFilter,"(%s)%c(%s)",aFilter.c_str(),aORChain ? '|' : '&',aNewFilter);
aFilter = newFilter;
}
}
} // addToFilter
#endif
#ifdef SCRIPT_SUPPORT
// Script functions
// ================
class TLDSfuncs {
public:
#ifdef OBJECT_FILTERING
#ifdef SYNCML_TAF_SUPPORT
// string GETCGITARGETFILTER()
// returns current CGI-specified target address filter expression
static void func_GetCGITargetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aTermP->setAsString(dsP->fTargetAddressFilter.c_str());
}; // func_GetCGITargetFilter
// string GETTARGETFILTER()
// returns current internal target address filter expression
static void func_GetTargetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aTermP->setAsString(dsP->fIntTargetAddressFilter.c_str());
}; // func_GetTargetFilter
// SETTARGETFILTER(string filter)
// sets (overwrites) the internal target address filter
static void func_SetTargetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aFuncContextP->getLocalVar(0)->getAsString(dsP->fIntTargetAddressFilter);
}; // func_SetTargetFilter
// ADDTARGETFILTER(string filter)
// adds a filter expression to the existing internal targetfilter (automatically paranthesizing and adding AND)
static void func_AddTargetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
string f;
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aFuncContextP->getLocalVar(0)->getAsString(f);
addToFilter(f.c_str(),dsP->fIntTargetAddressFilter,false); // AND-chaining
}; // func_AddTargetFilter
#endif // SYNCML_TAF_SUPPORT
// string GETFILTER()
// returns current sync set filter expression
static void func_GetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aTermP->setAsString(dsP->fSyncSetFilter.c_str());
}; // func_GetFilter
// SETFILTER(string filter)
// sets (overwrites) the current sync set filter
static void func_SetFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aFuncContextP->getLocalVar(0)->getAsString(dsP->fSyncSetFilter);
dsP->engFilteredFetchesFromDB(true); // update filter dependencies
}; // func_SetFilter
// ADDFILTER(string filter)
// adds a filter expression to the existing (dynamic) targetfilter (automatically paranthesizing and adding AND)
static void func_AddFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
string f;
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aFuncContextP->getLocalVar(0)->getAsString(f);
addToFilter(f.c_str(),dsP->fSyncSetFilter,false); // AND-chaining
dsP->engFilteredFetchesFromDB(true); // update filter dependencies
}; // func_AddFilter
// ADDSTATICFILTER(string filter)
// adds a filter expression to the existing (static) localdbfilter (automatically paranthesizing and adding AND)
static void func_AddStaticFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
string f;
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aFuncContextP->getLocalVar(0)->getAsString(f);
addToFilter(f.c_str(),dsP->fLocalDBFilter,false); // AND-chaining
dsP->engFilteredFetchesFromDB(true); // update filter dependencies
}; // func_AddStaticFilter
#endif // OBJECT_FILTERING
#ifdef SYSYNC_TARGET_OPTIONS
// string DBOPTIONS()
// returns current DB options
static void func_DBOptions(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aTermP->setAsString(dsP->fDBOptions.c_str());
}; // func_DBOptions
// integer DBHANDLESOPTS()
// returns true if database can completely handle options like /dr() and /li during fetching
static void func_DBHandlesOpts(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->dsOptionFilterFetchesFromDB()
);
}; // func_DBHandlesOpts
// timestamp STARTDATE()
// returns startdate if one is set in datastore
static void func_StartDate(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
lineartime_t d = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fDateRangeStart;
TTimestampField *resP = static_cast<TTimestampField *>(aTermP);
if (d==noLinearTime)
resP->assignEmpty();
else
resP->setTimestampAndContext(d,TCTX_UTC);
}; // func_StartDate
// SETSTARTDATE(timestamp startdate)
// sets startdate for datastore
static void func_SetStartDate(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TTimestampField *tsP = static_cast<TTimestampField *>(aFuncContextP->getLocalVar(0));
timecontext_t tctx;
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fDateRangeStart =
tsP->getTimestampAs(TCTX_UTC,&tctx); // floating will also be treated as UTC
}; // func_SetStartDate
// timestamp ENDDATE()
// returns enddate if one is set in datastore
static void func_EndDate(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
lineartime_t d = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fDateRangeEnd;
TTimestampField *resP = static_cast<TTimestampField *>(aTermP);
if (d==noLinearTime)
resP->assignEmpty();
else
resP->setTimestampAndContext(d,TCTX_UTC);
}; // func_EndDate
// SETENDDATE(timestamp startdate)
// sets enddate for datastore
static void func_SetEndDate(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TTimestampField *tsP = static_cast<TTimestampField *>(aFuncContextP->getLocalVar(0));
timecontext_t tctx;
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fDateRangeEnd =
tsP->getTimestampAs(TCTX_UTC,&tctx); // floating will also be treated as UTC
}; // func_SetEndDate
// integer DEFAULTSIZELIMIT()
// returns limit set for all items in this datastore (the /li(xxx) CGI option value)
static void func_DefaultLimit(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
fieldinteger_t i = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fSizeLimit;
if (i<0)
aTermP->unAssign(); // no limit
else
aTermP->setAsInteger(i);
}; // func_DefaultLimit
// SETDEFAULTSIZELIMIT(integer limit)
// sets limit for all items in this datastore (the /li(xxx) CGI option value)
static void func_SetDefaultLimit(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fSizeLimit =
aFuncContextP->getLocalVar(0)->getAsInteger();
}; // func_SetDefaultLimit
// integer NOATTACHMENTS()
// returns true if attachments should be suppressed (/na CGI option)
static void func_NoAttachments(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fNoAttachments
);
}; // func_NoAttachments
// SETNOATTACHMENTS(integer flag)
// if true, attachments will be suppressed (/na CGI option)
static void func_SetNoAttachments(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fNoAttachments =
aFuncContextP->getLocalVar(0)->getAsBoolean();
}; // func_SetNoAttachments
// integer MAXITEMCOUNT()
// returns item count limit (0=none) as set by /max(n) CGI option
static void func_MaxItemCount(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsInteger(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fMaxItemCount
);
}; // func_MaxItemCount
// SETMAXITEMCOUNT(integer maxcount)
// set item count limit (0=none) as set by /max(n) CGI option
static void func_SetMaxItemCount(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fMaxItemCount =
aFuncContextP->getLocalVar(0)->getAsInteger();
}; // func_SetMaxItemCount
#endif // SYSYNC_TARGET_OPTIONS
// integer SLOWSYNC()
// returns true if we are in slow sync
static void func_SlowSync(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->isSlowSync()
);
}; // func_SlowSync
// FORCESLOWSYNC()
// force a slow sync (like with /na CGI option)
static void func_ForceSlowSync(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->engForceSlowSync();
}; // func_ForceSlowSync
// integer ALERTCODE()
// returns the alert code as currently know by datastore (might change from normal to slow while processing)
static void func_AlertCode(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsInteger(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fAlertCode
);
}; // func_AlertCode
// SETALERTCODE(integer maxcount)
// set the alert code (makes sense in alertscript to modify the incoming code to something different)
static void func_SetAlertCode(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fAlertCode =
aFuncContextP->getLocalVar(0)->getAsInteger();
}; // func_SetAlertCode
// integer REFRESHONLY()
// returns true if sync is only refreshing local (note that alert code might be different, as local
// refresh can take place without telling the remote so, for compatibility with clients that do not support the mode)
static void func_RefreshOnly(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->isRefreshOnly()
);
}; // func_RefreshOnly
// SETREFRESHONLY(integer flag)
// modifies the refresh only flag (one way sync from remote to local only)
// Note that clearing this flag when a client has alerted one-way will probably lead to an error
static void func_SetRefreshOnly(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->engSetRefreshOnly(
aFuncContextP->getLocalVar(0)->getAsBoolean()
);
}; // func_SetRefreshOnly
// integer READONLY()
// returns true if sync is read-only (only reading from local datastore)
static void func_ReadOnly(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->isReadOnly()
);
}; // func_ReadOnly
// SETREADONLY(integer flag)
// modifies the read only flag (only reading from local datastore)
static void func_SetReadOnly(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->engSetReadOnly(
aFuncContextP->getLocalVar(0)->getAsBoolean()
);
}; // func_SetReadOnly
// integer FIRSTTIMESYNC()
// returns true if we are in first time slow sync
static void func_FirstTimeSync(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsBoolean(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->isFirstTimeSync()
);
}; // func_FirstTimeSync
// void SETCONFLICTSTRATEGY(string strategy)
// sets conflict strategy for this session
static void func_SetConflictStrategy(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
// convert to syncop
string s;
aFuncContextP->getLocalVar(0)->getAsString(s);
sInt16 strategy;
StrToEnum(conflictStrategyNames,numConflictStrategies, strategy, s.c_str());
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->fSessionConflictStrategy =
(TConflictResolution) strategy;
}; // func_SetConflictStrategy
// string DBNAME()
// returns name of DB
static void func_DBName(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsString(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->getName()
);
}; // func_DBName
// void ABORTDATASTORE(integer statuscode)
static void func_AbortDatastore(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->engAbortDataStoreSync(aFuncContextP->getLocalVar(0)->getAsInteger(),true); // we cause the abort locally
} // func_AbortDatastore
// string LOCALDBNAME()
// returns name of local DB with which it was identified for the sync
static void func_LocalDBName(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
aTermP->setAsString(
static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext())->getIdentifyingName()
);
}; // func_LocalDBName
// string REMOTEDBNAME()
// returns remote datastore's full name (as used by the remote in <sync> command, may contain subpath and CGI)
static void func_RemoteDBName(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
aTermP->setAsString(dsP->getRemoteDatastore()->getFullName());
}; // func_RemoteDBName
#ifdef SYSYNC_CLIENT
// ADDTARGETCGI(string cgi)
// adds CGI to the target URI. If target URI already contains a ?, string will be just
// appended, otherwise a ? is added, then the new CGI.
// Note: if string to be added is already contained, it will not be added again
static void func_AddTargetCGI(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
// Add extra CGI specified
string cgi;
aFuncContextP->getLocalVar(0)->getAsString(cgi);
addCGItoString(dsP->fRemoteDBPath,cgi.c_str(),true);
}; // func_AddTargetCGI
// SETRECORDFILTER(string filter, boolean inclusive)
// Sets record level filter expression for remote
static void func_SetRecordFilter(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
// put into record level filter
if (dsP->getSession()->getSyncMLVersion()>=syncml_vers_1_2) {
// DS 1.2: use <filter>
aFuncContextP->getLocalVar(0)->getAsString(dsP->fRemoteRecordFilterQuery);
dsP->fRemoteFilterInclusive = aFuncContextP->getLocalVar(1)->getAsBoolean();
}
else if (!aFuncContextP->getLocalVar(0)->isEmpty()) {
// DS 1.1 and below and not empty filter: add as cgi
string filtercgi;
if (aFuncContextP->getLocalVar(1)->getAsBoolean())
filtercgi = "/tf("; // exclusive, use TAF
else
filtercgi = "/fi("; // inclusive, use sync set filter
aFuncContextP->getLocalVar(0)->appendToString(filtercgi);
filtercgi += ')';
addCGItoString(dsP->fRemoteDBPath,filtercgi.c_str(),true);
}
}; // func_SetRecordFilter
// SETDAYSRANGE(integer daysbefore, integer daysafter)
// Sets type of record filter
static void func_SetDaysRange(TItemField *&aTermP, TScriptContext *aFuncContextP)
{
TLocalEngineDS *dsP = static_cast<TLocalEngineDS *>(aFuncContextP->getCallerContext());
// get params
int daysbefore = aFuncContextP->getLocalVar(0)->getAsInteger();
int daysafter = aFuncContextP->getLocalVar(1)->getAsInteger();
// depending on SyncML version, create a SINCE/BEFORE filter or use the /dr(x,y) syntax
if (dsP->getSession()->getSyncMLVersion()>=syncml_vers_1_2 && static_cast<TSyncAgent *>(dsP->getSession())->fServerHasSINCEBEFORE) {
// use the SINCE/BEFORE syntax
// BEFORE&EQ;20070808T000000Z&AND;SINCE&EQ;20070807T000000Z
lineartime_t now = getSystemNowAs(TCTX_UTC,aFuncContextP->getSessionZones());
string ts;
// AND-chain with possibly existing filter
cAppCharP sep = "";
if (!dsP->fRemoteRecordFilterQuery.empty())
sep = "&AND;";
if (daysbefore>=0) {
dsP->fRemoteRecordFilterQuery += sep;
dsP->fRemoteRecordFilterQuery += "SINCE&EQ;";
TimestampToISO8601Str(ts,now-daysbefore*linearDateToTimeFactor,TCTX_UTC,false,false);
dsP->fRemoteRecordFilterQuery += ts;
sep = "&AND;";
}
if (daysafter>=0) {
dsP->fRemoteRecordFilterQuery += sep;
dsP->fRemoteRecordFilterQuery += "BEFORE&EQ;";
TimestampToISO8601Str(ts,now+daysafter*linearDateToTimeFactor,TCTX_UTC,false,false);
dsP->fRemoteRecordFilterQuery += ts;
}
}
else {
// use the /dr(-x,y) syntax
string rangecgi;
StringObjPrintf(rangecgi,"/dr(%ld,%ld)",(long int)(-daysbefore),(long int)(daysafter));
addCGItoString(dsP->fRemoteDBPath,rangecgi.c_str(),true);
}
}; // func_SetDaysRange
#endif // SYSYNC_CLIENT
}; // TLDSfuncs
const uInt8 param_FilterArg[] = { VAL(fty_string) };
const uInt8 param_DateArg[] = { VAL(fty_timestamp) };
const uInt8 param_IntArg[] = { VAL(fty_integer) };
const uInt8 param_StrArg[] = { VAL(fty_string) };
const uInt8 param_OneInteger[] = { VAL(fty_integer) };
const TBuiltInFuncDef DBFuncDefs[] = {
#ifdef OBJECT_FILTERING
#ifdef SYNCML_TAF_SUPPORT
{ "GETCGITARGETFILTER", TLDSfuncs::func_GetCGITargetFilter, fty_string, 0, NULL },
{ "GETTARGETFILTER", TLDSfuncs::func_GetTargetFilter, fty_string, 0, NULL },
{ "SETTARGETFILTER", TLDSfuncs::func_SetTargetFilter, fty_none, 1, param_FilterArg },
{ "ADDTARGETFILTER", TLDSfuncs::func_AddTargetFilter, fty_none, 1, param_FilterArg },
#endif
{ "GETFILTER", TLDSfuncs::func_GetFilter, fty_string, 0, NULL },
{ "SETFILTER", TLDSfuncs::func_SetFilter, fty_none, 1, param_FilterArg },
{ "ADDFILTER", TLDSfuncs::func_AddFilter, fty_none, 1, param_FilterArg },
{ "ADDSTATICFILTER", TLDSfuncs::func_AddStaticFilter, fty_none, 1, param_FilterArg },
#endif
#ifdef SYSYNC_TARGET_OPTIONS
{ "DBOPTIONS", TLDSfuncs::func_DBOptions, fty_string, 0, NULL },
{ "STARTDATE", TLDSfuncs::func_StartDate, fty_timestamp, 0, NULL },
{ "ENDDATE", TLDSfuncs::func_EndDate, fty_timestamp, 0, NULL },
{ "SETSTARTDATE", TLDSfuncs::func_SetStartDate, fty_none, 1, param_DateArg },
{ "SETENDDATE", TLDSfuncs::func_SetEndDate, fty_none, 1, param_DateArg },
{ "MAXITEMCOUNT", TLDSfuncs::func_MaxItemCount, fty_integer, 0, NULL },
{ "SETMAXITEMCOUNT", TLDSfuncs::func_SetMaxItemCount, fty_none, 1, param_IntArg },
{ "NOATTACHMENTS", TLDSfuncs::func_NoAttachments, fty_integer, 0, NULL },
{ "SETNOATTACHMENTS", TLDSfuncs::func_SetNoAttachments, fty_none, 1, param_IntArg },
{ "DEFAULTSIZELIMIT", TLDSfuncs::func_DefaultLimit, fty_integer, 0, NULL },
{ "SETDEFAULTSIZELIMIT", TLDSfuncs::func_SetDefaultLimit, fty_none, 1, param_IntArg },
{ "DBHANDLESOPTS", TLDSfuncs::func_DBHandlesOpts, fty_integer, 0, NULL },
#endif
{ "ALERTCODE", TLDSfuncs::func_AlertCode, fty_integer, 0, NULL },
{ "SETALERTCODE", TLDSfuncs::func_SetAlertCode, fty_none, 1, param_IntArg },
{ "SLOWSYNC", TLDSfuncs::func_SlowSync, fty_integer, 0, NULL },
{ "FORCESLOWSYNC", TLDSfuncs::func_ForceSlowSync, fty_none, 0, NULL },
{ "REFRESHONLY", TLDSfuncs::func_RefreshOnly, fty_integer, 0, NULL },
{ "SETREFRESHONLY", TLDSfuncs::func_SetRefreshOnly, fty_none, 1, param_IntArg },
{ "READONLY", TLDSfuncs::func_ReadOnly, fty_integer, 0, NULL },
{ "SETREADONLY", TLDSfuncs::func_SetReadOnly, fty_none, 1, param_IntArg },
{ "FIRSTTIMESYNC", TLDSfuncs::func_FirstTimeSync, fty_integer, 0, NULL },
{ "SETCONFLICTSTRATEGY", TLDSfuncs::func_SetConflictStrategy, fty_none, 1, param_StrArg },
{ "DBNAME", TLDSfuncs::func_DBName, fty_string, 0, NULL },
{ "LOCALDBNAME", TLDSfuncs::func_LocalDBName, fty_string, 0, NULL },
{ "REMOTEDBNAME", TLDSfuncs::func_RemoteDBName, fty_string, 0, NULL },
{ "ABORTDATASTORE", TLDSfuncs::func_AbortDatastore, fty_none, 1, param_OneInteger },
};
// functions for all datastores
const TFuncTable DBFuncTable = {
sizeof(DBFuncDefs) / sizeof(TBuiltInFuncDef), // size of table
DBFuncDefs, // table pointer
NULL // no chain func
};
#ifdef SYSYNC_CLIENT
const uInt8 param_OneStr[] = { VAL(fty_string) };
const uInt8 param_OneInt[] = { VAL(fty_integer) };
const uInt8 param_TwoInt[] = { VAL(fty_integer), VAL(fty_integer) };
const uInt8 param_SetRecordFilter[] = { VAL(fty_string), VAL(fty_integer) };
const TBuiltInFuncDef ClientDBFuncDefs[] = {
{ "ADDTARGETCGI", TLDSfuncs::func_AddTargetCGI, fty_none, 1, param_OneStr },
{ "SETRECORDFILTER", TLDSfuncs::func_SetRecordFilter, fty_none, 2, param_SetRecordFilter },
{ "SETDAYSRANGE", TLDSfuncs::func_SetDaysRange, fty_none, 2, param_TwoInt },
};
// chain to general DB functions
static void *ClientDBChainFunc(void *&aCtx)
{
// caller context remains unchanged
// -> no change needed
// next table is general DS func table
return (void *)&DBFuncTable;
} // ClientDBChainFunc
// function table for client-only script functions
const TFuncTable ClientDBFuncTable = {
sizeof(ClientDBFuncDefs) / sizeof(TBuiltInFuncDef), // size of table
ClientDBFuncDefs, // table pointer
ClientDBChainFunc // chain to general agent funcs.
};
#endif // SYSYNC_CLIENT
#endif // SCRIPT_SUPPORT
// config
// ======
// conflict strategy names
// bfo: Problems with XCode (expicit qualification), already within namespace ?
//const char * const sysync::conflictStrategyNames[numConflictStrategies] = {
const char * const conflictStrategyNames[numConflictStrategies] = {
"duplicate", // add conflicting counterpart to both databases
"newer-wins", // newer version wins (if date/version comparison is possible, like sst_duplicate otherwise)
"server-wins", // server version wins (and is written to client)
"client-wins" // client version wins (and is written to server)
};
// type support config
TTypeSupportConfig::TTypeSupportConfig(const char* aName, TConfigElement *aParentElement) :
TConfigElement(aName,aParentElement)
{
clear();
} // TTypeSupportConfig::TTypeSupportConfig
TTypeSupportConfig::~TTypeSupportConfig()
{
clear();
} // TTypeSupportConfig::~TTypeSupportConfig
// init defaults
void TTypeSupportConfig::clear(void)
{
// init defaults
fPreferredTx = NULL;
fPreferredRx = NULL;
fPreferredLegacy = NULL;
fAdditionalTypes.clear();
#ifndef NO_REMOTE_RULES
fRuleMatchTypes.clear();
#endif
// clear inherited
inherited::clear();
} // TTypeSupportConfig::clear
#ifdef HARDCODED_CONFIG
// add type support
bool TTypeSupportConfig::addTypeSupport(
cAppCharP aTypeName,
bool aForRead,
bool aForWrite,
bool aPreferred,
cAppCharP aVariant,
cAppCharP aRuleMatch
) {
// search datatype
TDataTypeConfig *typecfgP =
static_cast<TRootConfig *>(getRootElement())->fDatatypesConfigP->getDataType(aTypeName);
if (!typecfgP) return false;
// search variant
TTypeVariantDescriptor variantDescP = NULL;
if (aVariant && *aVariant)
variantDescP = typecfgP->getVariantDescriptor(aVariant);
// now add datatype
if (aPreferred) {
// - preferred
if (aForRead) {
if (!fPreferredRx) {
fPreferredRx=typecfgP; // set it
fPrefRxVariantDescP=variantDescP;
}
}
if (aForWrite) {
if (!fPreferredTx) {
fPreferredTx=typecfgP; // set it
fPrefTxVariantDescP=variantDescP;
}
}
} // if preferred
else {
// - additional
TAdditionalDataType adt;
adt.datatypeconfig=typecfgP;
adt.forRead=aForRead;
adt.forWrite=aForWrite;
adt.variantDescP=variantDescP; // variant of that type
#ifndef NO_REMOTE_RULES
if (aRuleMatch) {
// this is a rulematch type (which overrides normal type selection mechanism)
AssignString(atd.remoteRuleMatch,aRuleMatch); // remote rule match string
fRuleMatchTypes.push_back(adt); // save it in the list
}
else
#endif
{
// standard type
fAdditionalTypes.push_back(adt); // save it in the list
}
}
return true;
} // TTypeSupportConfig::addTypeSupport
#else
// config element parsing
bool TTypeSupportConfig::localStartElement(const char *aElementName, const char **aAttributes, sInt32 aLine)
{
// checking the elements
if (strucmp(aElementName,"use")==0) {
expectEmpty(); // datatype usage specs may not have
// process arguments
const char* nam = getAttr(aAttributes,"datatype");
if (!nam)
return fail("use must have 'datatype' attribute");
// search datatype
TDataTypeConfig *typecfgP =
static_cast<TRootConfig *>(getRootElement())->fDatatypesConfigP->getDataType(nam);
if (!typecfgP)
return fail("unknown datatype '%s' specified",nam);
#ifndef NO_REMOTE_RULES
// get rulematch string, if any
cAppCharP ruleMatch = getAttr(aAttributes,"rulematch");
#endif
// convert variant
TTypeVariantDescriptor variantDescP=NULL; // no variant descriptor by default
cAppCharP variant = getAttr(aAttributes,"variant");
if (variant) {
// get a type-specific descriptor which describes the variant of a type to be used with this datastore
variantDescP = typecfgP->getVariantDescriptor(variant);
if (!variantDescP)
return fail("unknown variant '%s' specified",variant);
}
// convert mode
bool rd=true,wr=true;
const char* mode = getAttr(aAttributes,"mode");
if (mode) {
rd=false;
wr=false;
while (*mode) {
if (tolower(*mode)=='r') rd=true;
else if (tolower(*mode)=='w') wr=true;
else {
ReportError(true,"invalid mode '%c'",*mode);
return true;
}
// next char
mode++;
}
if (!rd && !wr)
return fail("mode must specify 'r', 'w' or 'rw' at least");
}
// get preferred
bool preferred=false;
const char* pref = getAttr(aAttributes,"preferred");
if (pref) {
if (!StrToBool(pref, preferred)) {
if (strucmp(pref,"legacy")==0) {
// this is the preferred type for blind and legacy mode sync attempts
fPreferredLegacy=typecfgP; // remember (note that there is only ONE preferred type, mode is ignored)
preferred=false; // not officially preferred
}
else
return fail("bad value for 'preferred'");
}
}
// now add datatype
if (preferred) {
// - preferred
if (rd) {
if (fPreferredRx)
return fail("preferred read type already defined");
else {
fPreferredRx=typecfgP; // set it
fPrefRxVariantDescP=variantDescP;
}
}
if (wr) {
if (fPreferredTx)
return fail("preferred write type already defined");
else {
fPreferredTx=typecfgP; // set it
fPrefTxVariantDescP=variantDescP;
}
}
} // if preferred
else {
// - additional
TAdditionalDataType adt;
adt.datatypeconfig=typecfgP;
adt.forRead=rd;
adt.forWrite=wr;
adt.variantDescP=variantDescP;
#ifndef NO_REMOTE_RULES
if (ruleMatch) {
// this is a rulematch type (which overrides normal type selection mechanism)
AssignString(adt.remoteRuleMatch,ruleMatch); // remote rule match string
fRuleMatchTypes.push_back(adt); // save it in the list
}
else
#endif
{
// standard type
fAdditionalTypes.push_back(adt); // save it in the list
}
}
}
// - none known here
else
return inherited::localStartElement(aElementName,aAttributes,aLine);
// ok
return true;
} // TTypeSupportConfig::localStartElement
#endif
// resolve
void TTypeSupportConfig::localResolve(bool aLastPass)
{
#ifndef HARDCODED_CONFIG
if (aLastPass) {
// check for required settings
if (!fPreferredTx || !fPreferredRx)
SYSYNC_THROW(TConfigParseException("'typesupport' must contain at least one preferred type for read and write"));
}
#endif
// resolve inherited
inherited::localResolve(aLastPass);
} // TTypeSupportConfig::localResolve
// datastore config
TLocalDSConfig::TLocalDSConfig(const char* aName, TConfigElement *aParentElement) :
TConfigElement(aName,aParentElement),
fTypeSupport("typesupport",this)
{
clear();
} // TLocalDSConfig::TLocalDSConfig
TLocalDSConfig::~TLocalDSConfig()
{
// nop so far
} // TLocalDSConfig::~TLocalDSConfig
// init defaults
void TLocalDSConfig::clear(void)
{
// init defaults
// - conflict resolution strategy
fConflictStrategy=cr_newer_wins;
fSlowSyncStrategy=cr_newer_wins;
fFirstTimeStrategy=cr_newer_wins;
// options
fLocalDBTypeID=0;
fReadOnly=false;
fReportUpdates=true;
fDeleteWins=false; // replace wins over delete by default
fResendFailing=true; // resend failing items in next session by default
#ifdef SYSYNC_SERVER
fTryUpdateDeleted=false; // no attempt to update already deleted items (assuming they are invisible only)
fAlwaysSendLocalID=false; // off as it used to be not SCTS conformant (but would give clients chances to remap IDs)
#endif
fMaxItemsPerMessage=0; // no limit
#ifdef OBJECT_FILTERING
// - filters
fRemoteAcceptFilter.erase();
fSilentlyDiscardUnaccepted=false;
fLocalDBFilterConf.erase();
fMakePassFilter.erase();
fInvisibleFilter.erase();
fMakeVisibleFilter.erase();
// - DS 1.2 Filter support (<filter> allowed in Alert, <filter-rx>/<filterCap> shown in devInf)
fDS12FilterSupport=false; // off by default, as clients usually don't have it
// - Set if date range support is available in this datastore
fDateRangeSupported=false;
#endif
#ifdef SCRIPT_SUPPORT
fDBInitScript.erase();
fSentItemStatusScript.erase();
fReceivedItemStatusScript.erase();
fAlertScript.erase();
#ifdef SYSYNC_CLIENT
fAlertPrepScript.erase();
#endif
fDBFinishScript.erase();
#endif
// clear embedded
fTypeSupport.clear();
// clear inherited
inherited::clear();
} // TLocalDSConfig::clear
#ifndef HARDCODED_CONFIG
// config element parsing
bool TLocalDSConfig::localStartElement(const char *aElementName, const char **aAttributes, sInt32 aLine)
{
// checking the elements
if (strucmp(aElementName,"dbtypeid")==0)
expectUInt32(fLocalDBTypeID);
else if (strucmp(aElementName,"typesupport")==0)
expectChildParsing(fTypeSupport);
else if (strucmp(aElementName,"conflictstrategy")==0)
expectEnum(sizeof(fConflictStrategy),&fConflictStrategy,conflictStrategyNames,numConflictStrategies);
else if (strucmp(aElementName,"slowsyncstrategy")==0)
expectEnum(sizeof(fSlowSyncStrategy),&fSlowSyncStrategy,conflictStrategyNames,numConflictStrategies);
else if (strucmp(aElementName,"firsttimestrategy")==0)
expectEnum(sizeof(fFirstTimeStrategy),&fFirstTimeStrategy,conflictStrategyNames,numConflictStrategies);
else if (strucmp(aElementName,"readonly")==0)
expectBool(fReadOnly);
else if (strucmp(aElementName,"reportupdates")==0)
expectBool(fReportUpdates);
else if (strucmp(aElementName,"deletewins")==0)
expectBool(fDeleteWins);
else if (strucmp(aElementName,"resendfailing")==0)
expectBool(fResendFailing);
#ifdef SYSYNC_SERVER
else if (strucmp(aElementName,"tryupdatedeleted")==0)
expectBool(fTryUpdateDeleted);
else if (strucmp(aElementName,"alwayssendlocalid")==0)
expectBool(fAlwaysSendLocalID);
else if (strucmp(aElementName,"alias")==0) {
// get a name
string name;
if (!getAttrExpanded(aAttributes, "name", name, true))
return fail("Missing 'name' attribute in 'alias'");
fAliasNames.push_back(name);
expectEmpty();
}
#endif
else if (strucmp(aElementName,"maxitemspermessage")==0)
expectUInt32(fMaxItemsPerMessage);
#ifdef OBJECT_FILTERING
// filtering
else if (strucmp(aElementName,"acceptfilter")==0)
expectString(fRemoteAcceptFilter);
else if (strucmp(aElementName,"silentdiscard")==0)
expectBool(fSilentlyDiscardUnaccepted);
else if (strucmp(aElementName,"localdbfilter")==0)
expectString(fLocalDBFilterConf);
else if (strucmp(aElementName,"makepassfilter")==0)
expectString(fMakePassFilter);
else if (strucmp(aElementName,"invisiblefilter")==0)
expectString(fInvisibleFilter);
else if (strucmp(aElementName,"makevisiblefilter")==0)
expectString(fMakeVisibleFilter);
else if (strucmp(aElementName,"ds12filters")==0)
expectBool(fDS12FilterSupport);
else if (strucmp(aElementName,"daterangesupport")==0)
expectBool(fDateRangeSupported);
#endif
#ifdef SCRIPT_SUPPORT
else if (strucmp(aElementName,"datastoreinitscript")==0)
expectScript(fDBInitScript,aLine,&DBFuncTable);
else if (strucmp(aElementName,"sentitemstatusscript")==0)
expectScript(fSentItemStatusScript,aLine,&ErrorFuncTable);
else if (strucmp(aElementName,"receiveditemstatusscript")==0)
expectScript(fReceivedItemStatusScript,aLine,&ErrorFuncTable);
else if (strucmp(aElementName,"alertscript")==0)
expectScript(fAlertScript,aLine,&DBFuncTable);
#ifdef SYSYNC_CLIENT
else if (strucmp(aElementName,"alertprepscript")==0)
expectScript(fAlertPrepScript,aLine,getClientDBFuncTable());
#endif
else if (strucmp(aElementName,"datastorefinishscript")==0)
expectScript(fDBFinishScript,aLine,&DBFuncTable);
#endif
#ifndef MINIMAL_CODE
else if (strucmp(aElementName,"displayname")==0)
expectString(fDisplayName);
#endif
// - none known here
else
return inherited::localStartElement(aElementName,aAttributes,aLine);
// ok
return true;
} // TLocalDSConfig::localStartElement
#endif
// resolve
void TLocalDSConfig::localResolve(bool aLastPass)
{
if (aLastPass) {
#ifdef SCRIPT_SUPPORT
TScriptContext *sccP = NULL;
SYSYNC_TRY {
// resolve all scripts in same context
// - first script needed (when alert is created)
#ifdef SYSYNC_CLIENT
TScriptContext::resolveScript(getSyncAppBase(),fAlertPrepScript,sccP,NULL);
#endif
// - scripts needed when database is made ready
TScriptContext::resolveScript(getSyncAppBase(),fDBInitScript,sccP,NULL);
TScriptContext::resolveScript(getSyncAppBase(),fSentItemStatusScript,sccP,NULL);
TScriptContext::resolveScript(getSyncAppBase(),fReceivedItemStatusScript,sccP,NULL);
TScriptContext::resolveScript(getSyncAppBase(),fAlertScript,sccP,NULL);
TScriptContext::resolveScript(getSyncAppBase(),fDBFinishScript,sccP,NULL);
// - forget this context
if (sccP) delete sccP;
}
SYSYNC_CATCH (...)
if (sccP) delete sccP;
SYSYNC_RETHROW;
SYSYNC_ENDCATCH
#endif
}
// resolve embedded
fTypeSupport.Resolve(aLastPass);
// resolve inherited
inherited::localResolve(aLastPass);
} // TLocalDSConfig::localResolve
// - add type support to datatstore from config
void TLocalDSConfig::addTypes(TLocalEngineDS *aDatastore, TSyncSession *aSessionP)
{
TSyncItemType *typeP;
TSyncItemType *writetypeP;
// preferred types, create instances only if not already existing
// - preferred receive
typeP = aSessionP->findLocalType(fTypeSupport.fPreferredRx);
if (!typeP) {
typeP = fTypeSupport.fPreferredRx->newSyncItemType(aSessionP,NULL); // local types are never exclusively related to a datastore
aSessionP->addLocalItemType(typeP); // add to session
}
// - preferred send
writetypeP = aSessionP->findLocalType(fTypeSupport.fPreferredTx);
if (!writetypeP) {
writetypeP = fTypeSupport.fPreferredTx->newSyncItemType(aSessionP,NULL); // local types are never exclusively related to a datastore
aSessionP->addLocalItemType(writetypeP);
}
// - set preferred types
aDatastore->setPreferredTypes(typeP,writetypeP);
// additional types
TAdditionalTypesList::iterator pos;
for (pos=fTypeSupport.fAdditionalTypes.begin(); pos!=fTypeSupport.fAdditionalTypes.end(); pos++) {
// - search for type already created from same config item
typeP = aSessionP->findLocalType((*pos).datatypeconfig);
if (!typeP) {
// - does not exist yet, create the type
typeP = (*pos).datatypeconfig->newSyncItemType(aSessionP,NULL); // local types are never exclusively related to a datastore
// - add type to session types
aSessionP->addLocalItemType(typeP);
}
// - add type to datastore's supported types
aDatastore->addTypeSupport(typeP,(*pos).forRead,(*pos).forWrite);
}
#ifndef NO_REMOTE_RULES
// rulematch types
for (pos=fTypeSupport.fRuleMatchTypes.begin(); pos!=fTypeSupport.fRuleMatchTypes.end(); pos++) {
// - search for type already created from same config item
typeP = aSessionP->findLocalType((*pos).datatypeconfig);
if (!typeP) {
// - does not exist yet, create the type
typeP = (*pos).datatypeconfig->newSyncItemType(aSessionP,NULL); // local types are never exclusively related to a datastore
// - add type to session types
aSessionP->addLocalItemType(typeP);
}
// - add type to datastore's rulematch types
aDatastore->addRuleMatchTypeSupport(typeP,(*pos).remoteRuleMatch.c_str());
}
#endif
// now apply type limits
// Note: this is usually derived, as limits are often defined within the datastore,
// not the type itself (however, for hardcoded template-based fieldlists,
// the limits are taken from the template, see TLocalDSConfig::addTypeLimits()
addTypeLimits(aDatastore, aSessionP);
} // TLocalDSConfig::addTypes
// Add (probably datastore-specific) limits such as MaxSize and NoTruncate to types
void TLocalDSConfig::addTypeLimits(TLocalEngineDS *aLocalDatastoreP, TSyncSession *aSessionP)
{
// add field size limitations from map to all types
TSyncItemTypePContainer::iterator pos;
TSyncItemTypePContainer *typesP = &(aLocalDatastoreP->fRxItemTypes);
for (uInt8 i=0; i<2; i++) {
for (pos=typesP->begin(); pos!=typesP->end(); pos++) {
// apply default limits to type (e.g. from hard-coded template in config)
(*pos)->addDefaultTypeLimits();
}
typesP = &(aLocalDatastoreP->fTxItemTypes);
}
} // TLocalDSConfig::addTypeLimits
// Check for alias names
uInt16 TLocalDSConfig::isDatastoreAlias(cAppCharP aDatastoreURI)
{
// only servers have (and may need) aliases
#ifdef SYSYNC_SERVER
for (TStringList::iterator pos = fAliasNames.begin(); pos!=fAliasNames.end(); pos++) {
if (*pos == aDatastoreURI)
return (*pos).size(); // return size of match
}
#endif
return 0;
} // TLocalDSConfig::isDatastoreAlias
/*
* Implementation of TLocalEngineDS
*/
/// @Note InternalResetDataStore() must also be callable from destructor
/// (care not to call other objects which will refer to the already
/// half-destructed datastore!)
void TLocalEngineDS::InternalResetDataStore(void)
{
// possibly complete, if not already done (should be, by engFinishDataStoreSync() !)
if (fLocalDSState>dssta_idle)
changeState(dssta_completed); // complete NOW, opportunity to show stats, etc.
// switch down to idle
changeState(dssta_idle);
/// @todo obsolete: fState=dss_idle;
fAbortStatusCode=LOCERR_OK; // not aborted yet
fLocalAbortCause=true; // assume local cause
fRemoteAddingStopped=false;
fAlertCode=0; // not yet alerted
/// Init Sync mode @ref dsSyncMode
fSyncMode=smo_twoway; // default to twoway
fForceSlowSync=false;
fSlowSync=false;
fRefreshOnly=false;
fReadOnly=false;
fReportUpdates=fDSConfigP->fReportUpdates; // update reporting according to what is configured
fServerAlerted=false;
fResuming=false;
#ifdef SUPERDATASTORES
fAsSubDatastoreOf=NULL; // is not a subdatastore
#endif
/// Init administrative data to defaults @ref dsAdminData
// - last
fLastRemoteAnchor.erase();
fLastLocalAnchor.erase();
// - current
fNextRemoteAnchor.erase();
fNextLocalAnchor.erase();
// suspend state
fResumeAlertCode=0; // none
fPreventResuming=false;
// suspend of chunked items
fPartialItemState=pi_state_none;
fLastSourceURI.erase();
fLastTargetURI.erase();
fLastItemStatus=0;
fPITotalSize=0;
fPIStoredSize=0;
fPIUnconfirmedSize=0;
if (fPIStoredDataAllocated) {
smlLibFree(fPIStoredDataP);
fPIStoredDataAllocated=false;
}
fPIStoredDataP=NULL;
// other state info
fFirstTimeSync=false; // not first sync by default
#ifdef SYSYNC_CLIENT
// - maps for add commands
fPendingAddMaps.clear();
fUnconfirmedMaps.clear();
fLastSessionMaps.clear();
#endif
#ifdef SYSYNC_SERVER
fTempGUIDMap.clear();
#endif
/// Init type negotiation
/// - for sending data
fLocalSendToRemoteTypeP = NULL;
fRemoteReceiveFromLocalTypeP = NULL;
/// - for receiving data
fLocalReceiveFromRemoteTypeP = NULL;
fRemoteSendToLocalTypeP = NULL;
/// Init Filtering @ref dsFiltering
resetFiltering();
/// Init item processing @ref dsItemProcessing
fSessionConflictStrategy=cr_duplicate; // will be updated later when sync mode is known
fItemSizeLimit=-1; // no limit yet
fCurrentSyncOp = sop_none; // will be set at engProcessItem()
fEchoItemOp = sop_none; // will be set at engProcessItem()
fItemConflictStrategy=fSessionConflictStrategy; // will be set at engProcessItem()
fForceConflict = false; // will be set at engProcessItem()
fDeleteWins = false; // will be set at engProcessItem()
fRejectStatus = -1; // will be set at engProcessItem()
#ifdef SCRIPT_SUPPORT
// - delete the script context if any
if (fSendingTypeScriptContextP) {
delete fSendingTypeScriptContextP;
fSendingTypeScriptContextP=NULL;
}
if (fReceivingTypeScriptContextP) {
delete fReceivingTypeScriptContextP;
fReceivingTypeScriptContextP=NULL;
}
if (fDataStoreScriptContextP) {
delete fDataStoreScriptContextP;
fDataStoreScriptContextP=NULL;
}
#endif
/// Init other vars @ref dsOther
/// Init Counters and statistics @ref dsCountStats
// - NOC from remote
fRemoteNumberOfChanges=-1; // none known yet
// - data transferred
fIncomingDataBytes=0;
fOutgoingDataBytes=0;
// - locally performed ops
fLocalItemsAdded=0;
fLocalItemsUpdated=0;
fLocalItemsDeleted=0;
fLocalItemsError=0;
// - remotely performed ops
fRemoteItemsAdded=0;
fRemoteItemsUpdated=0;
fRemoteItemsDeleted=0;
fRemoteItemsError=0;
#ifdef SYSYNC_SERVER
// - conflicts
fConflictsServerWins=0;
fConflictsClientWins=0;
fConflictsDuplicated=0;
// - slow sync matches
fSlowSyncMatches=0;
#endif
// Override defaults from ancestor
// - generally, limit GUID size to reasonable size (even if we can
// theoretically handle unlimited GUIDs in client, except for
// some DEBUGPRINTF statements that will crash for example with
// the brain-damaged GUIDs that Exchange server uses.
fMaxGUIDSize = 64;
} // TLocalEngineDS::InternalResetDataStore
/// constructor
TLocalEngineDS::TLocalEngineDS(TLocalDSConfig *aDSConfigP, TSyncSession *aSessionP, const char *aName, uInt32 aCommonSyncCapMask) :
TSyncDataStore(aSessionP, aName, aCommonSyncCapMask)
,fPIStoredDataP(NULL)
,fPIStoredDataAllocated(false)
#ifdef SCRIPT_SUPPORT
,fSendingTypeScriptContextP(NULL) // no associated script context
,fReceivingTypeScriptContextP(NULL) // no associated script context
,fDataStoreScriptContextP(NULL) // no datastore level context
#endif
,fRemoteDatastoreP(NULL) // no associated remote
{
// set config ptr
fDSConfigP = aDSConfigP;
if (!fDSConfigP)
SYSYNC_THROW(TSyncException(DEBUGTEXT("TLocalEngineDS::TLocalEngineDS called with NULL config","lds1")));
/// Init Sync state @ref dsSyncState
fLocalDSState=dssta_idle; // idle to begin with
// now reset
InternalResetDataStore();
} // TLocalEngineDS::TLocalEngineDS
TLocalEngineDS::~TLocalEngineDS()
{
// reset everything
InternalResetDataStore();
} // TLocalEngineDS::~TLocalEngineDS
#ifdef SYDEBUG
// return datastore state name
cAppCharP TLocalEngineDS::getDSStateName(void)
{
return LocalDSStateNames[fLocalDSState];
} // TLocalEngineDS::getDSStateName
// return datastore state name
cAppCharP TLocalEngineDS::getDSStateName(TLocalEngineDSState aState)
{
return LocalDSStateNames[aState];
} // TLocalEngineDS::getDSStateName
#endif
// reset datastore (after use)
void TLocalEngineDS::engResetDataStore(void)
{
// now reset
// - logic layer and above
dsResetDataStore();
// - myself
InternalResetDataStore();
// - anchestors
inherited::engResetDataStore();
} // TLocalEngineDS::engResetDataStore
// check if this datastore is accessible with given URI
// NOTE: By default, local datastore type is addressed with
// first path element of URI, rest of path might be used
// by derivates to subselect data folders etc.
uInt16 TLocalEngineDS::isDatastore(const char *aDatastoreURI)
{
// extract base name
string basename;
analyzeName(aDatastoreURI,&basename);
// compare only base name
// - compare with main name
int res = inherited::isDatastore(basename.c_str());
if (res==0) {
// Not main name: compare with aliases
res = fDSConfigP->isDatastoreAlias(basename.c_str());
}
return res;
} // TLocalEngineDS::isDatastore
/// get DB specific error message text for dbg log, or empty string if none
/// @return platform specific DB error text
string TLocalEngineDS::lastDBErrorText(void)
{
string s;
s.erase();
uInt32 err = lastDBError();
if (isDBError(err)) {
StringObjPrintf(s," (DB specific error code = %ld)",(long)lastDBError());
}
return s;
} // TLocalEngineDS::lastDBErrorText
#ifdef SYSYNC_CLIENT
// - init Sync Parameters (client case)
// Derivates might override this to pre-process and modify parameters
// (such as adding client settings as CGI to remoteDBPath)
bool TLocalEngineDS::dsSetClientSyncParams(
TSyncModes aSyncMode,
bool aSlowSync,
const char *aRemoteDBPath,
const char *aDBUser,
const char *aDBPassword,
const char *aLocalPathExtension,
const char *aRecordFilterQuery,
bool aFilterInclusive
)
{
// - set remote params
fRemoteDBPath=aRemoteDBPath;
AssignString(fDBUser,aDBUser);
AssignString(fDBPassword,aDBPassword);
// check for running under control of a superdatastore
// - aRemoteDBPath might contain a special prefix: "<super>remote", with "super" specifying the
// name of a local superdatastore to run the sync with
string opts;
if (!fRemoteDBPath.empty() && fRemoteDBPath.at(0)=='<') {
// we have an option prefix
size_t pfxe = fRemoteDBPath.find('>', 1);
if (pfxe!=string::npos) {
// extract options
opts.assign(fRemoteDBPath, 1, pfxe-1);
// store remote path cleaned from options
fRemoteDBPath.erase(0,pfxe+1);
}
}
if (!opts.empty()) {
#ifdef SUPERDATASTORES
// For now, the only option withing angle brackets is the name of the superdatastore, so opts==superdatastorename
// - look for superdatastore having the specified name
TSuperDSConfig *superdscfgP = static_cast<TSuperDSConfig *>(getSession()->getSessionConfig()->getLocalDS(opts.c_str()));
if (superdscfgP && superdscfgP->isAbstractDatastore()) {
// see if we have an instance of this already
fAsSubDatastoreOf = static_cast<TSuperDataStore *>(getSession()->findLocalDataStore(superdscfgP));
if (fAsSubDatastoreOf) {
// that superdatastore already exists, just override client sync params with those already set
aSyncMode = fAsSubDatastoreOf->fSyncMode;
aSlowSync = fAsSubDatastoreOf->fSlowSync;
aRecordFilterQuery = fAsSubDatastoreOf->fRemoteRecordFilterQuery.c_str();
}
else {
// instantiate new superdatastore
fAsSubDatastoreOf = static_cast<TSuperDataStore *>(superdscfgP->newLocalDataStore(getSession()));
if (fAsSubDatastoreOf) {
fSessionP->fLocalDataStores.push_back(fAsSubDatastoreOf);
// configure it with the same parameters as the subdatastore
if (!fAsSubDatastoreOf->dsSetClientSyncParams(
aSyncMode,
aSlowSync,
fRemoteDBPath.c_str(), // already cleaned from <xxx> prefix
aDBUser,
aDBPassword,
aLocalPathExtension,
aRecordFilterQuery,
aFilterInclusive
))
return false; // failed
}
}
if (fAsSubDatastoreOf) {
// find link config for this superdatastore
TSubDSLinkConfig *lcfgP = NULL;
TSubDSConfigList::iterator pos;
for(pos=superdscfgP->fSubDatastores.begin();pos!=superdscfgP->fSubDatastores.end();pos++) {
if ((*pos)->fLinkedDSConfigP==fDSConfigP) {
// this is the link
lcfgP = *pos;
break;
}
}
if (lcfgP) {
// now link into superdatastore
fAsSubDatastoreOf->addSubDatastoreLink(lcfgP,this);
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Warning: '%s' is not a subdatastore of '%s'", getName(), opts.c_str()));
return false; // failed
}
}
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Warning: No superdatastore name '%s' exists -> can't run '%s' under superdatastore control", opts.c_str(), getName()));
return false; // failed
}
#endif // SUPERDATASTORES
}
// sync mode
fSyncMode=aSyncMode;
fSlowSync=aSlowSync;
fRefreshOnly=fSyncMode==smo_fromserver; // here to make sure, should be set by setSyncMode(FromAlertCode) later anyway
// DS 1.2 filters
AssignString(fRemoteRecordFilterQuery,aRecordFilterQuery);
fRemoteFilterInclusive=aFilterInclusive;
// params
// - build local path
fLocalDBPath=URI_RELPREFIX;
fLocalDBPath+=getName();
if (aLocalPathExtension && *aLocalPathExtension) {
fLocalDBPath+='/';
fLocalDBPath+=aLocalPathExtension;
}
// - we have the params for syncing now
return changeState(dssta_clientparamset)==LOCERR_OK;
} // TLocalEngineDS::dsSetClientSyncParams
#endif // SYSYNC_CLIENT
// add support for more data types
// (for programatically creating local datastores from specialized TSyncSession derivates)
void TLocalEngineDS::addTypeSupport(TSyncItemType *aItemTypeP,bool aForRx, bool aForTx)
{
if (aForRx) fRxItemTypes.push_back(aItemTypeP);
if (aForTx) fTxItemTypes.push_back(aItemTypeP);
} // TLocalEngineDS::addTypeSupport
#ifndef NO_REMOTE_RULES
// add data type that overrides normal type selection if string matches active remote rule
void TLocalEngineDS::addRuleMatchTypeSupport(TSyncItemType *aItemTypeP,cAppCharP aRuleMatchString)
{
TRuleMatchTypeEntry rme;
rme.itemTypeP = aItemTypeP;
rme.ruleMatchString = aRuleMatchString;
fRuleMatchItemTypes.push_back(rme);
} // TLocalEngineDS::addRuleMatchTypeSupport
#endif
TTypeVariantDescriptor TLocalEngineDS::getVariantDescForType(TSyncItemType *aItemTypeP)
{
// search in config for specific variant descriptor
// - first check preferred rx
if (fDSConfigP->fTypeSupport.fPreferredRx == aItemTypeP->getTypeConfig())
return fDSConfigP->fTypeSupport.fPrefRxVariantDescP;
// - then check preferred tx
if (fDSConfigP->fTypeSupport.fPreferredTx == aItemTypeP->getTypeConfig())
return fDSConfigP->fTypeSupport.fPrefTxVariantDescP;
// - then check additional types
TAdditionalTypesList::iterator pos;
for (pos=fDSConfigP->fTypeSupport.fAdditionalTypes.begin(); pos!=fDSConfigP->fTypeSupport.fAdditionalTypes.end(); pos++) {
if ((*pos).datatypeconfig == aItemTypeP->getTypeConfig())
return (*pos).variantDescP;
}
// none found
return NULL;
} // TLocalEngineDS::getVariantDescForType
// - called when a item in the sync set changes its localID (due to local DB internals)
void TLocalEngineDS::dsLocalIdHasChanged(const char *aOldID, const char *aNewID)
{
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// make sure remapped localIDs get updated as well
TStringToStringMap::iterator pos;
for (pos=fTempGUIDMap.begin(); pos!=fTempGUIDMap.end(); pos++) {
if (pos->second == aOldID) {
// update ID
pos->second = aNewID;
break;
}
}
}
#endif // SYSYNC_SERVER
} // TLocalEngineDS::dsLocalIdHasChanged
#ifdef SYSYNC_SERVER
// for received GUIDs (Map command), obtain real GUID (might be temp GUID due to maxguidsize restrictions)
void TLocalEngineDS::obtainRealLocalID(string &aLocalID)
{
if (aLocalID.size()>0 && aLocalID[0]=='#') {
// seems to be a temp GUID
TStringToStringMap::iterator pos =
fTempGUIDMap.find(aLocalID);
if (pos!=fTempGUIDMap.end()) {
// found temp GUID mapping, replace it
PDEBUGPRINTFX(DBG_DATA,(
"translated tempLocalID='%s' back to real localID='%s'",
aLocalID.c_str(),
(*pos).second.c_str()
));
aLocalID = (*pos).second;
}
else {
PDEBUGPRINTFX(DBG_ERROR,("No realLocalID found for tempLocalID='%s'",aLocalID.c_str()));
}
}
} // TLocalEngineDS::obtainRealLocalID
// for sending GUIDs (Add command), generate temp GUID which conforms to maxguidsize of remote datastore if needed
void TLocalEngineDS::adjustLocalIDforSize(string &aLocalID, sInt32 maxguidsize, sInt32 prefixsize)
{
if (maxguidsize>0) {
if (aLocalID.length()+prefixsize>(uInt32)maxguidsize) { //BCPPB needed unsigned cast
// real GUID is too long, we need to create a temp
string tempguid;
StringObjPrintf(tempguid,"#%ld",(long)fTempGUIDMap.size()+1); // as list only grows, we have unique tempuids for sure
fTempGUIDMap[tempguid]=aLocalID;
PDEBUGPRINTFX(DBG_DATA,(
"translated realLocalID='%s' to tempLocalID='%s'",
aLocalID.c_str(),
tempguid.c_str()
));
aLocalID=tempguid;
}
}
} // TLocalEngineDS::adjustLocalIDforSize
#endif // SYSYNC_SERVER
// set Sync types needed for sending local data to remote DB
void TLocalEngineDS::setSendTypeInfo(
TSyncItemType *aLocalSendToRemoteTypeP,
TSyncItemType *aRemoteReceiveFromLocalTypeP
)
{
fLocalSendToRemoteTypeP=aLocalSendToRemoteTypeP;
fRemoteReceiveFromLocalTypeP=aRemoteReceiveFromLocalTypeP;
} // TLocalEngineDS::setSendTypeInfo
// set Sync types needed for receiving remote data in local DB
void TLocalEngineDS::setReceiveTypeInfo(
TSyncItemType *aLocalReceiveFromRemoteTypeP,
TSyncItemType *aRemoteSendToLocalTypeP
)
{
fLocalReceiveFromRemoteTypeP=aLocalReceiveFromRemoteTypeP;
fRemoteSendToLocalTypeP=aRemoteSendToLocalTypeP;
} // TLocalEngineDS::setReceiveTypeInfo
// - init usage of datatypes set with setSendTypeInfo/setReceiveTypeInfo
localstatus TLocalEngineDS::initDataTypeUse(void)
{
localstatus sta = LOCERR_OK;
// check compatibility
if (
!fLocalSendToRemoteTypeP || !fLocalReceiveFromRemoteTypeP ||
!fLocalSendToRemoteTypeP->isCompatibleWith(fLocalReceiveFromRemoteTypeP)
) {
// send and receive types not compatible
sta = 415;
PDEBUGPRINTFX(DBG_ERROR,("Incompatible send and receive types -> cannot sync (415)"));
engAbortDataStoreSync(sta,true,false); // do not proceed with sync of this datastore, local problem, not resumable
return sta;
}
#ifdef SCRIPT_SUPPORT
// let types initialize themselves for being used by this datastore
// - optimization: if both types are same, initialize only once
if (fLocalSendToRemoteTypeP == fLocalReceiveFromRemoteTypeP)
fLocalReceiveFromRemoteTypeP->initDataTypeUse(this,true,true); // send and receive
else {
fLocalSendToRemoteTypeP->initDataTypeUse(this,true,false); // for sending, not receiving
fLocalReceiveFromRemoteTypeP->initDataTypeUse(this,false,true); // not sending, for receiving
}
#endif
// ok
return sta;
} // TLocalEngineDS::initDataTypeUse
// conflict resolution strategy. Conservative here
TConflictResolution TLocalEngineDS::getConflictStrategy(bool aForSlowSync, bool aForFirstTime)
{
return aForSlowSync ?
(aForFirstTime ? fDSConfigP->fFirstTimeStrategy : fDSConfigP->fSlowSyncStrategy) :
fDSConfigP->fConflictStrategy;
} // TLocalEngineDS::getConflictStrategy
// add filter keywords and property names to filterCap
void TLocalEngineDS::addFilterCapPropsAndKeywords(SmlPcdataListPtr_t &aFilterKeywords, SmlPcdataListPtr_t &aFilterProps)
{
#ifdef OBJECT_FILTERING
// add my own properties
if (fDSConfigP->fDateRangeSupported) {
addPCDataStringToList("BEFORE", &aFilterKeywords);
addPCDataStringToList("SINCE", &aFilterKeywords);
}
// get default send type
TSyncItemType *itemTypeP = fSessionP->findLocalType(fDSConfigP->fTypeSupport.fPreferredTx);
TTypeVariantDescriptor variantDesc = NULL;
doesUseType(itemTypeP, &variantDesc);
// have it add it's keywords and properties
itemTypeP->addFilterCapPropsAndKeywords(aFilterKeywords,aFilterProps,variantDesc);
#endif
} // TLocalEngineDS::addFilterCapPropsAndKeywords
// reset all filter settings
void TLocalEngineDS::resetFiltering(void)
{
#ifdef OBJECT_FILTERING
// - dynamic sync set filter
fSyncSetFilter.erase();
// - static filter
fLocalDBFilter=fDSConfigP->fLocalDBFilterConf; // use configured localDB filter
// - TAF filters
#ifdef SYNCML_TAF_SUPPORT
fTargetAddressFilter.erase(); // none from <sync> yet
fIntTargetAddressFilter.erase(); // none from internal source (script)
#endif
#ifdef SYSYNC_TARGET_OPTIONS
// - Other filtering options
fDateRangeStart=0; // no date range
fDateRangeEnd=0;
fSizeLimit=-1; // no size limit
fMaxItemCount=0; // no item count limit
fNoAttachments=false; // attachments not suppressed
fDBOptions.erase(); // no options
#endif
// - Filtering requirements
fTypeFilteringNeeded=false;
fFilteringNeededForAll=false;
fFilteringNeeded=false;
#endif // OBJECT_FILTERING
} // TLocalEngineDS::resetFiltering
#ifdef OBJECT_FILTERING
/// @brief check single filter term for DS 1.2 filterkeywords.
/// @return true if term still needs to be added to normal filter expression, false if term will be handled otherwise
bool TLocalEngineDS::checkFilterkeywordTerm(
cAppCharP aIdent, bool aAssignToMakeTrue,
cAppCharP aOp, bool aCaseInsensitive,
cAppCharP aVal, bool aSpecialValue,
TSyncItemType *aItemTypeP
)
{
// show it to the datatype (if any)
if (aItemTypeP) {
if (!aItemTypeP->checkFilterkeywordTerm(aIdent, aAssignToMakeTrue, aOp, aCaseInsensitive, aVal, aSpecialValue))
return false; // type fully handles it, no need to check it further or add it to the filter expression
}
// we generally implement BEFORE and SINCE on the datastore level
// This might not make sense depending on the actual datatype, but does not harm either
#ifdef SYSYNC_TARGET_OPTIONS
timecontext_t tctx;
if (strucmp(aIdent,"BEFORE")==0) {
if (ISO8601StrToTimestamp(aVal,fDateRangeEnd,tctx)) {
TzConvertTimestamp(fDateRangeEnd,tctx,TCTX_UTC,getSessionZones(),fSessionP->fUserTimeContext);
}
else {
PDEBUGPRINTFX(DBG_ERROR,("invalid ISO datetime for BEFORE: '%s'",aVal));
return true; // add it to filter, possibly this is not meant to be a filterkeyword
}
}
else if (strucmp(aIdent,"SINCE")==0) {
if (ISO8601StrToTimestamp(aVal,fDateRangeStart,tctx)) {
TzConvertTimestamp(fDateRangeStart,tctx,TCTX_UTC,getSessionZones(),fSessionP->fUserTimeContext);
}
else {
PDEBUGPRINTFX(DBG_ERROR,("invalid ISO datetime for SINCE: '%s'",aVal));
return true; // add it to filter, possibly this is not meant to be a filterkeyword
}
}
else if (strucmp(aIdent,"MAXSIZE")==0) {
if (StrToFieldinteger(aVal,fSizeLimit)==0) {
PDEBUGPRINTFX(DBG_ERROR,("invalid integer for MAXSIZE: '%s'",aVal));
return true; // add it to filter, possibly this is not meant to be a filterkeyword
}
}
else if (strucmp(aIdent,"MAXCOUNT")==0) {
if (StrToULong(aVal,fMaxItemCount)==0) {
PDEBUGPRINTFX(DBG_ERROR,("invalid integer for MAXSIZE: '%s'",aVal));
return true; // add it to filter, possibly this is not meant to be a filterkeyword
}
}
else if (strucmp(aIdent,"NOATT")==0) {
if (!StrToBool(aVal,fNoAttachments)==0) {
PDEBUGPRINTFX(DBG_ERROR,("invalid boolean for NOATT: '%s'",aVal));
return true; // add it to filter, possibly this is not meant to be a filterkeyword
}
}
else if (strucmp(aIdent,"DBOPTIONS")==0) {
fDBOptions = aVal; // just get DB options
}
#endif
else {
// unknown identifier, add to filter expression
return true;
}
// this term will be processed by special mechanism like fDateRangeStart/fDateRangeEnd
// or fSizeLimit, so there is no need for normal filtering
return false; // do not include into filter
} // TLocalEngineDS::checkFilterkeywordTerm
/// @brief parse "syncml:filtertype-cgi" filter, convert into internal filter syntax
/// and possibly sets some special filter options (fDateRangeStart, fDateRangeEnd)
/// based on "filterkeywords" available for the type passed (DS 1.2).
/// For parsing DS 1.1/1.0 TAF-style filters, aItemType can be NULL, no type-specific
/// filterkeywords can be parsed then.
/// @return pointer to next character after processing (usually points to terminator)
/// @param[in] aCGI the NUL-terminated filter string
/// @param[in] aItemTypeP if not NULL, this is the item type the filter applies to
const char *TLocalEngineDS::parseFilterCGI(cAppCharP aCGI, TSyncItemType *aItemTypeP, string &aFilter)
{
const char *p=aCGI, *q;
sInt16 paraNest=0; // nested paranthesis
string ident;
char op[3];
char logop;
string val;
bool termtofilter;
bool assigntomaketrue;
bool specialvalue;
bool caseinsensitive;
PDEBUGPRINTFX(DBG_FILTER+DBG_EXOTIC,("Parsing syncml:filtertype-cgi filter: %s",aCGI));
aFilter.erase();
logop=0;
while (p && *p) {
if (aFilter.empty()) logop=0; // ignore logical operation that would be at beginning of an expression
// skip spaces
while (isspace(*p)) p++;
// now we need an ident or paranthesis
if (*p=='(') {
if (logop) aFilter+=logop; // expression continues, we need the logop now
logop=0; // now consumed
paraNest++;
aFilter+='(';
p++;
}
else {
// must be term: ident op val
// - check special case pseudo-identifiers
if (strucmp(p,"&LUID;",6)==0) {
ident="LUID";
p+=6;
}
else {
// normal identifier
// - search end
q=p;
while (isalnum(*q) || *q=='[' || *q==']' || *q=='.' || *q=='_') q++;
// - assign
if (q==p) {
PDEBUGPRINTFX(DBG_ERROR,("Expected identifier but found '%s'",p));
break;
}
ident.assign(p,q-p);
p=q;
}
// skip spaces
while (isspace(*p)) p++;
// next must be comparison operator, possibly preceeded by modifiers
op[0]=0; op[1]=0; op[2]=0;
assigntomaketrue=false;
specialvalue=false;
caseinsensitive=false;
// - check modifiers first
if (*p==':') { assigntomaketrue=true; p++; }
if (*p=='*') { specialvalue=true; p++; }
if (*p=='^') { caseinsensitive=true; p++; }
// - now OP either in internal form or as pseudo-entity
if (*p=='>' || *p=='<') {
// possible two-char ops (>=, <=, <>)
op[0]=*p++;
if (*p=='>' || *p=='=') {
op[1]=*p++;
}
}
else if (*p=='=' || *p=='%' || *p=='$') {
// single char ops, just use them as is
op[0]=*p++;
}
else if (*p=='&') {
p++;
if (tolower(*p)=='i') { caseinsensitive=true; p++; }
if (strucmp(p,"eq;",3)==0) { op[0]='='; p+=3; }
else if (strucmp(p,"gt;",3)==0) { op[0]='>'; p+=3; }
else if (strucmp(p,"ge;",3)==0) { op[0]='>'; op[1]='='; p+=3; }
else if (strucmp(p,"lt;",3)==0) { op[0]='<'; p+=3; }
else if (strucmp(p,"le;",3)==0) { op[0]='<'; op[1]='='; p+=3; }
else if (strucmp(p,"ne;",3)==0) { op[0]='<'; op[1]='>'; p+=3; }
else if (strucmp(p,"con;",4)==0) { op[0]='%'; p+=4; }
else if (strucmp(p,"ncon;",5)==0) { op[0]='$'; p+=5; }
else {
PDEBUGPRINTFX(DBG_ERROR,("Expected comparison operator pseudo-entity but found '%s'",p-1));
break;
}
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Expected comparison operator but found '%s'",p));
break;
}
// next must be value
// - check for special value cases
if (strucmp(p,"&NULL;",6)==0) {
// SyncML DS 1.2
p+=6;
val='E';
specialvalue=true;
}
else if (strucmp(p,"&UNASSIGNED;",12)==0) {
// Synthesis extension
p+=12;
val='U';
specialvalue=true;
}
else {
val.erase();
}
// - get value chars
while (*p && *p!='&' && *p!='|' && *p!=')') {
// value char, possibly hex escaped
uInt16 c;
if (*p=='%') {
// convert from hex
if (HexStrToUShort(p+1,c,2)==2) {
p+=3;
}
else
c=*p++;
}
else
c=*p++;
// add to value
val += (char)c;
} // value
// now we have identifier, op and value
// - check and possibly sort out filterkeyword terms
termtofilter = checkFilterkeywordTerm(ident.c_str(),assigntomaketrue,op,caseinsensitive,val.c_str(),specialvalue,aItemTypeP);
// - add to filter if not handled already by other mechanism
if (termtofilter) {
if (logop) aFilter+=logop; // if this is a continuation, add logical operator now
aFilter += ident;
if (assigntomaketrue) aFilter+=':';
if (specialvalue) aFilter+='*';
if (caseinsensitive) aFilter+='^';
aFilter += op;
aFilter += val;
}
else {
PDEBUGPRINTFX(DBG_FILTER+DBG_EXOTIC,(
"checkFilterkeywordTerm(%s,%hd,%s,%hd,%s,%hd) prevents adding to filter",
ident.c_str(),(uInt16)assigntomaketrue,op,(uInt16)caseinsensitive,val.c_str(),(uInt16)specialvalue
));
if (logop) {
PDEBUGPRINTFX(DBG_FILTER,("Ignored logical operation '%c' due to always-ANDed filterkeyword",logop));
}
}
// now check for continuation: optional closing paranthesis plus logical op
// - closing paranthesis
do {
// skip spaces
while (isspace(*p)) p++;
if (*p!=')') break;
if (paraNest==0) {
// as we might parse filters as part of /fi() or /tf() options,
// this is not an error but only means end of filter expression
goto endFilter;
}
aFilter+=')';
paraNest--;
p++;
} while (true);
// - logical op
if (*p==0)
break; // done
else if (*p=='&') {
logop=*p++; // if no entity matches, & by itself is treated as AND
if (strucmp(p,"amp;",4)==0) { logop='&'; p+=4; }
else if (strucmp(p,"and;",4)==0) { logop='&'; p+=4; }
else if (strucmp(p,"or;",3)==0) { logop='|'; p+=3; }
}
else if (*p=='|') {
logop='|';
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Expected logical operator or end of filter but found '%s'",p));
break;
}
} // not opening paranthesis
} // while not end of filter
endFilter:
PDEBUGPRINTFX(DBG_FILTER+DBG_EXOTIC,("Resulting internal filter: %s",aFilter.c_str()));
// return pointer to terminating character
return p;
} // TLocalEngineDS::parseFilterCGI
#endif
// analyze database name
void TLocalEngineDS::analyzeName(
const char *aDatastoreURI,
string *aBaseNameP,
string *aTableNameP,
string *aCGIP
)
{
const char *p,*q=NULL, *r;
r=strchr(aDatastoreURI,'?');
p=strchr(aDatastoreURI,'/');
if (r && p>r) p=NULL; // if slash is in CGI, ignore it
else q=p+1; // slash exclusive
if (p!=NULL) {
// we have more than just the first element
if (aBaseNameP) aBaseNameP->assign(aDatastoreURI,p-aDatastoreURI);
// rest is table name and probably CGI
if (aTableNameP) {
if (r) aTableNameP->assign(q,r-q); // we have CGI
else *aTableNameP=q; // entire rest is tablename
}
}
else {
// no second path element, but possibly CGI
// - assign base name
if (aBaseNameP) {
if (r)
(*aBaseNameP).assign(aDatastoreURI,r-aDatastoreURI); // only up to CGI
else
(*aBaseNameP)=aDatastoreURI; // complete name
}
// - there is no table name
if (aTableNameP) aTableNameP->erase();
}
// return CGI (w/o question mark) if any
if (aCGIP) {
if (r) *aCGIP=r+1; else aCGIP->erase();
}
} // TLocalEngineDS::analyzeName
#ifdef SYSYNC_TARGET_OPTIONS
// parses single option, returns pointer to terminating char of argument string
// or NULL on error
// Note: if aArguments is passed NULL, this is an option without arguments,
// and an arbitrary non-NULL will be returned if parsing is ok
const char *TLocalEngineDS::parseOption(
const char *aOptName,
const char *aArguments,
bool aFromSyncCommand
)
{
#ifdef OBJECT_FILTERING
if (strucmp(aOptName,"fi")==0) {
if (!aArguments) return NULL;
// make sync set filter expression
string f;
aArguments=parseFilterCGI(aArguments,fLocalSendToRemoteTypeP,f); // if type being used for sending to remote is known here, use it
if (!aFromSyncCommand) {
addToFilter(f.c_str(),fSyncSetFilter,false); // AND chaining
// call this once to give derivate a chance to see if it can filter the now set fSyncSetFilter
engFilteredFetchesFromDB(true);
}
return aArguments; // end of filter pattern
}
#ifdef SYNCML_TAF_SUPPORT
else if (strucmp(aOptName,"tf")==0) {
if (!aArguments) return NULL;
// make temporary filter (or TAF) expression
aArguments=parseFilterCGI(aArguments,fLocalSendToRemoteTypeP,fTargetAddressFilter); // if type being used for sending to remote is known here, use it
// Note: TAF filters are always evaluated internally as we need all SyncSet records
// regardless of possible TAF suppression (for slowsync matching etc.)
return aArguments; // end of filter pattern
}
#endif
else if (aArguments && strucmp(aOptName,"dr")==0) {
// date range limit
sInt16 dstart,dend;
if (sscanf(aArguments,"%hd,%hd",&dstart,&dend)==2) {
// - find end of arguments
aArguments=strchr(aArguments,')');
// - calculate start and end
fDateRangeStart=getSystemNowAs(TCTX_UTC,getSessionZones());
fDateRangeEnd=fDateRangeStart;
// - now use offsets
fDateRangeStart+=dstart*linearDateToTimeFactor;
fDateRangeEnd+=dend*linearDateToTimeFactor;
return aArguments;
}
else return NULL;
}
else if (aArguments && strucmp(aOptName,"li")==0) {
// size limit
sInt16 n=StrToFieldinteger(aArguments,fSizeLimit);
if (n>0) {
// - find end of arguments
aArguments+=n;
return aArguments;
}
else return NULL;
}
else
if (!aArguments && strucmp(aOptName,"na")==0) {
// no attachments
fNoAttachments=true;
return (const char *)1; // non-zero
}
else
if (aArguments && strucmp(aOptName,"max")==0) {
// maximum number of items (for email for example)
sInt16 n=StrToULong(aArguments,fMaxItemCount);
if (n>0) {
// - find end of arguments
aArguments+=n;
return aArguments;
}
else return NULL;
}
else
#endif
#ifdef SYSYNC_SERVER
if (IS_SERVER && !aArguments && strucmp(aOptName,"slow")==0) {
// force a slow sync
PDEBUGPRINTFX(DBG_HOT,("Slowsync forced by CGI-option in db path"));
fForceSlowSync=true;
return (const char *)1; // non-zero
}
else
#endif // SYSYNC_SERVER
if (aArguments && strucmp(aOptName,"o")==0) {
// datastore options
// - find end of arguments
const char *p=strchr(aArguments,')');
if (p) fDBOptions.assign(aArguments,p-aArguments);
return p;
}
else
return NULL; // not parsed
} // TLocalEngineDS::parseOption
#endif
// parse options
localstatus TLocalEngineDS::engParseOptions(
const char *aTargetURIOptions, // option string contained in target URI
bool aFromSyncCommand // must be set when parsing options from <sync> target URI
)
{
localstatus sta=LOCERR_OK;
if (aTargetURIOptions) {
const char *p = aTargetURIOptions;
#ifdef SYSYNC_TARGET_OPTIONS
const char *q;
#endif
char c;
string taf; // official TAF
while ((c=*p)) {
#ifdef SYSYNC_TARGET_OPTIONS
if (c=='/') {
// proprietary option lead-in
// - get option name
string optname;
optname.erase();
while(isalnum(c=*(++p)))
optname+=c;
// - get arguments
if (c=='(') {
q=p; // save
p++; // skip "("
p=parseOption(optname.c_str(),p,aFromSyncCommand);
if (!p) {
// unrecognized or badly formatted option, just add it to TAF
taf+='/';
taf+=optname;
p=q; // restart after option name
continue;
}
if (*p!=')') {
sta=406;
PDEBUGPRINTFX(DBG_ERROR,("Syntax error in target options"));
break;
}
}
else {
// option without arguments
if (!parseOption(optname.c_str(),NULL,aFromSyncCommand)) {
sta=406;
PDEBUGPRINTFX(DBG_ERROR,("Unknown target option"));
break;
} // error, not parsed
p--; // will be incremented once again below
}
}
else
#endif
{
// char not part of an option
taf+=c;
}
// next
p++;
}
// check if we have TAF
if (taf.size()>0) {
#if defined(TAF_AS_SYNCSETFILTER) && defined(SYSYNC_TARGET_OPTIONS)
// treat as "fi(<filterexpression>)" option like before 1.0.8.10
if (!parseOption("fi",taf.c_str(),aFromSyncCommand)) { sta=406; } // error, not parsed
#else
#ifdef SYNCML_TAF_SUPPORT
// treat as "tf(<filterexpression>)" = real TAF
if (!parseOption("tf",taf.c_str(),aFromSyncCommand)) { sta=406; } // error, not parsed
#else
sta=406;
PDEBUGPRINTFX(DBG_ERROR,("TAF not supported"));
#endif
#endif
}
}
// return status
return sta;
} // TLocalEngineDS::engParseOptions
// process SyncML 1.2 style filter
localstatus TLocalEngineDS::engProcessDS12Filter(SmlFilterPtr_t aTargetFilter)
{
localstatus sta=LOCERR_OK;
if (aTargetFilter) {
// check general availability
#ifdef OBJECT_FILTERING
if (!fDSConfigP->fDS12FilterSupport)
#endif
{
PDEBUGPRINTFX(DBG_ERROR,("DS 1.2 style filtering is not available or disabled in config (<ds12filters>)"));
sta=406;
goto error;
}
// check filter
TSyncItemType *itemTypeP=NULL; // no associated type so far
bool inclusiveFilter=false; // default is EXCLUSIVE
// - meta
if (aTargetFilter->meta) {
SmlMetInfMetInfPtr_t metaP = smlPCDataToMetInfP(aTargetFilter->meta);
const char *typestr = smlMetaTypeToCharP(metaP);
// get sync item type for it
// - filter mostly applies to items SENT, so we search these first
itemTypeP = getSendType(typestr,NULL);
if (!itemTypeP)
itemTypeP = getReceiveType(typestr,NULL);
PDEBUGPRINTFX(DBG_FILTER,("DS12 <Filter> <Type> is '%s' -> %sfound",typestr,itemTypeP ? "" : "NOT "));
if (!itemTypeP) {
sta=415;
goto error;
}
}
// - filtertype
if (aTargetFilter->filtertype) {
const char *ftystr = smlPCDataToCharP(aTargetFilter->filtertype);
if (strucmp(ftystr,SYNCML_FILTERTYPE_INCLUSIVE)==0) {
inclusiveFilter=true;
}
else if (strucmp(ftystr,SYNCML_FILTERTYPE_EXCLUSIVE)==0) {
inclusiveFilter=false;
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Invalid <FilterType> '%s'",ftystr));
sta=422;
goto error;
}
}
// - field level filter
if (aTargetFilter->field) {
/// @todo %%% to be implemented
PDEBUGPRINTFX(DBG_ERROR,("Field-level filtering not supported"));
sta=406;
goto error;
}
// - record level filter
if (aTargetFilter->record) {
#ifdef OBJECT_FILTERING
SmlItemPtr_t recordItemP = aTargetFilter->record->item;
if (recordItemP) {
// - check grammar
const char *grammarstr = smlMetaTypeToCharP(smlPCDataToMetInfP(recordItemP->meta));
if (strucmp(grammarstr,SYNCML_FILTERTYPE_CGI)!=0) {
PDEBUGPRINTFX(DBG_ERROR,("Invalid filter grammar '%s'",grammarstr));
sta=422;
goto error;
}
// now get the actual filter string
const char *filterstring = smlPCDataToCharP(recordItemP->data);
PDEBUGPRINTFX(DBG_HOT,(
"Remote specified %sCLUSIVE filter query: '%s'",
inclusiveFilter ? "IN" : "EX",
filterstring
));
if (*filterstring) {
string f;
// parse it
filterstring = parseFilterCGI(filterstring,itemTypeP,f);
if (*filterstring) {
// not read to end
PDEBUGPRINTFX(DBG_ERROR,("filter query syntax error at: '%s'",filterstring));
sta=422;
goto error;
}
/// @todo: %%% check if this is correct interpretation
// - exclusive is what we used to call "sync set" filtering
// - inclusive seems to be former TAF
if (inclusiveFilter) {
// INCLUSIVE
#ifdef SYNCML_TAF_SUPPORT
fTargetAddressFilter=f;
#else
PDEBUGPRINTFX(DBG_ERROR,("This SyncML engine version has no INCLUSIVE filter support"));
#endif
}
else {
// EXCLUSIVE
addToFilter(f.c_str(),fSyncSetFilter,false); // AND chaining
PDEBUGPRINTFX(DBG_FILTER,("complete sync set filter is now: '%s'",fSyncSetFilter.c_str()));
// call this once to give derivate a chance to see if it can filter the now set fSyncSetFilter
engFilteredFetchesFromDB(true);
}
}
} // if item
#else
// no object filtering
PDEBUGPRINTFX(DBG_ERROR,("This SyncML engine version has no filter support (only PRO has)"));
sta=406;
goto error;
#endif
} // record
} // filter at all
error:
return sta;
} // TLocalEngineDS::engProcessDS12Filter
// process Sync alert from remote party: check if alert code is supported,
// check if slow sync is needed due to anchor mismatch
// - server case: also generate appropriate Alert acknowledge command
TAlertCommand *TLocalEngineDS::engProcessSyncAlert(
TSuperDataStore *aAsSubDatastoreOf, // if acting as subdatastore
uInt16 aAlertCode, // the alert code
const char *aLastRemoteAnchor, // last anchor of remote
const char *aNextRemoteAnchor, // next anchor of remote
const char *aTargetURI, // target URI as sent by remote, no processing at all
const char *aIdentifyingTargetURI, // target URI that was used to identify datastore
const char *aTargetURIOptions, // option string contained in target URI
SmlFilterPtr_t aTargetFilter, // DS 1.2 filter, NULL if none
const char *aSourceURI, // source URI
TStatusCommand &aStatusCommand // status that might be modified
)
{
TAlertCommand *alertcmdP=NULL;
localstatus sta=LOCERR_OK;
SYSYNC_TRY {
if (IS_SERVER) {
// save the identifying URI
fIdentifyingDBName = aIdentifyingTargetURI;
}
// determine status of read-only option
fReadOnly=
fSessionP->getReadOnly() || // session level read-only flag (probably set by login)
fDSConfigP->fReadOnly; // or datastore config
#ifdef SUPERDATASTORES
// if running as subdatastore of a superdatastore already, this call mus be from a superdatastore as well (aAsSubDatastoreOf!=NULL)
// Note: On a client, fAsSubDatastoreOf is set earlier in dsSetClientSyncParams()
// On a server, fAsSubDatastoreOf will be set now to avoid alerting as sub- and normal datastore at the same time.
if (fAsSubDatastoreOf && !aAsSubDatastoreOf) {
// bad, cannot be alerted directly AND as subdatastore
aStatusCommand.setStatusCode(400);
ADDDEBUGITEM(aStatusCommand,"trying to alert already alerted subdatastore");
PDEBUGPRINTFX(DBG_ERROR,("Already alerted as subdatastore of '%s'",fAsSubDatastoreOf->getName()));
return NULL;
}
// set subdatastore mode
fAsSubDatastoreOf = aAsSubDatastoreOf;
#endif
// reset type info
fLocalSendToRemoteTypeP = NULL;
fLocalReceiveFromRemoteTypeP = NULL;
fRemoteReceiveFromLocalTypeP=NULL;
fRemoteSendToLocalTypeP=NULL;
// prepare database-level scripts
// NOTE: in client case, alertprepscript is already rebuilt here!
#ifdef SCRIPT_SUPPORT
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fDBInitScript,fDataStoreScriptContextP,fSessionP);
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fSentItemStatusScript,fDataStoreScriptContextP,fSessionP);
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fReceivedItemStatusScript,fDataStoreScriptContextP,fSessionP);
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fAlertScript,fDataStoreScriptContextP,fSessionP);
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fDBFinishScript,fDataStoreScriptContextP,fSessionP,true); // now instantiate vars
#endif
// NOTE for client case:
// ALL instantiated datastores have already sent an Alert to the server by now here
// check DS 1.2 <filter>
sta = engProcessDS12Filter(aTargetFilter);
if (sta != LOCERR_OK) {
aStatusCommand.setStatusCode(sta);
ADDDEBUGITEM(aStatusCommand,"Invalid <Filter> in target options");
return NULL; // error in options
}
// Filter CGI is now a combination of TAF and Synthesis-Style
// extras (options).
if (aTargetURIOptions && *aTargetURIOptions) {
// there are target address options (such as filter CGI and TAF)
sta = engParseOptions(aTargetURIOptions,false);
if (sta != LOCERR_OK) {
aStatusCommand.setStatusCode(sta);
ADDDEBUGITEM(aStatusCommand,"Invalid CGI target URI options");
return NULL; // error in options
}
}
if (IS_SERVER) {
// server case: initially we are not in refresh only mode. Alert code or alert script could change this
fRefreshOnly=false;
}
// save it for suspend and reference in scripts
fAlertCode=aAlertCode;
#ifdef SCRIPT_SUPPORT
// call the alert script, which might want to force a slow sync and/or a server sync set zap
TScriptContext::execute(
fDataStoreScriptContextP,
fDSConfigP->fAlertScript,
&DBFuncTable,
this // caller context
);
aAlertCode=fAlertCode; // get possibly modified version back (SETALERTCODE)
#endif
// if we process a sync alert now, we haven't started sync or map generation
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// make sure we are not carrying forward any left-overs. Last sessions's tempGUID mappings that are
// needed for "early map" resolution might be loaded by the call to engInitSyncAnchors below.
// IMPORTANT NOTE: the tempGUIDs that might get loaded will become invalid as soon as <Sync>
// starts - so fTempGUIDMap needs to be cleared again as soon as the first <Sync> command arrives from the client.
fTempGUIDMap.clear();
}
#endif
// save remote's next anchor for saving at end of session
fNextRemoteAnchor = aNextRemoteAnchor;
// get target info in case we are server
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// now get anchor info out of database
// - make sure other anchor variables are set
sta = engInitSyncAnchors(
aIdentifyingTargetURI, // use processed form, not as sent by remote
aSourceURI
);
if (sta!=LOCERR_OK) {
// error getting anchors
aStatusCommand.setStatusCode(syncmlError(sta));
PDEBUGPRINTFX(DBG_ERROR,("Could not get Sync Anchor info, status=%hd",sta));
return NULL; // no alert to send back
}
// Server ok until here
PDEBUGPRINTFX(DBG_PROTO,(
"Saved Last Remote Client Anchor='%s', received <last> Remote Client Anchor='%s' (must match for normal sync)",
fLastRemoteAnchor.c_str(),
aLastRemoteAnchor
));
PDEBUGPRINTFX(DBG_PROTO,(
"Received <next> Remote Client Anchor='%s' (to be compared with <last> in NEXT session)",
fNextRemoteAnchor.c_str()
));
PDEBUGPRINTFX(DBG_PROTO,(
"(Saved) Last Local Server Anchor='%s', (generated) Next Local Server Anchor='%s' (sent to client as <last>/<next> in <alert>)",
fLastLocalAnchor.c_str(),
fNextLocalAnchor.c_str()
));
}
#endif
#ifdef SYSYNC_CLIENT
if (IS_CLIENT) {
// Client ok until here
PDEBUGPRINTFX(DBG_PROTO,(
"Saved Last Remote Server Anchor='%s', received <last> Remote Server Anchor='%s' (must match for normal sync)",
fLastRemoteAnchor.c_str(),
aLastRemoteAnchor
));
PDEBUGPRINTFX(DBG_PROTO,(
"Received <next> Remote Server Anchor='%s' (to be compared with <last> in NEXT session)",
fNextRemoteAnchor.c_str()
));
}
#endif
PDEBUGPRINTFX(DBG_PROTO,(
"(Saved) fResumeAlertCode = %hd (valid for >DS 1.2 only)",
fResumeAlertCode
));
// Now check for resume
// - default to what was actually alerted
uInt16 effectiveAlertCode=aAlertCode;
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// - check if resuming server session
fResuming=false;
if (aAlertCode==225) {
if (fSessionP->getSyncMLVersion()<syncml_vers_1_2) {
aStatusCommand.setStatusCode(406);
ADDDEBUGITEM(aStatusCommand,"Resume not supported in SyncML prior to 1.2");
PDEBUGPRINTFX(DBG_ERROR,("Resume not supported in SyncML prior to 1.2"));
return NULL;
}
// Resume requested
if (fResumeAlertCode==0 || !dsResumeSupportedInDB()) {
// cannot resume, suggest a normal sync (in case anchors do not match, this will become a 508 below)
aStatusCommand.setStatusCode(509); // cannot resume, override
effectiveAlertCode=200; // suggest normal sync
ADDDEBUGITEM(aStatusCommand,"Cannot resume, suggesting a normal sync");
PDEBUGPRINTFX(DBG_ERROR,("Cannot resume, suggesting a normal sync"));
}
else {
// we can resume, use the saved alert code
effectiveAlertCode=fResumeAlertCode;
PDEBUGPRINTFX(DBG_HOT,("Alerted to resume previous session, Switching to alert Code = %hd",fResumeAlertCode));
fResuming=true;
}
}
}
#endif
// now do the actual alert internally
if (sta==LOCERR_OK) {
// check if we can process the alert
// NOTE: for client this might cause a change in Sync mode, if server
// alerts something different than client alerted before.
// Note that a client will keep fromserver mode even if server
// changes to two-way, as it might be that we have sent the server
// a two-way alert even if we want fromserver due to compatibility with
// servers that cannot do fromserver.
if (IS_SERVER) {
// - Server always obeys what client requests (that is, if alertscript does not modify it)
sta = setSyncModeFromAlertCode(effectiveAlertCode,false); // as server
} // server
else {
// - for client, check that server can't switch to a client writing mode
// (we had a case when mobical did that for a user and erased all his data)
TSyncModes prevMode = fSyncMode; // remember previous mode
sta = setSyncModeFromAlertCode(effectiveAlertCode,true); // as client
if (prevMode==smo_fromclient && fSyncMode!=smo_fromclient) {
// server tries to switch to a mode that could be writing data to the client
// - forbidden
sta=403;
aStatusCommand.setStatusCode(syncmlError(sta));
ADDDEBUGITEM(aStatusCommand,"Server may not write to client");
PDEBUGPRINTFX(DBG_ERROR,("From-Client only: Server may not alert mode that writes client data (%hd) - blocked",effectiveAlertCode));
// - also abort sync of this datastore without chance to resume, as this problem might
// originate from a resume attempt, which the server
// tried to convert to a normal or slow sync. With cancelling the resume here, we make sure
// next sync will start over and sending the desired (one-way) sync mode again.
engAbortDataStoreSync(sta, false, false); // remote problem, not resumable
}
} // client
if (!isAborted()) {
if (sta!=LOCERR_OK) {
// Sync type not supported
// - go back to idle
changeState(dssta_idle,true); // force to idle
aStatusCommand.setStatusCode(syncmlError(sta));
ADDDEBUGITEM(aStatusCommand,"Sync type not supported");
PDEBUGPRINTFX(DBG_ERROR,("Sync type (Alert code %hd) not supported, err=%hd",effectiveAlertCode,sta));
}
}
}
if (sta==LOCERR_OK) {
// Sync type supported
// - set new state to alerted
if (IS_CLIENT) {
changeState(dssta_clientalerted,true); // force it
}
else {
changeState(dssta_serveralerted,true); // force it
}
// - datastore state is now dss_alerted
PDEBUGPRINTFX(DBG_HOT,(
"Alerted (code=%hd) for %s%s %s%s%s ",
aAlertCode,
fResuming ? "Resumed " : "",
SyncModeDescriptions[fSyncMode],
fSlowSync ? (fSyncMode==smo_twoway ? "Slow Sync" : "Refresh") : "Normal Sync",
fReadOnly ? " (Readonly)" : "",
fRefreshOnly ? " (Refreshonly)" : ""
));
CONSOLEPRINTF((
"- Remote alerts (%hd): %s%s %s%s%s for '%s' (source='%s')",
aAlertCode,
fResuming ? "Resumed " : "",
SyncModeDescriptions[fSyncMode],
fSlowSync ? (fSyncMode==smo_twoway ? "Slow Sync" : "Refresh") : "Normal Sync",
fReadOnly ? " (Readonly)" : "",
fRefreshOnly ? " (Refreshonly)" : "",
aTargetURI,
aSourceURI
));
// - now test if the sync state is same in client & server
// (if saved anchor is empty, slow sync is needed anyway)
if (
(
(
(!fLastRemoteAnchor.empty() &&
( (fLastRemoteAnchor==aLastRemoteAnchor)
#ifdef SYSYNC_CLIENT
|| (fSessionP->fLenientMode && IS_CLIENT)
#endif
)
) || // either anchors must match (or lenient mode for client)...
(fResuming && *aLastRemoteAnchor==0) // ...or in case of resume, remote not sending anchor is ok as well
)
&& !fForceSlowSync // ...but no force for slowsync may be set internally
)
|| fSlowSync // if slow sync is requested by the remote anyway, we don't need to be in sync anyway, so just go on
) {
if (!(fLastRemoteAnchor==aLastRemoteAnchor) && fSessionP->fLenientMode) {
PDEBUGPRINTFX(DBG_ERROR,("Warning - remote anchor mismatch but tolerated in lenient mode"));
}
// sync state ok or Slow sync requested anyway:
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// we can generate Alert with same code as sent
// %%% Note: this is not entirely clear, as SCTS sends
// corresponding SERVER ALERTED code back.
// Specs suggest that we send the code back unmodified
uInt16 alertCode = getSyncStateAlertCode(fServerAlerted);
alertcmdP = new TAlertCommand(fSessionP,this,alertCode);
fAlertCode=alertCode; // save it for reference in scripts and for suspend/resume
}
#endif
}
else {
// switch to slow sync
fSlowSync=true;
PDEBUGPRINTFX(DBG_HOT,("Switched to SlowSync because of Anchor mismatch or server-side user option"));
CONSOLEPRINTF(("- switched to SlowSync because of Sync Anchor mismatch"));
// sync state not ok, we need slow sync
aStatusCommand.setStatusCode(508); // Refresh required
// update effective alert code
uInt16 alertCode = getSyncStateAlertCode(false);
fAlertCode=alertCode; // save it for reference in scripts and for suspend
// NOTE: if client detected slow-sync not before here, status 508 alone
// (without another Alert 201 sent to the server) is sufficient for
// server to switch to slow sync.
if (IS_SERVER) {
// generate Alert for Slow sync
alertcmdP = new TAlertCommand(fSessionP,this,alertCode);
}
}
// Now we are alerted for a sync
// - reset item counters
fItemsSent = 0;
fItemsReceived = 0;
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// Server case
// - show info
PDEBUGPRINTFX(DBG_HOT,(
"ALERTED from client for %s%s%s Sync",
fResuming ? "resumed " : "",
fSlowSync ? "slow" : "normal",
fFirstTimeSync ? " first time" : ""
));
// server: add Item with Anchors and URIs
SmlItemPtr_t itemP = newItem();
// - anchors
itemP->meta=newMetaAnchor(fNextLocalAnchor.c_str(),fLastLocalAnchor.c_str());
// - MaxObjSize here again to make SCTS happy
if (
(fSessionP->getRootConfig()->fLocalMaxObjSize>0) &&
(fSessionP->getSyncMLVersion()>=syncml_vers_1_1)
) {
// SyncML 1.1 has object size and we need to put it here for SCTS
smlPCDataToMetInfP(itemP->meta)->maxobjsize=newPCDataLong(
fSessionP->getRootConfig()->fLocalMaxObjSize
);
}
// - URIs (reversed from what was received in Alert)
itemP->source=newLocation(aTargetURI); // use unprocessed form as sent by remote
itemP->target=newLocation(aSourceURI);
// - add to alert command
alertcmdP->addItem(itemP);
// - set new state, alert now answered
changeState(dssta_serveransweredalert,true); // force it
} // server case
#endif // SYSYNC_SERVER
#ifdef SYSYNC_CLIENT
if (IS_CLIENT) {
// Client case
// - now sync mode is stable (late switch to slowsync has now occurred if any)
changeState(dssta_syncmodestable,true);
// - show info
PDEBUGPRINTFX(DBG_HOT,(
"ALERTED from server for %s%s%s Sync",
fResuming ? "resumed " : "",
fSlowSync ? "slow" : "normal",
fFirstTimeSync ? " first time" : ""
));
#ifdef PROGRESS_EVENTS
// - progress event
DB_PROGRESS_EVENT(
this,
pev_alerted,
fSlowSync ? (fFirstTimeSync ? 2 : 1) : 0,
fResuming ? 1 : 0,
fSyncMode
);
#endif // PROGRESS_EVENTS
} // client Case
#endif // SYSYNC_CLIENT
}
// clear partial item if we definitely know we are not resuming
if (!fResuming) {
// not resuming - prevent that partial item is used in TSyncOpCommand
fPartialItemState=pi_state_none;
// free this space early (would be freed at session end anyway, but we don't need it any more now)
if (fPIStoredDataAllocated) {
smlLibFree(fPIStoredDataP);
fPIStoredDataAllocated=false;
}
fPIStoredDataP=NULL;
}
// save name how remote adresses local database
// (for sending same URI back in own Sync)
fRemoteViewOfLocalURI = aTargetURI; // save it
if (IS_SERVER) {
fRemoteDBPath = aSourceURI;
}
if (sta!=LOCERR_OK) {
// no alert command
if (alertcmdP) delete alertcmdP;
alertcmdP=NULL;
aStatusCommand.setStatusCode(syncmlError(sta));
PDEBUGPRINTFX(DBG_HOT,("engProcessSyncAlert failed with status=%hd",sta));
}
}
SYSYNC_CATCH (...)
// clean up locally owned objects
if (alertcmdP) delete alertcmdP;
SYSYNC_RETHROW;
SYSYNC_ENDCATCH
// return alert command, if any
return alertcmdP;
} // TLocalEngineDS::engProcessSyncAlert
// process status received for sync alert
bool TLocalEngineDS::engHandleAlertStatus(TSyError aStatusCode)
{
bool handled=false;
if (IS_CLIENT) {
// for client, make sure we have just sent the alert
if (!testState(dssta_clientsentalert,true)) return false; // cannot switch if server not alerted
// anyway, we have seen the status
changeState(dssta_clientalertstatused,true); // force it
}
else {
// for server, check if client did combined init&sync
if (fLocalDSState>=dssta_syncmodestable) {
// must be combined init&sync
if (aStatusCode!=200) {
// everything except ok is not allowed here
PDEBUGPRINTFX(DBG_ERROR,("In combined init&sync, Alert status must be ok (but is %hd)",aStatusCode));
dsAbortDatastoreSync(400,false); // remote problem
}
// aborted or not, status is handled
return true;
}
// normal case with separate init: we need to have answered the alert here
if (!testState(dssta_serveransweredalert,true)) return false; // cannot switch if server not alerted
} // server case
// now check status code
if (aStatusCode==508) {
// remote party needs slow sync
PDEBUGPRINTFX(DBG_HOT,("engHandleAlertStatus: Remote party needs SlowSync, switching to slowsync (AFTER alert, cancelling possible Resume)"));
// Note: in server and client cases, this mode change may happen AFTER alert command exchange
// - switch to slow sync
fSlowSync=true;
// - if we are late-forced to slow sync, this means that this cannot be a resume
fResuming=false;
// - update effective alert code that will be saved when this session gets suspended
fAlertCode=getSyncStateAlertCode(fServerAlerted);
handled=true;
}
else if (aStatusCode==200) {
handled=true;
}
if (IS_CLIENT) {
// check for resume override by server
if (!handled && fResuming) {
// we have requested resume
if (aStatusCode==509) {
// resume not accepted by server, but overridden by another sync type
fResuming=false;
PDEBUGPRINTFX(DBG_ERROR,("engHandleAlertStatus: Server rejected Resume"));
handled=true;
}
}
}
else {
// if we have handled it here, sync mode is now stable
if (handled) {
// if we get that far, sync mode for server is now stable AND we can receive cached maps
changeState(dssta_syncmodestable,true); // force it, sync mode is now stable, no further changes are possible
}
}
// no other status codes are supported at the datastore level
if (!handled && aStatusCode>=400) {
engAbortDataStoreSync(aStatusCode, false); // remote problem
handled=true;
}
return handled; // status handled
} // TLocalEngineDS::engHandleAlertStatus
// initialize reception of syncop commands for datastore
// Note: previously, this was implemented as initLocalDatastoreSync in syncsession
localstatus TLocalEngineDS::engInitForSyncOps(
const char *aRemoteDatastoreURI // URI of remote datastore
)
{
localstatus sta = LOCERR_OK;
// no default types
TSyncItemType *LocalSendToRemoteTypeP=NULL; // used by local to send to remote
TSyncItemType *RemoteReceiveFromLocalTypeP=NULL; // used by remote to receive from local
TSyncItemType *LocalReceiveFromRemoteTypeP=NULL; // used by local to receive from remote
TSyncItemType *RemoteSendToLocalTypeP=NULL; // used by remote to send to local
// Now determine remote datastore
// Note: It might be that this was called already earlier in the session, so
// the link between local and remote datastore might already exist
if (fRemoteDatastoreP==NULL) {
// try to locate it by name and set it - in case of superdatastore, it will be set in all subdatastores
engSetRemoteDatastore(fSessionP->findRemoteDataStore(aRemoteDatastoreURI));
}
else {
// There is a remote datastore already associated
#ifdef SYDEBUG
// - make a sanity check to see if sepcified remote URI matches
if(fRemoteDatastoreP!=fSessionP->findRemoteDataStore(aRemoteDatastoreURI)) {
PDEBUGPRINTFX(DBG_ERROR,(
"Warning: Received remote DS LocURI '%s' does not match already associated DS '%s'. We use the associated DS.",
aRemoteDatastoreURI,
fRemoteDatastoreP->getName()
));
}
#endif
}
// Now create a dummy remote data store for a blind sync attempt
if (!fRemoteDatastoreP) {
// no such remote datastore for this local datastore known, create one (or fail)
#ifdef REMOTE_DS_MUST_BE_IN_DEVINF
if (fSessionP->fRemoteDataStoresKnown) {
// we have received devinf, but still can't find remote data store: error
// Note: we had to disable this because of bugs in smartner server
PDEBUGPRINTFX(DBG_ERROR,("Remote datastore name '%s' not found in received DevInf",aRemoteDatastoreURI));
return 404;
}
else
#else
if (fSessionP->fRemoteDataStoresKnown) {
// we have received devinf, but still can't find remote data store:
// just show in log, but continue as if there was no devInf received at all
PDEBUGPRINTFX(DBG_ERROR,("Warning: Remote datastore name '%s' not found in received DevInf.",aRemoteDatastoreURI));
}
#endif
{
// We couldn't retrieve DevInf (or !REMOTE_DS_MUST_BE_IN_DEVINF), so we have to try blind
// - check remote specifics here if we had no devinf (there might be default remote
// rules to apply or checking license restrictions
// - this is executed only once per session, after that, we'll be fRemoteDevInfLock-ed
if (!fSessionP->fRemoteDevInfKnown && !fSessionP->fRemoteDevInfLock) {
// detect client specific server behaviour if needed
sta = fSessionP->checkRemoteSpecifics(NULL);
fSessionP->remoteAnalyzed(); // analyzed now (accepted or not does not matter)
if (sta!=LOCERR_OK)
return sta; // not ok, device rejected
}
// default data types are those preferred by local datastore (or explicitly marked for blind sync attempts)
if (getDSConfig()->fTypeSupport.fPreferredLegacy) {
// we have a preferred type for blind sync attempts
LocalSendToRemoteTypeP = getSession()->findLocalType(getDSConfig()->fTypeSupport.fPreferredLegacy);
LocalReceiveFromRemoteTypeP = LocalSendToRemoteTypeP;
}
else {
// no specific "blind" preference, use my own normally preferred types
LocalSendToRemoteTypeP = getPreferredTxItemType(); // send in preferred tx type of local datastore
LocalReceiveFromRemoteTypeP = getPreferredRxItemType(); // receive in preferred rx type of local datastore
}
// same type on both end (as only local type exists)
RemoteReceiveFromLocalTypeP = LocalSendToRemoteTypeP; // same on both end
RemoteSendToLocalTypeP = LocalReceiveFromRemoteTypeP; // same on both end (as only local type exists)
// create "remote" datastore with matching properties to local one
PDEBUGPRINTFX(DBG_ERROR,("Warning: No DevInf for remote datastore, running blind sync attempt"));
TRemoteDataStore *remDsP;
MP_NEW(remDsP,DBG_OBJINST,"TRemoteDataStore",TRemoteDataStore(
fSessionP,
aRemoteDatastoreURI, // remote name of datastore
0 // standard Sync caps
));
// - set it (in case of superdatastore in all subdatastores as well)
engSetRemoteDatastore(remDsP);
// add type support
fRemoteDatastoreP->setPreferredTypes(
RemoteReceiveFromLocalTypeP, // remote receives in preferred tx type of local datastore
RemoteSendToLocalTypeP // remote sends in preferred rx type of local datastore
);
// add it to the remote datastore list
fSessionP->fRemoteDataStores.push_back(fRemoteDatastoreP);
// make sure late devInf arriving won't supersede our artificially created remote datastore any more
fSessionP->fRemoteDevInfLock=true;
}
}
else {
// found remote DB, determine default data exchange types
// - common types for sending data to remote
LocalSendToRemoteTypeP=getTypesForTxTo(fRemoteDatastoreP,&RemoteReceiveFromLocalTypeP);
// - common types for receiving data from remote
LocalReceiveFromRemoteTypeP=getTypesForRxFrom(fRemoteDatastoreP,&RemoteSendToLocalTypeP);
}
#ifndef NO_REMOTE_RULES
// check if rule match type will override what we found so far
if (!fSessionP->fActiveRemoteRules.empty()) {
// have a look at our rulematch types
TRuleMatchTypesContainer::iterator pos;
TSyncItemType *ruleMatchTypeP = NULL;
for (pos=fRuleMatchItemTypes.begin();pos!=fRuleMatchItemTypes.end();++pos) {
// there is a rule applied
// - parse match string in format "rule[,rule]..." with * and ? wildcards allowed in "rule"
cAppCharP p=(*pos).ruleMatchString;
while (*p!=0) {
// split at commas
cAppCharP e=strchr(p,',');
size_t n;
if (e) {
n=e-p;
e++;
}
else {
n=strlen(p);
e=p+n;
}
// see if that matches with any of the active rules
TRemoteRulesList::iterator apos;
for(apos=fSessionP->fActiveRemoteRules.begin();apos!=fSessionP->fActiveRemoteRules.end();apos++) {
if (strwildcmp((*apos)->getName(), p, 0, n)==0) {
ruleMatchTypeP=(*pos).itemTypeP; // get the matching type
break;
}
}
if (ruleMatchTypeP) break; // found a rule match type
// test next match target
p=e;
}
// apply if found one already
if (ruleMatchTypeP) {
// use this instead of normal types
// - local types
LocalSendToRemoteTypeP=ruleMatchTypeP; // used by local to send to remote
LocalReceiveFromRemoteTypeP=ruleMatchTypeP; // used by local to receive from remote
// Find matching remote types
// - first look for existing remote type with same config as local one
TSyncItemType *remCorrTypeP = fSessionP->findRemoteType(ruleMatchTypeP->getTypeConfig(),fRemoteDatastoreP);
// - if none found, create one and have it inherit the CTCap options of the generic version that is already there
if (!remCorrTypeP) {
// none found: need to create one
remCorrTypeP = ruleMatchTypeP->newCopyForSameType(fSessionP,fRemoteDatastoreP);
if (remCorrTypeP) {
// - get generic remote type (the one that might have received CTCap already)
TSyncItemType *remGenericTypeP = fRemoteDatastoreP->getSendType(ruleMatchTypeP);
// - copy options
if (remGenericTypeP) remCorrTypeP->copyCTCapInfoFrom(*remGenericTypeP);
}
}
// now assign
RemoteReceiveFromLocalTypeP=remCorrTypeP;
RemoteSendToLocalTypeP=remCorrTypeP;
// Show that we are using ruleMatch type
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,(
"An active remote rule overrides default type usage - forcing type '%s' for send and receive",
ruleMatchTypeP->getTypeConfig()->getName()
));
// done
break;
}
}
}
#endif
// check if we are sync compatible (common type for both directions)
if (LocalSendToRemoteTypeP && LocalReceiveFromRemoteTypeP && RemoteReceiveFromLocalTypeP && RemoteSendToLocalTypeP) {
// avoid further changes in remote devInf (e.g. by late result of GET, sent *after* first <sync>)
fSessionP->fRemoteDevInfLock=true;
// there is a common data type for each of both directions
// - show local types
PDEBUGPRINTFX(DBG_DATA,(
"Local Datastore '%s' - Types: tx to remote: '%s': %s (%s), rx from remote: '%s': %s (%s)",
getName(),
LocalSendToRemoteTypeP->getTypeConfig()->getName(),LocalSendToRemoteTypeP->getTypeName(), LocalSendToRemoteTypeP->getTypeVers(),
LocalReceiveFromRemoteTypeP->getTypeConfig()->getName(),LocalReceiveFromRemoteTypeP->getTypeName(), LocalReceiveFromRemoteTypeP->getTypeVers()
));
// - show remote types
PDEBUGPRINTFX(DBG_DATA+DBG_DETAILS,(
"Remote Datastore '%s' - Types: tx to local: '%s': %s (%s), rx from local: '%s': %s (%s)",
fRemoteDatastoreP->getName(),
RemoteSendToLocalTypeP->getTypeConfig()->getName(),RemoteSendToLocalTypeP->getTypeName(), RemoteSendToLocalTypeP->getTypeVers(),
RemoteReceiveFromLocalTypeP->getTypeConfig()->getName(),RemoteReceiveFromLocalTypeP->getTypeName(), RemoteReceiveFromLocalTypeP->getTypeVers()
));
}
else {
// datastores are not sync compatible
sta=415;
PDEBUGPRINTFX(DBG_ERROR,("No common datastore formats -> cannot sync (415)"));
PDEBUGPRINTFX(DBG_EXOTIC,("- LocalSendToRemoteTypeP = '%s'", LocalSendToRemoteTypeP ? LocalSendToRemoteTypeP->getTypeName() : "<missing>"));
PDEBUGPRINTFX(DBG_EXOTIC,("- LocalReceiveFromRemoteTypeP = '%s'", LocalReceiveFromRemoteTypeP ? LocalReceiveFromRemoteTypeP->getTypeName() : "<missing>"));
PDEBUGPRINTFX(DBG_EXOTIC,("- RemoteSendToLocalTypeP = '%s'", RemoteSendToLocalTypeP ? RemoteSendToLocalTypeP->getTypeName() : "<missing>"));
PDEBUGPRINTFX(DBG_EXOTIC,("- RemoteReceiveFromLocalTypeP = '%s'", RemoteReceiveFromLocalTypeP ? RemoteReceiveFromLocalTypeP->getTypeName() : "<missing>"));
engAbortDataStoreSync(sta,true,false); // do not proceed with sync of this datastore, local problem, not resumable
return sta;
}
// set type info in local datastore
setSendTypeInfo(LocalSendToRemoteTypeP,RemoteReceiveFromLocalTypeP);
setReceiveTypeInfo(LocalReceiveFromRemoteTypeP,RemoteSendToLocalTypeP);
// - initialize usage of types (checks compatibility as well)
return initDataTypeUse();
} // TLocalEngineDS::engInitForSyncOps
// called from <sync> command to generate sync sub-commands to be sent to remote
// Returns true if now finished for this datastore
// also changes state to dssta_syncgendone when all sync commands have been generated
bool TLocalEngineDS::engGenerateSyncCommands(
TSmlCommandPContainer &aNextMessageCommands,
TSmlCommand * &aInterruptedCommandP,
const char *aLocalIDPrefix
)
{
PDEBUGBLOCKFMT(("SyncGen","Now generating sync commands","datastore=%s",getName()));
bool finished=false;
#ifdef SYSYNC_CLIENT
if (IS_CLIENT)
finished = logicGenerateSyncCommandsAsClient(aNextMessageCommands, aInterruptedCommandP, aLocalIDPrefix);
#endif
#ifdef SYSYNC_SERVER
if (IS_SERVER)
finished = logicGenerateSyncCommandsAsServer(aNextMessageCommands, aInterruptedCommandP, aLocalIDPrefix);
#endif
// change state when finished
if (finished) {
changeState(dssta_syncgendone,true);
if (IS_CLIENT) {
// from client only skips to clientmapssent without any server communication
// (except if we are in old synthesis-compatible mode which runs from-client-only
// with empty sync-from-server and map phases.
if (getSyncMode()==smo_fromclient && !fSessionP->fCompleteFromClientOnly) {
// data access ends with all sync commands generated in from-client-only
PDEBUGPRINTFX(DBG_PROTO,("From-Client-Only sync: skipping directly to end of map phase now"));
changeState(dssta_dataaccessdone,true);
changeState(dssta_clientmapssent,true);
}
}
}
PDEBUGPRINTFX(DBG_DATA,(
"engGenerateSyncCommands ended, state='%s', sync generation %sdone",
getDSStateName(),
fLocalDSState>=dssta_syncgendone ? "" : "NOT "
));
PDEBUGENDBLOCK("SyncGen");
return finished;
} // TLocalEngineDS::engGenerateSyncCommands
// called to confirm a sync operation's completion (status from remote received)
// @note aSyncOp passed not necessarily reflects what was sent to remote, but what actually happened
void TLocalEngineDS::dsConfirmItemOp(TSyncOperation aSyncOp, cAppCharP aLocalID, cAppCharP aRemoteID, bool aSuccess, localstatus aErrorStatus)
{
// commands failed with "cancelled" should be re-sent for resume
if (!aSuccess && aErrorStatus==514 && dsResumeSupportedInDB() && fSessionP->isSuspending()) {
// cancelled syncop as result of explicit suspend: mark for resume as it was never really processed at the other end
PDEBUGPRINTFX(DBG_DATA+DBG_EXOTIC,("Cancelled SyncOp during suspend -> mark for resume"));
engMarkItemForResume(aLocalID,aRemoteID,true);
}
PDEBUGPRINTFX(DBG_DATA+DBG_EXOTIC,(
"dsConfirmItemOp completed, syncop=%s, localID='%s', remoteID='%s', %s, errorstatus=%hd",
SyncOpNames[aSyncOp],
aLocalID ? aLocalID : "<none>",
aRemoteID ? aRemoteID : "<none>",
aSuccess ? "SUCCESS" : "FAILURE",
aErrorStatus
));
} // TLocalEngineDS::dsConfirmItemOp
// handle status of sync operation
// Note: in case of superdatastore, status is always directed to the originating subdatastore, as
// the fDataStoreP of the SyncOpCommand is set to subdatastore when generating the SyncOps.
bool TLocalEngineDS::engHandleSyncOpStatus(TStatusCommand *aStatusCmdP,TSyncOpCommand *aSyncOpCmdP)
{
TSyError statuscode = aStatusCmdP->getStatusCode();
// we can make it simple here because we KNOW that we do not send multiple items per SyncOp, so we
// just need to look at the first item's target and source
const char *localID = aSyncOpCmdP->getSourceLocalID();
const char *remoteID = aSyncOpCmdP->getTargetRemoteID();
#ifdef SYSYNC_SERVER
string realLocID;
#endif
if (localID) {
#ifdef SUPERDATASTORES
// remove possible prefix if this item was sent in the <sync> command context of a superdatastore
if (fAsSubDatastoreOf) {
// let superdatastore remove the prefix for me
localID = fAsSubDatastoreOf->removeSubDSPrefix(localID,this);
}
#endif
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// for server only: convert to internal representation
realLocID=localID;
obtainRealLocalID(realLocID);
localID=realLocID.c_str();
}
#endif
}
// handle special cases for Add/Replace/Delete
TSyncOperation sop = aSyncOpCmdP->getSyncOp();
switch (sop) {
case sop_wants_add:
case sop_add:
if (statuscode<300 || statuscode==419) {
// All ok status 2xx as well as special "merged" 419 is ok for an add:
// Whatever remote said, I know this is an add and so I counts this as such
// (even if the remote somehow merged it with existing data,
// it is obviously a new item in my sync set with this remote)
fRemoteItemsAdded++;
dsConfirmItemOp(sop_add,localID,remoteID,true); // ok added
}
else if (
statuscode==418 &&
(isResuming()
|| (isSlowSync() && IS_CLIENT)
)
) {
// "Already exists"/418 is acceptable...
// ... in slow sync as client, as some servers use it instead of 200/419 for slow sync match
// ... during resumed sync as server with clients like Symbian which
// can detect duplicate adds themselves. Should not generally
// occur, as we shouldn't re-send them as long as we haven't seen
// a map. But symbian cannot send early maps - it instead does
// it's own duplicate checking.
// ... during resumed sync as client (as servers might issue 418 for
// items send a second time after an implicit suspend)
PDEBUGPRINTFX(DBG_ERROR,("Warning: received 418 status for add in resumed/slowsync session -> treat it as ok (200)"));
dsConfirmItemOp(sop_replace,localID,remoteID,true); // kind of ok
statuscode=200; // convert to ok (but no count incremented, as nothing changed)
}
else {
dsConfirmItemOp(sop_add,localID,remoteID,false,statuscode); // failed add
}
// adding with 420 error: device full
if (statuscode==420) {
// special case: device indicates that it is full, so stop adding in this session
PDEBUGPRINTFX(DBG_ERROR,("Warning: Status %hd: Remote device full -> preventing further adds in this session",statuscode));
engStopAddingToRemote();
fRemoteItemsError++; // this is considered a remote item error
}
break;
// case sop_copy: break;
case sop_wants_replace:
case sop_replace:
#ifdef SYSYNC_SERVER
if (IS_SERVER && (statuscode==404 || statuscode==410)) {
// obviously, remote item that we wanted to change does not exist any more.
// Instead of aborting the session we'll just remove the map item for that
// server item, such that it will be re-added in the next sync session
PDEBUGPRINTFX(DBG_DATA,("Status %hd: Replace target not found on client -> silently ignore but remove map in server (item will be added in next session), ",statuscode));
// remove map for remote item(s), targetRef contain remoteIDs
SmlTargetRefListPtr_t targetrefP = aStatusCmdP->getStatusElement()->targetRefList;
while (targetrefP) {
// target ref available
engProcessMap(smlPCDataToCharP(targetrefP->targetRef),NULL);
// next
targetrefP=targetrefP->next;
}
statuscode=410; // always use "gone" status (even if we might have received a 404)
dsConfirmItemOp(sop_replace,localID,remoteID,false,statuscode);
break;
}
else
#endif
if (statuscode==201) {
fRemoteItemsAdded++;
dsConfirmItemOp(sop_add,localID,remoteID,true); // ok as add
}
else if (statuscode<300 || statuscode==419) { // conflict resolved counts as ok as well
fRemoteItemsUpdated++;
dsConfirmItemOp(sop_replace,localID,remoteID,true); // ok as replace
}
#ifdef SYSYNC_CLIENT
else if (IS_CLIENT && (isSlowSync() && statuscode==418)) {
// "Already exists"/418 is acceptable as client in slow sync because some
// servers use it instead of 200/419 for slow sync match
PDEBUGPRINTFX(DBG_ERROR,("Warning: received 418 for for replace during slow sync - treat it as ok (200), but don't count as update"));
dsConfirmItemOp(sop_replace,localID,remoteID,true); // 418 is acceptable in slow sync (not really conformant, but e.g. happening with Scheduleworld)
statuscode=200; // always use "gone" status (even if we might have received a 404)
}
#endif // SYSYNC_CLIENT
else {
dsConfirmItemOp(sop_replace,localID,remoteID,false,statuscode); // failed replace
}
break;
case sop_archive_delete:
case sop_soft_delete:
case sop_delete:
if (statuscode<211) fRemoteItemsDeleted++;
// allow 211 and 404 for delete - after all, the record is not there
// any more on the remote
if (statuscode==404 || statuscode==211) {
PDEBUGPRINTFX(DBG_DATA,("Status: %hd: To-be-deleted item not found, but accepted this (changed status to 200)",statuscode));
statuscode=200;
}
// if ok (explicit or implicit), we can confirm the delete
dsConfirmItemOp(sop_delete,localID,remoteID,statuscode<300,statuscode); // counts as ok delete
break;
default: break;
} // switch
// check if we want to mark failed items for resend in the next session or abort
bool resend = fDSConfigP->fResendFailing; // get default from config
#ifdef SCRIPT_SUPPORT
// let script check status code
TErrorFuncContext errctx;
errctx.statuscode = statuscode;
errctx.resend = resend;
errctx.newstatuscode = statuscode;
errctx.syncop = sop;
errctx.datastoreP = this;
// - first check datastore level
if (
TScriptContext::executeTest(
false, // assume script does NOT handle status entirely
fDataStoreScriptContextP,
fDSConfigP->fSentItemStatusScript,
&ErrorFuncTable,
&errctx // caller context
)
) {
// completely handled
PDEBUGPRINTFX(DBG_ERROR,("Status: %hd: Handled by datastore script (original op was %s)",statuscode,SyncOpNames[sop]));
return true;
}
errctx.statuscode = errctx.newstatuscode;
// - then check session level
if (
TScriptContext::executeTest(
false, // assume script does NOT handle status entirely
fSessionP->fSessionScriptContextP,
fSessionP->getSessionConfig()->fSentItemStatusScript,
&ErrorFuncTable,
&errctx // caller context
)
) {
// completely handled
PDEBUGPRINTFX(DBG_ERROR,("Status: %hd: Handled by session script (original op was %s)",statuscode,SyncOpNames[sop]));
return true;
}
// not completely handled, use possibly modified status code
#ifdef SYDEBUG
if (statuscode != errctx.newstatuscode) {
PDEBUGPRINTFX(DBG_ERROR,("Status: Script changed original status=%hd to %hd (original op was %s)",statuscode,errctx.newstatuscode,SyncOpNames[errctx.syncop]));
}
#endif
statuscode = errctx.newstatuscode;
resend = errctx.resend;
#endif
// now perform default action according to status code
switch (statuscode) {
case 200:
break;
case 201:
PDEBUGPRINTFX(DBG_PROTO,("Status: %hd: Item added (original op was %s)",statuscode,SyncOpNames[sop]));
break;
case 204:
PDEBUGPRINTFX(DBG_PROTO,("Status: %hd: No content (original op was %s)",statuscode,SyncOpNames[sop]));
break;
case 207:
case 208:
case 209:
case 419:
PDEBUGPRINTFX(DBG_HOT,("Status: %hd: Conflict resolved (original op was %s)",statuscode,SyncOpNames[sop]));
break;
case 210:
PDEBUGPRINTFX(DBG_HOT,("Status: %hd: Delete without archive (original op was %s)",statuscode,SyncOpNames[sop]));
break;
case 211:
PDEBUGPRINTFX(DBG_ERROR,("Status: %hd: nothing deleted, item not found (original op was %s)",statuscode,SyncOpNames[sop]));
break;
case 410: // gone
case 420: // device full
// these have been handled above and are considered ok now
break;
case 514: // cancelled
// ignore cancelling while suspending, as these are CAUSED by the suspend
if (fSessionP->isSuspending() && dsResumeSupportedInDB()) {
// don't do anything here - we'll be suspended later (but process commands until then)
// dsConfirmItemOp() has already caused the item to be marked for resume
break;
}
// for non-DS-1.2 sessions, we treat 514 like the other errors below (that is - retry might help)
case 424: // size mismatch (e.g. due to faild partial item resume attempt -> retry will help)
case 417: // retry later (remote says that retry will probably work)
case 506: // processing error, retry later (remote says that retry will probably work)
case 404: // not found (retry is not likely to help, but does not harm too much, either)
case 408: // timeout (if that happens on a single item, retry probably helps)
case 415: // bad type (retry is not likely to help, but does not harm too much, either)
case 510: // datastore failure (too unspecific to know if retry might help, but why not?)
case 500: // general failure (too unspecific to know if retry might help, but why not?)
// these errors cause either a resend in a later session
// or only abort the datastore, but not the session
if (resend && dsResumeSupportedInDB()) {
PDEBUGPRINTFX(DBG_ERROR,("Status: General error %hd (original op was %s) -> marking item for resend in next session",statuscode,SyncOpNames[sop]));
engMarkItemForResend(localID,remoteID); // Note: includes incrementing fRemoteItemsError
}
else {
PDEBUGPRINTFX(DBG_ERROR,("Status: General error %hd (original op was %s) -> aborting sync with this datastore",statuscode,SyncOpNames[sop]));
engAbortDataStoreSync(statuscode,false); // remote problem
}
break;
default:
// let command handle it
return false;
//break;
}
// status handled
return true; // handled status
} // TLocalEngineDS::engHandleSyncOpStatus
/// Internal events during sync for derived classes
/// @Note local DB authorisation must be established already before calling these
/// - cause loading of all session anchoring info and other admin data (logicMakeAdminReady())
/// fLastRemoteAnchor,fLastLocalAnchor,fNextLocalAnchor; isFirstTimeSync() will be valid after the call
/// - in case of superdatastore, consolidates the anchor information from the subdatastores
localstatus TLocalEngineDS::engInitSyncAnchors(
cAppCharP aDatastoreURI, ///< local datastore URI
cAppCharP aRemoteDBID ///< ID of remote datastore (to find session information in local DB)
)
{
// nothing more to do than making admin data ready
// - this will fill all dsSavedAdminData members here and in all derived classes
localstatus sta=logicMakeAdminReady(aDatastoreURI, aRemoteDBID);
if (sta==LOCERR_OK) {
changeState(dssta_adminready); // admin data is now ready
}
// return on error
return sta;
} // TLocalEngineDS::engInitSyncAnchors
#ifdef SYSYNC_CLIENT
// initialize Sync alert for datastore according to Parameters set with dsSetClientSyncParams()
localstatus TLocalEngineDS::engPrepareClientSyncAlert(void)
{
#ifdef SUPERDATASTORES
// no operation here if running under control of a superdatastore.
// superdatastore's engPrepareClientSyncAlert() will call engPrepareClientRealDSSyncAlert of all subdatastores at the right time
if (fAsSubDatastoreOf)
return LOCERR_OK;
#endif
// this is a real datastore
return engPrepareClientDSForAlert();
} // TLocalEngineDS::engPrepareClientSyncAlert
// initialize Sync alert for datastore according to Parameters set with dsSetClientSyncParams()
localstatus TLocalEngineDS::engPrepareClientDSForAlert(void)
{
localstatus sta;
// reset the filters that might be added to in alertprepscript
// (as they might have been half set-up in a previous failed alert, they must be cleared and re-constructed here)
resetFiltering();
#ifdef SCRIPT_SUPPORT
// AlertPrepareScript to add filters and CGI
// - rebuild early (before all of the other DS scripts in makeAdminReady caused by engInitSyncAnchors below!)
TScriptContext::rebuildContext(fSessionP->getSyncAppBase(),fDSConfigP->fAlertPrepScript,fDataStoreScriptContextP,fSessionP);
// - add custom DS 1.2 filters and/or custom CGI to fRemoteDBPath
TScriptContext::execute(
fDataStoreScriptContextP,
fDSConfigP->fAlertPrepScript,
fDSConfigP->getClientDBFuncTable(), // function table with extra
this // datastore pointer needed for context
);
#endif
// - save the identifying name of the DB
fIdentifyingDBName = fLocalDBPath;
// - get information about last session out of database
sta = engInitSyncAnchors(
relativeURI(fLocalDBPath.c_str()),
fRemoteDBPath.c_str()
);
if (sta!=LOCERR_OK) {
// error getting anchors
PDEBUGPRINTFX(DBG_ERROR,("Could not get Sync Anchor info"));
return localError(sta);
}
// check if we are forced to slowsync (otherwise, fSlowSync is pre-set from dsSetClientSyncParams()
fSlowSync = fSlowSync || fLastLocalAnchor.empty() || fFirstTimeSync;
// check for resume
if (fResumeAlertCode!=0 && fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
// we have a suspended session, try to resume
PDEBUGPRINTFX(DBG_PROTO,("Found suspended session with Alert Code = %hd",fResumeAlertCode));
fResuming = true;
}
return LOCERR_OK; // ok
} // TLocalEngineDS::engPrepareClientDSForAlert
// generate Sync alert for datastore after initialisation with engPrepareClientSyncAlert()
// Note: this could be repeatedly called due to auth failures at beginning of session
// Note: this is a NOP for subDatastores (should not be called in this case, anyway)
localstatus TLocalEngineDS::engGenerateClientSyncAlert(
TAlertCommand *&aAlertCommandP
)
{
aAlertCommandP=NULL;
#ifdef SUPERDATASTORES
if (fAsSubDatastoreOf) return LOCERR_OK; // NOP, ok, only superdatastore creates an alert!
#endif
PDEBUGPRINTFX(DBG_PROTO,(
"(Saved) Last Local Client Anchor='%s', (generated) Next Local Client Anchor='%s' (sent to server as <last>/<next> in <alert>)",
fLastLocalAnchor.c_str(),
fNextLocalAnchor.c_str()
));
// create appropriate initial alert command
uInt16 alertCode = getSyncStateAlertCode(fServerAlerted,true);
// check for resume
if (fResuming) {
// check if what we resume is same as what we wanted to do
if (alertCode != fResumeAlertCode) {
// this is ok for client, just show in log
PDEBUGPRINTFX(DBG_PROTO,(
"Sync mode seems to have changed (alert code = %hd) since last Suspend (alert code = %hd)",
alertCode,
fResumeAlertCode
));
}
// resume
alertCode=225; // resume
PDEBUGPRINTFX(DBG_PROTO,(
"Alerting resume of last sync session (original alert code = %hd)",
fResumeAlertCode
));
}
aAlertCommandP = new TAlertCommand(fSessionP,this,alertCode);
PDEBUGPRINTFX(DBG_HOT,(
"%s: ALERTING server for %s%s%s Sync",
getName(),
fResuming ? "RESUMED " : "",
fSlowSync ? "slow" : "normal",
fFirstTimeSync ? " first time" : ""
));
// add Item with Anchors and URIs
SmlItemPtr_t itemP = newItem();
// - anchors
itemP->meta=newMetaAnchor(fNextLocalAnchor.c_str(),fLastLocalAnchor.c_str());
// - MaxObjSize here again to make SCTS happy
if (
(fSessionP->getSyncMLVersion()>=syncml_vers_1_1) &&
(fSessionP->getRootConfig()->fLocalMaxObjSize>0)
) {
// SyncML 1.1 has object size and we need to put it here for SCTS
smlPCDataToMetInfP(itemP->meta)->maxobjsize=newPCDataLong(
fSessionP->getRootConfig()->fLocalMaxObjSize
);
}
// - URIs
itemP->source=newLocation(fLocalDBPath.c_str()); // local DB ID
itemP->target=newLocation(fRemoteDBPath.c_str()); // use remote path as configured in client settings
// - add DS 1.2 filters
if (!fRemoteRecordFilterQuery.empty() || false /* %%% field level filter */) {
if (fSessionP->getSyncMLVersion()<syncml_vers_1_2) {
PDEBUGPRINTFX(DBG_ERROR,("Filter specified, but SyncML version is < 1.2"));
return 406; // feature not supported
}
SmlFilterPtr_t filterP = SML_NEW(SmlFilter_t);
memset(filterP,0,sizeof(SmlFilter_t));
if (filterP) {
// Must have a meta with the content type
// - get the preferred receive type
TSyncItemType *itemTypeP = fSessionP->findLocalType(fDSConfigP->fTypeSupport.fPreferredRx);
if (itemTypeP) {
// add meta type
filterP->meta = newMetaType(itemTypeP->getTypeName());
}
// add filtertype if needed (=not EXCLUSIVE)
if (fRemoteFilterInclusive) {
filterP->filtertype=newPCDataString(SYNCML_FILTERTYPE_INCLUSIVE);
}
// record level
if (!fRemoteRecordFilterQuery.empty()) {
// add <record>
filterP->record = SML_NEW(SmlRecordOrFieldFilter_t);
// - add item with data=filterquery
filterP->record->item = newStringDataItem(fRemoteRecordFilterQuery.c_str());
// - add meta type with grammar
filterP->record->item->meta = newMetaType(SYNCML_FILTERTYPE_CGI);
PDEBUGPRINTFX(DBG_HOT,(
"Alerting with %sCLUSIVE Record Level Filter Query = '%s'",
fRemoteFilterInclusive ? "IN" : "EX",
fRemoteRecordFilterQuery.c_str()
));
}
// field level
/// @todo %%% to be implemented
if (false) {
// !!! remember to add real check (now: false) in outer if-statement as well!!!!!
// %%% tbd
}
}
// add it to item
itemP->target->filter = filterP;
}
// - add to alert command
aAlertCommandP->addItem(itemP);
// we have now produced the client alert command, change state
return changeState(dssta_clientsentalert);
} // TLocalEngineDS::engGenerateClientSyncAlert
// Init engine for client sync
// - determine types to exchange
// - make sync set ready
localstatus TLocalEngineDS::engInitForClientSync(void)
{
#ifdef SUPERDATASTORES
// no init in case we are under control of a superdatastore -> the superdatastore will do that
if (fAsSubDatastoreOf)
return LOCERR_OK;
#endif
return engInitDSForClientSync();
} // TLocalEngineDS::engInitForClientSync
// Init engine for client sync
// - determine types to exchange
// - make sync set ready
localstatus TLocalEngineDS::engInitDSForClientSync(void)
{
// make ready for syncops
localstatus sta = engInitForSyncOps(getRemoteDBPath());
if (sta==LOCERR_OK) {
// - let local datastore (derived DB-specific class) prepare for sync
sta = changeState(dssta_dataaccessstarted);
if (sta==LOCERR_OK && isStarted(false)) {
// already started now, change state
sta = changeState(dssta_syncsetready);
}
}
return sta;
} // TLocalEngineDS::engInitDSForClientSync
#endif // Client
// get Alert code for current Sync State
uInt16 TLocalEngineDS::getSyncStateAlertCode(bool aServerAlerted, bool aClientMinimal)
{
uInt16 alertcode=0;
switch (fSyncMode) {
case smo_twoway :
alertcode = aServerAlerted ? 206 : 200;
break;
case smo_fromclient :
alertcode = aServerAlerted ? 207 : 202; // fully specified
break;
case smo_fromserver :
if (aClientMinimal) {
// refresh from server is just client not sending any data, so we can alert like two-way
alertcode = aServerAlerted ? 206 : 200;
}
else {
// correctly alert it
alertcode = aServerAlerted ? 209 : 204;
}
break;
case numSyncModes:
// invalid
break;
}
// slowsync/refresh variants are always plus one, except 206 --> 201 (same as client initiated slow sync)
if (fSlowSync) alertcode = (alertcode!=206 ? alertcode+1 : 201);
return alertcode;
} // TLocalEngineDS::getSyncStateAlertCode
/// initializes Sync state variables and returns false if alert is not supported
localstatus TLocalEngineDS::setSyncModeFromAlertCode(uInt16 aAlertCode, bool aAsClient)
{
localstatus sta;
TSyncModes syncMode;
bool slowSync, serverAlerted;
// - translate into mode and flags
sta=getSyncModeFromAlertCode(aAlertCode,syncMode,slowSync,serverAlerted);
if (sta==LOCERR_OK) {
// - set them
sta=setSyncMode(aAsClient,syncMode,slowSync,serverAlerted);
}
return sta;
} // TLocalEngineDS::setSyncModeFromAlertCode
/// initializes Sync mode variables
localstatus TLocalEngineDS::setSyncMode(bool aAsClient, TSyncModes aSyncMode, bool aIsSlowSync, bool aIsServerAlerted)
{
// get sync caps of this datastore
uInt32 synccapmask=getSyncCapMask();
// check if mode supported
if (aIsServerAlerted) {
// check if we support server alerted modes, SyncCap/Bit=7
if (~synccapmask & (1<<7)) return 406; // not supported
}
switch(aSyncMode) {
case smo_twoway:
// Two-way Sync, SyncCap/Bit=1
// or Two-way slow Sync, SyncCap/Bit=2
if (~synccapmask & (1<< (aIsSlowSync ? 2 : 1))) return 406; // not supported
if (fSyncMode==smo_fromserver && aAsClient)
aSyncMode=smo_fromserver; // for client, if already fromserver mode set, keep it
break;
case smo_fromclient:
// One-way from client, SyncCap/Bit=3
// or Refresh (=slow one-way) from client, SyncCap/Bit=4
if (~synccapmask & (1<< (aIsSlowSync ? 4 : 3))) return 406; // not supported
if (!aAsClient) fRefreshOnly=true; // as server, we are in refresh-only-mode if we get one-way from client
break;
case smo_fromserver:
// One-way from server, SyncCap/Bit=5
// or Refresh (=slow one-way) from server, SyncCap/Bit=6
if (~synccapmask & (1<< (aIsSlowSync ? 6 : 5))) return 406; // not supported
if (aAsClient) fRefreshOnly=true; // as client, we are in refresh-only-mode if we get one-way fromm server
break;
default:
return 400; // bad request
}
// now set mode and flags (possibly adjusted above)
fSyncMode=aSyncMode;
fSlowSync=aIsSlowSync;
fServerAlerted=aIsServerAlerted;
// ok
return LOCERR_OK;
} // TLocalEngineDS::setSyncMode
/// get Sync mode variables from given alert code
localstatus TLocalEngineDS::getSyncModeFromAlertCode(uInt16 aAlertCode, TSyncModes &aSyncMode, bool &aIsSlowSync, bool &aIsServerAlerted)
{
// these might be pre-defined)
/// @deprecated state change does not belong here
aIsSlowSync=false;
aIsServerAlerted=false;
aSyncMode=smo_twoway; // to make sure it is valid
// first test if server-alerted
if (aAlertCode>=206 && aAlertCode<210) {
// Server alerted modes
aIsServerAlerted=true;
}
// test for compatibility with alert code
switch(aAlertCode) {
case 200:
case 206:
// Two-way Sync
aSyncMode=smo_twoway;
aIsSlowSync=false;
break;
case 201:
// Two-way slow Sync
aSyncMode=smo_twoway;
aIsSlowSync=true;
break;
case 202:
case 207:
// One-way from client
aSyncMode=smo_fromclient;
aIsSlowSync=false;
break;
case 203:
case 208:
// refresh (=slow one-way) from client
aSyncMode=smo_fromclient;
aIsSlowSync=true;
break;
case 204:
case 209:
// One-way from server
aSyncMode=smo_fromserver;
aIsSlowSync=false;
break;
case 205:
case 210:
// refresh (=slow one-way) from server
aSyncMode=smo_fromserver;
aIsSlowSync=true;
break;
default:
// bad alert
return 400;
}
return LOCERR_OK;
} // TLocalEngineDS::getSyncModeFromAlertCode
// create new Sync capabilities info from capabilities mask
// Bit0=reserved, Bit1..Bitn = SyncType 1..n available
// Note: derived classes might add special sync codes and/or mask standard ones
SmlDevInfSyncCapPtr_t TLocalEngineDS::newDevInfSyncCap(uInt32 aSyncCapMask)
{
SmlDevInfSyncCapPtr_t synccapP;
SmlPcdataPtr_t synctypeP;
// new synccap structure
synccapP = SML_NEW(SmlDevInfSyncCap_t);
// synccap list is empty
synccapP->synctype=NULL;
// now add standard synccaps
for (sInt16 k=0; k<32; k++) {
if (aSyncCapMask & (1<<k)) {
// capability available
synctypeP=newPCDataLong(k);
addPCDataToList(synctypeP,&(synccapP->synctype));
}
}
// return it
return synccapP;
} // TLocalEngineDS::newDevInfSyncCap
// obtain new datastore info, returns NULL if none available
SmlDevInfDatastorePtr_t TLocalEngineDS::newDevInfDatastore(bool aAsServer, bool aWithoutCTCapProps)
{
SmlDevInfDatastorePtr_t datastoreP;
// set only basic info, details must be added in derived class
// - sourceref is the name of the datastore,
// or for server, if already alerted, the name used in the alert
// (this is to allow /dsname/foldername with clients that expect the
// devInf to contain exactly the same full path as name, like newer Nokias)
string dotname;
#ifdef SYSYNC_SERVER
if (IS_SERVER && testState(dssta_serveralerted,false) && fSessionP->fDSPathInDevInf) {
// server and already alerted
// - don't include sub-datastores
if (fAsSubDatastoreOf) {
return NULL;
}
// - use datastore spec as sent from remote, minus CGI, as relative spec
dotname = URI_RELPREFIX;
dotname += fSessionP->SessionRelativeURI(fRemoteViewOfLocalURI.c_str());
if (!fSessionP->fDSCgiInDevInf) {
// remove CGI
string::size_type n=dotname.find("?");
if (n!=string::npos)
dotname.resize(n); // remove CGI
}
}
else
#endif
{
// client or not yet alerted - just use datastore base name
StringObjPrintf(dotname,URI_RELPREFIX "%s",fName.c_str());
}
// create new
datastoreP=SML_NEW(SmlDevInfDatastore_t);
datastoreP->sourceref=newPCDataString(dotname);
#ifndef MINIMAL_CODE
// - Optional display name
datastoreP->displayname=newPCDataOptString(getDisplayName());
#else
datastoreP->displayname=NULL;
#endif
// - MaxGUIDsize (for client only)
if (aAsServer)
datastoreP->maxguidsize=NULL;
else
datastoreP->maxguidsize=newPCDataLong(fMaxGUIDSize);
// - check for legacy mode type (that is to be used as "preferred" instead of normal preferred)
TSyncItemType *legacyTypeP = NULL;
if (getSession()->fLegacyMode && getDSConfig()->fTypeSupport.fPreferredLegacy) {
// get the type marked as blind
legacyTypeP = getSession()->findLocalType(getDSConfig()->fTypeSupport.fPreferredLegacy);
}
// - RxPref
if (!fRxPrefItemTypeP) SYSYNC_THROW(TStructException("Datastore has no RxPref ItemType"));
datastoreP->rxpref = (legacyTypeP ? legacyTypeP : fRxPrefItemTypeP)->newXMitDevInf();
// - Rx (excluding the type we report as preferred)
datastoreP->rx=TSyncItemType::newXMitListDevInf(fRxItemTypes,legacyTypeP ? legacyTypeP : fRxPrefItemTypeP);
// - TxPref
if (!fTxPrefItemTypeP) SYSYNC_THROW(TStructException("Datastore has no TxPref ItemType"));
datastoreP->txpref = (legacyTypeP ? legacyTypeP : fTxPrefItemTypeP)->newXMitDevInf();
// - Tx (excluding the type we report as preferred)
datastoreP->tx=TSyncItemType::newXMitListDevInf(fTxItemTypes,legacyTypeP ? legacyTypeP : fTxPrefItemTypeP);
// - DSMem
/// @todo %%% tbd: add dsmem
datastoreP->dsmem=NULL;
// - SyncML DS 1.2 datastore-local CTCap
if (fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
// CTCap is local to datastore, get only CTCaps relevant for this datastore, but independently from alerted state
datastoreP->ctcap = fSessionP->newLocalCTCapList(false, this, aWithoutCTCapProps);
}
else
datastoreP->ctcap=NULL; // before SyncML 1.2, there was no datastore-local CTCap
// - SyncML DS 1.2 flags (SmlDevInfHierarchical_f)
/// @todo %%% tbd: add SmlDevInfHierarchical_f
datastoreP->flags=0;
// - SyncML DS 1.2 filters
datastoreP->filterrx=NULL;
datastoreP->filtercap=NULL;
#ifdef OBJECT_FILTERING
if (IS_SERVER && fDSConfigP->fDS12FilterSupport && fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
// Show Filter info in 1.2 devInf if this is not a client
// - FilterRx constant
datastoreP->filterrx = SML_NEW(SmlDevInfXmitList_t);
datastoreP->filterrx->next = NULL;
datastoreP->filterrx->data = SML_NEW(SmlDevInfXmit_t);
datastoreP->filterrx->data->cttype=newPCDataString(SYNCML_FILTERTYPE_CGI);
datastoreP->filterrx->data->verct=newPCDataString(SYNCML_FILTERTYPE_CGI_VERS);
// build filtercap
SmlPcdataListPtr_t filterkeywords = NULL;
SmlPcdataListPtr_t filterprops = NULL;
// - fill the lists from types
addFilterCapPropsAndKeywords(filterkeywords,filterprops);
// - if we have something, actually build a filtercap
if (filterkeywords || filterprops) {
// we have filtercaps, add them
// - FilterCap list
datastoreP->filtercap = SML_NEW(SmlDevInfFilterCapList_t);
datastoreP->filtercap->next = NULL;
datastoreP->filtercap->data = SML_NEW(SmlDevInfFilterCap_t);
datastoreP->filtercap->data->cttype=newPCDataString(SYNCML_FILTERTYPE_CGI);
datastoreP->filtercap->data->verct=newPCDataString(SYNCML_FILTERTYPE_CGI_VERS);
// - add list we've got
datastoreP->filtercap->data->filterkeyword=filterkeywords;
datastoreP->filtercap->data->propname=filterprops;
}
}
#endif // OBJECT_FILTERING
// - Sync capabilities of this datastore
datastoreP->synccap=newDevInfSyncCap(getSyncCapMask());
// return it
return datastoreP;
} // TLocalEngineDS::newDevInfDatastore
// Set remote datastore for local
void TLocalEngineDS::engSetRemoteDatastore(
TRemoteDataStore *aRemoteDatastoreP // the remote datastore involved
)
{
// save link to remote datastore
if (fRemoteDatastoreP) {
if (fRemoteDatastoreP!=aRemoteDatastoreP)
SYSYNC_THROW(TSyncException("Sync continues with different datastore"));
}
fRemoteDatastoreP=aRemoteDatastoreP;
} // TLocalEngineDS::engSetRemoteDatastore
// SYNC command bracket start (check credentials if needed)
bool TLocalEngineDS::engProcessSyncCmd(
SmlSyncPtr_t aSyncP, // the Sync element
TStatusCommand &aStatusCommand, // status that might be modified
bool &aQueueForLater // will be set if command must be queued for later (re-)execution
)
{
// get number of changes info if available
if (aSyncP->noc) {
StrToLong(smlPCDataToCharP(aSyncP->noc),fRemoteNumberOfChanges);
}
// check if datastore is aborted
if (CheckAborted(aStatusCommand)) return false;
// check
if (!fRemoteDatastoreP)
SYSYNC_THROW(TSyncException("No remote datastore linked"));
// let remote datastore process it first
if (!fRemoteDatastoreP->remoteProcessSyncCmd(aSyncP,aStatusCommand,aQueueForLater)) {
PDEBUGPRINTFX(DBG_ERROR,("TLocalEngineDS::engProcessSyncCmd: remote datastore failed processing <sync>"));
changeState(dssta_idle,true); // force it
return false;
}
// check for combined init&sync
if (!testState(dssta_syncmodestable,false)) {
// <sync> encountered before sync mode stable: could be combined init&sync session
if (fLocalDSState>=dssta_serveransweredalert) {
// ok for switching to combined init&sync
PDEBUGPRINTFX(DBG_HOT,("TLocalEngineDS::engProcessSyncCmd: detected combined init&sync, freeze sync mode already now"));
// - freeze sync mode as it is now
changeState(dssta_syncmodestable,true); // force it, sync mode is now stable, no further changes are possible
}
}
// now init if this is the first <sync> command
bool startingNow = false; // assume start already initiated
if (testState(dssta_syncmodestable,true)) {
// all alert and alert status must be done by now, sync mode must be stable
CONSOLEPRINTF(("- Starting Sync with Datastore '%s', %s sync",fRemoteViewOfLocalURI.c_str(),fSlowSync ? "slow" : "normal"));
startingNow = true; // initiating start now
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// at this point, all temporary GUIDs become invalid (no "early map" possible any more which might refer to last session's tempGUIDs)
fTempGUIDMap.clear(); // forget all previous session's temp GUID mappings
// let local datastore (derived DB-specific class) prepare for sync
localstatus sta = changeState(dssta_dataaccessstarted);
if (sta!=LOCERR_OK) {
// abort session (old comment: %%% aborting datastore only does not work, will loop, why? %%%)
aStatusCommand.setStatusCode(syncmlError(sta));
PDEBUGPRINTFX(DBG_ERROR,("TLocalEngineDS::engProcessSyncCmd: could not change state to dsssta_dataaccessstarted -> abort"));
engAbortDataStoreSync(sta,true); // local problem
return false;
}
}
#endif
}
// if data access started (finished or not), check start status
// for every execution and re-execution of the sync command
if (testState(dssta_dataaccessstarted)) {
// queue <sync> command if datastore is not yet started already
if (engIsStarted(!startingNow)) { // wait only if start was already initiated
// - is now initialized
if (IS_SERVER) {
// - for server, make the sync set ready now (as engine is now started)
changeState(dssta_syncsetready,true); // force it
}
else {
// - for client, we need at least dssta_syncgendone (sync set has been ready long ago, we've already sent changes to server!)
if (!testState(dssta_syncgendone)) {
// bad sequence of commands (<sync> from server too early!)
aStatusCommand.setStatusCode(400);
PDEBUGPRINTFX(DBG_ERROR,("TLocalEngineDS::engProcessSyncCmd: client received SYNC before sending SYNC complete"));
engAbortDataStoreSync(400,false,false); // remote problem, not resumable
return false;
}
}
PDEBUGPRINTFX(DBG_HOT,(
"- Started %s Sync (first <sync> command)",
fSlowSync ? "slow" : "normal"
));
if (fRemoteNumberOfChanges>=0) PDEBUGPRINTFX(DBG_HOT,("- NumberOfChanges announced by remote = %ld",(long)fRemoteNumberOfChanges));
DB_PROGRESS_EVENT(this,pev_syncstart,0,0,0);
}
else {
// - not yet started
PDEBUGPRINTFX(DBG_HOT,(
"- Starting sync not yet complete - re-execute <sync> command again in next message"
));
aQueueForLater=true;
return true; // ok so far
}
}
// must be syncready here (otherwise we return before we reach this)
if (!testState(dssta_syncsetready)) {
aStatusCommand.setStatusCode(403); // forbidden
ADDDEBUGITEM(aStatusCommand,"SYNC received too early");
PDEBUGPRINTFX(DBG_ERROR,("TLocalEngineDS::engProcessSyncCmd: SYNC received too early"));
engAbortDataStoreSync(403,false,false); // remote problem, not resumable
return false;
}
// state is now syncing
/// @deprecated - dssta_syncsetready is enough
//fState=dss_syncing;
return true;
} // TLocalEngineDS::engProcessSyncCmd
// SYNC command bracket end (but another might follow in next message)
bool TLocalEngineDS::engProcessSyncCmdEnd(bool &aQueueForLater)
{
bool ok=true;
// queue it for later as long as datastore is not ready now
if (!engIsStarted(false)) { // not waiting if not started
// no state change, just postpone execution
aQueueForLater=true;
}
// also inform remote
if (fRemoteDatastoreP) ok=fRemoteDatastoreP->remoteProcessSyncCmdEnd();
return ok;
} // TLocalEngineDS::engProcessSyncCmdEnd
#ifdef SYSYNC_SERVER
// server case: called whenever outgoing Message of Sync Package starts
void TLocalEngineDS::engServerStartOfSyncMessage(void)
{
// this is where we might start our own <Sync> command (all
// received commands are now processed)
// - Note that this might be a subdatastore -> if so, do NOT
// start a sync (superdatastore will handle this)
// - Note that this will be called even if current message is
// already full, so it could well be that this sync command
// is queued.
if (!fSessionP->fCompleteFromClientOnly && testState(dssta_serverseenclientmods) && getSyncMode()==smo_fromclient) {
// from-client only does not send back a <sync> command, simply end data access here
PDEBUGPRINTFX(DBG_PROTO,("from-client-only:do not send <sync> command back to client, data access ends here"));
changeState(dssta_syncgendone,true);
changeState(dssta_dataaccessdone,true);
}
// ### SyncFest #5, found with Tactel Jazz Client:
// - do not send anything when remote datastore is not known
else if (fRemoteDatastoreP) {
if (!testState(dssta_serversyncgenstarted) && testState(dssta_serverseenclientmods)) {
changeState(dssta_serversyncgenstarted,true);
if (!isSubDatastore()) {
// - Note: if sync command was already started, the
// finished(), continueIssue() mechanism will make sure that
// more commands are generated
// - Note2: if all sync commands can be sent at once,
// fState will be modified by issuing <sync>, so
// it must be ok for issuing syncops here already!
TSyncCommand *synccmdP =
new TSyncCommand(
fSessionP,
this, // local datastore
fRemoteDatastoreP // remote datastore
);
// issue
ISSUE_COMMAND_ROOT(fSessionP,synccmdP);
}
}
}
else {
changeState(dssta_idle,true); // force it
}
} // TLocalEngineDS::engServerStartOfSyncMessage
#endif // server only
// called whenever Message of Sync Package ends or after last queued Sync command is executed
// - aEndOfAllSyncCommands is true when at end of Sync-data-from-remote packet
// AND all possibly queued sync/syncop commands have been processed.
void TLocalEngineDS::engEndOfSyncFromRemote(bool aEndOfAllSyncCommands)
{
// is called for all local datastores, including superdatastore, even inactive ones, so check state first
if (testState(dssta_syncsetready)) {
if (aEndOfAllSyncCommands) {
// we are at end of sync-data-from-remote for THIS datastore
if (IS_CLIENT) {
// - we are done with <Sync> from server, that is, data access is done now
changeState(dssta_dataaccessdone,true); // force it
}
else {
// - server has seen all client modifications now
// Note: in case of the simulated-empty-sync-hack in action, we
// allow that we are already in server_sync_gen_started and
// won't try to force down to dssta_serverseenclientmods
if (!fSessionP->fFakeFinalFlag || getDSState()<dssta_serverseenclientmods) {
// under normal circumstances, wee need dssta_serverseenclientmods here
changeState(dssta_serverseenclientmods,true); // force it
}
else {
// hack exception
PDEBUGPRINTFX(DBG_ERROR,("Warning: simulated </final> active - allowing state>server_seen_client_mods"));
}
}
}
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
engServerStartOfSyncMessage();
}
#endif
// now do final things
if (testState(dssta_dataaccessdone,true)) {
// @todo: I think, as long as we need to send maps, we're not done yet!!!
// sync packets in both directions done, forget remote datastore
fRemoteDatastoreP=NULL;
}
} // dssta_syncsetready
} // TLocalEngineDS::engEndOfSyncFromRemote
// - must return true if this datastore is finished with <sync>
// (if all datastores return true,
// session is allowed to finish sync packet with outgoing message
bool TLocalEngineDS::isSyncDone(void)
{
// is called for all local datastores, even inactive ones, which must signal sync done, too
// - only datastores currently receiving or sending <sync> commands are not done with sync
// - aborted datastores are also done with sync, no matter what status they have
return (
fAbortStatusCode!=0 ||
//(fState!=dss_syncsend && fState!=dss_syncing && fState!=dss_syncready && fState!=dss_syncfinish)
!testState(dssta_clientsentalert) || // nothing really happened yet...
testState(dssta_syncgendone) // ...or already completed generating <sync>
);
} // TLocalEngineDS::isSyncDone
// test datastore state for minimal or exact state
bool TLocalEngineDS::testState(TLocalEngineDSState aMinState, bool aNeedExactMatch)
{
bool result =
(!aNeedExactMatch || (fLocalDSState==aMinState)) &&
(fLocalDSState>=aMinState);
DEBUGPRINTFX(DBG_EXOTIC,(
"%s: testState=%s - expected state%c='%s', found state=='%s'",
getName(),
result ? "TRUE" : "FALSE",
aNeedExactMatch ? '=' : '>',
getDSStateName(aMinState),
getDSStateName()
));
return result;
} // TLocalEngineDS::testState
// change datastore state, calls logic layer before and after change
localstatus TLocalEngineDS::changeState(TLocalEngineDSState aNewState, bool aForceOnError)
{
localstatus err1,err2;
TLocalEngineDSState oldState = fLocalDSState;
// nop if no change in state
if (aNewState==oldState) return LOCERR_OK;
// state cannot be decremented except down to adminready and below
if ((aNewState<oldState) && (aNewState>dssta_adminready)) {
PDEBUGPRINTFX(DBG_ERROR,(
"%s: Internal error: attempt to reduce state from '%s' to '%s' - aborting",
getName(),
getDSStateName(oldState),
getDSStateName(aNewState)
));
err1 = 500;
dsAbortDatastoreSync(err1,true);
return err1;
}
// give logic opportunity to react before state changes
PDEBUGBLOCKFMT((
"DSStateChange",
"Datastore changes state",
"datastore=%s|oldstate=%s|newstate=%s",
getName(),
getDSStateName(oldState),
getDSStateName(aNewState)
));
err2 = LOCERR_OK;
err1 = dsBeforeStateChange(oldState,aNewState);
if (!aForceOnError && err1) goto endchange;
// switch state
fLocalDSState = aNewState;
// now give logic opportunity to react again
err2 = dsAfterStateChange(oldState,aNewState);
endchange:
PDEBUGENDBLOCK("DSStateChange");
// return most recent error
return err2 ? err2 : err1;
} // TLocalEngineDS::changeState
// test datastore abort status
// datastore is aborted when
// - it was explicitly aborted (engAbortDataStoreSync() called, fAbortStatusCode set)
// - session is suspending and the datastore has not yet completed sync up to sending
// maps (client) or admin already saved (server+client).
// If client has sent maps, all that MIGHT be missing would be map status, and
// if that hasn't arrived, the pendingMaps mechanism will make sure these get
// sent in the next session.
bool TLocalEngineDS::isAborted(void)
{
return fAbortStatusCode!=0 || (fSessionP->isSuspending() && !testState(dssta_clientmapssent));
} // TLocalEngineDS::isAborted
// abort sync with this datastore
void TLocalEngineDS::engAbortDataStoreSync(TSyError aStatusCode, bool aLocalProblem, bool aResumable)
{
if (fLocalDSState!=dssta_idle && !fAbortStatusCode) {
// prepare status
fAbortStatusCode = aStatusCode ? aStatusCode : 514; // make sure we have a non-zero fAbortStatusCode
fLocalAbortCause = aLocalProblem;
if (!aResumable) preventResuming(); // prevent resuming
PDEBUGBLOCKFMT((
"DSAbort","Aborting datastore sync","abortStatusCode=%hd|localProblem=%s|resumable=%s",
aStatusCode,
aLocalProblem ? "yes" : "no",
aResumable ? "yes" : "no"
));
// tell that to the session
fSessionP->DatastoreFailed(aStatusCode,aLocalProblem);
// as soon as sync set is ready, we have potentially started the sync and resume makes sense
// NOTE: before we have made the sync set ready, WE MUST NOT resume, because making the sync
// set ready includes zapping it on slow refreshes, and this is only done when not resuming
// (so saving a suspend state before dssta_syncsetready would cause that the zapping is
// possibly skipped)
if (!testState(dssta_syncsetready)) preventResuming(); // prevent resuming before sync set is ready
// save resume (or non-resumable!) status only if this is NOT A TIMEOUT, because if it is a
// (server) timeout, suspend state was saved at end of last request, and writing again here would destroy
// the state.
if (aStatusCode!=408) {
engSaveSuspendState(true); // save even if already aborted
}
// let derivates know
dsAbortDatastoreSync(aStatusCode, aLocalProblem);
// show abort
PDEBUGPRINTFX(DBG_ERROR,(
"*************** Warning: Datastore flagged aborted (after %ld sec. request processing, %ld sec. total) with %s Status %hd",
(long)((getSession()->getSystemNowAs(TCTX_UTC)-fSessionP->getLastRequestStarted()) / secondToLinearTimeFactor),
(long)((getSession()->getSystemNowAs(TCTX_UTC)-fSessionP->getSessionStarted()) / secondToLinearTimeFactor),
aLocalProblem ? "LOCAL" : "REMOTE",
aStatusCode
));
DB_PROGRESS_EVENT(
this,
pev_syncend,
getAbortStatusCode(),
fSlowSync ? (fFirstTimeSync ? 2 : 1) : 0,
fResuming ? 1 : 0
);
PDEBUGENDBLOCK("DSAbort");
}
} // TLocalEngineDS::engAbortDataStoreSync
// check if aborted, set status to abort reason code if yes
bool TLocalEngineDS::CheckAborted(TStatusCommand &aStatusCommand)
{
if (fAbortStatusCode!=0) {
aStatusCommand.setStatusCode(
fSessionP->getSyncMLVersion()>=syncml_vers_1_1 ? 514 : // cancelled
(fAbortStatusCode<LOCAL_STATUS_CODE ? fAbortStatusCode : 512) // sync failed
);
PDEBUGPRINTFX(DBG_DATA,("This datastore is in aborted state, rejects all commands with %hd",aStatusCommand.getStatusCode()));
return true; // aborted, status set
}
return false; // not aborted
} // TLocalEngineDS::CheckAborted
// Do common logfile substitutions
void TLocalEngineDS::DoLogSubstitutions(string &aLog,bool aPlaintext)
{
#ifndef MINIMAL_CODE
string s;
if (aPlaintext) {
StringObjTimestamp(s,fEndOfSyncTime);
// %T Time of sync (in derived datastores, this is the point of reference for newer/older comparisons) as plain text
StringSubst(aLog,"%T",s,2);
// %seT Time of session end (with this datastore) as plain text
StringSubst(aLog,"%seT",s,4);
// %ssT Time of session start as plain text
StringObjTimestamp(s,fSessionP->getSessionStarted());
StringSubst(aLog,"%ssT",s,4);
}
// %sdT sync duration (in seconds) for this datastore (start of session until datastore finished)
StringSubst(aLog,"%sdT",((sInt32)(fEndOfSyncTime-fSessionP->getSessionStarted())/secondToLinearTimeFactor),4);
// %nD Datastore name
StringSubst(aLog,"%nD",getName(),3);
// %rD Datastore remote path
StringSubst(aLog,"%rD",fRemoteDBPath,3);
// %lD Datastore local path (complete with all CGI)
StringSubst(aLog,"%lD",fRemoteViewOfLocalURI,3);
// %iR Remote Device ID (URI)
StringSubst(aLog,"%iR",fSessionP->getRemoteURI(),3);
// %nR Remote name: [Manufacturer ]Model")
StringSubst(aLog,"%nR",fSessionP->getRemoteDescName(),3);
// %vR Remote Device Version Info ("Type (HWV, FWV, SWV) Oem")
StringSubst(aLog,"%vR",fSessionP->getRemoteInfoString(),3);
// %U User Name
StringSubst(aLog,"%U",fSessionP->getSyncUserName(),2);
// %iS local Session ID
StringSubst(aLog,"%iS",fSessionP->getLocalSessionID(),3);
// %sS Status code (0 if successful)
StringSubst(aLog,"%sS",fAbortStatusCode,3);
// %ssS Session Status code (0 if successful)
StringSubst(aLog,"%ssS",fSessionP->getAbortReasonStatus(),4);
// %syV SyncML version (as text) of session
StringSubst(aLog,"%syV",SyncMLVerDTDNames[fSessionP->getSyncMLVersion()],4);
// %syV SyncML version numeric (0=unknown, 1=1.0, 2=1.1, 3=1.2) of session
StringSubst(aLog,"%syVn",(long)fSessionP->getSyncMLVersion(),5);
// %mS Syncmode (0=twoway, 1=fromclient 2=fromserver)
StringSubst(aLog,"%mS",(sInt32)fSyncMode,3);
// %tS Synctype (0=normal,1=slow,2=firsttime slow, +10 if resumed session)
StringSubst(aLog,"%tS",(fSlowSync ? (fFirstTimeSync ? 2 : 1) : 0) + (isResuming() ? 10 : 0),3);
// %laI locally added Items
StringSubst(aLog,"%laI",fLocalItemsAdded,4);
// %raI remotely added Items
StringSubst(aLog,"%raI",fRemoteItemsAdded,4);
// %ldI locally deleted Items
StringSubst(aLog,"%ldI",fLocalItemsDeleted,4);
// %rdI remotely deleted Items
StringSubst(aLog,"%rdI",fRemoteItemsDeleted,4);
// %luI locally updated Items
StringSubst(aLog,"%luI",fLocalItemsUpdated,4);
// %ruI remotely updated Items
StringSubst(aLog,"%ruI",fRemoteItemsUpdated,4);
// %reI locally not accepted Items (sent error to remote, remote MAY resend them or abort the session)
StringSubst(aLog,"%leI",fLocalItemsError,4);
// %leI remotely not accepted Items (got error from remote, local will resend them later)
StringSubst(aLog,"%reI",fRemoteItemsError,4);
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
// %smI Slowsync matched Items
StringSubst(aLog,"%smI",fSlowSyncMatches,4);
// %scI Server won Conflicts
StringSubst(aLog,"%scI",fConflictsServerWins,4);
// %ccI Client won Conflicts
StringSubst(aLog,"%ccI",fConflictsClientWins,4);
// %dcI Conflicts with duplications
StringSubst(aLog,"%dcI",fConflictsDuplicated,4);
// %tiB total incoming bytes
StringSubst(aLog,"%tiB",fSessionP->getIncomingBytes(),4);
// %toB total outgoing bytes
StringSubst(aLog,"%toB",fSessionP->getOutgoingBytes(),4);
}
#endif
// %niB net incoming data bytes for this datastore
StringSubst(aLog,"%diB",fIncomingDataBytes,4);
// %noB net incoming data bytes for this datastore
StringSubst(aLog,"%doB",fOutgoingDataBytes,4);
#endif
} // TLocalEngineDS::DoLogSubstitutions
// log datastore sync result
// - Called at end of sync with this datastore
void TLocalEngineDS::dsLogSyncResult(void)
{
#ifndef MINIMAL_CODE
if (fSessionP->logEnabled()) {
string logtext;
logtext=fSessionP->getSessionConfig()->fLogFileFormat;
if (!logtext.empty()) {
// substitute
DoLogSubstitutions(logtext,true); // plaintext
// show
fSessionP->WriteLogLine(logtext.c_str());
}
}
#endif
} // TLocalEngineDS::dsLogSyncResult
// Terminate all activity with this datastore
// Note: may be called repeatedly, must only execute relevant shutdown code once
void TLocalEngineDS::engTerminateDatastore(localstatus aAbortStatusCode)
{
// now abort (if not already aborted), then finish activities
engFinishDataStoreSync(aAbortStatusCode);
// and finally reset completely
engResetDataStore();
} // TLocalEngineDS::TerminateDatastore
// called at very end of sync session, when everything is done
// Note: is also called before deleting a datastore (so aborted sessions
// can do cleanup and/or statistics display as well)
void TLocalEngineDS::engFinishDataStoreSync(localstatus aErrorStatus)
{
// set end of sync time
fEndOfSyncTime = getSession()->getSystemNowAs(TCTX_UTC);
// check if we have something to do at all
if (fLocalDSState!=dssta_idle && fLocalDSState!=dssta_completed) {
if (aErrorStatus==LOCERR_OK) {
// Check if we need to abort now due to failed items only
if (fRemoteItemsError>0) {
// remote reported errors
if (fSlowSync && fRemoteItemsAdded==0 && fRemoteItemsDeleted==0 && fRemoteItemsUpdated==0 && fSessionP->getSessionConfig()->fAbortOnAllItemsFailed) {
PDEBUGPRINTFX(DBG_ERROR+DBG_DETAILS,("All remote item operations failed -> abort sync"));
engAbortDataStoreSync(512,false,false); // remote problems (only failed items in a slow sync) caused sync to fail, not resumable
}
else
fSessionP->DatastoreHadErrors(); // at least SOME items were successful, so it's not a completely unsuccessful sync
}
}
// abort, if requested from caller or only-failed-items
if (aErrorStatus!=LOCERR_OK)
engAbortDataStoreSync(aErrorStatus,true); // if we have an error here, this is considered a local problem
else {
DB_PROGRESS_EVENT(
this,
pev_syncend,
fAbortStatusCode,
fSlowSync ? (fFirstTimeSync ? 2 : 1) : 0,
fResuming ? 1 : 0
);
}
#ifdef SUPERDATASTORES
// if this is part of a superdatastore, include its statistics into mine, as
// superdatastore can not save any statistics.
// This ensures that the result sum over all subdatastores is correct,
// however the assignment of error and byte counts is not (all non-related
// counts go to first subdatastores with the following code)
if (fAsSubDatastoreOf) {
fOutgoingDataBytes += fAsSubDatastoreOf->fOutgoingDataBytes;
fIncomingDataBytes += fAsSubDatastoreOf->fIncomingDataBytes;
fRemoteItemsError += fAsSubDatastoreOf->fRemoteItemsError;
fLocalItemsError += fAsSubDatastoreOf->fLocalItemsError;
// consumed now, clear in superdatastore
fAsSubDatastoreOf->fOutgoingDataBytes=0;
fAsSubDatastoreOf->fIncomingDataBytes=0;
fAsSubDatastoreOf->fRemoteItemsError=0;
fAsSubDatastoreOf->fLocalItemsError=0;
}
#endif
// make log entry
dsLogSyncResult();
// update my session state vars for successful sessions
if (aErrorStatus==LOCERR_OK) {
// update anchor
fLastRemoteAnchor=fNextRemoteAnchor;
fLastLocalAnchor=fNextLocalAnchor; // note: when using TStdLogicDS, this is not saved, but re-generated at next sync from timestamp
// no resume
fResumeAlertCode=0;
// no resume item (just to make sure we don't get strange effects later)
fLastItemStatus = 0;
fLastSourceURI.erase();
fLastTargetURI.erase();
fPartialItemState = pi_state_none;
fPIStoredSize = 0;
}
// now shift state to complete, let logic and implementation save the state
changeState(dssta_completed,true);
#ifdef SCRIPT_SUPPORT
// - call DB finish script
TScriptContext::execute(
fDataStoreScriptContextP,
fDSConfigP->fDBFinishScript,
&DBFuncTable, // context's function table
this // datastore pointer needed for context
);
#endif
}
// in any case: idle now again (note: could be shift from dssta_completed to dssta_idle)
changeState(dssta_idle,true);
} // TLocalEngineDS::engFinishDataStoreSync
/// inform everyone of coming state change
localstatus TLocalEngineDS::dsBeforeStateChange(TLocalEngineDSState aOldState,TLocalEngineDSState aNewState)
{
localstatus sta = LOCERR_OK;
return sta;
} // TLocalEngineDS::dsBeforeStateChange
/// inform everyone of happened state change
localstatus TLocalEngineDS::dsAfterStateChange(TLocalEngineDSState aOldState,TLocalEngineDSState aNewState)
{
localstatus sta = LOCERR_OK;
if (aOldState>dssta_idle && aNewState==dssta_completed) {
// we are going from a non-idle state to completed
// - show statistics
showStatistics();
}
return sta;
} // TLocalEngineDS::dsAfterStateChange
// show statistics or error of current sync
void TLocalEngineDS::showStatistics(void)
{
// Console
CONSOLEPRINTF((""));
CONSOLEPRINTF(("- Sync Statistics for '%s' (%s), %s sync",
getName(),
fRemoteViewOfLocalURI.c_str(),
fSlowSync ? "slow" : "normal"
));
// now show results
if (isAborted()) {
// failed
CONSOLEPRINTF((" ************ Failed with status code=%hd",fAbortStatusCode));
}
else {
// successful: show statistics on console
CONSOLEPRINTF((" =================================================="));
if (IS_SERVER) {
CONSOLEPRINTF((" on Server on Client"));
}
else {
CONSOLEPRINTF((" on Client on Server"));
}
CONSOLEPRINTF((" Added: %9ld %9ld",fLocalItemsAdded,fRemoteItemsAdded));
CONSOLEPRINTF((" Deleted: %9ld %9ld",fLocalItemsDeleted,fRemoteItemsDeleted));
CONSOLEPRINTF((" Updated: %9ld %9ld",fLocalItemsUpdated,fRemoteItemsUpdated));
CONSOLEPRINTF((" Rejected with error: %9ld %9ld",fLocalItemsError,fRemoteItemsError));
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
CONSOLEPRINTF((" SlowSync Matches: %9ld",fSlowSyncMatches));
CONSOLEPRINTF((" Server won Conflicts: %9ld",fConflictsServerWins));
CONSOLEPRINTF((" Client won Conflicts: %9ld",fConflictsClientWins));
CONSOLEPRINTF((" Conflicts with Duplication: %9ld",fConflictsDuplicated));
}
#endif
}
CONSOLEPRINTF((""));
// Always provide statistics as events
DB_PROGRESS_EVENT(this,pev_dsstats_l,fLocalItemsAdded,fLocalItemsUpdated,fLocalItemsDeleted);
DB_PROGRESS_EVENT(this,pev_dsstats_r,fRemoteItemsAdded,fRemoteItemsUpdated,fRemoteItemsDeleted);
DB_PROGRESS_EVENT(this,pev_dsstats_e,fLocalItemsError,fRemoteItemsError,0);
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
DB_PROGRESS_EVENT(this,pev_dsstats_s,fSlowSyncMatches,0,0);
DB_PROGRESS_EVENT(this,pev_dsstats_c,fConflictsServerWins,fConflictsClientWins,fConflictsDuplicated);
}
#endif
// NOTE: pev_dsstats_d should remain the last log data event sent (as it terminates collecting data in some GUIs)
DB_PROGRESS_EVENT(this,pev_dsstats_d,fOutgoingDataBytes,fIncomingDataBytes,fRemoteItemsError);
// Always show statistics in debug log
#ifdef SYDEBUG
PDEBUGPRINTFX(DBG_HOT,("Sync Statistics for '%s' (%s), %s sync",
getName(),
fRemoteViewOfLocalURI.c_str(),
fSlowSync ? "slow" : "normal"
));
if (PDEBUGTEST(DBG_HOT)) {
string stats =
"==================================================\n";
if (IS_SERVER) {
stats += " on Server on Client\n";
}
else {
stats += " on Client on Server\n";
}
StringObjAppendPrintf(stats,"Added: %9ld %9ld\n",(long)fLocalItemsAdded,(long)fRemoteItemsAdded);
StringObjAppendPrintf(stats,"Deleted: %9ld %9ld\n",(long)fLocalItemsDeleted,(long)fRemoteItemsDeleted);
StringObjAppendPrintf(stats,"Updated: %9ld %9ld\n",(long)fLocalItemsUpdated,(long)fRemoteItemsUpdated);
StringObjAppendPrintf(stats,"Rejected with error: %9ld %9ld\n\n",(long)fLocalItemsError,(long)fRemoteItemsError);
#ifdef SYSYNC_SERVER
if (IS_SERVER) {
StringObjAppendPrintf(stats,"SlowSync Matches: %9ld\n",(long)fSlowSyncMatches);
StringObjAppendPrintf(stats,"Server won Conflicts: %9ld\n",(long)fConflictsServerWins);
StringObjAppendPrintf(stats,"Client won Conflicts: %9ld\n",(long)fConflictsClientWins);
StringObjAppendPrintf(stats,"Conflicts with Duplication: %9ld\n\n",(long)fConflictsDuplicated);
}
#endif
StringObjAppendPrintf(stats,"Content Data Bytes sent: %9ld\n",(long)fOutgoingDataBytes);
StringObjAppendPrintf(stats,"Content Data Bytes received: %9ld\n\n",(long)fIncomingDataBytes);
StringObjAppendPrintf(stats,"Duration of sync [seconds]: %9ld\n",(long)((fEndOfSyncTime-fSessionP->getSessionStarted())/secondToLinearTimeFactor));
PDEBUGPUTSXX(DBG_HOT,stats.c_str(),0,true);
}
if (isAborted()) {
// failed
PDEBUGPRINTFX(DBG_ERROR,("Warning: Failed with status code=%hd, statistics are incomplete!!",fAbortStatusCode));
}
#endif
} // TLocalEngineDS::showStatistics
// create a new syncop command for sending to remote
TSyncOpCommand *TLocalEngineDS::newSyncOpCommand(
TSyncItem *aSyncItemP, // the sync item
TSyncItemType *aSyncItemTypeP, // the sync item type
cAppCharP aLocalIDPrefix
)
{
// get operation
TSyncOperation syncop=aSyncItemP->getSyncOp();
// obtain meta
SmlPcdataPtr_t metaP = newMetaType(aSyncItemTypeP->getTypeName());
// create command
TSyncOpCommand *syncopcmdP = new TSyncOpCommand(fSessionP,this,syncop,metaP);
// make sure item does not have stuff it is not allowed to have
// %%% SCTS does not like SourceURI in Replace and Delete commands sent to Client
// there are the only ones allowed to carry a GUID
if (IS_SERVER) {
#ifdef SYSYNC_SERVER
// Server: commands only have remote IDs, except add which only has target ID
if (syncop==sop_add || syncop==sop_wants_add)
aSyncItemP->clearRemoteID(); // no remote ID
else {
if (!fDSConfigP->fAlwaysSendLocalID) {
// only if localID may not be included in all syncops
aSyncItemP->clearLocalID(); // no local ID
}
}
#endif
}
else {
// Client: all commands only have local IDs
aSyncItemP->clearRemoteID(); // no remote ID
}
// add the localID prefix if we do have a localID to send
if (aSyncItemP->hasLocalID()) {
if (IS_SERVER) {
#ifdef SYSYNC_SERVER
// make sure GUID (plus prefixes) is not exceeding allowed size
adjustLocalIDforSize(aSyncItemP->fLocalID,getRemoteDatastore()->getMaxGUIDSize(),aLocalIDPrefix ? strlen(aLocalIDPrefix) : 0);
#endif
}
// add local ID prefix, if any
if (aLocalIDPrefix && *aLocalIDPrefix)
aSyncItemP->fLocalID.insert(0,aLocalIDPrefix);
}
#ifdef SYSYNC_TARGET_OPTIONS
// init item generation variables
fItemSizeLimit=fSizeLimit;
#else
fItemSizeLimit=-1; // no limit
#endif
// now add item
SmlItemPtr_t itemP = aSyncItemTypeP->newSmlItem(aSyncItemP,this);
// check if data size is ok
if (itemP && fSessionP->fMaxOutgoingObjSize) {
if (itemP->data && itemP->data->content && itemP->data->length) {
// there is data, check if size is ok
if (itemP->data->length > fSessionP->fMaxOutgoingObjSize) {
// too large, suppress it
PDEBUGPRINTFX(DBG_ERROR,(
"WARNING: outgoing item is larger (%ld) than MaxObjSize (%ld) of remote -> suppress now/mark for resend",
(long)itemP->data->length,
(long)fSessionP->fMaxOutgoingObjSize
));
smlFreeItemPtr(itemP);
itemP=NULL;
// mark item for resend
// For datastores without resume support, this will just have no effect at all
engMarkItemForResend(aSyncItemP->getLocalID(),aSyncItemP->getRemoteID());
}
}
}
if (itemP) {
// add it to the command
syncopcmdP->addItem(itemP);
}
else {
// no item - command is invalid, delete it
delete syncopcmdP;
syncopcmdP=NULL;
}
// return command
return syncopcmdP;
} // TLocalEngineDS::newSyncOpCommand
// create SyncItem suitable for being sent from local to remote
TSyncItem *TLocalEngineDS::newItemForRemote(
uInt16 aExpectedTypeID // typeid of expected type
)
{
// safety
if (!canCreateItemForRemote())
SYSYNC_THROW(TSyncException("newItemForRemote called without sufficient type information ready"));
// create
TSyncItem *itemP = fLocalSendToRemoteTypeP->newSyncItem(fRemoteReceiveFromLocalTypeP,this);
if (!itemP)
SYSYNC_THROW(TSyncException("newItemForRemote could not create item"));
// check type
if (!itemP->isBasedOn(aExpectedTypeID)) {
PDEBUGPRINTFX(DBG_ERROR,(
"newItemForRemote created item of typeID %hd, caller expects %hd",
itemP->getTypeID(),
aExpectedTypeID
));
SYSYNC_THROW(TSyncException("newItemForRemote created wrong item type"));
}
return itemP;
} // TLocalEngineDS::newItemForRemote
// return pure relative (item) URI (removes absolute part or ./ prefix)
const char *TLocalEngineDS::DatastoreRelativeURI(const char *aURI)
{
return relativeURI(relativeURI(aURI,fSessionP->getLocalURI()),getName());
} // TLocalEngineDS::DatastoreRelativeURI
// - init filtering and check if needed (sets fTypeFilteringNeeded, fFilteringNeeded and fFilteringNeededForAll)
void TLocalEngineDS::initPostFetchFiltering(void)
{
#ifdef OBJECT_FILTERING
if (!fLocalSendToRemoteTypeP) {
fTypeFilteringNeeded=false;
fFilteringNeeded=false;
fFilteringNeededForAll=false;
}
else {
// get basic settings from type
fLocalSendToRemoteTypeP->initPostFetchFiltering(fTypeFilteringNeeded,fFilteringNeededForAll,this);
fFilteringNeeded=fTypeFilteringNeeded;
// NOTE: if type filtering is needed, it's the responsibility of initPostFetchFiltering() of
// the type to check (using the DBHANDLESOPTS() script func) if DB does already handle
// the range filters and such and possibly avoid type filtering then.
// then check for standard filter requirements
#ifdef SYDEBUG
#ifdef SYNCML_TAF_SUPPORT
if (!fTargetAddressFilter.empty()) PDEBUGPRINTFX(DBG_DATA,("using (dynamic, temporary) TAF expression from CGI : %s",fTargetAddressFilter.c_str()));
if (!fIntTargetAddressFilter.empty()) PDEBUGPRINTFX(DBG_DATA,("using (dynamic, temporary) internally set TAF expression : %s",fIntTargetAddressFilter.c_str()));
#endif // SYNCML_TAF_SUPPORT
if (!fSyncSetFilter.empty()) PDEBUGPRINTFX(DBG_DATA,("using (dynamic) sync set filter expression : %s",fSyncSetFilter.c_str()));
if (!fLocalDBFilter.empty()) PDEBUGPRINTFX(DBG_DATA,("using (static) local db filter expression : %s",fLocalDBFilter.c_str()));
#endif // SYDEBUG
// - if DB does the standard filters, we don't need to check them here again
if (!engFilteredFetchesFromDB(true)) {
// If DB does NOT do the standard filters, we have to do them here
// - this is the case if we have an (old-style) sync set filter, but not filtered by DB
// we need to filter all because sync set filter can be dynamic
if (!fSyncSetFilter.empty())
fFilteringNeededForAll=true;
// always return true if there is something to filter at all
if (
!fLocalDBFilter.empty() ||
!fDSConfigP->fInvisibleFilter.empty() ||
!fSyncSetFilter.empty() ||
!fDSConfigP->fRemoteAcceptFilter.empty()
)
fFilteringNeeded=true;
}
}
PDEBUGPRINTFX(DBG_FILTER+DBG_HOT,(
"Datastore-level postfetch filtering %sneeded%s",
fFilteringNeeded ? "" : "NOT ",
fFilteringNeeded ? (fFilteringNeededForAll ? " and to be applied to all records" : " only for changed records") : ""
));
#endif
} // TLocalEngineDS::initPostFetchFiltering
// filter fetched record
bool TLocalEngineDS::postFetchFiltering(TSyncItem *aSyncItemP)
{
#ifndef OBJECT_FILTERING
return true; // no filters, always pass
#else
if (!aSyncItemP) return false; // null item does not pass
// first do standard filters
// - if DB has filtered the
bool passes=true;
if (fFilteringNeeded) {
// - first make sure outgoing object has all properties set
// such that it would pass the acceptance filter (for example KIND for calendar...)
if (!aSyncItemP->makePassFilter(fDSConfigP->fRemoteAcceptFilter.c_str())) {
// we could not make item pass acceptance filters
PDEBUGPRINTFX(DBG_ERROR,("- item localid='%s' cannot be made passing <acceptfilter> -> ignored",aSyncItemP->getLocalID()));
passes=false;
}
// now check for field-level filters
if (passes && !engFilteredFetchesFromDB()) {
// DB has not already filtered these, so we need to do it here
// - "moving target" first
passes=fSyncSetFilter.empty() || aSyncItemP->testFilter(fSyncSetFilter.c_str());
if (passes) {
// - static filters
passes =
aSyncItemP->testFilter(fLocalDBFilter.c_str()) && // local filter
(
fDSConfigP->fInvisibleFilter.empty() || // and either no invisibility defined...
!aSyncItemP->testFilter(fDSConfigP->fInvisibleFilter.c_str()) // ...or NOT passed
);
}
}
if (passes && fTypeFilteringNeeded) {
// finally, apply type's filter
passes=aSyncItemP->postFetchFiltering(this);
}
}
else {
// no filtering needed, DB has already filtered out those that would not pass
// BUT: make sure outgoing items WILL pass the acceptance filter. If this
// cannot be done, item will be filtered out.
if (!aSyncItemP->makePassFilter(fDSConfigP->fRemoteAcceptFilter.c_str())) {
// we could not make item pass acceptance filters
PDEBUGPRINTFX(DBG_ERROR,("- item localid='%s' cannot be made passing <acceptfilter> -> ignored",aSyncItemP->getLocalID()));
passes=false;
}
}
#ifdef SYDEBUG
if (!passes) {
PDEBUGPRINTFX(DBG_DATA,("- item localid='%s' does not pass filters -> ignored",aSyncItemP->getLocalID()));
}
#endif
// return result
return passes;
#endif
} // TLocalEngineDS::postFetchFiltering
#ifdef OBJECT_FILTERING
// - called to check if incoming item passes acception filters
bool TLocalEngineDS::isAcceptable(TSyncItem *aSyncItemP, TStatusCommand &aStatusCommand)
{
// test acceptance
if (aSyncItemP->testFilter(fDSConfigP->fRemoteAcceptFilter.c_str())) return true; // ok
// not accepted, set 415 error
if (!fDSConfigP->fSilentlyDiscardUnaccepted)
aStatusCommand.setStatusCode(415);
ADDDEBUGITEM(aStatusCommand,"Received item does not pass acceptance filter");
PDEBUGPRINTFX(DBG_ERROR,(
"Received item does not pass acceptance filter: %s",
fDSConfigP->fRemoteAcceptFilter.c_str()
));
return false;
} // TLocalEngineDS::isAcceptable
/// @brief called to make incoming item visible
/// @return true if now visible
bool TLocalEngineDS::makeVisible(TSyncItem *aSyncItemP)
{
bool invisible=false;
if (!fDSConfigP->fInvisibleFilter.empty()) {
invisible=aSyncItemP->testFilter(fDSConfigP->fInvisibleFilter.c_str());
}
if (invisible) {
return aSyncItemP->makePassFilter(fDSConfigP->fMakeVisibleFilter.c_str());
}
return true; // is already visible
} // TLocalEngineDS::makeVisible
/// @brief called to make incoming item INvisible
/// @return true if now INvisible
bool TLocalEngineDS::makeInvisible(TSyncItem *aSyncItemP)
{
// return true if could make invisible or already was invisible
if (fDSConfigP->fInvisibleFilter.empty())
return false; // no invisible filter, cannot make invisible
// make pass invisible filter - if successful, we're now invisible
return aSyncItemP->makePassFilter(fDSConfigP->fInvisibleFilter.c_str()); // try to make invisible (and return result)
} // TLocalEngineDS::makeInvisible
// - called to make incoming item pass sync set filtering
bool TLocalEngineDS::makePassSyncSetFilter(TSyncItem *aSyncItemP)
{
bool pass=true;
// make sure we pass sync set filtering and stay visible
if (!fSyncSetFilter.empty()) {
// try to make pass sync set filter (modifies item only if it would not pass otherwise)
pass=aSyncItemP->makePassFilter(fSyncSetFilter.c_str());
}
if (!pass || fSyncSetFilter.empty()) {
// specified sync set filter cannot make item pass, or no sync set filter at all:
// - apply makePassFilter default expression
if (!fDSConfigP->fMakePassFilter.empty()) {
pass=aSyncItemP->makePassFilter(fDSConfigP->fMakePassFilter.c_str());
if (pass) {
// check again to check if item would pass the syncset filter now
pass=aSyncItemP->testFilter(fSyncSetFilter.c_str());
}
}
}
return pass;
} // TLocalEngineDS::makePassSyncSetFilter
#endif
// process remote item
bool TLocalEngineDS::engProcessRemoteItem(
TSyncItem *syncitemP,
TStatusCommand &aStatusCommand
)
{
#ifdef SYSYNC_CLIENT
if (IS_CLIENT)
return engProcessRemoteItemAsClient(syncitemP,aStatusCommand); // status, must be set to correct status code (ok / error)
#endif
#ifdef SYSYNC_SERVER
if (IS_SERVER)
return engProcessRemoteItemAsServer(syncitemP,aStatusCommand); // status, must be set to correct status code (ok / error)
#endif
// neither
return false;
} // TLocalEngineDS::engProcessRemoteItem
// process SyncML SyncOp command for this datastore
bool TLocalEngineDS::engProcessSyncOpItem(
TSyncOperation aSyncOp, // the operation
SmlItemPtr_t aItemP, // the item to be processed
SmlMetInfMetInfPtr_t aMetaP, // command-wide meta, if any
TStatusCommand &aStatusCommand // pre-set 200 status, can be modified in case of errors
)
{
bool regular = false;
// determine SyncItemType that can handle this item data
if (fRemoteDatastoreP==NULL) {
PDEBUGPRINTFX(DBG_ERROR,("engProcessSyncOpItem: Remote Datastore not known"));
aStatusCommand.setStatusCode(500);
}
// - start with default
TSyncItemType *remoteTypeP=getRemoteSendType();
TSyncItemType *localTypeP=getLocalReceiveType();
// - see if command-wide meta plus item contents specify another type
// (item meta, if present, overrides command wide meta)
// see if item itself or command meta specify a type name or format
SmlMetInfMetInfPtr_t itemmetaP = smlPCDataToMetInfP(aItemP->meta);
// - format
TFmtTypes fmt=fmt_chr;
if (itemmetaP && itemmetaP->format)
smlPCDataToFormat(itemmetaP->format,fmt); // use type name from item's meta
else if (aMetaP && aMetaP->format)
smlPCDataToFormat(aMetaP->format,fmt); // use type name from command-wide meta
// - type
string versstr;
const char *typestr = NULL;
if (itemmetaP && itemmetaP->type)
typestr = smlPCDataToCharP(itemmetaP->type); // use type name from item's meta
else if (aMetaP && aMetaP->type)
typestr = smlPCDataToCharP(aMetaP->type); // use type name from command-wide meta
// check if there is a type specified
if (typestr) {
PDEBUGPRINTFX(DBG_DATA,("Explicit type '%s' specified in command or item meta",typestr));
if (strcmp(remoteTypeP->getTypeName(),typestr)!=0) {
// specified type is NOT default type: search appropriate remote type
remoteTypeP=fRemoteDatastoreP->getSendType(typestr,NULL); // no version known so far
if (!remoteTypeP) {
// specified type is not a remote type listed in remote's devInf.
// But as remote is actually using it, we can assume it does support it, so use local type of same name instead
PDEBUGPRINTFX(DBG_ERROR,("According to remote devInf, '%s' is not supported, but obviously it is used here so we try to handle it",typestr));
// look it up in local datastore's list
remoteTypeP=getReceiveType(typestr,NULL);
}
}
if (remoteTypeP) {
#ifdef APP_CAN_EXPIRE
// get modified date of item
lineardate_t moddat=0; // IMPORTANT, must be initialized in case expiryFromData returns nothing!
bool ok = remoteTypeP->expiryFromData(aItemP,moddat)<=MAX_EXPIRY_DIFF+5;
// ok==true: we are within hard expiry
// ok==false: we are out of hard expiry
#ifdef SYSER_REGISTRATION
if (getSession()->getSyncAppBase()->fRegOK) {
// we have a license (permanent or timed) --> hard expiry is irrelevant
// (so override ok according to validity of current license)
ok=true; // assume ok
// check if license is timed, and if so, check if mod date is within timed range
// (if not, set ok to false)
uInt8 rd = getSession()->getSyncAppBase()->fRegDuration;
if (rd) {
lineardate_t ending = date2lineardate(rd/12+2000,rd%12+1,1);
ok = ending>=moddat; // ok if not modified after end of license period
}
}
#endif
// when we have no license (neither permanent nor timed), hard expiry decides as is
// (so just use ok as is)
if (!ok) {
aStatusCommand.setStatusCode(403); // forbidden to hack this expiry stuff!
fSessionP->AbortSession(403,true); // local problem
return false;
}
#endif // APP_CAN_EXPIRE
// we have a type, which should be able to determine version from data
if (remoteTypeP->versionFromData(aItemP,versstr)) {
// version found, Make sure version matches as well
PDEBUGPRINTFX(DBG_DATA,("Version '%s' obtained from item data",versstr.c_str()));
// check if current remotetype already has correct version (and type, but we know this already)
if (!remoteTypeP->supportsType(remoteTypeP->getTypeName(),versstr.c_str(),true)) {
// no, type/vers do not match, search again
remoteTypeP=fRemoteDatastoreP->getSendType(typestr,versstr.c_str());
if (!remoteTypeP) {
// specified type is not a remote type listed in remote's devInf.
// But as remote is actually using it, we can assume it does support it, so use local type of same name instead
PDEBUGPRINTFX(DBG_ERROR,("According to remote devInf, '%s' version '%s' is not supported, but obviously it is used here so we try to handle it",typestr,versstr.c_str()));
// look it up in local datastore's list
remoteTypeP=getReceiveType(typestr,versstr.c_str());
}
}
}
else {
PDEBUGPRINTFX(DBG_HOT,("Version could not be obtained from item data"));
}
}
if (!remoteTypeP) {
// no matching remote type: fail
aStatusCommand.setStatusCode(415);
ADDDEBUGITEM(aStatusCommand,"Incompatible content type specified in command or item meta");
PDEBUGPRINTFX(DBG_ERROR,(
"Incompatible content type '%s' version '%s' specified in command or item meta",
typestr,
versstr.empty() ? "[none]" : versstr.c_str()
));
return false; // irregular
}
else {
// we have the remote type, now determine matching local type
// - first check if this is compatible with the existing localTypeP (which
// was possibly selected by remote rule match
if (!localTypeP->supportsType(remoteTypeP->getTypeName(),remoteTypeP->getTypeVers(),false)) {
// current default local type does not support specified remote type
// - find a matching local type
localTypeP=getReceiveType(remoteTypeP);
#ifdef SYDEBUG
if (localTypeP) {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,(
"Explicit type '%s' does not match default type -> switching to local type '%s' for processing item",
typestr,
localTypeP->getTypeConfig()->getName()
));
}
#endif
}
}
}
// now process
if (localTypeP && remoteTypeP) {
TSyncItem *syncitemP = NULL;
// create the item (might have empty data in case of delete)
syncitemP=remoteTypeP->newSyncItem(aItemP,aSyncOp,fmt,localTypeP,this,aStatusCommand);
if (!syncitemP) {
// failed to create item
return false; // irregular
}
// Now start the real processing
PDEBUGBLOCKFMT(("Process_Item","processing remote item",
"SyncOp=%s|LocalID=%s|RemoteID=%s",
SyncOpNames[syncitemP->getSyncOp()],
syncitemP->getLocalID(),
syncitemP->getRemoteID()
));
#ifdef SCRIPT_SUPPORT
TErrorFuncContext errctx;
errctx.syncop = syncitemP->getSyncOp();
#endif
SYSYNC_TRY {
// this call frees the item
regular =
engProcessRemoteItem(syncitemP,aStatusCommand);
syncitemP = NULL;
PDEBUGENDBLOCK("Process_Item");
}
SYSYNC_CATCH (...)
// Hmm, was the item freed? Not sure, so assume that it was freed.
PDEBUGENDBLOCK("Process_Item");
SYSYNC_RETHROW;
SYSYNC_ENDCATCH
// Check for datastore level scripts that might change the status code and/or regular status
#ifdef SCRIPT_SUPPORT
errctx.statuscode = aStatusCommand.getStatusCode();
errctx.newstatuscode = errctx.statuscode;
errctx.datastoreP = this;
// call script
regular =
TScriptContext::executeTest(
regular, // pass through regular status
fDataStoreScriptContextP,
fDSConfigP->fReceivedItemStatusScript,
&ErrorFuncTable,
&errctx // caller context
);
// use possibly modified status code
#ifdef SYDEBUG
if (aStatusCommand.getStatusCode() != errctx.newstatuscode) {
PDEBUGPRINTFX(DBG_ERROR,("Status: Datastore script changed original status=%hd to %hd (original op was %s)",aStatusCommand.getStatusCode(),errctx.newstatuscode,SyncOpNames[errctx.syncop]));
}
#endif
aStatusCommand.setStatusCode(errctx.newstatuscode);
#endif
if (regular) {
// item 100% successfully processed
// - set new defaults to same type as current item
setReceiveTypeInfo(localTypeP,remoteTypeP);
}
}
else {
// missing remote or local type: fail
aStatusCommand.setStatusCode(415);
ADDDEBUGITEM(aStatusCommand,"Unknown content type");
PDEBUGPRINTFX(DBG_ERROR,(
"Missing remote or local SyncItemType"
));
regular=false; // irregular
}
return regular;
} // TLocalEngineDS::engProcessSyncOpItem
#ifdef SYSYNC_SERVER
// Server Case
// ===========
// helper to force a conflict
TSyncItem *TLocalEngineDS::forceConflict(TSyncItem *aSyncItemP)
{
TStatusCommand dummy(fSessionP);
// - create new item
TSyncItem *conflictingItemP =
newItemForRemote(aSyncItemP->getTypeID());
if (!conflictingItemP) return NULL;
// - set IDs
conflictingItemP->setLocalID(aSyncItemP->getLocalID());
conflictingItemP->setRemoteID(aSyncItemP->getRemoteID());
// - this is always a replace conflict (item exists in DB)
conflictingItemP->setSyncOp(sop_wants_replace);
// - try to get from DB
bool ok=logicRetrieveItemByID(*conflictingItemP,dummy);
if (ok && dummy.getStatusCode()!=404) {
// item found in DB, add it to the sync set so it can be sent to remote
// if not cancelled by dontSendItemAsServer()
SendItemAsServer(conflictingItemP);
PDEBUGPRINTFX(DBG_DATA,("Forced conflict with corresponding item from server DB"));
}
else {
// no item found, we cannot force a conflict
delete conflictingItemP;
conflictingItemP=NULL;
}
return conflictingItemP;
} // TLocalEngineDS::forceConflict
// process map
localstatus TLocalEngineDS::engProcessMap(cAppCharP aRemoteID, cAppCharP aLocalID)
{
if (!testState(dssta_syncmodestable)) {
// Map received when not appropriate
PDEBUGPRINTFX(DBG_ERROR,("Map not allowed in this stage of sync"));
return 403;
}
// pre-process localID
string realLocalID;
if (aLocalID && *aLocalID) {
// Note: Map must be ready to have either empty local or remote ID to delete an entry
// perform reverse lookup of received GUID to real GUID
realLocalID = aLocalID;
obtainRealLocalID(realLocalID);
aLocalID=realLocalID.c_str();
}
else {
aLocalID=NULL;
}
// pre-process remoteID
if (!aRemoteID || *aRemoteID==0)
aRemoteID=NULL;
// let implementation process the map command
return logicProcessMap(aRemoteID, aLocalID);
} // TLocalEngineDS::engProcessMap
// process sync operation from client with specified sync item
// (according to current sync mode of local datastore)
// - returns true (and unmodified or non-200-successful status) if
// operation could be processed regularily
// - returns false (but probably still successful status) if
// operation was processed with internal irregularities, such as
// trying to delete non-existant item in datastore with
// incomplete Rollbacks (which returns status 200 in this case!).
bool TLocalEngineDS::engProcessRemoteItemAsServer(
TSyncItem *aSyncItemP,
TStatusCommand &aStatusCommand // status, must be set to correct status code (ok / error)
)
{
TSyncItem *conflictingItemP=NULL;
TSyncItem *echoItemP=NULL;
TSyncItem *delitemP=NULL;
bool changedincoming=false;
bool changedexisting=false;
bool remainsvisible=true; // usually, we want the item to remain visible in the sync set
TStatusCommand dummy(fSessionP);
// get some info out of item (we might need it after item is already consumed)
TSyncOperation syncop=aSyncItemP->getSyncOp();
uInt16 itemtypeid=aSyncItemP->getTypeID();
string remoteid=aSyncItemP->getRemoteID();
// check if datastore is aborted
if(CheckAborted(aStatusCommand))
return false;
// send event (but no abort checking)
DB_PROGRESS_EVENT(this,pev_itemreceived,++fItemsReceived,fRemoteNumberOfChanges,0);
fPreventAdd = false;
fIgnoreUpdate = false;
// show
PDEBUGPRINTFX(DBG_DATA,("%s item operation received",SyncOpNames[syncop]));
// check if receiving commands is allowed at all
if (fSyncMode==smo_fromserver) {
// Modifications from client not allowed during update from server only
aStatusCommand.setStatusCode(403);
ADDDEBUGITEM(aStatusCommand,"Client command not allowed in one-way/refresh from server");
PDEBUGPRINTFX(DBG_ERROR,("Client command not allowed in one-way/refresh from server"));
delete aSyncItemP;
return false;
}
// let item check itself to catch special cases
// - init variables which are used/modified by item checking
#ifdef SYSYNC_TARGET_OPTIONS
// init item generation variables
fItemSizeLimit=fSizeLimit;
#else
fItemSizeLimit=-1; // no limit
#endif
fCurrentSyncOp = syncop;
fEchoItemOp = sop_none;
fItemConflictStrategy=fSessionConflictStrategy; // get default strategy for this item
fForceConflict = false;
fDeleteWins = fDSConfigP->fDeleteWins; // default to configured value
fRejectStatus = -1; // no rejection
// - now check
// check reads and possibly modifies:
// - fEchoItemOp : if not sop_none, the incoming item is echoed back to the remote with the specified syncop
// - fItemConflictStrategy : might be changed from the pre-set datastore default
// - fForceConflict : if set, a conflict is forced by adding the corresponding local item (if any) to the list of items to be sent
// - fDeleteWins : if set, in a replace/delete conflict delete will win (regardless of strategy)
// - fPreventAdd : if set, attempt to add item from remote (even implicitly trough replace) will cause no add but delete of remote item
// - fIgnoreUpdate : if set, attempt to update item from remote will be ignored, only adds (also implicit ones) are executed
// - fRejectStatus : if set>=0, incoming item is irgnored silently(==0) or with error(!=0)
aSyncItemP->checkItem(this);
// - create echo item if we need one
if (fEchoItemOp!=sop_none) {
// Note: sop_add makes no sense at all.
// Note: If echo is enabled, conflicts are not checked, as echo makes only sense in
// cases where we know that a conflict cannot occur or is irrelevant
// - artifically create a "conflicting" item, that is, one to be sent back to remote
echoItemP=newItemForRemote(aSyncItemP->getTypeID());
// - assign data from incoming item if echo is not a delete
if (fEchoItemOp!=sop_delete && fEchoItemOp!=sop_archive_delete && fEchoItemOp!=sop_soft_delete)
echoItemP->replaceDataFrom(*aSyncItemP);
// - set remote ID (note again: sop_add makes no sense here)
echoItemP->setRemoteID(aSyncItemP->getRemoteID());
// - set sop
echoItemP->setSyncOp(fEchoItemOp);
// - now check for possible conflict
if (!fSlowSync) {
conflictingItemP = getConflictingItemByRemoteID(aSyncItemP);
// remove item if there is one that would conflict with the echo
if (conflictingItemP) dontSendItemAsServer(conflictingItemP);
conflictingItemP = NULL;
}
// - add echo to the list of items to be sent (DB takes ownership)
SendItemAsServer(echoItemP);
PDEBUGPRINTFX(DBG_DATA,("Echoed item back to remote with sop=%s",SyncOpNames[fEchoItemOp]));
// process item normally (except that we don't check for LUID conflicts)
}
// - check if incoming item should be processed at all
if (fRejectStatus>=0) {
// Note: a forced conflict can still occur even if item is rejected
// (this has the effect of unconditionally letting the server item win)
if (fForceConflict && syncop!=sop_add) {
conflictingItemP = forceConflict(aSyncItemP);
// Note: conflictingitem is always a replace
if (conflictingItemP) {
if (syncop==sop_delete) {
// original was delete, forced conflict means re-adding to remote
conflictingItemP->setSyncOp(sop_wants_add);
}
else {
// merge here because we'll not process the item further
conflictingItemP->mergeWith(*aSyncItemP,changedexisting,changedincoming,this);
}
}
}
// now discard the incoming item
delete aSyncItemP;
PDEBUGPRINTFX(fRejectStatus>=400 ? DBG_ERROR : DBG_DATA,("Item rejected with Status=%hd",fRejectStatus));
if (fRejectStatus>0) {
// rejected with status code (not necessarily error)
aStatusCommand.setStatusCode(fRejectStatus);
if (fRejectStatus>=300) {
// non 200-codes are errors
ADDDEBUGITEM(aStatusCommand,"Item rejected");
return false;
}
}
// silently rejected
return true;
}
// now perform requested operation
bool ok=false;
localstatus sta;
switch (syncop) {
readonly_delete:
// read-only handling of delete is like soft delete: remove map entry, but nothing else
PDEBUGPRINTFX(DBG_DATA,("Read-Only Datastore: Prevented actual deletion, just removing map entry"));
case sop_soft_delete:
// Readonly: allowed, as only map is touched
// soft delete from client is treated as an indication that the item was
// removed from the client's datastore, but is still in the set
// of sync data for that client.
// This means that the map item must be removed.
// - when the item is hard-deleted on the server, nothing will happen at next sync
// - when the item is modified on the server, it will be re-added to the client at next sync
// - when slow sync is performed, the item will be re-added, too.
// %%%%% Note that this does NOT work as it is now, as adds also occur for non-modified
// items that have no map AND are visible under current targetFilter.
// probably we should use a map entry with no remoteID for soft-deleted items later....
// Delete Map entry by remote ID
aSyncItemP->clearLocalID(); // none
sta=engProcessMap(aSyncItemP->getRemoteID(),NULL);
ok=sta==LOCERR_OK;
aStatusCommand.setStatusCode(ok ? 200 : sta);
break;
case sop_archive_delete:
if (fReadOnly) goto readonly_delete; // register removal of item in map, but do nothing to data itself
#ifdef OBJECT_FILTERING
if (!fDSConfigP->fInvisibleFilter.empty()) {
// turn into replace with all fields unavailable but made to pass invisible filter
// - make sure that no data field is assigned
aSyncItemP->cleardata();
// - make item pass "invisible" filter
if (aSyncItemP->makePassFilter(fDSConfigP->fInvisibleFilter.c_str())) {
// item now passes invisible rule, that is, it is invisible -> replace in DB
goto archive_delete;
}
}
// fall trough, no archive delete supported
#endif
// No archive delete support if there is no filter to detect/generate invisibles
// before SyncML 1.1 : we could return 210 here and still process the delete op.
// SyncML 1.1 : we must return 501 (not implemented) here
aStatusCommand.setStatusCode(501);
PDEBUGPRINTFX(DBG_ERROR,("Datastore does not support Archive-Delete, error status = 501"));
delete aSyncItemP;
ok=false;
break;
case sop_delete:
// delete item by LUID
if (fSlowSync) {
aStatusCommand.setStatusCode(403);
ADDDEBUGITEM(aStatusCommand,"Delete during slow sync not allowed");
PDEBUGPRINTFX(DBG_ERROR,("Delete during slow sync not allowed"));
delete aSyncItemP;
ok=false;
break;
}
// check for conflict with replace from server
// Note: conflict cases do not change local DB, so they are allowed before checking fReadOnly
if (!echoItemP) conflictingItemP = getConflictingItemByRemoteID(aSyncItemP); // do not check conflicts if we have already created an echo
// - check if we must force the conflict
if (!conflictingItemP && fForceConflict) {
conflictingItemP=forceConflict(aSyncItemP);
}
if (conflictingItemP) {
// conflict only if other party has replace
if (conflictingItemP->getSyncOp()==sop_replace || conflictingItemP->getSyncOp()==sop_wants_replace) {
if (!fDeleteWins) {
// act as if successfully deleted and cause re-adding of still existing server item
// - discard deletion
delete aSyncItemP;
// - remove map entry for this item (it no longer exists on the client)
sta = engProcessMap(NULL,conflictingItemP->getLocalID());
aStatusCommand.setStatusCode(sta==LOCERR_OK ? 200 : sta);
// - change replace to add (as to-be-replaced item is already deleted on remote)
conflictingItemP->setSyncOp(sop_add);
// - remove remote ID (will be assigned a new ID because the item is now re-added)
conflictingItemP->setRemoteID("");
// - no server operation needed
PDEBUGPRINTFX(DBG_DATA,("Conflict of Client Delete with Server replace -> discarded delete, re-added server item to client"));
ok=true;
break;
}
else {
// delete preceedes replace
// - avoid sending item from server
dontSendItemAsServer(conflictingItemP);
// - let delete happen
}
}
// if both have deleted the item, we should remove the map
// and avoid sending a delete to the client
else if (conflictingItemP->getSyncOp()==sop_delete) {
// - discard deletion
delete aSyncItemP;
// - remove map entry for this item (it no longer exists)
sta = engProcessMap(NULL,conflictingItemP->getLocalID());
aStatusCommand.setStatusCode(sta==LOCERR_OK ? 200 : sta);
// - make sure delete from server is not sent
dontSendItemAsServer(conflictingItemP);
PDEBUGPRINTFX(DBG_DATA,("Client and Server have deleted same item -> just removed map entry"));
ok=true;
break;
}
}
// real delete is discarded silently when fReadOnly is set
if (fReadOnly) goto readonly_delete; // register removal of item in map, but do nothing to data itself
// really delete
fLocalItemsDeleted++;
remainsvisible=false; // deleted not visible any more
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // delete in local database NOW
break;
case sop_copy:
if (fReadOnly) {
delete aSyncItemP; // we don't need it
aStatusCommand.setStatusCode(200);
PDEBUGPRINTFX(DBG_DATA,("Read-Only: copy command silently discarded"));
ok=true;
break;
}
// %%% note: this would belong into specific datastore implementation, but is here
// now for simplicity as copy isn't used heavily het
// retrieve data from local datastore
if (!logicRetrieveItemByID(*aSyncItemP,aStatusCommand)) { ok=false; break; }
// process like add
/// @todo %%%%%%%%%%%%%%%% NOTE: MISSING SENDING BACK MAP COMMAND for new GUID created
goto normal_add;
case sop_add:
// test for slow sync
if (fSlowSync) goto sop_slow_add; // add in slow sync is like replace
normal_add:
// add as new item to server DB
aStatusCommand.setStatusCode(201); // item added (if no error occurs)
if (fReadOnly) {
delete aSyncItemP; // we don't need it
PDEBUGPRINTFX(DBG_DATA,("Read-Only: add command silently discarded"));
ok=true;
break;
}
// check if adds are prevented
if (!fPreventAdd) {
// add allowed
fLocalItemsAdded++;
#ifdef OBJECT_FILTERING
// test if acceptable
if (!isAcceptable(aSyncItemP,aStatusCommand)) { ok=false; break; } // cannot be accepted
// Note: making item to pass sync set filter is implemented in derived DB implementation
// as criteria for passing might be in data that must first be read from the DB
#endif
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // add to local database NOW
if (!remainsvisible && fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Added item is not visible under current filters -> remove it on client"));
goto removefromremoteandsyncset;
}
break;
}
goto preventadd;
archive_delete:
sop_slow_add:
aSyncItemP->setSyncOp(sop_replace); // set correct op
// ...and process like replace
case sop_reference_only:
case sop_replace:
#ifdef OBJECT_FILTERING
// test if acceptable
if (!isAcceptable(aSyncItemP,aStatusCommand)) { ok=false; break; } // cannot be accepted
// Note: making item to pass sync set filter is implemented in derived DB implementation
// as criteria for passing might be in data that must first be read from the DB
#endif
// check for conflict with server side modifications
if (!fSlowSync) {
if (!echoItemP) conflictingItemP = getConflictingItemByRemoteID(aSyncItemP);
// - check if we must force the conflict
if (!conflictingItemP && fForceConflict) {
conflictingItemP=forceConflict(aSyncItemP);
}
bool deleteconflict=false;
if (conflictingItemP) {
// Note: if there is a conflict, this replace cannot be an
// implicit add, so we don't need to check for fPreventAdd
// here.
// Note: if we are in ignoreUpdate mode, the only conflict resolution
// possible is unconditional server win
sInt16 cmpRes = SYSYNC_NOT_COMPARABLE;
// assume we can resolve the conflict
aStatusCommand.setStatusCode(419); // default to server win
ADDDEBUGITEM(aStatusCommand,"Conflict resolved by server");
PDEBUGPRINTFX(DBG_HOT,(
"Conflict: Remote <%s> with remoteID=%s <--> Local <%s> with localID=%s, remoteID=%s",
SyncOpNames[aSyncItemP->getSyncOp()],
aSyncItemP->getRemoteID(),
SyncOpNames[conflictingItemP->getSyncOp()],
conflictingItemP->getLocalID(),
conflictingItemP->getRemoteID()
));
// we have a conflict, decide what to do
TConflictResolution crstrategy;
if (fReadOnly || fIgnoreUpdate) {
// server always wins and overwrites modified client version
PDEBUGPRINTFX(DBG_DATA,("Read-Only or IgnoreUpdate: server always wins"));
crstrategy=cr_server_wins;
}
else {
// two-way
crstrategy = fItemConflictStrategy; // get conflict strategy pre-set for this item
if (conflictingItemP->getSyncOp()==sop_delete) {
// server wants to delete item, client wants to replace
if (fDSConfigP->fTryUpdateDeleted) {
// if items are not really deleted, but only made invisible,
// we can assume we can update the "deleted" item
// BUT ONLY if the conflict strategy is not "server always wins"
if (crstrategy==cr_server_wins) {
PDEBUGPRINTFX(DBG_PROTO+DBG_HOT,("Conflict of Client Replace with Server delete and strategy is server-wins -> delete from client"));
aStatusCommand.setStatusCode(419); // server wins, client command ignored
break; // done
}
else {
PDEBUGPRINTFX(DBG_PROTO+DBG_HOT,("Conflict of Client Replace with Server delete -> try to update already deleted item (as it might still exist in syncset)"));
// apply replace (and in case of !fDeleteWins, possible implicit add)
fPreventAdd=fDeleteWins; // we want implicit add only if delete cannot win
remainsvisible=!fDeleteWins; // we want to see the item in the sync set if delete does not win!
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible);
}
if (fDeleteWins) {
if (!ok) {
// could not update already deleted item
PDEBUGPRINTFX(DBG_PROTO,("Could not update already deleted server item (seems to be really deleted, not just invisible)"));
aStatusCommand.setStatusCode(419); // server wins, client command ignored
}
else {
// update of invisible item successful, but it will still be deleted from client
// Note: possibly, the update was apparently successful, but only because an UPDATE with no
// target does not report an error. So effectively, no update might have happened.
PDEBUGPRINTFX(DBG_PROTO,("Updated already deleted server item, but delete still wins -> client item will be deleted"));
fLocalItemsUpdated++;
aStatusCommand.setStatusCode(200); // client command successful (but same item will still be deleted)
}
// nothing more to do, let delete happen on the client (conflictingItemP delete will be sent)
ok=true;
}
else {
// not fDeleteWins - item failed, updated or implicitly added
if (ok) {
// update (or implicit add) successful
if (aStatusCommand.getStatusCode()==201) {
PDEBUGPRINTFX(DBG_PROTO,("Client Update wins and has re-added already deleted server item -> prevent delete on client"));
fLocalItemsAdded++;
}
else {
PDEBUGPRINTFX(DBG_PROTO,("Client Update wins and has updated still existing server item -> prevent delete on client"));
fLocalItemsUpdated++;
}
// and client item wins - prevent sending delete to client
// - don't send delete to client
conflictingItemP->setSyncOp(sop_none); // just in case...
dontSendItemAsServer(conflictingItemP);
}
}
// done
break;
}
else {
// Normal delete conflict processing (assuming deleted items REALLY deleted)
if (!fDeleteWins) {
// - client always wins (replace over delete)
crstrategy=cr_client_wins;
deleteconflict=true; // flag condition for processing below
// - change from replace to add, because item is already deleted in server and must be re-added
fLocalItemsAdded++;
aSyncItemP->setSyncOp(sop_add);
PDEBUGPRINTFX(DBG_PROTO,("Conflict of Client Replace with Server delete -> client wins, client item is re-added to server"));
}
else {
// delete wins, just discard incoming item
delete aSyncItemP;
PDEBUGPRINTFX(DBG_PROTO,("Conflict of Client Replace with Server delete -> DELETEWINS() set -> ignore client replace"));
ok=true;
break;
}
}
}
else {
// replace from client conflicts with replace from server
// - compare items for further conflict resolution
// NOTE: it is serveritem.compareWith(clientitem)
cmpRes = conflictingItemP->compareWith(
*aSyncItemP,eqm_conflict,this
#ifdef SYDEBUG
,PDEBUGTEST(DBG_CONFLICT) // show conflict comparisons in normal sync if conflict details are enabled
#endif
);
PDEBUGPRINTFX(DBG_DATA,(
"Compared conflicting items with eqm_conflict: remoteItem %s localItem",
cmpRes==0 ? "==" : (cmpRes>0 ? "<" : ">")
));
// see if we can determine newer item
if (crstrategy==cr_newer_wins) {
if (cmpRes!=0 && conflictingItemP->sortable(*aSyncItemP)) {
// newer item wins
// (comparison was: serveritem.compareWith(clientitem), so
// cmpRes<0 means that client is newer
PDEBUGPRINTFX(DBG_PROTO,("Conflict resolved by identifying newer item"));
if (cmpRes > 0)
crstrategy=cr_server_wins; // server has newer item
else
crstrategy=cr_client_wins; // client has newer item
}
else {
// newer item cannot be determined, duplicate items
crstrategy=cr_duplicate;
}
PDEBUGPRINTFX(DBG_DATA,(
"Newer item %sdetermined: %s",
crstrategy==cr_duplicate ? "NOT " : "",
crstrategy==cr_client_wins ? "Client item is newer and wins" :
(crstrategy==cr_server_wins ? "Server item is newer ans wins" : "item is duplicated if different")
));
}
}
// modify strategy based on compare
if (cmpRes==0 && crstrategy==cr_duplicate) {
// items are equal by definition of item comparison,
// but obviously both changed, this means that changes should be
// mergeable
// So, by deciding arbitrarily that server has won, we will not loose any data
crstrategy=cr_server_wins; // does not matter, because merge will be attempted
PDEBUGPRINTFX(DBG_DATA,("Duplication avoided because items are equal by their own definition, just merge"));
}
// if adds prevented, we cannot duplicate, let server win
if (fPreventAdd && crstrategy==cr_duplicate) crstrategy=cr_server_wins;
} // not fReadOnly
// now apply strategy
if (crstrategy==cr_duplicate) {
// add items vice versa
PDEBUGPRINTFX(DBG_PROTO,("Conflict resolved by duplicating items in both databases"));
aStatusCommand.setStatusCode(209);
fConflictsDuplicated++;
// - set server item such that it will be added as new item to client DB
conflictingItemP->setSyncOp(sop_add);
// - break up mapping between client and server item BEFORE adding to server
// because else adding of item with already existing remoteID can fail.
// In addition, item now being sent to client may not have a map before
// it receives a map command from the client!
sta = engProcessMap(NULL,conflictingItemP->getLocalID());
if(sta!=LOCERR_OK) {
PDEBUGPRINTFX(DBG_ERROR,(
"Problem (status=%hd) removing map entry for LocalID='%s'",
sta,
conflictingItemP->getLocalID()
));
}
// - add client item as new item to server DB
fLocalItemsAdded++;
aSyncItemP->setSyncOp(sop_add); // set correct op
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // add to local database NOW
break;
}
else if (crstrategy==cr_server_wins) {
// Note: for fReadOnly, this is always the case!
// server item wins and is sent to client
PDEBUGPRINTFX(DBG_PROTO,("Conflict resolved: server item replaces client item"));
aStatusCommand.setStatusCode(419); // server wins, client command ignored
fConflictsServerWins++;
// - make sure item is set to replace data in client
conflictingItemP->setSyncOp(sop_replace);
// - attempt to merge data from loosing item (accumulating fields)
if (!fReadOnly) {
conflictingItemP->mergeWith(*aSyncItemP,changedexisting,changedincoming,this);
}
if (fIgnoreUpdate) changedexisting=false; // never try to update existing item
if (changedexisting) {
// we have merged something, so server must be updated, too
// Note: after merge, both items are equal. We check if conflictingitem
// has changed, but if yes, we write the incoming item. Conflicting item
// will get sent to client later
PDEBUGPRINTFX(DBG_DATA,("*** Merged some data from loosing client item into winning server item"));
// set correct status for conflict resultion by merge
aStatusCommand.setStatusCode(207); // merged
// process update in local database
fLocalItemsUpdated++;
aSyncItemP->setSyncOp(sop_replace); // update
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // update in local database NOW
break;
}
else {
// - item sent by client has lost and can be deleted now
// %%% possibly add option here to archive item in some way
// BUT ONLY IF NOT fReadOnly
delete aSyncItemP;
}
}
else if (crstrategy==cr_client_wins) {
// client item wins and is sent to server
PDEBUGPRINTFX(DBG_PROTO,("Conflict resolved: client item replaces server item"));
aStatusCommand.setStatusCode(208); // client wins
fConflictsClientWins++;
// - attempt to merge data from loosing item (accumulating fields)
if (!deleteconflict) {
aSyncItemP->mergeWith(*conflictingItemP,changedincoming,changedexisting,this);
}
if (changedincoming) {
// we have merged something, so client must be updated even if it has won
// Note: after merge, both items are equal. We check if aSyncItemP
// has changed, but if yes, we make sure the conflicting item gets
// sent to the client
PDEBUGPRINTFX(DBG_DATA,("*** Merged some data from loosing server item into winning client item"));
conflictingItemP->setSyncOp(sop_replace); // update
// set correct status for conflict resultion by merge
aStatusCommand.setStatusCode(207); // merged
// will be sent because it is in the list
}
else {
// - make sure conflicting item from server is NOT sent to client
conflictingItemP->setSyncOp(sop_none); // just in case...
dontSendItemAsServer(conflictingItemP);
aStatusCommand.setStatusCode(200); // ok
}
// - replace item in server (or leave it as is, if conflict was with delete)
if (!deleteconflict) {
fLocalItemsUpdated++;
aSyncItemP->setSyncOp(sop_replace);
}
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // replace in local database NOW
break;
}
} // replace conflict
else {
// normal replace without any conflict
if (fReadOnly) {
delete aSyncItemP; // we don't need it
aStatusCommand.setStatusCode(200);
PDEBUGPRINTFX(DBG_DATA,("Read-Only: replace command silently discarded"));
ok=true;
break;
}
// no conflict, just let client replace server's item
PDEBUGPRINTFX(DBG_DATA+DBG_CONFLICT,("No Conflict: client item replaces server item"));
// - replace item in server (or add if item does not exist and not fPreventAdd)
aSyncItemP->setSyncOp(sop_replace);
remainsvisible=true; // should remain visible
if (!logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible)) {
// check if this is a 404 or 410 and fPreventAdd
if (fPreventAdd && (aStatusCommand.getStatusCode()==404 || aStatusCommand.getStatusCode()==410))
goto preventadd2; // to-be-replaced item not found and implicit add prevented -> delete from remote
// simply failed
ok=false;
break;
}
// still visible in sync set?
if (!remainsvisible && fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
// -> cause item to be deleted on remote
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Item replaced no longer visible in syncset -> returning delete to remote"));
goto removefromremoteandsyncset;
}
// processed ok
if (aStatusCommand.getStatusCode()==201)
fLocalItemsAdded++;
else
fLocalItemsUpdated++;
ok=true;
break;
}
} // normal sync
else {
// slow sync (replaces AND adds are treated the same)
// - first do a strict search for identical item. This is required to
// prevent that in case of multiple (loosely compared) matches we
// catch the wrong item and cause a mess at slowsync
// NOTE: we do compare only relevant fields (eqm_conflict)
TSyncItem *matchingItemP = getMatchingItem(aSyncItemP,eqm_conflict);
if (!matchingItemP) {
// try again with less strict comparison (eqm_slowsync or eqm_always for firsttimesync)
DEBUGPRINTFX(DBG_DATA+DBG_MATCH,("Strict search for matching item failed, try with configured EqMode now"));
matchingItemP = getMatchingItem(aSyncItemP,fFirstTimeSync ? eqm_always : eqm_slowsync);
}
if (matchingItemP) {
// both sides already have this item
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,(
"Slow Sync Match detected - localID='%s' matches incoming item",
matchingItemP->getLocalID()
));
fSlowSyncMatches++;
aStatusCommand.setStatusCode(syncop==sop_add ? 201 : 200); // default is: simply ok. But if original op was Add, MUST return 201 status (SCTS requires it)
bool matchingok=false;
// - do not update map yet, as we still don't know if client item will
// possibly be added instead of mapped
// Note: ONLY in case this is a reference-only item, the map is already updated!
bool mapupdated = syncop==sop_reference_only;
// - determine which one is winning
bool needserverupdate=false;
bool needclientupdate=false;
// if updates are ignored, we can short-cut here
// Note: if this is a reference-only item, it was already updated (if needed) before last suspend
// so skip updating now!
if (syncop!=sop_reference_only && !fIgnoreUpdate) {
// Not a reference-only and also updates not suppressed
// - for a read-only datastore, this defaults to server always winning
TConflictResolution crstrategy =
fReadOnly ?
cr_server_wins : // server always wins for read-only
fItemConflictStrategy; // pre-set strategy for this item
// Determine what data to use
if (crstrategy==cr_newer_wins) {
// use newer
// Note: comparison is clientitem.compareWith(serveritem)
// so if result>0, client is newer than server
sInt16 cmpRes = aSyncItemP->compareWith(
*matchingItemP,eqm_nocompare,this
#ifdef SYDEBUG
,PDEBUGTEST(DBG_CONFLICT+DBG_DETAILS) // show age comparisons only if we want to see details
#endif
);
if (cmpRes==1) crstrategy=cr_client_wins;
else if (cmpRes==-1 || fPreventAdd) crstrategy=cr_server_wins; // server wins if adds prevented
else crstrategy=cr_duplicate; // fall back to duplication if we can't determine newer item
PDEBUGPRINTFX(DBG_DATA,(
"Newer item %sdetermined: %s",
crstrategy==cr_duplicate ? "NOT " : "",
crstrategy==cr_client_wins ? "Client item is newer and wins" :
(crstrategy==cr_server_wins ? "Server item is newer and wins" : "item is duplicated if different")
));
}
// if adds prevented, we cannot duplicate, let server win
if (fPreventAdd && crstrategy==cr_duplicate) crstrategy=cr_server_wins;
// now execute chosen strategy
if (crstrategy==cr_client_wins) {
// - merge server's data into client item
PDEBUGPRINTFX(DBG_DATA,("Trying to merge some data from loosing server item into winning client item"));
aSyncItemP->mergeWith(*matchingItemP,changedincoming,changedexisting,this);
// only count if server gets updated
if (changedexisting) fConflictsClientWins++;
// Note: changedexisting will cause needserverupdate to be set below
}
else if (crstrategy==cr_server_wins) {
// - merge client data into server item
PDEBUGPRINTFX(DBG_DATA,("Trying to merge some data from loosing client item into winning server item"));
matchingItemP->mergeWith(*aSyncItemP,changedexisting,changedincoming,this);
// only count if client gets updated
if (changedincoming) fConflictsServerWins++;
// Note: changedincoming will cause needclientupdate to be set below
}
else if (crstrategy==cr_duplicate) {
// test if items are equal enough
// (Note: for first-sync, compare mode for item matching can be looser
// (eqm_always), so re-comparison here makes sense)
if (
matchingItemP->compareWith(
*aSyncItemP,eqm_slowsync,this
#ifdef SYDEBUG
,PDEBUGTEST(DBG_CONFLICT+DBG_DETAILS) // show equality re-test only for details enabled
#endif
)!=0
) {
string guid;
// items are not really equal in content, so duplicate them on both sides
PDEBUGPRINTFX(DBG_PROTO,("Matching items are not fully equal, duplicate them on both sides"));
fConflictsDuplicated++;
// - duplicates contain merged data
matchingItemP->mergeWith(*aSyncItemP,changedexisting,changedincoming,this);
// - add client item (with server data merged) as new item to server
fLocalItemsAdded++;
aSyncItemP->setSyncOp(sop_add);
aStatusCommand.setStatusCode(201); // item added (if no error occurs)
remainsvisible=true; // should remain visible
matchingok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible,&guid); // add item in local database NOW
aSyncItemP=NULL; // is already deleted!
if (matchingok) { // do it only if server add successful, because otherwise we don't have a GUID
// - make sure same item is ADDED as new item to client
matchingItemP->setSyncOp(sop_add); // add it, prevent it from re-match (is sop_wants_add now)
matchingItemP->setLocalID(guid.c_str()); // this is now a pair with the newly added item (not the original one)
matchingItemP->setRemoteID(""); // we don't know the remote ID yet
}
// adding duplicate to server (add) is already done
changedexisting=false;
changedincoming=false;
mapupdated=true; // no need to update map
needserverupdate=false; // already done
// client must received the (updated) server item as an add (set above)
needclientupdate=true;
}
}
} // if not ignoreUpdate
// Update server map now if required
// - NOTE THAT THIS IS VERY IMPORTANT TO DO BEFORE any possible
// replaces, because replacing the matchingItem can only be
// done via its remoteID, which is, at this moment, probably not
// valid. After Mapping, it is ensured that the mapped remoteID
// uniquely identifies the matchingItem.
if (!mapupdated) {
// - update map in server
sta = engProcessMap(
aSyncItemP->getRemoteID(), // remote ID (LUID) of item received from client
matchingItemP->getLocalID() // local ID (GUID) of item already stored in server
);
matchingok = sta==LOCERR_OK;
if (!matchingok) {
// failed
ok=false;
aStatusCommand.setStatusCode(sta);
break;
}
}
// Now prepare updates of (already mapped) server and client items if needed
if (changedexisting) {
// matched item in server's sync set was changed and must be update in server DB
// update server only if updates during non-first-time slowsync are enabled
if (fFirstTimeSync || fSessionP->fUpdateServerDuringSlowsync) {
needserverupdate=true; // note: ineffective if fReadOnly
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Server data was updated by record sent by client, REPLACE it in server DB"));
}
else {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Server data was updated by record sent by client, but server updates during non-firsttime slowsyncs are disabled"));
}
}
if (changedincoming) {
// incoming item from remote was changed after receiving and must be reflected
// back to client
// NOTE: this can also happen with sop_reference_only items
// - client will be updated because matchingItemP is still in list
matchingItemP->setSyncOp(sop_replace); // cancel wants_add state, prevent re-match
// - matchingItem was retrieved BEFORE map was done, and has no valid remote ID
// so remote ID must be added now.
matchingItemP->setRemoteID(aSyncItemP->getRemoteID());
// update client only if updates during non-first-time slowsync are enabled
if (fFirstTimeSync || fSessionP->fUpdateClientDuringSlowsync) {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Record sent by client was updated with server data, client will receive a REPLACE"));
needclientupdate=true;
}
else {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Record sent by client was updated, but client updates during non-firsttime slowsyncs are disabled"));
}
}
// update
// - check if client must be updated
if (!needclientupdate) {
// prevent updating client
// - make sure matching item from server is NOT sent to client
matchingItemP->setSyncOp(sop_none); // just in case...
dontSendItemAsServer(matchingItemP);
}
else {
// check if replaces may be sent to client during slowsync
if (matchingItemP->getSyncOp()==sop_replace && fSessionP->fNoReplaceInSlowsync) {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Update of client item suppressed because of <noreplaceinslowsync>"));
matchingItemP->setSyncOp(sop_none); // just in case...
dontSendItemAsServer(matchingItemP);
}
else {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Update of client item enabled (will be sent later)"));
}
}
// - check if server must be updated (NEVER for fReadOnly)
if (!fReadOnly && needserverupdate && aSyncItemP) {
// update server
// - update server side (NOTE: processItemAsServer takes ownership, pointer gets invalid!)
fLocalItemsUpdated++;
aSyncItemP->setSyncOp(sop_replace);
remainsvisible=true; // should remain visible
matchingok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // replace item in local database NOW
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Updated server item"));
}
else {
// - delete incoming item unprocessed (if not already deleted)
if (aSyncItemP) delete aSyncItemP;
}
// check if we need to actively delete item from the client as it falls out of the filter
if (!remainsvisible && fSessionP->getSyncMLVersion()>=syncml_vers_1_2) {
// -> cause item to be deleted on remote
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("Slow sync matched item no longer visible in syncset -> returning delete to remote"));
goto removefromremoteandsyncset;
}
ok=matchingok;
break;
}
else {
PDEBUGPRINTFX(DBG_DATA+DBG_HOT,("No matching item found - add it to local database"));
// this item is not yet on the server, add it normally
aStatusCommand.setStatusCode(201); // item added (if no error occurs)
if (fReadOnly) {
delete aSyncItemP; // we don't need it
PDEBUGPRINTFX(DBG_DATA,("Read-Only: slow-sync add/replace command silently discarded"));
ok=true;
break;
}
if (fPreventAdd) goto preventadd;
fLocalItemsAdded++;
aSyncItemP->setSyncOp(sop_add); // set correct op
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // add to local database NOW
break;
}
} // slow sync
break; // just in case....
preventadd:
// add not allowed, delete remote item instead
// - consume original
delete aSyncItemP;
preventadd2:
aStatusCommand.setStatusCode(201); // pretend adding item was successful
PDEBUGPRINTFX(DBG_DATA,("Prevented explicit add, returning delete to remote"));
ok=true;
goto removefromremote; // as we have PREVENTED adding the item, it is not in the map
removefromremoteandsyncset:
// remove item from local map first
engProcessMap(remoteid.c_str(),NULL);
removefromremote:
// have item removed from remote
delitemP = newItemForRemote(itemtypeid);
delitemP->setRemoteID(remoteid.c_str());
delitemP->setSyncOp(sop_delete);
SendItemAsServer(delitemP); // pass ownership
break;
default :
SYSYNC_THROW(TSyncException("Unknown sync op in TLocalEngineDS::processRemoteItemAsServer"));
} // switch
if (ok) {
DB_PROGRESS_EVENT(this,pev_itemprocessed,fLocalItemsAdded,fLocalItemsUpdated,fLocalItemsDeleted);
}
else {
// if the DB has a error string to show, add it here
aStatusCommand.addItemString(lastDBErrorText().c_str());
}
// done
return ok;
} // TLocalEngineDS::engProcessRemoteItemAsServer
/// @brief called at end of request processing, should be used to save suspend state
/// @note superdatastore does it itself to have correct order of things happening
void TLocalEngineDS::engRequestEnded(void)
{
#ifdef SUPERDATASTORES
if (fAsSubDatastoreOf)
return;
#endif
// If DS 1.2: Make sure everything is ready for a resume in case there's an abort (implicit Suspend)
// before the next request. Note that the we cannot wait for session timeout, as the resume attempt
// from the client probably arrives much earlier.
// Note: It is ESSENTIAL not to save the state until sync set is ready, because saving state will
// cause DB access, and DB access is not permitted while sync set is possibly still loading
// (possibly in a separate thread!). So dssta_syncmodestable (as in <=3.0.0.2) is NOT enough here!
if (testState(dssta_syncsetready)) {
// make sure all unsent items are marked for resume
engSaveSuspendState(false); // only if not already aborted
}
// let datastore prepare for end of request
dsRequestEnded();
// and let it prepare for end of this thread as well
dsThreadMayChangeNow();
} // TLocalEngineDS::engRequestEnded
#endif // SYSYNC_SERVER
#ifdef SYSYNC_CLIENT
// Client Case
// ===========
// process sync operation from server with specified sync item
// (according to current sync mode of local datastore)
// - returns true (and unmodified or non-200-successful status) if
// operation could be processed regularily
// - returns false (but probably still successful status) if
// operation was processed with internal irregularities, such as
// trying to delete non-existant item in datastore with
// incomplete Rollbacks (which returns status 200 in this case!).
bool TLocalEngineDS::engProcessRemoteItemAsClient(
TSyncItem *aSyncItemP,
TStatusCommand &aStatusCommand // status, must be set to correct status code (ok / error)
)
{
string remoteid,localid;
bool ok;
bool remainsvisible;
// send event and check for user abort
#ifdef PROGRESS_EVENTS
if (!DB_PROGRESS_EVENT(this,pev_itemreceived,++fItemsReceived,fRemoteNumberOfChanges,0)) {
fSessionP->AbortSession(500,true,LOCERR_USERABORT); // this also causes datastore to be aborted
}
if (!SESSION_PROGRESS_EVENT(fSessionP,pev_suspendcheck,NULL,0,0,0)) {
fSessionP->SuspendSession(LOCERR_USERSUSPEND);
}
#endif
// check if datastore is aborted
if (CheckAborted(aStatusCommand)) return false;
// init behaviour vars (these are normally used by server only,
// but must be initialized correctly for client as well as descendants might test them
fPreventAdd = false;
fIgnoreUpdate = false;
// get operation out of item
TSyncOperation syncop=aSyncItemP->getSyncOp();
// show
DEBUGPRINTFX(DBG_DATA,("%s item operation received",SyncOpNames[syncop]));
// check if receiving commands is allowed at all
// - must be in correct sync state
if (!testState(dssta_syncgendone)) {
// Modifications from server not allowed before client has done sync gen
// %%% we could possibly relax this one, depending on the DB
aStatusCommand.setStatusCode(403);
PDEBUGPRINTFX(DBG_ERROR,("Server command not allowed before client has sent entire <sync>"));
delete aSyncItemP;
return false;
}
// - must not be one-way
if (fSyncMode==smo_fromclient) {
// Modifications from server not allowed during update from client only
aStatusCommand.setStatusCode(403);
ADDDEBUGITEM(aStatusCommand,"Server command not allowed in one-way/refresh from client");
PDEBUGPRINTFX(DBG_ERROR,("Server command not allowed in one-way/refresh from client"));
delete aSyncItemP;
return false;
}
else {
// silently discard all modifications if readonly
if (fReadOnly) {
PDEBUGPRINTFX(DBG_ERROR,("Read-Only: silently discarding all modifications"));
aStatusCommand.setStatusCode(200); // always ok (but never "added"), so server cannot expect Map
delete aSyncItemP;
return true;
}
// let item check itself to catch special cases
// - init variables which are used/modified by item checking
fItemSizeLimit=-1; // no limit
fCurrentSyncOp = syncop;
fEchoItemOp = sop_none;
fItemConflictStrategy=fSessionConflictStrategy; // get default strategy for this item
fForceConflict = false;
fDeleteWins = fDSConfigP->fDeleteWins; // default to configured value
fRejectStatus = -1; // no rejection
// - now check
// check reads and possibly modifies:
// - fEchoItemOp : if not sop_none, the incoming item is echoed back to the remote with the specified syncop
// - fItemConflictStrategy : might be changed from the pre-set datastore default
// - fForceConflict : if set, a conflict is forced by adding the corresponding local item (if any) to the list of items to be sent
// - fDeleteWins : if set, in a replace/delete conflict delete will win (regardless of strategy)
// - fPreventAdd : if set, attempt to add item from remote (even implicitly trough replace) will cause no add but delete of remote item
// - fIgnoreUpdate : if set, attempt to update item from remote will be ignored, only adds (also implicit ones) are executed
// - fRejectStatus : if set>=0, incoming item is irgnored silently(==0) or with error(!=0)
aSyncItemP->checkItem(this);
// - check if incoming item should be processed at all
if (fRejectStatus>=0) {
// now discard the incoming item
delete aSyncItemP;
PDEBUGPRINTFX(fRejectStatus>=400 ? DBG_ERROR : DBG_DATA,("Item rejected with Status=%hd",fRejectStatus));
if (fRejectStatus>0) {
// rejected with status code (not necessarily error)
aStatusCommand.setStatusCode(fRejectStatus);
if (fRejectStatus>=300) {
// non 200-codes are errors
ADDDEBUGITEM(aStatusCommand,"Item rejected");
return false;
}
}
// silently rejected
return true;
}
// now perform requested operation
switch (syncop) {
case sop_soft_delete:
case sop_archive_delete:
case sop_delete:
// delete item
fLocalItemsDeleted++;
remainsvisible=false; // deleted not visible any more
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible); // delete in local database NOW
break;
case sop_copy:
// %%% note: this would belong into specific datastore implementation, but is here
// now for simplicity as copy isn't used heavily het
// retrieve data from local datastore
if (!logicRetrieveItemByID(*aSyncItemP,aStatusCommand)) {
ok=false;
break;
}
// process like add
case sop_add:
// add as new item to client DB
aStatusCommand.setStatusCode(201); // item added (if no error occurs)
fLocalItemsAdded++;
// add to local datastore
// - get remoteid BEFORE processing item (as logicProcessRemoteItem consumes the item!!)
remoteid=aSyncItemP->getRemoteID(); // get remote ID
// check if this remoteid is already known from last session - if so, this means that
// this add was re-sent and must NOT be executed
if (isAddFromLastSession(remoteid.c_str())) {
aStatusCommand.setStatusCode(418); // already exists
PDEBUGPRINTFX(DBG_ERROR,("Warning: Item with same server-side ID (GUID) was already added in previous session - ignore add now"));
delete aSyncItemP; // forget item
ok=false;
break;
}
#ifdef OBJECT_FILTERING
if (!isAcceptable(aSyncItemP,aStatusCommand)) {
delete aSyncItemP; // forget item
ok=false; // cannot be accepted
break;
}
#endif
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible,&localid); // add to local database NOW, get back local GUID
if (!ok) break;
// if added (not replaced), we need to send map
if (aStatusCommand.getStatusCode()==201) {
// really added: remember map entry
DEBUGPRINTFX(DBG_ADMIN+DBG_DETAILS,(
"engProcessRemoteItemAsClient: add command: adding new entry to fPendingAddMaps - localid='%s', remoteID='%s'",
localid.c_str(),
remoteid.c_str()
));
fPendingAddMaps[localid]=remoteid;
}
ok=true; // fine
break;
case sop_replace:
// - replace item in client
fLocalItemsUpdated++;
aSyncItemP->setSyncOp(sop_replace);
#ifdef OBJECT_FILTERING
if (!isAcceptable(aSyncItemP,aStatusCommand)) {
ok=false; // cannot be accepted
break;
}
#endif
// - get remoteid BEFORE processing item (as logicProcessRemoteItem consumes the item!!),
// in case replace is converted to add and we need to register a map entry.
remoteid=aSyncItemP->getRemoteID(); // get remote ID
remainsvisible=true; // should remain visible
ok=logicProcessRemoteItem(aSyncItemP,aStatusCommand,remainsvisible,&localid); // replace in local database NOW
// if added (not replaced), we need to send map
if (aStatusCommand.getStatusCode()==201) {
// Note: logicProcessRemoteItem should NOT do an add if we have no remoteid, but return 404.
// The following check is just additional security.
// really added: remember map entry if server sent remoteID (normally, it won't for Replace)
if (!remoteid.empty()) {
// we can handle that, as remote sent us the remoteID we need to map it correctly
DEBUGPRINTFX(DBG_ADMIN+DBG_DETAILS,(
"engProcessRemoteItemAsClient: replace command for unknown localID but with remoteID -> adding new entry to fPendingAddMaps - localid='%s', remoteID='%s'",
localid.c_str(),
remoteid.c_str()
));
fPendingAddMaps[localid]=remoteid;
}
else {
// we cannot handle this (we shouldn't have, in logicProcessRemoteItem!!)
aStatusCommand.setStatusCode(510);
ok=false;
}
}
break; // fine, ok = irregularity status
default:
SYSYNC_THROW(TSyncException("Unknown sync op in TLocalEngineDS::processRemoteItemAsClient"));
} // switch
// processed
if (ok) {
DB_PROGRESS_EVENT(this,pev_itemprocessed,fLocalItemsAdded,fLocalItemsUpdated,fLocalItemsDeleted);
}
else {
// if the DB has a error string to show, add it here
aStatusCommand.addItemString(lastDBErrorText().c_str());
}
return ok;
}
} // TLocalEngineDS::processRemoteItemAsClient
// client case: called whenever outgoing Message of Sync Package starts
void TLocalEngineDS::engClientStartOfSyncMessage(void)
{
// is called for all local datastores, even inactive ones, so check state first
if (testState(dssta_dataaccessstarted) && !isAborted()) {
// only alerted non-sub datastores will start a <sync> command here, ONCE
// if there are pending maps, they will be sent FIRST
if (fRemoteDatastoreP) {
if (!testState(dssta_clientsyncgenstarted)) {
// shift state to syncgen started
// NOTE: if all sync commands can be sent at once,
// state will change again by issuing <sync>, so
// it MUST be changed here (not after issuing!)
changeState(dssta_clientsyncgenstarted,true);
// - make sure remotedatastore has correct full name
fRemoteDatastoreP->setFullName(getRemoteDBPath());
// an interrupted command at this point is a map command - continueIssue() will take care
if (!fSessionP->isInterrupedCmdPending() && numUnsentMaps()>0) {
// Check for pending maps from previous session (even in DS 1.0..1.1 case this is possible)
fUnconfirmedMaps.clear(); // no unconfirmed maps left...
fLastSessionMaps.clear(); // ...and no lastSessionMaps yet: all are in pendingMaps
// if this is a not-resumed slow sync, pending maps must not be sent, but discarded
if (isSlowSync() && !isResuming()) {
// forget the pending maps
PDEBUGPRINTFX(DBG_HOT,("There are %ld cached map entries from last Session, but this is a non-resumed slow sync: discard them",(long)numUnsentMaps()));
fPendingAddMaps.clear();
}
else {
// - now sending pending (cached) map commands from previous session
// Note: if map command was already started, the
// finished(), continueIssue() mechanism will make sure that
// more commands are generated. This mechanism will also make
// sure that outgoing package cannot get <final/> until
// map is completely sent.
// Note2: subdatastores do not generate their own map commands,
// but are called by superdatastore for contributing to united map
if (!isSubDatastore()) {
PDEBUGBLOCKFMT(("LastSessionMaps","Now sending cached map entries from last Session","datastore=%s",getName()));
TMapCommand *mapcmdP =
new TMapCommand(
fSessionP,
this, // local datastore
fRemoteDatastoreP // remote datastore
);
// issue
ISSUE_COMMAND_ROOT(fSessionP,mapcmdP);
PDEBUGENDBLOCK("LastSessionMaps");
}
}
}
// Now, send sync command (unless we are a subdatastore, in this case the superdatastore will take care)
if (!isSubDatastore()) {
// Note: if sync command was already started, the
// finished(), continueIssue() mechanism will make sure that
// more commands are generated
// Note2: subdatastores do not generate their own sync commands,
// but switch to dssta_client/serversyncgenstarted for contributing to united sync command
TSyncCommand *synccmdP =
new TSyncCommand(
fSessionP,
this, // local datastore
fRemoteDatastoreP // remote datastore
);
// issue
ISSUE_COMMAND_ROOT(fSessionP,synccmdP);
}
}
}
else {
PDEBUGPRINTFX(DBG_ERROR,("engClientStartOfSyncMessage can't start sync phase - missing remotedatastore"));
changeState(dssta_idle,true); // force to idle, nothing happened yet
}
} // if dsssta_dataaccessstarted and not aborted
} // TLocalEngineDS::engClientStartOfSyncMessage
// Client only: returns number of unsent map items
sInt32 TLocalEngineDS::numUnsentMaps(void)
{
return fPendingAddMaps.size();
} // TLocalEngineDS::numUnsentMaps
// Client only: called whenever outgoing Message starts that may contain <Map> commands
// @param[in] aNotYetInMapPackage set if we are still in sync-from-server package
// @note usually, client starts sending maps while still receiving syncops from server
void TLocalEngineDS::engClientStartOfMapMessage(bool aNotYetInMapPackage)
{
// is called for all local datastores, even inactive ones, so check state first
if (testState(dssta_syncgendone) && !isAborted()) {
// datastores that have finished generating their <sync>
// now can start a <map> command here, once (if not isInterrupedCmdPending(), that is, not a map already started)
if (fRemoteDatastoreP) {
// start a new map command if we don't have any yet and we are not done (dssta_clientmapssent) yet
if (!fSessionP->isInterrupedCmdPending() && !testState(dssta_clientmapssent)) {
// check if we should start one (that is, if the list is not empty)
if (numUnsentMaps()>0) {
// - now sending map command
// NOTE: if all map commands can be sent at once,
// fState will be modified again by issuing <map>, so
// it MUST be set here (not after issuing!)
// - data access done only if we are in Map package now
if (!aNotYetInMapPackage)
changeState(dssta_dataaccessdone); // usually already set in engEndOfSyncFromRemote(), but does not harm here
// Note: if map command was already started, the
// finished(), continueIssue() mechanism will make sure that
// more commands are generated. This mechanism will also make
// sure that outgoing package cannot get <final/> until
// map is completely sent.
// Note2: subdatastores do not generate their own map commands,
// but superdatastore calls their generateMapItem for contributing to united map
if (!isSubDatastore()) {
TMapCommand *mapcmdP =
new TMapCommand(
fSessionP,
this, // local datastore
fRemoteDatastoreP // remote datastore
);
// issue
ISSUE_COMMAND_ROOT(fSessionP,mapcmdP);
}
}
else {
// we need no map items now, but if this is still sync-from-server-package,
// we are not done yet
if (aNotYetInMapPackage) {
DEBUGPRINTFX(DBG_PROTO,("No map command need to be generated now, but still in <sync> from server package"));
}
else {
// we are done now
DEBUGPRINTFX(DBG_PROTO,("All map commands sending complete"));
changeState(dssta_clientmapssent);
}
}
}
} // if fRemoteDataStoreP
} // if >=dssta_syncgendone
} // TLocalEngineDS::engClientStartOfMapMessage
// called to mark maps confirmed, that is, we have received ok status for them
void TLocalEngineDS::engMarkMapConfirmed(cAppCharP aLocalID, cAppCharP aRemoteID)
{
// As this is client-only, we don't need to check for tempGUIDs here.
// Note: superdatastore has an implementation which dispatches by prefix
TStringToStringMap::iterator pos=fUnconfirmedMaps.find(aLocalID);
if (pos!=fUnconfirmedMaps.end()) {
DEBUGPRINTFX(DBG_ADMIN+DBG_EXOTIC,(
"engMarkMapConfirmed: deleting confirmed entry localID='%s', remoteID='%s' from fUnconfirmedMaps",
aLocalID,
aRemoteID
));
// move it to lastsessionmap
fLastSessionMaps[(*pos).first]=(*pos).second;
// remove it from unconfirmed map
fUnconfirmedMaps.erase(pos);
}
} // TLocalEngineDS::engMarkMapConfirmed
// Check if the remoteid was used by an add command not
// fully mapped&confirmed in the previous session
bool TLocalEngineDS::isAddFromLastSession(cAppCharP aRemoteID)
{
TStringToStringMap::iterator pos;
TStringToStringMap *mapListP;
for (int i=0; i<3; i++) {
// determine next list to search
mapListP = i==0 ? &fPendingAddMaps : (i==1 ? &fUnconfirmedMaps : &fLastSessionMaps);
// search it
for (pos=mapListP->begin(); pos!=mapListP->end(); ++pos) {
if (strcmp((*pos).second.c_str(),aRemoteID)==0)
return true; // remoteID known -> is add from last session
}
}
// not found in any of the lists
return false;
} // TLocalEngineDS::isAddFromLastSession
// - called to generate Map items
// Returns true if now finished for this datastore
// also sets fState to dss_done when finished
bool TLocalEngineDS::engGenerateMapItems(TMapCommand *aMapCommandP, cAppCharP aLocalIDPrefix)
{
#ifdef USE_SML_EVALUATION
sInt32 leavefree = fSessionP->getNotUsableBufferBytes();
#else
sInt32 freeroom = fSessionP->getFreeCommandSize();
#endif
TStringToStringMap::iterator pos=fPendingAddMaps.begin();
PDEBUGBLOCKFMT(("MapGenerate","Generating Map items...","datastore=%s",getName()));
do {
// check if already done
if (pos==fPendingAddMaps.end()) break; // done
// get ID
string locID = (*pos).first;
dsFinalizeLocalID(locID); // make sure we have the permanent version in case datastore implementation did deliver temp IDs
// create prefixed version of ID
string prefixedLocID;
AssignString(prefixedLocID, aLocalIDPrefix); // init with prefix (if any)
prefixedLocID += locID; // append local ID
// add it to map command
aMapCommandP->addMapItem(prefixedLocID.c_str(),(*pos).second.c_str());
// check if we could send this command
#ifdef USE_SML_EVALUATION
if (
(aMapCommandP->evalIssue(
fSessionP->peekNextOutgoingCmdID(),
fSessionP->getOutgoingMsgID()
) // what is left in buffer after sending Map so far
>=leavefree) // all this must still be more than what we MUST leave free
)
#else
if (freeroom>aMapCommandP->messageSize())
#endif
{
// yes, it should work
PDEBUGPRINTFX(DBG_PROTO,(
"Mapitem generated: localID='%s', remoteID='%s'",
prefixedLocID.c_str(),
(*pos).second.c_str()
));
// move sent ones to unconfirmed list (Note: use real locID, without prefix!)
fUnconfirmedMaps[locID]=(*pos).second;
// remove item from to-be-sent list
TStringToStringMap::iterator temp_pos = pos++; // make copy and set iterator to next
fPendingAddMaps.erase(temp_pos); // now entry can be deleted (N.M. Josuttis, pg204)
}
else {
// no room for this item in this message, interrupt now
// - delete already added item again
aMapCommandP->deleteLastMapItem();
// - interrupt here
PDEBUGPRINTFX(DBG_PROTO,("Interrupted generating Map items because max message size reached"))
PDEBUGENDBLOCK("MapGenerate");
return false;
}
} while(true);
// done
// if we are dataaccessdone or more -> end of map phase for this datastore
if (testState(dssta_dataaccessdone)) {
changeState(dssta_clientmapssent,true);
PDEBUGPRINTFX(DBG_PROTO,("Finished generating Map items, server has finished <sync>, we are done now"))
}
#ifdef SYDEBUG
// else if we are not yet dssta_syncgendone -> this is the end of a early pending map send
else if (!dbgTestState(dssta_syncgendone)) {
PDEBUGPRINTFX(DBG_PROTO,("Finished sending cached Map items from last session"))
}
// otherwise, we are not really finished with the maps yet (but with the current map command)
else {
PDEBUGPRINTFX(DBG_PROTO,("Finished generating Map items for now, but server still sending <Sync>"))
}
#endif
PDEBUGENDBLOCK("MapGenerate");
return true;
} // TLocalEngineDS::engGenerateMapItems
#endif // SYSYNC_SERVER
// - called to mark an already generated (but probably not sent or not yet statused) item
// as "to-be-resumed", by localID or remoteID (latter only in server case).
// NOTE: This must be repeatable without side effects, as server must mark/save suspend state
// after every request (and not just at end of session)
void TLocalEngineDS::engMarkItemForResume(cAppCharP aLocalID, cAppCharP aRemoteID, bool aUnSent)
{
#ifdef SUPERDATASTORES
// if we are acting as a subdatastore, aLocalID might be prefixed
if (fAsSubDatastoreOf && aLocalID) {
// remove prefix
aLocalID = fAsSubDatastoreOf->removeSubDSPrefix(aLocalID, this);
}
#endif
#ifdef SYSYNC_SERVER
// Now mark for resume
if (IS_SERVER && aLocalID && *aLocalID) {
// localID can be a translated localid at this point (for adds), so check for it
string localid=aLocalID;
obtainRealLocalID(localid);
logicMarkItemForResume(localid.c_str(), aRemoteID, aUnSent);
}
else
#endif
{
// localID not used or client (which never has tempGUIDs)
logicMarkItemForResume(aLocalID, aRemoteID, aUnSent);
}
} // TLocalEngineDS::engMarkItemForResume
// - called to mark an already generated (but probably not sent or not yet statused) item
// as "to-be-resent", by localID or remoteID (latter only in server case).
void TLocalEngineDS::engMarkItemForResend(cAppCharP aLocalID, cAppCharP aRemoteID)
{
#ifdef SUPERDATASTORES
// if we are acting as a subdatastore, aLocalID might be prefixed
if (fAsSubDatastoreOf && aLocalID) {
// remove prefix
aLocalID = fAsSubDatastoreOf->removeSubDSPrefix(aLocalID, this);
}
#endif
// a need to resend is always a problem with the remote (either explicit non-ok status
// received or implicit like data size too big to be sent at all due to maxmsgsize or
// maxobjsize restrictions.
fRemoteItemsError++;
// now mark for resend
#ifdef SYSYNC_SERVER
if (IS_SERVER && aLocalID && *aLocalID) {
// localID can be a translated localid at this point (for adds), so check for it
string localid=aLocalID;
obtainRealLocalID(localid);
logicMarkItemForResend(localid.c_str(), aRemoteID);
}
else
#endif
{
// localID not used or client (which never has tempGUIDs)
logicMarkItemForResend(aLocalID, aRemoteID);
}
} // TLocalEngineDS::engMarkItemForResend
// @brief save everything needed to resume later, in case we get suspended
/// - Might be called multiple times during a session, must make sure every time
/// that the status is correct, that is, previous suspend state is erased
localstatus TLocalEngineDS::engSaveSuspendState(bool aAnyway)
{
// only save here if not aborted already (aborting saves the state immediately)
// or explicitly requested
if (aAnyway || !isAborted()) {
// only save if DS 1.2 and supported by DB
if ((fSessionP->getSyncMLVersion()>=syncml_vers_1_2) && dsResumeSupportedInDB()) {
PDEBUGBLOCKFMT(("SaveSuspendState","Saving state for suspend/resume","datastore=%s",getName()));
// save alert state (if not explicitly prevented)
fResumeAlertCode=fPreventResuming ? 0 : fAlertCode;
if (fResumeAlertCode) {
if (fPartialItemState!=pi_state_save_outgoing) {
// ONLY if we have no request for saving an outgoing item state already,
// we possibly need to save a pending incoming item
// if there is an incompletely received item, let it update Partial Item (fPIxxx) state
// (if it is an item of this datastore, that is).
if (fSessionP->fIncompleteDataCommandP)
fSessionP->fIncompleteDataCommandP->updatePartialItemState(this);
}
// this makes sure that only ungenerated (but to-be generated) items will be
// marked for resume. Items that have been generated in this session (but might
// have been marked for resume in a previous session must no longer be marked
// after this call.
// This also includes saving state for a partially sent item so we could resume it (fPIxxx)
logicMarkOnlyUngeneratedForResume();
// then, we need to additionally mark those items for resume which have been
// generated, but not yet sent or sent but not received status so far.
fSessionP->markPendingForResume(this);
}
// let datastore make all this persistent
// NOTE: this must happen even if we have no suspend state here,
// as marked-for-resends need to be saved here as well.
localstatus sta=logicSaveResumeMarks();
if (sta!=LOCERR_OK) {
PDEBUGPRINTFX(DBG_ERROR,("Error saving suspend state with logicSaveResumeMarks(), status=%hd",sta));
}
PDEBUGENDBLOCK("SaveSuspendState");
return sta;
}
// resume not supported due to datastore or SyncML version<1.2 -> ok anyway
PDEBUGPRINTFX(DBG_PROTO,("SaveSuspendState not possible (SyncML<1.2 or not supported by DB)"));
}
return LOCERR_OK;
} // TLocalEngineDS::engSaveSuspendState
} // namespace sysync
/* end of TLocalEngineDS implementation */
// eof
|