summaryrefslogtreecommitdiff
path: root/bin/bbackupd/BackupDaemon.cpp
blob: 2e80cd2d76016e3ffc0e4a6dc76ab4b76cc2ecf3 (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
// --------------------------------------------------------------------------
//
// File
//		Name:    BackupDaemon.cpp
//		Purpose: Backup daemon
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------

#include "Box.h"

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

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif
#ifdef HAVE_SIGNAL_H
	#include <signal.h>
#endif
#ifdef HAVE_SYSLOG_H
	#include <syslog.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 "Configuration.h"
#include "IOStream.h"
#include "MemBlockStream.h"
#include "CommonException.h"
#include "BoxPortsAndFiles.h"

#include "SSLLib.h"
#include "TLSContext.h"

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

#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

#ifdef WIN32
// --------------------------------------------------------------------------
//
// Function
//		Name:    HelperThread()
//		Purpose: Background thread function, called by Windows,
//			calls the BackupDaemon's RunHelperThread method
//			to listen for and act on control communications
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
unsigned int WINAPI HelperThread(LPVOID lpParam) 
{ 
	((BackupDaemon *)lpParam)->RunHelperThread();

	return 0;
}
#endif

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::BackupDaemon()
//		Purpose: constructor
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::BackupDaemon()
	: mState(BackupDaemon::State_Initialising),
	  mpCommandSocketInfo(0),
	  mDeleteUnusedRootDirEntriesAfter(0)
{
	// Only ever one instance of a daemon
	SSLLib::Initialise();
	
	// Initialise notifcation sent status
	for(int l = 0; l <= NotifyEvent__MAX; ++l)
	{
		mNotificationsSent[l] = false;
	}

#ifdef WIN32
	// Create a thread to handle the named pipe
	HANDLE hThread;
	unsigned int dwThreadId;

	hThread = (HANDLE) _beginthreadex( 
        	NULL,                        // default security attributes 
        	0,                           // use default stack size  
        	HelperThread,                // thread function 
        	this,                        // argument to thread function 
        	0,                           // use default creation flags 
        	&dwThreadId);                // returns the thread identifier 
#endif
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::~BackupDaemon()
//		Purpose: Destructor
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::~BackupDaemon()
{
	DeleteAllLocations();
	DeleteAllIDMaps();
	
	if(mpCommandSocketInfo != 0)
	{
		delete mpCommandSocketInfo;
		mpCommandSocketInfo = 0;
	}
}

// --------------------------------------------------------------------------
//
// 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
//
// --------------------------------------------------------------------------
const char *BackupDaemon::DaemonBanner() const
{
#ifndef NDEBUG
	// Don't display banner in debug builds
	return 0;
#else
	return BANNER_TEXT("Backup Client");
#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"))
	{
		printf(
				"==============================================================================\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(std::vector<Location *>::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 assoicated mount vector
	mIDMapMounts.clear();
}

#ifdef WIN32
void BackupDaemon::RunHelperThread(void)
{
	this->mReceivedCommandConn = false;
	mpCommandSocketInfo = new CommandSocketInfo;
	WinNamedPipeStream& rSocket(mpCommandSocketInfo->mListeningSocket);

	// loop until the parent process exits, or we decide
	// to kill the thread ourselves
	while (!IsTerminateWanted())
	{
		try
		{
			rSocket.Accept(BOX_NAMED_PIPE_NAME);
		}
		catch(std::exception &e)
		{
			::syslog(LOG_ERR, "Failed to open command socket: "
				"%s", e.what());
			SetTerminateWanted();
			break; // this is fatal to listening thread
		}
		catch(...)
		{
			::syslog(LOG_ERR, "Failed to open command socket: "
				"unknown error");
			SetTerminateWanted();
			break; // this is fatal to listening thread
		}

		try
		{
			// Errors here do not kill the thread,
			// only the current connection.

			// This next section comes from Ben's original function
			// Log
			::syslog(LOG_INFO, "Connection from command socket");

			// Send a header line summarising the configuration 
			// and current state
			const Configuration &conf(GetConfiguration());
			char summary[256];
			size_t summarySize = sprintf(summary, 
				"bbackupd: %d %d %d %d\nstate %d\n",
				conf.GetKeyValueBool("AutomaticBackup"),
				conf.GetKeyValueInt("UpdateStoreInterval"),
				conf.GetKeyValueInt("MinimumFileAge"),
				conf.GetKeyValueInt("MaxUploadWait"),
				mState);

			rSocket.Write(summary, summarySize);
			rSocket.Write("ping\n", 5);

			IOStreamGetLine readLine(rSocket);
			std::string command;

			while (rSocket.IsConnected() && 
				readLine.GetLine(command) &&
				!IsTerminateWanted())
			{
				TRACE1("Received command '%s' over "
					"command socket\n", command.c_str());

				bool sendOK = false;
				bool sendResponse = true;
				bool disconnect = false;

				// Command to process!
				if(command == "quit" || command == "")
				{
					// Close the socket.
					disconnect = true;
					sendResponse = false;
				}
				else if(command == "sync")
				{
					// Sync now!
					this->mDoSyncFlagOut = true;
					this->mSyncIsForcedOut = false;
					sendOK = true;
				}
				else if(command == "force-sync")
				{
					// Sync now (forced -- overrides any SyncAllowScript)
					this->mDoSyncFlagOut = true;
					this->mSyncIsForcedOut = true;
					sendOK = true;
				}
				else if(command == "reload")
				{
					// Reload the configuration
					SetReloadConfigWanted();
					sendOK = true;
				}
				else if(command == "terminate")
				{
					// Terminate the daemon cleanly
					SetTerminateWanted();
					sendOK = true;
				}
				else
				{
					::syslog(LOG_ERR, "Received unknown command '%s' from client", command.c_str());
					sendResponse = true;
					sendOK = false;
				}

				// Send a response back?
				if (sendResponse)
				{
					const char* response = sendOK ? "ok\n" : "error\n";
					rSocket.Write(
						response, strlen(response));
				}

				if (disconnect) 
				{
					break;
				}

				this->mReceivedCommandConn = true;
			}

			rSocket.Close();
		}
		catch(BoxException &e)
		{
			::syslog(LOG_ERR, "Communication error with "
				"control client: %s", e.what());
		}
		catch(std::exception &e)
		{
			::syslog(LOG_ERR, "Internal error in command socket "
				"thread: %s", e.what());
		}
		catch(...)
		{
			::syslog(LOG_ERR, "Communication error with control client");
		}
	}
} 
#endif

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Run()
//		Purpose: Run function for daemon
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::Run()
{
#ifdef WIN32
	// init our own timer for file diff timeouts
	InitTimer();

	try
	{
		Run2();
	}
	catch(...)
	{
		FiniTimer();
		throw;
	}

	FiniTimer();
#else // ! WIN32
	// Ignore SIGPIPE (so that if a command connection is broken, the daemon doesn't terminate)
	::signal(SIGPIPE, SIG_IGN);

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

	// Handle things nicely on exceptions
	try
	{
		Run2();
	}
	catch(...)
	{
		if(mpCommandSocketInfo != 0)
		{
			try 
			{
				delete mpCommandSocketInfo;
			}
			catch(std::exception &e)
			{
				::syslog(LOG_WARNING, "Internal error while "
					"closing command socket after "
					"another exception: %s", e.what());
			}
			catch(...)
			{
				::syslog(LOG_WARNING,
					"Error closing command socket "
					"after exception, ignored.");
			}
			mpCommandSocketInfo = 0;
		}

		throw;
	}

	// Clean up
	if(mpCommandSocketInfo != 0)
	{
		delete mpCommandSocketInfo;
		mpCommandSocketInfo = 0;
	}
#endif
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Run2()
//		Purpose: Run function for daemon (second stage)
//		Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::Run2()
{
	// Read in the certificates creating a TLS context
	TLSContext tlsContext;
	const Configuration &conf(GetConfiguration());
	std::string certFile(conf.GetKeyValue("CertificateFile"));
	std::string keyFile(conf.GetKeyValue("PrivateKeyFile"));
	std::string caFile(conf.GetKeyValue("TrustedCAsFile"));
	tlsContext.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").c_str());

	// max diffing time, keep-alive time
	if(conf.KeyExists("MaximumDiffingTime"))
	{
		BackupClientContext::SetMaximumDiffingTime(conf.GetKeyValueInt("MaximumDiffingTime"));
	}
	if(conf.KeyExists("KeepAliveTime"))
	{
		BackupClientContext::SetKeepAliveTime(conf.GetKeyValueInt("KeepAliveTime"));
	}

	// Setup various timings
	
	// How often to connect to the store (approximate)
	box_time_t updateStoreInterval = SecondsToBoxTime(conf.GetKeyValueInt("UpdateStoreInterval"));

	// But are we connecting automatically?
	bool automaticBackup = conf.GetKeyValueBool("AutomaticBackup");
	
	// 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
	maxUploadWait = (maxUploadWait > minimumFileAge)?(maxUploadWait - minimumFileAge):(0);

	// When the next sync should take place -- which is ASAP
	box_time_t nextSyncTime = 0;

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

 	// --------------------------------------------------------------------------------------------
 
	// And what's the current client store marker?
	int64_t clientStoreMarker = 
		BackupClientContext::ClientStoreMarker_NotKnown;
	// haven't contacted the store yet

 	bool deleteStoreObjectInfoFile = DeserializeStoreObjectInfo(
		clientStoreMarker, lastSyncTime, nextSyncTime);
 
	// --------------------------------------------------------------------------------------------
	

	// Set state
	SetState(State_Idle);

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

		// Is a delay necessary?
		{
			box_time_t currentTime;
			do
			{
				// Need to check the stop run thing here too, so this loop isn't run if we should be stopping
				if(StopRun()) break;
				
				currentTime = GetCurrentBoxTime();
	
				// Pause a while, but no more than MAX_SLEEP_TIME seconds (use the conditional because times are unsigned)
				box_time_t requiredDelay = (nextSyncTime < currentTime)?(0):(nextSyncTime - currentTime);
				// If there isn't automatic backup happening, set a long delay. And limit delays at the same time.
				if(!automaticBackup || requiredDelay > SecondsToBoxTime(MAX_SLEEP_TIME))
					requiredDelay = SecondsToBoxTime(MAX_SLEEP_TIME);

				// Only do the delay if there is a delay required
				if(requiredDelay > 0)
				{
					// Sleep somehow. There are choices on how this should be done, depending on the state of the control connection
					if(mpCommandSocketInfo != 0)
					{
						// A command socket exists, so sleep by handling connections with it
						WaitOnCommandSocket(requiredDelay, doSync, doSyncForcedByCommand);
					}
					else
					{
						// No command socket or connection, just do a normal sleep
						time_t sleepSeconds = BoxTimeToSeconds(requiredDelay);
						::sleep((sleepSeconds <= 0)?1:sleepSeconds);
					}
				}
				
			} while((!automaticBackup || (currentTime < nextSyncTime)) && !doSync && !StopRun());
		}

		// Time of sync start, and if it's time for another sync (and we're doing automatic syncs), set the flag
		box_time_t currentSyncStartTime = GetCurrentBoxTime();
		if(automaticBackup && currentSyncStartTime >= nextSyncTime)
		{
			doSync = true;
		}
		
		// Use a script to see if sync is allowed now?
		if(!doSyncForcedByCommand && doSync && !StopRun())
		{
			int d = UseScriptToSeeIfSyncAllowed();
			if(d > 0)
			{
				// Script has asked for a delay
				nextSyncTime = GetCurrentBoxTime() + SecondsToBoxTime(d);
				doSync = false;
			}
		}

		// Ready to sync? (but only if we're not supposed to be stopping)
		if(doSync && !StopRun())
		{
			// Touch a file to record times in filesystem
			TouchFileInWorkingDir("last_sync_start");
		
			// Tell anything connected to the command socket
			SendSyncStartOrFinish(true /* start */);
			
			// Reset statistics on uploads
			BackupStoreFile::ResetStats();
			
			// Calculate the sync period of files to examine
			box_time_t syncPeriodStart = lastSyncTime;
			box_time_t syncPeriodEnd = currentSyncStartTime - minimumFileAge;
			// Check logic
			ASSERT(syncPeriodEnd > syncPeriodStart);
			// Paranoid check on sync times
			if(syncPeriodStart >= syncPeriodEnd) continue;
			
			// 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 eligable 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));
			}

			// Delete the serialised store object file,
			// so that we don't try to reload it after a
			// partially completed backup
			if(deleteStoreObjectInfoFile && 
				!DeleteStoreObjectInfo())
			{
				::syslog(LOG_ERR, "Failed to delete the "
					"StoreObjectInfoFile, backup cannot "
					"continue safely.");
				// prevent runaway process where the logs fill up -- without this
				// the log message will be emitted in a tight loop.
				::sleep(60); 
				continue;
			}

			// In case the backup throws an exception,
			// we should not try to delete the store info
			// object file again.
			deleteStoreObjectInfoFile = false;
			
			// Do sync
			bool errorOccurred = false;
			int errorCode = 0, errorSubCode = 0;
			const char* errorString = "unknown";

			try
			{
				// Set state and log start
				SetState(State_Connected);
				::syslog(LOG_INFO, "Beginning scan of local files");

				// Then create a client context object (don't just connect, as this may be unnecessary)
				BackupClientContext clientContext(*this, tlsContext, conf.GetKeyValue("StoreHostname"),
					conf.GetKeyValueInt("AccountNumber"), conf.GetKeyValueBool("ExtendedLogging"));
					
				// Set up the sync parameters
				BackupClientDirectoryRecord::SyncParams params(*this, clientContext);
				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"));
				
				// Set store marker
				clientContext.SetClientStoreMarker(clientStoreMarker);
				
				// Set up the locations, if necessary -- need to do it here so we have a (potential) connection to use
				if(mLocations.empty())
				{
					const Configuration &locations(conf.GetSubConfiguration("BackupLocations"));
					
					// Make sure all the directory records are set up
					SetupLocations(clientContext, locations);
				}
				
				// Get some ID maps going
				SetupIDMapsForSync();

				// Delete any unused directories?
				DeleteUnusedRootDirEntries(clientContext);
								
				// Go through the records, syncing them
				for(std::vector<Location *>::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
					(*i)->mpDirectoryRecord->SyncDirectory(params, BackupProtocolClientListDirectory::RootDirectory, (*i)->mPath);

					// Unset exclude lists (just in case)
					clientContext.SetExcludeLists(0, 0);
				}
				
				// Errors reading any files?
				if(params.mReadErrorsOnFilesystemObjects)
				{
					// Notify administrator
					NotifySysadmin(NotifyEvent_ReadError);
				}
				else
				{
					// Unset the read error flag, so the error is
					// reported again in the future
					mNotificationsSent[NotifyEvent_ReadError] = false;
				}
				
				// Perform any deletions required -- these are delayed until the end
				// to allow renaming to happen neatly.
				clientContext.PerformDeletions();

				// Close any open connection
				clientContext.CloseAnyOpenConnection();
				
				// Get the new store marker
				clientStoreMarker = clientContext.GetClientStoreMarker();
				
				// Check the storage limit
				if(clientContext.StorageLimitExceeded())
				{
					// Tell the sysadmin about this
					NotifySysadmin(NotifyEvent_StoreFull);
				}
				else
				{
					// 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)
					lastSyncTime = syncPeriodEnd;
					// unflag the storage full notify flag so that next time the store is full, and alert will be sent
					mNotificationsSent[NotifyEvent_StoreFull] = false;
				}
				
				// Calculate when the next sync run should be
				nextSyncTime = currentSyncStartTime + updateStoreInterval + Random::RandomInt(updateStoreInterval >> SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY);
			
				// Commit the ID Maps
				CommitIDMapsAfterSync();

				// Log
				::syslog(LOG_INFO, "Finished scan of local files");

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

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

				deleteStoreObjectInfoFile = 
					SerializeStoreObjectInfo(
						clientStoreMarker, 
						lastSyncTime, nextSyncTime);

				// --------------------------------------------------------------------------------------------
			}
			catch(BoxException &e)
			{
				errorOccurred = true;
				errorString = e.what();
				errorCode = e.GetType();
				errorSubCode = e.GetSubType();
			}
			catch(std::exception &e)
			{
				::syslog(LOG_ERR, "Internal error during "
					"backup run: %s", e.what());
				errorOccurred = true;
			}
			catch(...)
			{
				// TODO: better handling of exceptions here... need to be very careful
				errorOccurred = true;
			}
			
			if(errorOccurred)
			{
				// Is it a berkely db failure?
				bool isBerkelyDbFailure = (errorCode == BackupStoreException::ExceptionType
					&& errorSubCode == BackupStoreException::BerkelyDBFailure);
				if(isBerkelyDbFailure)
				{
					// Delete corrupt files
					DeleteCorruptBerkelyDbFiles();
				}

				// Clear state data
				syncPeriodStart = 0;	// go back to beginning of time
				clientStoreMarker = BackupClientContext::ClientStoreMarker_NotKnown;	// no store marker, so download everything
				DeleteAllLocations();
				DeleteAllIDMaps();

				// Handle restart?
				if(StopRun())
				{
					::syslog(LOG_INFO, "Exception (%d/%d) due to signal", errorCode, errorSubCode);
					return;
				}

				// If the Berkely db files get corrupted, delete them and try again immediately
				if(isBerkelyDbFailure)
				{
					::syslog(LOG_ERR, "Berkely db inode map files corrupted, deleting and restarting scan. Renamed files and directories will not be tracked until after this scan.\n");
					::sleep(1);
				}
				else
				{
					// Not restart/terminate, pause and retry
					SetState(State_Error);
					::syslog(LOG_ERR, 
						"Exception caught (%s %d/%d), "
						"reset state and waiting "
						"to retry...", 
						errorString, errorCode, 
						errorSubCode);
					::sleep(10);
					nextSyncTime = currentSyncStartTime + 
						SecondsToBoxTime(90) +
						Random::RandomInt(
							updateStoreInterval >> 
							SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY);
				}
			}

			// Log the stats
			::syslog(LOG_INFO, "File statistics: total file size uploaded %lld, bytes already on server %lld, encoded size %lld",
				BackupStoreFile::msStats.mBytesInEncodedFiles, BackupStoreFile::msStats.mBytesAlreadyOnServer,
				BackupStoreFile::msStats.mTotalFileStreamSize);
			BackupStoreFile::ResetStats();

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

			// Touch a file to record times in filesystem
			TouchFileInWorkingDir("last_sync_finish");
		}
		
		// Set state
		SetState(storageLimitExceeded?State_StorageLimitExceeded:State_Idle);

	} while(!StopRun());
	
	// Make sure we have a clean start next time round (if restart)
	DeleteAllLocations();
	DeleteAllIDMaps();
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::UseScriptToSeeIfSyncAllowed()
//		Purpose: Private. Use a script to see if the sync should be allowed (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);

	// Run it?
	pid_t pid = 0;
	try
	{
		std::auto_ptr<IOStream> pscript(LocalProcessStream(conf.GetKeyValue("SyncAllowScript").c_str(), pid));

		// Read in the result
		IOStreamGetLine getLine(*pscript);
		std::string line;
		if(getLine.GetLine(line, true, 30000)) // 30 seconds should be enough
		{
			// Got a string, intepret
			if(line == "now")
			{
				// Script says do it now. Obey.
				waitInSeconds = -1;
			}
			else
			{
				// How many seconds to wait?
				waitInSeconds = BoxConvert::Convert<int32_t, const std::string&>(line);
				::syslog(LOG_INFO, "Delaying sync by %d seconds (SyncAllowScript '%s')", waitInSeconds, conf.GetKeyValue("SyncAllowScript").c_str());
			}
		}
		
	}
	catch(std::exception &e)
	{
		::syslog(LOG_ERR, "Internal error running SyncAllowScript: "
			"%s", e.what());
	}
	catch(...)
	{
		// Ignore any exceptions
		// Log that something bad happened
		::syslog(LOG_ERR, "Error running SyncAllowScript '%s'", conf.GetKeyValue("SyncAllowScript").c_str());
	}

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

	return waitInSeconds;
}



// --------------------------------------------------------------------------
//
// 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)
{
#ifdef WIN32
	// Really could use some interprocess protection, mutex etc
	// any side effect should be too bad???? :)
	DWORD timeout = (DWORD)BoxTimeToMilliSeconds(RequiredDelay);

	while ( this->mReceivedCommandConn == false )
	{
		Sleep(1);

		if ( timeout == 0 )
		{
			DoSyncFlagOut = false;
			SyncIsForcedOut = false;
			return;
		}
		timeout--;
	}
	this->mReceivedCommandConn = false;
	DoSyncFlagOut = this->mDoSyncFlagOut;
	SyncIsForcedOut = this->mSyncIsForcedOut;

	return;
#else // ! WIN32
	ASSERT(mpCommandSocketInfo != 0);
	if(mpCommandSocketInfo == 0) {::sleep(1); return;} // failure case isn't too bad
	
	TRACE1("Wait on command socket, delay = %lld\n", 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(mpCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			// No connection, listen for a new one
			mpCommandSocketInfo->mpConnectedSocket.reset(mpCommandSocketInfo->mListeningSocket.Accept(timeout).release());
			
			if(mpCommandSocketInfo->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;
				::syslog(LOG_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(mpCommandSocketInfo->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
					::syslog(LOG_ERR, "Incoming command connection from peer had different user ID than this process, or security check could not be completed.");
					mpCommandSocketInfo->mpConnectedSocket.reset();
					return;
				}
				else
				{
					// Log
					::syslog(LOG_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);
					mpCommandSocketInfo->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(mpCommandSocketInfo->mpConnectedSocket.get() != 0);
		
		// Is there a getline object ready?
		if(mpCommandSocketInfo->mpGetLine == 0)
		{
			// Create a new one
			mpCommandSocketInfo->mpGetLine = new IOStreamGetLine(*(mpCommandSocketInfo->mpConnectedSocket.get()));
		}
		
		// Ping the remote side, to provide errors which will mean the socket gets closed
		mpCommandSocketInfo->mpConnectedSocket->Write("ping\n", 5);
		
		// Wait for a command or something on the socket
		std::string command;
		while(mpCommandSocketInfo->mpGetLine != 0 && !mpCommandSocketInfo->mpGetLine->IsEOF()
			&& mpCommandSocketInfo->mpGetLine->GetLine(command, false /* no preprocessing */, timeout))
		{
			TRACE1("Receiving command '%s' over command socket\n", command.c_str());
			
			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)
			{
				mpCommandSocketInfo->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(mpCommandSocketInfo->mpGetLine != 0 && mpCommandSocketInfo->mpGetLine->IsEOF())
		{
			CloseCommandConnection();
		}
	}
	catch(std::exception &e)
	{
		::syslog(LOG_ERR, "Internal error in command socket thread: "
			"%s", e.what());
		// If an error occurs, and there is a connection active, just close that
		// connection and continue. Otherwise, let the error propagate.
		if(mpCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			throw; // thread will die
		}
		else
		{
			// Close socket and ignore error
			CloseCommandConnection();
		}
	}
	catch(...)
	{
		// If an error occurs, and there is a connection active, just close that
		// connection and continue. Otherwise, let the error propagate.
		if(mpCommandSocketInfo->mpConnectedSocket.get() == 0)
		{
			throw; // thread will die
		}
		else
		{
			// Close socket and ignore error
			CloseCommandConnection();
		}
	}
#endif // WIN32
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::CloseCommandConnection()
//		Purpose: Close the command connection, ignoring any errors
//		Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::CloseCommandConnection()
{
#ifndef WIN32
	try
	{
		TRACE0("Closing command connection\n");
		
		if(mpCommandSocketInfo->mpGetLine)
		{
			delete mpCommandSocketInfo->mpGetLine;
			mpCommandSocketInfo->mpGetLine = 0;
		}
		mpCommandSocketInfo->mpConnectedSocket.reset();
	}
	catch(std::exception &e)
	{
		::syslog(LOG_ERR, "Internal error while closing command "
			"socket: %s", e.what());
	}
	catch(...)
	{
		// Ignore any errors
	}
#endif
}


// --------------------------------------------------------------------------
//
// 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.

#ifdef __MINGW32__
#warning race condition: what happens if socket is closed?
#endif

	if (mpCommandSocketInfo != NULL &&
#ifdef WIN32
	    mpCommandSocketInfo->mListeningSocket.IsConnected()
#else
	    mpCommandSocketInfo->mpConnectedSocket.get() != 0
#endif
	    )
	{
		const char* message = SendStart ? "start-sync\n" : "finish-sync\n";
		try
		{
#ifdef WIN32
			mpCommandSocketInfo->mListeningSocket.Write(message, 
				(int)strlen(message));
#else
			mpCommandSocketInfo->mpConnectedSocket->Write(message,
				strlen(message));
#endif
		}
		catch(std::exception &e)
		{
			::syslog(LOG_ERR, "Internal error while sending to "
				"command socket client: %s", 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)
{
	if(!mLocations.empty())
	{
		// Looks correctly set up
		return;
	}

	// Make sure that if a directory is reinstated, then it doesn't get deleted	
	mDeleteUnusedRootDirEntriesAfter = 0;
	mUnusedRootDirEntries.clear();

	// Just a check to make sure it's right.
	DeleteAllLocations();
	
	// Going to need a copy of the root directory. Get a connection, and fetch it.
	BackupProtocolClient &connection(rClientContext.GetConnection());
	
	// Ask server for a list of everything in the root directory, which is a directory itself
	std::auto_ptr<BackupProtocolClientSuccess> dirreply(connection.QueryListDirectory(
			BackupProtocolClientListDirectory::RootDirectory,
			BackupProtocolClientListDirectory::Flags_Dir,	// only directories
			BackupProtocolClientListDirectory::Flags_Deleted | BackupProtocolClientListDirectory::Flags_OldVersion, // exclude old/deleted stuff
			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)
		{
			TRACE1("Found mount point at %s\n", 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)
		{
			TRACE1("Found mount point at %s\n", 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 NDEBUG
	{
		std::set<std::string, mntLenCompare>::const_reverse_iterator i(mountPoints.rbegin());
		ASSERT(*i == "/");
	}
#endif // n NDEBUG
#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.
	for(std::list<std::pair<std::string, Configuration> >::const_iterator i = rLocationsConf.mSubConfigurations.begin();
		i != rLocationsConf.mSubConfigurations.end(); ++i)
	{
TRACE0("new location\n");
		// Create a record for it
		Location *ploc = new Location;
		try
		{
			// Setup names in the location record
			ploc->mName = i->first;
			ploc->mPath = i->second.GetKeyValue("Path");
			
			// Read the exclude lists from the Configuration
			ploc->mpExcludeFiles = BackupClientMakeExcludeList_Files(i->second);
			ploc->mpExcludeDirs = BackupClientMakeExcludeList_Dirs(i->second);
			
			// 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_EXCEPTION(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] != '/')
				{
					::syslog(LOG_ERR, "Location path '%s' isn't absolute", ploc->mPath.c_str());
				}
				// Go through the mount points found, and find a suitable one
				std::string mountName("/");
				{
					std::set<std::string, mntLenCompare>::const_iterator i(mountPoints.begin());
					TRACE1("%d potential mount points\n", mountPoints.size());
					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)
						TRACE1("checking against mount point %s\n", i->c_str());
						if(::strncmp(i->c_str(), ploc->mPath.c_str(), i->size()) == 0)
						{
							// Match
							mountName = *i;
							break;
						}
					}
					TRACE2("mount point chosen for %s is %s\n", ploc->mPath.c_str(), mountName.c_str());
				}

#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?
			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);
			}
			else
			{
				// 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;
				attr.ReadAttributes(ploc->mPath.c_str(), true /* directories have zero mod times */,
					0 /* not interested in mod time */, &attrModTime /* get the attribute modification time */);
				
				// Execute create directory command
				MemBlockStream attrStream(attr);
				std::auto_ptr<BackupProtocolClientSuccess> dirCreate(connection.QueryCreateDirectory(
					BackupProtocolClientListDirectory::RootDirectory,
					attrModTime, dirname, attrStream));
					
				// Object ID for later creation
				oid = dirCreate->GetObjectID();
			}

			// Create and store the directory object for the root of this location
			ASSERT(oid != 0);
			BackupClientDirectoryRecord *precord = new BackupClientDirectoryRecord(oid, i->first);
			ploc->mpDirectoryRecord.reset(precord);
			
			// Push it back on the vector of locations
			mLocations.push_back(ploc);
		}
		catch(...)
		{
			delete ploc;
			ploc = 0;
			throw;
		}
	}
	
	// Any entries in the root directory which need deleting?
	if(dir.GetNumberOfEntries() > 0)
	{
		::syslog(LOG_INFO, "%d redundant locations in root directory found, will delete from store after %d seconds.",
			dir.GetNumberOfEntries(), BACKUP_DELETE_UNUSED_ROOT_ENTRIES_AFTER);

		// 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
			::syslog(LOG_INFO, "Unused location in root: %s", name.c_str());
		}
		ASSERT(mUnusedRootDirEntries.size() > 0);
		// Time to delete them
		mDeleteUnusedRootDirEntriesAfter =
			GetCurrentBoxTime() + SecondsToBoxTime(BACKUP_DELETE_UNUSED_ROOT_ENTRIES_AFTER);
	}
}


// --------------------------------------------------------------------------
//
// 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()
{
	// Need to do different things depending on whether it's an in memory implementation,
	// or whether it's all stored on disc.
	
#ifdef BACKIPCLIENTINODETOIDMAP_IN_MEMORY_IMPLEMENTATION

	// Make sure we have some blank, empty ID maps
	DeleteIDMapVector(mNewIDMaps);
	FillIDMapVector(mNewIDMaps, true /* new maps */);

	// Then make sure that the current maps have objects, even if they are empty
	// (for the very first run)
	if(mCurrentIDMaps.empty())
	{
		FillIDMapVector(mCurrentIDMaps, false /* current maps */);
	}

#else

	// Make sure we have some blank, empty ID maps
	DeleteIDMapVector(mNewIDMaps);
	FillIDMapVector(mNewIDMaps, true /* new maps */);
	DeleteIDMapVector(mCurrentIDMaps);
	FillIDMapVector(mCurrentIDMaps, false /* new maps */);

#endif
}


// --------------------------------------------------------------------------
//
// 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";
			}

			// 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
		TRACE1("Deleting %s\n", filename.c_str());
		::unlink(filename.c_str());
		
		// Add a suffix for the new map
		filename += ".n";

		// Delete that too
		TRACE1("Deleting %s\n", filename.c_str());
		::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()
{
	// Need to do different things depending on whether it's an in memory implementation,
	// or whether it's all stored on disc.
	
#ifdef BACKIPCLIENTINODETOIDMAP_IN_MEMORY_IMPLEMENTATION
	// Remove the current ID maps
	DeleteIDMapVector(mCurrentIDMaps);

	// Copy the (pointers to) "new" maps over to be the new "current" maps
	mCurrentIDMaps = mNewIDMaps;
	
	// Clear the new ID maps vector (not delete them!)
	mNewIDMaps.clear();

#else

	// 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)
		{
			THROW_EXCEPTION(CommonException, OSFileError)
		}
	}

#endif
}



// --------------------------------------------------------------------------
//
// 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
		toDel->Close();
		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(std::vector<Location *>::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];
	char newStateSize = sprintf(newState, "state %d\n", State);

#ifdef WIN32
	#ifndef _MSC_VER
		#warning FIX ME: race condition
	#endif

	// what happens if the socket is closed by the other thread before
	// we can write to it? Null pointer deref at best.
	if (mpCommandSocketInfo && 
	    mpCommandSocketInfo->mListeningSocket.IsConnected())
	{
		try
		{
			mpCommandSocketInfo->mListeningSocket.Write(newState, newStateSize);
		}
		catch(std::exception &e)
		{
			::syslog(LOG_ERR, "Internal error while writing state "
				"to command socket: %s", e.what());
			CloseCommandConnection();
		}
		catch(...)
		{
			CloseCommandConnection();
		}
	}
#else
	if(mpCommandSocketInfo != 0 && mpCommandSocketInfo->mpConnectedSocket.get() != 0)
	{
		// Something connected to the command socket, tell it about the new state
		try
		{
			mpCommandSocketInfo->mpConnectedSocket->Write(newState, newStateSize);
		}
		catch(std::exception &e)
		{
			::syslog(LOG_ERR, "Internal error while writing state "
				"to command socket: %s", e.what());
			CloseCommandConnection();
		}
		catch(...)
		{
			CloseCommandConnection();
		}
	}
#endif
}


// --------------------------------------------------------------------------
//
// 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
	FileStream touch(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
}


// --------------------------------------------------------------------------
//
// 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(int Event)
{
	static const char *sEventNames[] = {"store-full", "read-error", 0};

	TRACE1("BackupDaemon::NotifySysadmin() called, event = %d\n", Event);

	if(Event < 0 || Event > NotifyEvent__MAX)
	{
		THROW_EXCEPTION(BackupStoreException, BadNotifySysadminEventCode);
	}

	// Don't send lots of repeated messages
	if(mNotificationsSent[Event])
	{
		return;
	}

	// Is there a notifation script?
	const Configuration &conf(GetConfiguration());
	if(!conf.KeyExists("NotifyScript"))
	{
		// Log, and then return
		::syslog(LOG_ERR, "Not notifying administrator about event %s -- set NotifyScript to do this in future", sEventNames[Event]);
		return;
	}

	// Script to run
	std::string script(conf.GetKeyValue("NotifyScript") + ' ' + sEventNames[Event]);
	
	// Log what we're about to do
	::syslog(LOG_INFO, "About to notify administrator about event %s, running script '%s'", sEventNames[Event], script.c_str());
	
	// Then do it
	if(::system(script.c_str()) != 0)
	{
		::syslog(LOG_ERR, "Notify script returned an error code. ('%s')", script.c_str());
	}

	// Flag that this is done so the administrator isn't constantly bombarded with lots of errors
	mNotificationsSent[Event] = true;
}


// --------------------------------------------------------------------------
//
// 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() || mDeleteUnusedRootDirEntriesAfter == 0)
	{
		// Nothing to do.
		return;
	}
	
	// Check time
	if(GetCurrentBoxTime() < mDeleteUnusedRootDirEntriesAfter)
	{
		// Too early to delete files
		return;
	}

	// Entries to delete, and it's the right time to do so...
	::syslog(LOG_INFO, "Deleting unused locations from store root...");
	BackupProtocolClient &connection(rContext.GetConnection());
	for(std::vector<std::pair<int64_t,std::string> >::iterator i(mUnusedRootDirEntries.begin()); i != mUnusedRootDirEntries.end(); ++i)
	{
		connection.QueryDeleteDirectory(i->first);
		
		// Log this
		::syslog(LOG_INFO, "Deleted %s (ID %08llx) from store root", i->second.c_str(), i->first);
	}

	// 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::Location::Location()
//		Purpose: Constructor
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
BackupDaemon::Location::Location()
	: mIDMapIndex(0),
	  mpExcludeFiles(0),
	  mpExcludeDirs(0)
{
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Location::~Location()
//		Purpose: Destructor
//		Created: 11/11/03
//
// --------------------------------------------------------------------------
BackupDaemon::Location::~Location()
{
	// Clean up exclude locations
	if(mpExcludeDirs != 0)
	{
		delete mpExcludeDirs;
		mpExcludeDirs = 0;
	}
	if(mpExcludeFiles != 0)
	{
		delete mpExcludeFiles;
		mpExcludeFiles = 0;
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Location::Deserialize(Archive & rArchive)
//		Purpose: Deserializes this object instance from a stream of bytes, using an Archive abstraction.
//
//		Created: 2005/04/11
//
// --------------------------------------------------------------------------
void BackupDaemon::Location::Deserialize(Archive &rArchive)
{
	//
	//
	//
	mpDirectoryRecord.reset(NULL);
	if (mpExcludeFiles)
	{
		delete mpExcludeFiles;
		mpExcludeFiles = NULL;
	}
	if (mpExcludeDirs)
	{
		delete mpExcludeDirs;
		mpExcludeDirs = NULL;
	}

	//
	//
	//
	rArchive.Read(mName);
	rArchive.Read(mPath);
	rArchive.Read(mIDMapIndex);

	//
	//
	//
	int64_t aMagicMarker = 0;
	rArchive.Read(aMagicMarker);

	if (aMagicMarker == ARCHIVE_MAGIC_VALUE_NOOP)
	{
		// NOOP
	}
	else if (aMagicMarker == ARCHIVE_MAGIC_VALUE_RECURSE)
	{
		BackupClientDirectoryRecord *pSubRecord = new BackupClientDirectoryRecord(0, "");
		if (!pSubRecord)
			throw std::bad_alloc();

		mpDirectoryRecord.reset(pSubRecord);
		mpDirectoryRecord->Deserialize(rArchive);
	}
	else
	{
		// there is something going on here
		THROW_EXCEPTION(CommonException, Internal)
	}

	//
	//
	//
	rArchive.Read(aMagicMarker);

	if (aMagicMarker == ARCHIVE_MAGIC_VALUE_NOOP)
	{
		// NOOP
	}
	else if (aMagicMarker == ARCHIVE_MAGIC_VALUE_RECURSE)
	{
		mpExcludeFiles = new ExcludeList;
		if (!mpExcludeFiles)
			throw std::bad_alloc();

		mpExcludeFiles->Deserialize(rArchive);
	}
	else
	{
		// there is something going on here
		THROW_EXCEPTION(CommonException, Internal)
	}

	//
	//
	//
	rArchive.Read(aMagicMarker);

	if (aMagicMarker == ARCHIVE_MAGIC_VALUE_NOOP)
	{
		// NOOP
	}
	else if (aMagicMarker == ARCHIVE_MAGIC_VALUE_RECURSE)
	{
		mpExcludeDirs = new ExcludeList;
		if (!mpExcludeDirs)
			throw std::bad_alloc();

		mpExcludeDirs->Deserialize(rArchive);
	}
	else
	{
		// there is something going on here
		THROW_EXCEPTION(CommonException, Internal)
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::Location::Serialize(Archive & rArchive)
//		Purpose: Serializes this object instance into a stream of bytes, using an Archive abstraction.
//
//		Created: 2005/04/11
//
// --------------------------------------------------------------------------
void BackupDaemon::Location::Serialize(Archive & rArchive) const
{
	//
	//
	//
	rArchive.Write(mName);
	rArchive.Write(mPath);
	rArchive.Write(mIDMapIndex);

	//
	//
	//
	if (mpDirectoryRecord.get() == NULL)
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_NOOP;
		rArchive.Write(aMagicMarker);
	}
	else
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_RECURSE; // be explicit about whether recursion follows
		rArchive.Write(aMagicMarker);

		mpDirectoryRecord->Serialize(rArchive);
	}

	//
	//
	//
	if (!mpExcludeFiles)
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_NOOP;
		rArchive.Write(aMagicMarker);
	}
	else
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_RECURSE; // be explicit about whether recursion follows
		rArchive.Write(aMagicMarker);

		mpExcludeFiles->Serialize(rArchive);
	}

	//
	//
	//
	if (!mpExcludeDirs)
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_NOOP;
		rArchive.Write(aMagicMarker);
	}
	else
	{
		int64_t aMagicMarker = ARCHIVE_MAGIC_VALUE_RECURSE; // be explicit about whether recursion follows
		rArchive.Write(aMagicMarker);

		mpExcludeDirs->Serialize(rArchive);
	}
}

// --------------------------------------------------------------------------
//
// 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(int64_t aClientStoreMarker, 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 = 1;

bool BackupDaemon::SerializeStoreObjectInfo(int64_t aClientStoreMarker, 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(aClientStoreMarker);
		anArchive.Write(theLastSyncTime);
		anArchive.Write(theNextSyncTime);

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

		for (int v = 0; v < iCount; v++)
		{
			ASSERT(mLocations[v]);
			mLocations[v]->Serialize(anArchive);
		}

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

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

		//
		//
		//
		aFile.Close();
		::syslog(LOG_INFO, "Saved store object info file '%s'", 
			StoreObjectInfoFile.c_str());
	}
	catch(std::exception &e)
	{
		::syslog(LOG_ERR, "Internal error writing store object "
			"info file (%s): %s",
			StoreObjectInfoFile.c_str(), e.what());
	}
	catch(...)
	{
		::syslog(LOG_ERR, "Internal error writing store object "
			"info file (%s): unknown error",
			StoreObjectInfoFile.c_str());
	}

	DeleteAllLocations();
	catch(std::exception &e)
	{
		::syslog(LOG_WARNING, "Requested store object info file '%s' "
			"not accessible or could not be created: %s", 
			StoreObjectInfoFile.c_str(), e.what());
	}
	catch(...)
	{
		::syslog(LOG_WARNING, "Requested store object info file '%s' "
			"not accessible or could not be created: "
			"unknown error", StoreObjectInfoFile.c_str());
	}

	return created;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupDaemon::DeserializeStoreObjectInfo(int64_t & aClientStoreMarker, 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(int64_t & aClientStoreMarker, 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)
		{
			::syslog(LOG_WARNING, "Store object info file '%s' "
				"is not a valid or compatible serialised "
				"archive. Will re-cache from store.", 
				StoreObjectInfoFile.c_str());
			return false;
		}

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

		if (strMagicValue != STOREOBJECTINFO_MAGIC_ID_STRING)
		{
			::syslog(LOG_WARNING, "Store object info file '%s' "
				"is not a valid or compatible serialised "
				"archive. Will re-cache from store.", 
				StoreObjectInfoFile.c_str());
			return false;
		}

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

		if (iVersion != STOREOBJECTINFO_VERSION)
		{
			::syslog(LOG_WARNING, "Store object info file '%s' "
				"version %d unsupported. "
				"Will re-cache from store.", 
				StoreObjectInfoFile.c_str(), 
				iVersion);
			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())
		{
			::syslog(LOG_WARNING, "Store object info file '%s' "
				"out of date. Will re-cache from store", 
				StoreObjectInfoFile.c_str());
			return false;
		}

		//
		// this is it, go at it
		//
		anArchive.Read(aClientStoreMarker);
		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);
		}

		//
		//
		//
		aFile.Close();
		::syslog(LOG_INFO, "Loaded store object info file '%s', "
			"version [%d]", StoreObjectInfoFile.c_str(), 
			iVersion);

		return true;
	} 
	catch(std::exception &e)
	{
		::syslog(LOG_ERR, "Internal error reading store object "
			"info file (%s): %s",
			StoreObjectInfoFile.c_str(), e.what());
	}
	catch(...)
	{
		::syslog(LOG_ERR, "Internal error reading store object "
			"info file (%s): unknown error",
			StoreObjectInfoFile.c_str());
	}

	DeleteAllLocations();

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

	::syslog(LOG_WARNING, "Requested store object info file '%s' "
		"does not exist, not accessible, or inconsistent. "
		"Will re-cache from store.", 
		StoreObjectInfoFile.c_str());

	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
		::syslog(LOG_ERR, "Expected to be able to delete "
			"store object info file '%s', but the file did not exist.",
			storeObjectInfoFile.c_str());
		// Return true to stop things going around in a loop
		return true;
	}

	// Actually delete it
	if(::unlink(storeObjectInfoFile.c_str()) != 0)
	{
		::syslog(LOG_ERR, "Failed to delete the old "
			"store object info file '%s': %s",
			storeObjectInfoFile.c_str(), strerror(errno));
		return false;
	}

	return true;
}