libdoltlite-sys 0.38.25

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


#include "bcv_int.h"
#include "blockcachevfs.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef __WIN32__
# include <windows.h>
# define strerror_r(errno,buf,len) strerror_s(buf,len,errno)
#endif
#include <fcntl.h>
#include <errno.h>
#include <assert.h>

#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/md5.h>

#ifdef __WIN32__
# define BCV_PATH_SEPARATOR "\\"
# define osMkdir(x,y) mkdir(x)
# define signal(x,y)
#else
# define BCV_PATH_SEPARATOR "/"
# define osMkdir(x,y) mkdir(x,y)
# include <signal.h>
#endif

#include "sqlite3.h"
#include "simplexml.h"

/* Default values of various command line parameters. */
#define BCV_DEFAULT_CACHEFILE_SIZE   (1024*1024*1024)
#define BCV_DEFAULT_HTTPLOG_TIMEOUT  3600
#define BCV_DEFAULT_HTTPLOG_NENTRY   -1

#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))

typedef struct CommandSwitches CommandSwitches;
struct CommandSwitches {
  /* Used by almost all commands: */
  char *zContainer;               /* -container ARG */
  char *zModule;                  /* -module ARG */
  char *zUser;                    /* -user ARG */
  char *zSecret;                  /* -auth ARG */

  /* Used by 'create' command only: */
  i64 szBlk;                      /* -blocksize ARG */
  int nNamebytes;                 /* -namebytes ARG */

  /* Used by 'attach': */
  int bReadonly;                  /* -readonly is present */
  int bSecure;                    /* -secure is present */
  char *zAlias;                   /* -alias ARG */

  /* Used by 'upload', 'download' and 'daemon' */
  int nRequest;                   /* -nrequest ARG */

  /* Used by daemon only: */
  char *zAddr;                    /* -addr ARG */
  int iPort;                      /* -port ARG */
  int bNoTimestamps;              /* True if -notimestamps is specified */
  int bAutoexit;                  /* True if -autoexit is specified */
  i64 szCache;                    /* Size of cache file in bytes */
  int mLog;                       /* Mask of daemon events to log */
  int bReadyMessage;              /* Daemon outputs "ready" message */
  int nHttpTimeout;               /* Value of --httptimeout option */

  int nHttpLogTimeout;            /* Value of --httplogtimeout option */
  int nHttpLogNentry;             /* Value of --httplognentry option */
};

#define BCV_LOG_MESSAGE   0x01
#define BCV_LOG_HTTP      0x20
#define BCV_LOG_HTTPRETRY 0x04
#define BCV_LOG_EVENT     0x02
#define BCV_LOG_VERBOSE   0x40
#define BCV_LOG_SCHEDULE  0x80

#define BCV_LOG_POLL      0x04
#define BCV_LOG_UPLOAD    0x08
#define BCV_LOG_CACHE     0x10


static void fatal_sql_error(sqlite3 *db, const char *zMsg){
  fprintf(stderr, "FATAL: SQL error in %s (rc=%d) (errmsg=%s)\n", 
      zMsg, sqlite3_errcode(db), sqlite3_errmsg(db)
  );
  abort();
}


typedef struct SelectOption SelectOption;
struct SelectOption {
  const char *zOpt;
  u32 mask;
  int eVal;
};

/*
** A printf() style function that outputs a message on stderr, then calls
** exit(-1). This is used for command line errors and other fatal conditions
*/
static void fatal_error(const char *zFmt, ...){
  char *zMsg;
  va_list ap;
  va_start(ap, zFmt);
  zMsg = sqlite3_vmprintf(zFmt, ap);
  fprintf(stderr, "FATAL: %s\n", zMsg);
  sqlite3_free(zMsg);
  va_end(ap);
  abort();
}

void fatal_system_error(const char *zApi, int iError){
  char *zBuf = bcvMalloc(1000);
  strerror_r(iError, zBuf, 1000);
  zBuf[999] = '\0';
  fatal_error("%s - %s", zApi, zBuf);
}

static void *bdMalloc(int n){
  void *pRet = sqlite3_malloc(n);
  if( pRet==0 ){
    fatal_oom_error();
  }
  return pRet;
}

static void *bdMallocZero(int n){
  void *pRet = bdMalloc(n);
  memset(pRet, 0, n);
  return pRet;
}

#if 0
static void *bdBufferDup(const void *aIn, int nIn){
  void *pRet = bdMalloc(nIn);
  memcpy(pRet, aIn, nIn);
  return pRet;
}
#endif

static char *bdStrdup(const char *zIn){
  char *zRet = 0;
  if( zIn ){
    int nIn = bcvStrlen(zIn);
    zRet = bdMalloc(nIn+1);
    memcpy(zRet, zIn, nIn+1);
  }
  return zRet;
}

static int select_option(
  const char *zOpt, 
  SelectOption *aOpt,
  u32 mask,
  int bUnknownFatal               /* If true, unknown option is a fatal error */
){
  int nOpt = strlen(zOpt);
  int i;
  int nMatch = 0;
  int iRet = -1;
  char *zMsg = 0;
  int nCandidate = 0;

  for(i=0; aOpt[i].zOpt; i++){
    if( aOpt[i].mask & mask ){
      int n = strlen(aOpt[i].zOpt);
      if( nOpt && n>=nOpt && 0==memcmp(zOpt, aOpt[i].zOpt, nOpt) ){
        nMatch++;
        iRet = i;
      }
      nCandidate++;
    }
  }

  if( nMatch==1 ) return iRet;
  if( nMatch==0 ){
    int iCand = 0;
    if( bUnknownFatal==0 && zOpt[0]!='-' ) return -1;
    zMsg = sqlite3_mprintf("unknown option \"%s\". Expected ", zOpt);
    for(i=0; aOpt[i].zOpt; i++){
      if( aOpt[i].mask & mask ){
        iCand++;
        if( iCand<nCandidate ){
          zMsg = sqlite3_mprintf("%z%s%s", zMsg, (i==0?"":", "), aOpt[i].zOpt);
        }else{
          zMsg = sqlite3_mprintf("%z or %s", zMsg, aOpt[i].zOpt);
        }
      }
    }
  }else{
    int iCand = 0;
    int bFirst = 1;
    zMsg = sqlite3_mprintf("ambiguous option \"%s\" - could be ", zOpt);
    for(i=0; aOpt[i].zOpt; i++){
      if( aOpt[i].mask & mask ){
        int n = strlen(aOpt[i].zOpt);
        if( n>=nOpt && 0==memcmp(zOpt, aOpt[i].zOpt, nOpt) ){
          iCand++;
          if( iCand==nMatch ){
            zMsg = sqlite3_mprintf("%z or %s", zMsg, aOpt[i].zOpt);
          }else{
            zMsg = sqlite3_mprintf("%z%s%s",zMsg,(bFirst?"":", "),aOpt[i].zOpt);
            bFirst = 0;
          }
        }
      }
    }
  }

  fatal_error("%s", zMsg);
  return 0;
}


/*
** Parse the nul-terminated string indicated by argument zSize as a size
** parameter. A size parameter consists of any number of digits optionally
** followed by 'K', 'M' or 'G'. If successful, the size in bytes is returned.
** Otherwise, a fatal error is raised and the function does not return.
*/
static i64 parse_size(const char *zSize){
  i64 ret = 0;
  int i;

  for(i=0; zSize[i]; i++){
    if( zSize[i]<'0' || zSize[i]>'9' ) break;
    ret = ret*10 + (zSize[i]-'0');
  }

  switch( zSize[i] ){
    case 'k': case 'K':
      ret = ret * 1024;
      i++;
      break;
    case 'm': case 'M':
      ret = ret * 1024*1024;
      i++;
      break;
    case 'g': case 'G':
      ret = ret * 1024*1024*1024;
      i++;
      break;
  }

  if( zSize[i] ){
    fatal_error("parse error in size: %s", zSize);
  }

  return ret;
}

static int parse_seconds(const char *zSeconds){
  i64 ret = 0;
  int i;

  for(i=0; zSeconds[i]; i++){
    if( zSeconds[i]<'0' || zSeconds[i]>'9' ){
      fatal_error("parse error in seconds: %s", zSeconds);
    }
    ret = ret*10 + (zSeconds[i]-'0');
    if( ret>0x7fffffff ){
      fatal_error(
          "parse error in seconds (max value is %d): %s", 0x7fffffff, zSeconds
      );
    }
  }

  return (int)ret;
}

static int parse_integer(const char *zInt){
  i64 ret = 0;
  int i = 0;
  int bMinus = 0;

  if( zInt[0]=='-' ){
    i = bMinus = 1;
  }else if( zInt[0]=='+' ){
    i = 1;
  }

  for(; zInt[i]; i++){
    if( zInt[i]<'0' || zInt[i]>'9' ){
      fatal_error("parse error in integer: %s", zInt);
    }
    ret = ret*10 + (zInt[i]-'0');
    if( ret>0x7fffffff ){
      fatal_error(
          "parse error in integer (max value is %d): %s", 0x7fffffff, zInt
      );
    }
  }

  return (int)ret * (bMinus ? -1 : 1);
}


#define COMMANDLINE_CONTAINER    1
#define COMMANDLINE_DIRECTORY    4
#define COMMANDLINE_PORT         5
#define COMMANDLINE_CACHESIZE    7
#define COMMANDLINE_AUTOEXIT     8
#define COMMANDLINE_BLOCKSIZE    9
#define COMMANDLINE_POLLTIME     10
#define COMMANDLINE_DELETETIME   11
#define COMMANDLINE_GCTIME       12
#define COMMANDLINE_RETRYTIME    13
#define COMMANDLINE_LOG          14
#define COMMANDLINE_NODELETE     15
#define COMMANDLINE_CLOBBER      17
#define COMMANDLINE_NWRITE       18
#define COMMANDLINE_NDELETE      19
#define COMMANDLINE_READYMSG     20
#define COMMANDLINE_NAMEBYTES    21
#define COMMANDLINE_PERSISTENT   22
#define COMMANDLINE_VTAB         23
#define COMMANDLINE_NOTIMESTAMPS 27
#define COMMANDLINE_MODULE       28
#define COMMANDLINE_USER         29
#define COMMANDLINE_SECRET       30
#define COMMANDLINE_NREQUEST     31
#define COMMANDLINE_READONLY     32
#define COMMANDLINE_ALIAS        33
#define COMMANDLINE_POLL         34
#define COMMANDLINE_LAZY         35
#define COMMANDLINE_ADDR         36
#define COMMANDLINE_SECURE       37
#define COMMANDLINE_NONONCE      38
#define COMMANDLINE_AUTODETACH   39
#define COMMANDLINE_HTTPTIMEOUT  40
#define COMMANDLINE_HTTPLOGTIMEOUT 41
#define COMMANDLINE_HTTPLOGNENTRY  42

#define COMMAND_ALL              0xFFFFFFFF
#define COMMAND_DAEMON           0x40000000
#define COMMAND_CREATE           0x20000000      /* -blocksize, -namebytes */
#define COMMAND_CMDLINE          0x08000000      /* -module, -user, -auth */
#define COMMAND_CONTAINER        0x04000000
#define COMMAND_NREQUEST         0x02000000      /* -nrequest */

#define COMMAND_AUTH_CONTAINER (COMMAND_CMDLINE | COMMAND_CONTAINER)
#define COMMAND_UPDOWN         (COMMAND_AUTH_CONTAINER | COMMAND_NREQUEST)
#define COMMAND_CMDLINE_DAEMON (COMMAND_CMDLINE | COMMAND_DAEMON)


static void parse_more_switches(
  CommandSwitches *pCmd, 
  const char **azArg, 
  int nArg, 
  int *piFail,
  u32 mask
){
  int i;
  SelectOption aSwitch[] = {
    { "-file",           COMMAND_ALL    , 0},
    { "-delay",          COMMAND_ALL    , -1},
    { "-container",      COMMAND_CONTAINER      , COMMANDLINE_CONTAINER    },
    { "-port",           COMMAND_DAEMON         , COMMANDLINE_PORT         },
    { "-addr",           COMMAND_DAEMON         , COMMANDLINE_ADDR         },
    { "-cachesize",      COMMAND_DAEMON         , COMMANDLINE_CACHESIZE    },
    { "-autoexit",       COMMAND_DAEMON         , COMMANDLINE_AUTOEXIT     },
    { "-blocksize",      COMMAND_CREATE         , COMMANDLINE_BLOCKSIZE    },
    { "-log",            COMMAND_CMDLINE_DAEMON , COMMANDLINE_LOG          },
    { "-readymessage",   COMMAND_DAEMON         , COMMANDLINE_READYMSG     },
    { "-namebytes",      COMMAND_CREATE         , COMMANDLINE_NAMEBYTES    },
    { "-notimestamps",   COMMAND_DAEMON         , COMMANDLINE_NOTIMESTAMPS },
    { "-nrequest",       COMMAND_NREQUEST       , COMMANDLINE_NREQUEST     },
    { "-module",         COMMAND_CMDLINE        , COMMANDLINE_MODULE       },
    { "-user",           COMMAND_CMDLINE        , COMMANDLINE_USER         },
    { "-authentication", COMMAND_CMDLINE        , COMMANDLINE_SECRET,      },
    { "-httptimeout",    COMMAND_DAEMON         , COMMANDLINE_HTTPTIMEOUT  },
    { "-httplogtimeout", COMMAND_DAEMON         , COMMANDLINE_HTTPLOGTIMEOUT },
    { "-httplognentry",  COMMAND_DAEMON         , COMMANDLINE_HTTPLOGNENTRY  },
    { 0, 0 }
  };

  if( piFail ){
    *piFail = nArg;
  }

  for(i=0; i<nArg; i++){
    int iVal = select_option(azArg[i], aSwitch, mask, (piFail ? 0 : 1));
    if( iVal<0 ){
      *piFail = i;
      return;
    }

    switch( aSwitch[iVal].eVal){
      case -1:
      case 0:
      case COMMANDLINE_CONTAINER:
      case COMMANDLINE_DIRECTORY:
      case COMMANDLINE_PORT:
      case COMMANDLINE_ADDR:
      case COMMANDLINE_CACHESIZE:
      case COMMANDLINE_BLOCKSIZE:
      case COMMANDLINE_POLLTIME:
      case COMMANDLINE_DELETETIME:
      case COMMANDLINE_GCTIME:
      case COMMANDLINE_RETRYTIME:
      case COMMANDLINE_LOG:
      case COMMANDLINE_NWRITE:
      case COMMANDLINE_NDELETE:
      case COMMANDLINE_NAMEBYTES:
      case COMMANDLINE_MODULE:
      case COMMANDLINE_USER:
      case COMMANDLINE_SECRET:
      case COMMANDLINE_NREQUEST:
      case COMMANDLINE_ALIAS:
      case COMMANDLINE_AUTODETACH:
      case COMMANDLINE_HTTPTIMEOUT:
      case COMMANDLINE_HTTPLOGTIMEOUT:
      case COMMANDLINE_HTTPLOGNENTRY:
        i++;
        if( i==nArg ){
          fatal_error("option requires an argument: %s\n", azArg[i-1]);
        }
        break;
      default:
        break;
    }

    switch( aSwitch[iVal].eVal ){
      case -1: {
        sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
        int n = parse_seconds(azArg[i]);
        pVfs->xSleep(pVfs, 1000000*n);
        break;
      }
      case 0: {
        const char *zFile = azArg[i];
        const char *azParse[256];
        int nParse;
        int fd;
        struct stat buf;          /* Used to fstat() database file */
        char *aBuf;
        size_t nRead;
        char *p;

        /* Read the contents of file into a buffer obtained from
        ** sqlite3_malloc(). Append a nul-terminator to the buffer. */
        fd = open(zFile, O_RDONLY|O_BINARY);
        if( fd<0 ){
          fatal_error("failed to open file %s", azArg[i]);
        }
        fstat(fd, &buf);
        aBuf = bcvMallocZero(buf.st_size+1);
        nRead = read(fd, aBuf, buf.st_size);
        close(fd);
        if( nRead!=buf.st_size ){
          fatal_error("error reading file %s", azArg[i]);
        }

        memset((char**)azParse, 0, sizeof(azParse));
        nParse = 0;
        p = aBuf;
        while( nParse<sizeof(azParse)/sizeof(azParse[0]) ){
          while( bcv_isspace(*p) ){
            *p = '\0';
            p++;
          }
          if( *p=='\0' ) break;
          azParse[nParse++] = p;
          while( !bcv_isspace(*p) ) p++;
        }
        parse_more_switches(pCmd, azParse, nParse, 0, mask);
        sqlite3_free(aBuf);
        break;
      }
      case COMMANDLINE_CONTAINER:
        pCmd->zContainer = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_MODULE:
        sqlite3_free(pCmd->zModule);
        pCmd->zModule = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_USER:
        sqlite3_free(pCmd->zUser);
        pCmd->zUser = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_SECRET:
        sqlite3_free(pCmd->zSecret);
        pCmd->zSecret = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_ALIAS:
        sqlite3_free(pCmd->zAlias);
        pCmd->zAlias = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_ADDR:
        sqlite3_free(pCmd->zAddr);
        pCmd->zAddr = bcvStrdup(azArg[i]);
        break;
      case COMMANDLINE_PORT:
        pCmd->iPort = atoi(azArg[i]);
        break;
      case COMMANDLINE_CACHESIZE:
        pCmd->szCache = parse_size(azArg[i]);
        break;
      case COMMANDLINE_BLOCKSIZE:
        pCmd->szBlk = parse_size(azArg[i]);
        break;
      case COMMANDLINE_NOTIMESTAMPS:
        pCmd->bNoTimestamps = 1;
        break;
      case COMMANDLINE_AUTOEXIT:
        pCmd->bAutoexit = 1;
        break;
      case COMMANDLINE_NAMEBYTES:
        pCmd->nNamebytes = parse_integer(azArg[i]);
        if( pCmd->nNamebytes>BCV_MAX_NAMEBYTES 
         || pCmd->nNamebytes<BCV_MIN_NAMEBYTES
        ){
          fatal_error("value for -namebytes out of range "
              "(should be %d <= value <= %d)",
              BCV_MIN_NAMEBYTES, BCV_MAX_NAMEBYTES
          );
        }
        break;
      case COMMANDLINE_LOG: {
        int ii;
        const char *zArg = azArg[i];
        for(ii=0; zArg[ii]; ii++){
          switch( zArg[ii] ){
            case 'm':
              pCmd->mLog |= BCV_LOG_MESSAGE;
              break;
            case 'e':
              pCmd->mLog |= BCV_LOG_EVENT;
              break;
            case 'p':
              pCmd->mLog |= BCV_LOG_POLL;
              break;
            case 'u':
              pCmd->mLog |= BCV_LOG_UPLOAD;
              break;
            case 'c':
              pCmd->mLog |= BCV_LOG_CACHE;
              break;
            case 'h':
              pCmd->mLog |= BCV_LOG_HTTP;
              break;
            case 'r':
              pCmd->mLog |= BCV_LOG_HTTPRETRY;
              break;
            case 'v':
              pCmd->mLog |= BCV_LOG_VERBOSE;
              break;
            case 's':
              pCmd->mLog |= BCV_LOG_SCHEDULE;
              break;
            default:
              /* no-op */
              break;
          }
        }
        break;
      }
      case COMMANDLINE_READYMSG:
        pCmd->bReadyMessage = 1;
        break;
      case COMMANDLINE_NREQUEST:
        pCmd->nRequest = parse_integer(azArg[i]);
        break;
      case COMMANDLINE_READONLY:
        pCmd->bReadonly = 1;
        break;
      case COMMANDLINE_SECURE:
        pCmd->bSecure = 1;
        break;
      case COMMANDLINE_HTTPTIMEOUT:
        pCmd->nHttpTimeout = parse_seconds(azArg[i]);
        break;
      case COMMANDLINE_HTTPLOGTIMEOUT:
        pCmd->nHttpLogTimeout = parse_seconds(azArg[i]);
        break;
      case COMMANDLINE_HTTPLOGNENTRY:
        pCmd->nHttpLogNentry = parse_integer(azArg[i]);
        break;
      default:
        break;
    }
  }
}

static void parse_switches(
  CommandSwitches *pCmd, 
  char **azArg, 
  int nArg, 
  int *piFail,
  u32 mask
){
  memset(pCmd, 0, sizeof(CommandSwitches));
  pCmd->nHttpLogTimeout = BCV_DEFAULT_HTTPLOG_TIMEOUT;
  pCmd->nHttpLogNentry = BCV_DEFAULT_HTTPLOG_NENTRY;
  parse_more_switches(pCmd, (const char**)azArg, nArg, piFail, mask);
}

static void free_parse_switches(CommandSwitches *pCmd){
  sqlite3_free(pCmd->zContainer);
  sqlite3_free(pCmd->zModule);
  sqlite3_free(pCmd->zUser);
  sqlite3_free(pCmd->zSecret);
  sqlite3_free(pCmd->zAddr);
  memset(pCmd, 0, sizeof(CommandSwitches));
}

static void missing_required_switch(const char *zSwitch){
  fatal_error("missing required switch: %s\n", zSwitch);
}

static void bcvHttpLog(void *pUnused, int bRetry, const char *zMsg){
  if( bRetry || pUnused!=0 ){
    fprintf(stdout, "INFO(h): %s\n", zMsg);
    fflush(stdout);
  }
}

static void bcvOpenHandle(CommandSwitches *pCmd, sqlite3_bcv **ppBcv){
  int rc;
  if( pCmd->zModule==0 ) missing_required_switch("-module");
  rc = sqlite3_bcv_open(
      pCmd->zModule, pCmd->zUser, pCmd->zSecret, pCmd->zContainer, ppBcv
  );
  if( rc!=SQLITE_OK ){
    fatal_error("error (%d): %s\n", rc, sqlite3_bcv_errmsg(*ppBcv));
  }else{
    if( pCmd->mLog & BCV_LOG_VERBOSE ){
      sqlite3_bcv_config(*ppBcv, SQLITE_BCVCONFIG_VERBOSE, (int)1);
    }
    if( pCmd->mLog & (BCV_LOG_HTTP|BCV_LOG_HTTPRETRY) ){
      void *pCtx = (void*)(pCmd->mLog & BCV_LOG_HTTP ? 1 : 0);
      sqlite3_bcv_config(*ppBcv, SQLITE_BCVCONFIG_LOG, pCtx, bcvHttpLog);
    }
    sqlite3_bcv_config(*ppBcv, SQLITE_BCVCONFIG_NREQUEST, pCmd->nRequest);
  }
}

static void bcvOpenContainer(
  CommandSwitches *pCmd, 
  BcvContainer **ppCont,
  BcvDispatch **ppDisp
){
  int rc = SQLITE_OK;
  char *zErr = 0;
  if( pCmd->zModule==0 ) missing_required_switch("-module");
  rc = bcvContainerOpen(
      pCmd->zModule, pCmd->zUser, pCmd->zSecret, pCmd->zContainer, ppCont, &zErr
  );
  if( rc!=SQLITE_OK ){
    fatal_error("error (%d): %s\n", rc, zErr);
  }
  rc = bcvDispatchNew(ppDisp);
  if( rc!=SQLITE_OK ){
    assert( rc==SQLITE_NOMEM );
    fatal_error("error (%d): out of memory\n", rc);
  }
  bcvDispatchVerbose(*ppDisp, (pCmd->mLog & BCV_LOG_VERBOSE) ? 1 : 0);
  if( pCmd->mLog & (BCV_LOG_HTTP|BCV_LOG_HTTPRETRY) ){
    void *pCtx = (void*)(pCmd->mLog & BCV_LOG_HTTP ? 1 : 0);
    bcvDispatchLog(*ppDisp, pCtx, bcvHttpLog);
  }
}

static int xProgress(void *pCtx, sqlite3_int64 nDone, sqlite3_int64 nTotal){
  fprintf(stdout, ".");
  fflush(stdout);
  return 0;
}

/*
** Command: $argv[0] upload ?SWITCHES? DBFILE ?NAME?
**
** Upload a database file to cloud storage. The container and manifest
** file must already exist.
*/
static int main_upload(int argc, char **argv){
  CommandSwitches cmd;
  int iFail = 0;
  int *ptr;
  const char *zDbfile;
  const char *zName;
  sqlite3_bcv *pBcv;
  int rc;

  /* Parse command line */
  if( argc<=2 ){
    fprintf(stderr, "Usage: %s upload ?SWITCHES? DBFILE ?NAME?\n", argv[0]);
    exit(1);
  }
  ptr = &iFail;
  while( iFail<argc-4 ){
    parse_switches(&cmd, &argv[2], argc-3, ptr, COMMAND_UPDOWN);
    ptr = 0;
  }
  assert( iFail==argc-4 || iFail==argc-3 );
  if( iFail==argc-4 ){
    zDbfile = (const char*)argv[argc-2];
    zName = (const char*)argv[argc-1];
  }else{
    zDbfile = (const char*)argv[argc-1];
    zName = &zDbfile[strlen(zDbfile)];
    while( zName>zDbfile && zName[-1]!='/' && zName[-1]!='\\' ) zName--;
  }
  if( cmd.zContainer==0 ) missing_required_switch("-container");

  bcvOpenHandle(&cmd, &pBcv);
  sqlite3_bcv_config(pBcv, SQLITE_BCVCONFIG_PROGRESS, (void*)0, xProgress);

  rc = sqlite3_bcv_upload(pBcv, zDbfile, zName);
  if( rc ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }else{
    fprintf(stdout, "\n");
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);

  return rc;
}

/*
** Command: $argv[0] download ?SWITCHES? DBNAME ?LOCALFILE?
**
** Download a database file from cloud storage.
*/
static int main_download(int argc, char **argv){
  CommandSwitches cmd;
  int iFail = 0;
  int *ptr = 0;
  const char *zRemote = 0;
  const char *zLocal = 0;
  sqlite3_bcv *pBcv = 0;
  int rc;

  /* Parse command line */
  if( argc<=2 ){
    fprintf(stderr, 
        "Usage: %s download ?SWITCHES? DBNAME ?LOCALFILE?\n", argv[0]
    );
    exit(1);
  }
  ptr = &iFail;
  while( iFail<argc-4 ){
    parse_switches(&cmd, &argv[2], argc-3, ptr, COMMAND_UPDOWN);
    ptr = 0;
  }
  if( iFail==argc-4 ){
    zRemote = (const char*)argv[argc-2];
    zLocal = (const char*)argv[argc-1];
  }else{
    zLocal = zRemote = (const char*)argv[argc-1];
  }
  if( cmd.zContainer==0 ) missing_required_switch("-container");

  bcvOpenHandle(&cmd, &pBcv);
  sqlite3_bcv_config(pBcv, SQLITE_BCVCONFIG_PROGRESS, (void*)0, xProgress);

  rc = sqlite3_bcv_download(pBcv, zRemote, zLocal);
  if( rc ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }else{
    fprintf(stdout, "\n");
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);
  return rc;
}

/*
** Command: $argv[0] copy ?SWITCHES? DB1 DB2
**
** Make a copy of a database within cloud storage.
*/
static int main_copy(int argc, char **argv){
  const char *zDbFrom, *zDbTo;
  CommandSwitches cmd;
  int rc;
  sqlite3_bcv *pBcv = 0;

  /* Parse command line */
  if( argc<4 ){
    fprintf(stderr, "Usage: %s copy ?SWITCHES? DBFROM DBTO\n", argv[0]);
    exit(1);
  }
  zDbFrom = argv[argc-2];
  zDbTo = argv[argc-1];
  parse_switches(&cmd, &argv[2], argc-4, 0, COMMAND_AUTH_CONTAINER);

  bcvOpenHandle(&cmd, &pBcv);
  rc = sqlite3_bcv_copy(pBcv, zDbFrom, zDbTo);
  if( rc ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);

  return rc;
}

static int filesCb(void *pApp, int rc, char *z){
  if( rc==SQLITE_OK ){
    if( z ) printf("%s\n", z);
  }else{
    fatal_error("error (%d) - %s", rc, z);
  }
  return SQLITE_OK;
}

/*
** Command: $argv[0] files ?SWITCHES? CONTAINER
*/
static int main_files(int argc, char **argv){
  CommandSwitches cmd;
  BcvContainer *pCont = 0;
  BcvDispatch *pDisp = 0;
  int rc;

  /* Parse command line */
  if( argc<3 ){
    fprintf(stderr, "Usage: %s files ?SWITCHES? CONTAINER\n", argv[0]);
    exit(1);
  }
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_CMDLINE);
  cmd.zContainer = bdStrdup(argv[argc-1]);

  bcvOpenContainer(&cmd, &pCont, &pDisp);
  bcvDispatchList(pDisp, pCont, 0, 0, filesCb);
  rc = bcvDispatchRunAll(pDisp);
  if( rc!=SQLITE_OK ) fatal_error("error %d", rc);

  bcvDispatchFree(pDisp);
  bcvContainerClose(pCont);
  free_parse_switches(&cmd);
  return 0;
}

static void bcvFetchManifestCb(
  void *pApp, 
  int rc, 
  char *zETag, 
  const u8 *aData, 
  int nData,
  const u8 *aHdrs, int nHdrs
){
  Manifest **ppMan = (Manifest**)pApp;
  char *zErr = 0;
  int prc;

  if( rc!=SQLITE_OK ){
    fatal_error("error %d - %s", rc, zETag);
  }
  prc = bcvManifestParseCopy(aData, nData, zETag, ppMan, &zErr);
  if( prc ){
    fatal_error("error parsing manifest (%d) - %s", prc, zErr);
  }
}

static Manifest *bcvFetchManifest(CommandSwitches *pCmd){
  BcvContainer *pCont = 0;        /* Connection to cloud storage */
  BcvDispatch *pDisp = 0;         /* Dispatcher used to manage pCont */
  Manifest *pMan = 0;
  int rc;

  bcvOpenContainer(pCmd, &pCont, &pDisp);
  bcvDispatchFetch(pDisp, pCont,BCV_MANIFEST_FILE,0,0,&pMan,bcvFetchManifestCb);
  rc = bcvDispatchRunAll(pDisp);
  if( rc!=SQLITE_OK ) fatal_error("error %d", rc);
  bcvDispatchFree(pDisp);
  bcvContainerClose(pCont);
  return pMan;
}


static int main_list(int argc, char **argv){
  CommandSwitches cmd;
  Manifest *p;
  int i;

  /* Parse command line */
  if( argc<3 ){
    fprintf(stderr, "Usage: %s manifest ?SWITCHES? CONTAINER\n", argv[0]);
    exit(1);
  }
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_CMDLINE);
  cmd.zContainer = argv[argc-1];

  p = bcvFetchManifest(&cmd);
  for(i=0; i<p->nDb; i++){
    ManifestDb *pDb = &p->aDb[i];
    printf("%s %d blocks\n", pDb->zDName, pDb->nBlkLocal);
  }
  bcvManifestFree(p);
  return 0;
}

static int bdOpenLocalFile(
  const char *zCont, 
  const char *zDb, 
  int bWal,
  int bReadonly,
  sqlite3_file **ppFile
){
  char *zPath;
  int rc;
  zPath = bcvMprintf("%s%s%s%s", zCont, zCont?"/":"", zDb, bWal?"-wal":"");
  rc = bcvOpenLocal(zPath, bWal, bReadonly, ppFile);
  sqlite3_free(zPath);
  return rc;
}


/*
** Command: $argv[0] manifest ?SWITCHES? CONTAINER
*/
static int main_manifest(int argc, char **argv){
  CommandSwitches cmd;
  Manifest *p = 0;
  int i, j;

  /* Parse command line */
  if( argc<3 ){
    fprintf(stderr, "Usage: %s manifest ?SWITCHES? CONTAINER\n", argv[0]);
    exit(1);
  }
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_CMDLINE);
  cmd.zContainer = argv[argc-1];
  p = bcvFetchManifest(&cmd);

  printf("Manifest version: %d\n", BCV_MANIFEST_VERSION);
  printf("Block size: %d\n", p->szBlk);
  printf("Database count: %d\n", p->nDb);

  printf("Delete Block list: (%d blocks)\n", p->nDelBlk);
  for(i=0; i<p->nDelBlk; i++){
    u8 *aEntry = &p->aDelBlk[i*GCENTRYBYTES(p)];
    i64 t;
    char aBuf[BCV_MAX_FSNAMEBYTES];
    bcvBlockidToText(NAMEBYTES(p), aEntry, aBuf);
    t = bcvGetU64(&aEntry[NAMEBYTES(p)]);
    printf("    %s (t=%lld)\n", aBuf, t);
  }

  for(i=0; i<p->nDb; i++){
    ManifestDb *pDb = &p->aDb[i];
    printf("Database %d id: %lld\n", i, pDb->iDbId);
    printf("Database %d name: %s\n", i, pDb->zDName);
    printf("Database %d version: %d\n", i, pDb->iVersion);
    printf("Database %d block list: (%d blocks)\n", i, pDb->nBlkLocal);
    for(j=0; j<pDb->nBlkLocal; j++){
      char aBuf[BCV_MAX_FSNAMEBYTES];
      bcvBlockidToText(NAMEBYTES(p), &pDb->aBlkLocal[j*NAMEBYTES(p)], aBuf);
      printf("    %s\n", aBuf);
    }
  }

  bcvManifestFree(p);
  return 0;
}

static int main_delete(int argc, char **argv){
  const char *zDbfile;
  CommandSwitches cmd;
  sqlite3_bcv *pBcv = 0;
  int rc;

  /* Parse command line */
  if( argc<=2 ){
    fprintf(stderr, "Usage: %s delete ?SWITCHES? DB\n", argv[0]);
    exit(1);
  }
  zDbfile = argv[argc-1];
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_AUTH_CONTAINER);
  if( cmd.zContainer==0 ) missing_required_switch("-container");

  bcvOpenHandle(&cmd, &pBcv);
  rc = sqlite3_bcv_delete(pBcv, zDbfile);
  if( rc ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);

  return rc;
}

static int main_create(int argc, char **argv){
  const char *zCont;              /* Name of new container */
  CommandSwitches cmd;
  sqlite3_bcv *pBcv = 0;
  int rc;

  /* Parse command line */
  if( argc<=2 ){
    fprintf(stderr, "Usage: %s create ?SWITCHES? CONTAINER\n", argv[0]);
    exit(1);
  }
  zCont = argv[argc-1];
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_CREATE | COMMAND_CMDLINE); 

  cmd.zContainer = (char*)zCont;
  bcvOpenHandle(&cmd, &pBcv);
  cmd.zContainer = 0;
  rc = sqlite3_bcv_create(pBcv, cmd.nNamebytes, cmd.szBlk);
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);

  return rc;
}

static int main_destroy(int argc, char **argv){
  const char *zCont;              /* Name of new container */
  CommandSwitches cmd;
  sqlite3_bcv *pBcv = 0;
  int rc;

  /* Parse command line */
  if( argc<=2 ){
    fprintf(stderr, "Usage: %s destroy ?SWITCHES? CONTAINER\n", argv[0]);
    exit(1);
  }
  zCont = argv[argc-1];
  parse_switches(&cmd, &argv[2], argc-3, 0, COMMAND_CMDLINE);
  cmd.zContainer = (char*)zCont;
  bcvOpenHandle(&cmd, &pBcv);
  cmd.zContainer = 0;
  rc = sqlite3_bcv_destroy(pBcv);
  if( rc ){
    fprintf(stderr, "error (%d): %s\n", rc, sqlite3_bcv_errmsg(pBcv));
  }
  sqlite3_bcv_close(pBcv);
  free_parse_switches(&cmd);
  return rc;
}

/**************************************************************************
***************************************************************************
** START OF DAEMON CODE
***************************************************************************
**************************************************************************/

#define BCV_MAX_RESERVE 10

typedef struct DaemonCtx DaemonCtx;
typedef struct DClient DClient;
typedef struct FetchCtx FetchCtx;
typedef struct DPrefetch DPrefetch;

struct DPrefetch {
  int bPrefetch;                  /* True if this is a prefetch connection */
  int nOutstanding;
  int iNext;
  int bReply;
  int errCode;
  char *zErrMsg;
};

/*
** pMan, pManDb:
**   Non-NULL only when a transaction is open. The manifest and specific
**   datbase within it on which the transaction is open.
*/
struct DClient {
  int nRef;                       /* Ref count on this structure */
  DaemonCtx *pCtx;
  DClient *pNext;                 /* Next client belonging to this daemon */
  int iClientId;                  /* Client id */
  BCV_SOCKET_TYPE fd;             /* Localhost socket for this client */
  char *zClientId;                /* PRAGMA bcv_client */

  Container *pCont;               /* Container this client reads from */
  i64 iDbId;                      /* Id of accessed database */
  Manifest *pMan;
  ManifestDb *pManDb;
  CacheEntry **apRef;

  DPrefetch prefetch;             /* If this is a prefetch client */

  BcvContainer *pBcv;             /* BCV handle, if any */
  char *zAuth;                    /* Authentication string used by pBcv */
  BcvMessage *pMsg;               /* Client message currently being processed */

  int pgsz;                       /* Page-size of connected database */
  sqlite3_file *pCloseFd;
};

struct DaemonCtx {
  BCV_SOCKET_TYPE fdListen;       /* Socket fd waiting on new connections */
  int iListenPort;                /* Port fdListen is listening on */
  CommandSwitches cmd;            /* Command line options */

  BcvCommon c;                    /* Hash tables and so on */
  BcvDispatch *pDisp;             /* Dispatch object used by this daemon */

  DClient *pClientList;           /* List of connected clients */
  int iNextId;                    /* Next client or encryption id */

  sqlite3_file *pCacheFile;
};

struct FetchCtx {
  DClient *pClient;               /* Client object */
  DaemonCtx *pCtx;
  CacheEntry *pEntry;             /* Cache entry to populate (if any) */
  Container *pCont;
  BcvIntKey *pKey;
};

static void daemon_usage(char *argv0){
  fatal_error("Usage: %s daemon ?SWITCHES? CONTAINER [CONTAINER...]", argv0);
}

static void daemon_log_timestamp(DaemonCtx *p, char *zBuf){
  if( p->cmd.bNoTimestamps ){
    zBuf[0] = '\0';
  }else{
    sqlite3_int64 ms = sqlite_timestamp();
    int Z, A, B, C, D, E, X1;
    int s;

    int day, month, year;
    int sec, min, hour;

    Z = (int)((ms + 43200000)/86400000);
    A = (int)((Z - 1867216.25)/36524.25);
    A = Z + 1 + A - (A/4);
    B = A + 1524;
    C = (int)((B - 122.1)/365.25);
    D = (36525*(C&32767))/100;
    E = (int)((B-D)/30.6001);
    X1 = (int)(30.6001*E);

    day =  B - D - X1;
    month = E<14 ? E-1 : E-13;
    year = month>2 ? C - 4716 : C - 4715;

    s = (int)((ms + 43200000) % 86400000)/1000;
    hour = s/3600;
    s -= hour*3600;
    min = s/60;
    sec = s - min*60;

    sqlite3_snprintf(128, zBuf,
        " [%.4d/%.2d/%.2d %.2d:%.2d:%.2d.%.3d]", 
        year, month, day, hour, min, sec, ms%1000
    );
  }
}

static void daemon_vlog(DaemonCtx *p, int flags, const char *zFmt, va_list ap){
  if( p->cmd.mLog & flags ){
    char zTime[128];
    char *zMsg = sqlite3_vmprintf(zFmt, ap);
    daemon_log_timestamp(p, zTime);
    fprintf(stdout, "INFO(%s%s%s%s%s%s%s%s)%s: %s\n",
        (flags & BCV_LOG_POLL ? "p" : ""),
        (flags & BCV_LOG_EVENT ? "e" : ""),
        (flags & BCV_LOG_MESSAGE ? "m" : ""),
        (flags & BCV_LOG_UPLOAD ? "u" : ""),
        (flags & BCV_LOG_CACHE ? "c" : ""),
        (flags & BCV_LOG_HTTPRETRY ? "r" : ""),
        (flags & BCV_LOG_HTTP ? "h" : ""),
        (flags & BCV_LOG_SCHEDULE ? "s" : ""),
        zTime, zMsg);
    fflush(stdout);
    sqlite3_free(zMsg);
  }
}

static void daemon_event_log(DaemonCtx *p, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  daemon_vlog(p, BCV_LOG_EVENT, zFmt, ap);
  va_end(ap);
}

static void daemon_msg_log(DaemonCtx *p, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  daemon_vlog(p, BCV_LOG_MESSAGE, zFmt, ap);
  va_end(ap);
}

static void daemon_log(DaemonCtx *p, int flags, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  daemon_vlog(p, flags, zFmt, ap);
  va_end(ap);
}

static void bdHttpLog(void *pApp, int bRetry, const char *zMsg){
  DaemonCtx *p = (DaemonCtx*)pApp;
  int flags = BCV_LOG_HTTP | (bRetry ? BCV_LOG_HTTPRETRY : 0);
  daemon_log(p, flags, "%s", zMsg);
}

static void daemon_error(const char *zFmt, ...){
  char *zMsg;
  va_list ap;
  va_start(ap, zFmt);
  zMsg = sqlite3_vmprintf(zFmt, ap);
  fprintf(stdout, "ERROR: %s\n", zMsg);
  fflush(stdout);
  sqlite3_free(zMsg);
  va_end(ap);
}

/*
** Start listening on a localhost port. Return the port number. 
**
** If successful, the port number is left in DaemonCtx.iListenPort. If an
** error occurs, this function does not return. Instead, it outputs a
** message to stderr and exits.
*/
static void bdListen(DaemonCtx *p){
  int nAttempt = p->cmd.iPort ? 1 : 1000;
  int i;
  struct sockaddr_in addr;
  int tr = 1;

  p->fdListen = socket(AF_INET, SOCK_STREAM, 0);
  if( bcv_socket_is_valid(p->fdListen)==0 ){
    fatal_system_error("listen()", errno);
  }
#ifndef __WIN32__
  setsockopt(p->fdListen, SOL_SOCKET, SO_REUSEADDR, &tr, sizeof(int));
#endif

  for(i=0; i<nAttempt; i++){
    int iPort = p->cmd.iPort ? p->cmd.iPort : 22002+i;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    if( p->cmd.zAddr ){
      addr.sin_addr.s_addr = inet_addr(p->cmd.zAddr);
      if( addr.sin_addr.s_addr==INADDR_NONE ){
        fatal_error("invalid IP address: %s", p->cmd.zAddr);
      }
    }else{
      addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    }
    addr.sin_port = htons(iPort);

    if( bind(p->fdListen, (struct sockaddr*)&addr, sizeof(addr))==0 ){
      if( listen(p->fdListen, 16)<0 ){
        fatal_system_error("listen()", errno);
      }else{
        p->iListenPort = iPort;
        return;
      }
    }
  }

  fatal_error("failed to bind to localhost port - tried %d to %d", 
      22002, 22002+nAttempt-1
  );
}

/*
** This is called by the daemon main loop whenever there is a new client
** connection.
*/
static void bdNewConnection(DaemonCtx *p){
  struct sockaddr_in addr;        /* Address of new client */
  socklen_t len = sizeof(addr);   /* Size of addr in bytes */
  DClient *pNew;                  /* New client object */

  pNew = (DClient*)bcvMallocZero(sizeof(DClient));
  pNew->fd = accept(p->fdListen, (struct sockaddr*)&addr, &len);
  if( pNew->fd<0 ){
    fatal_system_error("accept()", errno);
  }
  pNew->iClientId = ++p->iNextId;
  pNew->pNext = p->pClientList;
  pNew->pCtx = p;
  pNew->nRef = 1;
  p->pClientList = pNew;

  if( p->cmd.mLog & BCV_LOG_MESSAGE ){
    daemon_msg_log(p, "%d->D: connect!", pNew->iClientId);
  }
}

/*
** Return a string representation of the array of unsigned integers passed
** via the two arguments. e.g. "1,2,3,4,5". It is the responsibility of the
** caller to eventually free the returned buffer using sqlite3_free().
*/
static char *bdArrayToString(u32 *aInt, int nInt){
  char *zRet = 0;
  int ii;
  for(ii=0; ii<nInt; ii++){
    zRet = bcvMprintf("%z%s%d", zRet, zRet?",":"", (int)aInt[ii]);
  }
  return zRet;
}

static void bdLogRecvMsg(DaemonCtx *p, DClient *pClient, BcvMessage *pMsg){
  if( p->cmd.mLog & BCV_LOG_MESSAGE ){
    switch( pMsg->eType ){
      case BCV_MESSAGE_ATTACH:
        daemon_msg_log(p, "%d->D: ATTACH"
            "(\"%s\", \"%s\", \"%s\", \"%s\", %d bytes of auth-data, 0x%02.x)",
            pClient->iClientId,
            pMsg->u.attach.zStorage,
            pMsg->u.attach.zAccount,
            pMsg->u.attach.zContainer,
            pMsg->u.attach.zAlias,
            bcvStrlen(pMsg->u.attach.zAuth),
            pMsg->u.attach.flags
        );
        break;

      case BCV_MESSAGE_DETACH:
        daemon_msg_log(p, "%d->D: "
            "DETACH(\"%s\")", pClient->iClientId, pMsg->u.detach.zName
        );
        break;

      case BCV_MESSAGE_VTAB:
        daemon_msg_log(p, "%d->D: "
            "VTAB(\"%s\", \"%s\", \"%s\")", pClient->iClientId, 
            pMsg->u.vtab.zVtab,
            pMsg->u.vtab.zContainer,
            pMsg->u.vtab.zDatabase
        );
        break;

      case BCV_MESSAGE_READ: {
        char *zArray = bdArrayToString(pMsg->u.read.aMru, pMsg->u.read.nMru);
        daemon_msg_log(p, "%d->D: READ(%d, [%s])", 
            pClient->iClientId, (int)pMsg->u.read.iBlk, zArray
        );
        sqlite3_free(zArray);
        break;
      }

      case BCV_MESSAGE_END: {
        char *zArray = bdArrayToString(pMsg->u.end.aMru, pMsg->u.end.nMru);
        daemon_msg_log(p, "%d->D: END([%s])", pClient->iClientId, zArray);
        sqlite3_free(zArray);
        break;
      }

      case BCV_MESSAGE_HELLO:
        daemon_msg_log(p, "%d->D: "
            "HELLO(\"%s\",\"%s\")", pClient->iClientId, 
            pMsg->u.hello.zContainer, pMsg->u.hello.zDatabase
        );
        break;

      case BCV_MESSAGE_CMD: {
        int eCmd = pMsg->u.cmd.eCmd;
        daemon_msg_log(p, "%d->D: CMD(%s)", pClient->iClientId, 
          eCmd==BCV_CMD_POLL ? "poll" : 
          eCmd==BCV_CMD_CLIENT ? "client" : "???"
        );
        break;
      }

      case BCV_MESSAGE_PASS:
        daemon_msg_log(p, "%d->D: "
            "PASS(%d bytes of auth data)", pClient->iClientId, 
            bcvStrlen(pMsg->u.pass.zAuth)
        );
        break;

      case BCV_MESSAGE_PREFETCH:
        daemon_msg_log(p, "%d->D: "
            "PREFETCH(%d bytes of auth data, %d, %d)", pClient->iClientId, 
            bcvStrlen(pMsg->u.prefetch.zAuth), pMsg->u.prefetch.nRequest,
            pMsg->u.prefetch.nMs
        );
        break;
      default:
        assert( 0 );
    }
  }
}

static void bdLogSendMsg(DaemonCtx *p, DClient *pClient, BcvMessage *pMsg){
  if( p->cmd.mLog & BCV_LOG_MESSAGE ){
    switch( pMsg->eType ){
      case BCV_MESSAGE_REPLY:
        daemon_msg_log(p, "D->%d: REPLY(%d, \"%s\")",
            pClient->iClientId,
            pMsg->u.error_r.errCode,
            pMsg->u.error_r.zErrMsg
        );
        break;
      case BCV_MESSAGE_VTAB_REPLY:
        daemon_msg_log(p, "D->%d: VTAB_REPLY(%d bytes...)", 
            pClient->iClientId, pMsg->u.vtab_r.nData
        );
        break;
      case BCV_MESSAGE_HELLO_REPLY:
        daemon_msg_log(p, 
            "D->%d: HELLO_REPLY(%d,\"%s\",\"%s\",\"%s\",\"%s\",%d,%d)",
            pClient->iClientId, 
            pMsg->u.hello_r.errCode,
            pMsg->u.hello_r.zErrMsg,
            pMsg->u.hello_r.zStorage,
            pMsg->u.hello_r.zAccount,
            pMsg->u.hello_r.zContainer,
            pMsg->u.hello_r.szBlk,
            pMsg->u.hello_r.bEncrypted
        );
        break;
      case BCV_MESSAGE_READ_REPLY: {
        char *z = bdArrayToString(pMsg->u.read_r.aBlk, pMsg->u.read_r.nBlk);
        daemon_msg_log(p, "D->%d: READ_REPLY(%d, \"%s\", [%s])",
            pClient->iClientId,
            pMsg->u.read_r.errCode,
            pMsg->u.read_r.zErrMsg,
            z
        );
        sqlite3_free(z);
        break;
      }

      case BCV_MESSAGE_PASS_REPLY: {
        daemon_msg_log(p, "D->%d: PASS_REPLY(%d, \"%s\", 16 bytes of key)",
            pClient->iClientId,
            pMsg->u.pass_r.errCode,
            pMsg->u.pass_r.zErrMsg
        );
        break;
      }

      case BCV_MESSAGE_PREFETCH_REPLY: {
        daemon_msg_log(p, "D->%d: PREFETCH_REPLY(%d, \"%s\", %d, %d)",
            pClient->iClientId,
            pMsg->u.prefetch_r.errCode,
            pMsg->u.prefetch_r.zErrMsg,
            pMsg->u.prefetch_r.nOutstanding,
            pMsg->u.prefetch_r.nOnDemand
        );
        break;
      }
      default:
        assert( 0 );
        break;
    }
  }
}

static void bdReleaseEntryRefs(DClient *pClient){
  int nRef = pClient->pManDb->nBlkLocal;
  int ii;
  for(ii=0; ii<nRef; ii++){
    CacheEntry *pEntry = pClient->apRef[ii];
    if( pEntry ){
      assert( pEntry->nRef>0 );
      pEntry->nRef--;
    }
  }
  memset(pClient->apRef, 0, sizeof(CacheEntry*) * nRef);
}

static void bdClientDecrRefcount(DClient *pClient){
  pClient->nRef--;
  if( pClient->nRef==0 ){
    sqlite3_free(pClient);
  }
}

static void bdDisconnectClient(
  DaemonCtx *p, 
  DClient *pClient, 
  const char *zWhy
){
  DClient **pp;
  Container *pCont = pClient->pCont;

  daemon_msg_log(p, "%d->D: disconnect.. (%s)", pClient->iClientId, zWhy);

  /* Decrement the ref-count on a container, if this client was associated
  ** with one.  */
  if( pCont ){
    assert( pCont->nClient>0 );
    pCont->nClient--;
  }

  /* Remove the client from the linked list at DaemonCtx.pClientList */
  for(pp=&p->pClientList; *pp!=pClient; pp=&(*pp)->pNext);
  *pp = pClient->pNext;

  /* Close the socket connection */
  bcv_close_socket(pClient->fd);
  pClient->fd = INVALID_SOCKET;

  /* Free any message that was waiting for a reply */
  sqlite3_free(pClient->pMsg);
  pClient->pMsg = 0;

  if( pClient->apRef ){
    bdReleaseEntryRefs(pClient);
    sqlite3_free(pClient->apRef);
  }
  bcvManifestDeref(pClient->pMan);

  bcvContainerClose(pClient->pBcv);
  sqlite3_free(pClient->zAuth);
  sqlite3_free(pClient->prefetch.zErrMsg);

  if( pClient->pCloseFd ){
    pClient->pCloseFd->pMethods->xShmUnmap(pClient->pCloseFd, 0);
  }
  bcvCloseLocal(pClient->pCloseFd);
  pClient->pCloseFd = 0;

  sqlite3_free(pClient->zClientId);
  pClient->zClientId = 0;

  /* Free the client structure itself */
  bdClientDecrRefcount(pClient);
}

static void bdSendMsg(DaemonCtx *p, DClient *pClient, BcvMessage *pMsg){
  int rc;
  bdLogSendMsg(p, pClient, pMsg);
  rc = bcvSendMsg(pClient->fd, pMsg);
  if( rc!=SQLITE_OK ){
    bdDisconnectClient(p, pClient, "send() failure");
  }
}

static DClient *bdFetchClient(FetchCtx *pDLCtx){
  return pDLCtx->pClient->fd==INVALID_SOCKET ? 0 : pDLCtx->pClient;
}

static void bdBlockDownloadFree(FetchCtx *p){
  bdClientDecrRefcount(p->pClient);
  bcvIntEncryptionKeyFree(p->pKey);
  sqlite3_free(p);
}

/*
** Create a directory for container zCont.
*/
static void bcvCreateDir(int *pRc, BcvCommon *p, const char *zCont){
  struct stat buf;
  char *zDir = bcvMprintfRc(pRc, 
      "%s" BCV_PATH_SEPARATOR "%s", p->zDir, zCont
  );
  if( *pRc==SQLITE_OK && stat(zDir, &buf)<0 ){
    if( osMkdir(zDir, 0755)<0 && stat(zDir, &buf)<0 ){
      *pRc = SQLITE_CANTOPEN;
    }
  }
  sqlite3_free(zDir);
}

static void bdAttachCb(
  void *pCtx, 
  int errCode, 
  char *zETag, 
  const u8 *aData, 
  int nData,
  const u8 *aHdrs, int nHdrs
){
  BcvMessage reply;
  FetchCtx *pDLCtx = (FetchCtx*)pCtx;
  DClient *pClient = bdFetchClient(pDLCtx);
  BcvCommon *pCommon = &pDLCtx->pCtx->c;
  BcvMessage *pMsg = 0;
  Container *pCont = 0;
  int rc = errCode;
  Manifest *pMan = 0;
  char *zErr = 0;
  const char *zName = 0;

  /* If the client has already disconnected, do nothing. */
  bdBlockDownloadFree(pDLCtx);
  if( pClient==0 ) return;

  /* Check if there is already a container of the same name attached. 
  ** If there is, it is an error.  */
  pMsg = pClient->pMsg;
  zName = pMsg->u.attach.zAlias?pMsg->u.attach.zAlias:pMsg->u.attach.zContainer;
  if( rc==SQLITE_OK && bcvfsFindContAlias(pCommon, zName, 0) ){
    if( pMsg->u.attach.flags & SQLITE_BCV_ATTACH_IFNOT ) goto attach_cb_out;
    zErr = sqlite3_mprintf("container already attached: %s", zName);
    rc = SQLITE_ERROR;
  }

  /* Create a directory to use */
  bcvCreateDir(&rc, pCommon, zName);

  /* Parse the manifest */
  if( rc==SQLITE_OK ){
    rc = bcvManifestParseCopy(aData, nData, zETag, &pMan, &zErr);
  }

  if( rc==SQLITE_OK ){
    if( pCommon->szBlk==0 ){
      pCommon->szBlk = pMan->szBlk;
    }else if( pCommon->szBlk!=pMan->szBlk ){
      zErr = sqlite3_mprintf("block size mismatch for container: %s", zName);
      rc = SQLITE_ERROR;
    }
  }

  /* Allocate the container object */
  pCont = bcvContainerAlloc(&rc, pCommon,
      pMsg->u.attach.zStorage, pMsg->u.attach.zAccount,
      pMsg->u.attach.zContainer, zName
  );

  if( rc==SQLITE_OK && (pMsg->u.attach.flags & SQLITE_BCV_ATTACH_SECURE) ){
    sqlite3_randomness(BCV_LOCAL_KEYSIZE, pCont->aKey);
    pCont->pKey = bcvIntEncryptionKeyNew(pCont->aKey);
    if( pCont->pKey==0 ) fatal_oom_error();
    pCont->iEnc = ++pClient->pCtx->iNextId;
  }

  /* Parse the manifest and install it into the container. */
  if( rc==SQLITE_OK ){
    rc = bcvManifestInstall(pCommon, pCont, pMan);
  }

  /* If successful, link the container into the list */
  if( rc==SQLITE_OK ){
    pCont->pMan = pMan;
    pCont->pNext = pCommon->pCList;
    pCommon->pCList = pCont;
  }else{
    bcvManifestFree(pMan);
    bcvContainerFree(pCont);
  }

 attach_cb_out:
  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_REPLY;
  reply.u.error_r.errCode = rc;
  reply.u.error_r.szBlk = pCommon->szBlk;
  if( rc!=SQLITE_OK ){
    reply.u.error_r.zErrMsg = zErr ? zErr : zETag;
  }

  bdSendMsg(pClient->pCtx, pClient, &reply);
  bcvContainerClose(pClient->pBcv);
  pClient->pBcv = 0;
  pClient->pMsg = 0;
  sqlite3_free(pMsg);
  sqlite3_free(zErr);
}

static void bdDispatchFetch(
  BcvDispatch *p,
  BcvContainer *pCont,
  const char *zFile,
  const char *zETag,
  const void *pMd5,
  FetchCtx *pCtx,
  void (*x)(void*, int rc, char *zETag, const u8*, int, const u8*, int)
){
  int rc = bcvDispatchFetch(p, pCont, zFile, zETag, pMd5, (void*)pCtx, x);
  if( rc!=SQLITE_OK ) fatal_oom_error();
}

static FetchCtx *bdFetchCtx(
  DClient *pClient,
  CacheEntry *pEntry
){
  FetchCtx *p = (FetchCtx*)bdMallocZero(sizeof(FetchCtx));
  p->pClient = pClient;
  p->pEntry = pEntry;
  p->pCtx = pClient->pCtx;
  p->pCont = pClient->pCont;
  if( p->pCont && p->pCont->pKey ){
    p->pKey = bcvIntEncryptionKeyRef(p->pCont->pKey);
  }
  pClient->nRef++;
  return p;
}

/*
** Handle an ATTACH message from a client.
**
** This routine just kicks off a network request for the manifest file of
** the specified container - the callback is bdAttachCb. It does not check
** that the container is not already attached, as this has to be checked
** again after the network request is answered anyway.
*/
static void bdHandleAttach(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  int rc = SQLITE_OK;;
  BcvContainer *pBcv = 0;
  char *zErr = 0;

  assert( pClient->pBcv==0 );
  assert( pClient->pMsg==0 );

  rc = bcvContainerOpen(
      pMsg->u.attach.zStorage, pMsg->u.attach.zAccount,
      pMsg->u.attach.zAuth, pMsg->u.attach.zContainer, 
      &pBcv, &zErr
  );
  if( rc==SQLITE_OK ){
    FetchCtx *pFetch = bdFetchCtx(pClient, 0);
    pClient->pMsg = pMsg;
    pClient->pBcv = pBcv;
    bdDispatchFetch(p->pDisp, pBcv, BCV_MANIFEST_FILE, 0,0, pFetch, bdAttachCb);
  }else{
    BcvMessage reply;
    memset(&reply, 0, sizeof(reply));
    reply.eType = BCV_MESSAGE_REPLY;
    reply.u.error_r.errCode = rc;
    reply.u.error_r.zErrMsg = zErr;
    bdSendMsg(p, pClient, &reply);
    bcvContainerClose(pBcv);
    sqlite3_free(pMsg);
    pClient->pMsg = 0;
    pClient->pBcv = 0;
  }
  sqlite3_free(zErr);
}

/*
** Handle an DETACH message from a client.
*/
static void bdHandleDetach(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  BcvMessage reply;
  Container *pCont = 0;
  char *zErr = 0;
  int rc = SQLITE_OK;

  pCont = bcvfsFindContAlias(&p->c, pMsg->u.detach.zName, &zErr);
  if( !pCont ){
    rc = SQLITE_ERROR;
  }else if( pCont->nClient>0 ){
    rc = SQLITE_ERROR;
    zErr = sqlite3_mprintf("container is busy: %s", pMsg->u.detach.zName);
  }else{
    rc = bcvContainerDetachAndFree(&p->c, pCont);
    if( rc!=SQLITE_OK ) fatal_sql_error(p->c.bdb, "bcvHandleDetach");
  }

  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_REPLY;
  reply.u.error_r.errCode = rc;
  reply.u.error_r.zErrMsg = zErr;
  bdSendMsg(p, pClient, &reply);
  sqlite3_free(zErr);
  sqlite3_free(pMsg);
}

/*
** GCC does not define the offsetof() macro so we'll have to do it
** ourselves.
*/
#ifndef offsetof
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
#endif


/*
** Version of xClientCount for proxy VFS
*/
static void bcvProxyClientCount(
  BcvCommon *pCommon, 
  Container *pCont, 
  int iDbId, 
  int *pnClient,
  int *pnPrefetch,
  int *pnReader
){
  DClient *pClient = 0;
  DaemonCtx *p = 0;
  int nClient = 0;
  int nPrefetch = 0;
  int nReader = 0;

  p = (DaemonCtx*)&((u8*)pCommon)[-offsetof(DaemonCtx, c)];
  for(pClient=p->pClientList; pClient; pClient=pClient->pNext){
    if( pClient->pCont==pCont && pClient->iDbId==iDbId ){
      if( pClient->prefetch.bPrefetch ){
        nPrefetch++;
      }else{
        nClient++;
        if( pClient->apRef ) nReader++;
      }
    }
  }

  *pnClient = nClient;
  *pnPrefetch = nPrefetch;
  *pnReader = nReader;
}

/*
** This function is used to populate the daemon-specific part of a
** BCV_MESSAGE_VTAB_REPLY message for a query on the "bcv_stat" virtual
** table. Specifically, this adds two rows to the returned data:
**
**   memory_client_manifest:
**     Total byte of memory used by manifests that are kept in memory only 
**     for clients use - not the newest manifest available held by the 
**     container object.
**
**   memory_client_array:
**     Memory used for arrays of block references held in the daemon on 
**     behalf of clients.
**  
*/
static u8 *bdExtraVtabData(int *pRc, DaemonCtx *p, u8 *aData, int *pnData){
  i64 nManifest = 0;
  i64 nArray = 0;
  DClient *pClient = 0;

  BcvBuffer buf;
  buf.aData = aData;
  buf.nData = buf.nAlloc = *pnData;

  for(pClient = p->pClientList; pClient; pClient=pClient->pNext){
    if( pClient->pMan && pClient->pMan!=pClient->pCont->pMan ){
      assert( pClient->pMan->nRef>=1 );
      nManifest += bcvManifestSize(pClient->pMan) / pClient->pMan->nRef;
    }
    if( pClient->apRef ){
      assert( pClient->pManDb );
      nArray += (pClient->pManDb->nBlkLocal * sizeof(CacheEntry*));
    }
  }

  bcvBufferMsgString(pRc, &buf, "memory_client_manifest");
  bcvBufferAppendU64(pRc, &buf, (u64)nManifest);
  bcvBufferMsgString(pRc, &buf, "memory_client_array");
  bcvBufferAppendU64(pRc, &buf, (u64)nArray);

  *pnData = buf.nData;
  return buf.aData;
}

/*
** Handle a message of type BCV_MESSAGE_VTAB from client pClient.
*/
static void bdHandleVtab(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  const char *zTab = pMsg->u.vtab.zVtab;
  const char *zCont = pMsg->u.vtab.zContainer;
  const char *zDb = pMsg->u.vtab.zDatabase;
  const u32 colUsed = pMsg->u.vtab.colUsed;

  int rc = SQLITE_OK;
  BcvMessage reply;
  u8 *aData = 0;
  int nData = 0;
  int iVersion = pMsg->u.vtab.iVersion;

  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_VTAB_REPLY;

  aData = bcvDatabaseVtabData(&rc, &p->c, 
      zTab, zCont, zDb, bcvProxyClientCount, colUsed, &nData, &iVersion
  );
  if( 0==bcvStrcmp(zTab, "bcv_stat") ){
    aData = bdExtraVtabData(&rc, p, aData, &nData);
  }

  reply.u.vtab_r.aData = aData;
  reply.u.vtab_r.nData = nData;
  reply.u.vtab_r.iVersion = iVersion;
  bdSendMsg(p, pClient, &reply);

  sqlite3_free(aData);
  sqlite3_free(pMsg);
}

/*
** Handle a message of type BCV_MESSAGE_HELLO from client pClient.
*/
static void bdHandleHello(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  const char *zCont = pMsg->u.hello.zContainer;
  const char *zDb = pMsg->u.hello.zDatabase;
  Container *pCont = 0;
  ManifestDb *pDb = 0;
  BcvMessage reply;
  char *zErr = 0;

  pClient->prefetch.bPrefetch = pMsg->u.hello.bPrefetch;
  pCont = bcvfsFindContAlias(&p->c, zCont, &zErr);
  if( pCont && zDb ){
    pDb = bcvfsFindDatabase(pCont->pMan, zDb, -1);
    if( pDb==0 ){
      zErr = bcvMprintf("no such database: /%s/%s", zCont, zDb);
      pCont = 0;
    }

    if( pCont ){
      int rc = bcvfsCreateLocalDb(&p->c, zCont, zDb, &pClient->pCloseFd);
      if( rc!=SQLITE_OK ){
        zErr = bcvMprintf(
            "failed to create database files: /%s/%s", zCont, zDb
        );
        pCont = 0;
      }
    }
  }

  memset(&reply, 0, sizeof(BcvMessage));
  reply.eType = BCV_MESSAGE_HELLO_REPLY;
  if( pCont==0 ){
    reply.u.hello_r.errCode = SQLITE_CANTOPEN;
    reply.u.hello_r.zErrMsg = zErr;
  }else{
    pClient->pCont = pCont;
    if( pDb ) pClient->iDbId = pDb->iDbId;
    pCont->nClient++;
    reply.u.hello_r.szBlk = pCont->pMan->szBlk;
    reply.u.hello_r.zStorage = pCont->zStorage;
    reply.u.hello_r.zAccount = pCont->zAccount;
    reply.u.hello_r.zContainer = pCont->zContainer;
    reply.u.hello_r.iDbId = pClient->iDbId;
    reply.u.hello_r.szBlk = pCont->pMan->szBlk;
    reply.u.hello_r.bEncrypted = (pCont->pKey!=0);
  }

  bdSendMsg(p, pClient, &reply);
  sqlite3_free(pMsg);
  sqlite3_free(zErr);
}

/*
** Send a message of type READ_REPLY to client pClient. The message
** contains error code rc and error message zErr.
*/
static void bdReadReplyError(
  DClient *pClient,
  int rc,
  const char *zErr
){
  BcvMessage reply;
  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_READ_REPLY;
  reply.u.read_r.errCode = rc;
  reply.u.read_r.zErrMsg = zErr;
  bdSendMsg(pClient->pCtx, pClient, &reply);
}

static void bdHandleReadMsg(DaemonCtx *p, DClient *pClient);

static void bdWriteBlock(
  BcvCommon *pCommon, 
  CacheEntry *pEntry
){
  int rc = SQLITE_OK;
  sqlite3_stmt *pStmt = pCommon->pInsertBlock;
  sqlite3_bind_int(pStmt, 1, pEntry->iPos);
  sqlite3_bind_blob(pStmt, 2, pEntry->aName, pEntry->nName, SQLITE_STATIC);
  sqlite3_step(pStmt);
  rc = sqlite3_reset(pStmt);
  if( rc ) fatal_sql_error(pCommon->bdb, "bdWriteBlock()");
  sqlite3_clear_bindings(pStmt);
}

/*
** Write nData bytes of data from buffer aData[] to offset iOff of the
** file opened by file descriptor pFd. If it is not NULL, encrypt the data 
** using pKey before writing it to disk.
*/
static int bdWriteFile(
  sqlite3_file *pFd, 
  BcvIntKey *pKey,
  const u8 *aData, 
  int nData, 
  i64 iOff
){
  const int szChunk = 32768;      /* Any size acceptable to xWrite() */
  const int szEncChunk = 512;     /* Must match size in bcvfsProxyDecrypt */
  u8 *aBuf = 0;                   /* Interim buffer for encryption, if req. */
  int rc = SQLITE_OK;             /* Return code */
  int i;                          /* Offset within aData[] */

  if( pKey ){
    aBuf = (u8*)bdMalloc(szChunk);
  }

  assert( (nData % sizeof(aBuf))==0 );
  for(i=0; i<nData && rc==SQLITE_OK; i+=szChunk){
    const u8 *aWrite = &aData[i];
    int nWrite = MIN(nData - i, szChunk);
    assert( (nWrite % szEncChunk)==0 );
    if( pKey ){
      int jj;
      memcpy(aBuf, aWrite, nWrite);
      for(jj=0; jj<nWrite; jj+=szEncChunk){
        bcvIntEncrypt(pKey, iOff+i+jj, 0, &aBuf[jj], szEncChunk);
      }
      aWrite = aBuf;
    }
    rc = pFd->pMethods->xWrite(pFd, aWrite, nWrite, iOff+i);
  }

  sqlite3_free(aBuf);
  return rc;
}

static void bdBlockDownloadCb(
  void *pCtx, 
  int errCode, 
  char *zETag, 
  const u8 *aData, 
  int nData,
  const u8 *aHdrs, int nHdrs
){
  FetchCtx *pDLCtx = (FetchCtx*)pCtx;
  DClient *pClient = bdFetchClient(pDLCtx);
  DaemonCtx *p = pDLCtx->pCtx;
  CacheEntry *pEntry = pDLCtx->pEntry;
  int rc = errCode;

  if( rc==SQLITE_OK ){
    if( p->cmd.mLog & BCV_LOG_EVENT ){
      char zName[BCV_MAX_FSNAMEBYTES];
      bcvBlockidToText(pEntry->nName, pEntry->aName, zName);
      daemon_event_log(p, "writing %s to cache slot %d", zName, pEntry->iPos);
    }
    i64 iOff = (pEntry->iPos * p->c.szBlk);
    rc = bdWriteFile(p->pCacheFile, pDLCtx->pKey, aData, nData, iOff);
  }

  if( rc==SQLITE_OK ){
    pEntry->bValid = 1;
    bcvfsLruAdd(&p->c, pEntry);
    if( pDLCtx->pKey==0 ) bdWriteBlock(&p->c, pEntry);
  }else{
    /* An error has occurred. Unless it has already disconnected (pClient==0),
    ** send an error reply to the client that initiated this request. Then
    ** mark the cache entry as unused.  */
    if( pClient ){
      bdReadReplyError(pClient, errCode, zETag);
      sqlite3_free(pClient->pMsg);
      pClient->pMsg = 0;
    }
    bcvfsHashRemove(&p->c, pEntry);
    bcvfsUnusedAdd(&p->c, pEntry);
  }

  bdBlockDownloadFree(pDLCtx);
}

/*
** Ensure that the BCV handle at pClient->pBcv is one configured to use
** authentication string zAuth. Then return a copy of it.
*/
static BcvContainer *bdUpdateBCV(DClient *pClient, const char *zAuth){
  if( pClient->pBcv==0 || bcvStrcmp(zAuth, pClient->zAuth) ){
    char *zErr = 0;
    int rc = SQLITE_OK;

    bcvContainerClose(pClient->pBcv);
    sqlite3_free(pClient->zAuth);
    pClient->pBcv = 0;
    pClient->zAuth = 0;

    rc = bcvContainerOpen(
        pClient->pCont->zStorage, pClient->pCont->zAccount,
        zAuth, pClient->pCont->zContainer, &pClient->pBcv, &zErr
    );
    if( rc!=SQLITE_OK ){
      fatal_error("failed to create BCV: %s", zErr);
    }
    pClient->zAuth = bdStrdup(zAuth);
  }
  return pClient->pBcv;
}

static i64 bdFindMinTick(DaemonCtx *pCtx){
  BcvCommon *p = &pCtx->c;
  i64 iRet = 0;
  CacheEntry *pEntry = 0;
  int nAllow = ((p->nMaxCache+p->szBlk-1) / p->szBlk);
  int nReserve = MIN(nAllow/5, BCV_MAX_RESERVE);
  int nIgnore = p->nBlk - (nAllow - nReserve);

  for(pEntry=p->pUnused; pEntry; pEntry=pEntry->pHashNext){
    nIgnore--;
  }
  for(pEntry=p->pLruFirst; pEntry && nIgnore>0; pEntry=pEntry->pLruNext){
    iRet = pEntry->iLruTick;
    nIgnore--;
  }

  return iRet;
}

/*
**
*/
static CacheEntry *bdHashFind(
  BcvCommon *pCommon,             /* Hash tables to search */
  const u8 *aName, int nName,     /* Name of block to search for */
  int iEnc                        /* Required encryption index */
){
  CacheEntry *pEntry = bcvfsHashFind(pCommon, aName, nName);
  if( pEntry && pEntry->iEnc!=iEnc ){
    while( (pEntry = pEntry->pHashNext) ){
      if( pEntry->iEnc==iEnc 
       && pEntry->nName==nName 
       && memcpy(pEntry->aName, aName, nName)
      ){
        break;
      }
    }
  }
  return pEntry;
}

static void bdHandleReadMsg(DaemonCtx *p, DClient *pClient){
  const int iEnc = pClient->pCont->iEnc;
  int iBlk = pClient->pMsg->u.read.iBlk;
  int nName = NAMEBYTES(pClient->pMan);
  u8 *aName = &pClient->pManDb->aBlkLocal[nName * iBlk];
  CacheEntry *pEntry = 0;

  /* Check if the required block is already in the cache. There
  ** are three possibilities: 
  **
  **   1) The block is not in the cache and is not currently being
  **      downloaded. In this case start the download.
  **
  **   2) The block is in the cache but is not ready to use - it
  **      is still being downloaded. In this case just wait.
  **
  **   3) The block is in the cache and ready to use. The READ
  **      message can be answered immediately in this case.
  */
  pEntry = bdHashFind(&p->c, aName, nName, iEnc);
  if( pEntry==0 ){
    /* Case (1) - download the block */
    BcvContainer *pBcv = pClient->pBcv;
    int rc = SQLITE_OK;
    char zName[BCV_MAX_FSNAMEBYTES];
    CacheEntry *pEntry = 0;
    FetchCtx *pDLCtx = 0;

    pEntry = bcvfsAllocCacheEntry(&rc, &p->c);
    if( rc!=SQLITE_OK ) fatal_oom_error();
    memcpy(pEntry->aName, aName, nName);
    pEntry->nName = nName;
    pEntry->iEnc = iEnc;
    bcvfsHashAdd(&p->c, pEntry);

    pDLCtx = bdFetchCtx(pClient, pEntry);
    bcvfsBlockidToText(aName, nName, zName);
    bcvDispatchClientId(p->pDisp, pClient->zClientId);
    bcvDispatchLogmsg(p->pDisp, "demand %d of %s",iBlk,pClient->pManDb->zDName);
    bdDispatchFetch(p->pDisp, pBcv, zName, 0, 0, pDLCtx, bdBlockDownloadCb);
    bcvDispatchClientId(p->pDisp, 0);

  }else if( pEntry->bValid==0 ){
    /* Case (2) - wait */
  }else{
    /* Case (3) - answer the READ message now */
    BcvMessage reply;
    ManifestDb *pDb = pClient->pManDb;
    int ii;
    i64 iMinTick = bdFindMinTick(p);

    /* Shift pEntry to the end of the LRU list */
    bcvfsLruRemoveIf(&p->c, pEntry);
    bcvfsLruAddIf(&p->c, pEntry);

    memset(&reply, 0, sizeof(BcvMessage));
    reply.eType = BCV_MESSAGE_READ_REPLY;
    reply.u.read_r.aBlk = (u32*)bdMallocZero(pDb->nBlkLocal * sizeof(u32));
    reply.u.read_r.nBlk = pDb->nBlkLocal;
    memset(pClient->apRef, 0, pDb->nBlkLocal * sizeof(CacheEntry*));
    for(ii=0; ii<pDb->nBlkLocal; ii++){
      const u8 *aName = &pDb->aBlkLocal[ii*nName];
      CacheEntry *pEntry = bdHashFind(&p->c, aName, nName, iEnc);
      if( pEntry && pEntry->bValid && pEntry->iLruTick>iMinTick ){
        reply.u.read_r.aBlk[ii] = pEntry->iPos + 1;
        pEntry->nRef++;
        pClient->apRef[ii] = pEntry;
      }
    }

    bdSendMsg(p, pClient, &reply);
    sqlite3_free(pClient->pMsg);
    sqlite3_free(reply.u.read_r.aBlk);
    pClient->pMsg = 0;
  }
}

#if 0
static void log_db_blocks(DaemonCtx *pCtx, Manifest *pMan, int iDb){
  ManifestDb *pDb = &pMan->aDb[iDb];
  int ii;
  for(ii=0; ii<pDb->nBlkLocal; ii++){
    CacheEntry *pEntry = 0;
    u8 *aName = &pDb->aBlkLocal[NAMEBYTES(pMan) * ii];
    char zName[BCV_MAX_FSNAMEBYTES];
    bcvBlockidToText(pMan, aName, zName);
    pEntry = bcvfsHashFind(&pCtx->c, aName, NAMEBYTES(pMan));
    daemon_event_log(pCtx, "block %d of \"%s\" is %s (cache-file-pos=%d)",
        ii, pDb->zDName, zName, pEntry?pEntry->iPos:-1
    );
  }
}
#endif

/*
** This callback is invoked when a GET request for a manifest file made
** by bdHandlePollCmdMsg() is ready.
*/
static void bdPollCb(
  void *pCtx,                     /* Pointer to requesting DClient */
  int errCode,                    /* Error code */
  char *zETag,                    /* E-Tag (rc==SQLITE_OK) or error message */
  const u8 *aData, int nData,     /* Serialized manifest */
  const u8 *aHdrs, int nHdrs
){
  FetchCtx *pDLCtx = (FetchCtx*)pCtx;
  DClient *pClient = bdFetchClient(pDLCtx);
  Container *pCont = pDLCtx->pCont;
  DaemonCtx *p = pDLCtx->pCtx;
  DClient *pIter = 0;
  char *zErr = 0;                 /* Error message (from sqlite3_malloc) */
  int rc = errCode;               /* Error code */
  Manifest *pMan = 0;             /* Parsed manifest object */

  if( rc!=SQLITE_OK ){
    zErr = bdStrdup(zETag);
  }else{
    rc = bcvManifestParseCopy(aData, nData, zETag, &pMan, &zErr);
  }

  if( rc==SQLITE_OK ){
    rc = bcvManifestUpdate(&p->c, pCont, pMan, &zErr);
  }
  pCont->eState = CONTAINER_STATE_NONE;

  /* Search for clients that currently have an open transaction on this
  ** container. If possible (if the db they have open has not changed),
  ** upgrade such clients to the new manifest object. */
  for(pIter=p->pClientList; pIter; pIter=pIter->pNext){
    if( pIter->pMan && pIter->pCont==pCont ){
      ManifestDb *pOldDb = pIter->pManDb;
      int iOff = pOldDb - pIter->pMan->aDb;
      ManifestDb *pNewDb = 0;

      if( iOff<pMan->nDb ){
        pNewDb = &pMan->aDb[iOff];
        if( pNewDb->iDbId!=pOldDb->iDbId ) pNewDb = 0;
      }
      if( pNewDb==0 ){
        pNewDb = bcvManifestDbidToDb(pMan, pOldDb->iDbId);
      }
      if( pNewDb && pNewDb->iVersion==pOldDb->iVersion ){
        assert( pNewDb->nBlkOrig==pOldDb->nBlkOrig );
        assert( 0==memcmp(
            pNewDb->aBlkOrig, pOldDb->aBlkOrig, NAMEBYTES(pMan)*pOldDb->nBlkOrig
        ));
        bcvManifestDeref(pIter->pMan);
        pIter->pMan = pMan;
        pIter->pManDb = pNewDb;
        bcvManifestRef(pMan);
      }
    }
  }

  if( pClient ){
    BcvMessage reply;
    memset(&reply, 0, sizeof(reply));
    reply.eType = BCV_MESSAGE_REPLY;
    reply.u.error_r.errCode = rc;
    reply.u.error_r.zErrMsg = zErr;
    sqlite3_free(pClient->pMsg);
    pClient->pMsg = 0;
    bdSendMsg(pClient->pCtx, pClient, &reply); 
  }

  sqlite3_free(zErr);
  bdBlockDownloadFree(pDLCtx);
}

/*
** The client passed as the second argument is currently processing a
** message of type BCV_MESSAGE_CMD, subtype BCV_CMD_POLL. If possible,
** get on with handling this message.
*/
static void bdHandlePollCmdMsg(DaemonCtx *p, DClient *pClient){
  Container *pCont = pClient->pCont;
  assert( pCont && pClient->iDbId==0 && pClient->pMsg );

  /* If the container is currently in state NONE, proceed with the poll.
  ** Otherwise, do nothing - this function will be called again at some
  ** point when the container state is NONE.  */
  if( pCont->eState==CONTAINER_STATE_NONE ){
    FetchCtx *pDLCtx = bdFetchCtx(pClient, 0);
    BcvDispatch *pDisp = p->pDisp;
    BcvContainer *pBcv = bdUpdateBCV(pClient, pClient->pMsg->u.cmd.zAuth);
    bdDispatchFetch(pDisp, pBcv, BCV_MANIFEST_FILE, 0, 0, pDLCtx, bdPollCb);
    pCont->eState = CONTAINER_STATE_POLL;
  }
}

/*
** Array aMru[] (size nMru) is an MRU array just received as part of
** a READ or END message. Shuffle entries within the LRU list accordingly.
*/
static void bdProcessMRUList(
  DaemonCtx *p, 
  DClient *pClient,
  u32 *aMru,
  int nMru
){
  CacheEntry **apRef = pClient->apRef;
  int ii;
  for(ii=nMru-1; ii>=0; ii--){
    CacheEntry *pEntry = apRef[ aMru[ii] ];
    assert( (int)aMru[ii]<pClient->pManDb->nBlkLocal && pEntry );
    assert( pEntry->bValid && pEntry->bDirty==0 );

    bcvfsLruRemoveIf(&p->c, pEntry);
    bcvfsLruAddIf(&p->c, pEntry);
  }
}

/*
** Handle a message of type BCV_MESSAGE_READ from client pClient.
*/
static void bdHandleRead(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  int rc = SQLITE_OK;
  char *zErr = 0;

  /* Take a reference to the container manifest if this is the first
  ** READ message of the transaction. Or, if this is the second or 
  ** subsequent request of the transaction, release all currently held 
  ** references.  */
  if( pClient->pMan==0 ){
    Manifest *pMan = pClient->pCont->pMan;
    ManifestDb *pDb = bcvManifestDbidToDb(pMan, pClient->iDbId);
    if( pDb==0 ){
      zErr = sqlite3_mprintf("database has been deleted");
      rc = SQLITE_ERROR;
    }else{
      int nByte = pDb->nBlkLocal * sizeof(CacheEntry*);
      bcvManifestRef(pMan);
      pClient->pMan = pMan;
      pClient->pManDb = pDb;
      pClient->apRef = (CacheEntry**)bdMallocZero(nByte);
    }
  }else{
    bdProcessMRUList(p, pClient, pMsg->u.read.aMru, pMsg->u.read.nMru);
    bdReleaseEntryRefs(pClient);
  }

  bdUpdateBCV(pClient, pMsg->u.read.zAuth);

  /* If no error has occurred, try to handle the READ message now. 
  ** Otherwise, return an error to the client.  */
  if( rc==SQLITE_OK ){
    pClient->pMsg = pMsg;
  }else{
    bdReadReplyError(pClient, SQLITE_ERROR, 0);
    sqlite3_free(pMsg);
  }
}

/*
** Handle a message of type BCV_MESSAGE_END from client pClient.
*/
static void bdHandleEnd(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  bdProcessMRUList(p, pClient, pMsg->u.end.aMru, pMsg->u.end.nMru);
  bdReleaseEntryRefs(pClient);
  sqlite3_free(pClient->apRef);
  pClient->apRef = 0;
  bcvManifestDeref(pClient->pMan);
  pClient->pMan = 0;
  pClient->pManDb = 0;
  sqlite3_free(pMsg);
}

static void bdPassCb(
  void *pCtx, 
  int errCode, 
  char *zETag, 
  const u8 *aData, 
  int nData,
  const u8 *aHdrs, int nHdrs
){
  BcvMessage reply;
  FetchCtx *pDLCtx = (FetchCtx*)pCtx;
  DClient *pClient = bdFetchClient(pDLCtx);
  DaemonCtx *p = pDLCtx->pCtx;

  bdBlockDownloadFree(pDLCtx);

  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_PASS_REPLY;
  if( errCode==SQLITE_OK ){
    reply.u.pass_r.aKey = pClient->pCont->aKey;
  }else{
    reply.u.pass_r.errCode = errCode;
    reply.u.pass_r.zErrMsg = zETag;
  }

  bdSendMsg(p, pClient, &reply);
}

/*
** Handle a PASS message from a client.
*/
static void bdHandlePass(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  BcvContainer *pBcv = 0;
  FetchCtx *pDLCtx = bdFetchCtx(pClient, 0);
 
  pBcv = bdUpdateBCV(pClient, pMsg->u.pass.zAuth);
  bdDispatchFetch(p->pDisp, pBcv, BCV_MANIFEST_FILE, 0, 0, pDLCtx, bdPassCb);
  sqlite3_free(pMsg);
}

static void bdHandleClient(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  BcvMessage reply;

  sqlite3_free(pClient->zClientId);
  pClient->zClientId = bdStrdup(pMsg->u.cmd.zAuth);

  memset(&reply, 0, sizeof(reply));
  reply.eType = BCV_MESSAGE_REPLY;
  bdSendMsg(p, pClient, &reply);
  sqlite3_free(pMsg);
}

static void bdSendPrefetchReply(DClient *pClient){
  BcvMessage msg;
  DClient *pIter = 0;
  int nOnDemand = 0;

  int rc = pClient->prefetch.errCode;
  if( rc==SQLITE_OK 
   && pClient->prefetch.nOutstanding==0 
   && pClient->prefetch.iNext>=pClient->pManDb->nBlkLocal 
  ){
    rc = SQLITE_DONE;
  }

  for(pIter=pClient->pCtx->pClientList; pIter; pIter=pIter->pNext){
    if( pIter->pMsg && pIter->pMsg->eType==BCV_MESSAGE_READ ){
      nOnDemand++;
    }
  }

  memset(&msg, 0, sizeof(msg));
  msg.eType = BCV_MESSAGE_PREFETCH_REPLY;
  msg.u.prefetch_r.errCode = rc;
  msg.u.prefetch_r.zErrMsg = pClient->prefetch.zErrMsg;
  msg.u.prefetch_r.nOutstanding = pClient->prefetch.nOutstanding;
  msg.u.prefetch_r.nOnDemand = nOnDemand;
  bdSendMsg(pClient->pCtx, pClient, &msg);

  pClient->prefetch.bReply = 0;
  pClient->prefetch.errCode = SQLITE_OK;
  sqlite3_free(pClient->prefetch.zErrMsg);
  pClient->prefetch.zErrMsg = 0;
  if( rc==HTTP_AUTH_ERROR ){
    pClient->prefetch.iNext = 0;
  }
}

/*
** This callback is invoked to announce that a block requested by 
** bdHandlePrefetch() had finished downloading. Or that an error has occurred
** while attempting the same.
*/
static void bdPrefetchCb(
  void *pCtx, 
  int errCode, 
  char *zETag, 
  const u8 *aData, 
  int nData,
  const u8 *aHdrs, int nHdrs
){
  FetchCtx *pDLCtx = (FetchCtx*)pCtx;
  DClient *pClient = bdFetchClient(pDLCtx);
  DaemonCtx *p = pDLCtx->pCtx;
  CacheEntry *pEntry = pDLCtx->pEntry;
  int rc = errCode;

  if( rc==SQLITE_OK ){
    i64 iOff = (pEntry->iPos * p->c.szBlk);
    rc = bdWriteFile(p->pCacheFile, pDLCtx->pKey, aData, nData, iOff);
  }

  if( rc==SQLITE_OK ){
    pEntry->bValid = 1;
    bcvfsLruAdd(&p->c, pEntry);
    if( pDLCtx->pKey==0 ) bdWriteBlock(&p->c, pEntry);
  }else{
    bcvfsHashRemove(&p->c, pEntry);
    bcvfsUnusedAdd(&p->c, pEntry);
  }

  if( pClient ){
    pClient->prefetch.nOutstanding--;

    if( rc!=SQLITE_OK && pClient->prefetch.errCode==SQLITE_OK ){
      pClient->prefetch.errCode = rc;
      pClient->prefetch.zErrMsg = sqlite3_mprintf("%s", zETag);
    }

    if( pClient->prefetch.bReply ){
      bdSendPrefetchReply(pClient);
      pClient->prefetch.bReply = 0;
    }
  }

  bdBlockDownloadFree(pDLCtx);
}


static void bdHandlePrefetch(
  DaemonCtx *p, 
  DClient *pClient, 
  BcvMessage *pMsg
){
  BcvContainer *pBcv = 0;
  int rc = SQLITE_OK;

  pClient->prefetch.bReply = 1;
  pClient->prefetch.bPrefetch = 1;

  pBcv = bdUpdateBCV(pClient, pMsg->u.pass.zAuth);
  if( pClient->pManDb==0 ){
    Manifest *pMan = pClient->pCont->pMan;
    ManifestDb *pDb = bcvManifestDbidToDb(pMan, pClient->iDbId);
    if( pDb ){
      bcvManifestRef(pMan);
      pClient->pMan = pMan;
      pClient->pManDb = pDb;
    }else{
      /* Error - database no longer exists */
      assert( 0 );
    }
  }

  while( pClient->prefetch.nOutstanding<pMsg->u.prefetch.nRequest
      && pClient->prefetch.iNext<pClient->pManDb->nBlkLocal
  ){
    int nName = NAMEBYTES(pClient->pMan);
    int iBlk = pClient->prefetch.iNext++;
    const u8 *aName = &pClient->pManDb->aBlkLocal[iBlk * nName];
    CacheEntry *pEntry = 0;

    pEntry = bdHashFind(&p->c, aName, nName, pClient->pCont->iEnc);
    if( pEntry==0 ){
      char zName[BCV_MAX_FSNAMEBYTES];
      FetchCtx *pDL = 0;

      pEntry = bcvfsAllocCacheEntry(&rc, &p->c);
      if( rc!=SQLITE_OK ) fatal_oom_error();
      pEntry->iEnc = pClient->pCont->iEnc;
      memcpy(pEntry->aName, aName, nName);
      pEntry->nName = nName;
      bcvfsHashAdd(&p->c, pEntry);
      assert( pEntry->bValid==0 );

      pClient->prefetch.nOutstanding++;
      pDL = bdFetchCtx(pClient, pEntry);
      bcvfsBlockidToText(pEntry->aName, nName, zName);
      bcvDispatchClientId(p->pDisp, "prefetch");
      bcvDispatchLogmsg(p->pDisp, 
          "prefetch %d of %s", iBlk, pClient->pManDb->zDName
      );
      bdDispatchFetch(p->pDisp, pBcv, zName, 0, 0, pDL, bdPrefetchCb);
      bcvDispatchClientId(p->pDisp, 0);
    }
  }

  if( pClient->prefetch.nOutstanding==0 && pClient->prefetch.bReply ){
    bdSendPrefetchReply(pClient);
  }

  sqlite3_free(pMsg);
}

/*
** This is called by the daemon main loop whenever there is input detected
** on a socket associated with client pClient.
*/
static void bdHandleClientMessage(
  DaemonCtx *p, 
  DClient *pClient, 
  int *pbLogin                    /* Set to true if message is a LOGIN */
){
  BcvMessage *pMsg = 0;
  int rc = SQLITE_OK;

  rc = bcvRecvMsg(pClient->fd, &pMsg);
  if( rc!=SQLITE_OK ){
    bdDisconnectClient(p, pClient, "client hangup");
  }else{
    assert( pClient->pMsg==0 );
    bdLogRecvMsg(p, pClient, pMsg);
    switch( pMsg->eType ){
      case BCV_MESSAGE_ATTACH:
        bdHandleAttach(p, pClient, pMsg);
        break;
      case BCV_MESSAGE_DETACH:
        bdHandleDetach(p, pClient, pMsg);
        break;
      case BCV_MESSAGE_VTAB:
        bdHandleVtab(p, pClient, pMsg);
        *pbLogin = 1;
        break;
      case BCV_MESSAGE_HELLO:
        bdHandleHello(p, pClient, pMsg);
        break;
      case BCV_MESSAGE_READ:
        bdHandleRead(p, pClient, pMsg);
        *pbLogin = 1;
        break;
      case BCV_MESSAGE_END:
        bdHandleEnd(p, pClient, pMsg);
        break;
      case BCV_MESSAGE_CMD:
        if( pMsg->u.cmd.eCmd==BCV_CMD_POLL ){
          pClient->pMsg = pMsg;
        }else{
          bdHandleClient(p, pClient, pMsg);
        }
        break;
      case BCV_MESSAGE_PASS:
        bdHandlePass(p, pClient, pMsg);
        break;
      case BCV_MESSAGE_PREFETCH:
        bdHandlePrefetch(p, pClient, pMsg);
        break;
      default:
        fatal_error("unexpected message type: %d", pMsg->eType);
    }
  }

}


static void bdMainloop(DaemonCtx *p){
  int bClient = 0;

  while( 1 ){
    DClient *pNextClient;
    DClient *pClient;
    int nFd = 1;
    int i;
    struct curl_waitfd *aWait;    /* Array of file descriptors to select() on */
    int rc;

    /* Assemble the set of file-descriptors to wait for events on. The
    ** listening socket fd, and one socket fd for each connected client. */
    for(pClient=p->pClientList; pClient; pClient=pClient->pNext) nFd++;
    aWait = bcvMallocZero(sizeof(struct curl_waitfd) * nFd);
    aWait[0].fd = p->fdListen;
    aWait[0].events = CURL_WAIT_POLLIN;
    i = 1;
    for(pClient=p->pClientList; pClient; pClient=pClient->pNext){
      aWait[i].fd = pClient->fd;
      aWait[i].events = CURL_WAIT_POLLIN;
      i++;
    }

    /* Run the dispatcher. This will execute callbacks for any completed
    ** network requests.  */
    rc = bcvDispatchRun(p->pDisp, aWait, nFd, 10000);
    if( rc!=SQLITE_OK ){
      fatal_error("bcvDispatchRun() failed - %d", rc);
    }

    /* Check for client messages */
    i = 1;
    for(pClient=p->pClientList; pClient; pClient=pNextClient){
      pNextClient = pClient->pNext;
      if( aWait[i].revents ){
        bdHandleClientMessage(p, pClient, &bClient);
      }
      i++;
    }

    /* Check for new connections */
    if( aWait[0].revents!=0 ){
      bdNewConnection(p);
    }

    /* Check if any PIN, POLL or READ clients can continue. */
    for(pClient=p->pClientList; pClient; pClient=pNextClient){
      BcvMessage *pMsg = pClient->pMsg;
      pNextClient = pClient->pNext;
      if( pMsg ){
        assert( pMsg->eType==BCV_MESSAGE_READ
             || pMsg->eType==BCV_MESSAGE_CMD
             || pMsg->eType==BCV_MESSAGE_ATTACH
        );
        if( pMsg->eType==BCV_MESSAGE_READ ){
          bdHandleReadMsg(p, pClient);
        }else if( pMsg->eType==BCV_MESSAGE_CMD ){
          assert( pMsg->u.cmd.eCmd==BCV_CMD_POLL );
          bdHandlePollCmdMsg(p, pClient);
        }
      }
    }

    /* Check if it is time to bail out (due to -autoexit option) */ 
    sqlite3_free(aWait);
    if( p->cmd.bAutoexit && bClient && p->pClientList==0 ){
      break;
    }
  }
}

/*
** Populate the portnumber.bcv file used by the [attach] and [detach]
** commands to locate the daemon's listening port.
*/
static void bdWritePortNumber(DaemonCtx *pCtx, const char *zDir){
  char *aBuf = 0;
  sqlite3_file *pFile = 0;
  int rc;
  const char *zAddr = pCtx->cmd.zAddr;
  char *zFile = bcvMprintf("%s/portnumber.bcv", zDir);

  if( zAddr==0 ) zAddr = "127.0.0.1";
  aBuf = bcvMprintf("%s:%d", zAddr, pCtx->iListenPort);

  rc = bdOpenLocalFile(0, zFile, 0, 0, &pFile);
  if( rc==SQLITE_OK ){
    rc = pFile->pMethods->xTruncate(pFile, 0);
  }
  if( rc==SQLITE_OK ){
    rc = pFile->pMethods->xWrite(pFile, (void*)aBuf, strlen(aBuf), 0);
  }
  if( rc!=SQLITE_OK ){
    fatal_error("failed to create and populate file: portnumber.bcv");
  }
  sqlite3_free(aBuf);
  sqlite3_free(zFile);
  bcvCloseLocal(pFile);
}

static void bdCleanup(DaemonCtx *p){
  bcvCommonDestroy(&p->c);
  bcvCloseLocal(p->pCacheFile);
  bcvDispatchFree(p->pDisp);
  sqlite3_free(p);
}

/*
** Command: $argv[0] daemon ?SWITCHES? DIRECTORY
*/
static int main_daemon(int argc, char **argv){
  CommandSwitches *pCmd;
  DaemonCtx *p = 0;
  const char *zDir = 0;           /* DIRECTORY argument */
  char *zFullDir = 0;             /* Full-path to zDir (from sqlite3_malloc) */
  sqlite3 *db = 0;                /* blocksdb.bcv */
  int rc = SQLITE_OK;
  i64 nUsed;
  char *zErr = 0;

  p = (DaemonCtx*)bcvMallocZero(sizeof(DaemonCtx));
  pCmd = &p->cmd;

  /* Parse command line */
  if( argc<3 ) daemon_usage(argv[0]);
  zDir = argv[argc-1];
  parse_switches(pCmd, &argv[2], argc-3, 0, COMMAND_DAEMON|COMMAND_NREQUEST);
  if( pCmd->szCache<=0 ) pCmd->szCache = BCV_DEFAULT_CACHEFILE_SIZE;
  if( pCmd->nHttpTimeout<=0 ) pCmd->nHttpTimeout = BCV_DEFAULT_HTTPTIMEOUT;

  /* Open the listen socket */
  bdListen(p);

  /* Open and initialize blocksdb.bcv */
  zFullDir = bcvGetFullpath(&rc, zDir);
  db = bcvOpenAndInitDb(&rc, zFullDir, &zErr);
  if( rc!=SQLITE_OK ){
    fatal_error("failed to open and lock directory: %s (%s)", zDir, zErr);
  }

  p->c.pVfs = sqlite3_vfs_find(0);
  p->c.bDaemon = 1;
  rc = bcvfsCacheInit(&p->c, db, zFullDir);
  p->c.nMaxCache = pCmd->szCache;
  if( rc!=SQLITE_OK ){
    fatal_error("failed to initialize in directory: %s", zDir);
  }else{
    char *zCacheFile = sqlite3_mprintf(
        "%s" BCV_PATH_SEPARATOR "%s", zFullDir, BCV_CACHEFILE_NAME
    );
    rc = bcvOpenLocal(zCacheFile, 0, 0, &p->pCacheFile);
    if( rc!=SQLITE_OK ){
      fatal_error("failed to open cachefile in directory: %s", zDir);
    }
    sqlite3_free(zCacheFile);
  }
  

  /* Write the "portnumber.bcv" file clients read to find the listening port */
  bdWritePortNumber(p, zFullDir);

  /* Allocate a dispatcher object for the daemon to use */
  rc = bcvDispatchNew(&p->pDisp);
  if( rc!=SQLITE_OK ) fatal_oom_error();
  p->c.pLog = bcvLogNew();
  bcvLogConfig(p->c.pLog, SQLITE_BCV_HTTPLOG_TIMEOUT, pCmd->nHttpLogTimeout);
  bcvLogConfig(p->c.pLog, SQLITE_BCV_HTTPLOG_NENTRY, pCmd->nHttpLogNentry);
  bcvDispatchLogObj(p->pDisp, p->c.pLog);
  bcvDispatchVerbose(p->pDisp, (pCmd->mLog & BCV_LOG_VERBOSE) ? 1 : 0);
  bcvDispatchTimeout(p->pDisp, pCmd->nHttpTimeout);
  if( pCmd->mLog & (BCV_LOG_HTTP|BCV_LOG_HTTPRETRY) ){
    bcvDispatchLog(p->pDisp, p, bdHttpLog);
  }

  /* If the -readymessage option was passed, output the message "ready\n"
  ** on stdout to indicate that initialization has finished and database
  ** clients may expect to access databases successfully. This is used
  ** by test scripts.  */
  if( p->cmd.bReadyMessage ){
    fprintf(stdout, "ready\n");
    fflush(stdout);
  }
  daemon_event_log(p, "listening on localhost port %d", p->iListenPort);

  /* Run the daemon main loop. This only exits if (a) the -autoexit option
  ** was passed and (b) the number of connected database clients drops to
  ** zero.  */
  bdMainloop(p);

  /* The main loop has exited. Attempt to clean up all memory allocations,
  ** then output an error message if this reveals that this process has 
  ** leaked memory.  */
  bdCleanup(p);
  sqlite3_bcv_shutdown();
  sqlite3_reset_auto_extension();
  nUsed = sqlite3_memory_used();
  if( nUsed>0 ){
    daemon_error("daemon leaked %d bytes of memory", (int)nUsed);
    return 1;
  }

  return 0;
}

#define STRINGVALUE2(x) #x
#define STRINGVALUE(x) STRINGVALUE2(x)

static void bcvCustomInit(void){
#ifdef SQLITE_BCV_CUSTOM_INIT
  int rc = SQLITE_BCV_CUSTOM_INIT();
  if( rc!=SQLITE_OK ){
    const char *zFunc = STRINGVALUE(SQLITE_BCV_CUSTOM_INIT);
    fatal_error("custom init function %s() failed (rc=%d)", zFunc, rc);
  }
#endif
}

void bcvRestoreDefaultVfs(void);

int main(int argc, char **argv){
  SelectOption aCmd[] = {
    { "upload",   1 , 0},
    { "download", 1 , 1},
    { "list",     1 , 3},
    { "manifest", 1 , 4},
    { "delete",   1 , 5},
    { "destroy",  1 , 6},
    { "create",   1 , 7},
    { "daemon",   1 , 8},
    { "files",    1 , 9},
    { "copy",     1 , 10},
    { 0, 0 }
  };
  int rc;
  int iCmd;

  bcv_socket_init();
  curl_global_init(CURL_GLOBAL_ALL);
  OpenSSL_add_all_algorithms();

  signal(SIGPIPE, SIG_IGN);

  sqlite3_initialize();
  bcvCustomInit();

  iCmd = select_option(argc>=2 ? argv[1] : "", aCmd, 0xFFFFFFFF, 1);
  switch( aCmd[iCmd].eVal ){
    case 0:
      rc = main_upload(argc, argv);
      break;
    case 1:
      rc = main_download(argc, argv);
      break;
    case 3:
      rc = main_list(argc, argv);
      break;
    case 4:
      rc = main_manifest(argc, argv);
      break;
    case 5:
      rc = main_delete(argc, argv);
      break;
    case 6:
      rc = main_destroy(argc, argv);
      break;
    case 7:
      rc = main_create(argc, argv);
      break;
    case 8:
      rc = main_daemon(argc, argv);
      break;
    case 9:
      rc = main_files(argc, argv);
      break;
    case 10:
      rc = main_copy(argc, argv);
      break;
  }

  return rc;
}