summaryrefslogtreecommitdiff
path: root/bin/bbackupd/BackupDaemon.cpp
blob: 88518ae2312e739ba9bb0764f13f26f56406fc8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
// --------------------------------------------------------------------------
//
// File
//		Name:    BackupDaemon.cpp
//		Purpose: Backup daemon
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------

#include "Box.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif
#ifdef HAVE_SIGNAL_H
	#include <signal.h>
#endif
#ifdef HAVE_SYS_PARAM_H
	#include <sys/param.h>
#endif
#ifdef HAVE_SYS_WAIT_H
	#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
	#include <sys/mount.h>
#endif
#ifdef HAVE_MNTENT_H
	#include <mntent.h>
#endif 
#ifdef HAVE_SYS_MNTTAB_H
	#include <cstdio>
	#include <sys/mnttab.h>
#endif
#ifdef HAVE_PROCESS_H
	#include <process.h>
#endif

#include <iostream>
#include <set>
#include <sstream>

#include "Configuration.h"
#include "IOStream.h"
#include "MemBlockStream.h"
#include "CommonException.h"
#include "BoxPortsAndFiles.h"

#include "SSLLib.h"

#include "autogen_BackupProtocol.h"
#include "autogen_ClientException.h"
#include "autogen_ConversionException.h"
#include "Archive.h"
#include "BackupClientContext.h"
#include "BackupClientCryptoKeys.h"
#include "BackupClientDirectoryRecord.h"
#include "BackupClientFileAttributes.h"
#include "BackupClientInodeToIDMap.h"
#include "BackupClientMakeExcludeList.h"
#include "BackupDaemon.h"
#include "BackupDaemonConfigVerify.h"
#include "BackupStoreConstants.h"
#include "BackupStoreDirectory.h"
#include "BackupStoreException.h"
#include "BackupStoreFile.h"
#include "BackupStoreFilenameClear.h"
#include "BannerText.h"
#include "Conversion.h"
#include "ExcludeList.h"
#include "FileStream.h"
#include "IOStreamGetLine.h"
#include "LocalProcessStream.h"
#include "Logging.h"
#include "Random.h"
#include "Timer.h"
#include "Utils.h"

#ifdef WIN32
	#include "Win32ServiceFunctions.h"
	#include "Win32BackupService.h"

	extern Win32BackupService* gpDaemonService;

#	ifdef ENABLE_VSS
#		include <comdef.h>
#		include <Vss.h>
#		include <VsWriter.h>
#		include <VsBackup.h>
		
		// http://www.flounder.com/cstring.htm
		std::string GetMsgForHresult(HRESULT hr)
		{
			std::ostringstream buf;

			if(hr == VSS_S_ASYNC_CANCELLED)
			{
				buf << "VSS async operation cancelled";
			}
			else if(hr == VSS_S_ASYNC_FINISHED)
			{
				buf << "VSS async operation finished";
			}
			else if(hr == VSS_S_ASYNC_PENDING)
			{
				buf << "VSS async operation pending";
			}
			else
			{
				buf << _com_error(hr).ErrorMessage();
			}
			
			buf << " (" << BOX_FORMAT_HEX32(hr) << ")";
			return buf.str();
		}

		std::string WideStringToString(WCHAR *buf)
		{
			if (buf == NULL)
			{
				return "(null)";
			}

			char* pStr = ConvertFromWideString(buf, CP_UTF8);
			
			if(pStr == NULL)
			{
				return "(conversion failed)";
			}
			
			std::string result(pStr);
			free(pStr);
			return result;
		}

		std::string GuidToString(GUID guid)
		{
			wchar_t buf[64];
			StringFromGUID2(guid, buf, sizeof(buf));
			return WideStringToString(buf);
		}

		std::string BstrToString(const BSTR arg)
		{
			if(arg == NULL)
			{
				return std::string("(null)");
			}
			else
			{
				// Extract the *long* before where the arg points to
				long len = ((long *)arg)[-1] / 2;
				std::wstring wstr((WCHAR *)arg, len);
				std::string str;
				if(!ConvertFromWideString(wstr, &str, CP_UTF8))
				{
					throw std::exception("string conversion failed");
				}
				return str;
			}
		}
#	endif
#endif

#include "MemLeakFindOn.h"

static const time_t MAX_SLEEP_TIME = 1024;

// Make the actual sync period have a little bit of extra time, up to a 64th of the main sync period.
// This prevents repetative cycles of load on the server
#define		SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY	6

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::BackupDaemon()
//		Purpose: constructor
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::BackupDaemon()
	: mState(BackupDaemon::State_Initialising),
	  mDeleteRedundantLocationsAfter(0),
	  mLastNotifiedEvent(SysadminNotifier::MAX),
	  mDeleteUnusedRootDirEntriesAfter(0),
	  mClientStoreMarker(BackupClientContext::ClientStoreMarker_NotKnown),
	  mStorageLimitExceeded(false),
	  mReadErrorsOnFilesystemObjects(false),
	  mLastSyncTime(0),
	  mNextSyncTime(0),
	  mCurrentSyncStartTime(0),
	  mUpdateStoreInterval(0),
	  mDeleteStoreObjectInfoFile(false),
	  mDoSyncForcedByPreviousSyncError(false),
	  mNumFilesUploaded(-1),
	  mNumDirsCreated(-1),
	  mMaxBandwidthFromSyncAllowScript(0),
	  mLogAllFileAccess(false),
	  mpProgressNotifier(this),
	  mpLocationResolver(this),
	  mpRunStatusProvider(this),
	  mpSysadminNotifier(this)
	#ifdef WIN32
	, mInstallService(false),
	  mRemoveService(false),
	  mRunAsService(false),
	  mServiceName("bbackupd")
	#endif
#ifdef ENABLE_VSS
	, mpVssBackupComponents(NULL)
#endif
{
	// Only ever one instance of a daemon
	SSLLib::Initialise();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::~BackupDaemon()
//		Purpose: Destructor
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::~BackupDaemon()
{
	DeleteAllLocations();
	DeleteAllIDMaps();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DaemonName()
//		Purpose: Get name of daemon
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
const char *BackupDaemon::DaemonName() const
{
	return "bbackupd";
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DaemonBanner()
//		Purpose: Daemon banner
//		Created: 1/1/04
//
// --------------------------------------------------------------------------
std::string BackupDaemon::DaemonBanner() const
{
	return BANNER_TEXT("Backup Client");
}

void BackupDaemon::Usage()
{
	this->Daemon::Usage();

#ifdef WIN32
	std::cout <<
	"  -s         Run as a Windows Service, for internal use only\n"
	"  -i         Install Windows Service (you may want to specify a config file)\n"
	"  -r         Remove Windows Service\n"
	"  -S <name>  Service name for -i and -r options\n";
#endif
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::GetConfigVerify()
//		Purpose: Get configuration specification
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
const ConfigurationVerify *BackupDaemon::GetConfigVerify() const
{
	// Defined elsewhere
	return &BackupDaemonConfigVerify;
}

#ifdef PLATFORM_CANNOT_FIND_PEER_UID_OF_UNIX_SOCKET
// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::SetupInInitialProcess()
//		Purpose: Platforms with non-checkable credentials on 
//			local sockets only.
//			Prints a warning if the command socket is used.
//		Created: 25/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::SetupInInitialProcess()
{
	// Print a warning on this platform if the CommandSocket is used.
	if(GetConfiguration().KeyExists("CommandSocket"))
	{
		BOX_WARNING(
			"==============================================================================\n"
			"SECURITY WARNING: This platform cannot check the credentials of connections to\n"
			"the command socket. This is a potential DoS security problem.\n"
			"Remove the CommandSocket directive from the bbackupd.conf file if bbackupctl\n"
			"is not used.\n"
			"==============================================================================\n"
			);
	}
}
#endif


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeleteAllLocations()
//		Purpose: Deletes all records stored
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::DeleteAllLocations()
{
	// Run through, and delete everything
	for(Locations::iterator i = mLocations.begin();
		i != mLocations.end(); ++i)
	{
		delete *i;
	}

	// Clear the contents of the map, so it is empty
	mLocations.clear();
	
	// And delete everything from the associated mount vector
	mIDMapMounts.clear();
}

#ifdef WIN32
std::string BackupDaemon::GetOptionString()
{
	std::string oldOpts = this->Daemon::GetOptionString();
	ASSERT(oldOpts.find("s") == std::string::npos);
	ASSERT(oldOpts.find("S") == std::string::npos);
	ASSERT(oldOpts.find("i") == std::string::npos);
	ASSERT(oldOpts.find("r") == std::string::npos);
	return oldOpts + "sS:ir";
}

int BackupDaemon::ProcessOption(signed int option)
{
	switch(option)
	{
		case 's':
		{
			mRunAsService = true;
			return 0;
		}

		case 'S':
		{
			mServiceName = optarg;
			Logging::SetProgramName(mServiceName);
			return 0;
		}

		case 'i':
		{
			mInstallService = true;
			return 0;
		}

		case 'r':
		{
			mRemoveService = true;
			return 0;
		}

		default:
		{
			return this->Daemon::ProcessOption(option);
		}
	}
}

int BackupDaemon::Main(const std::string &rConfigFileName)
{
	if (mInstallService)
	{
		return InstallService(rConfigFileName.c_str(), mServiceName);
	}

	if (mRemoveService)
	{
		return RemoveService(mServiceName);
	}

#ifdef ENABLE_VSS
	HRESULT result = CoInitialize(NULL);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to initialize COM: " << 
			GetMsgForHresult(result));
		return 1;
	}
#endif

	int returnCode;

	if (mRunAsService)
	{
		// We will be called reentrantly by the Service Control
		// Manager, and we had better not call OurService again!
		mRunAsService = false;

		BOX_INFO("Box Backup service starting");
		returnCode = OurService(rConfigFileName.c_str());
		BOX_INFO("Box Backup service shut down");
	}
	else
	{
		returnCode = this->Daemon::Main(rConfigFileName);
	}
	
	return returnCode;
}
#endif

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Run()
//		Purpose: Run function for daemon
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::Run()
{
	// initialise global timer mechanism
	Timers::Init();
	
	#ifndef WIN32
		// Ignore SIGPIPE so that if a command connection is broken,
		// the daemon doesn't terminate.
		::signal(SIGPIPE, SIG_IGN);
	#endif

	// Create a command socket?
	const Configuration &conf(GetConfiguration());
	if(conf.KeyExists("CommandSocket"))
	{
		// Yes, create a local UNIX socket
		mapCommandSocketInfo.reset(new CommandSocketInfo);
		const char *socketName =
			conf.GetKeyValue("CommandSocket").c_str();
		#ifdef WIN32
			mapCommandSocketInfo->mListeningSocket.Listen(
				socketName);
		#else
			::unlink(socketName);
			mapCommandSocketInfo->mListeningSocket.Listen(
				Socket::TypeUNIX, socketName);
		#endif
	}

	// Handle things nicely on exceptions
	try
	{
		Run2();
	}
	catch(...)
	{
		try 
		{
			mapCommandSocketInfo.reset();
		}
		catch(std::exception &e)
		{
			BOX_WARNING("Internal error while closing command "
				"socket after another exception, ignored: " <<
				e.what());
		}
		catch(...)
		{
			BOX_WARNING("Error closing command socket after "
				"exception, ignored.");
		}

		Timers::Cleanup();
		
		throw;
	}

	// Clean up
	mapCommandSocketInfo.reset();
	Timers::Cleanup();
}

void BackupDaemon::InitCrypto()
{
	// Read in the certificates creating a TLS context
	const Configuration &conf(GetConfiguration());
	std::string certFile(conf.GetKeyValue("CertificateFile"));
	std::string keyFile(conf.GetKeyValue("PrivateKeyFile"));
	std::string caFile(conf.GetKeyValue("TrustedCAsFile"));
	mTlsContext.Initialise(false /* as client */, certFile.c_str(),
		keyFile.c_str(), caFile.c_str());
	
	// Set up the keys for various things
	BackupClientCryptoKeys_Setup(conf.GetKeyValue("KeysFile"));
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Run2()
//		Purpose: Run function for daemon (second stage)
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::Run2()
{
	InitCrypto();

	const Configuration &conf(GetConfiguration());

	// How often to connect to the store (approximate)
	mUpdateStoreInterval = SecondsToBoxTime(
		conf.GetKeyValueInt("UpdateStoreInterval"));

	// But are we connecting automatically?
	bool automaticBackup = conf.GetKeyValueBool("AutomaticBackup");
	
	// When the next sync should take place -- which is ASAP
	mNextSyncTime = 0;

	// When the last sync started (only updated if the store was not full when the sync ended)
	mLastSyncTime = 0;

 	// --------------------------------------------------------------------------------------------
 
 	mDeleteStoreObjectInfoFile = DeserializeStoreObjectInfo(
		mLastSyncTime, mNextSyncTime);
 
	// --------------------------------------------------------------------------------------------
	

	// Set state
	SetState(State_Idle);

	mDoSyncForcedByPreviousSyncError = false;

	// Loop around doing backups
	do
	{
		// Flags used below
		bool storageLimitExceeded = false;
		bool doSync = false;
		bool mDoSyncForcedByCommand = false;

		box_time_t currentTime = GetCurrentBoxTime();

		// Check whether we should be stopping, and if so,
		// don't hang around waiting on the command socket.
		if(StopRun())
		{
			BOX_INFO("Skipping command socket polling "
				"due to shutdown request");
			break;
		}

		// Is a delay necessary?
		currentTime = GetCurrentBoxTime();
		box_time_t requiredDelay = (mNextSyncTime < currentTime)
				? (0) : (mNextSyncTime - currentTime);

		if (mDoSyncForcedByPreviousSyncError)
		{
			BOX_INFO("Last backup was not successful, "
				"next one starting at " <<
				FormatTime(mNextSyncTime, false));
		}
		else if (automaticBackup)
		{
			BOX_INFO("Automatic backups are enabled, "
				"next one starting at " <<
				FormatTime(mNextSyncTime, false));
		}
		else
		{
			BOX_INFO("No automatic backups, waiting for "
				"bbackupctl snapshot command");
			requiredDelay = SecondsToBoxTime(MAX_SLEEP_TIME);
		}

		if(requiredDelay > SecondsToBoxTime(MAX_SLEEP_TIME))
		{
			requiredDelay = SecondsToBoxTime(MAX_SLEEP_TIME);
		}

		// Only delay if necessary
		if(requiredDelay == 0)
		{
			// No sleep necessary, so don't listen on the command
			// socket at all right now.
		}
		else if(mapCommandSocketInfo.get() != 0)
		{
			// A command socket exists, so sleep by waiting for a
			// connection or command on it.
			WaitOnCommandSocket(requiredDelay, doSync,
				mDoSyncForcedByCommand);
		}
		else
		{
			// No command socket or connection, just do a normal
			// sleep.
			time_t sleepSeconds = 
				BoxTimeToSeconds(requiredDelay);
			::sleep((sleepSeconds <= 0)
				? 1 : sleepSeconds);
		}

		if(StopRun())
		{
			BOX_INFO("Stopping idle loop due to shutdown request");
			break;
		}
		else if(doSync)
		{
			BOX_INFO("Starting a backup immediately due to "
				"bbackupctl sync command");
		}
		else if(currentTime < mNextSyncTime)
		{
			BOX_TRACE("Sleeping again because next sync time "
				"has not arrived");
			continue;
		}
		else if(mDoSyncForcedByPreviousSyncError)
		{
			BOX_INFO("Last backup was not successful, next one "
				"starting now");
		}
		else if(automaticBackup)
		{
			BOX_INFO("Automatic backups are enabled, next one "
				"starting now");
		}
		else
		{
			BOX_TRACE("Sleeping again because automatic backups "
				"are not enabled");
			continue;
		}

		// If we pass this point, or exit the loop, we should have
		// logged something at INFO level or higher to explain why.

		// Use a script to see if sync is allowed now?
		if(mDoSyncForcedByCommand)
		{
			BOX_INFO("Skipping SyncAllowScript due to bbackupctl "
				"force-sync command");
		}
		else
		{
			int d = UseScriptToSeeIfSyncAllowed();
			if(d > 0)
			{
				// Script has asked for a delay
				mNextSyncTime = GetCurrentBoxTime() + 
					SecondsToBoxTime(d);
				BOX_INFO("Impending backup stopped by "
					"SyncAllowScript, next attempt "
					"scheduled for " <<
					FormatTime(mNextSyncTime, false));
				continue;
			}
		}

		RunSyncNowWithExceptionHandling();
		
		// Set state
		SetState(storageLimitExceeded?State_StorageLimitExceeded:State_Idle);
	}
	while(!StopRun());
	
	// Make sure we have a clean start next time round (if restart)
	DeleteAllLocations();
	DeleteAllIDMaps();
}

void BackupDaemon::RunSyncNowWithExceptionHandling()
{
	bool errorOccurred = false;
	int errorCode = 0, errorSubCode = 0;
	const char* errorString = "unknown";

	try
	{
		OnBackupStart();
		// Do sync
		RunSyncNow();
	}
	catch(BoxException &e)
	{
		errorOccurred = true;
		errorString = e.what();
		errorCode = e.GetType();
		errorSubCode = e.GetSubType();
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Internal error during backup run: " << e.what());
		errorOccurred = true;
		errorString = e.what();
	}
	catch(...)
	{
		// TODO: better handling of exceptions here...
		// need to be very careful
		errorOccurred = true;
	}

	// do not retry immediately without a good reason
	mDoSyncForcedByPreviousSyncError = false;

	// Is it a berkely db failure?
	bool isBerkelyDbFailure = false;

	// Notify system administrator about the final state of the backup
	if(errorOccurred)
	{
		if (errorCode == BackupStoreException::ExceptionType
			&& errorSubCode == BackupStoreException::BerkelyDBFailure)
		{
			isBerkelyDbFailure = true;
		}

		if(isBerkelyDbFailure)
		{
			// Delete corrupt files
			DeleteCorruptBerkelyDbFiles();
		}

		ResetCachedState();

		// Handle restart?
		if(StopRun())
		{
			BOX_NOTICE("Exception (" << errorCode
				<< "/" << errorSubCode 
				<< ") due to signal");
			OnBackupFinish();
			return;
		}

		NotifySysadmin(SysadminNotifier::BackupError);

		// If the Berkely db files get corrupted,
		// delete them and try again immediately.
		if(isBerkelyDbFailure)
		{
			BOX_ERROR("Berkely db inode map files corrupted, "
				"deleting and restarting scan. Renamed files "
				"and directories will not be tracked until "
				"after this scan.");
			::sleep(1);
		}
		else
		{
			// Not restart/terminate, pause and retry
			// Notify administrator
			SetState(State_Error);
			BOX_ERROR("Exception caught (" << errorString <<
				" " << errorCode << "/" << errorSubCode <<
				"), reset state and waiting to retry...");
			::sleep(10);
			mNextSyncTime = mCurrentSyncStartTime + 
				SecondsToBoxTime(100) +
				Random::RandomInt(mUpdateStoreInterval >> 
					SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY);
		}
	}

	if(mReadErrorsOnFilesystemObjects)
	{
		NotifySysadmin(SysadminNotifier::ReadError);
	}

	if(mStorageLimitExceeded)
	{
		NotifySysadmin(SysadminNotifier::StoreFull);
	}

	if (!errorOccurred && !mReadErrorsOnFilesystemObjects &&
		!mStorageLimitExceeded)
	{
		NotifySysadmin(SysadminNotifier::BackupOK);
	}
	
	// If we were retrying after an error, and this backup succeeded,
	// then now would be a good time to stop :-)
	mDoSyncForcedByPreviousSyncError = errorOccurred && !isBerkelyDbFailure;

	OnBackupFinish();
}

void BackupDaemon::ResetCachedState()
{
	// Clear state data
	// Go back to beginning of time
	mLastSyncTime = 0;
	mClientStoreMarker = BackupClientContext::ClientStoreMarker_NotKnown;	// no store marker, so download everything
	DeleteAllLocations();
	DeleteAllIDMaps();
}

void BackupDaemon::RunSyncNow()
{
	// Delete the serialised store object file,
	// so that we don't try to reload it after a
	// partially completed backup
	if(mDeleteStoreObjectInfoFile && !DeleteStoreObjectInfo())
	{
		BOX_ERROR("Failed to delete the StoreObjectInfoFile, "
			"backup cannot continue safely.");
		THROW_EXCEPTION(ClientException, 
			FailedToDeleteStoreObjectInfoFile);
	}

	// In case the backup throws an exception,
	// we should not try to delete the store info
	// object file again.
	mDeleteStoreObjectInfoFile = false;

	const Configuration &conf(GetConfiguration());

	std::auto_ptr<FileLogger> fileLogger;

	if (conf.KeyExists("LogFile"))
	{
		Log::Level level = Log::INFO;
		if (conf.KeyExists("LogFileLevel"))
		{
			level = Logging::GetNamedLevel(
				conf.GetKeyValue("LogFileLevel"));
		}
		fileLogger.reset(new FileLogger(conf.GetKeyValue("LogFile"),
			level));
	}

	std::string extendedLogFile;
	if (conf.KeyExists("ExtendedLogFile"))
	{
		extendedLogFile = conf.GetKeyValue("ExtendedLogFile");
	}
	
	if (conf.KeyExists("LogAllFileAccess"))
	{
		mLogAllFileAccess = conf.GetKeyValueBool("LogAllFileAccess");
	}
	
	// Then create a client context object (don't 
	// just connect, as this may be unnecessary)
	BackupClientContext clientContext
	(
		*mpLocationResolver, 
		mTlsContext, 
		conf.GetKeyValue("StoreHostname"),
		conf.GetKeyValueInt("StorePort"),
		conf.GetKeyValueUint32("AccountNumber"), 
		conf.GetKeyValueBool("ExtendedLogging"),
		conf.KeyExists("ExtendedLogFile"),
		extendedLogFile,
		*mpProgressNotifier,
		conf.GetKeyValueBool("TcpNice")
	);
		
	// The minimum age a file needs to be before it will be
	// considered for uploading
	box_time_t minimumFileAge = SecondsToBoxTime(
		conf.GetKeyValueInt("MinimumFileAge"));

	// The maximum time we'll wait to upload a file, regardless
	// of how often it's modified
	box_time_t maxUploadWait = SecondsToBoxTime(
		conf.GetKeyValueInt("MaxUploadWait"));
	// Adjust by subtracting the minimum file age, so is relative
	// to sync period end in comparisons
	if (maxUploadWait > minimumFileAge)
	{
		maxUploadWait -= minimumFileAge;
	}
	else
	{
		maxUploadWait = 0;
	}

	// Calculate the sync period of files to examine
	box_time_t syncPeriodStart = mLastSyncTime;
	box_time_t syncPeriodEnd = GetCurrentBoxTime() - minimumFileAge;

	if(syncPeriodStart >= syncPeriodEnd &&
		syncPeriodStart - syncPeriodEnd < minimumFileAge)
	{
		// This can happen if we receive a force-sync command less
		// than minimumFileAge after the last sync. Deal with it by
		// moving back syncPeriodStart, which should not do any
		// damage.
		syncPeriodStart = syncPeriodEnd - SecondsToBoxTime(1);
	}

	if(syncPeriodStart >= syncPeriodEnd)
	{
		BOX_ERROR("Invalid (negative) sync period: perhaps your clock "
			"is going backwards? (" << syncPeriodStart << " to " <<
			syncPeriodEnd << ")");
		THROW_EXCEPTION(ClientException, ClockWentBackwards);
	}

	// Check logic
	ASSERT(syncPeriodEnd > syncPeriodStart);
	// Paranoid check on sync times
	if(syncPeriodStart >= syncPeriodEnd) return;
	
	// Adjust syncPeriodEnd to emulate snapshot 
	// behaviour properly
	box_time_t syncPeriodEndExtended = syncPeriodEnd;

	// Using zero min file age?
	if(minimumFileAge == 0)
	{
		// Add a year on to the end of the end time,
		// to make sure we sync files which are 
		// modified after the scan run started.
		// Of course, they may be eligible to be 
		// synced again the next time round,
		// but this should be OK, because the changes 
		// only upload should upload no data.
		syncPeriodEndExtended += SecondsToBoxTime(
			(time_t)(356*24*3600));
	}

	// Set up the sync parameters
	BackupClientDirectoryRecord::SyncParams params(*mpRunStatusProvider,
		*mpSysadminNotifier, *mpProgressNotifier, clientContext, this);
	params.mSyncPeriodStart = syncPeriodStart;
	params.mSyncPeriodEnd = syncPeriodEndExtended;
	// use potentially extended end time
	params.mMaxUploadWait = maxUploadWait;
	params.mFileTrackingSizeThreshold = 
		conf.GetKeyValueInt("FileTrackingSizeThreshold");
	params.mDiffingUploadSizeThreshold = 
		conf.GetKeyValueInt("DiffingUploadSizeThreshold");
	params.mMaxFileTimeInFuture = 
		SecondsToBoxTime(conf.GetKeyValueInt("MaxFileTimeInFuture"));
	mNumFilesUploaded = 0;
	mNumDirsCreated = 0;

	if(conf.KeyExists("MaxUploadRate"))
	{
		params.mMaxUploadRate = conf.GetKeyValueInt("MaxUploadRate");
	}

	if(mMaxBandwidthFromSyncAllowScript != 0)
	{
		params.mMaxUploadRate = mMaxBandwidthFromSyncAllowScript;
	}

	mDeleteRedundantLocationsAfter =
		conf.GetKeyValueInt("DeleteRedundantLocationsAfter");
	mStorageLimitExceeded = false;
	mReadErrorsOnFilesystemObjects = false;

	// Setup various timings
	int maximumDiffingTime = 600;
	int keepAliveTime = 60;

	// max diffing time, keep-alive time
	if(conf.KeyExists("MaximumDiffingTime"))
	{
		maximumDiffingTime = conf.GetKeyValueInt("MaximumDiffingTime");
	}
	if(conf.KeyExists("KeepAliveTime"))
	{
		keepAliveTime = conf.GetKeyValueInt("KeepAliveTime");
	}

	clientContext.SetMaximumDiffingTime(maximumDiffingTime);
	clientContext.SetKeepAliveTime(keepAliveTime);
	
	// Set store marker
	clientContext.SetClientStoreMarker(mClientStoreMarker);
	
	// Set up the locations, if necessary -- 
	// need to do it here so we have a 
	// (potential) connection to use
	{
		const Configuration &locations(
			conf.GetSubConfiguration(
				"BackupLocations"));
		
		// Make sure all the directory records
		// are set up
		SetupLocations(clientContext, locations);
	}
	
	mpProgressNotifier->NotifyIDMapsSetup(clientContext);
	
	// Get some ID maps going
	SetupIDMapsForSync();

	// Delete any unused directories?
	DeleteUnusedRootDirEntries(clientContext);

#ifdef ENABLE_VSS
	CreateVssBackupComponents();
#endif
					
	// Go through the records, syncing them
	for(Locations::const_iterator 
		i(mLocations.begin()); 
		i != mLocations.end(); ++i)
	{
		// Set current and new ID map pointers
		// in the context
		clientContext.SetIDMaps(mCurrentIDMaps[(*i)->mIDMapIndex],
			mNewIDMaps[(*i)->mIDMapIndex]);
	
		// Set exclude lists (context doesn't
		// take ownership)
		clientContext.SetExcludeLists(
			(*i)->mpExcludeFiles,
			(*i)->mpExcludeDirs);

		// Sync the directory
		std::string locationPath = (*i)->mPath;
#ifdef ENABLE_VSS
		if((*i)->mIsSnapshotCreated)
		{
			locationPath = (*i)->mSnapshotPath;
		}
#endif

		(*i)->mpDirectoryRecord->SyncDirectory(params,
			BackupProtocolListDirectory::RootDirectory,
			locationPath, std::string("/") + (*i)->mName, **i);

		// Unset exclude lists (just in case)
		clientContext.SetExcludeLists(0, 0);
	}
	
	// Perform any deletions required -- these are
	// delayed until the end to allow renaming to 
	// happen neatly.
	clientContext.PerformDeletions();

	// Close any open connection
	clientContext.CloseAnyOpenConnection();

#ifdef ENABLE_VSS
	CleanupVssBackupComponents();
#endif

	// Get the new store marker
	mClientStoreMarker = clientContext.GetClientStoreMarker();
	mStorageLimitExceeded = clientContext.StorageLimitExceeded();
	mReadErrorsOnFilesystemObjects |=
		params.mReadErrorsOnFilesystemObjects;

	if(!mStorageLimitExceeded)
	{
		// The start time of the next run is the end time of this
		// run. This is only done if the storage limit wasn't
		// exceeded (as things won't have been done properly if
		// it was)
		mLastSyncTime = syncPeriodEnd;
	}

	// Commit the ID Maps
	CommitIDMapsAfterSync();

	// Calculate when the next sync run should be
	mNextSyncTime = mCurrentSyncStartTime + 
		mUpdateStoreInterval + 
		Random::RandomInt(mUpdateStoreInterval >>
		SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY);

	// --------------------------------------------------------------------------------------------

	// We had a successful backup, save the store 
	// info. If we save successfully, we must 
	// delete the file next time we start a backup

	mDeleteStoreObjectInfoFile = 
		SerializeStoreObjectInfo(mLastSyncTime,
			mNextSyncTime);

	// --------------------------------------------------------------------------------------------
}

#ifdef ENABLE_VSS
bool BackupDaemon::WaitForAsync(IVssAsync *pAsync,
	const std::string& description)
{
	BOX_INFO("VSS: waiting for " << description << " to complete");
	HRESULT result;

	do
	{
		result = pAsync->Wait(1000);
		if(result != S_OK)
		{
			BOX_ERROR("VSS: Failed to wait for " << description <<
				" to complete: " << GetMsgForHresult(result));
			break;
		}

		HRESULT result2;
		result = pAsync->QueryStatus(&result2, NULL);
		if(result != S_OK)
		{
			BOX_ERROR("VSS: Failed to query " << description <<
				" status: " << GetMsgForHresult(result));
			break;
		}

		result = result2;
		BOX_INFO("VSS: " << description << " status: " <<
			GetMsgForHresult(result));
	}
	while(result == VSS_S_ASYNC_PENDING);

	pAsync->Release();

	return (result == VSS_S_ASYNC_FINISHED);
}

#define CALL_MEMBER_FN(object, method) ((object).*(method))

bool BackupDaemon::CallAndWaitForAsync(AsyncMethod method,
	const std::string& description)
{
	IVssAsync *pAsync;
	HRESULT result = CALL_MEMBER_FN(*mpVssBackupComponents, method)(&pAsync);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: " << description << " failed: " <<
			GetMsgForHresult(result));
		return false;
	}

	return WaitForAsync(pAsync, description);
}

void FreeSnapshotProp(VSS_SNAPSHOT_PROP *pSnap)
{
	CoTaskMemFree(pSnap->m_pwszSnapshotDeviceObject);
	CoTaskMemFree(pSnap->m_pwszOriginalVolumeName);
	CoTaskMemFree(pSnap->m_pwszOriginatingMachine);
	CoTaskMemFree(pSnap->m_pwszServiceMachine);
	CoTaskMemFree(pSnap->m_pwszExposedName);
	CoTaskMemFree(pSnap->m_pwszExposedPath);
}

void BackupDaemon::CreateVssBackupComponents()
{
	std::map<char, VSS_ID> volumesIncluded;

	HRESULT result = ::CreateVssBackupComponents(&mpVssBackupComponents);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to create backup components: " << 
			GetMsgForHresult(result));
		return;
	}

	result = mpVssBackupComponents->InitializeForBackup(NULL);
	if(result != S_OK)
	{
		std::string message = GetMsgForHresult(result);

		if (result == VSS_E_UNEXPECTED)
		{
			message = "Check the Application Log for details, and ensure "
				"that the Volume Shadow Copy, COM+ System Application, "
				"and Distributed Transaction Coordinator services "
				"are running";
		}

		BOX_ERROR("VSS: Failed to initialize for backup: " << message);
		return;
	}

	result = mpVssBackupComponents->SetContext(VSS_CTX_BACKUP);
	if(result == E_NOTIMPL)
	{
		BOX_INFO("VSS: Failed to set context to VSS_CTX_BACKUP: "
			"not implemented, probably Windows XP, ignored.");
	}
	else if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to set context to VSS_CTX_BACKUP: " <<
			GetMsgForHresult(result));
		return;
	}

	result = mpVssBackupComponents->SetBackupState(
		false, /* no components for now */
		true, /* might as well ask for a bootable backup */
		VSS_BT_FULL,
		false /* what is Partial File Support? */);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to set backup state: " <<
			GetMsgForHresult(result));
		return;
	}

	if(!CallAndWaitForAsync(&IVssBackupComponents::GatherWriterMetadata,
		"GatherWriterMetadata()"))
	{
		goto CreateVssBackupComponents_cleanup_WriterMetadata;
	}

	UINT writerCount;
	result = mpVssBackupComponents->GetWriterMetadataCount(&writerCount);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to get writer count: " <<
			GetMsgForHresult(result));
		goto CreateVssBackupComponents_cleanup_WriterMetadata;
	}

	for(UINT iWriter = 0; iWriter < writerCount; iWriter++)
	{
		BOX_INFO("VSS: Getting metadata from writer " << iWriter);
		VSS_ID writerInstance;
		IVssExamineWriterMetadata* pMetadata;
		result = mpVssBackupComponents->GetWriterMetadata(iWriter,
			&writerInstance, &pMetadata);
		if(result != S_OK)
		{
			BOX_ERROR("Failed to get VSS metadata from writer " << iWriter <<
				": " << GetMsgForHresult(result));
			continue;
		}

		UINT includeFiles, excludeFiles, numComponents;
		result = pMetadata->GetFileCounts(&includeFiles, &excludeFiles,
			&numComponents);
		if(result != S_OK)
		{
			BOX_ERROR("VSS: Failed to get metadata file counts from "
				"writer " << iWriter <<	": " << 
				GetMsgForHresult(result));
			pMetadata->Release();
			continue;
		}

		for(UINT iComponent = 0; iComponent < numComponents; iComponent++)
		{
			IVssWMComponent* pComponent;
			result = pMetadata->GetComponent(iComponent, &pComponent);
			if(result != S_OK)
			{
				BOX_ERROR("VSS: Failed to get metadata component " <<
					iComponent << " from writer " << iWriter << ": " << 
					GetMsgForHresult(result));
				continue;
			}

			PVSSCOMPONENTINFO pComponentInfo;
			result = pComponent->GetComponentInfo(&pComponentInfo);
			if(result != S_OK)
			{
				BOX_ERROR("VSS: Failed to get metadata component " <<
					iComponent << " info from writer " << iWriter << ": " << 
					GetMsgForHresult(result));
				pComponent->Release();
				continue;
			}

			BOX_TRACE("VSS: writer " << iWriter << " component " << 
				iComponent << " info:");
			switch(pComponentInfo->type)
			{
			case VSS_CT_UNDEFINED: BOX_TRACE("VSS: type: undefined"); break;
			case VSS_CT_DATABASE:  BOX_TRACE("VSS: type: database"); break;
			case VSS_CT_FILEGROUP: BOX_TRACE("VSS: type: filegroup"); break;
			default:
				BOX_WARNING("VSS: type: unknown (" << pComponentInfo->type << ")");
			}

			BOX_TRACE("VSS: logical path: " << 
				BstrToString(pComponentInfo->bstrLogicalPath));
			BOX_TRACE("VSS: component name: " << 
				BstrToString(pComponentInfo->bstrComponentName));
			BOX_TRACE("VSS: caption: " << 
				BstrToString(pComponentInfo->bstrCaption));
			BOX_TRACE("VSS: restore metadata: " << 
				pComponentInfo->bRestoreMetadata);
			BOX_TRACE("VSS: notify on complete: " << 
				pComponentInfo->bRestoreMetadata);
			BOX_TRACE("VSS: selectable: " << 
				pComponentInfo->bSelectable);
			BOX_TRACE("VSS: selectable for restore: " << 
				pComponentInfo->bSelectableForRestore);
			BOX_TRACE("VSS: component flags: " << 
				BOX_FORMAT_HEX32(pComponentInfo->dwComponentFlags));
			BOX_TRACE("VSS: file count: " << 
				pComponentInfo->cFileCount);
			BOX_TRACE("VSS: databases: " << 
				pComponentInfo->cDatabases);
			BOX_TRACE("VSS: log files: " << 
				pComponentInfo->cLogFiles);
			BOX_TRACE("VSS: dependencies: " << 
				pComponentInfo->cDependencies);

			pComponent->FreeComponentInfo(pComponentInfo);
			pComponent->Release();
		}

		pMetadata->Release();
	}

	VSS_ID snapshotSetId;
	result = mpVssBackupComponents->StartSnapshotSet(&snapshotSetId);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to start snapshot set: " <<
			GetMsgForHresult(result));
		goto CreateVssBackupComponents_cleanup_WriterMetadata;
	}

	// Add all volumes included as backup locations to the snapshot set
	for(Locations::iterator
		iLocation  = mLocations.begin();
		iLocation != mLocations.end();
		iLocation++)
	{
		Location& rLocation(**iLocation);
		std::string path = rLocation.mPath;
		// convert to absolute and remove Unicode prefix
		path = ConvertPathToAbsoluteUnicode(path.c_str()).substr(4);

		if(path.length() >= 3 && path[1] == ':' && path[2] == '\\')
		{
			std::string volumeRoot = path.substr(0, 3);

			std::map<char, VSS_ID>::iterator i = 
				volumesIncluded.find(path[0]);

			if(i == volumesIncluded.end())
			{
				std::wstring volumeRootWide;
				volumeRootWide.push_back((WCHAR) path[0]);
				volumeRootWide.push_back((WCHAR) ':');
				volumeRootWide.push_back((WCHAR) '\\');
				VSS_ID newVolumeId;
				result = mpVssBackupComponents->AddToSnapshotSet(
					(VSS_PWSZ)(volumeRootWide.c_str()), GUID_NULL,
					&newVolumeId);
				if(result == S_OK)
				{
					BOX_TRACE("VSS: Added volume " << volumeRoot <<
						" for backup location " << path <<
						" to snapshot set");
					volumesIncluded[path[0]] = newVolumeId;
					rLocation.mSnapshotVolumeId = newVolumeId;
					rLocation.mIsSnapshotCreated = true;

					// If the snapshot path starts with the volume root
					// (drive letter), because the path is absolute (as
					// it should be), then remove it so that the
					// resulting snapshot path can be appended to the
					// snapshot device object to make a real path,
					// without a spurious drive letter in it.

					if (path.substr(0, volumeRoot.length()) == volumeRoot)
					{
						path = path.substr(volumeRoot.length());
					}

					rLocation.mSnapshotPath = path;
				}
				else
				{
					BOX_ERROR("VSS: Failed to add volume " <<
						volumeRoot << " to snapshot set: " <<
						GetMsgForHresult(result));
					goto CreateVssBackupComponents_cleanup_WriterMetadata;
				}
			}
			else
			{
				BOX_TRACE("VSS: Skipping already included volume " <<
					volumeRoot << " for backup location " << path);
				rLocation.mSnapshotVolumeId = i->second;
				rLocation.mIsSnapshotCreated = true;
			}
		}
		else
		{
			BOX_WARNING("VSS: Skipping backup location " << path <<
				" which does not start with a volume specification");
		}
	}

	if(!CallAndWaitForAsync(&IVssBackupComponents::PrepareForBackup,
		"PrepareForBackup()"))
	{
		goto CreateVssBackupComponents_cleanup_WriterMetadata;
	}

	if(!CallAndWaitForAsync(&IVssBackupComponents::DoSnapshotSet,
		"DoSnapshotSet()"))
	{
		goto CreateVssBackupComponents_cleanup_WriterMetadata;
	}

	if(!CallAndWaitForAsync(&IVssBackupComponents::GatherWriterStatus,
		"GatherWriterStatus()"))
	{
		goto CreateVssBackupComponents_cleanup_WriterStatus;
	}

	result = mpVssBackupComponents->GetWriterStatusCount(&writerCount);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to get writer status count: " << 
			GetMsgForHresult(result));
		goto CreateVssBackupComponents_cleanup_WriterStatus;
	}

	for(UINT iWriter = 0; iWriter < writerCount; iWriter++)
	{
		VSS_ID instance, writer;
		BSTR writerNameBstr;
		VSS_WRITER_STATE writerState;
		HRESULT writerResult;

		result = mpVssBackupComponents->GetWriterStatus(iWriter,
			&instance, &writer, &writerNameBstr, &writerState,
			&writerResult);
		if(result != S_OK)
		{
			BOX_ERROR("VSS: Failed to query writer " << iWriter <<
				" status: " << GetMsgForHresult(result));
			goto CreateVssBackupComponents_cleanup_WriterStatus;
		}

		std::string writerName = BstrToString(writerNameBstr);
		::SysFreeString(writerNameBstr);

		if(writerResult != S_OK)
		{
			BOX_ERROR("VSS: Writer " << iWriter << " (" <<
				writerName << ") failed: " <<
				GetMsgForHresult(writerResult));
			continue;
		}

		std::string stateName;

		switch(writerState)
		{
#define WRITER_STATE(code) \
		case code: stateName = #code; break;
		WRITER_STATE(VSS_WS_UNKNOWN);
		WRITER_STATE(VSS_WS_STABLE);
		WRITER_STATE(VSS_WS_WAITING_FOR_FREEZE);
		WRITER_STATE(VSS_WS_WAITING_FOR_THAW);
		WRITER_STATE(VSS_WS_WAITING_FOR_POST_SNAPSHOT);
		WRITER_STATE(VSS_WS_WAITING_FOR_BACKUP_COMPLETE);
		WRITER_STATE(VSS_WS_FAILED_AT_IDENTIFY);
		WRITER_STATE(VSS_WS_FAILED_AT_PREPARE_BACKUP);
		WRITER_STATE(VSS_WS_FAILED_AT_PREPARE_SNAPSHOT);
		WRITER_STATE(VSS_WS_FAILED_AT_FREEZE);
		WRITER_STATE(VSS_WS_FAILED_AT_THAW);
		WRITER_STATE(VSS_WS_FAILED_AT_POST_SNAPSHOT);
		WRITER_STATE(VSS_WS_FAILED_AT_BACKUP_COMPLETE);
		WRITER_STATE(VSS_WS_FAILED_AT_PRE_RESTORE);
		WRITER_STATE(VSS_WS_FAILED_AT_POST_RESTORE);
		WRITER_STATE(VSS_WS_FAILED_AT_BACKUPSHUTDOWN);
#undef WRITER_STATE
		default:
			std::ostringstream o;
			o << "unknown (" << writerState << ")";
			stateName = o.str();
		}

		BOX_TRACE("VSS: Writer " << iWriter << " (" <<
			writerName << ") is in state " << stateName);
	}

	// lookup new snapshot volume for each location that has a snapshot
	for(Locations::iterator
		iLocation  = mLocations.begin();
		iLocation != mLocations.end();
		iLocation++)
	{
		Location& rLocation(**iLocation);
		if(rLocation.mIsSnapshotCreated)
		{
			VSS_SNAPSHOT_PROP prop;
			result = mpVssBackupComponents->GetSnapshotProperties(
				rLocation.mSnapshotVolumeId, &prop);
			if(result != S_OK)
			{
				BOX_ERROR("VSS: Failed to get snapshot properties "
					"for volume " << GuidToString(rLocation.mSnapshotVolumeId) <<
					" for location " << rLocation.mPath << ": " <<
					GetMsgForHresult(result));
				rLocation.mIsSnapshotCreated = false;
				continue;
			}

			rLocation.mSnapshotPath =
				WideStringToString(prop.m_pwszSnapshotDeviceObject) +
				DIRECTORY_SEPARATOR + rLocation.mSnapshotPath;
			FreeSnapshotProp(&prop);

			BOX_INFO("VSS: Location " << rLocation.mPath << " using "
				"snapshot path " << rLocation.mSnapshotPath);
		}
	}

	IVssEnumObject *pEnum;
	result = mpVssBackupComponents->Query(GUID_NULL, VSS_OBJECT_NONE,
		VSS_OBJECT_SNAPSHOT, &pEnum);
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to query snapshot list: " << 
			GetMsgForHresult(result));
		goto CreateVssBackupComponents_cleanup_WriterStatus;
	}

	while(result == S_OK)
	{
		VSS_OBJECT_PROP rgelt;
		ULONG count;
		result = pEnum->Next(1, &rgelt, &count);

		if(result == S_FALSE)
		{
			// end of list, break out of the loop
			break;
		}
		else if(result != S_OK)
		{
			BOX_ERROR("VSS: Failed to enumerate snapshot: " << 
				GetMsgForHresult(result));
		}
		else if(count != 1)
		{
			BOX_ERROR("VSS: Failed to enumerate snapshot: " <<
				"Next() returned " << count << " objects instead of 1");
		}
		else if(rgelt.Type != VSS_OBJECT_SNAPSHOT)
		{
			BOX_ERROR("VSS: Failed to enumerate snapshot: " <<
				"Next() returned a type " << rgelt.Type << " object "
				"instead of VSS_OBJECT_SNAPSHOT");
		}
		else
		{
			VSS_SNAPSHOT_PROP *pSnap = &rgelt.Obj.Snap;
			BOX_TRACE("VSS: Snapshot ID: " << 
				GuidToString(pSnap->m_SnapshotId));
			BOX_TRACE("VSS: Snapshot set ID: " << 
				GuidToString(pSnap->m_SnapshotSetId));
			BOX_TRACE("VSS: Number of volumes: " << 
				pSnap->m_lSnapshotsCount);
			BOX_TRACE("VSS: Snapshot device object: " << 
				WideStringToString(pSnap->m_pwszSnapshotDeviceObject));
			BOX_TRACE("VSS: Original volume name: " << 
				WideStringToString(pSnap->m_pwszOriginalVolumeName));
			BOX_TRACE("VSS: Originating machine: " << 
				WideStringToString(pSnap->m_pwszOriginatingMachine));
			BOX_TRACE("VSS: Service machine: " << 
				WideStringToString(pSnap->m_pwszServiceMachine));
			BOX_TRACE("VSS: Exposed name: " << 
				WideStringToString(pSnap->m_pwszExposedName));
			BOX_TRACE("VSS: Exposed path: " << 
				WideStringToString(pSnap->m_pwszExposedPath));
			BOX_TRACE("VSS: Provider ID: " << 
				GuidToString(pSnap->m_ProviderId));
			BOX_TRACE("VSS: Snapshot attributes: " << 
				BOX_FORMAT_HEX32(pSnap->m_lSnapshotAttributes));
			BOX_TRACE("VSS: Snapshot creation time: " << 
				BOX_FORMAT_HEX32(pSnap->m_tsCreationTimestamp));

			std::string status;
			switch(pSnap->m_eStatus)
			{
			case VSS_SS_UNKNOWN:                     status = "Unknown (error)"; break;
			case VSS_SS_PREPARING:                   status = "Preparing"; break;
			case VSS_SS_PROCESSING_PREPARE:          status = "Preparing (processing)"; break;
			case VSS_SS_PREPARED:                    status = "Prepared"; break;
			case VSS_SS_PROCESSING_PRECOMMIT:        status = "Precommitting"; break;
			case VSS_SS_PRECOMMITTED:                status = "Precommitted"; break;
			case VSS_SS_PROCESSING_COMMIT:           status = "Commiting"; break;
			case VSS_SS_COMMITTED:                   status = "Committed"; break;
			case VSS_SS_PROCESSING_POSTCOMMIT:       status = "Postcommitting"; break;
			case VSS_SS_PROCESSING_PREFINALCOMMIT:   status = "Pre final committing"; break;
			case VSS_SS_PREFINALCOMMITTED:           status = "Pre final committed"; break;
			case VSS_SS_PROCESSING_POSTFINALCOMMIT:  status = "Post final committing"; break;
			case VSS_SS_CREATED:                     status = "Created"; break;
			case VSS_SS_ABORTED:                     status = "Aborted"; break;
			case VSS_SS_DELETED:                     status = "Deleted"; break;
			case VSS_SS_POSTCOMMITTED:               status = "Postcommitted"; break;
			default:
				std::ostringstream buf;
				buf << "Unknown code: " << pSnap->m_eStatus;
				status = buf.str();
			}

			BOX_TRACE("VSS: Snapshot status: " << status);
			FreeSnapshotProp(pSnap);
		}
	}

	pEnum->Release();

CreateVssBackupComponents_cleanup_WriterStatus:
	result = mpVssBackupComponents->FreeWriterStatus();
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to free writer status: " <<
			GetMsgForHresult(result));
	}

CreateVssBackupComponents_cleanup_WriterMetadata:
	result = mpVssBackupComponents->FreeWriterMetadata();
	if(result != S_OK)
	{
		BOX_ERROR("VSS: Failed to free writer metadata: " <<
			GetMsgForHresult(result));
	}
}

void BackupDaemon::CleanupVssBackupComponents()
{
	if(mpVssBackupComponents == NULL)
	{
		return;
	}

	CallAndWaitForAsync(&IVssBackupComponents::BackupComplete,
		"BackupComplete()");

	mpVssBackupComponents->Release();
	mpVssBackupComponents = NULL;
}
#endif

void BackupDaemon::OnBackupStart()
{
	// Touch a file to record times in filesystem
	TouchFileInWorkingDir("last_sync_start");

	// Reset statistics on uploads
	BackupStoreFile::ResetStats();
	
	// Tell anything connected to the command socket
	SendSyncStartOrFinish(true /* start */);
	
	// Notify administrator
	NotifySysadmin(SysadminNotifier::BackupStart);

	// Setup timer for polling the command socket
	mapCommandSocketPollTimer.reset(new Timer(COMMAND_SOCKET_POLL_INTERVAL,
		"CommandSocketPollTimer"));

	// Set state and log start
	SetState(State_Connected);
	BOX_NOTICE("Beginning scan of local files");
}

void BackupDaemon::OnBackupFinish()
{
	try
	{
		// Log
		BOX_NOTICE("Finished scan of local files");

		// Log the stats
		BOX_NOTICE("File statistics: total file size uploaded "
			<< BackupStoreFile::msStats.mBytesInEncodedFiles
			<< ", bytes already on server "
			<< BackupStoreFile::msStats.mBytesAlreadyOnServer
			<< ", encoded size "
			<< BackupStoreFile::msStats.mTotalFileStreamSize
			<< ", " << mNumFilesUploaded << " files uploaded, "
			<< mNumDirsCreated << " dirs created");

		// Reset statistics again
		BackupStoreFile::ResetStats();

		// Notify administrator
		NotifySysadmin(SysadminNotifier::BackupFinish);

		// Stop the timer for polling the command socket,
		// to prevent needless alarms while sleeping.
		mapCommandSocketPollTimer.reset();

		// Tell anything connected to the command socket
		SendSyncStartOrFinish(false /* finish */);

		// Touch a file to record times in filesystem
		TouchFileInWorkingDir("last_sync_finish");
	}
	catch (std::exception &e)
	{
		BOX_ERROR("Failed to perform backup finish actions: " << e.what());
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::UseScriptToSeeIfSyncAllowed()
//		Purpose: Private. Use a script to see if the sync should be
//			 allowed now (if configured). Returns -1 if it's
//			 allowed, time in seconds to wait otherwise.
//		Created: 21/6/04
//
// --------------------------------------------------------------------------
int BackupDaemon::UseScriptToSeeIfSyncAllowed()
{
	const Configuration &conf(GetConfiguration());

	// Got a script to run?
	if(!conf.KeyExists("SyncAllowScript"))
	{
		// No. Do sync.
		return -1;
	}

	// If there's no result, try again in five minutes
	int waitInSeconds = (60*5);

	std::string script(conf.GetKeyValue("SyncAllowScript") + 
		" \"" + GetConfigFileName() + "\"");

	// Run it?
	pid_t pid = 0;
	try
	{
		std::auto_ptr<IOStream> pscript(LocalProcessStream(script,
			pid));

		// Read in the result
		IOStreamGetLine getLine(*pscript);
		std::string line;
		if(getLine.GetLine(line, true, 30000)) // 30 seconds should be enough
		{
			waitInSeconds = BackupDaemon::ParseSyncAllowScriptOutput(script, line);
		}
		else
		{
			BOX_ERROR("SyncAllowScript output nothing within "
				"30 seconds, waiting 5 minutes to try again"
				" (" << script << ")");
		}
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Internal error running SyncAllowScript: "
			<< e.what() << " (" << script << ")");
	}
	catch(...)
	{
		// Ignore any exceptions
		// Log that something bad happened
		BOX_ERROR("Unknown error running SyncAllowScript (" <<
			script << ")");
	}

	// Wait and then cleanup child process, if any
	if(pid != 0)
	{
		int status = 0;
		::waitpid(pid, &status, 0);
	}

	return waitInSeconds;
}

int BackupDaemon::ParseSyncAllowScriptOutput(const std::string& script,
	const std::string& output)
{
	int waitInSeconds = (60*5);
	std::istringstream iss(output);

	std::string delay;
	iss >> delay;

	if(delay == "")
	{
		BOX_ERROR("SyncAllowScript output an empty line");
		return waitInSeconds;
	}

	// Got a string, interpret
	if(delay == "now")
	{
		// Script says do it now. Obey.
		waitInSeconds = -1;

		BOX_NOTICE("SyncAllowScript requested a backup now "
			<< "(" << script << ")");
	}
	else
	{
		try
		{
			// How many seconds to wait?
			waitInSeconds = BoxConvert::Convert<int32_t, const std::string&>(delay);
		}
		catch(ConversionException &e)
		{
			BOX_ERROR("SyncAllowScript output an invalid "
				"number: '" << output << "' (" <<
				script << ")");
			throw;
		}

		BOX_NOTICE("SyncAllowScript requested a delay of " << 
			waitInSeconds << " seconds (" << script << ")");
	}

	if(iss.eof())
	{
		// No bandwidth limit requested
		mMaxBandwidthFromSyncAllowScript = 0;
		BOX_NOTICE("SyncAllowScript did not set a maximum bandwidth "
			"(" << script << ")");
	}
	else
	{
		std::string maxBandwidth;
		iss >> maxBandwidth;

		try
		{
			// How many seconds to wait?
			mMaxBandwidthFromSyncAllowScript =
				BoxConvert::Convert<int32_t, const std::string&>(maxBandwidth);
		}
		catch(ConversionException &e)
		{
			BOX_ERROR("Invalid maximum bandwidth from "
				"SyncAllowScript: '" <<
				output << "' (" << script << ")");
			throw;
		}

		BOX_NOTICE("SyncAllowScript set maximum bandwidth to " <<
			mMaxBandwidthFromSyncAllowScript << " kB/s (" <<
			script << ")");
	}

	return waitInSeconds;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::RunBackgroundTask()
//		Purpose: Checks for connections or commands on the command
//			 socket and handles them with minimal delay. Polled
//			 during lengthy operations such as file uploads.
//		Created: 07/04/14
//
// --------------------------------------------------------------------------
bool BackupDaemon::RunBackgroundTask(State state, uint64_t progress,
	uint64_t maximum)
{
	BOX_TRACE("BackupDaemon::RunBackgroundTask: state = " << state <<
		", progress = " << progress << "/" << maximum);
	
	if(mapCommandSocketPollTimer->HasExpired())
	{
		mapCommandSocketPollTimer->Reset(COMMAND_SOCKET_POLL_INTERVAL);
	}
	else
	{
		// Do no more work right now
		return true;
	}

	if(mapCommandSocketInfo.get())
	{
		BOX_TRACE("BackupDaemon::RunBackgroundTask: polling command socket");

		bool sync_flag_out, sync_is_forced_out;

		WaitOnCommandSocket(0, // RequiredDelay
			sync_flag_out, sync_is_forced_out);

		if(sync_flag_out)
		{
			BOX_WARNING("Ignoring request to sync while "
				"already syncing.");
		}
	}

	return true;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::WaitOnCommandSocket(box_time_t, bool &, bool &)
//		Purpose: Waits on a the command socket for a time of UP TO the required time
//				 but may be much less, and handles a command if necessary.
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::WaitOnCommandSocket(box_time_t RequiredDelay, bool &DoSyncFlagOut, bool &SyncIsForcedOut)
{
	DoSyncFlagOut = false;
	SyncIsForcedOut = false;

	ASSERT(mapCommandSocketInfo.get());
	if(!mapCommandSocketInfo.get())
	{
		// failure case isn't too bad
		::sleep(1);
		return;
	}
	
	BOX_TRACE("Wait on command socket, delay = " << RequiredDelay);
	
	try
	{
		// Timeout value for connections and things
		int timeout = ((int)BoxTimeToMilliSeconds(RequiredDelay)) + 1;
		// Handle bad boundary cases
		if(timeout <= 0) timeout = 1;
		if(timeout == INFTIM) timeout = 100000;

		// Wait for socket connection, or handle a command?
		if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			// No connection, listen for a new one
			mapCommandSocketInfo->mpConnectedSocket.reset(mapCommandSocketInfo->mListeningSocket.Accept(timeout).release());
			
			if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
			{
				// If a connection didn't arrive, there was a timeout, which means we've
				// waited long enough and it's time to go.
				return;
			}
			else
			{
#ifdef PLATFORM_CANNOT_FIND_PEER_UID_OF_UNIX_SOCKET
				bool uidOK = true;
				BOX_WARNING("On this platform, no security check can be made on the credentials of peers connecting to the command socket. (bbackupctl)");
#else
				// Security check -- does the process connecting to this socket have
				// the same UID as this process?
				bool uidOK = false;
				// BLOCK
				{
					uid_t remoteEUID = 0xffff;
					gid_t remoteEGID = 0xffff;
					if(mapCommandSocketInfo->mpConnectedSocket->GetPeerCredentials(remoteEUID, remoteEGID))
					{
						// Credentials are available -- check UID
						if(remoteEUID == ::getuid())
						{
							// Acceptable
							uidOK = true;
						}
					}
				}
#endif // PLATFORM_CANNOT_FIND_PEER_UID_OF_UNIX_SOCKET
				
				// Is this an acceptable connection?
				if(!uidOK)
				{
					// Dump the connection
					BOX_ERROR("Incoming command connection from peer had different user ID than this process, or security check could not be completed.");
					mapCommandSocketInfo->mpConnectedSocket.reset();
					return;
				}
				else
				{
					// Log
					BOX_INFO("Connection from command socket");
					
					// Send a header line summarising the configuration and current state
					const Configuration &conf(GetConfiguration());
					char summary[256];
					int summarySize = sprintf(summary, "bbackupd: %d %d %d %d\nstate %d\n",
						conf.GetKeyValueBool("AutomaticBackup"),
						conf.GetKeyValueInt("UpdateStoreInterval"),
						conf.GetKeyValueInt("MinimumFileAge"),
						conf.GetKeyValueInt("MaxUploadWait"),
						mState);
					mapCommandSocketInfo->mpConnectedSocket->Write(summary, summarySize);
					
					// Set the timeout to something very small, so we don't wait too long on waiting
					// for any incoming data
					timeout = 10; // milliseconds
				}
			}
		}

		// So there must be a connection now.
		ASSERT(mapCommandSocketInfo->mpConnectedSocket.get() != 0);
		
		// Is there a getline object ready?
		if(mapCommandSocketInfo->mpGetLine == 0)
		{
			// Create a new one
			mapCommandSocketInfo->mpGetLine = new IOStreamGetLine(*(mapCommandSocketInfo->mpConnectedSocket.get()));
		}
		
		// Ping the remote side, to provide errors which will mean the socket gets closed
		mapCommandSocketInfo->mpConnectedSocket->Write("ping\n", 5);
		
		// Wait for a command or something on the socket
		std::string command;
		while(mapCommandSocketInfo->mpGetLine != 0 && !mapCommandSocketInfo->mpGetLine->IsEOF()
			&& mapCommandSocketInfo->mpGetLine->GetLine(command, false /* no preprocessing */, timeout))
		{
			BOX_TRACE("Receiving command '" << command 
				<< "' over command socket");
			
			bool sendOK = false;
			bool sendResponse = true;
		
			// Command to process!
			if(command == "quit" || command == "")
			{
				// Close the socket.
				CloseCommandConnection();
				sendResponse = false;
			}
			else if(command == "sync")
			{
				// Sync now!
				DoSyncFlagOut = true;
				SyncIsForcedOut = false;
				sendOK = true;
			}
			else if(command == "force-sync")
			{
				// Sync now (forced -- overrides any SyncAllowScript)
				DoSyncFlagOut = true;
				SyncIsForcedOut = true;
				sendOK = true;
			}
			else if(command == "reload")
			{
				// Reload the configuration
				SetReloadConfigWanted();
				sendOK = true;
			}
			else if(command == "terminate")
			{
				// Terminate the daemon cleanly
				SetTerminateWanted();
				sendOK = true;
			}
			
			// Send a response back?
			if(sendResponse)
			{
				mapCommandSocketInfo->mpConnectedSocket->Write(sendOK?"ok\n":"error\n", sendOK?3:6);
			}
			
			// Set timeout to something very small, so this just checks for data which is waiting
			timeout = 1;
		}
		
		// Close on EOF?
		if(mapCommandSocketInfo->mpGetLine != 0 && mapCommandSocketInfo->mpGetLine->IsEOF())
		{
			CloseCommandConnection();
		}
	}
	catch(ConnectionException &ce)
	{
		BOX_NOTICE("Failed to write to command socket: " << ce.what());

		// If an error occurs, and there is a connection active,
		// just close that connection and continue. Otherwise,
		// let the error propagate.

		if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			throw; // thread will die
		}
		else
		{
			// Close socket and ignore error
			CloseCommandConnection();
		}
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Failed to write to command socket: " <<
			e.what());

		// If an error occurs, and there is a connection active,
		// just close that connection and continue. Otherwise,
		// let the error propagate.

		if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			throw; // thread will die
		}
		else
		{
			// Close socket and ignore error
			CloseCommandConnection();
		}
	}
	catch(...)
	{
		BOX_ERROR("Failed to write to command socket: unknown error");

		// If an error occurs, and there is a connection active,
		// just close that connection and continue. Otherwise,
		// let the error propagate.

		if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			throw; // thread will die
		}
		else
		{
			// Close socket and ignore error
			CloseCommandConnection();
		}
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::CloseCommandConnection()
//		Purpose: Close the command connection, ignoring any errors
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::CloseCommandConnection()
{
	try
	{
		BOX_TRACE("Closing command connection");
		
		if(mapCommandSocketInfo->mpGetLine)
		{
			delete mapCommandSocketInfo->mpGetLine;
			mapCommandSocketInfo->mpGetLine = 0;
		}
		mapCommandSocketInfo->mpConnectedSocket.reset();
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Internal error while closing command "
			"socket: " << e.what());
	}
	catch(...)
	{
		// Ignore any errors
	}
}


// --------------------------------------------------------------------------
//
// File
//		Name:    BackupDaemon.cpp
//		Purpose: Send a start or finish sync message to the command socket, if it's connected.
//				 
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::SendSyncStartOrFinish(bool SendStart)
{
	// The bbackupctl program can't rely on a state change, because it 
	// may never change if the server doesn't need to be contacted.

	if(mapCommandSocketInfo.get() &&
		mapCommandSocketInfo->mpConnectedSocket.get() != 0)
	{
		std::string message = SendStart ? "start-sync" : "finish-sync";
		try
		{
			message += "\n";
			mapCommandSocketInfo->mpConnectedSocket->Write(
				message.c_str(), message.size());
		}
		catch(std::exception &e)
		{
			BOX_ERROR("Internal error while sending to "
				"command socket client: " << e.what());
			CloseCommandConnection();
		}
		catch(...)
		{
			CloseCommandConnection();
		}
	}
}




#if !defined(HAVE_STRUCT_STATFS_F_MNTONNAME) && !defined(HAVE_STRUCT_STATVFS_F_NMTONNAME)
	// string comparison ordering for when mount points are handled
	// by code, rather than the OS.
	typedef struct
	{
		bool operator()(const std::string &s1, const std::string &s2)
		{
			if(s1.size() == s2.size())
			{
				// Equal size, sort according to natural sort order
				return s1 < s2;
			}
			else
			{
				// Make sure longer strings go first
				return s1.size() > s2.size();
			}
		}
	} mntLenCompare;
#endif

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::SetupLocations(BackupClientContext &, const Configuration &)
//		Purpose: Makes sure that the list of directories records is correctly set up
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::SetupLocations(BackupClientContext &rClientContext, const Configuration &rLocationsConf)
{
	// Going to need a copy of the root directory. Get a connection,
	// and fetch it.
	BackupProtocolCallable& connection(rClientContext.GetConnection());
	
	// Ask server for a list of everything in the root directory,
	// which is a directory itself
	std::auto_ptr<BackupProtocolSuccess> dirreply(
		connection.QueryListDirectory(
			BackupProtocolListDirectory::RootDirectory,
			// only directories
			BackupProtocolListDirectory::Flags_Dir,
			// exclude old/deleted stuff
			BackupProtocolListDirectory::Flags_Deleted |
			BackupProtocolListDirectory::Flags_OldVersion,
			false /* no attributes */));

	// Retrieve the directory from the stream following
	BackupStoreDirectory dir;
	std::auto_ptr<IOStream> dirstream(connection.ReceiveStream());
	dir.ReadFromStream(*dirstream, connection.GetTimeout());
	
	// Map of mount names to ID map index
	std::map<std::string, int> mounts;
	int numIDMaps = 0;

#ifdef HAVE_MOUNTS
#if !defined(HAVE_STRUCT_STATFS_F_MNTONNAME) && !defined(HAVE_STRUCT_STATVFS_F_MNTONNAME)
	// Linux and others can't tell you where a directory is mounted. So we
	// have to read the mount entries from /etc/mtab! Bizarre that the OS
	// itself can't tell you, but there you go.
	std::set<std::string, mntLenCompare> mountPoints;
	// BLOCK
	FILE *mountPointsFile = 0;

#ifdef HAVE_STRUCT_MNTENT_MNT_DIR
	// Open mounts file
	mountPointsFile = ::setmntent("/proc/mounts", "r");
	if(mountPointsFile == 0)
	{
		mountPointsFile = ::setmntent("/etc/mtab", "r");
	}
	if(mountPointsFile == 0)
	{
		THROW_EXCEPTION(CommonException, OSFileError);
	}

	try
	{
		// Read all the entries, and put them in the set
		struct mntent *entry = 0;
		while((entry = ::getmntent(mountPointsFile)) != 0)
		{
			BOX_TRACE("Found mount point at " << entry->mnt_dir);
			mountPoints.insert(std::string(entry->mnt_dir));
		}

		// Close mounts file
		::endmntent(mountPointsFile);
	}
	catch(...)
	{
		::endmntent(mountPointsFile);
		throw;
	}
#else // ! HAVE_STRUCT_MNTENT_MNT_DIR
	// Open mounts file
	mountPointsFile = ::fopen("/etc/mnttab", "r");
	if(mountPointsFile == 0)
	{
		THROW_EXCEPTION(CommonException, OSFileError);
	}

	try
	{
		// Read all the entries, and put them in the set
		struct mnttab entry;
		while(getmntent(mountPointsFile, &entry) == 0)
		{
			BOX_TRACE("Found mount point at " << entry.mnt_mountp);
			mountPoints.insert(std::string(entry.mnt_mountp));
		}

		// Close mounts file
		::fclose(mountPointsFile);
	}
	catch(...)
	{
		::fclose(mountPointsFile);
		throw;
	}
#endif // HAVE_STRUCT_MNTENT_MNT_DIR
	// Check sorting and that things are as we expect
	ASSERT(mountPoints.size() > 0);
#ifndef BOX_RELEASE_BUILD
	{
		std::set<std::string, mntLenCompare>::reverse_iterator i(mountPoints.rbegin());
		ASSERT(*i == "/");
	}
#endif // n BOX_RELEASE_BUILD
#endif // n HAVE_STRUCT_STATFS_F_MNTONNAME || n HAVE_STRUCT_STATVFS_F_MNTONNAME
#endif // HAVE_MOUNTS

	// Then... go through each of the entries in the configuration,
	// making sure there's a directory created for it.
	std::vector<std::string> locNames =
		rLocationsConf.GetSubConfigurationNames();

	// We only want completely configured locations to be in the list
	// when this function exits, so move them all to a temporary list.
	// Entries matching a properly configured location will be moved
	// back to mLocations. Anything left in this list after the loop
	// finishes will be deleted.
	Locations tmpLocations = mLocations;
	mLocations.clear();

	// The ID map list will be repopulated automatically by this loop
	mIDMapMounts.clear();

	for(std::vector<std::string>::iterator
		pLocName  = locNames.begin();
		pLocName != locNames.end();
		pLocName++)
	{
		Location* pLoc = NULL;

		// Try to find and reuse an existing Location object
		for(Locations::const_iterator
			i  = tmpLocations.begin();
			i != tmpLocations.end(); i++)
		{
			if ((*i)->mName == *pLocName)
			{
				BOX_TRACE("Location already configured: " << *pLocName);
				pLoc = *i;
				break;
			}
		}
			
		const Configuration& rConfig(
			rLocationsConf.GetSubConfiguration(*pLocName));
		std::auto_ptr<Location> apLoc;

		try
		{
			if(pLoc == NULL)
			{
				// Create a record for it
				BOX_TRACE("New location: " << *pLocName);
				pLoc = new Location;

				// ensure deletion if setup fails
				apLoc.reset(pLoc);

				// Setup names in the location record
				pLoc->mName = *pLocName;
				pLoc->mPath = rConfig.GetKeyValue("Path");
				
				// Read the exclude lists from the Configuration
				pLoc->mpExcludeFiles = BackupClientMakeExcludeList_Files(rConfig);
				pLoc->mpExcludeDirs = BackupClientMakeExcludeList_Dirs(rConfig);
			}

			// Does this exist on the server?
			// Remove from dir object early, so that if we fail
			// to stat the local directory, we still don't 
			// consider to remote one for deletion.
			BackupStoreDirectory::Iterator iter(dir);
			BackupStoreFilenameClear dirname(pLoc->mName);	// generate the filename
			BackupStoreDirectory::Entry *en = iter.FindMatchingClearName(dirname);
			int64_t oid = 0;
			if(en != 0)
			{
				oid = en->GetObjectID();
				
				// Delete the entry from the directory, so we get a list of
				// unused root directories at the end of this.
				dir.DeleteEntry(oid);
			}
		
			// Do a fsstat on the pathname to find out which mount it's on
			{

#if defined HAVE_STRUCT_STATFS_F_MNTONNAME || defined HAVE_STRUCT_STATVFS_F_MNTONNAME || defined WIN32

				// BSD style statfs -- includes mount point, which is nice.
#ifdef HAVE_STRUCT_STATVFS_F_MNTONNAME
				struct statvfs s;
				if(::statvfs(pLoc->mPath.c_str(), &s) != 0)
#else // HAVE_STRUCT_STATVFS_F_MNTONNAME
				struct statfs s;
				if(::statfs(pLoc->mPath.c_str(), &s) != 0)
#endif // HAVE_STRUCT_STATVFS_F_MNTONNAME
				{
					THROW_SYS_ERROR("Failed to stat path "
						"'" << pLoc->mPath << "' "
						"for location "
						"'" << pLoc->mName << "'",
						CommonException, OSFileError);
				}

				// Where the filesystem is mounted
				std::string mountName(s.f_mntonname);

#else // !HAVE_STRUCT_STATFS_F_MNTONNAME && !WIN32

				// Warn in logs if the directory isn't absolute
				if(pLoc->mPath[0] != '/')
				{
					BOX_WARNING("Location path '"
						<< pLoc->mPath 
						<< "' is not absolute");
				}
				// Go through the mount points found, and find a suitable one
				std::string mountName("/");
				{
					std::set<std::string, mntLenCompare>::const_iterator i(mountPoints.begin());
					BOX_TRACE(mountPoints.size() 
						<< " potential mount points");
					for(; i != mountPoints.end(); ++i)
					{
						// Compare first n characters with the filename
						// If it matches, the file belongs in that mount point
						// (sorting order ensures this)
						BOX_TRACE("checking against mount point " << *i);
						if(::strncmp(i->c_str(), pLoc->mPath.c_str(), i->size()) == 0)
						{
							// Match
							mountName = *i;
							break;
						}
					}
					BOX_TRACE("mount point chosen for "
						<< pLoc->mPath << " is "
						<< mountName);
				}

#endif
				
				// Got it?
				std::map<std::string, int>::iterator f(mounts.find(mountName));
				if(f != mounts.end())
				{
					// Yes -- store the index
					pLoc->mIDMapIndex = f->second;
				}
				else
				{
					// No -- new index
					pLoc->mIDMapIndex = numIDMaps;
					mounts[mountName] = numIDMaps;
					
					// Store the mount name
					mIDMapMounts.push_back(mountName);
					
					// Increment number of maps
					++numIDMaps;
				}
			}
		
			// Does this exist on the server?
			if(en == 0)
			{
				// Doesn't exist, so it has to be created on the server. Let's go!
				// First, get the directory's attributes and modification time
				box_time_t attrModTime = 0;
				BackupClientFileAttributes attr;
				try
				{
					attr.ReadAttributes(pLoc->mPath.c_str(), 
						true /* directories have zero mod times */,
						0 /* not interested in mod time */, 
						&attrModTime /* get the attribute modification time */);
				}
				catch (BoxException &e)
				{
					BOX_ERROR("Failed to get attributes "
						"for path '" << pLoc->mPath
						<< "', skipping location '" <<
						pLoc->mName << "'");
					throw;
				}
				
				// Execute create directory command
				try
				{
					std::auto_ptr<IOStream> attrStream(
						new MemBlockStream(attr));
					std::auto_ptr<BackupProtocolSuccess>
						dirCreate(connection.QueryCreateDirectory(
						BackupProtocolListDirectory::RootDirectory,
						attrModTime, dirname, attrStream));
						
					// Object ID for later creation
					oid = dirCreate->GetObjectID();
				}
				catch (BoxException &e)
				{
					BOX_ERROR("Failed to create remote "
						"directory '/" << pLoc->mName <<
						"', skipping location '" <<
						pLoc->mName << "'");
					throw;
				}

			}

			// Create and store the directory object for the root of this location
			ASSERT(oid != 0);
			if(pLoc->mpDirectoryRecord.get() == NULL)
			{
				BackupClientDirectoryRecord *precord =
					new BackupClientDirectoryRecord(oid, *pLocName);
				pLoc->mpDirectoryRecord.reset(precord);
			}
			
			// Remove it from the temporary list to avoid deletion
			tmpLocations.remove(pLoc);

			// Push it back on the vector of locations
			mLocations.push_back(pLoc);

			if(apLoc.get() != NULL)
			{
				// Don't delete it now!
				apLoc.release();
			}
		}
		catch (std::exception &e)
		{
			BOX_ERROR("Failed to configure location '"
				<< pLoc->mName << "' path '"
				<< pLoc->mPath << "': " << e.what() <<
				": please check for previous errors");
			mReadErrorsOnFilesystemObjects = true;
		}
		catch(...)
		{
			BOX_ERROR("Failed to configure location '"
				<< pLoc->mName << "' path '"
				<< pLoc->mPath << "': please check for "
				"previous errors");
			mReadErrorsOnFilesystemObjects = true;
		}
	}

	// Now remove any leftovers
	for(BackupDaemon::Locations::iterator
		i  = tmpLocations.begin();
		i != tmpLocations.end(); i++)
	{
		BOX_INFO("Removing obsolete location from memory: " <<
			(*i)->mName);
		delete *i;
	}

	tmpLocations.clear();
	
	// Any entries in the root directory which need deleting?
	if(dir.GetNumberOfEntries() > 0 &&
		mDeleteRedundantLocationsAfter == 0)
	{
		BOX_NOTICE(dir.GetNumberOfEntries() << " redundant locations "
			"in root directory found, but will not delete because "
			"DeleteRedundantLocationsAfter = 0");
	}
	else if(dir.GetNumberOfEntries() > 0)
	{
		box_time_t now = GetCurrentBoxTime();

		// This should reset the timer if the list of unused
		// locations changes, but it will not if the number of
		// unused locations does not change, but the locations
		// do change, e.g. one mysteriously appears and another
		// mysteriously appears. (FIXME)
		if (dir.GetNumberOfEntries() != mUnusedRootDirEntries.size() ||
			mDeleteUnusedRootDirEntriesAfter == 0)
		{
			mDeleteUnusedRootDirEntriesAfter = now + 
				SecondsToBoxTime(mDeleteRedundantLocationsAfter);
		}

		int secs = BoxTimeToSeconds(mDeleteUnusedRootDirEntriesAfter
			- now);

		BOX_NOTICE(dir.GetNumberOfEntries() << " redundant locations "
			"in root directory found, will delete from store "
			"after " << secs << " seconds.");

		// Store directories in list of things to delete
		mUnusedRootDirEntries.clear();
		BackupStoreDirectory::Iterator iter(dir);
		BackupStoreDirectory::Entry *en = 0;
		while((en = iter.Next()) != 0)
		{
			// Add name to list
			BackupStoreFilenameClear clear(en->GetName());
			const std::string &name(clear.GetClearFilename());
			mUnusedRootDirEntries.push_back(
				std::pair<int64_t,std::string>
				(en->GetObjectID(), name));
			// Log this
			BOX_INFO("Unused location in root: " << name);
		}
		ASSERT(mUnusedRootDirEntries.size() > 0);
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::SetupIDMapsForSync()
//		Purpose: Sets up ID maps for the sync process -- make sure they're all there
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
void BackupDaemon::SetupIDMapsForSync()
{
	// Make sure we have some blank, empty ID maps
	DeleteIDMapVector(mNewIDMaps);
	FillIDMapVector(mNewIDMaps, true /* new maps */);
	DeleteIDMapVector(mCurrentIDMaps);
	FillIDMapVector(mCurrentIDMaps, false /* new maps */);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::FillIDMapVector(std::vector<BackupClientInodeToIDMap *> &)
//		Purpose: Fills the vector with the right number of empty ID maps
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
void BackupDaemon::FillIDMapVector(std::vector<BackupClientInodeToIDMap *> &rVector, bool NewMaps)
{
	ASSERT(rVector.size() == 0);
	rVector.reserve(mIDMapMounts.size());
	
	for(unsigned int l = 0; l < mIDMapMounts.size(); ++l)
	{
		// Create the object
		BackupClientInodeToIDMap *pmap = new BackupClientInodeToIDMap();
		try
		{
			// Get the base filename of this map
			std::string filename;
			MakeMapBaseName(l, filename);
			
			// If it's a new one, add a suffix
			if(NewMaps)
			{
				filename += ".n";
			}

			// The new map file should not exist yet. If there's
			// one left over from a previous failed run, it's not
			// useful to us because we never read from it and will
			// overwrite the entries of all files that still
			// exist, so we should just delete it and start afresh.
			if(NewMaps && FileExists(filename.c_str()))
			{
				BOX_NOTICE("Found an incomplete ID map "
					"database, deleting it to start "
					"afresh: " << filename);
				if(unlink(filename.c_str()) != 0)
				{
					BOX_LOG_NATIVE_ERROR(BOX_FILE_MESSAGE(
						filename, "Failed to delete "
						"incomplete ID map database"));
				}
			}

			// If it's not a new map, it may not exist in which case an empty map should be created
			if(!NewMaps && !FileExists(filename.c_str()))
			{
				pmap->OpenEmpty();
			}
			else
			{
				// Open the map
				pmap->Open(filename.c_str(), !NewMaps /* read only */, NewMaps /* create new */);
			}
			
			// Store on vector
			rVector.push_back(pmap);
		}
		catch(...)
		{
			delete pmap;
			throw;
		}
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeleteCorruptBerkelyDbFiles()
//		Purpose: Delete the Berkely db files from disc after they have been corrupted.
//		Created: 14/9/04
//
// --------------------------------------------------------------------------
void BackupDaemon::DeleteCorruptBerkelyDbFiles()
{
	for(unsigned int l = 0; l < mIDMapMounts.size(); ++l)
	{
		// Get the base filename of this map
		std::string filename;
		MakeMapBaseName(l, filename);
		
		// Delete the file
		BOX_TRACE("Deleting " << filename);
		::unlink(filename.c_str());
		
		// Add a suffix for the new map
		filename += ".n";

		// Delete that too
		BOX_TRACE("Deleting " << filename);
		::unlink(filename.c_str());
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    MakeMapBaseName(unsigned int, std::string &)
//		Purpose: Makes the base name for a inode map
//		Created: 20/11/03
//
// --------------------------------------------------------------------------
void BackupDaemon::MakeMapBaseName(unsigned int MountNumber, std::string &rNameOut) const
{
	// Get the directory for the maps
	const Configuration &config(GetConfiguration());
	std::string dir(config.GetKeyValue("DataDirectory"));

	// Make a leafname
	std::string leaf(mIDMapMounts[MountNumber]);
	for(unsigned int z = 0; z < leaf.size(); ++z)
	{
		if(leaf[z] == DIRECTORY_SEPARATOR_ASCHAR)
		{
			leaf[z] = '_';
		}
	}

	// Build the final filename
	rNameOut = dir + DIRECTORY_SEPARATOR "mnt" + leaf;
}




// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::CommitIDMapsAfterSync()
//		Purpose: Commits the new ID maps, so the 'new' maps are now the 'current' maps.
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
void BackupDaemon::CommitIDMapsAfterSync()
{
	// Get rid of the maps in memory (leaving them on disc of course)
	DeleteIDMapVector(mCurrentIDMaps);
	DeleteIDMapVector(mNewIDMaps);

	// Then move the old maps into the new places
	for(unsigned int l = 0; l < mIDMapMounts.size(); ++l)
	{
		std::string target;
		MakeMapBaseName(l, target);
		std::string newmap(target + ".n");
		
		// Try to rename
#ifdef WIN32
		// win32 rename doesn't overwrite existing files
		::remove(target.c_str());
#endif
		if(::rename(newmap.c_str(), target.c_str()) != 0)
		{
			BOX_LOG_SYS_ERROR("Failed to rename ID map: " <<
				newmap << " to " << target);
			THROW_EXCEPTION(CommonException, OSFileError)
		}
	}
}



// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeleteIDMapVector(std::vector<BackupClientInodeToIDMap *> &)
//		Purpose: Deletes the contents of a vector of ID maps
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
void BackupDaemon::DeleteIDMapVector(std::vector<BackupClientInodeToIDMap *> &rVector)
{
	while(!rVector.empty())
	{
		// Pop off list
		BackupClientInodeToIDMap *toDel = rVector.back();
		rVector.pop_back();
		
		// Close and delete
		delete toDel;
	}
	ASSERT(rVector.size() == 0);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::FindLocationPathName(const std::string &, std::string &) const
//		Purpose: Tries to find the path of the root of a backup location. Returns true (and path in rPathOut)
//				 if it can be found, false otherwise.
//		Created: 12/11/03
//
// --------------------------------------------------------------------------
bool BackupDaemon::FindLocationPathName(const std::string &rLocationName, std::string &rPathOut) const
{
	// Search for the location
	for(Locations::const_iterator i(mLocations.begin()); i != mLocations.end(); ++i)
	{
		if((*i)->mName == rLocationName)
		{
			rPathOut = (*i)->mPath;
			return true;
		}
	}
	
	// Didn't find it
	return false;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::SetState(int)
//		Purpose: Record current action of daemon, and update process title to reflect this
//		Created: 11/12/03
//
// --------------------------------------------------------------------------
void BackupDaemon::SetState(int State)
{
	// Two little checks
	if(State == mState) return;
	if(State < 0) return;

	// Update
	mState = State;
	
	// Set process title
	const static char *stateText[] = {"idle", "connected", "error -- waiting for retry", "over limit on server -- not backing up"};
	SetProcessTitle(stateText[State]);

	// If there's a command socket connected, then inform it -- disconnecting from the
	// command socket if there's an error

	char newState[64];
	sprintf(newState, "state %d", State);
	std::string message = newState;

	message += "\n";

	if(!mapCommandSocketInfo.get())
	{
		return;
	}

	if(mapCommandSocketInfo->mpConnectedSocket.get() == 0)
	{
		return;
	}

	// Something connected to the command socket, tell it about the new state
	try
	{
		mapCommandSocketInfo->mpConnectedSocket->Write(message.c_str(),
			message.length());
	}
	catch(ConnectionException &ce)
	{
		BOX_NOTICE("Failed to write state to command socket: " <<
			ce.what());
		CloseCommandConnection();
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Failed to write state to command socket: " <<
			e.what());
		CloseCommandConnection();
	}
	catch(...)
	{
		BOX_ERROR("Failed to write state to command socket: "
			"unknown error");
		CloseCommandConnection();
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::TouchFileInWorkingDir(const char *)
//		Purpose: Make sure a zero length file of the name exists in the working directory.
//				 Use for marking times of events in the filesystem.
//		Created: 21/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::TouchFileInWorkingDir(const char *Filename)
{
	// Filename
	const Configuration &config(GetConfiguration());
	std::string fn(config.GetKeyValue("DataDirectory") + DIRECTORY_SEPARATOR_ASCHAR);
	fn += Filename;
	
	// Open and close it to update the timestamp
	try
	{
		FileStream touch(fn, O_WRONLY | O_CREAT | O_TRUNC,
			S_IRUSR | S_IWUSR);
	}
	catch (std::exception &e)
	{
		BOX_ERROR("Failed to write to timestamp file: " << fn << ": " <<
			e.what());
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::NotifySysadmin(int)
//		Purpose: Run the script to tell the sysadmin about events
//			 which need attention.
//		Created: 25/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::NotifySysadmin(SysadminNotifier::EventCode Event)
{
	static const char *sEventNames[] = 
	{
		"store-full",
		"read-error", 
		"backup-error",
		"backup-start",
		"backup-finish",
		"backup-ok",
		0
	};

	// BOX_TRACE("sizeof(sEventNames)  == " << sizeof(sEventNames));
	// BOX_TRACE("sizeof(*sEventNames) == " << sizeof(*sEventNames));
	// BOX_TRACE("NotifyEvent__MAX == " << NotifyEvent__MAX);
	ASSERT((sizeof(sEventNames)/sizeof(*sEventNames)) == SysadminNotifier::MAX + 1);

	if(Event < 0 || Event >= SysadminNotifier::MAX)
	{
		BOX_ERROR("BackupDaemon::NotifySysadmin() called for "
			"invalid event code " << Event);
		THROW_EXCEPTION(BackupStoreException,
			BadNotifySysadminEventCode);
	}

	BOX_TRACE("BackupDaemon::NotifySysadmin() called, event = " << 
		sEventNames[Event]);

	if(!GetConfiguration().KeyExists("NotifyAlways") ||
		!GetConfiguration().GetKeyValueBool("NotifyAlways"))
	{
		// Don't send lots of repeated messages
		// Note: backup-start and backup-finish will always be
		// logged, because mLastNotifiedEvent is never set to
		// these values and therefore they are never "duplicates".
		if(mLastNotifiedEvent == Event)
		{
			if(Event == SysadminNotifier::BackupOK)
			{
				BOX_INFO("Suppressing duplicate notification "
					"about " << sEventNames[Event]);
			}
			else
			{
				BOX_WARNING("Suppressing duplicate notification "
					"about " << sEventNames[Event]);
			}
			return;
		}
	}

	// Is there a notification script?
	const Configuration &conf(GetConfiguration());
	if(!conf.KeyExists("NotifyScript"))
	{
		// Log, and then return
		if(Event != SysadminNotifier::BackupStart &&
			Event != SysadminNotifier::BackupFinish)
		{
			BOX_INFO("Not notifying administrator about event "
				<< sEventNames[Event] << ", set NotifyScript "
				"to do this in future");
		}
		return;
	}

	// Script to run
	std::string script(conf.GetKeyValue("NotifyScript") + " " +
		sEventNames[Event] + " \"" + GetConfigFileName() + "\"");
	
	// Log what we're about to do
	BOX_INFO("About to notify administrator about event "
		<< sEventNames[Event] << ", running script '" << script << "'");
	
	// Then do it
	int returnCode = ::system(script.c_str());
	if(returnCode != 0)
	{
		BOX_WARNING("Notify script returned error code: " <<
			returnCode << " (" << script << ")");
	}
	else if(Event != SysadminNotifier::BackupStart &&
		Event != SysadminNotifier::BackupFinish)
	{
		mLastNotifiedEvent = Event;
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeleteUnusedRootDirEntries(BackupClientContext &)
//		Purpose: Deletes any unused entries in the root directory, if they're scheduled to be deleted.
//		Created: 13/5/04
//
// --------------------------------------------------------------------------
void BackupDaemon::DeleteUnusedRootDirEntries(BackupClientContext &rContext)
{
	if(mUnusedRootDirEntries.empty())
	{
		BOX_INFO("Not deleting unused entries - none in list");
		return;
	}
	
	if(mDeleteUnusedRootDirEntriesAfter == 0)
	{
		BOX_INFO("Not deleting unused entries - "
			"zero delete time (bad)");
		return;
	}

	// Check time
	box_time_t now = GetCurrentBoxTime();
	if(now < mDeleteUnusedRootDirEntriesAfter)
	{
		int secs = BoxTimeToSeconds(mDeleteUnusedRootDirEntriesAfter
			- now);
		BOX_INFO("Not deleting unused entries - too early ("
			<< secs << " seconds remaining)");
		return;
	}

	// Entries to delete, and it's the right time to do so...
	BOX_NOTICE("Deleting unused locations from store root...");
	BackupProtocolCallable &connection(rContext.GetConnection());
	for(std::vector<std::pair<int64_t,std::string> >::iterator
		i(mUnusedRootDirEntries.begin());
		i != mUnusedRootDirEntries.end(); ++i)
	{
		connection.QueryDeleteDirectory(i->first);
		rContext.GetProgressNotifier().NotifyFileDeleted(
			i->first, i->second);
	}

	// Reset state
	mDeleteUnusedRootDirEntriesAfter = 0;
	mUnusedRootDirEntries.clear();
}

// --------------------------------------------------------------------------

typedef struct
{
	int32_t mMagicValue;	// also the version number
	int32_t mNumEntries;
	int64_t mObjectID;		// this object ID
	int64_t mContainerID;	// ID of container
	uint64_t mAttributesModTime;
	int32_t mOptionsPresent;	// bit mask of optional sections / features present

} loc_StreamFormat;

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::CommandSocketInfo::CommandSocketInfo()
//		Purpose: Constructor
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
BackupDaemon::CommandSocketInfo::CommandSocketInfo()
	: mpGetLine(0)
{
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::CommandSocketInfo::~CommandSocketInfo()
//		Purpose: Destructor
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
BackupDaemon::CommandSocketInfo::~CommandSocketInfo()
{
	if(mpGetLine)
	{
		delete mpGetLine;
		mpGetLine = 0;
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::SerializeStoreObjectInfo(
//			 box_time_t theLastSyncTime,
//			 box_time_t theNextSyncTime)
//		Purpose: Serializes remote directory and file information
//			 into a stream of bytes, using an Archive
//			 abstraction.
//		Created: 2005/04/11
//
// --------------------------------------------------------------------------

static const int STOREOBJECTINFO_MAGIC_ID_VALUE = 0x7777525F;
static const std::string STOREOBJECTINFO_MAGIC_ID_STRING = "BBACKUPD-STATE";
static const int STOREOBJECTINFO_VERSION = 2;

bool BackupDaemon::SerializeStoreObjectInfo(box_time_t theLastSyncTime,
	box_time_t theNextSyncTime) const
{
	if(!GetConfiguration().KeyExists("StoreObjectInfoFile"))
	{
		return false;
	}

	std::string StoreObjectInfoFile = 
		GetConfiguration().GetKeyValue("StoreObjectInfoFile");

	if(StoreObjectInfoFile.size() <= 0)
	{
		return false;
	}

	bool created = false;

	try
	{
		FileStream aFile(StoreObjectInfoFile.c_str(), 
			O_WRONLY | O_CREAT | O_TRUNC);
		created = true;

		Archive anArchive(aFile, 0);

		anArchive.Write(STOREOBJECTINFO_MAGIC_ID_VALUE);
		anArchive.Write(STOREOBJECTINFO_MAGIC_ID_STRING); 
		anArchive.Write(STOREOBJECTINFO_VERSION);
		anArchive.Write(GetLoadedConfigModifiedTime());
		anArchive.Write(mClientStoreMarker);
		anArchive.Write(theLastSyncTime);
		anArchive.Write(theNextSyncTime);

		//
		//
		//
		int64_t iCount = mLocations.size();
		anArchive.Write(iCount);

		for(Locations::const_iterator i = mLocations.begin();
			i != mLocations.end(); i++)
		{
			ASSERT(*i);
			(*i)->Serialize(anArchive);
		}

		//
		//
		//
		iCount = mIDMapMounts.size();
		anArchive.Write(iCount);

		for(int v = 0; v < iCount; v++)
			anArchive.Write(mIDMapMounts[v]);

		//
		//
		//
		iCount = mUnusedRootDirEntries.size();
		anArchive.Write(iCount);

		for(int v = 0; v < iCount; v++)
		{
			anArchive.Write(mUnusedRootDirEntries[v].first);
			anArchive.Write(mUnusedRootDirEntries[v].second);
		}

		if (iCount > 0)
		{
			anArchive.Write(mDeleteUnusedRootDirEntriesAfter);
		}

		//
		//
		//
		aFile.Close();
		BOX_INFO("Saved store object info file version " <<
			STOREOBJECTINFO_VERSION << " (" <<
			StoreObjectInfoFile << ")");
	}
	catch(std::exception &e)
	{
		BOX_ERROR("Failed to write StoreObjectInfoFile: " <<
			StoreObjectInfoFile << ": " << e.what());
	}
	catch(...)
	{
		BOX_ERROR("Failed to write StoreObjectInfoFile: " <<
			StoreObjectInfoFile << ": unknown error");
	}

	return created;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeserializeStoreObjectInfo(
//			 box_time_t & theLastSyncTime,
//			 box_time_t & theNextSyncTime)
//		Purpose: Deserializes remote directory and file information
//			 from a stream of bytes, using an Archive
//			 abstraction.
//		Created: 2005/04/11
//
// --------------------------------------------------------------------------
bool BackupDaemon::DeserializeStoreObjectInfo(box_time_t & theLastSyncTime,
	box_time_t & theNextSyncTime)
{
	//
	//
	//
	DeleteAllLocations();

	//
	//
	//
	if(!GetConfiguration().KeyExists("StoreObjectInfoFile"))
	{
		return false;
	}

	std::string StoreObjectInfoFile = 
		GetConfiguration().GetKeyValue("StoreObjectInfoFile");

	if(StoreObjectInfoFile.size() <= 0)
	{
		return false;
	}

	try
	{
		FileStream aFile(StoreObjectInfoFile.c_str(), O_RDONLY);
		Archive anArchive(aFile, 0);

		//
		// see if the content looks like a valid serialised archive
		//
		int iMagicValue = 0;
		anArchive.Read(iMagicValue);

		if(iMagicValue != STOREOBJECTINFO_MAGIC_ID_VALUE)
		{
			BOX_WARNING("Store object info file "
				"is not a valid or compatible serialised "
				"archive. Will re-cache from store. "
				"(" << StoreObjectInfoFile << ")");
			return false;
		}

		//
		// get a bit optimistic and read in a string identifier
		//
		std::string strMagicValue;
		anArchive.Read(strMagicValue);

		if(strMagicValue != STOREOBJECTINFO_MAGIC_ID_STRING)
		{
			BOX_WARNING("Store object info file "
				"is not a valid or compatible serialised "
				"archive. Will re-cache from store. "
				"(" << StoreObjectInfoFile << ")");
			return false;
		}

		//
		// check if we are loading some future format
		// version by mistake
		//
		int iVersion = 0;
		anArchive.Read(iVersion);

		if(iVersion != STOREOBJECTINFO_VERSION)
		{
			BOX_WARNING("Store object info file "
				"version " << iVersion << " unsupported. "
				"Will re-cache from store. "
				"(" << StoreObjectInfoFile << ")");
			return false;
		}

		//
		// check if this state file is even valid 
		// for the loaded bbackupd.conf file
		//
		box_time_t lastKnownConfigModTime;
		anArchive.Read(lastKnownConfigModTime);

		if(lastKnownConfigModTime != GetLoadedConfigModifiedTime())
		{
			BOX_WARNING("Store object info file "
				"out of date. Will re-cache from store. "
				"(" << StoreObjectInfoFile << ")");
			return false;
		}

		//
		// this is it, go at it
		//
		anArchive.Read(mClientStoreMarker);
		anArchive.Read(theLastSyncTime);
		anArchive.Read(theNextSyncTime);

		//
		//
		//
		int64_t iCount = 0;
		anArchive.Read(iCount);

		for(int v = 0; v < iCount; v++)
		{
			Location* pLocation = new Location;
			if(!pLocation)
			{
				throw std::bad_alloc();
			}

			pLocation->Deserialize(anArchive);
			mLocations.push_back(pLocation);
		}

		//
		//
		//
		iCount = 0;
		anArchive.Read(iCount);

		for(int v = 0; v < iCount; v++)
		{
			std::string strItem;
			anArchive.Read(strItem);

			mIDMapMounts.push_back(strItem);
		}

		//
		//
		//
		iCount = 0;
		anArchive.Read(iCount);

		for(int v = 0; v < iCount; v++)
		{
			int64_t anId;
			anArchive.Read(anId);

			std::string aName;
			anArchive.Read(aName);

			mUnusedRootDirEntries.push_back(std::pair<int64_t, std::string>(anId, aName));
		}

		if (iCount > 0)
			anArchive.Read(mDeleteUnusedRootDirEntriesAfter);

		//
		//
		//
		aFile.Close();
		BOX_INFO("Loaded store object info file version " << iVersion
			<< " (" << StoreObjectInfoFile << ")");
		
		return true;
	} 
	catch(std::exception &e)
	{
		BOX_ERROR("Internal error reading store object info file: "
			<< StoreObjectInfoFile << ": " << e.what());
	}
	catch(...)
	{
		BOX_ERROR("Internal error reading store object info file: "
			<< StoreObjectInfoFile << ": unknown error");
	}

	DeleteAllLocations();

	mClientStoreMarker = BackupClientContext::ClientStoreMarker_NotKnown;
	theLastSyncTime = 0;
	theNextSyncTime = 0;

	BOX_WARNING("Store object info file is missing, not accessible, "
		"or inconsistent. Will re-cache from store. "
		"(" << StoreObjectInfoFile << ")");
	
	return false;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeleteStoreObjectInfo()
//		Purpose: Deletes the serialised state file, to prevent us
//			 from using it again if a backup is interrupted.
//
//		Created: 2006/02/12
//
// --------------------------------------------------------------------------

bool BackupDaemon::DeleteStoreObjectInfo() const
{
	if(!GetConfiguration().KeyExists("StoreObjectInfoFile"))
	{
		return false;
	}

	std::string storeObjectInfoFile(GetConfiguration().GetKeyValue("StoreObjectInfoFile"));

	// Check to see if the file exists
	if(!FileExists(storeObjectInfoFile.c_str()))
	{
		// File doesn't exist -- so can't be deleted. But something
		// isn't quite right, so log a message
		BOX_WARNING("StoreObjectInfoFile did not exist when it "
			"was supposed to: " << storeObjectInfoFile);

		// Return true to stop things going around in a loop
		return true;
	}

	// Actually delete it
	if(::unlink(storeObjectInfoFile.c_str()) != 0)
	{
		BOX_LOG_SYS_ERROR("Failed to delete the old "
			"StoreObjectInfoFile: " << storeObjectInfoFile);
		return false;
	}

	return true;
}