summaryrefslogtreecommitdiff
path: root/bin/bbackupquery/BackupQueries.cpp
blob: 6f07525471e372674c6080edbceb40d364a1679b (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
// --------------------------------------------------------------------------
//
// File
//		Name:    BackupQueries.cpp
//		Purpose: Perform various queries on the backup store server.
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------

#include "Box.h"

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifdef HAVE_DIRENT_H
	#include <dirent.h>
#endif

#include <set>
#include <limits>

#include "BackupQueries.h"
#include "Utils.h"
#include "Configuration.h"
#include "autogen_BackupProtocolClient.h"
#include "BackupStoreFilenameClear.h"
#include "BackupStoreDirectory.h"
#include "IOStream.h"
#include "BoxTimeToText.h"
#include "FileStream.h"
#include "BackupStoreFile.h"
#include "TemporaryDirectory.h"
#include "FileModificationTime.h"
#include "BackupClientFileAttributes.h"
#include "CommonException.h"
#include "BackupClientRestore.h"
#include "BackupStoreException.h"
#include "ExcludeList.h"
#include "BackupClientMakeExcludeList.h"

#include "MemLeakFindOn.h"

// min() and max() macros from stdlib.h break numeric_limits<>::min(), etc.
#undef min
#undef max

#define COMPARE_RETURN_SAME			1
#define COMPARE_RETURN_DIFFERENT	2
#define COMPARE_RETURN_ERROR		3


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::BackupQueries()
//		Purpose: Constructor
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
BackupQueries::BackupQueries(BackupProtocolClient &rConnection, const Configuration &rConfiguration)
	: mrConnection(rConnection),
	  mrConfiguration(rConfiguration),
	  mQuitNow(false),
	  mRunningAsRoot(false),
	  mWarnedAboutOwnerAttributes(false),
	  mReturnCode(0)		// default return code
{
	#ifdef WIN32
	mRunningAsRoot = TRUE;
	#else
	mRunningAsRoot = (::geteuid() == 0);
	#endif
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::~BackupQueries()
//		Purpose: Destructor
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
BackupQueries::~BackupQueries()
{
}

typedef struct
{
	const char* name;
	const char* opts;
} QueryCommandSpecification;

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::DoCommand(const char *)
//		Purpose: Perform a command
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
void BackupQueries::DoCommand(const char *Command)
{
	// is the command a shell command?
	if(Command[0] == 's' && Command[1] == 'h' && Command[2] == ' ' && Command[3] != '\0')
	{
		// Yes, run shell command
		::system(Command + 3);
		return;
	}

	// split command into components
	std::vector<std::string> cmdElements;
	std::string options;
	{
		const char *c = Command;
		bool inQuoted = false;
		bool inOptions = false;
		
		std::string s;
		while(*c != 0)
		{
			// Terminating char?
			if(*c == ((inQuoted)?'"':' '))
			{
				if(!s.empty()) cmdElements.push_back(s);
				s.resize(0);
				inQuoted = false;
				inOptions = false;
			}
			else
			{
				// No. Start of quoted parameter?
				if(s.empty() && *c == '"')
				{
					inQuoted = true;
				}
				// Start of options?
				else if(s.empty() && *c == '-')
				{
					inOptions = true;
				}
				else
				{
					if(inOptions)
					{
						// Option char
						options += *c;
					}
					else
					{
						// Normal string char
						s += *c;
					}
				}
			}
		
			++c;
		}
		if(!s.empty()) cmdElements.push_back(s);
	}
	
	// Check...
	if(cmdElements.size() < 1)
	{
		// blank command
		return;
	}
	
	// Data about commands
	static QueryCommandSpecification commands[] = 
	{
		{ "quit", "" },
		{ "exit", "" },
		{ "list", "rodIFtTsh", },
		{ "pwd",  "" },
		{ "cd",   "od" },
		{ "lcd",  "" },
		{ "sh",   "" },
		{ "getobject", "" },
		{ "get",  "i" },
		{ "compare", "alcqE" },
		{ "restore", "dri" },
		{ "help", "" },
		{ "usage", "" },
		{ "undelete", "" },
		{ NULL, NULL } 
	};
	#define COMMAND_Quit		0
	#define COMMAND_Exit		1
	#define COMMAND_List		2
	#define COMMAND_pwd			3
	#define COMMAND_cd			4
	#define COMMAND_lcd			5
	#define COMMAND_sh			6
	#define COMMAND_GetObject	7
	#define COMMAND_Get			8
	#define COMMAND_Compare		9
	#define COMMAND_Restore		10
	#define COMMAND_Help		11
	#define COMMAND_Usage		12
	#define COMMAND_Undelete	13
	static const char *alias[] = {"ls",			0};
	static const int aliasIs[] = {COMMAND_List, 0};
	
	// Work out which command it is...
	int cmd = 0;
	while(commands[cmd].name != 0 && ::strcmp(cmdElements[0].c_str(), commands[cmd].name) != 0)
	{
		cmd++;
	}
	if(commands[cmd].name == 0)
	{
		// Check for aliases
		int a;
		for(a = 0; alias[a] != 0; ++a)
		{
			if(::strcmp(cmdElements[0].c_str(), alias[a]) == 0)
			{
				// Found an alias
				cmd = aliasIs[a];
				break;
			}
		}
	
		// No such command
		if(alias[a] == 0)
		{
			printf("Unrecognised command: %s\n", Command);
			return;
		}
	}

	// Arguments
	std::vector<std::string> args(cmdElements.begin() + 1, cmdElements.end());

	// Set up options
	bool opts[256];
	for(int o = 0; o < 256; ++o) opts[o] = false;
	// BLOCK
	{
		// options
		const char *c = options.c_str();
		while(*c != 0)
		{
			// Valid option?
			if(::strchr(commands[cmd].opts, *c) == NULL)
			{
				printf("Invalid option '%c' for command %s\n", 
					*c, commands[cmd].name);
				return;
			}
			opts[(int)*c] = true;
			++c;
		}
	}

	if(cmd != COMMAND_Quit && cmd != COMMAND_Exit)
	{
		// If not a quit command, set the return code to zero
		SetReturnCode(0);
	}

	// Handle command
	switch(cmd)
	{
	case COMMAND_Quit:
	case COMMAND_Exit:
		mQuitNow = true;
		break;
		
	case COMMAND_List:
		CommandList(args, opts);
		break;
		
	case COMMAND_pwd:
		{
			// Simple implementation, so do it here
			printf("%s (%08llx)\n", 
				GetCurrentDirectoryName().c_str(), 
				(long long)GetCurrentDirectoryID());
		}
		break;

	case COMMAND_cd:
		CommandChangeDir(args, opts);
		break;
		
	case COMMAND_lcd:
		CommandChangeLocalDir(args);
		break;
		
	case COMMAND_sh:
		printf("The command to run must be specified as an argument.\n");
		break;
		
	case COMMAND_GetObject:
		CommandGetObject(args, opts);
		break;
		
	case COMMAND_Get:
		CommandGet(args, opts);
		break;
		
	case COMMAND_Compare:
		CommandCompare(args, opts);
		break;
		
	case COMMAND_Restore:
		CommandRestore(args, opts);
		break;
		
	case COMMAND_Usage:
		CommandUsage();
		break;
		
	case COMMAND_Help:
		CommandHelp(args);
		break;

	case COMMAND_Undelete:
		CommandUndelete(args, opts);
		break;
		
	default:
		break;
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandList(const std::vector<std::string> &, const bool *)
//		Purpose: List directories (optionally recursive)
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
void BackupQueries::CommandList(const std::vector<std::string> &args, const bool *opts)
{
	#define LIST_OPTION_RECURSIVE		'r'
	#define LIST_OPTION_ALLOWOLD		'o'
	#define LIST_OPTION_ALLOWDELETED	'd'
	#define LIST_OPTION_NOOBJECTID		'I'
	#define LIST_OPTION_NOFLAGS		'F'
	#define LIST_OPTION_TIMES_LOCAL		't'
	#define LIST_OPTION_TIMES_UTC		'T'
	#define LIST_OPTION_SIZEINBLOCKS	's'
	#define LIST_OPTION_DISPLAY_HASH	'h'

	// default to using the current directory
	int64_t rootDir = GetCurrentDirectoryID();

	// name of base directory
	std::string listRoot;	// blank

	// Got a directory in the arguments?
	if(args.size() > 0)
	{
#ifdef WIN32
		std::string storeDirEncoded;
		if(!ConvertConsoleToUtf8(args[0].c_str(), storeDirEncoded))
			return;
#else
		const std::string& storeDirEncoded(args[0]);
#endif
	
		// Attempt to find the directory
		rootDir = FindDirectoryObjectID(storeDirEncoded, 
			opts[LIST_OPTION_ALLOWOLD], 
			opts[LIST_OPTION_ALLOWDELETED]);

		if(rootDir == 0)
		{
			printf("Directory '%s' not found on store\n",
				args[0].c_str());
			return;
		}
	}
	
	// List it
	List(rootDir, listRoot, opts, true /* first level to list */);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::List(int64_t, const std::string &, const bool *)
//		Purpose: Do the actual listing of directories and files
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
void BackupQueries::List(int64_t DirID, const std::string &rListRoot, const bool *opts, bool FirstLevel)
{
	// Generate exclude flags
	int16_t excludeFlags = BackupProtocolClientListDirectory::Flags_EXCLUDE_NOTHING;
	if(!opts[LIST_OPTION_ALLOWOLD]) excludeFlags |= BackupProtocolClientListDirectory::Flags_OldVersion;
	if(!opts[LIST_OPTION_ALLOWDELETED]) excludeFlags |= BackupProtocolClientListDirectory::Flags_Deleted;

	// Do communication
	mrConnection.QueryListDirectory(
			DirID,
			BackupProtocolClientListDirectory::Flags_INCLUDE_EVERYTHING,	// both files and directories
			excludeFlags,
			true /* want attributes */);

	// Retrieve the directory from the stream following
	BackupStoreDirectory dir;
	std::auto_ptr<IOStream> dirstream(mrConnection.ReceiveStream());
	dir.ReadFromStream(*dirstream, mrConnection.GetTimeout());

	// Then... display everything
	BackupStoreDirectory::Iterator i(dir);
	BackupStoreDirectory::Entry *en = 0;
	while((en = i.Next()) != 0)
	{
		// Display this entry
		BackupStoreFilenameClear clear(en->GetName());
		
		// Object ID?
		if(!opts[LIST_OPTION_NOOBJECTID])
		{
			// add object ID to line
#ifdef _MSC_VER
			printf("%08I64x ", (int64_t)en->GetObjectID());
#else
			printf("%08llx ", (long long)en->GetObjectID());
#endif
		}
		
		// Flags?
		if(!opts[LIST_OPTION_NOFLAGS])
		{
			static const char *flags = BACKUPSTOREDIRECTORY_ENTRY_FLAGS_DISPLAY_NAMES;
			char displayflags[16];
			// make sure f is big enough
			ASSERT(sizeof(displayflags) >= sizeof(BACKUPSTOREDIRECTORY_ENTRY_FLAGS_DISPLAY_NAMES) + 3);
			// Insert flags
			char *f = displayflags;
			const char *t = flags;
			int16_t en_flags = en->GetFlags();
			while(*t != 0)
			{
				*f = ((en_flags&1) == 0)?'-':*t;
				en_flags >>= 1;
				f++;
				t++;
			}
			// attributes flags
			*(f++) = (en->HasAttributes())?'a':'-';

			// terminate
			*(f++) = ' ';
			*(f++) = '\0';
			printf(displayflags);
			
			if(en_flags != 0)
			{
				printf("[ERROR: Entry has additional flags set] ");
			}
		}
		
		if(opts[LIST_OPTION_TIMES_UTC])
		{
			// Show UTC times...
			std::string time = BoxTimeToISO8601String(
				en->GetModificationTime(), false);
			printf("%s ", time.c_str());
		}

		if(opts[LIST_OPTION_TIMES_LOCAL])
		{
			// Show local times...
			std::string time = BoxTimeToISO8601String(
				en->GetModificationTime(), true);
			printf("%s ", time.c_str());
		}
		
		if(opts[LIST_OPTION_DISPLAY_HASH])
		{
#ifdef _MSC_VER
			printf("%016I64x ", (int64_t)en->GetAttributesHash());
#else
			printf("%016llx ", (long long)en->GetAttributesHash());
#endif
		}
		
		if(opts[LIST_OPTION_SIZEINBLOCKS])
		{
#ifdef _MSC_VER
			printf("%05I64d ", (int64_t)en->GetSizeInBlocks());
#else
			printf("%05lld ", (long long)en->GetSizeInBlocks());
#endif
		}
		
		// add name
		if(!FirstLevel)
		{
#ifdef WIN32
			std::string listRootDecoded;
			if(!ConvertUtf8ToConsole(rListRoot.c_str(), 
				listRootDecoded)) return;
			printf("%s/", listRootDecoded.c_str());
#else
			printf("%s/", rListRoot.c_str());
#endif
		}
		
#ifdef WIN32
		{
			std::string fileName;
			if(!ConvertUtf8ToConsole(
				clear.GetClearFilename().c_str(), fileName))
				return;
			printf("%s", fileName.c_str());
		}
#else
		printf("%s", clear.GetClearFilename().c_str());
#endif
		
		if(!en->GetName().IsEncrypted())
		{
			printf("[FILENAME NOT ENCRYPTED]");
		}

		printf("\n");
		
		// Directory?
		if((en->GetFlags() & BackupStoreDirectory::Entry::Flags_Dir) != 0)
		{
			// Recurse?
			if(opts[LIST_OPTION_RECURSIVE])
			{
				std::string subroot(rListRoot);
				if(!FirstLevel) subroot += '/';
				subroot += clear.GetClearFilename();
				List(en->GetObjectID(), subroot, opts, false /* not the first level to list */);
			}
		}
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::FindDirectoryObjectID(const std::string &)
//		Purpose: Find the object ID of a directory on the store, or return 0 for not found.
//				 If pStack != 0, the object is set to the stack of directories.
//				 Will start from the current directory stack.
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
int64_t BackupQueries::FindDirectoryObjectID(const std::string &rDirName, bool AllowOldVersion,
			bool AllowDeletedDirs, std::vector<std::pair<std::string, int64_t> > *pStack)
{
	// Split up string into elements
	std::vector<std::string> dirElements;
	SplitString(rDirName, '/', dirElements);

	// Start from current stack, or root, whichever is required
	std::vector<std::pair<std::string, int64_t> > stack;
	int64_t dirID = BackupProtocolClientListDirectory::RootDirectory;
	if(rDirName.size() > 0 && rDirName[0] == '/')
	{
		// Root, do nothing
	}
	else
	{
		// Copy existing stack
		stack = mDirStack;
		if(stack.size() > 0)
		{
			dirID = stack[stack.size() - 1].second;
		}
	}

	// Generate exclude flags
	int16_t excludeFlags = BackupProtocolClientListDirectory::Flags_EXCLUDE_NOTHING;
	if(!AllowOldVersion) excludeFlags |= BackupProtocolClientListDirectory::Flags_OldVersion;
	if(!AllowDeletedDirs) excludeFlags |= BackupProtocolClientListDirectory::Flags_Deleted;

	// Read directories
	for(unsigned int e = 0; e < dirElements.size(); ++e)
	{
		if(dirElements[e].size() > 0)
		{
			if(dirElements[e] == ".")
			{
				// Ignore.
			}
			else if(dirElements[e] == "..")
			{
				// Up one!
				if(stack.size() > 0)
				{
					// Remove top element
					stack.pop_back();
					
					// New dir ID
					dirID = (stack.size() > 0)?(stack[stack.size() - 1].second):BackupProtocolClientListDirectory::RootDirectory;
				}
				else
				{	
					// At root anyway
					dirID = BackupProtocolClientListDirectory::RootDirectory;
				}
			}
			else
			{
				// Not blank element. Read current directory.
				std::auto_ptr<BackupProtocolClientSuccess> dirreply(mrConnection.QueryListDirectory(
						dirID,
						BackupProtocolClientListDirectory::Flags_Dir,	// just directories
						excludeFlags,
						true /* want attributes */));

				// Retrieve the directory from the stream following
				BackupStoreDirectory dir;
				std::auto_ptr<IOStream> dirstream(mrConnection.ReceiveStream());
				dir.ReadFromStream(*dirstream, mrConnection.GetTimeout());

				// Then... find the directory within it
				BackupStoreDirectory::Iterator i(dir);
				BackupStoreFilenameClear dirname(dirElements[e]);
				BackupStoreDirectory::Entry *en = i.FindMatchingClearName(dirname);
				if(en == 0)
				{
					// Not found
					return 0;
				}
				
				// Object ID for next round of searching
				dirID = en->GetObjectID();

				// Push onto stack
				stack.push_back(std::pair<std::string, int64_t>(dirElements[e], dirID));
			}
		}
	}
	
	// If required, copy the new stack to the caller
	if(pStack)
	{
		*pStack = stack;
	}

	return dirID;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::GetCurrentDirectoryID()
//		Purpose: Returns the ID of the current directory
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
int64_t BackupQueries::GetCurrentDirectoryID()
{
	// Special case for root
	if(mDirStack.size() == 0)
	{
		return BackupProtocolClientListDirectory::RootDirectory;
	}
	
	// Otherwise, get from the last entry on the stack
	return mDirStack[mDirStack.size() - 1].second;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::GetCurrentDirectoryName()
//		Purpose: Gets the name of the current directory
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
std::string BackupQueries::GetCurrentDirectoryName()
{
	// Special case for root
	if(mDirStack.size() == 0)
	{
		return std::string("/");
	}

	// Build path
	std::string r;
	for(unsigned int l = 0; l < mDirStack.size(); ++l)
	{
		r += "/";
#ifdef WIN32
		std::string dirName;
		if(!ConvertUtf8ToConsole(mDirStack[l].first.c_str(), dirName))
			return "error";
		r += dirName;
#else
		r += mDirStack[l].first;
#endif
	}
	
	return r;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandChangeDir(const std::vector<std::string> &)
//		Purpose: Change directory command
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------
void BackupQueries::CommandChangeDir(const std::vector<std::string> &args, const bool *opts)
{
	if(args.size() != 1 || args[0].size() == 0)
	{
		printf("Incorrect usage.\ncd [-o] [-d] <directory>\n");
		return;
	}

#ifdef WIN32
	std::string dirName;
	if(!ConvertConsoleToUtf8(args[0].c_str(), dirName)) return;
#else
	const std::string& dirName(args[0]);
#endif
	
	std::vector<std::pair<std::string, int64_t> > newStack;
	int64_t id = FindDirectoryObjectID(dirName, opts['o'], opts['d'], 
		&newStack);
	
	if(id == 0)
	{
		printf("Directory '%s' not found\n", args[0].c_str());
		return;
	}
	
	// Store new stack
	mDirStack = newStack;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandChangeLocalDir(const std::vector<std::string> &)
//		Purpose: Change local directory command
//		Created: 2003/10/11
//
// --------------------------------------------------------------------------
void BackupQueries::CommandChangeLocalDir(const std::vector<std::string> &args)
{
	if(args.size() != 1 || args[0].size() == 0)
	{
		printf("Incorrect usage.\nlcd <local-directory>\n");
		return;
	}
	
	// Try changing directory
#ifdef WIN32
	std::string dirName;
	if(!ConvertConsoleToUtf8(args[0].c_str(), dirName)) return;
	int result = ::chdir(dirName.c_str());
#else
	int result = ::chdir(args[0].c_str());
#endif
	if(result != 0)
	{
		printf((errno == ENOENT || errno == ENOTDIR)?"Directory '%s' does not exist\n":"Error changing dir to '%s'\n",
			args[0].c_str());
		return;
	}
	
	// Report current dir
	char wd[PATH_MAX];
	if(::getcwd(wd, PATH_MAX) == 0)
	{
		printf("Error getting current directory\n");
		return;
	}

#ifdef WIN32
	if(!ConvertUtf8ToConsole(wd, dirName)) return;
	printf("Local current directory is now '%s'\n", dirName.c_str());
#else
	printf("Local current directory is now '%s'\n", wd);
#endif
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandGetObject(const std::vector<std::string> &, const bool *)
//		Purpose: Gets an object without any translation.
//		Created: 2003/10/11
//
// --------------------------------------------------------------------------
void BackupQueries::CommandGetObject(const std::vector<std::string> &args, const bool *opts)
{
	// Check args
	if(args.size() != 2)
	{
		printf("Incorrect usage.\ngetobject <object-id> <local-filename>\n");
		return;
	}
	
	int64_t id = ::strtoll(args[0].c_str(), 0, 16);
	if(id == std::numeric_limits<long long>::min() || id == std::numeric_limits<long long>::max() || id == 0)
	{
		printf("Not a valid object ID (specified in hex)\n");
		return;
	}
	
	// Does file exist?
	struct stat st;
	if(::stat(args[1].c_str(), &st) == 0 || errno != ENOENT)
	{
		printf("The local file %s already exists\n", args[1].c_str());
		return;
	}
	
	// Open file
	FileStream out(args[1].c_str(), O_WRONLY | O_CREAT | O_EXCL);
	
	// Request that object
	try
	{
		// Request object
		std::auto_ptr<BackupProtocolClientSuccess> getobj(mrConnection.QueryGetObject(id));
		if(getobj->GetObjectID() != BackupProtocolClientGetObject::NoObject)
		{
			// Stream that object out to the file
			std::auto_ptr<IOStream> objectStream(mrConnection.ReceiveStream());
			objectStream->CopyStreamTo(out);
			
			printf("Object ID %08llx fetched successfully.\n", id);
		}
		else
		{
			printf("Object does not exist on store.\n");
			::unlink(args[1].c_str());
		}
	}
	catch(...)
	{
		::unlink(args[1].c_str());
		printf("Error occured fetching object.\n");
	}
}



// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandGet(const std::vector<std::string> &, const bool *)
//		Purpose: Command to get a file from the store
//		Created: 2003/10/12
//
// --------------------------------------------------------------------------
void BackupQueries::CommandGet(const std::vector<std::string> &args, const bool *opts)
{
	// At least one argument?
	// Check args
	if(args.size() < 1 || (opts['i'] && args.size() != 2) || args.size() > 2)
	{
		printf("Incorrect usage.\n"
			"get <remote-filename> [<local-filename>] or\n"
			"get -i <object-id> <local-filename>\n");
		return;
	}

	// Find object ID somehow
	int64_t fileId;
	int64_t dirId = GetCurrentDirectoryID();
	std::string localName;

	// BLOCK
	{
#ifdef WIN32
		std::string fileName;
		if(!ConvertConsoleToUtf8(args[0].c_str(), fileName))
			return;
#else
		std::string fileName(args[0]);
#endif

		if(!opts['i'])
		{
			// does this remote filename include a path?
			std::string::size_type index = fileName.rfind('/');
			if(index != std::string::npos)
			{
				std::string dirName(fileName.substr(0, index));
				fileName = fileName.substr(index + 1);

				dirId = FindDirectoryObjectID(dirName);
				if(dirId == 0)
				{
					printf("Directory '%s' not found\n", 
						dirName.c_str());
					return;
				}
			}
		}

		BackupStoreFilenameClear fn(fileName);

		// Need to look it up in the current directory
		mrConnection.QueryListDirectory(
				dirId,
				BackupProtocolClientListDirectory::Flags_File,	// just files
				(opts['i'])?(BackupProtocolClientListDirectory::Flags_EXCLUDE_NOTHING):(BackupProtocolClientListDirectory::Flags_OldVersion | BackupProtocolClientListDirectory::Flags_Deleted), // only current versions
				false /* don't want attributes */);

		// Retrieve the directory from the stream following
		BackupStoreDirectory dir;
		std::auto_ptr<IOStream> dirstream(mrConnection.ReceiveStream());
		dir.ReadFromStream(*dirstream, mrConnection.GetTimeout());

		if(opts['i'])
		{
			// Specified as ID. 
			fileId = ::strtoll(args[0].c_str(), 0, 16);
			if(fileId == std::numeric_limits<long long>::min() || 
				fileId == std::numeric_limits<long long>::max() || 
				fileId == 0)
			{
				printf("Not a valid object ID (specified in hex)\n");
				return;
			}
			
			// Check that the item is actually in the directory
			if(dir.FindEntryByID(fileId) == 0)
			{
				printf("ID '%08llx' not found in current "
					"directory on store.\n"
					"(You can only download objects by ID "
					"from the current directory.)\n", 
					fileId);
				return;
			}
			
			// Must have a local name in the arguments (check at beginning of function ensures this)
			localName = args[1];
		}
		else
		{				
			// Specified by name, find the object in the directory to get the ID
			BackupStoreDirectory::Iterator i(dir);
#ifdef WIN32
			std::string fileName;
			if(!ConvertConsoleToUtf8(args[0].c_str(), fileName))
				return;
			BackupStoreFilenameClear fn(fileName);
#else
			BackupStoreFilenameClear fn(args[0]);
#endif
			BackupStoreDirectory::Entry *en = i.FindMatchingClearName(fn);
			
			if(en == 0)
			{
				printf("Filename '%s' not found in current "
					"directory on store.\n"
					"(Subdirectories in path not "
					"searched.)\n", args[0].c_str());
				return;
			}
			
			fileId = en->GetObjectID();
			
			// Local name is the last argument, which is either 
			// the looked up filename, or a filename specified 
			// by the user.
			localName = args[args.size() - 1];
		}
	}
	
	// Does local file already exist? (don't want to overwrite)
	struct stat st;
	if(::stat(localName.c_str(), &st) == 0 || errno != ENOENT)
	{
		printf("The local file %s already exists, will not overwrite it.\n", localName.c_str());
		return;
	}
	
	// Request it from the store
	try
	{
		// Request object
		mrConnection.QueryGetFile(dirId, fileId);

		// Stream containing encoded file
		std::auto_ptr<IOStream> objectStream(mrConnection.ReceiveStream());
		
		// Decode it
		BackupStoreFile::DecodeFile(*objectStream, localName.c_str(), mrConnection.GetTimeout());

		// Done.
		printf("Object ID %08llx fetched sucessfully.\n", fileId);
	}
	catch(...)
	{
		::unlink(localName.c_str());
		printf("Error occured fetching file.\n");
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CompareParams::CompareParams()
//		Purpose: Constructor
//		Created: 29/1/04
//
// --------------------------------------------------------------------------
BackupQueries::CompareParams::CompareParams()
	: mQuickCompare(false),
	  mIgnoreExcludes(false),
	  mDifferences(0),
	  mDifferencesExplainedByModTime(0),
	  mExcludedDirs(0),
	  mExcludedFiles(0),
	  mpExcludeFiles(0),
	  mpExcludeDirs(0),
	  mLatestFileUploadTime(0)
{
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CompareParams::~CompareParams()
//		Purpose: Destructor
//		Created: 29/1/04
//
// --------------------------------------------------------------------------
BackupQueries::CompareParams::~CompareParams()
{
	DeleteExcludeLists();
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CompareParams::DeleteExcludeLists()
//		Purpose: Delete the include lists contained
//		Created: 29/1/04
//
// --------------------------------------------------------------------------
void BackupQueries::CompareParams::DeleteExcludeLists()
{
	if(mpExcludeFiles != 0)
	{
		delete mpExcludeFiles;
		mpExcludeFiles = 0;
	}
	if(mpExcludeDirs != 0)
	{
		delete mpExcludeDirs;
		mpExcludeDirs = 0;
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandCompare(const std::vector<std::string> &, const bool *)
//		Purpose: Command to compare data on the store with local data
//		Created: 2003/10/12
//
// --------------------------------------------------------------------------
void BackupQueries::CommandCompare(const std::vector<std::string> &args, const bool *opts)
{
	// Parameters, including count of differences
	BackupQueries::CompareParams params;
	params.mQuickCompare = opts['q'];
	params.mIgnoreExcludes = opts['E'];
	
	// Try and work out the time before which all files should be on the server
	{
		std::string syncTimeFilename(mrConfiguration.GetKeyValue("DataDirectory") + DIRECTORY_SEPARATOR_ASCHAR);
		syncTimeFilename += "last_sync_start";
		// Stat it to get file time
		struct stat st;
		if(::stat(syncTimeFilename.c_str(), &st) == 0)
		{
			// Files modified after this time shouldn't be on the server, so report errors slightly differently
			params.mLatestFileUploadTime = FileModificationTime(st)
					- SecondsToBoxTime(mrConfiguration.GetKeyValueInt("MinimumFileAge"));
		}
		else
		{
			printf("Warning: couldn't determine the time of the last synchronisation -- checks not performed.\n");
		}
	}

	// Quick compare?
	if(params.mQuickCompare)
	{
		printf("WARNING: Quick compare used -- file attributes are not checked.\n");
	}
	
	if(!opts['l'] && opts['a'] && args.size() == 0)
	{
		// Compare all locations
		const Configuration &locations(mrConfiguration.GetSubConfiguration("BackupLocations"));
		for(std::list<std::pair<std::string, Configuration> >::const_iterator i = locations.mSubConfigurations.begin();
				i != locations.mSubConfigurations.end(); ++i)
		{
			CompareLocation(i->first, params);
		}
	}
	else if(opts['l'] && !opts['a'] && args.size() == 1)
	{
		// Compare one location
		CompareLocation(args[0], params);
	}
	else if(!opts['l'] && !opts['a'] && args.size() == 2)
	{
		// Compare directory to directory
		
		// Can't be bothered to do all the hard work to work out which location it's on, and hence which exclude list
		if(!params.mIgnoreExcludes)
		{
			printf("Cannot use excludes on directory to directory comparison -- use -E flag to specify ignored excludes\n");
			return;
		}
		else
		{
			// Do compare
			Compare(args[0], args[1], params);
		}
	}
	else
	{
		printf("Incorrect usage.\ncompare -a\n or compare -l <location-name>\n or compare <store-dir-name> <local-dir-name>\n");
		return;
	}
	
	printf("\n[ %d (of %d) differences probably due to file modifications after the last upload ]\nDifferences: %d (%d dirs excluded, %d files excluded)\n",
		params.mDifferencesExplainedByModTime, params.mDifferences, params.mDifferences, params.mExcludedDirs, params.mExcludedFiles);
	
	// Set return code?
	if(opts['c'])
	{
		SetReturnCode((params.mDifferences == 0)?COMPARE_RETURN_SAME:COMPARE_RETURN_DIFFERENT);
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CompareLocation(const std::string &, BackupQueries::CompareParams &)
//		Purpose: Compare a location
//		Created: 2003/10/13
//
// --------------------------------------------------------------------------
void BackupQueries::CompareLocation(const std::string &rLocation, BackupQueries::CompareParams &rParams)
{
	// Find the location's sub configuration
	const Configuration &locations(mrConfiguration.GetSubConfiguration("BackupLocations"));
	if(!locations.SubConfigurationExists(rLocation.c_str()))
	{
		printf("Location %s does not exist.\n", rLocation.c_str());
		return;
	}
	const Configuration &loc(locations.GetSubConfiguration(rLocation.c_str()));
	
	try
	{
		// Generate the exclude lists
		if(!rParams.mIgnoreExcludes)
		{
			rParams.mpExcludeFiles = BackupClientMakeExcludeList_Files(loc);
			rParams.mpExcludeDirs = BackupClientMakeExcludeList_Dirs(loc);
		}
				
		// Then get it compared
		Compare(std::string("/") + rLocation, 
			loc.GetKeyValue("Path"), rParams);
	}
	catch(...)
	{
		// Clean up
		rParams.DeleteExcludeLists();
		throw;
	}
	
	// Delete exclude lists
	rParams.DeleteExcludeLists();
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::Compare(const std::string &, const std::string &, BackupQueries::CompareParams &)
//		Purpose: Compare a store directory against a local directory
//		Created: 2003/10/13
//
// --------------------------------------------------------------------------
void BackupQueries::Compare(const std::string &rStoreDir, const std::string &rLocalDir, BackupQueries::CompareParams &rParams)
{
#ifdef WIN32
	std::string storeDirEncoded;
	if(!ConvertConsoleToUtf8(rStoreDir.c_str(), storeDirEncoded)) return;
#else
	const std::string& storeDirEncoded(rStoreDir);
#endif
	
	// Get the directory ID of the directory -- only use current data
	int64_t dirID = FindDirectoryObjectID(storeDirEncoded);
	
	// Found?
	if(dirID == 0)
	{
		printf("Local directory '%s' exists, but "
			"server directory '%s' does not exist\n", 
			rLocalDir.c_str(), rStoreDir.c_str());		
		rParams.mDifferences ++;
		return;
	}

#ifdef WIN32
	std::string localDirEncoded;
	if(!ConvertConsoleToUtf8(rLocalDir.c_str(), localDirEncoded)) return;
#else
	std::string localDirEncoded(rLocalDir);
#endif
	
	// Go!
	Compare(dirID, storeDirEncoded, localDirEncoded, rParams);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::Compare(int64_t, const std::string &,
//			 const std::string &, BackupQueries::CompareParams &)
//		Purpose: Compare a store directory against a local directory
//		Created: 2003/10/13
//
// --------------------------------------------------------------------------
void BackupQueries::Compare(int64_t DirID, const std::string &rStoreDir, const std::string &rLocalDir, BackupQueries::CompareParams &rParams)
{
#ifdef WIN32
	// By this point, rStoreDir and rLocalDir should be in UTF-8 encoding

	std::string localDirDisplay;
	std::string storeDirDisplay;

	if(!ConvertUtf8ToConsole(rLocalDir.c_str(), localDirDisplay)) return;
	if(!ConvertUtf8ToConsole(rStoreDir.c_str(), storeDirDisplay)) return;
#else
	const std::string& localDirDisplay(rLocalDir);
	const std::string& storeDirDisplay(rStoreDir);
#endif

	// Get info on the local directory
	struct stat st;
	if(::lstat(rLocalDir.c_str(), &st) != 0)
	{
		// What kind of error?
		if(errno == ENOTDIR)
		{
			printf("Local object '%s' is a file, "
				"server object '%s' is a directory\n", 
				localDirDisplay.c_str(), 
				storeDirDisplay.c_str());
			rParams.mDifferences ++;
		}
		else if(errno == ENOENT)
		{
			printf("Local directory '%s' does not exist "
				"(compared to server directory '%s')\n",
				localDirDisplay.c_str(), 
				storeDirDisplay.c_str());
		}
		else
		{
			printf("ERROR: stat on local dir '%s'\n", 
				localDirDisplay.c_str());
		}
		return;
	}

	// Get the directory listing from the store
	mrConnection.QueryListDirectory(
			DirID,
			BackupProtocolClientListDirectory::Flags_INCLUDE_EVERYTHING,	// get everything
			BackupProtocolClientListDirectory::Flags_OldVersion | BackupProtocolClientListDirectory::Flags_Deleted,	// except for old versions and deleted files
			true /* want attributes */);

	// Retrieve the directory from the stream following
	BackupStoreDirectory dir;
	std::auto_ptr<IOStream> dirstream(mrConnection.ReceiveStream());
	dir.ReadFromStream(*dirstream, mrConnection.GetTimeout());

	// Test out the attributes
	if(!dir.HasAttributes())
	{
		printf("Store directory '%s' doesn't have attributes.\n", 
			storeDirDisplay.c_str());
	}
	else
	{
		// Fetch the attributes
		const StreamableMemBlock &storeAttr(dir.GetAttributes());
		BackupClientFileAttributes attr(storeAttr);

		// Get attributes of local directory
		BackupClientFileAttributes localAttr;
		localAttr.ReadAttributes(rLocalDir.c_str(), 
			true /* directories have zero mod times */);

		if(!(attr.Compare(localAttr, true, true /* ignore modification times */)))
		{
			printf("Local directory '%s' has different attributes "
				"to store directory '%s'.\n",
				localDirDisplay.c_str(), 
				storeDirDisplay.c_str());
			rParams.mDifferences ++;
		}
	}

	// Open the local directory
	DIR *dirhandle = ::opendir(rLocalDir.c_str());
	if(dirhandle == 0)
	{
		printf("ERROR: opendir on local dir '%s'\n", 
			localDirDisplay.c_str());
		return;
	}
	try
	{
		// Read the files and directories into sets
		std::set<std::string> localFiles;
		std::set<std::string> localDirs;
		struct dirent *localDirEn = 0;
		while((localDirEn = readdir(dirhandle)) != 0)
		{
			// Not . and ..!
			if(localDirEn->d_name[0] == '.' && 
				(localDirEn->d_name[1] == '\0' || (localDirEn->d_name[1] == '.' && localDirEn->d_name[2] == '\0')))
			{
				// ignore, it's . or ..
				
#ifdef HAVE_VALID_DIRENT_D_TYPE
				if (localDirEn->d_type != DT_DIR)
				{
					fprintf(stderr, "ERROR: d_type does "
						"not really work on your "
						"platform. Reconfigure Box!\n");
					return;
				}
#endif
				
				continue;
			}

#ifndef HAVE_VALID_DIRENT_D_TYPE
			std::string fn(rLocalDir);
			fn += DIRECTORY_SEPARATOR_ASCHAR;
			fn += localDirEn->d_name;
			struct stat st;
			if(::lstat(fn.c_str(), &st) != 0)
			{
			    THROW_EXCEPTION(CommonException, OSFileError)
			}
			
			// Entry -- file or dir?
			if(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
			{	
			    // File or symbolic link
			    localFiles.insert(std::string(localDirEn->d_name));
			}
			else if(S_ISDIR(st.st_mode))
			{
			    // Directory
			    localDirs.insert(std::string(localDirEn->d_name));
			}
#else
			// Entry -- file or dir?
			if(localDirEn->d_type == DT_REG || localDirEn->d_type == DT_LNK)
			{
				// File or symbolic link
				localFiles.insert(std::string(localDirEn->d_name));
			}
			else if(localDirEn->d_type == DT_DIR)
			{
				// Directory
				localDirs.insert(std::string(localDirEn->d_name));
			}
#endif
		}
		// Close directory
		if(::closedir(dirhandle) != 0)
		{
			printf("ERROR: closedir on local dir '%s'\n", 
				localDirDisplay.c_str());
		}
		dirhandle = 0;
	
		// Do the same for the store directories
		std::set<std::pair<std::string, BackupStoreDirectory::Entry *> > storeFiles;
		std::set<std::pair<std::string, BackupStoreDirectory::Entry *> > storeDirs;
		
		BackupStoreDirectory::Iterator i(dir);
		BackupStoreDirectory::Entry *storeDirEn = 0;
		while((storeDirEn = i.Next()) != 0)
		{
			// Decrypt filename
			BackupStoreFilenameClear name(storeDirEn->GetName());
		
			// What is it?
			if((storeDirEn->GetFlags() & BackupStoreDirectory::Entry::Flags_File) == BackupStoreDirectory::Entry::Flags_File)
			{
				// File
				storeFiles.insert(std::pair<std::string, BackupStoreDirectory::Entry *>(name.GetClearFilename(), storeDirEn));
			}
			else
			{
				// Dir
				storeDirs.insert(std::pair<std::string, BackupStoreDirectory::Entry *>(name.GetClearFilename(), storeDirEn));
			}
		}

#ifdef _MSC_VER
		typedef std::set<std::string>::iterator string_set_iter_t;
#else
		typedef std::set<std::string>::const_iterator string_set_iter_t;
#endif
		
		// Now compare files.
		for(std::set<std::pair<std::string, BackupStoreDirectory::Entry *> >::const_iterator i = storeFiles.begin(); i != storeFiles.end(); ++i)
		{
			const std::string& fileName(i->first);
#ifdef WIN32
			// File name is also in UTF-8 encoding, 
			// need to convert to console
			std::string fileNameDisplay;
			if(!ConvertUtf8ToConsole(i->first.c_str(), 
				fileNameDisplay)) return;
#else
			const std::string& fileNameDisplay(i->first);
#endif

			std::string localPathDisplay = localDirDisplay +
				DIRECTORY_SEPARATOR + fileNameDisplay;
			std::string storePathDisplay = storeDirDisplay +
				"/" + fileNameDisplay;

			// Does the file exist locally?
			string_set_iter_t local(localFiles.find(fileName));
			if(local == localFiles.end())
			{
				// Not found -- report
				printf("Local file '%s' does not exist, "
					"but store file '%s' does.\n",
					localPathDisplay.c_str(),
					storePathDisplay.c_str());
				rParams.mDifferences ++;
			}
			else
			{
				try
				{
					// make local name of file for comparison
					std::string localPath(rLocalDir + DIRECTORY_SEPARATOR + fileName);

					// Files the same flag?
					bool equal = true;
					
					// File modified after last sync flag
					bool modifiedAfterLastSync = false;
						
					if(rParams.mQuickCompare)
					{
						// Compare file -- fetch it
						mrConnection.QueryGetBlockIndexByID(i->second->GetObjectID());

						// Stream containing block index
						std::auto_ptr<IOStream> blockIndexStream(mrConnection.ReceiveStream());
						
						// Compare
						equal = BackupStoreFile::CompareFileContentsAgainstBlockIndex(localPath.c_str(), *blockIndexStream, mrConnection.GetTimeout());
					}
					else
					{
						// Compare file -- fetch it
						mrConnection.QueryGetFile(DirID, i->second->GetObjectID());
	
						// Stream containing encoded file
						std::auto_ptr<IOStream> objectStream(mrConnection.ReceiveStream());
	
						// Decode it
						std::auto_ptr<BackupStoreFile::DecodedStream> fileOnServerStream;
						// Got additional attibutes?
						if(i->second->HasAttributes())
						{
							// Use these attributes
							const StreamableMemBlock &storeAttr(i->second->GetAttributes());
							BackupClientFileAttributes attr(storeAttr);
							fileOnServerStream.reset(BackupStoreFile::DecodeFileStream(*objectStream, mrConnection.GetTimeout(), &attr).release());
						}
						else
						{
							// Use attributes stored in file
							fileOnServerStream.reset(BackupStoreFile::DecodeFileStream(*objectStream, mrConnection.GetTimeout()).release());
						}
						
						// Should always be something in the auto_ptr, it's how the interface is defined. But be paranoid.
						if(!fileOnServerStream.get())
						{
							THROW_EXCEPTION(BackupStoreException, Internal)
						}
						
						// Compare attributes
						BackupClientFileAttributes localAttr;
						box_time_t fileModTime = 0;
						localAttr.ReadAttributes(localPath.c_str(), false /* don't zero mod times */, &fileModTime);					
						modifiedAfterLastSync = (fileModTime > rParams.mLatestFileUploadTime);
						if(!localAttr.Compare(fileOnServerStream->GetAttributes(),
								true /* ignore attr mod time */,
								fileOnServerStream->IsSymLink() /* ignore modification time if it's a symlink */))
						{
							printf("Local file '%s' "
								"has different attributes "
								"to store file '%s'.\n",
								localPathDisplay.c_str(), 
								storePathDisplay.c_str());						
							rParams.mDifferences ++;
							if(modifiedAfterLastSync)
							{
								rParams.mDifferencesExplainedByModTime ++;
								printf("(the file above was modified after the last sync time -- might be reason for difference)\n");
							}
							else if(i->second->HasAttributes())
							{
								printf("(the file above has had new attributes applied)\n");
							}
						}
	
						// Compare contents, if it's a regular file not a link
						// Remember, we MUST read the entire stream from the server.
						if(!fileOnServerStream->IsSymLink())
						{
							// Open the local file
							FileStream l(localPath.c_str());
							
							// Size
							IOStream::pos_type fileSizeLocal = l.BytesLeftToRead();
							IOStream::pos_type fileSizeServer = 0;
							
							// Test the contents
							char buf1[2048];
							char buf2[2048];
							while(fileOnServerStream->StreamDataLeft() && l.StreamDataLeft())
							{
								int size = fileOnServerStream->Read(buf1, sizeof(buf1), mrConnection.GetTimeout());
								fileSizeServer += size;
								
								if(l.Read(buf2, size) != size
										|| ::memcmp(buf1, buf2, size) != 0)
								{
									equal = false;
									break;
								}
							}
	
							// Check read all the data from the server and file -- can't be equal if local and remote aren't the same length
							// Can't use StreamDataLeft() test on file, because if it's the same size, it won't know
							// it's EOF yet.
							if(fileOnServerStream->StreamDataLeft() || fileSizeServer != fileSizeLocal)
							{
								equal = false;
							}

							// Must always read the entire decoded string, if it's not a symlink
							if(fileOnServerStream->StreamDataLeft())
							{
								// Absorb all the data remaining
								char buffer[2048];
								while(fileOnServerStream->StreamDataLeft())
								{
									fileOnServerStream->Read(buffer, sizeof(buffer), mrConnection.GetTimeout());
								}
							}
						}
					}

					// Report if not equal.
					if(!equal)
					{
						printf("Local file '%s' "
							"has different contents "
							"to store file '%s'.\n",
							localPathDisplay.c_str(), 
							storePathDisplay.c_str());
						rParams.mDifferences ++;
						if(modifiedAfterLastSync)
						{
							rParams.mDifferencesExplainedByModTime ++;
							printf("(the file above was modified after the last sync time -- might be reason for difference)\n");
						}
						else if(i->second->HasAttributes())
						{
							printf("(the file above has had new attributes applied)\n");
						}
					}
				}
				catch(BoxException &e)
				{
					printf("ERROR: (%d/%d) during file fetch and comparison for '%s'\n",
						e.GetType(),
						e.GetSubType(),
						storePathDisplay.c_str());
				}
				catch(...)
				{
					printf("ERROR: (unknown) during file fetch and comparison for '%s'\n", storePathDisplay.c_str());
				}

				// Remove from set so that we know it's been compared
				localFiles.erase(local);
			}
		}
		
		// Report any files which exist on the locally, but not on the store
		for(string_set_iter_t i = localFiles.begin(); i != localFiles.end(); ++i)
		{
#ifdef WIN32
			// File name is also in UTF-8 encoding, 
			// need to convert to console
			std::string fileNameDisplay;
			if(!ConvertUtf8ToConsole(i->c_str(), fileNameDisplay)) 
				return;
#else
			const std::string& fileNameDisplay(*i);
#endif

			std::string localPath(rLocalDir + 
				DIRECTORY_SEPARATOR + *i);
			std::string localPathDisplay(localDirDisplay +
				DIRECTORY_SEPARATOR + fileNameDisplay);
			std::string storePathDisplay(storeDirDisplay +
				"/" + fileNameDisplay);

			// Should this be ignored (ie is excluded)?
			if(rParams.mpExcludeFiles == 0 || 
				!(rParams.mpExcludeFiles->IsExcluded(localPath)))
			{
				printf("Local file '%s' exists, "
					"but store file '%s' "
					"does not exist.\n",
					localPathDisplay.c_str(),
					storePathDisplay.c_str());
				rParams.mDifferences ++;
				
				// Check the file modification time
				{
					struct stat st;
					if(::stat(localPath.c_str(), &st) == 0)
					{
						if(FileModificationTime(st) > rParams.mLatestFileUploadTime)
						{
							rParams.mDifferencesExplainedByModTime ++;
							printf("(the file above was modified after the last sync time -- might be reason for difference)\n");
						}
					}
				}
			}
			else
			{
				rParams.mExcludedFiles ++;
			}
		}		
		
		// Finished with the files, clear the sets to reduce memory usage slightly
		localFiles.clear();
		storeFiles.clear();
		
		// Now do the directories, recusively to check subdirectories
		for(std::set<std::pair<std::string, BackupStoreDirectory::Entry *> >::const_iterator i = storeDirs.begin(); i != storeDirs.end(); ++i)
		{
#ifdef WIN32
			// Directory name is also in UTF-8 encoding, 
			// need to convert to console
			std::string subdirNameDisplay;
			if(!ConvertUtf8ToConsole(i->first.c_str(), 
				subdirNameDisplay))
				return;
#else
			const std::string& subdirNameDisplay(i->first);
#endif

			std::string localPathDisplay = localDirDisplay +
				DIRECTORY_SEPARATOR + subdirNameDisplay;
			std::string storePathDisplay = storeDirDisplay +
				"/" + subdirNameDisplay;

			// Does the directory exist locally?
			string_set_iter_t local(localDirs.find(i->first));
			if(local == localDirs.end())
			{
				// Not found -- report
				printf("Local directory '%s' does not exist, "
					"but store directory '%s' does.\n",
					localPathDisplay.c_str(),
					storePathDisplay.c_str());
				rParams.mDifferences ++;
			}
			else
			{
				// Compare directory
				Compare(i->second->GetObjectID(), rStoreDir + "/" + i->first, rLocalDir + DIRECTORY_SEPARATOR + i->first, rParams);
				
				// Remove from set so that we know it's been compared
				localDirs.erase(local);
			}
		}
		
		// Report any files which exist on the locally, but not on the store
		for(std::set<std::string>::const_iterator i = localDirs.begin(); i != localDirs.end(); ++i)
		{
#ifdef WIN32
			// File name is also in UTF-8 encoding, 
			// need to convert to console
			std::string fileNameDisplay;
			if(!ConvertUtf8ToConsole(i->c_str(), fileNameDisplay))
				return;
#else
			const std::string& fileNameDisplay(*i);
#endif

			std::string localPath = rLocalDir +
				DIRECTORY_SEPARATOR + *i;
			std::string storePath = rStoreDir +
				"/" + *i;

			std::string localPathDisplay = localDirDisplay +
				DIRECTORY_SEPARATOR + fileNameDisplay;
			std::string storePathDisplay = storeDirDisplay +
				"/" + fileNameDisplay;

			// Should this be ignored (ie is excluded)?
			if(rParams.mpExcludeDirs == 0 || !(rParams.mpExcludeDirs->IsExcluded(localPath)))
			{
				printf("Local directory '%s' exists, but "
					"store directory '%s' does not exist.\n",
					localPathDisplay.c_str(),
					storePathDisplay.c_str());
				rParams.mDifferences ++;
			}
			else
			{
				rParams.mExcludedDirs ++;
			}
		}		
		
	}
	catch(...)
	{
		if(dirhandle != 0)
		{
			::closedir(dirhandle);
		}
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandRestore(const std::vector<std::string> &, const bool *)
//		Purpose: Restore a directory
//		Created: 23/11/03
//
// --------------------------------------------------------------------------
void BackupQueries::CommandRestore(const std::vector<std::string> &args, const bool *opts)
{
	// Check arguments
	if(args.size() != 2)
	{
		printf("Incorrect usage.\nrestore [-d] [-r] [-i] <directory-name> <local-directory-name>\n");
		return;
	}

	// Restoring deleted things?
	bool restoreDeleted = opts['d'];

	// Get directory ID
	int64_t dirID = 0;
	if(opts['i'])
	{
		// Specified as ID. 
		dirID = ::strtoll(args[0].c_str(), 0, 16);
		if(dirID == std::numeric_limits<long long>::min() || dirID == std::numeric_limits<long long>::max() || dirID == 0)
		{
			printf("Not a valid object ID (specified in hex)\n");
			return;
		}
	}
	else
	{
#ifdef WIN32
		std::string storeDirEncoded;
		if(!ConvertConsoleToUtf8(args[0].c_str(), storeDirEncoded))
			return;
#else
		const std::string& storeDirEncoded(args[0]);
#endif
	
		// Look up directory ID
		dirID = FindDirectoryObjectID(storeDirEncoded, 
			false /* no old versions */, 
			restoreDeleted /* find deleted dirs */);
	}
	
	// Allowable?
	if(dirID == 0)
	{
		printf("Directory '%s' not found on server\n", args[0].c_str());
		return;
	}
	if(dirID == BackupProtocolClientListDirectory::RootDirectory)
	{
		printf("Cannot restore the root directory -- restore locations individually.\n");
		return;
	}
	
#ifdef WIN32
	std::string localName;
	if(!ConvertConsoleToUtf8(args[1].c_str(), localName)) return;
#else
	std::string localName(args[1]);
#endif

	// Go and restore...
	switch(BackupClientRestore(mrConnection, dirID, localName.c_str(), 
		true /* print progress dots */, restoreDeleted, 
		false /* don't undelete after restore! */, 
		opts['r'] /* resume? */))
	{
	case Restore_Complete:
		printf("Restore complete\n");
		break;
	
	case Restore_ResumePossible:
		printf("Resume possible -- repeat command with -r flag to resume\n");
		break;
	
	case Restore_TargetExists:
		printf("The target directory exists. You cannot restore over an existing directory.\n");
		break;
		
	default:
		printf("ERROR: Unknown restore result.\n");
		break;
	}
}



// These are autogenerated by a script.
extern char *help_commands[];
extern char *help_text[];


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandHelp(const std::vector<std::string> &args)
//		Purpose: Display help on commands
//		Created: 15/2/04
//
// --------------------------------------------------------------------------
void BackupQueries::CommandHelp(const std::vector<std::string> &args)
{
	if(args.size() == 0)
	{
		// Display a list of all commands
		printf("Available commands are:\n");
		for(int c = 0; help_commands[c] != 0; ++c)
		{
			printf("    %s\n", help_commands[c]);
		}
		printf("Type \"help <command>\" for more information on a command.\n\n");
	}
	else
	{
		// Display help on a particular command
		int c;
		for(c = 0; help_commands[c] != 0; ++c)
		{
			if(::strcmp(help_commands[c], args[0].c_str()) == 0)
			{
				// Found the command, print help
				printf("\n%s\n", help_text[c]);
				break;
			}
		}
		if(help_commands[c] == 0)
		{
			printf("No help found for command '%s'\n", args[0].c_str());
		}
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandUsage()
//		Purpose: Display storage space used on server
//		Created: 19/4/04
//
// --------------------------------------------------------------------------
void BackupQueries::CommandUsage()
{
	// Request full details from the server
	std::auto_ptr<BackupProtocolClientAccountUsage> usage(mrConnection.QueryGetAccountUsage());

	// Display each entry in turn
	int64_t hardLimit = usage->GetBlocksHardLimit();
	int32_t blockSize = usage->GetBlockSize();
	CommandUsageDisplayEntry("Used", usage->GetBlocksUsed(), hardLimit, blockSize);
	CommandUsageDisplayEntry("Old files", usage->GetBlocksInOldFiles(), hardLimit, blockSize);
	CommandUsageDisplayEntry("Deleted files", usage->GetBlocksInDeletedFiles(), hardLimit, blockSize);
	CommandUsageDisplayEntry("Directories", usage->GetBlocksInDirectories(), hardLimit, blockSize);
	CommandUsageDisplayEntry("Soft limit", usage->GetBlocksSoftLimit(), hardLimit, blockSize);
	CommandUsageDisplayEntry("Hard limit", hardLimit, hardLimit, blockSize);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandUsageDisplayEntry(const char *, int64_t, int64_t, int32_t)
//		Purpose: Display an entry in the usage table
//		Created: 19/4/04
//
// --------------------------------------------------------------------------
void BackupQueries::CommandUsageDisplayEntry(const char *Name, int64_t Size, int64_t HardLimit, int32_t BlockSize)
{
	// Calculate size in Mb
	double mb = (((double)Size) * ((double)BlockSize)) / ((double)(1024*1024));
	int64_t percent = (Size * 100) / HardLimit;

	// Bar graph
	char bar[41];
	unsigned int b = (int)((Size * (sizeof(bar)-1)) / HardLimit);
	if(b > sizeof(bar)-1) {b = sizeof(bar)-1;}
	for(unsigned int l = 0; l < b; l++)
	{
		bar[l] = '*';
	}
	bar[b] = '\0';

	// Print the entryj
	::printf("%14s %10.1fMb %3d%% %s\n", Name, mb, (int32_t)percent, bar);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupQueries::CommandUndelete(const std::vector<std::string> &, const bool *)
//		Purpose: Undelete a directory
//		Created: 23/11/03
//
// --------------------------------------------------------------------------
void BackupQueries::CommandUndelete(const std::vector<std::string> &args, const bool *opts)
{
	// Check arguments
	if(args.size() != 1)
	{
		printf("Incorrect usage.\nundelete <directory-name>\n");
		return;
	}

#ifdef WIN32
	std::string storeDirEncoded;
	if(!ConvertConsoleToUtf8(args[0].c_str(), storeDirEncoded)) return;
#else
	const std::string& storeDirEncoded(args[0]);
#endif
	
	// Get directory ID
	int64_t dirID = FindDirectoryObjectID(storeDirEncoded, 
		false /* no old versions */, true /* find deleted dirs */);
	
	// Allowable?
	if(dirID == 0)
	{
		printf("Directory '%s' not found on server\n", args[0].c_str());
		return;
	}
	if(dirID == BackupProtocolClientListDirectory::RootDirectory)
	{
		printf("Cannot undelete the root directory.\n");
		return;
	}

	// Undelete
	mrConnection.QueryUndeleteDirectory(dirID);
}